effect-browser 0.3.0-beta.24 → 0.3.0-beta.25

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 (345) hide show
  1. package/README.md +333 -157
  2. package/dist/Action.d.mts +1 -1
  3. package/dist/Action.mjs +61 -9
  4. package/dist/Action.mjs.map +1 -1
  5. package/dist/Browser.d.mts +2 -2
  6. package/dist/Browser.mjs +2 -2
  7. package/dist/BrowserError.d.mts +2 -2
  8. package/dist/BrowserError.mjs +194 -41
  9. package/dist/BrowserError.mjs.map +1 -1
  10. package/dist/BrowserEvent.d.mts +1 -1
  11. package/dist/BrowserEvent.mjs +166 -35
  12. package/dist/BrowserEvent.mjs.map +1 -1
  13. package/dist/Cdp.d.mts +15 -0
  14. package/dist/Cdp.mjs +22 -0
  15. package/dist/Cdp.mjs.map +1 -0
  16. package/dist/Change.d.mts +2 -2
  17. package/dist/Change.mjs +33 -6
  18. package/dist/Change.mjs.map +1 -1
  19. package/dist/Frame.d.mts +2 -2
  20. package/dist/Frame.mjs +132 -14
  21. package/dist/Frame.mjs.map +1 -1
  22. package/dist/{Style.d.mts → InputStyle.d.mts} +93 -25
  23. package/dist/{Style.mjs → InputStyle.mjs} +1 -1
  24. package/dist/Layout.d.mts +2 -2
  25. package/dist/Layout.mjs +58 -16
  26. package/dist/Layout.mjs.map +1 -1
  27. package/dist/Overlay.d.mts +2 -2
  28. package/dist/Overlay.mjs +33 -5
  29. package/dist/Overlay.mjs.map +1 -1
  30. package/dist/Page.d.mts +2 -2
  31. package/dist/Page.mjs +2 -2
  32. package/dist/PageTime.d.mts +2 -2
  33. package/dist/PageTime.mjs +13 -3
  34. package/dist/PageTime.mjs.map +1 -1
  35. package/dist/Pose.d.mts +2 -2
  36. package/dist/Pose.mjs +30 -9
  37. package/dist/Pose.mjs.map +1 -1
  38. package/dist/Site.d.mts +288 -18
  39. package/dist/Site.mjs +11 -3
  40. package/dist/Site.mjs.map +1 -1
  41. package/dist/Snapshot.d.mts +2 -2
  42. package/dist/Snapshot.mjs +87 -6
  43. package/dist/Snapshot.mjs.map +1 -1
  44. package/dist/Text.d.mts +2 -0
  45. package/dist/Text.mjs +45 -0
  46. package/dist/Text.mjs.map +1 -0
  47. package/dist/Window.d.mts +2 -2
  48. package/dist/Window.mjs +31 -6
  49. package/dist/Window.mjs.map +1 -1
  50. package/dist/ai/BrowserTools.d.mts +4987 -0
  51. package/dist/ai/BrowserTools.mjs +3 -0
  52. package/dist/ai/PageControl.d.mts +286 -0
  53. package/dist/ai/PageControl.mjs +426 -0
  54. package/dist/ai/PageControl.mjs.map +1 -0
  55. package/dist/ai/PromptCache.d.mts +16 -0
  56. package/dist/ai/PromptCache.mjs +72 -0
  57. package/dist/ai/PromptCache.mjs.map +1 -0
  58. package/dist/ai/Tabs.d.mts +2 -0
  59. package/dist/ai/Tabs.mjs +72 -0
  60. package/dist/ai/Tabs.mjs.map +1 -0
  61. package/dist/ai/ToolError.d.mts +34 -0
  62. package/dist/ai/ToolError.mjs +2 -0
  63. package/dist/ai/index.d.mts +6 -0
  64. package/dist/ai/index.mjs +6 -0
  65. package/dist/index.d.mts +7 -18
  66. package/dist/index.mjs +6 -9
  67. package/dist/{Action-24sLOubi.d.mts → internal/Action-CkanNTUw.d.mts} +64 -4
  68. package/dist/{Browser-DGR6ZEYo.d.mts → internal/Browser-DD9Vm1c-.d.mts} +75 -11
  69. package/dist/{Browser-CAQFhTkM.mjs → internal/Browser-vzD7i2oj.mjs} +174 -237
  70. package/dist/internal/Browser-vzD7i2oj.mjs.map +1 -0
  71. package/dist/{BrowserError-BlcmLVzn.d.mts → internal/BrowserError-CsuRYcDX.d.mts} +187 -28
  72. package/dist/{BrowserEvent-C2p-NwuU.d.mts → internal/BrowserEvent-tGPYYf6R.d.mts} +168 -13
  73. package/dist/internal/BrowserTools-Yi3lOX4h.mjs +497 -0
  74. package/dist/internal/BrowserTools-Yi3lOX4h.mjs.map +1 -0
  75. package/dist/{Style-T3ezDYLI.mjs → internal/InputStyle-CPzxoN4g.mjs} +75 -20
  76. package/dist/internal/InputStyle-CPzxoN4g.mjs.map +1 -0
  77. package/dist/{moment/Moment.mjs → internal/Moment-CstaX1mR.mjs} +49 -16
  78. package/dist/internal/Moment-CstaX1mR.mjs.map +1 -0
  79. package/dist/{moment/Moment.d.mts → internal/Moment-DOcldBdf.d.mts} +53 -20
  80. package/dist/internal/Page-BfGxn7oN.d.mts +1553 -0
  81. package/dist/{Page-BaAOshxo.mjs → internal/Page-DqF-tuTx.mjs} +62 -74
  82. package/dist/internal/Page-DqF-tuTx.mjs.map +1 -0
  83. package/dist/internal/Release-CFONkPDP.d.mts +39 -0
  84. package/dist/internal/Stage-D5ymSXDT.mjs +298 -0
  85. package/dist/internal/Stage-D5ymSXDT.mjs.map +1 -0
  86. package/dist/internal/Stillness-DCPeAN1a.mjs +1124 -0
  87. package/dist/internal/Stillness-DCPeAN1a.mjs.map +1 -0
  88. package/dist/internal/Supervisor-BcY_QNIY.d.mts +108 -0
  89. package/dist/internal/Supervisor-BcglY23c.mjs +531 -0
  90. package/dist/internal/Supervisor-BcglY23c.mjs.map +1 -0
  91. package/dist/internal/Tabs-dXMscIUQ.d.mts +52 -0
  92. package/dist/internal/TestPage-CYiYbh63.d.mts +159 -0
  93. package/dist/internal/ToolError-DArsRS2m.mjs +117 -0
  94. package/dist/internal/ToolError-DArsRS2m.mjs.map +1 -0
  95. package/dist/{plan/index.d.mts → internal/Walk-BNXcfZ2z.d.mts} +59 -35
  96. package/dist/{plan/index.mjs → internal/Walk-C5ky7uSf.mjs} +83 -51
  97. package/dist/internal/Walk-C5ky7uSf.mjs.map +1 -0
  98. package/dist/{ActionPort.mjs → internal/action-port-B5EkeGOR.mjs} +6 -12
  99. package/dist/internal/action-port-B5EkeGOR.mjs.map +1 -0
  100. package/dist/internal/cdp/workerd.d.mts +13 -0
  101. package/dist/internal/cdp/workerd.mjs +19 -0
  102. package/dist/internal/cdp/workerd.mjs.map +1 -0
  103. package/dist/{Clock.mjs → internal/clock-BKSAEf00.mjs} +13 -13
  104. package/dist/internal/clock-BKSAEf00.mjs.map +1 -0
  105. package/dist/{connection-Db-YtlbE.d.mts → internal/connection-BaB0vp1o.d.mts} +6 -6
  106. package/dist/{connection-C_jWYIwe.mjs → internal/connection-C2X4GmXM.mjs} +19 -15
  107. package/dist/internal/connection-C2X4GmXM.mjs.map +1 -0
  108. package/dist/internal/events-DzCrww-y.mjs +72 -0
  109. package/dist/internal/events-DzCrww-y.mjs.map +1 -0
  110. package/dist/internal/fold.inpage-uhrT-dOB.mjs +49 -0
  111. package/dist/internal/fold.inpage-uhrT-dOB.mjs.map +1 -0
  112. package/dist/internal/functions-jBOs6GKv.mjs +27 -0
  113. package/dist/internal/functions-jBOs6GKv.mjs.map +1 -0
  114. package/dist/{Geometry-DJx9qrYy.d.mts → internal/geometry-Dhj_ztJs.d.mts} +3 -3
  115. package/dist/{Geometry.mjs → internal/geometry-Lxyflb9J.mjs} +3 -12
  116. package/dist/internal/geometry-Lxyflb9J.mjs.map +1 -0
  117. package/dist/{Matching.mjs → internal/matching-Cs-UeOY0.mjs} +3 -3
  118. package/dist/internal/matching-Cs-UeOY0.mjs.map +1 -0
  119. package/dist/internal/page-DFQb-YOK.mjs +436 -0
  120. package/dist/internal/page-DFQb-YOK.mjs.map +1 -0
  121. package/dist/{pose.inpage-CLq7Mfdr.mjs → internal/pose.inpage-CBFeWcVa.mjs} +2 -48
  122. package/dist/internal/pose.inpage-CBFeWcVa.mjs.map +1 -0
  123. package/dist/{Url.mjs → internal/url-DB0pQYk6.mjs} +3 -12
  124. package/dist/internal/url-DB0pQYk6.mjs.map +1 -0
  125. package/dist/policy/Policy.d.mts +60 -6
  126. package/dist/policy/Policy.mjs +52 -9
  127. package/dist/policy/Policy.mjs.map +1 -1
  128. package/dist/policy/index.d.mts +2 -0
  129. package/dist/policy/index.mjs +2 -0
  130. package/dist/{film → presentation}/Film.d.mts +83 -16
  131. package/dist/{film → presentation}/Film.mjs +82 -30
  132. package/dist/presentation/Film.mjs.map +1 -0
  133. package/dist/presentation/Motion.d.mts +5 -1
  134. package/dist/presentation/Motion.mjs +16 -2
  135. package/dist/presentation/Motion.mjs.map +1 -1
  136. package/dist/presentation/Presentation.d.mts +42 -7
  137. package/dist/presentation/Presentation.mjs +26 -9
  138. package/dist/presentation/Presentation.mjs.map +1 -1
  139. package/dist/presentation/Stage.d.mts +40 -6
  140. package/dist/presentation/Stage.mjs +1 -262
  141. package/dist/presentation/index.d.mts +5 -0
  142. package/dist/presentation/index.mjs +5 -0
  143. package/dist/supervisor/Release.d.mts +2 -0
  144. package/dist/supervisor/Release.mjs +40 -0
  145. package/dist/supervisor/Release.mjs.map +1 -0
  146. package/dist/supervisor/Supervisor.d.mts +2 -104
  147. package/dist/supervisor/Supervisor.mjs +2 -515
  148. package/dist/supervisor/index.d.mts +3 -0
  149. package/dist/supervisor/index.mjs +3 -0
  150. package/dist/testing/HttpCassette.d.mts +98 -0
  151. package/dist/testing/HttpCassette.mjs +146 -0
  152. package/dist/testing/HttpCassette.mjs.map +1 -0
  153. package/dist/testing/Story.d.mts +31 -0
  154. package/dist/testing/Story.mjs +76 -0
  155. package/dist/testing/Story.mjs.map +1 -0
  156. package/dist/testing/TestBrowser.d.mts +191 -0
  157. package/dist/testing/TestBrowser.mjs +105 -0
  158. package/dist/testing/TestBrowser.mjs.map +1 -0
  159. package/dist/testing/TestModel.d.mts +133 -0
  160. package/dist/testing/TestModel.mjs +209 -0
  161. package/dist/testing/TestModel.mjs.map +1 -0
  162. package/dist/testing/TestPage.d.mts +2 -0
  163. package/dist/testing/TestPage.mjs +47 -0
  164. package/dist/testing/TestPage.mjs.map +1 -0
  165. package/dist/testing/index.d.mts +6 -311
  166. package/dist/testing/index.mjs +6 -521
  167. package/dist/timeline/Moment.d.mts +3 -0
  168. package/dist/timeline/Moment.mjs +3 -0
  169. package/dist/timeline/Stillness.d.mts +34 -0
  170. package/dist/timeline/Stillness.mjs +2 -0
  171. package/dist/timeline/index.d.mts +3 -0
  172. package/dist/timeline/index.mjs +3 -0
  173. package/dist/walk/Walk.d.mts +2 -0
  174. package/dist/walk/Walk.mjs +2 -0
  175. package/dist/walk/index.d.mts +2 -0
  176. package/dist/walk/index.mjs +2 -0
  177. package/package.json +54 -163
  178. package/src/Action.ts +73 -8
  179. package/src/Browser.ts +75 -9
  180. package/src/BrowserError.ts +258 -63
  181. package/src/BrowserEvent.ts +252 -55
  182. package/src/Cdp.ts +42 -0
  183. package/src/Change.ts +68 -3
  184. package/src/Frame.ts +247 -14
  185. package/src/{Style.ts → InputStyle.ts} +98 -22
  186. package/src/Layout.ts +95 -24
  187. package/src/Overlay.ts +42 -3
  188. package/src/Page.ts +144 -320
  189. package/src/PageTime.ts +29 -4
  190. package/src/Pose.ts +38 -7
  191. package/src/Site.ts +15 -3
  192. package/src/Snapshot.ts +179 -3
  193. package/src/Text.ts +60 -0
  194. package/src/Window.ts +53 -3
  195. package/src/ai/BrowserTools.ts +778 -0
  196. package/src/ai/PageControl.ts +702 -0
  197. package/src/ai/PromptCache.ts +87 -0
  198. package/src/ai/Tabs.ts +84 -0
  199. package/src/ai/ToolError.ts +50 -0
  200. package/src/ai/index.ts +36 -0
  201. package/src/ai/internal/crops.ts +38 -0
  202. package/src/ai/internal/points.ts +57 -0
  203. package/src/ai/internal/receipts.ts +107 -0
  204. package/src/index.ts +83 -6
  205. package/src/{ActionPort.ts → internal/action-port.ts} +3 -3
  206. package/src/{providers → internal/cdp}/connection.ts +19 -12
  207. package/src/internal/cdp/workerd.ts +36 -0
  208. package/src/{Clock.ts → internal/clock.ts} +20 -0
  209. package/src/internal/input/actions.ts +1 -1
  210. package/src/internal/input/dispatch.ts +2 -2
  211. package/src/internal/input/guard.inpage.ts +1 -1
  212. package/src/internal/input/guard.ts +1 -1
  213. package/src/internal/input/perform.ts +5 -5
  214. package/src/internal/input/pointer.ts +2 -2
  215. package/src/internal/input/targets.inpage.ts +3 -3
  216. package/src/{Matching.ts → internal/matching.ts} +6 -6
  217. package/src/internal/page/bridge.ts +2 -2
  218. package/src/internal/page/clock.inpage.ts +1 -1
  219. package/src/internal/page/compose.inpage.ts +2 -2
  220. package/src/internal/page/context.ts +2 -2
  221. package/src/internal/page/functions.ts +84 -0
  222. package/src/internal/page/navigation.ts +1 -1
  223. package/src/internal/page/openings.ts +2 -2
  224. package/src/internal/page/page.ts +33 -35
  225. package/src/internal/page/port.ts +14 -8
  226. package/src/internal/page/replies.ts +1 -1
  227. package/src/internal/page/requests.ts +1 -1
  228. package/src/internal/page/scripts.ts +1 -1
  229. package/src/internal/page/time.ts +1 -1
  230. package/src/internal/pictures/capture.ts +1 -4
  231. package/src/internal/pictures/dimensions.ts +1 -1
  232. package/src/internal/pictures/frame.ts +1 -1
  233. package/src/internal/pictures/pictures.ts +53 -61
  234. package/src/internal/reading/context.inpage.ts +2 -2
  235. package/src/internal/reading/expect.inpage.ts +1 -1
  236. package/src/internal/reading/layout.inpage.ts +3 -3
  237. package/src/internal/reading/layout.ts +5 -5
  238. package/src/internal/reading/outline.inpage.ts +3 -3
  239. package/src/internal/reading/reading.ts +11 -19
  240. package/src/internal/reading/ready.inpage.ts +2 -2
  241. package/src/internal/reading/ready.ts +3 -2
  242. package/src/internal/reading/subjects.inpage.ts +3 -3
  243. package/src/internal/reading/text.inpage.ts +2 -2
  244. package/src/internal/reading/walk.inpage.ts +1 -1
  245. package/src/internal/timeline/changes.inpage.ts +2 -2
  246. package/src/internal/timeline/changes.ts +3 -4
  247. package/src/internal/timeline/sight.inpage.ts +2 -2
  248. package/src/internal/timeline/window.ts +3 -4
  249. package/src/policy/Policy.ts +70 -16
  250. package/src/policy/index.ts +12 -0
  251. package/src/{film → presentation}/Film.ts +104 -37
  252. package/src/presentation/Motion.ts +45 -3
  253. package/src/presentation/Presentation.ts +47 -14
  254. package/src/presentation/Stage.ts +73 -35
  255. package/src/presentation/index.ts +30 -0
  256. package/src/presentation/{feed.ts → internal/feed.ts} +1 -1
  257. package/src/supervisor/Release.ts +45 -0
  258. package/src/supervisor/Supervisor.ts +80 -5
  259. package/src/supervisor/index.ts +18 -0
  260. package/src/supervisor/{contract.ts → internal/contract.ts} +14 -10
  261. package/src/supervisor/{lifecycle.ts → internal/lifecycle.ts} +7 -7
  262. package/src/supervisor/{runtime.ts → internal/runtime.ts} +7 -7
  263. package/src/testing/HttpCassette.ts +260 -0
  264. package/src/testing/Story.ts +103 -0
  265. package/src/testing/TestBrowser.ts +14 -4
  266. package/src/testing/TestModel.ts +297 -0
  267. package/src/testing/TestPage.ts +92 -4
  268. package/src/testing/index.ts +35 -1
  269. package/src/testing/{evidence.ts → internal/evidence.ts} +19 -11
  270. package/src/testing/{model.ts → internal/model.ts} +14 -8
  271. package/src/testing/{page.ts → internal/page.ts} +55 -56
  272. package/src/{moment → timeline}/Moment.ts +79 -29
  273. package/src/{stillness → timeline}/Stillness.ts +61 -43
  274. package/src/timeline/index.ts +18 -0
  275. package/src/{stillness/Pixels.ts → timeline/internal/pixels.ts} +2 -2
  276. package/src/{moment → timeline/internal}/words.ts +2 -2
  277. package/src/walk/Walk.ts +165 -0
  278. package/src/walk/index.ts +12 -0
  279. package/src/{plan → walk/internal}/choose.ts +23 -14
  280. package/src/{plan → walk/internal}/data.ts +37 -14
  281. package/src/{plan → walk/internal}/execute.ts +79 -36
  282. package/src/{plan → walk/internal}/record.ts +6 -6
  283. package/src/{plan → walk/internal}/targets.ts +35 -25
  284. package/dist/ActionPort.d.mts +0 -15
  285. package/dist/ActionPort.mjs.map +0 -1
  286. package/dist/Browser-CAQFhTkM.mjs.map +0 -1
  287. package/dist/Change-CxT1mp2e.d.mts +0 -80
  288. package/dist/Clock-Du5nP-nK.d.mts +0 -57
  289. package/dist/Clock.d.mts +0 -2
  290. package/dist/Clock.mjs.map +0 -1
  291. package/dist/Frame-UEH2hO5T.d.mts +0 -124
  292. package/dist/Geometry.d.mts +0 -2
  293. package/dist/Geometry.mjs.map +0 -1
  294. package/dist/Matching-MtcWZ_hA.d.mts +0 -266
  295. package/dist/Matching.d.mts +0 -2
  296. package/dist/Matching.mjs.map +0 -1
  297. package/dist/Overlay-CoGw5tL_.d.mts +0 -27
  298. package/dist/Page-BaAOshxo.mjs.map +0 -1
  299. package/dist/Page-CLzh5E9w.d.mts +0 -718
  300. package/dist/PageTime-68UPUZpZ.d.mts +0 -29
  301. package/dist/Pose-2qqGzPvb.d.mts +0 -32
  302. package/dist/Released-tURbFmal.d.mts +0 -15
  303. package/dist/Snapshot-CtBVOtuu.d.mts +0 -73
  304. package/dist/Stillness-BwP0RdI4.mjs +0 -157
  305. package/dist/Stillness-BwP0RdI4.mjs.map +0 -1
  306. package/dist/Style-T3ezDYLI.mjs.map +0 -1
  307. package/dist/Url-B7P-TWwL.d.mts +0 -26
  308. package/dist/Url.d.mts +0 -2
  309. package/dist/Url.mjs.map +0 -1
  310. package/dist/Window-BDa8MtNP.d.mts +0 -34
  311. package/dist/connection-C_jWYIwe.mjs.map +0 -1
  312. package/dist/film/Film.mjs.map +0 -1
  313. package/dist/moment/Moment.mjs.map +0 -1
  314. package/dist/plan/index.mjs.map +0 -1
  315. package/dist/pose.inpage-CLq7Mfdr.mjs.map +0 -1
  316. package/dist/presentation/Stage.mjs.map +0 -1
  317. package/dist/presentation/feed.d.mts +0 -20
  318. package/dist/presentation/feed.mjs +0 -18
  319. package/dist/presentation/feed.mjs.map +0 -1
  320. package/dist/providers/Cdp.d.mts +0 -9
  321. package/dist/providers/Cdp.mjs +0 -15
  322. package/dist/providers/Cdp.mjs.map +0 -1
  323. package/dist/providers/Chromium.d.mts +0 -32
  324. package/dist/providers/Chromium.mjs +0 -55
  325. package/dist/providers/Chromium.mjs.map +0 -1
  326. package/dist/providers/Released.d.mts +0 -2
  327. package/dist/providers/Released.mjs +0 -12
  328. package/dist/providers/Released.mjs.map +0 -1
  329. package/dist/stillness/Stillness.d.mts +0 -12
  330. package/dist/stillness/Stillness.mjs +0 -2
  331. package/dist/supervisor/Supervisor.mjs.map +0 -1
  332. package/dist/testing/index.mjs.map +0 -1
  333. package/dist/workerd/Cdp.d.mts +0 -8
  334. package/dist/workerd/Cdp.mjs +0 -13
  335. package/dist/workerd/Cdp.mjs.map +0 -1
  336. package/src/plan/index.ts +0 -36
  337. package/src/providers/Cdp.ts +0 -16
  338. package/src/providers/Chromium.ts +0 -99
  339. package/src/providers/Released.ts +0 -13
  340. package/src/workerd/Cdp.ts +0 -11
  341. /package/dist/{fold.inpage-CyVZQHZL.d.mts → internal/fold.inpage-CyVZQHZL.d.mts} +0 -0
  342. /package/dist/{rolldown-runtime-D7D4PA-g.mjs → internal/rolldown-runtime-D7D4PA-g.mjs} +0 -0
  343. /package/src/{Geometry.ts → internal/geometry.ts} +0 -0
  344. /package/src/{Url.ts → internal/url.ts} +0 -0
  345. /package/src/{stillness → timeline/internal}/utilsBundle.d.ts +0 -0
@@ -1,21 +1,25 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { Plan, Point, maximumSamples } from "./Geometry.mjs";
3
- import { parse, redact, redactWithin } from "./Url.mjs";
4
- import { nameOf, recorded } from "./Action.mjs";
5
- import { Action, ActionAnnounced, Box, CursorChanged, DialogShown, Disconnected, KeyChanged, Navigated, PageClosed, PageLoaded, PageOpened, PageUntracked, PointerPressed, PointerReleased, RecordedEvent, RequestRefused, SessionEnding, Subject, TextInserted, TrackEvent, TrackPerformed, TrackPlanned, WheelScrolled } from "./BrowserEvent.mjs";
6
- import { BrowserError, Busy, Closed, EventHistoryExpired, Failed, InvalidRequest, Limit, NavigationFailed, NotActionable, NotFound, PolicyTimeout, StaleRef, Suspended, Threw, Timeout, call, failWith, reasonOf, refuse, undispatched } from "./BrowserError.mjs";
7
- import { BrowserPaint, CaptureStats, Frame, Image, Screenshot, sameCapture } from "./Frame.mjs";
8
- import { _ as PreparedInputResultSchema, c as State, g as make$32, h as FailFast, i as InputRequest, l as Text, m as Correlation, o as Region, p as redacted, r as Found, s as ResolvedTarget, u as Zoom, v as ValidatedInputResultSchema } from "./Page-BaAOshxo.mjs";
9
- import { Snapshot } from "./Snapshot.mjs";
10
- import { checked, execute, methods } from "./ActionPort.mjs";
11
- import { estimate, mapping, monotonicMillis, toBrowserSeconds, toHostTime, uncertaintyAt } from "./Clock.mjs";
12
- import { pickRequests, request } from "./Matching.mjs";
13
- import { n as poseRequest } from "./pose.inpage-CLq7Mfdr.mjs";
14
- import { d as description, f as parts$1, t as Current$2, u as validated } from "./Style-T3ezDYLI.mjs";
15
- import { Layout, Place, Word } from "./Layout.mjs";
16
- import { Change, Changes } from "./Change.mjs";
17
- import { Window } from "./Window.mjs";
18
- import { Pose } from "./Pose.mjs";
2
+ import { a as maximumSamples, n as Point, t as Plan } from "./geometry-Lxyflb9J.mjs";
3
+ import { a as redactWithin, i as redact, n as parse } from "./url-DB0pQYk6.mjs";
4
+ import { nameOf, recorded } from "../Action.mjs";
5
+ import { Action, ActionAnnounced, Box, CursorChanged, DialogShown, Disconnected, KeyChanged, Navigated, PageClosed, PageLoaded, PageOpened, PageUntracked, PointerPressed, PointerReleased, RequestRefused, SessionEnding, Subject, TextInserted, TrackEvent, TrackPerformed, TrackPlanned, WheelScrolled } from "../BrowserEvent.mjs";
6
+ import { BrowserError, Busy, Closed, Failed, InvalidRequest, Limit, NavigationFailed, NotActionable, NotFound, PolicyTimeout, StaleRef, Suspended, Threw, Timeout, call, failWith, reasonOf, refuse, undispatched } from "../BrowserError.mjs";
7
+ import { a as toBrowserSeconds, i as monotonicMillis, n as mapping, o as toHostTime, r as millisOf, s as uncertaintyAt, t as estimate } from "./clock-BKSAEf00.mjs";
8
+ import { a as State, d as FailFast, f as make$31, i as ResolvedTarget, l as redacted, m as ValidatedInputResultSchema, n as InputRequest, p as PreparedInputResultSchema, u as Correlation } from "./Page-DqF-tuTx.mjs";
9
+ import { n as pickRequests, r as request } from "./matching-Cs-UeOY0.mjs";
10
+ import { n as poseRequest } from "./pose.inpage-CBFeWcVa.mjs";
11
+ import "./fold.inpage-uhrT-dOB.mjs";
12
+ import { i as key, t as Implementation } from "./functions-jBOs6GKv.mjs";
13
+ import { n as execute, r as methods, t as checked } from "./action-port-B5EkeGOR.mjs";
14
+ import { d as description, f as parts$1, t as Current$2, u as validated } from "./InputStyle-CPzxoN4g.mjs";
15
+ import { BrowserPaint, CaptureStats, Frame, Image, Region, Screenshot, Zoom, sameCapture } from "../Frame.mjs";
16
+ import { Layout, Place, Word } from "../Layout.mjs";
17
+ import { Found, Snapshot } from "../Snapshot.mjs";
18
+ import { Text } from "../Text.mjs";
19
+ import { Change, Changes } from "../Change.mjs";
20
+ import { Window } from "../Window.mjs";
21
+ import { Pose } from "../Pose.mjs";
22
+ import { t as make$32 } from "./events-DzCrww-y.mjs";
19
23
  import { Cache, Cause, Clock, Context, Data, DateTime, Deferred, Duration, Effect, Exit, Fiber, FiberSet, MutableRef, Option, Queue, Ref, Result, Schedule, Schema, Scope, Semaphore, Stream, SynchronizedRef } from "effect";
20
24
  import { SecureRandom } from "effect/crypto";
21
25
  import { Base64 } from "effect/encoding";
@@ -76,7 +80,7 @@ const step$1 = (state, input, stopped) => {
76
80
  } : state;
77
81
  }
78
82
  };
79
- const make$31 = (options) => {
83
+ const make$30 = (options) => {
80
84
  let state = {
81
85
  _tag: "Open",
82
86
  inputs: /* @__PURE__ */ new Set()
@@ -200,9 +204,9 @@ const ScrollPlanSchema = Schema.NullOr(Schema.Struct({
200
204
  //#endregion
201
205
  //#region src/internal/page/port.ts
202
206
  /** Scoped protocol interception at the owned session boundary; native is the default. */
203
- const Operation = Context.Reference("effect-browser/ProtocolOperation", { defaultValue: () => void 0 });
204
- const Script = Context.Reference("effect-browser/ProtocolScript", { defaultValue: () => void 0 });
205
- const Current$1 = Context.Reference("effect-browser/ProtocolPort", { defaultValue: () => ({}) });
207
+ const Operation = Context.Reference("effect-browser/internal/page/ProtocolOperation", { defaultValue: () => void 0 });
208
+ const Script = Context.Reference("effect-browser/internal/page/ProtocolScript", { defaultValue: () => void 0 });
209
+ const Current$1 = Context.Reference("effect-browser/internal/page/ProtocolPort", { defaultValue: () => ({}) });
206
210
  /** The provider owns creation and passes its session to an optional scoped test adapter. */
207
211
  const openSession = Effect.fnUntraced(function* (open, nativePage, channel = "page") {
208
212
  const hooks = yield* Current$1;
@@ -253,7 +257,7 @@ const openCapture = Effect.fnUntraced(function* (page, source, handlers) {
253
257
  var InputFailure = class extends Data.TaggedError("InputFailure") {};
254
258
  /** Native page calls join their operation's reply ownership, including script mutations. */
255
259
  const Current = Context.Reference("effect-browser/internal/input/Current", { defaultValue: () => void 0 });
256
- const make$30 = () => {
260
+ const make$29 = () => {
257
261
  const outstanding = /* @__PURE__ */ new Set();
258
262
  const idle = Effect.gen(function* () {
259
263
  while (outstanding.size > 0) yield* Effect.promise(() => Promise.all(outstanding));
@@ -387,7 +391,7 @@ const CurrentCost = Context.Reference("effect-browser/internal/page/CurrentCost"
387
391
  const track = (reply) => Fiber.getCurrent()?.getRef(Current)?.track(reply) ?? reply;
388
392
  const sizeOf = (value) => value === void 0 ? 0 : new TextEncoder().encode(JSON.stringify(value)).byteLength;
389
393
  const decodeWith = (operation, schema) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError((error) => undispatched(operation, new Failed({ detail: error.message }))));
390
- const make$29 = (options, scope) => {
394
+ const make$28 = (options, scope) => {
391
395
  const { id, clock } = options;
392
396
  const now = () => monotonicMillis(clock);
393
397
  const owned = Effect.provideService(Clock.Clock, clock);
@@ -454,7 +458,7 @@ const make$29 = (options, scope) => {
454
458
  const noteInput = () => {
455
459
  activity.inputAt = Math.max(activity.inputAt, now());
456
460
  };
457
- const lane = make$32({
461
+ const lane = make$31({
458
462
  now,
459
463
  actionTimeout: options.settings.actionTimeout,
460
464
  documentAt: () => activity.documentAt,
@@ -488,7 +492,7 @@ const encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));
488
492
  */
489
493
  const clockSource = "(() => {var pageScript = (function() {\n //#region src/internal/page/clock.inpage.ts\n const timers = (real, now, held, report) => {\n const all = /* @__PURE__ */ new Map();\n let next = 1;\n const arm = (id, timer) => {\n timer.real = real.setTimeout(() => {\n if (all.get(id) === timer && !held()) fire(id, timer);\n }, Math.max(0, timer.at - now()));\n };\n const fire = (id, timer) => {\n if (timer.every > 0) {\n timer.at = Math.max(timer.at + timer.every, now());\n if (!held()) arm(id, timer);\n } else all.delete(id);\n try {\n timer.run();\n } catch (error) {\n report(error);\n }\n };\n const schedule = (every) => (handler, delay, ...args) => {\n const id = next++;\n const millis = Math.max(every ? 1 : 0, Number(delay) || 0);\n const run = () => {\n if (typeof handler === \"function\") Reflect.apply(handler, window, args);\n else (0, eval)(handler);\n };\n const timer = {\n run,\n every: every ? millis : 0,\n at: now() + millis\n };\n all.set(id, timer);\n if (!held()) arm(id, timer);\n return id;\n };\n const clear = (id) => {\n const timer = all.get(Number(id));\n if (timer?.real !== void 0) real.clearTimeout(timer.real);\n all.delete(Number(id));\n };\n const runDue = (target, reach) => {\n let due;\n for (const entry of all) if (entry[1].at <= target && (due === void 0 || entry[1].at < due[1].at)) due = entry;\n if (due === void 0) return false;\n reach(due[1].at);\n fire(...due);\n return true;\n };\n return {\n setTimeout: schedule(false),\n setInterval: schedule(true),\n clear,\n runDue,\n pause: () => {\n for (const timer of all.values()) if (timer.real !== void 0) real.clearTimeout(timer.real);\n },\n resume: () => {\n for (const [id, timer] of all) arm(id, timer);\n }\n };\n };\n const animations = () => {\n let ours = /* @__PURE__ */ new WeakSet();\n const catchUp = () => {\n for (const animation of document.getAnimations()) if (animation.playState === \"running\") {\n animation.pause();\n if (!ours.has(animation)) animation.currentTime = 0;\n ours.add(animation);\n }\n };\n const move = (by) => {\n if (by <= 0) return;\n for (const animation of document.getAnimations()) {\n if (!ours.has(animation) || animation.playState !== \"paused\") continue;\n const at = Number(animation.currentTime) + by * animation.playbackRate;\n const end = Number(animation.effect?.getComputedTiming().endTime ?? Infinity);\n if (animation.playbackRate >= 0 ? at >= end : at <= 0) {\n ours.delete(animation);\n animation.finish();\n } else animation.currentTime = at;\n }\n };\n const play = () => {\n for (const animation of document.getAnimations()) if (ours.has(animation) && animation.playState === \"paused\") animation.play();\n ours = /* @__PURE__ */ new WeakSet();\n };\n return {\n catchUp,\n move,\n play\n };\n };\n const clock = (parts) => (name) => {\n if (window !== window.top) return;\n const real = {\n setTimeout: window.setTimeout.bind(window),\n clearTimeout: window.clearTimeout.bind(window),\n requestAnimationFrame: window.requestAnimationFrame.bind(window),\n cancelAnimationFrame: window.cancelAnimationFrame.bind(window),\n now: performance.now.bind(performance),\n dateNow: Date.now,\n Date\n };\n let held = false;\n let frozen = 0;\n let shift = 0;\n let dated;\n let nextFrame = 1;\n const pageNow = () => held ? frozen : real.now() + shift;\n const dateNow = () => dated === void 0 ? real.dateNow() : Math.floor(pageNow() + dated);\n const report = (error) => {\n real.setTimeout(() => {\n throw error;\n });\n };\n const timed = parts.timers(real, pageNow, () => held, report);\n const animated = parts.animations();\n const frames = /* @__PURE__ */ new Map();\n const request = (id, frame) => {\n frame.real = real.requestAnimationFrame(() => {\n frames.delete(id);\n frame.run(pageNow());\n });\n };\n const reach = (at) => {\n animated.catchUp();\n animated.move(at - frozen);\n frozen = Math.max(frozen, at);\n };\n const hold = () => {\n if (held) return;\n dated ??= real.dateNow() - real.now();\n frozen = pageNow();\n held = true;\n timed.pause();\n for (const frame of frames.values()) if (frame.real !== void 0) real.cancelAnimationFrame(frame.real);\n animated.catchUp();\n };\n const advance = (by) => {\n const target = frozen + by;\n for (let guard = 0; guard < 1e4 && timed.runDue(target, reach); guard++);\n reach(target);\n const callbacks = [...frames.values()];\n frames.clear();\n for (const frame of callbacks) try {\n frame.run(frozen);\n } catch (error) {\n report(error);\n }\n animated.catchUp();\n };\n const release = () => {\n if (!held) return;\n held = false;\n shift = Math.max(shift, frozen - real.now());\n timed.resume();\n for (const [id, frame] of frames) request(id, frame);\n animated.play();\n };\n const define = (target, key, value) => Object.defineProperty(target, key, {\n value,\n writable: true,\n configurable: true\n });\n define(window, \"setTimeout\", timed.setTimeout);\n define(window, \"setInterval\", timed.setInterval);\n define(window, \"clearTimeout\", timed.clear);\n define(window, \"clearInterval\", timed.clear);\n define(window, \"requestAnimationFrame\", (run) => {\n const id = nextFrame++;\n const frame = { run };\n frames.set(id, frame);\n if (!held) request(id, frame);\n return id;\n });\n define(window, \"cancelAnimationFrame\", (id) => {\n const frame = frames.get(id);\n if (frame?.real !== void 0) real.cancelAnimationFrame(frame.real);\n frames.delete(id);\n });\n define(performance, \"now\", pageNow);\n function PageDate(...args) {\n if (new.target === void 0) return new real.Date(dateNow()).toString();\n return Reflect.construct(real.Date, args.length === 0 ? [dateNow()] : args, new.target);\n }\n Object.setPrototypeOf(PageDate, real.Date);\n PageDate.prototype = real.Date.prototype;\n define(PageDate, \"now\", dateNow);\n define(window, \"Date\", PageDate);\n document.addEventListener(name, (event) => {\n const detail = \"detail\" in event ? event.detail : void 0;\n const op = typeof detail === \"object\" && detail !== null && \"op\" in detail ? detail.op : \"\";\n const by = typeof detail === \"object\" && detail !== null && \"by\" in detail ? Number(detail.by) : 0;\n if (op === \"holds\") {\n if (held) event.preventDefault();\n return;\n }\n if (op === \"hold\" || op === \"advance\") hold();\n if (op === \"advance\" && Number.isFinite(by) && by >= 0) advance(by);\n if (op === \"release\") release();\n event.preventDefault();\n }, true);\n };\n //#endregion\n return clock({\n timers,\n animations\n });\n})();\n\nreturn pageScript;})()";
490
494
  /** The expression that installs the script and evaluates to its API; packaging freezes it. */
491
- const installSource = "(() => {var pageScript = (function() {\n //#region src/Matching.ts\n const match = () => {\n /**\n * How names, text and context compare: one Unicode form, without invisible format characters,\n * spaces collapsed, and case folded upper first, so that \"ß\" and \"SS\" read the same.\n */\n const normalize = (value) => value.normalize(\"NFKC\").replace(/\\p{Cf}/gu, \"\").replace(/\\s+/g, \" \").trim().toUpperCase().toLowerCase();\n /** A string that reads the same, or, unless `whole`, appears within; or a pattern found within. */\n const rule = (wanted, whole) => {\n if (typeof wanted !== \"string\") {\n const found = new RegExp(wanted.source, wanted.flags.replace(/[gy]/g, \"\"));\n return (value) => found.test(value.replace(/\\s+/g, \" \").trim());\n }\n const target = normalize(wanted);\n return whole ? (value) => normalize(value) === target : (value) => normalize(value).includes(target);\n };\n /** Whether a value's words appear, whole and in order, among a text's: \"BTC\" not in \"WBTC\". */\n const holds = (text, value) => ` ${normalize(text)} `.includes(` ${normalize(value)} `);\n /** Whether a candidate meets every rule a query gives; a rule left out always holds. */\n const compile = (request) => {\n const role = request.role === null ? null : normalize(request.role);\n const name = request.name === null ? null : rule(request.name, true);\n const text = request.text === null ? null : rule(request.text, false);\n const { near } = request;\n return (candidate) => {\n if (role !== null && normalize(candidate.role ?? \"\") !== role) return false;\n if (text !== null && !text(candidate.text())) return false;\n if (name !== null && !name(candidate.name())) return false;\n if (near === null) return true;\n const { row, column, label, heading } = candidate.context();\n return [\n row,\n column,\n label,\n heading\n ].some((value) => value !== void 0 && holds(value, near));\n };\n };\n /** A comparison token for ordered observations, without retaining their text. */\n const mark = (observations) => {\n let hash = 2166136261;\n for (const shown of observations) for (let index = 0; index < shown.length; index++) hash = Math.imul(hash ^ shown.charCodeAt(index), 16777619);\n return `${observations.length}:${(hash >>> 0).toString(16)}`;\n };\n return {\n compile,\n holds,\n normalize,\n mark\n };\n };\n //#endregion\n //#region src/Url.ts\n const addresses = () => {\n const withheld = \"••••••••\";\n const credential = /token|secret|passw|passcode|passphrase|signature|credential|assertion|verifier|bearer|jwt|hmac|apikey|accesskey|privatekey|sess(?:ion)?id|saml(?:response|art)|(?:sig|otp)$|(?:auth|api|access|private|secret|signing|client|encryption|licen[cs]e|session|master|app|device|verification|verify|confirmation|confirm|activation|activate|reset|recovery|login|security|magic|onetime|mfa|2fa|sms|email|otp|oob)(?:code|key)$|^(?:auth|authorization|pwd|pass)$/;\n const ambiguous = /^(?:code|key|session|sid|ticket)$/;\n const secret = (name, value) => {\n const bare = name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n return value !== \"\" && (credential.test(bare) || ambiguous.test(bare) && value.length >= 16 && /\\d/.test(value) && /[a-z]/i.test(value));\n };\n const masked = (parameters, separator) => parameters.split(separator).map((parameter) => {\n const [name = \"\", value = \"\"] = [...new URLSearchParams(parameter)][0] ?? [];\n return secret(name, value) ? `${parameter.slice(0, parameter.indexOf(\"=\") + 1)}${withheld}` : parameter;\n }).join(separator);\n /**\n * `url` as the library reports it: without userinfo, and with each credential's value withheld,\n * so the rest keeps its identity, such as a chart's `?ticker=ETH`. An address without a host,\n * such as `data:` or `about:blank`, is content or a fixed name, and stays as it is.\n */\n const redact = (url) => {\n const parsed = URL.parse(url);\n if (parsed === null || parsed.host === \"\") return url;\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.pathname = masked(parsed.pathname, \";\");\n parsed.search = masked(parsed.search.slice(1), \"&\");\n if (parsed.hash.includes(\"=\")) {\n const fragment = parsed.hash.slice(1);\n const question = fragment.indexOf(\"?\");\n const start = question >= 0 && question < fragment.indexOf(\"=\") ? question + 1 : 0;\n parsed.hash = fragment.slice(0, start) + masked(fragment.slice(start), \"&\");\n }\n return parsed.href.replaceAll(encodeURIComponent(withheld), withheld);\n };\n return {\n withheld,\n redact\n };\n };\n //#endregion\n //#region src/internal/input/edit.inpage.ts\n const edit = (names, guard, placing) => {\n const { activeElement, clean, describe, inCurrentDocument, isDisabled, isHtml, isInput, isSecret, isSelect, isTextArea, lookup, nameOf, roleOf } = names;\n const { textEntry, typingRefusal } = guard;\n /** Whether text may be typed into a ref or focus, and, for a `secret`, only into a secret field. */\n const typeable = (ref, secret) => {\n const element = ref === null ? activeElement() : lookup(ref);\n if (element === void 0) return {\n error: \"stale\",\n detail: `${ref ?? \"the focused element\"} is not on the page any more`\n };\n const refusal = element === null ? secret ? \"nothing has focus to type a secret into\" : void 0 : typingRefusal(element, ref !== null) ?? (secret && !isSecret(element) ? `${describe(element)} is not a secret field` : void 0);\n if (refusal !== void 0) return {\n error: \"untypeable\",\n detail: refusal\n };\n if (element === null || ref !== null || !textEntry(element)) return {\n ok: true,\n secret: element !== null && isSecret(element)\n };\n const role = roleOf(element);\n const tag = element.tagName.toLowerCase();\n return {\n ok: true,\n secret: isSecret(element),\n subject: {\n role,\n name: nameOf(element, role),\n tag,\n context: placing.contextOf(element)\n }\n };\n };\n /**\n * The focused field, when it is a text field named `name`: one a page put in place of a field\n * just pressed and gave focus to, as a typeahead does.\n */\n const replacement = (name) => {\n const active = activeElement();\n return active !== null && textEntry(active) && inCurrentDocument(active) && nameOf(active, roleOf(active)) === name ? active : void 0;\n };\n /**\n * Focus a field to type into. `follow` is the field's name when the action pressed it first: a\n * page may answer the press with another field of that name in its place, focused, and the keys\n * follow focus there, as a person's would.\n */\n const focus = (ref, replace, follow) => {\n const element = lookup(ref) ?? (follow === null ? void 0 : replacement(follow));\n if (element === void 0) return {\n error: `${ref} is not on the page any more`,\n stale: true\n };\n if (isDisabled(element)) return { error: `${ref} is disabled` };\n if (!textEntry(element)) return { error: `${ref} is ${describe(element)}, not a text field` };\n if (isHtml(element)) element.focus();\n if (replace) {\n if (isInput(element) || isTextArea(element)) element.select();\n else element.ownerDocument.getSelection()?.selectAllChildren(element);\n }\n return {\n ok: true,\n detail: describe(element),\n secret: isSecret(element)\n };\n };\n /** Focus any element that takes focus, such as a link or a button, for a key pressed on it. */\n const focusOn = (ref) => {\n const element = lookup(ref);\n if (element === void 0) return {\n error: `${ref} is not on the page any more`,\n stale: true\n };\n if (isDisabled(element)) return { error: `${ref} is disabled` };\n if (isHtml(element)) element.focus();\n return activeElement() === element ? {\n ok: true,\n detail: describe(element)\n } : { error: `${ref} is ${describe(element)}, which does not take focus` };\n };\n const select = (ref, values) => {\n const element = lookup(ref);\n if (element === void 0) return {\n error: `${ref} is not on the page any more`,\n stale: true\n };\n if (!isSelect(element)) return { error: `${ref} is ${describe(element)}, not a <select>; click it and pick an option` };\n const wanted = values.map((value) => value.trim().toLowerCase());\n const options = Array.from(element.options);\n const chosen = options.filter((option) => wanted.includes(option.value.toLowerCase()) || wanted.includes(clean(option.text).toLowerCase()));\n if (chosen.length === 0) return { error: `no option matches; the options are ${options.map((option) => JSON.stringify(clean(option.text, 40))).join(\", \")}` };\n for (const option of options) option.selected = chosen.includes(option);\n element.dispatchEvent(new Event(\"input\", { bubbles: true }));\n element.dispatchEvent(new Event(\"change\", { bubbles: true }));\n return {\n ok: true,\n detail: chosen.map((option) => clean(option.text, 40)).join(\", \")\n };\n };\n return {\n focus,\n focusOn,\n select,\n typeable\n };\n };\n //#endregion\n //#region src/internal/input/evidence.inpage.ts\n const evidence = (names, placing) => {\n const { clean, isDocument, isInput, isSelect, isTextArea, nameOf, parentOf, roleOf, textOf } = names;\n const { groups, headingBefore, textBeside, treeOf } = placing;\n /** A field a submission would send. */\n const isField = (element) => (isInput(element) && ![\n \"button\",\n \"submit\",\n \"reset\",\n \"image\"\n ].includes(element.type) || isSelect(element) || isTextArea(element)) && !element.matches(\":disabled\");\n const isFilled = (field) => isInput(field) && (field.type === \"checkbox\" || field.type === \"radio\") ? field.checked : isInput(field) && field.type === \"file\" ? (field.files?.length ?? 0) > 0 : field.value !== \"\";\n const dialogOf = (element) => {\n for (let node = element; node !== null; node = parentOf(node)) if (node.tagName === \"DIALOG\" || /^(?:alert)?dialog$/.test(node.getAttribute(\"role\") ?? \"\")) return node;\n };\n /** What the page says about an input's first target, for a judge. Never a field's value. */\n const evidenceOf = (element, form, method, action) => {\n const name = nameOf(element, roleOf(element));\n const ids = element.getAttribute(\"aria-describedby\");\n const description = clean(ids === null ? element.getAttribute(\"aria-description\") ?? element.getAttribute(\"title\") : ids.split(/\\s+/).map((id) => element.ownerDocument.getElementById(id)?.textContent ?? \"\").join(\" \"), 120);\n const dialog = dialogOf(element);\n const title = dialog?.querySelector(\"h1,h2,h3,h4,h5,h6,[role=heading]\");\n const dialogName = dialog === void 0 ? \"\" : clean(nameOf(dialog, \"dialog\"), 120) || (title === null || title === void 0 ? \"\" : clean(textOf(title), 120));\n const root = element.getRootNode();\n const top = isDocument(root) ? root.body ?? root : root;\n const inTree = element.closest(\"dialog,[role=dialog],[role=alertdialog]\");\n let nearby = \"\";\n for (const scope of /* @__PURE__ */ new Set([\n element.closest(groups),\n inTree,\n top\n ])) if (scope !== null && nearby === \"\") nearby = textBeside(element, scope, true) || textBeside(element, scope, false);\n const heading = headingBefore(element, treeOf(element));\n const fields = form === null ? [] : Array.from(form.elements).filter(isField).slice(0, 16).map((field) => {\n const autocomplete = clean(field.getAttribute(\"autocomplete\"), 40);\n return {\n type: isInput(field) ? field.type : field.tagName.toLowerCase(),\n name: clean(isInput(field) && field.type === \"hidden\" ? field.getAttribute(\"name\") : nameOf(field, roleOf(field)), 40),\n ...autocomplete === \"\" ? {} : { autocomplete },\n filled: isFilled(field)\n };\n });\n return {\n title: clean(document.title, 120),\n ...description === \"\" || description === name ? {} : { description },\n ...dialogName === \"\" ? {} : { dialog: dialogName },\n ...heading === void 0 ? {} : { heading },\n ...nearby === \"\" ? {} : { nearby },\n ...form === null ? {} : { form: {\n method: method ?? form.method,\n action: action ?? form.action,\n fields\n } }\n };\n };\n return {\n evidenceOf,\n isField,\n isFilled\n };\n };\n //#endregion\n //#region src/internal/input/guard.inpage.ts\n const guard = (names, targets, evidence) => {\n const { activeElement, textEntry, clean, describe, inCurrentDocument, interactiveRoles, isButton, isDisabled, isHtml, isInput, isLabel, isRoot, isSecret, isSelect, isTextArea, lookup, parentOf, refFor, roleOf } = names;\n const { controlOf, details, hitAt, hrefAttribute, linkOf, receives, within } = targets;\n const { evidenceOf, isField, isFilled } = evidence;\n const nativeActivation = (element) => hrefAttribute(element) !== null || element.tagName === \"BUTTON\" || element.tagName === \"SUMMARY\" || isInput(element) && element.type !== \"hidden\";\n /**\n * The element whose activation behaviour a click or key on `element` runs, as the browser\n * resolves it along the composed path: a link, button, input, summary or a label's control.\n */\n const activationTarget = (element) => {\n for (let node = element; node !== null; node = parentOf(node)) {\n if (nativeActivation(node)) return node;\n if (isLabel(node) && node.control !== null) return node.control;\n }\n };\n /**\n * A control between a press's hit and the approved target that is not the target's own\n * activation, such as a link or button a hover handler nested into it. The approval inspected\n * the target, so that control would act unapproved.\n */\n const nestedControl = (element, hit) => {\n if (!within(element, hit)) return void 0;\n const own = activationTarget(element);\n for (let node = hit; node !== null && node !== element; node = parentOf(node) ?? node.ownerDocument.defaultView?.frameElement ?? null) if (node !== own && (nativeActivation(node) || isSelect(node) || isTextArea(node) || isLabel(node) && node.control !== null && node.control !== own || activatingRoles.has(roleOf(node) ?? \"\"))) return node;\n };\n const activatingRoles = /* @__PURE__ */ new Set([\n \"button\",\n \"link\",\n \"checkbox\",\n \"radio\",\n \"switch\",\n \"tab\",\n \"menuitem\",\n \"menuitemcheckbox\",\n \"menuitemradio\",\n \"option\",\n \"treeitem\"\n ]);\n const typingRefusal = (element, explicit) => textEntry(element) ? void 0 : explicit ? `${describe(element)} is not a text field` : activationTarget(element) !== void 0 || isSelect(element) || activatingRoles.has(roleOf(element) ?? \"\") ? `focus is on ${describe(element)}, which typed text could activate or change; type into a text field by ref, or use press for keys` : void 0;\n const isSubmitter = (element) => isButton(element) && element.type === \"submit\" || isInput(element) && (element.type === \"submit\" || element.type === \"image\");\n const defaultSubmitter = (form) => {\n const root = form.getRootNode();\n return isRoot(root) ? Array.from(root.querySelectorAll(\"button,input\")).find((candidate) => isSubmitter(candidate) && candidate.form === form) : void 0;\n };\n const purpose = (control, form) => [\n control.getAttribute(\"id\"),\n control.getAttribute(\"name\"),\n control.getAttribute(\"inputmode\"),\n control.getAttribute(\"autocomplete\"),\n control.getAttribute(\"aria-label\"),\n form?.getAttribute(\"id\"),\n form?.getAttribute(\"name\"),\n form?.getAttribute(\"aria-label\")\n ];\n const boundUrl = (url) => {\n const hash = url.indexOf(\"#\");\n return hash === -1 || /^#[/!]/.test(url.slice(hash)) ? url : url.slice(0, hash);\n };\n const inspectInput = (element, plan) => {\n const metadata = details(element, element, 0, 0);\n const control = activationTarget(element) ?? element;\n const form = isInput(control) || isButton(control) || isTextArea(control) || isSelect(control) ? control.form : null;\n const key = plan.keys === null ? void 0 : /(?:^|\\+)(\\+|[^+]+)$/.exec(plan.keys)?.[1];\n const enter = key === \"Enter\";\n const activation = plan.action === \"click\" || plan.action === \"press\" && (enter || key === \"Space\");\n const fieldEnter = isInput(control) && ![\n \"button\",\n \"reset\",\n \"submit\",\n \"image\",\n \"file\",\n \"color\",\n \"hidden\"\n ].includes(control.type) && (plan.action === \"press\" && enter || plan.action === \"type\" && plan.submit);\n const submits = form !== null && (activation && isSubmitter(control) || fieldEnter);\n const submitter = isSubmitter(control) ? control : form === null ? void 0 : defaultSubmitter(form);\n const formValue = (attribute, property) => form === null ? void 0 : submitter?.hasAttribute(`form${attribute}`) === true ? submitter[property] : form[attribute];\n const formDestination = formValue(\"action\", \"formAction\");\n const formMethod = formValue(\"method\", \"formMethod\");\n const formTarget = formValue(\"target\", \"formTarget\");\n const link = linkOf(element);\n const href = link === void 0 ? null : hrefAttribute(link);\n const sends = submits && formMethod !== \"dialog\";\n const destination = sends ? formDestination : activation ? metadata.href : void 0;\n const acts = plan.action !== \"hover\" && plan.action !== \"scroll\";\n const builtIn = sends || href !== null && !/^\\s*(?:#\\s*|javascript:[^]*)$/i.test(href) || isInput(control) && ![\n \"button\",\n \"submit\",\n \"image\",\n \"reset\"\n ].includes(control.type) || (isInput(control) || isButton(control)) && control.type === \"reset\" && form !== null || control.tagName === \"SUMMARY\" || control.closest(\"select\") !== null || textEntry(control);\n const facts = [];\n if (sends) facts.push(\"form-submit\");\n if (activation && link?.hasAttribute(\"download\") === true) facts.push(\"download\");\n if (activation && isInput(control) && control.type === \"file\") facts.push(\"upload\");\n if (plan.action === \"type\" && isSecret(control) || sends && form !== null && Array.from(form.elements).some((field) => isField(field) && isSecret(field) && isFilled(field))) facts.push(\"secret\");\n if (activation && !builtIn) facts.push(\"scripted\");\n if (acts && (metadata.role === \"canvas\" || metadata.role === \"iframe\" || metadata.name === \"\")) facts.push(\"opaque\");\n const role = metadata.role;\n const boundName = role !== null && (interactiveRoles.has(role) || role === \"canvas\" || role === \"iframe\") && !(isHtml(element) && element.isContentEditable) ? metadata.name : null;\n const fingerprint = JSON.stringify([\n purpose(control, form),\n element.tagName,\n element.id,\n role,\n boundName,\n metadata.href,\n control === element ? null : refFor(control),\n isInput(control) || isButton(control) ? control.type : control.tagName,\n isDisabled(control),\n control.getAttribute(\"readonly\"),\n control.getAttribute(\"aria-readonly\"),\n isHtml(control) && control.isContentEditable,\n control.getAttribute(\"name\"),\n control.getAttribute(\"accept\"),\n control.hasAttribute(\"multiple\"),\n link?.getAttribute(\"download\"),\n form === null ? null : refFor(form),\n form === null ? null : boundUrl(form.action),\n form?.method,\n form?.target,\n submitter === void 0 ? null : refFor(submitter),\n formDestination === void 0 ? void 0 : boundUrl(formDestination),\n formMethod,\n formTarget,\n submitter?.formNoValidate,\n form?.noValidate\n ]);\n return {\n inspected: {\n ref: refFor(element),\n element: metadata.element,\n role: metadata.role,\n name: metadata.name,\n cursor: metadata.cursor,\n ...metadata.href === void 0 ? {} : { href: metadata.href },\n secret: isSecret(control),\n fingerprint\n },\n facts,\n destination,\n explain: () => evidenceOf(element, form, formMethod, formDestination)\n };\n };\n const inspect = (plan) => {\n const targets = [];\n const facts = /* @__PURE__ */ new Set();\n let destination = plan.destination ?? void 0;\n let explain = () => ({ title: clean(document.title, 120) });\n for (const [index, target] of plan.targets.entries()) {\n let element;\n if (target === null) element = activeElement();\n else if (typeof target === \"string\") {\n element = lookup(target);\n if (element === void 0) return {\n error: \"stale\",\n detail: target + \" is not on the page any more\",\n index\n };\n } else {\n if (!Number.isFinite(target.x) || !Number.isFinite(target.y) || target.x < 0 || target.y < 0 || target.x >= window.innerWidth || target.y >= window.innerHeight) return {\n error: \"outside\",\n detail: \"the point is outside the viewport\"\n };\n const hit = hitAt(document, target.x, target.y);\n element = hit === null ? null : controlOf(hit);\n if (element === null) return {\n error: \"offscreen\",\n detail: \"nothing is painted at the point\"\n };\n }\n if (element === null) {\n targets.push(null);\n continue;\n }\n if (!inCurrentDocument(element)) return {\n error: \"stale\",\n detail: \"the input target belongs to a replaced document\",\n index\n };\n const refusal = plan.action === \"type\" ? typingRefusal(element, target !== null) : void 0;\n if (refusal !== void 0) return {\n error: \"untypeable\",\n detail: refusal\n };\n const inspected = inspectInput(element, plan);\n if (index === 0) explain = inspected.explain;\n targets.push(inspected.inspected);\n for (const fact of inspected.facts) facts.add(fact);\n destination ??= inspected.destination;\n if (inspected.destination !== void 0) try {\n if (new URL(inspected.destination, location.href).origin !== location.origin) facts.add(\"cross-origin\");\n } catch {\n return {\n error: \"outside\",\n detail: \"the input destination is not a valid URL\"\n };\n }\n }\n if (destination !== void 0) try {\n destination = new URL(destination, location.href).href;\n if (new URL(destination).origin !== location.origin) facts.add(\"cross-origin\");\n } catch {\n return {\n error: \"outside\",\n detail: \"the input destination is not a valid URL\"\n };\n }\n return {\n url: boundUrl(location.href),\n targets,\n facts: [...facts],\n ...destination === void 0 ? {} : { destination },\n explain\n };\n };\n const prepareInput = (plan) => {\n const inspected = inspect(plan);\n if (\"error\" in inspected) return inspected;\n const { explain, ...prepared } = inspected;\n return {\n ...prepared,\n evidence: explain()\n };\n };\n const bindings = (targets) => targets.map((target) => target === null ? null : [target.ref, target.fingerprint]);\n const validate = (plan, prepared, options) => {\n const current = inspect(plan);\n if (\"error\" in current) return current.error === \"stale\" ? current : {\n error: \"changed\",\n detail: current.detail\n };\n if (current.url !== prepared.url || (current.destination === void 0 || prepared.destination === void 0 ? current.destination !== prepared.destination : boundUrl(current.destination) !== boundUrl(prepared.destination)) || JSON.stringify(current.facts) !== JSON.stringify(prepared.facts) || JSON.stringify(bindings(current.targets)) !== JSON.stringify(bindings(prepared.targets))) return {\n error: \"changed\",\n detail: \"the page or input target changed while the policy was deciding\"\n };\n if (options.focused === true) {\n const active = activeElement();\n const expected = prepared.targets[0];\n if (active === null || expected === null || expected === void 0 || refFor(active) !== expected.ref) return {\n error: \"changed\",\n detail: \"focus moved away from the approved element\"\n };\n }\n for (const press of options.presses ?? []) {\n const expected = prepared.targets[press.index];\n const element = expected === null || expected === void 0 ? void 0 : lookup(expected.ref);\n const hit = hitAt(document, press.x, press.y);\n if (element === void 0 || hit === null || !receives(element, hit)) return {\n error: \"changed\",\n detail: `the approved target is no longer under the pointer at (${press.x}, ${press.y})`\n };\n const nested = nestedControl(element, hit);\n if (nested !== void 0) return {\n error: \"changed\",\n detail: `${describe(nested)} inside the approved target would receive the press at (${press.x}, ${press.y})`\n };\n }\n return { ok: true };\n };\n const validateInput = (plan, prepared, options = {}) => {\n if ((options.presses ?? []).length === 0) return validate(plan, prepared, options);\n const { promise, resolve } = Promise.withResolvers();\n if (document.visibilityState === \"hidden\") resolve();\n else requestAnimationFrame(() => requestAnimationFrame(() => resolve()));\n return promise.then(() => validate(plan, prepared, options));\n };\n return {\n prepareInput,\n textEntry,\n typingRefusal,\n validateInput\n };\n };\n //#endregion\n //#region src/internal/input/targets.inpage.ts\n const targets = (names, walked, placing) => {\n const { describe, isDisabled, lookup, nameOf, parentOf, roleOf } = names;\n const { boxOf, controlOf, hitAt } = walked;\n const { contextOf } = placing;\n /** Whether `node` is `ancestor` or inside it, across shadow roots and same-origin frames. */\n const within = (ancestor, node) => {\n for (let current = node; current !== null;) {\n if (current === ancestor) return true;\n current = parentOf(current) ?? current.ownerDocument.defaultView?.frameElement ?? null;\n }\n return false;\n };\n const receives = (element, hit) => within(element, hit) || within(hit, element);\n const hrefAttribute = (element) => element.localName === \"a\" || element.localName === \"area\" ? element.getAttribute(\"href\") ?? element.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\") : null;\n const linkOf = (element) => {\n for (let node = element; node !== null; node = parentOf(node)) if (hrefAttribute(node) !== null) return node;\n };\n const details = (element, hit, x, y) => {\n const link = linkOf(element);\n let href;\n if (link !== void 0) try {\n href = new URL(hrefAttribute(link) ?? \"\", link.ownerDocument.baseURI).href;\n } catch {\n href = void 0;\n }\n const role = roleOf(element);\n const view = hit.ownerDocument.defaultView ?? window;\n return {\n x,\n y,\n element: describe(element),\n tag: element.tagName.toLowerCase(),\n role,\n name: nameOf(element, role),\n cursor: view.getComputedStyle(hit).cursor,\n ...href === void 0 ? {} : { href }\n };\n };\n const point = (target, scroll = true) => {\n if (typeof target !== \"string\") {\n const { x, y } = target;\n if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x >= window.innerWidth || y >= window.innerHeight) return {\n error: \"outside\",\n detail: `(${x}, ${y}) is outside the viewport`\n };\n const hit = hitAt(document, x, y);\n if (hit === null) return {\n error: \"offscreen\",\n detail: `nothing is painted at (${x}, ${y})`\n };\n const control = controlOf(hit);\n return {\n ...details(control, hit, x, y),\n context: contextOf(control),\n box: boxOf(control)\n };\n }\n const ref = target;\n const element = lookup(ref);\n if (element === void 0) return {\n error: \"stale\",\n detail: `${ref} is not on the page any more`\n };\n if (isDisabled(element)) return {\n error: \"disabled\",\n detail: `${ref} is disabled`\n };\n const rect = element.getBoundingClientRect();\n if (rect.width === 0 && rect.height === 0) return {\n error: \"hidden\",\n detail: `${ref} has no size on the page`\n };\n let box = {\n left: rect.left,\n top: rect.top,\n right: rect.right,\n bottom: rect.bottom\n };\n let visible = { ...box };\n let outside = false;\n for (let inner = element;;) {\n const view = inner.ownerDocument.defaultView ?? window;\n outside ||= box.left < 0 || box.top < 0 || box.right > view.innerWidth || box.bottom > view.innerHeight;\n visible = {\n left: Math.max(visible.left, 0),\n top: Math.max(visible.top, 0),\n right: Math.min(visible.right, view.innerWidth),\n bottom: Math.min(visible.bottom, view.innerHeight)\n };\n for (let ancestor = parentOf(inner); ancestor !== null; ancestor = parentOf(ancestor)) {\n const style = view.getComputedStyle(ancestor);\n const clip = ancestor.getBoundingClientRect();\n if (/(auto|scroll|hidden|clip)/.test(style.overflowX)) {\n visible.left = Math.max(visible.left, clip.left + ancestor.clientLeft);\n visible.right = Math.min(visible.right, clip.left + ancestor.clientLeft + ancestor.clientWidth);\n }\n if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {\n visible.top = Math.max(visible.top, clip.top + ancestor.clientTop);\n visible.bottom = Math.min(visible.bottom, clip.top + ancestor.clientTop + ancestor.clientHeight);\n }\n }\n const frame = view.frameElement;\n if (frame === null) break;\n const frameBox = frame.getBoundingClientRect();\n const dx = frameBox.left + frame.clientLeft;\n const dy = frameBox.top + frame.clientTop;\n box = {\n left: box.left + dx,\n top: box.top + dy,\n right: box.right + dx,\n bottom: box.bottom + dy\n };\n visible = {\n left: Math.max(visible.left + dx, dx),\n top: Math.max(visible.top + dy, dy),\n right: Math.min(visible.right + dx, dx + frame.clientWidth),\n bottom: Math.min(visible.bottom + dy, dy + frame.clientHeight)\n };\n inner = frame;\n }\n if (outside || visible.right <= visible.left || visible.bottom <= visible.top) {\n if (scroll) {\n element.scrollIntoView({\n block: \"center\",\n inline: \"center\",\n behavior: \"instant\"\n });\n return point(target, false);\n }\n return {\n error: \"offscreen\",\n detail: outside ? ref + \" is outside the viewport\" : `${ref} could not be scrolled into view`\n };\n }\n const x = (visible.left + visible.right) / 2;\n const y = (visible.top + visible.bottom) / 2;\n const hit = hitAt(document, x, y);\n if (hit !== null && !receives(element, hit)) return {\n error: \"covered\",\n detail: `${ref} is covered by ${describe(hit)}`\n };\n return {\n ...details(element, hit ?? element, Math.round(x), Math.round(y)),\n context: contextOf(element)\n };\n };\n const scrollPlan = (ref) => {\n const element = lookup(ref);\n if (element === void 0 || element.ownerDocument !== document) return null;\n const target = element.getBoundingClientRect();\n const centerX = (target.left + target.right) / 2;\n const centerY = (target.top + target.bottom) / 2;\n for (let ancestor = parentOf(element); ancestor !== null; ancestor = parentOf(ancestor)) {\n const style = window.getComputedStyle(ancestor);\n const horizontal = /^(auto|scroll)$/.test(style.overflowX) && ancestor.scrollWidth > ancestor.clientWidth;\n const vertical = /^(auto|scroll)$/.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight;\n if (!horizontal && !vertical) continue;\n const box = ancestor.getBoundingClientRect();\n const left = Math.max(0, box.left + ancestor.clientLeft);\n const top = Math.max(0, box.top + ancestor.clientTop);\n const right = Math.min(window.innerWidth, box.left + ancestor.clientLeft + ancestor.clientWidth);\n const bottom = Math.min(window.innerHeight, box.top + ancestor.clientTop + ancestor.clientHeight);\n if (right <= left || bottom <= top) continue;\n const x = (left + right) / 2;\n const y = (top + bottom) / 2;\n const dx = horizontal && (target.left < left || target.right > right) ? centerX - x : 0;\n const dy = vertical && (target.top < top || target.bottom > bottom) ? centerY - y : 0;\n if (dx === 0 && dy === 0) continue;\n const hit = hitAt(document, x, y);\n if (hit !== null && (hit === ancestor || ancestor.contains(hit))) return {\n x,\n y,\n dx,\n dy\n };\n }\n const dx = target.left < 0 || target.right > window.innerWidth ? centerX - window.innerWidth / 2 : 0;\n const dy = target.top < 0 || target.bottom > window.innerHeight ? centerY - window.innerHeight / 2 : 0;\n return dx === 0 && dy === 0 ? null : {\n x: window.innerWidth / 2,\n y: window.innerHeight / 2,\n dx,\n dy\n };\n };\n return {\n controlOf,\n details,\n hitAt,\n hrefAttribute,\n linkOf,\n point,\n receives,\n scrollPlan,\n within\n };\n };\n //#endregion\n //#region src/internal/reading/context.inpage.ts\n const context = (names, walked) => {\n const { clean, isButton, isDocument, isHtml, isInput, isRoot } = names;\n const { isSelect, isTextArea, roleOf, textOf } = names;\n const { visible } = walked;\n const known = () => ({\n headers: /* @__PURE__ */ new Map(),\n headings: /* @__PURE__ */ new Map()\n });\n const unspoken = \"button,select,textarea,option,script,style,noscript,template,[role=button],[role=menuitem],[role=option],[role=tab],[role=switch],[role=checkbox],[role=radio],[aria-hidden=true]\";\n const groups = \"tr,li,article,fieldset,form,section,dialog,[role=row],[role=listitem],[role=group],[role=region],[role=dialog],[role=alertdialog]\";\n /** The visible text just before (or after) a target within `scope`, nearest kept, ≤120 characters. */\n const textBeside = (target, scope, backwards) => {\n const walker = target.ownerDocument.createTreeWalker(scope, NodeFilter.SHOW_TEXT);\n const labels = isInput(target) || isTextArea(target) || isSelect(target) || isButton(target) ? Array.from(target.labels ?? []) : [];\n let text = \"\";\n walker.currentNode = target;\n for (let steps = 0; steps < 400 && text.replace(/\\s+/g, \"\").length < 120; steps++) {\n const node = backwards ? walker.previousNode() : walker.nextNode();\n if (node === null) break;\n const parent = node.parentElement;\n if (parent === null || target.contains(parent) || parent.closest(unspoken) !== null || isHtml(parent) && parent.isContentEditable || labels.some((label) => label.contains(parent)) || !visible(parent)) continue;\n text = backwards ? `${node.textContent ?? \"\"} ${text}` : `${text} ${node.textContent ?? \"\"}`;\n }\n const words = text.replace(/\\s+/g, \" \").trim();\n return words.length <= 120 ? words : backwards ? `…${words.slice(-119).trimStart()}` : `${words.slice(0, 119).trimEnd()}…`;\n };\n /** The nearest visible heading before `target` in tree order, within `scope`. */\n const headingBefore = (target, scope, read = known()) => {\n let headings = read.headings.get(scope);\n if (headings === void 0) {\n headings = Array.from(scope.querySelectorAll(\"h1,h2,h3,h4,h5,h6,[role=heading]\")).filter((element) => roleOf(element) === \"heading\");\n read.headings.set(scope, headings);\n }\n for (const heading of headings.toReversed()) {\n if ((heading.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING) === 0) continue;\n const text = visible(heading) ? clean(textOf(heading), 120) : \"\";\n if (text !== \"\") return text;\n }\n };\n /** Whether an element is pinned to the viewport, where the markup around it says nothing. */\n const pinned = (element) => {\n if (!isHtml(element)) return false;\n let top = element;\n while (top.offsetParent !== null && isHtml(top.offsetParent)) top = top.offsetParent;\n return top !== element.ownerDocument.body && top !== element.ownerDocument.documentElement && getComputedStyle(top).position === \"fixed\";\n };\n const span = (cell) => Math.max(1, Number(cell.getAttribute(\"colspan\")) || 1);\n const tables = \"table,[role=table],[role=grid],[role=treegrid]\";\n /** A cell's row and column names, or nothing when it is not in a table with either. */\n const tableContext = (cell, read) => {\n const row = cell.closest(\"tr,[role=row]\");\n const table = row?.closest(tables);\n if (row === null || row === void 0 || table === null || table === void 0) return {};\n let header = read.headers.get(table);\n if (header === void 0) {\n const first = table.querySelector(\"thead tr, tr:has(> th), [role=row]:has(> [role=columnheader])\");\n header = first?.closest(tables) === table ? first : null;\n read.headers.set(table, header);\n }\n if (row === header) return {};\n const cells = Array.from(row.children);\n const index = cells.indexOf(cell);\n const lettered = (other) => /\\p{L}/u.test(textOf(other));\n const named = cells.find((other) => other.matches(\"th,[role=rowheader]\") && lettered(other)) ?? cells.find((other) => other !== cell && lettered(other));\n let left = cells.slice(0, index).reduce((sum, other) => sum + span(other), 0);\n const over = index === -1 || header === null ? void 0 : Array.from(header.children).find((candidate) => (left -= span(candidate)) < 0);\n return {\n row: named === void 0 || named === cell ? void 0 : clean(textOf(named), 60) || void 0,\n column: over === void 0 ? void 0 : clean(textOf(over), 60) || void 0\n };\n };\n /** Where text around an element is read: its dialog, else its own tree, never across a shadow root. */\n const treeOf = (element) => {\n const root = element.getRootNode();\n return element.closest(\"dialog,[role=dialog],[role=alertdialog]\") ?? (isDocument(root) ? root.body ?? root : isRoot(root) ? root : element.ownerDocument);\n };\n /** The words around an element that say which one it is. */\n const contextOf = (element, read = known()) => {\n const cell = element.closest(\"td,th,[role=cell],[role=gridcell],[role=rowheader],[role=columnheader]\");\n const table = cell === null ? {} : tableContext(cell, read);\n const parent = element.parentElement;\n const scope = element.closest(groups) ?? (parent === null || parent === element.ownerDocument.body || parent.tagName === \"HTML\" ? void 0 : parent);\n const beside = table.row !== void 0 || table.column !== void 0 || scope === void 0 ? \"\" : textBeside(element, scope, true);\n const heading = pinned(element) ? void 0 : headingBefore(element, treeOf(element), read);\n return {\n ...table,\n label: beside.length > 40 ? `…${beside.slice(-39).trimStart()}` : beside || void 0,\n heading: heading === void 0 ? void 0 : clean(heading, 60)\n };\n };\n return {\n contextOf,\n groups,\n headingBefore,\n known,\n textBeside,\n treeOf\n };\n };\n //#endregion\n //#region src/internal/reading/controls.inpage.ts\n const controls = (names, subjects, texts) => {\n const { clean, isInput, isSelect, isTextArea, refFor, textEntry } = names;\n const { stateOf } = subjects;\n const { shown } = texts;\n const states = (element, role) => {\n const { level, ...flags } = stateOf(element, role);\n const held = Object.entries(flags).flatMap(([name, value]) => value === true ? [name] : []);\n return [...level === void 0 ? [] : [`level=${level}`], ...held].map((name) => ` [${name}]`).join(\"\");\n };\n const valueOf = (element) => {\n if (isSelect(element)) {\n const selected = Array.from(element.selectedOptions, (option) => clean(option.text, 40));\n const options = Array.from(element.options).slice(0, 12).map((option) => clean(option.text, 40));\n const more = element.options.length > 12 ? ` +${element.options.length - 12} more` : \"\";\n return ` value=${JSON.stringify(selected.join(\", \"))} options=${JSON.stringify(options.join(\" | \") + more)}`;\n }\n const value = isInput(element) || isTextArea(element) ? shown(element, true) : void 0;\n return value === void 0 || value === \"\" ? \"\" : ` value=${JSON.stringify(clean(value, 80))}`;\n };\n /** A control as a value, as its outline line shows it. */\n const controlOf = (element, role, kind, name) => {\n const { disabled, checked } = stateOf(element, role);\n const select = isSelect(element) ? element : void 0;\n const value = select !== void 0 ? Array.from(select.selectedOptions, (option) => clean(option.text, 80)).join(\", \") : isInput(element) || isTextArea(element) ? clean(shown(element, true), 200) : \"\";\n const editable = textEntry(element);\n return {\n ref: refFor(element),\n kind,\n name,\n value,\n ...select === void 0 ? {} : {\n options: Array.from(select.options).slice(0, 64).map((option) => clean(option.text, 80)),\n optionCount: select.options.length\n },\n ...disabled ? { disabled } : {},\n ...checked === void 0 ? {} : { checked },\n ...editable ? { editable } : {}\n };\n };\n /**\n * The elements a selector matches, each read whole, so one inside another that matched is left\n * to it; or why the selector is not CSS.\n */\n const rootsOf = (selector) => {\n let matched;\n try {\n matched = Array.from(document.querySelectorAll(selector));\n } catch {\n return { invalid: `${JSON.stringify(selector)} is not a CSS selector` };\n }\n return matched.filter((root) => !matched.some((other) => other !== root && other.contains(root)));\n };\n return {\n controlOf,\n rootsOf,\n states,\n valueOf\n };\n };\n //#endregion\n //#region src/internal/reading/expect.inpage.ts\n const expectations = (names, subjected, matching) => {\n const { isInput, isSelect, isTextArea, roleOf, textOf } = names;\n const { elementsOf, stateOf } = subjected;\n const markOf = (elements) => matching.mark(elements.map((element) => {\n const { focused: _focused, ...state } = stateOf(element, roleOf(element));\n const value = isInput(element) || isSelect(element) || isTextArea(element) ? element.value : \"\";\n return `${textOf(element)}\\u0000${value}\\u0000${JSON.stringify(state)}\\u0001`;\n }));\n /**\n * What `find` matches, looked at every 100 ms until `want` holds of it or `millis` have passed,\n * with its mark then. It gives no refs.\n */\n const until = async (request, want, millis) => {\n const deadline = performance.now() + millis;\n for (;;) {\n const elements = elementsOf(request);\n if (\"invalid\" in elements) return elements;\n const mark = markOf(elements);\n const met = want === \"some\" ? elements.length > 0 : want === \"none\" ? elements.length === 0 : mark !== want.other;\n const left = deadline - performance.now();\n if (met || left <= 0) return {\n met,\n mark\n };\n const { promise, resolve } = Promise.withResolvers();\n setTimeout(resolve, Math.min(100, left));\n await promise;\n }\n };\n return { until };\n };\n //#endregion\n //#region src/internal/reading/layout.inpage.ts\n const layout = (names, walked, subjected, matching, placing) => {\n const { isDisabled, isOwn, nameOf, refFor, roleOf, textOf } = names;\n const { boxOf, inView, visible } = walked;\n const most = 200;\n const area = (element) => {\n const { width, height } = element.getBoundingClientRect();\n return width * height;\n };\n const chosen = (elements, choose) => choose === \"first\" ? elements[0] : choose === \"last\" ? elements.at(-1) : elements.reduce((best, element) => best === void 0 || (choose === \"smallest\" ? area(element) < area(best) : area(element) > area(best)) ? element : best, void 0);\n const fixed = (element) => {\n for (let at = element; at !== null; at = at.parentElement) if (getComputedStyle(at).position === \"fixed\") return true;\n return false;\n };\n const words = (element, wanted, dx, dy) => {\n const parts = [];\n let text = \"\";\n const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_TEXT);\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n parts.push({\n node,\n start: text.length\n });\n text += node.nodeValue ?? \"\";\n }\n const pattern = typeof wanted === \"string\" ? new RegExp(wanted.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"), \"giu\") : new RegExp(wanted.source, wanted.flags.replace(/[gy]/g, \"\") + \"g\");\n const at = (index, end) => {\n const part = parts.findLast(({ start }) => end ? start < index : start <= index) ?? parts[0];\n return part === void 0 ? [element, 0] : [part.node, index - part.start];\n };\n const found = [];\n for (const match of text.matchAll(pattern)) {\n if (found.length === most) break;\n if (match[0] === \"\") continue;\n const range = element.ownerDocument.createRange();\n range.setStart(...at(match.index, false));\n range.setEnd(...at(match.index + match[0].length, true));\n const { x, y, width, height } = range.getBoundingClientRect();\n if (width > 0 || height > 0) found.push({\n text: match[0],\n box: {\n x: x + dx,\n y: y + dy,\n width,\n height\n }\n });\n }\n return found;\n };\n const selected = (pick) => {\n let elements;\n try {\n elements = Array.from(document.querySelectorAll(pick.selector));\n } catch {\n return { invalid: `${JSON.stringify(pick.selector)} is not a CSS selector` };\n }\n const rules = matching.compile(pick);\n return elements.filter((element) => {\n const role = roleOf(element, pick.role !== null);\n const box = boxOf(element);\n return !isOwn(element) && box.width * box.height > 0 && visible(element) && (pick.scope === \"document\" || inView(new DOMRect(box.x, box.y, box.width, box.height))) && (pick.state !== \"enabled\" || !isDisabled(element)) && rules({\n role,\n name: () => nameOf(element, role),\n text: () => textOf(element),\n context: () => placing.contextOf(element)\n });\n });\n };\n const read = (picks) => {\n const places = [];\n const missing = [];\n for (const pick of picks) {\n const elements = pick.selector === null ? subjected.elementsOf(pick) : selected({\n ...pick,\n selector: pick.selector\n });\n if (\"invalid\" in elements) return { invalid: `${pick.id}: ${elements.invalid}` };\n const element = chosen(elements, pick.choose);\n if (element === void 0) {\n missing.push(pick.id);\n continue;\n }\n const role = roleOf(element, pick.role !== null);\n const box = boxOf(element);\n const own = element.getBoundingClientRect();\n places.push({\n id: pick.id,\n ref: refFor(element),\n subject: {\n role,\n name: nameOf(element, role),\n tag: element.tagName.toLowerCase(),\n context: placing.contextOf(element)\n },\n box,\n fixed: fixed(element),\n words: pick.words === null ? void 0 : words(element, pick.words, box.x - own.x, box.y - own.y)\n });\n }\n return { layout: {\n url: location.href,\n viewport: {\n width: innerWidth,\n height: innerHeight\n },\n scroll: {\n x: scrollX,\n y: scrollY\n },\n scale: devicePixelRatio,\n places,\n missing\n } };\n };\n return { read };\n };\n //#endregion\n //#region src/internal/reading/names.inpage.ts\n const elements = () => {\n const isInput = (element) => element.tagName === \"INPUT\";\n const isTextArea = (element) => element.tagName === \"TEXTAREA\";\n const isSelect = (element) => element.tagName === \"SELECT\";\n const isFrame = (element) => element.tagName === \"IFRAME\";\n const isHtml = (element) => \"innerText\" in element;\n const isButton = (element) => element.tagName === \"BUTTON\";\n const isLabel = (element) => element.tagName === \"LABEL\";\n const textOf = (element) => isHtml(element) ? element.innerText : element.textContent ?? \"\";\n const isElement = (node) => node.nodeType === Node.ELEMENT_NODE;\n const isDocument = (node) => node.nodeType === Node.DOCUMENT_NODE;\n /** The native fields and editable regions that can receive typed text. */\n const textEntry = (element) => isInput(element) && ![\n \"button\",\n \"reset\",\n \"submit\",\n \"image\",\n \"checkbox\",\n \"radio\",\n \"file\",\n \"range\",\n \"color\",\n \"hidden\"\n ].includes(element.type) || isTextArea(element) || isHtml(element) && element.isContentEditable;\n const own = /* @__PURE__ */ new WeakSet();\n const adopt = (node) => own.add(node);\n /** Whether a node is the library's own, or inside a shadow root of one of its own. */\n const isOwn = (node) => {\n const root = node.getRootNode();\n return own.has(node) || root instanceof ShadowRoot && own.has(root.host);\n };\n const clean = (value, max = 160) => {\n const text = (value ?? \"\").replace(/\\s+/g, \" \").trim();\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n };\n return {\n adopt,\n clean,\n isInput,\n isTextArea,\n isSelect,\n isFrame,\n isHtml,\n isButton,\n isLabel,\n textOf,\n isElement,\n isDocument,\n isOwn,\n textEntry\n };\n };\n const names = (native) => {\n const { clean, isInput, isTextArea, isSelect, isFrame, textOf, isElement } = native;\n const byElement = /* @__PURE__ */ new WeakMap();\n const byRef = /* @__PURE__ */ new Map();\n const refs = { next: 1 };\n const interactiveRoles = new Set(\"button link checkbox radio tab menuitem menuitemcheckbox menuitemradio option switch slider combobox listbox textbox searchbox spinbutton treeitem\".split(\" \"));\n const containers = {\n HEADER: \"banner\",\n NAV: \"navigation\",\n MAIN: \"main\",\n ASIDE: \"complementary\",\n FOOTER: \"contentinfo\",\n FORM: \"form\",\n DIALOG: \"dialog\"\n };\n const valueRoles = new Set(\"combobox listbox option textbox searchbox spinbutton slider\".split(\" \"));\n /**\n * A label's own words, without the options or values of the controls inside it, native or\n * scripted, such as the custom select Browserbase puts in place of a native one.\n */\n const labelText = (label) => {\n let text = \"\";\n const collect = (node) => {\n for (const child of Array.from(node.childNodes)) if (child.nodeType === Node.TEXT_NODE) text += child.textContent ?? \"\";\n else if (isElement(child) && ![\n \"SELECT\",\n \"TEXTAREA\",\n \"INPUT\",\n \"SCRIPT\",\n \"STYLE\"\n ].includes(child.tagName) && !valueRoles.has(roleOf(child) ?? \"\")) collect(child);\n };\n collect(label);\n return text;\n };\n const roleOf = (element, structural = false) => {\n const explicit = element.getAttribute(\"role\");\n if (explicit !== null && explicit.trim() !== \"\") return explicit.trim().split(/\\s+/)[0] ?? null;\n const tag = element.tagName;\n if (tag === \"A\") return element.hasAttribute(\"href\") ? \"link\" : null;\n if (tag === \"BUTTON\" || tag === \"SUMMARY\") return \"button\";\n if (isSelect(element)) return element.multiple ? \"listbox\" : \"combobox\";\n if (tag === \"TEXTAREA\") return \"textbox\";\n if (isInput(element)) {\n const type = element.type;\n if (type === \"hidden\" || type === \"color\" || type === \"file\") return null;\n if (type === \"checkbox\" || type === \"radio\") return type;\n if (type === \"range\") return \"slider\";\n if (type === \"number\") return \"spinbutton\";\n if (type === \"search\") return \"searchbox\";\n if (type === \"button\" || type === \"submit\" || type === \"reset\" || type === \"image\") return \"button\";\n return \"textbox\";\n }\n if (/^H[1-6]$/.test(tag)) return \"heading\";\n if (tag === \"IMG\") return \"img\";\n if (tag === \"CANVAS\") return \"canvas\";\n if (tag === \"IFRAME\") return \"iframe\";\n if (element.getAttribute(\"contenteditable\") === \"true\") return \"textbox\";\n if (structural) {\n if (tag === \"TH\") return element.getAttribute(\"scope\") === \"row\" ? \"rowheader\" : \"columnheader\";\n const roles = {\n TABLE: \"table\",\n TR: \"row\",\n TD: \"cell\",\n TBODY: \"rowgroup\",\n THEAD: \"rowgroup\",\n TFOOT: \"rowgroup\",\n UL: \"list\",\n OL: \"list\",\n MENU: \"list\",\n LI: \"listitem\"\n };\n if (roles[tag] !== void 0) return roles[tag];\n }\n return containers[tag] ?? null;\n };\n const nameOf = (element, role) => {\n const labelledBy = element.getAttribute(\"aria-labelledby\");\n if (labelledBy !== null) {\n const text = labelledBy.split(/\\s+/).map((id) => {\n const labelling = element.ownerDocument.getElementById(id);\n return labelling === null ? \"\" : labelText(labelling);\n }).join(\" \");\n if (clean(text) !== \"\") return clean(text);\n }\n const label = element.getAttribute(\"aria-label\");\n if (label !== null && clean(label) !== \"\") return clean(label);\n if (isInput(element) || isTextArea(element) || isSelect(element)) {\n const labels = element.labels === null ? \"\" : Array.from(element.labels, labelText).join(\" \");\n if (clean(labels) !== \"\") return clean(labels);\n if (isInput(element) && (element.type === \"button\" || element.type === \"submit\" || element.type === \"reset\")) return clean(element.value);\n return clean(element.getAttribute(\"placeholder\") ?? element.getAttribute(\"title\") ?? element.getAttribute(\"name\"));\n }\n if (role === \"img\") return clean(element.getAttribute(\"alt\") ?? element.getAttribute(\"title\"));\n if (role === \"iframe\") return clean(element.getAttribute(\"title\") ?? element.getAttribute(\"name\"));\n if (role === null || interactiveRoles.has(role) || role === \"heading\") {\n const text = isSecret(element) ? \"\" : clean(textOf(element), 120);\n if (text !== \"\") return text;\n const titled = element.querySelector(\"[title],img[alt],svg title\");\n const fallback = titled === null ? null : titled.tagName === \"IMG\" ? titled.getAttribute(\"alt\") : titled.tagName.toLowerCase() === \"title\" ? titled.textContent : titled.getAttribute(\"title\");\n return clean(element.getAttribute(\"title\") ?? fallback);\n }\n return \"\";\n };\n const isDisabled = (element) => element.matches(\":disabled\") || element.getAttribute(\"aria-disabled\") === \"true\";\n const refFor = (element) => {\n const known = byElement.get(element);\n if (known !== void 0 && byRef.get(known)?.deref() === element) return known;\n const ref = `e${refs.next++}`;\n byElement.set(element, ref);\n byRef.set(ref, new WeakRef(element));\n return ref;\n };\n const lookup = (ref) => {\n const element = byRef.get(ref)?.deref();\n return element !== void 0 && element.isConnected && inCurrentDocument(element) ? element : void 0;\n };\n const describe = (element) => {\n const id = element.id === \"\" ? \"\" : `#${element.id}`;\n const name = clean(nameOf(element, roleOf(element)), 40);\n return `<${element.tagName.toLowerCase()}${id}>${name === \"\" ? \"\" : ` \"${name}\"`}`;\n };\n const isRoot = (node) => node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n const parentOf = (element) => {\n const root = element.getRootNode();\n return element.parentElement ?? (isRoot(root) && \"host\" in root ? root.host : null);\n };\n const activeElement = () => {\n let active = document.activeElement;\n while (active !== null) {\n const inner = active.shadowRoot?.activeElement ?? (isFrame(active) ? active.contentDocument?.activeElement : null);\n if (inner === null || inner === void 0 || inner === active) return active;\n active = inner;\n }\n return null;\n };\n const inCurrentDocument = (element) => {\n let owner = element.ownerDocument;\n while (owner !== document) {\n const frame = owner.defaultView?.frameElement;\n if (frame === null || frame === void 0 || !frame.isConnected || isFrame(frame) && frame.contentDocument !== owner) return false;\n owner = frame.ownerDocument;\n }\n return true;\n };\n const secretToken = /(?:^|\\s)(?:current-password|new-password|one-time-code|cc-number|cc-csc|cc-exp(?:-month|-year)?)(?=\\s|$)/i;\n const secrets = /* @__PURE__ */ new WeakSet();\n /**\n * A field the DOM marks as secret, now or before: by its type, its autocomplete tokens, or a\n * style that shows dots for what it holds, as a PIN field may.\n */\n const isSecret = (element) => {\n if (isInput(element) && element.type === \"password\" || secretToken.test(element.getAttribute(\"autocomplete\") ?? \"\") || (isInput(element) || isTextArea(element)) && !/^(none)?$/.test(getComputedStyle(element).getPropertyValue(\"-webkit-text-security\"))) secrets.add(element);\n return secrets.has(element);\n };\n return {\n ...native,\n activeElement,\n containers,\n describe,\n inCurrentDocument,\n interactiveRoles,\n isDisabled,\n isRoot,\n isSecret,\n lookup,\n nameOf,\n parentOf,\n refFor,\n refs,\n roleOf\n };\n };\n //#endregion\n //#region src/internal/reading/outline.inpage.ts\n const outline = (names, walked, subjects, texts, controlling, url) => {\n const { clean, containers, isFrame, nameOf, refFor, roleOf, textOf } = names;\n const { visit } = walked;\n const { isControl } = subjects;\n const { cut } = texts;\n const textBlocks = /^(?:P|LI|TD|TH|DT|DD|LABEL|SPAN|BLOCKQUOTE|FIGCAPTION|CAPTION|PRE|STRONG|EM|B|I|SMALL|TIME|CODE|LEGEND)$/;\n const nested = \"a[href],button,input,select,textarea,summary,[role],[onclick],[tabindex],[contenteditable],canvas,iframe\";\n const noise = /^[\\s|•·\\-–—,.:;()[\\]{}\"'/\\\\]*$/;\n /** Text inside a control's label is already that control's name. */\n const inControlLabel = (element) => {\n const label = element.closest(\"label\");\n return label !== null && label.control !== null;\n };\n const hrefOf = (element) => {\n if (element.tagName !== \"A\") return \"\";\n const raw = element.getAttribute(\"href\") ?? \"\";\n if (raw === \"\" || raw.startsWith(\"javascript:\")) return \"\";\n try {\n const { origin, href } = new URL(raw, element.ownerDocument.baseURI);\n const reported = url.redact(href);\n const own = origin === location.origin && reported.startsWith(origin);\n return ` -> ${clean(own ? reported.slice(origin.length) : reported, 80)}`;\n } catch {\n return \"\";\n }\n };\n const snapshot = (request) => {\n const roots = request.within === null ? [null] : controlling.rootsOf(request.within);\n if (\"invalid\" in roots) return roots;\n const width = window.innerWidth;\n const height = window.innerHeight;\n const query = request.query === null ? null : request.query.toLowerCase();\n const lines = [];\n const controls = [];\n let above = 0;\n let below = 0;\n const placement = (rect) => {\n if (request.full) return \"in\";\n if (rect.bottom <= 0) return \"above\";\n if (rect.top >= height) return \"below\";\n if (rect.right <= 0 || rect.left >= width) return \"aside\";\n return \"in\";\n };\n const count = (rect) => {\n const where = placement(rect);\n if (where === \"above\") above++;\n if (where === \"below\") below++;\n return where;\n };\n const emit = (depth, line, rect) => {\n if (count(rect) !== \"in\") return false;\n if (query !== null && !line.toLowerCase().includes(query)) return false;\n lines.push(`${\" \".repeat(Math.min(depth, 8))}- ${line}`);\n return true;\n };\n const control = (element, rect, role, depth) => {\n const name = nameOf(element, role);\n const kind = role ?? \"clickable\";\n const box = request.boxes || role === \"canvas\" || role === \"iframe\" ? ` ${Math.round(rect.width)}x${Math.round(rect.height)} at (${Math.round(rect.x)},${Math.round(rect.y)})` : \"\";\n const line = placement(rect) === \"in\" ? `${kind}${name === \"\" ? \"\" : ` ${JSON.stringify(name)}`} [ref=${refFor(element)}]${controlling.states(element, role)}${controlling.valueOf(element)}${hrefOf(element)}${box}` : kind;\n if (emit(depth, line, rect)) controls.push(controlling.controlOf(element, role, kind, name));\n if (isFrame(element)) {\n const body = element.contentDocument?.body;\n if ((body === null || body === void 0) && placement(rect) === \"in\") lines.push(`${\" \".repeat(Math.min(depth + 1, 8))}- (another site's frame: use a screenshot and coordinates)`);\n return {\n depth: depth + 1,\n insidePointer: false,\n controls: false\n };\n }\n if ([\n \"INPUT\",\n \"SELECT\",\n \"TEXTAREA\",\n \"CANVAS\",\n \"IMG\"\n ].includes(element.tagName)) return void 0;\n return {\n depth: depth + 1,\n insidePointer: true,\n controls: true\n };\n };\n const enter = (element, style, rect, { depth, insidePointer }) => {\n const role = roleOf(element);\n if (isControl(element, role, style, rect, insidePointer)) return control(element, rect, role, depth);\n if (role === \"heading\") {\n emit(depth, `heading ${JSON.stringify(nameOf(element, role))}${controlling.states(element, role)}`, rect);\n return;\n }\n if (role === \"img\") {\n const alt = nameOf(element, role);\n if (alt !== \"\") emit(depth, `img ${JSON.stringify(alt)}`, rect);\n return;\n }\n let inner = depth;\n if (role !== null && (containers[element.tagName] !== void 0 || role === \"dialog\")) {\n const label = element.getAttribute(\"aria-label\");\n if (emit(depth, `${role}${label === null ? \"\" : ` ${JSON.stringify(clean(label))}`}:`, rect)) inner = depth + 1;\n }\n if (textBlocks.test(element.tagName) && element.querySelector(nested) === null) {\n if (inControlLabel(element)) return void 0;\n const text = clean(textOf(element), 300);\n if (text !== \"\" && !noise.test(text)) emit(inner, `text: ${text}`, rect);\n return;\n }\n let own = \"\";\n for (const node of Array.from(element.childNodes)) if (node.nodeType === Node.TEXT_NODE) own += node.textContent ?? \"\";\n own = clean(own, 300);\n if (own !== \"\" && !noise.test(own) && !inControlLabel(element)) emit(inner, `text: ${own}`, rect);\n return {\n depth: inner,\n insidePointer: insidePointer || style.cursor === \"pointer\",\n controls: false\n };\n };\n const visitor = {\n enter,\n admit: (child, place) => !place.controls || child.matches(nested) || child.querySelector(nested) !== null,\n outside: count\n };\n for (const root of roots) visit(root, !request.full, {\n depth: 0,\n insidePointer: false,\n controls: false\n }, visitor);\n const outlined = cut(lines.join(\"\\n\"), request.maxChars);\n return { snapshot: {\n ...outlined,\n url: location.href,\n title: document.title,\n above,\n below,\n viewport: {\n width,\n height\n },\n scroll: {\n y: Math.round(window.scrollY),\n height: Math.round(document.documentElement.scrollHeight)\n },\n controls: controls.filter((control) => outlined.text.includes(`[ref=${control.ref}]`))\n } };\n };\n const viewport = () => ({\n width: window.innerWidth,\n height: window.innerHeight\n });\n return {\n snapshot,\n viewport\n };\n };\n //#endregion\n //#region src/internal/reading/ready.inpage.ts\n const ready = (walked, texts, kept) => {\n const { inView, visible } = walked;\n let copy;\n const boxed = (element) => {\n const rect = element.getBoundingClientRect();\n return rect.width * rect.height > 0 && inView(rect);\n };\n const showing = (elements) => Array.from(elements).filter((element) => boxed(element) && visible(element));\n const drawn = (canvas) => {\n copy ??= new OffscreenCanvas(32, 32).getContext(\"2d\", { willReadFrequently: true });\n if (copy === null) return true;\n try {\n copy.clearRect(0, 0, 32, 32);\n copy.imageSmoothingQuality = \"high\";\n copy.drawImage(canvas, 0, 0, 32, 32);\n return new Uint32Array(copy.getImageData(0, 0, 32, 32).data.buffer).some((pixel) => pixel !== 0);\n } catch {\n return true;\n }\n };\n const content = () => showing(document.querySelectorAll(\"video, iframe, embed, object\")).length > 0 || showing(document.querySelectorAll(\"img, svg\")).some((picture) => {\n const { width, height } = picture.getBoundingClientRect();\n return width > 64 && height > 64;\n }) || (texts.read({\n ref: null,\n maxChars: 1,\n unmask: false\n })?.text ?? \"\") !== \"\" || showing(document.querySelectorAll(\"canvas\")).some(drawn);\n const painted = () => {\n const { promise, resolve } = Promise.withResolvers();\n if (document.visibilityState === \"hidden\") resolve(false);\n else requestAnimationFrame(() => resolve(true));\n return promise;\n };\n const check = (quietMillis, clock) => painted().then((paints) => {\n const waiting = [];\n const held = clock !== null && !document.dispatchEvent(new CustomEvent(clock, {\n detail: { op: \"holds\" },\n cancelable: true\n }));\n if (document.readyState === \"loading\") waiting.push(\"load\");\n if (!paints) waiting.push(\"paint\");\n if (document.getAnimations().some((animation) => {\n const effect = animation.effect;\n return (animation.playState === \"running\" || held && animation.playState === \"paused\") && effect !== null && Number.isFinite(effect.getComputedTiming().endTime) && \"target\" in effect && effect.target instanceof Element && boxed(effect.target);\n })) waiting.push(\"animations\");\n if (Array.from(document.images).some((image) => !image.complete && boxed(image))) waiting.push(\"images\");\n if (document.fonts.status !== \"loaded\") waiting.push(\"fonts\");\n if (showing(document.querySelectorAll(\"[aria-busy=true]\")).length > 0) waiting.push(\"busy\");\n if (!content()) waiting.push(\"content\");\n if (kept.changing() > performance.timeOrigin + performance.now() - quietMillis) waiting.push(\"changing\");\n return waiting;\n });\n /**\n * Check until the page is ready, or for `millis`, and say what it is still waiting for; with\n * `quietMillis`, until nothing the record saw in view has changed for that long, too.\n */\n const wait = async (millis, quietMillis = 0, clock = null) => {\n const until = performance.now() + millis;\n for (;;) {\n const waiting = await check(quietMillis, clock);\n if (waiting.length === 0 || performance.now() >= until) return waiting;\n const { promise, resolve } = Promise.withResolvers();\n setTimeout(resolve, Math.min(50, until - performance.now()));\n await promise;\n }\n };\n /**\n * One task, then a frame: what the page's handlers for input did at once has run, a navigation\n * one of them started in a timer has been asked for, and their effect has painted. Says whether\n * the page painted, which a hidden one does not.\n */\n const settle = () => {\n const { promise, resolve } = Promise.withResolvers();\n setTimeout(resolve, 0);\n return promise.then(painted);\n };\n return {\n wait,\n settle\n };\n };\n //#endregion\n //#region src/internal/reading/subjects.inpage.ts\n const states = (names) => (element, role) => {\n const { isDisabled, isInput } = names;\n const given = (attribute) => {\n const value = element.getAttribute(attribute);\n return value === \"true\" || (value === \"false\" ? false : void 0);\n };\n const checkable = element.hasAttribute(\"aria-checked\") || [\n \"checkbox\",\n \"radio\",\n \"switch\",\n \"menuitemcheckbox\",\n \"menuitemradio\"\n ].includes(role ?? \"\");\n return {\n disabled: isDisabled(element),\n checked: checkable ? isInput(element) && element.checked || element.getAttribute(\"aria-checked\") === \"true\" : void 0,\n expanded: given(\"aria-expanded\"),\n selected: given(\"aria-selected\"),\n pressed: given(\"aria-pressed\"),\n focused: element.ownerDocument.activeElement === element,\n level: role === \"heading\" ? Number(element.getAttribute(\"aria-level\")) || Number(/^H([1-6])$/.exec(element.tagName)?.[1]) || 2 : void 0\n };\n };\n const subjects = (names, walked, matching, placing, stateOf) => {\n const { isDisabled, nameOf, refFor, roleOf, textOf } = names;\n const { acts, boxOf, controlOf, hitAt, inView } = walked;\n const { contextOf, known } = placing;\n /** What the outline lists as a control, with a ref: something a person would act on. */\n const isControl = (element, role, style, rect, insidePointer) => acts(element, role) || style.cursor === \"pointer\" && !insidePointer && rect.width > 0 && rect.height > 0;\n /**\n * The elements in scope that match a query, in tree order. Without text, an element matches\n * when it has a role or is a control. With text, any element can, but text inside a control or\n * heading is that control's or heading's, and an element is left out when one inside it\n * matches too: the smallest element showing the text is found, not each one around it.\n */\n const matched = (request) => {\n const { at } = request;\n const matches = matching.compile(request);\n const byText = request.text !== null;\n const viewport = request.scope === \"viewport\";\n const read = known();\n if (request.selector !== null) try {\n document.querySelector(request.selector);\n } catch {\n return { invalid: `${JSON.stringify(request.selector)} is not a CSS selector` };\n }\n const eligible = (element) => (request.selector === null || element.matches(request.selector)) && (request.state !== \"enabled\" || !isDisabled(element));\n const entries = [];\n const open = [];\n const named = (entry) => entry.name ??= nameOf(entry.element, entry.role);\n const placed = (entry) => entry.context ??= contextOf(entry.element, read);\n const judge = (entry, text) => matches({\n role: entry.role,\n name: () => named(entry),\n text,\n context: () => placed(entry)\n });\n const hit = at === null ? null : hitAt(document, at.x, at.y);\n if (hit !== null) {\n const element = controlOf(hit);\n const { x, y, width, height } = boxOf(element);\n const entry = {\n element,\n rect: new DOMRect(x, y, width, height),\n role: roleOf(element, request.role !== null),\n matched: false\n };\n entry.matched = eligible(element) && judge(entry, () => textOf(element));\n entries.push(entry);\n }\n if (at === null) walked.visit(null, viewport, {\n pointer: false,\n owned: false\n }, {\n enter: (element, style, rect, state) => {\n const role = roleOf(element, request.role !== null);\n const control = isControl(element, role, style, rect, state.pointer);\n const unit = control || role === \"heading\";\n const entry = eligible(element) && (byText ? unit || !state.owned : request.selector !== null || role !== null || control) && (!viewport || inView(rect)) ? {\n element,\n rect,\n role,\n matched: false\n } : void 0;\n if (entry !== void 0) entries.push(entry);\n open.push({\n entry,\n inline: style.display === \"inline\",\n parts: [],\n inside: false\n });\n return {\n pointer: state.pointer || style.cursor === \"pointer\",\n owned: state.owned || unit\n };\n },\n text: byText ? (node) => open.at(-1)?.parts.push(node.textContent ?? \"\") : void 0,\n leave: () => {\n const closed = open.pop();\n const parent = open.at(-1);\n if (closed === void 0) return;\n const { entry } = closed;\n const text = closed.parts.join(\"\");\n if (parent !== void 0) parent.parts.push(closed.inline ? text : ` ${text} `);\n if (entry !== void 0 && !(byText && closed.inside)) entry.matched = judge(entry, () => text);\n if (parent !== void 0) parent.inside ||= closed.inside || entry?.matched === true;\n }\n });\n return {\n entries: entries.filter((entry) => entry.matched),\n named,\n placed\n };\n };\n const find = (request) => {\n const result = matched(request);\n if (result.invalid !== void 0) return { invalid: result.invalid };\n const { entries, named, placed } = result;\n return { found: entries.map((entry) => ({\n ref: refFor(entry.element),\n subject: {\n role: entry.role,\n name: named(entry),\n tag: entry.element.tagName.toLowerCase(),\n context: placed(entry)\n },\n box: {\n x: Math.round(entry.rect.x),\n y: Math.round(entry.rect.y),\n width: Math.round(entry.rect.width),\n height: Math.round(entry.rect.height)\n },\n inViewport: inView(entry.rect),\n state: stateOf(entry.element, entry.role)\n })) };\n };\n /** The elements `find` would find, in tree order, with no refs given. */\n const elementsOf = (request) => {\n const result = matched(request);\n return result.invalid !== void 0 ? { invalid: result.invalid } : result.entries.map((entry) => entry.element);\n };\n return {\n find,\n elementsOf,\n isControl,\n stateOf\n };\n };\n //#endregion\n //#region src/internal/reading/text.inpage.ts\n const text = (names, walked) => {\n const { isHtml, isInput, isSecret, isSelect, isTextArea, lookup } = names;\n const valueless = [\n \"checkbox\",\n \"radio\",\n \"button\",\n \"submit\",\n \"reset\",\n \"image\",\n \"file\"\n ];\n /** What a field holds, or undefined for an element that holds nothing entered. */\n const valueOf = (element) => {\n if (isInput(element)) return valueless.includes(element.type) ? void 0 : element.value;\n if (isTextArea(element)) return element.value;\n if (isSelect(element)) return Array.from(element.selectedOptions, (option) => option.text).join(\", \");\n const parent = element.parentElement;\n return isHtml(element) && element.isContentEditable && !(parent !== null && isHtml(parent) && parent.isContentEditable) ? element.innerText : void 0;\n };\n /** What a field shows: `••••` unless `unmask`, and always for a secret field; \"\" when empty. */\n const shown = (element, unmask) => {\n const value = valueOf(element);\n if (value === void 0 || value.trim() === \"\") return value === void 0 ? void 0 : \"\";\n return unmask && !isSecret(element) ? value : \"••••\";\n };\n /** Lines cut after the last whole line within `max` characters, or at `max` when none is. */\n const cut = (lines, max) => {\n if (lines.length <= max) return {\n text: lines,\n truncated: false\n };\n const end = lines.lastIndexOf(\"\\n\", max);\n return {\n text: lines.slice(0, end > 0 ? end : max),\n truncated: true\n };\n };\n /**\n * What the viewport, or one element whole, shows as text: a line per block, table cells apart by\n * a tab, and each field as `shown` gives it.\n */\n const lines = (root, unmask) => {\n const lines = [];\n let line = \"\";\n const end = () => {\n const words = line.replace(/[^\\S\\t]+/g, \" \").replace(/ ?\\t ?/g, \" \").trim();\n if (words !== \"\") lines.push(words);\n line = \"\";\n };\n walked.visit(root, root === null, false, {\n enter: (element, style) => {\n const { display } = style;\n const value = shown(element, unmask);\n const block = !display.startsWith(\"inline\") && display !== \"contents\" && display !== \"table-cell\";\n if (display === \"table-cell\") line += \" \";\n if (block || element.tagName === \"BR\") end();\n if (value === void 0 && !(isInput(element) && valueless.includes(element.type))) return block;\n const label = isInput(element) && /^(button|submit|reset)$/.test(element.type);\n line += ` ${value ?? (label ? element.value : \"\")} `;\n if (block) end();\n },\n text: (node) => {\n line += node.textContent ?? \"\";\n },\n leave: (_, block) => {\n if (block) end();\n }\n });\n end();\n return lines.join(\"\\n\");\n };\n const read = (request) => {\n const root = request.ref === null ? null : lookup(request.ref);\n return root === void 0 ? null : {\n ...cut(lines(root, request.unmask), request.maxChars),\n url: location.href,\n title: document.title\n };\n };\n return {\n cut,\n lines,\n read,\n shown\n };\n };\n //#endregion\n //#region src/internal/reading/walk.inpage.ts\n const walk = (names) => {\n const { interactiveRoles, isElement, isFrame, isInput, parentOf, roleOf } = names;\n const skipped = new Set(\"SCRIPT STYLE NOSCRIPT TEMPLATE HEAD META LINK SVG\".split(\" \"));\n /** Whether a box, in top-document pixels, meets the viewport. */\n const inView = (rect, width = innerWidth, height = innerHeight) => rect.right > 0 && rect.bottom > 0 && rect.left < width && rect.top < height;\n /** Whether an element reached on its own shows, by the walk's rule and its ancestors'. */\n const visible = (element) => {\n if (element.closest(\"[aria-hidden=true]\") !== null) return false;\n if (element.checkVisibility({\n opacityProperty: true,\n visibilityProperty: true\n })) return true;\n if (getComputedStyle(element).display !== \"contents\") return false;\n for (let node = element; node !== null; node = parentOf(node)) {\n const style = getComputedStyle(node);\n if (style.display === \"none\" || style.opacity === \"0\" || node === element && style.visibility !== \"visible\") return false;\n }\n return true;\n };\n const untransformed = (frame, rect) => {\n if (rect.width !== frame.offsetWidth || rect.height !== frame.offsetHeight) return false;\n let ancestor = frame;\n while (ancestor !== null) {\n const style = (ancestor.ownerDocument.defaultView ?? window).getComputedStyle(ancestor);\n if (style.transform !== \"none\" || style.scale !== \"none\" || style.rotate !== \"none\" || style.perspective !== \"none\" || style.zoom !== \"1\") return false;\n ancestor = parentOf(ancestor);\n }\n return true;\n };\n /** The element painted at a point, inside shadow roots and same-origin frames. */\n const hitAt = (root, x, y) => {\n let hit = root.elementFromPoint(x, y);\n while (hit?.shadowRoot !== null && hit?.shadowRoot !== void 0) {\n const inner = hit.shadowRoot.elementFromPoint(x, y);\n if (inner === null || inner === hit) break;\n hit = inner;\n }\n if (hit !== null && isFrame(hit)) {\n const document = hit.contentDocument;\n if (document !== null) {\n const rect = hit.getBoundingClientRect();\n if (untransformed(hit, rect)) return hitAt(document, x - rect.left - hit.clientLeft, y - rect.top - hit.clientTop) ?? hit;\n }\n }\n return hit;\n };\n /** Whether its role or a click handler makes an element a control. */\n const acts = (element, role) => isInput(element) && element.type !== \"hidden\" || role !== null && (interactiveRoles.has(role) || role === \"canvas\" || role === \"iframe\") || element.hasAttribute(\"onclick\");\n const controlOf = (hit) => {\n let element = hit;\n while (element !== null) {\n if (acts(element, roleOf(element))) return element;\n element = parentOf(element);\n }\n return hit;\n };\n /** An element's box in top-document viewport pixels, through the frames around it. */\n const boxOf = (element) => {\n const { x, y, width, height } = element.getBoundingClientRect();\n const frame = element.ownerDocument.defaultView?.frameElement ?? null;\n if (frame === null) return {\n x,\n y,\n width,\n height\n };\n const outer = boxOf(frame);\n return {\n x: x + outer.x + frame.clientLeft,\n y: y + outer.y + frame.clientTop,\n width,\n height\n };\n };\n /** What is painted where pinned things sit, what is pinned in view, and every element holding it. */\n const painted = (width, height) => {\n const keep = /* @__PURE__ */ new Set();\n const hold = (element) => {\n for (let node = element; node !== null && !keep.has(node); node = parentOf(node) ?? node.ownerDocument.defaultView?.frameElement ?? null) keep.add(node);\n };\n for (const y of [\n 8,\n 48,\n height / 2,\n height - 48,\n height - 8\n ]) for (const x of [\n 8,\n 48,\n width / 4,\n width / 2,\n width * 3 / 4,\n width - 48,\n width - 8\n ]) if (x >= 0 && y >= 0 && x < width && y < height) {\n hold(hitAt(document, x, y));\n for (const beneath of document.elementsFromPoint(x, y)) hold(beneath);\n }\n for (const element of Array.from(document.querySelectorAll(\":modal, :popover-open\"))) hold(element);\n for (const element of Array.from(document.querySelectorAll(\"[style*=\\\"fixed\\\" i]\"))) if (inView(element.getBoundingClientRect(), width, height)) hold(element);\n return keep;\n };\n /**\n * Visit `root` and what it holds, or the whole document when `root` is null. With `viewport`,\n * a subtree outside the viewport is skipped, as described above.\n */\n const visit = (root, viewport, state, visitor) => {\n const { innerWidth: width, innerHeight: height } = window;\n let keep;\n const children = (parent, inner, dx, dy) => {\n const nodes = visitor.text === void 0 ? parent.children : parent.childNodes;\n for (const node of Array.from(nodes)) if (node.nodeType === Node.TEXT_NODE) visitor.text?.(node, inner);\n else if (isElement(node) && (visitor.admit === void 0 || visitor.admit(node, inner))) one(node, inner, dx, dy);\n };\n const one = (element, outer, dx, dy) => {\n if (skipped.has(element.tagName.toUpperCase())) return;\n const local = element.getBoundingClientRect();\n const rect = new DOMRect(local.x + dx, local.y + dy, local.width, local.height);\n if (viewport && local.width > 0 && local.height > 0 && !inView(rect, width, height) && !(keep ??= painted(width, height)).has(element)) {\n visitor.outside?.(rect);\n return;\n }\n const style = getComputedStyle(element);\n if (style.display === \"none\" || style.opacity === \"0\" || element.getAttribute(\"aria-hidden\") === \"true\") return;\n if (!visible(element)) {\n for (const child of Array.from(element.children)) one(child, outer, dx, dy);\n return;\n }\n const inner = visitor.enter(element, style, rect, outer);\n if (inner === void 0) return;\n if (isFrame(element)) {\n const body = element.contentDocument?.body;\n if (body !== null && body !== void 0) children(body, inner, rect.x, rect.y);\n } else {\n if (element.shadowRoot !== null) children(element.shadowRoot, inner, dx, dy);\n children(element, inner, dx, dy);\n }\n visitor.leave?.(element, inner);\n };\n if (root === null) children(document, state, 0, 0);\n else one(root, state, 0, 0);\n };\n return {\n acts,\n boxOf,\n controlOf,\n hitAt,\n inView,\n visible,\n visit\n };\n };\n //#endregion\n //#region src/internal/timeline/changes.inpage.ts\n const changes = (names, walked, placing, kept, seeing, marking, recorder) => {\n const { clean, isInput, roleOf, nameOf } = names;\n const groups = \"tr,[role=row],form,dialog,[role=dialog],[role=alertdialog]\";\n /** Whether `element` lies in what an input on `target` acted on, its group, or what it controls. */\n const local = (target, element) => {\n const controls = target.closest(\"[aria-controls]\")?.getAttribute(\"aria-controls\") ?? \"\";\n const group = target.closest(groups);\n return target.contains(element) || group?.contains(element) === true || controls.split(/\\s+/).some((id) => id !== \"\" && document.getElementById(id)?.contains(element) === true);\n };\n /** What an element sits in, or sat in as it went. */\n const parentOf = (key) => key instanceof Element ? key.isConnected ? key.parentElement : marking.placeOf(key) ?? null : null;\n const fluxMillis = 1e4;\n const stillMillis = 2e3;\n /**\n * Each input a change may follow, with what the page did before it: what changed in the 10 s\n * before, the parents that gained or lost a child then, and whether nothing changed, and nothing\n * was let go, in the 2 s before. What holds the input's target, as a menu holds its item, came\n * with it, so it counts only as changing itself.\n */\n const before = () => {\n const inputs = recorder.inputs();\n if (inputs.length === 0) return [];\n const { tracks, losses } = kept.recent();\n return inputs.map(({ at, target }) => {\n const changed = /* @__PURE__ */ new Set();\n const moved = /* @__PURE__ */ new Set();\n let still = losses.every((lost) => lost >= at || lost < at - stillMillis);\n for (const { key, kind, initial, samples } of tracks) {\n const prior = samples.flatMap(({ at: when, shown }, index) => kind === \"value\" || when >= at || when < at - fluxMillis ? [] : [shown === null || (index === 0 ? initial : samples[index - 1]?.shown) === null]);\n if (prior.length > 0) changed.add(key);\n if (prior.length === 0 || key instanceof Element && key.contains(target)) continue;\n if (prior.includes(true)) moved.add(parentOf(key));\n if (samples.some(({ at: when }) => when < at && when >= at - stillMillis)) still = false;\n }\n return {\n at,\n target,\n changed,\n moved,\n still\n };\n });\n };\n /** The input a change followed, on the page's clock, where `Change.cause`'s rule names one. */\n const causeOf = (one, element, inputs) => {\n const parent = parentOf(one.track.key);\n for (const input of inputs.toReversed()) {\n const after = one.startedAt - input.at;\n if (after < 0) continue;\n if (after > 3e3) break;\n if (!(one.track.known >= input.at - fluxMillis || input.changed.has(one.track.key) || parent !== null && input.moved.has(parent)) && (local(input.target, element) || after <= 500 && input.still)) return input.at;\n }\n };\n const describe = (one, known, unmask, inputs) => {\n const { track, kind, before, after, lowest, highest, ...times } = one;\n const element = track.key instanceof Element ? track.key : null;\n const where = element?.isConnected === true ? element : marking.placeOf(track.key) ?? null;\n const box = where === null ? void 0 : walked.boxOf(where);\n const role = element === null ? null : roleOf(element);\n const field = kind === \"value\";\n const checkable = element !== null && isInput(element) && /^(checkbox|radio)$/.test(element.type);\n const masked = (value) => value === void 0 || !field || unmask || checkable || value === \"\" ? value : \"••••\";\n return {\n ...times,\n kind,\n subject: {\n role,\n name: element === null ? \"\" : field ? nameOf(element, role) : clean(element.getAttribute(\"aria-label\"), 120),\n tag: element === null ? \"title\" : element.tagName.toLowerCase(),\n context: kind === \"title\" || where === null ? {} : placing.contextOf(where, known)\n },\n box: box === void 0 || box.width === 0 && box.height === 0 ? void 0 : box,\n before: masked(before),\n after: masked(after),\n lowest: field ? void 0 : lowest,\n highest: field ? void 0 : highest,\n cause: field || where === null ? void 0 : causeOf(one, where, inputs)\n };\n };\n /** What changed after `since`, up to `until`, and no later than now. */\n const read = (request) => {\n const now = performance.timeOrigin + performance.now();\n recorder.start();\n seeing.settle();\n const until = Math.min(request.until ?? now, now);\n const { from, dropped, folded } = kept.read(request.since ?? Number.NEGATIVE_INFINITY, until, now);\n const known = placing.known();\n const inputs = before();\n return {\n until,\n from,\n dropped,\n records: folded.map((one) => describe(one, known, request.unmask, inputs))\n };\n };\n return { read };\n };\n //#endregion\n //#region src/internal/timeline/fold.inpage.ts\n const fold = () => {\n /** The one number some words show, such as 61240 in \"$61,240\"; none for none or several. */\n const number = (words) => {\n const found = words.match(/[-+−]?\\d[\\d,]*(?:\\.\\d+)?/g);\n const value = Number(found?.length === 1 ? found[0]?.replaceAll(\",\", \"\").replace(\"−\", \"-\") : \"\");\n return found?.length === 1 && Number.isFinite(value) ? [value] : [];\n };\n /** A track's changes after `since`, up to `until`, if one was seen in view. */\n const over = (track, since, until) => {\n const inside = track.samples.filter((sample) => sample.at > since && sample.at <= until);\n const first = inside[0];\n const last = inside.at(-1);\n if (first === void 0 || last === void 0 || !inside.some((sample) => sample.seen === true)) return void 0;\n const prior = track.samples[track.samples.indexOf(first) - 1];\n const lost = track.known <= since ? track.known : void 0;\n const start = prior === void 0 ? lost === void 0 ? void 0 : track.initial : prior.shown;\n const words = [start, ...inside.map((sample) => sample.shown)].filter((each) => typeof each === \"string\");\n const numbers = words.flatMap(number);\n const ranged = inside.length > 1 && numbers.length === words.length;\n const kind = track.kind !== \"content\" ? track.kind : last.shown === null ? start === null ? \"brief\" : \"disappeared\" : start === null ? \"appeared\" : \"text\";\n return {\n track,\n kind,\n startedAt: first.at,\n at: last.at,\n before: kind === \"disappeared\" ? words.at(-1) : start ?? void 0,\n after: kind === \"brief\" ? words.at(-1) : last.shown ?? void 0,\n count: inside.length,\n lowest: ranged ? words[numbers.indexOf(Math.min(...numbers))] : void 0,\n highest: ranged ? words[numbers.indexOf(Math.max(...numbers))] : void 0,\n earlier: prior?.at ?? (lost === Number.NEGATIVE_INFINITY ? void 0 : lost)\n };\n };\n /**\n * How readily a track gives way when the record is full: one that holds no change first, then\n * one that keeps changing, one never seen in view and one that has gone; news never does.\n */\n const rank = ({ samples: [only, ...more] }) => only === void 0 ? 4 : more.length > 0 ? 3 : only.seen === false ? 2 : only.shown === null ? 1 : 0;\n return {\n number,\n over,\n rank\n };\n };\n //#endregion\n //#region src/internal/timeline/history.inpage.ts\n const history = (folding, bounds = {\n tracks: 256,\n samples: 32,\n retention: 6e4\n }) => {\n const { tracks: maxTracks, samples: maxSamples, retention } = bounds;\n const tracks = /* @__PURE__ */ new Map();\n let refused = /* @__PURE__ */ new WeakSet();\n let losses = [];\n let lastLoss = Number.NEGATIVE_INFINITY;\n const gone = [];\n let begun;\n const lose = (at, count) => {\n const last = losses.at(-1);\n if (count <= 0) return;\n lastLoss = Math.max(lastLoss, at);\n if (last?.[0] === at) last[1] += count;\n else losses.push([at, count]);\n if (losses.length > 256) losses.shift();\n };\n const latest = (track) => track.samples.at(-1)?.at ?? Number.NEGATIVE_INFINITY;\n const drop = (track) => {\n tracks.delete(track.key);\n gone.push(track.key);\n };\n let version = 0;\n let barren = -1;\n /** What gives way for a newcomer: one that holds no change, then one that keeps changing. */\n const victim = () => {\n let chosen;\n let rank = 0;\n for (const track of barren === version ? [] : tracks.values()) {\n const next = folding.rank(track);\n if (next > rank) [chosen, rank] = [track, next];\n if (rank === 4) break;\n }\n if (chosen === void 0) barren = version;\n return chosen;\n };\n const evict = (track) => {\n drop(track);\n if (track.samples.length > 0) refused.add(track.key);\n for (const sample of track.samples) lose(sample.at, 1);\n };\n /** A key the record cannot keep: its change is counted. */\n const refuse = (key, at) => {\n refused.add(key);\n lose(at, 1);\n };\n /**\n * A new state for `key` at `at`: its sample, or none when it is no change or finds no room.\n * `initial` says what a key not yet kept showed before.\n */\n const note = (key, kind, at, shown, initial) => {\n let track = tracks.get(key);\n if (track === void 0) {\n const full = !refused.has(key) && tracks.size >= maxTracks;\n const out = full ? victim() : void 0;\n if (refused.has(key) || full && out === void 0) return refuse(key, at);\n const before = initial();\n if (shown !== void 0 && shown === before) return void 0;\n if (out !== void 0) evict(out);\n track = {\n key,\n kind,\n initial: before,\n known: Number.NEGATIVE_INFINITY,\n samples: []\n };\n tracks.set(key, track);\n }\n const { samples } = track;\n version++;\n if (samples.at(-1)?.at === at) samples.pop();\n const previous = samples.length === 0 ? track.initial : samples.at(-1)?.shown;\n if (shown !== void 0 && shown === previous) return void 0;\n const oldest = samples.length >= maxSamples ? samples.shift() : void 0;\n if (oldest !== void 0) {\n track.initial = oldest.shown;\n track.known = oldest.at;\n lose(oldest.at, 1);\n }\n const sample = {\n at,\n shown,\n seen: void 0\n };\n samples.push(sample);\n return sample;\n };\n /** Judge a sample as the page rendered it; a state that repeats the one before is no change. */\n const settle = (key, sample, shown, seen) => {\n const track = tracks.get(key);\n version++;\n if (sample.shown === void 0) sample.shown = shown;\n if (sample.seen === void 0) sample.seen = seen;\n if (track === void 0) return;\n let previous = track.initial;\n const changes = track.samples.filter((each) => {\n const same = each.shown !== void 0 && each.shown === previous;\n if (!same) previous = each.shown;\n return !same;\n });\n track.samples.splice(0, track.samples.length, ...changes);\n };\n /**\n * The window after `since`, up to `until`: where the record is whole, how many changes in it the\n * record let go, and each element's changes, oldest first by when they began.\n */\n const read = (since, until, now) => {\n for (const track of tracks.values()) if (latest(track) < now - retention) drop(track);\n return {\n from: Math.min(until, Math.max(begun ?? now, now - retention, lastLoss)),\n dropped: losses.reduce((sum, [at, count]) => at > since && at <= until ? sum + count : sum, 0),\n folded: [...tracks.values()].flatMap((track) => folding.over(track, since, until) ?? []).toSorted((left, right) => left.startedAt - right.startedAt)\n };\n };\n /** When something in view last changed, or something not yet judged; for a wait for stillness. */\n const changing = () => Math.max(begun ?? Number.NEGATIVE_INFINITY, ...Array.from(tracks.values(), (track) => track.samples.findLast((sample) => sample.seen !== false)?.at ?? Number.NEGATIVE_INFINITY));\n return {\n begin: (at) => {\n begun = at;\n },\n begun: () => begun !== void 0,\n clear: () => {\n for (const track of tracks.values()) drop(track);\n refused = /* @__PURE__ */ new WeakSet();\n losses = [];\n lastLoss = Number.NEGATIVE_INFINITY;\n begun = void 0;\n },\n changing,\n /** Keys whose tracks went since this was last asked, for the recorder to stop watching. */\n forgotten: () => gone.splice(0),\n has: (key) => tracks.has(key),\n /** Whether the record has let `key` go: its later changes are counted, never kept. */\n refuses: (key) => refused.has(key),\n lose,\n note,\n read,\n /** Each element's history, and when the record let changes go, for a read to judge causes. */\n recent: () => ({\n tracks: [...tracks.values()],\n losses: losses.map(([at]) => at)\n }),\n /** A track moves to the element that took its key's place, as a re-rendered price does. */\n rekey: (from, to) => {\n const track = tracks.get(from);\n if (track === void 0 || tracks.has(to)) return false;\n tracks.delete(from);\n track.key = to;\n tracks.set(to, track);\n return true;\n },\n settle\n };\n };\n //#endregion\n //#region src/internal/timeline/marks.inpage.ts\n const marks = (names, kept, seeing) => {\n const { clean, isElement, isHtml } = names;\n const unwritten = new Set(\"SCRIPT STYLE NOSCRIPT TEMPLATE TITLE\".split(\" \"));\n const hiding = /display\\s*:\\s*none|visibility\\s*:\\s*hidden|opacity\\s*:\\s*0(?![.\\d])/i;\n let places = /* @__PURE__ */ new WeakMap();\n let title = \"\";\n const words = (text) => clean(text, 200) || null;\n const content = (element, at, shown, initial) => {\n const sample = kept.note(element, \"content\", at, shown, initial);\n if (sample !== void 0) seeing.look(element, sample);\n };\n /** What a text-only element said before this batch: its text with the batch undone. */\n const before = (leaf, records) => {\n let nodes = Array.from(leaf.childNodes);\n const old = /* @__PURE__ */ new Map();\n for (const record of records.toReversed()) if (record.type === \"characterData\") old.set(record.target, record.oldValue ?? \"\");\n else {\n const added = new Set(Array.from(record.addedNodes));\n nodes = nodes.filter((node) => !added.has(node));\n const next = record.nextSibling === null ? -1 : nodes.indexOf(record.nextSibling);\n nodes.splice(next === -1 ? nodes.length : next, 0, ...Array.from(record.removedNodes));\n }\n return words(nodes.map((node) => old.get(node) ?? node.textContent).join(\"\"));\n };\n const attribute = (element, { attributeName: name, oldValue: old }, at) => {\n const was = name === \"hidden\" ? old !== null : name === \"aria-hidden\" ? old === \"true\" : name === \"open\" ? element.tagName === \"DIALOG\" && old === null : name === \"style\" && hiding.test(old ?? \"\");\n if (name === \"style\" && !was && !hiding.test(element.getAttribute(\"style\") ?? \"\")) return;\n const state = seeing.state(element);\n if (!kept.has(element) && !was && state === void 0 && name !== \"open\") return seeing.glance(element);\n content(element, at, void 0, () => was || state === false ? null : name === \"open\" && old === null ? words(element.querySelector(\":scope > summary\")?.textContent) : words(element.textContent));\n };\n /** What one mutation added to and removed from `target`. */\n const nodes = (change, target, batch) => {\n const added = Array.from(change.addedNodes).slice(0, 64);\n const removed = Array.from(change.removedNodes).slice(0, 64);\n const text = [...added, ...removed].some((node) => !isElement(node) && /\\S/.test(node.textContent ?? \"\"));\n kept.lose(batch.at, Math.max(change.addedNodes.length, change.removedNodes.length) - 64);\n if (text) batch.owners.add(target);\n removed.forEach((gone, index) => {\n const node = added[index];\n if (!isElement(gone)) return;\n batch.left.add(gone);\n if (node !== void 0 && isElement(node) && kept.rekey(gone, node)) seeing.unwatch(gone);\n else if (kept.has(gone)) {\n places.set(gone, target);\n const sample = kept.note(gone, \"content\", batch.at, null, () => void 0);\n if (sample !== void 0) sample.seen = seeing.viewed(gone);\n seeing.unwatch(gone);\n }\n });\n for (const node of added) if (isElement(node) && isHtml(node) && !unwritten.has(node.tagName) && !node.isContentEditable) {\n if (kept.has(node) || !text && !batch.left.has(node)) {\n batch.arrived.add(node);\n content(node, batch.at, void 0, () => null);\n }\n }\n };\n /** Whether `element` is inside something this batch added, which tells it with its own words. */\n const inside = (element, arrived) => {\n for (let up = element.parentElement; arrived.size > 0 && up !== null; up = up.parentElement) if (arrived.has(up)) return true;\n return false;\n };\n const ownerOf = (change) => change.type === \"characterData\" ? change.target.parentElement : change.target;\n /** Mark what one batch of mutations changed, at `at`. */\n const mark = (records, at) => {\n const batch = {\n at,\n owners: /* @__PURE__ */ new Set(),\n arrived: /* @__PURE__ */ new Set(),\n left: /* @__PURE__ */ new Set()\n };\n let byOwner;\n for (const change of records) {\n const target = ownerOf(change);\n if (target === null || !isElement(target) || inside(target, batch.arrived)) continue;\n const known = kept.has(target) || kept.refuses(target);\n if (change.type !== \"attributes\") if (change.type === \"characterData\" || target.childElementCount === 0 && known) batch.owners.add(target);\n else nodes(change, target, batch);\n else if (isHtml(target) && target !== document.body && target !== document.documentElement) attribute(target, change, at);\n }\n for (const owner of batch.owners) {\n const leaf = owner.childElementCount === 0;\n if (kept.refuses(owner)) kept.lose(at, 1);\n if (kept.refuses(owner) || !isHtml(owner) || unwritten.has(owner.tagName)) continue;\n if (owner === document.body || owner.isContentEditable) continue;\n if (batch.arrived.has(owner) || inside(owner, batch.arrived)) continue;\n content(owner, at, leaf ? words(owner.textContent) : void 0, () => {\n byOwner ??= Map.groupBy(records, ownerOf);\n return leaf ? before(owner, byOwner.get(owner) ?? []) : void 0;\n });\n }\n if (document.title === title) return;\n const previous = words(title);\n const sample = kept.note(document, \"title\", at, words(title = document.title), () => previous);\n if (sample !== void 0) sample.seen = true;\n };\n return {\n mark,\n /** Where a removed element was, which gives its context. */\n placeOf: (key) => places.get(key),\n /** Start afresh, from the document's title now. */\n reset: () => {\n places = /* @__PURE__ */ new WeakMap();\n title = document.title;\n }\n };\n };\n //#endregion\n //#region src/internal/timeline/record.inpage.ts\n const record = (names, texts, kept, seeing, marking) => {\n const { isElement, isInput } = names;\n const epoch = () => performance.timeOrigin + performance.now();\n const declared = \"[role=alert],[role=status],[role=log],[role=dialog],[role=alertdialog],[aria-live],dialog,[popover]\";\n let running = false;\n let lastRead = 0;\n let focused = /* @__PURE__ */ new WeakMap();\n const inputs = [];\n const targetOf = (event) => {\n const target = event.composedPath()[0];\n return target instanceof Node && isElement(target) ? target : void 0;\n };\n /** A field's value as the record keeps it: a secret one's as `••••`, a box's checked or not. */\n const valueOf = (field) => isInput(field) && (field.type === \"checkbox\" || field.type === \"radio\") ? field.checked ? \"checked\" : \"not checked\" : texts.shown(field, true);\n const onFocus = (event) => {\n const field = targetOf(event);\n const value = field === void 0 ? void 0 : valueOf(field);\n if (field !== void 0 && value !== void 0) focused.set(field, value);\n };\n const onValue = (event) => {\n const field = targetOf(event);\n const value = field === void 0 ? void 0 : valueOf(field);\n if (field === void 0 || value === void 0) return;\n const sample = kept.note(field, \"value\", epoch(), value, () => focused.get(field) ?? null);\n if (sample !== void 0) seeing.look(field, sample);\n };\n const note = (target) => {\n inputs.push({\n at: epoch(),\n target\n });\n if (inputs.length > 8) inputs.shift();\n };\n const onInput = (event) => {\n const target = targetOf(event);\n if (event.isTrusted && target !== void 0) note(target);\n };\n const listeners = [\n [\"focusin\", onFocus],\n [\"input\", onValue],\n [\"change\", onValue],\n [\"pointerdown\", onInput],\n [\"keydown\", onInput]\n ];\n const options = {\n capture: true,\n passive: true\n };\n const stop = () => {\n running = false;\n document.removeEventListener(\"DOMContentLoaded\", begin);\n observer.disconnect();\n for (const [type, listener] of listeners) document.removeEventListener(type, listener, options);\n seeing.clear();\n kept.clear();\n kept.forgotten();\n inputs.length = 0;\n focused = /* @__PURE__ */ new WeakMap();\n };\n const observer = new MutationObserver((records) => {\n const at = epoch();\n if (at - lastRead > 12e4) stop();\n else marking.mark(records, at);\n });\n const begin = () => {\n if (!running || kept.begun()) return;\n observer.observe(document, {\n subtree: true,\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributeFilter: [\n \"hidden\",\n \"open\",\n \"aria-hidden\",\n \"class\",\n \"style\"\n ],\n attributeOldValue: true\n });\n for (const [type, listener] of listeners) document.addEventListener(type, listener, options);\n marking.reset();\n for (const element of Array.from(document.querySelectorAll(declared)).slice(0, 64)) seeing.glance(element, true);\n kept.begin(epoch());\n };\n return {\n stop,\n /** Record from now, once the document is parsed; each read keeps the record going. */\n start: () => {\n lastRead = epoch();\n if (running) return;\n running = true;\n if (document.readyState === \"loading\") document.addEventListener(\"DOMContentLoaded\", begin, { once: true });\n else begin();\n },\n /**\n * Keep an input at `target` now, as a trusted one is kept: what a site does through its own\n * app, whose events the page sees as untrusted, so its changes can name their cause.\n */\n note,\n inputs: () => inputs\n };\n };\n //#endregion\n //#region src/internal/timeline/sight.inpage.ts\n const sight = (names, walked, texts, kept) => {\n const { clean } = names;\n const { visible } = walked;\n let viewed = /* @__PURE__ */ new WeakMap();\n let watching = /* @__PURE__ */ new WeakSet();\n let states = /* @__PURE__ */ new WeakMap();\n const waiting = /* @__PURE__ */ new Map();\n /** What an element shows: its words, if its style shows it. */\n const shownBy = (element) => element.isConnected && visible(element) ? clean(texts.lines(element, false), 200) || null : null;\n /** Settle what waited on an element; its words are read once, if one of them needs them. */\n const judge = (element, pending, seen, was) => {\n const shown = pending.some((sample) => sample.shown === void 0) ? shownBy(element) : void 0;\n for (const sample of pending) {\n const now = sample.shown === void 0 ? shown : sample.shown;\n kept.settle(element, sample, now, now === null ? was : seen);\n }\n };\n const observer = new IntersectionObserver((entries) => {\n for (const { target, isIntersecting } of entries) {\n const was = viewed.get(target) ?? false;\n const seen = isIntersecting && visible(target);\n const pending = waiting.get(target);\n viewed.set(target, seen);\n waiting.delete(target);\n if (pending !== void 0) judge(target, pending, seen, was);\n if (!kept.has(target)) {\n states.set(target, visible(target));\n unwatch(target);\n }\n }\n });\n /** Watch an element, asking for a fresh report even if it is watched already. */\n const watch = (element) => {\n watching.add(element);\n observer.unobserve(element);\n observer.observe(element);\n };\n const unwatch = (element) => {\n watching.delete(element);\n observer.unobserve(element);\n };\n return {\n /** Judge a sample at once if what it shows and whether it is in view are known, else on render. */\n look: (element, sample) => {\n const view = viewed.get(element);\n if (sample.shown !== void 0 && view !== void 0 && watching.has(element)) {\n sample.seen = view;\n return;\n }\n waiting.set(element, [...waiting.get(element) ?? [], sample]);\n watch(element);\n },\n /**\n * Look at an element once, for its state when it next changes: as it renders, or `now`, by its\n * style, as for the few the record looks at as it starts.\n */\n glance: (element, now = false) => {\n if (now) states.set(element, visible(element));\n if (!watching.has(element)) watch(element);\n },\n /** Whether the style of an element looked at once showed it, if it was. */\n state: (element) => states.get(element),\n /** Whether a watched element was in view as the page last rendered it. */\n viewed: (element) => viewed.get(element) ?? false,\n unwatch,\n /** Judge now what the page has not rendered since it changed, as a hidden tab never does. */\n settle: () => {\n for (const [element, pending] of waiting) {\n const seen = element.isConnected && walked.inView(element.getBoundingClientRect()) && visible(element);\n judge(element, pending, seen, viewed.get(element) ?? false);\n viewed.set(element, seen);\n }\n waiting.clear();\n for (const key of kept.forgotten()) if (key instanceof Element) unwatch(key);\n },\n clear: () => {\n observer.disconnect();\n waiting.clear();\n viewed = /* @__PURE__ */ new WeakMap();\n watching = /* @__PURE__ */ new WeakSet();\n states = /* @__PURE__ */ new WeakMap();\n }\n };\n };\n //#endregion\n //#region src/internal/page/compose.inpage.ts\n const compose = (parts, next) => {\n const named = parts.names(parts.elements());\n if (next !== void 0) named.refs.next = next;\n const walked = parts.walk(named);\n const placing = parts.context(named, walked);\n const matching = parts.match();\n const subjected = parts.subjects(named, walked, matching, placing, parts.states(named));\n const texts = parts.text(named, walked);\n const controlled = parts.controls(named, subjected, texts);\n const kept = parts.history(parts.fold());\n const seeing = parts.sight(named, walked, texts, kept);\n const marking = parts.marks(named, kept, seeing);\n const recorder = parts.record(named, texts, kept, seeing, marking);\n const url = parts.addresses();\n const read = parts.outline(named, walked, subjected, texts, controlled, url);\n const readiness = parts.ready(walked, texts, kept);\n const overlaid = parts.overlay(named);\n const posing = parts.pose(named);\n return {\n named,\n walked,\n placing,\n overlaid,\n posing,\n recorder,\n url,\n reads: {\n refs: named.refs,\n snapshot: read.snapshot,\n find: subjected.find,\n layout: parts.layout(named, walked, subjected, matching, placing).read,\n overlay: overlaid.draw,\n pose: posing.set,\n unpose: posing.clear,\n until: parts.expectations(named, subjected, matching).until,\n text: texts.read,\n record: recorder.start,\n stopRecord: recorder.stop,\n changes: parts.changes(named, walked, placing, kept, seeing, marking, recorder).read,\n ready: readiness.wait,\n settle: readiness.settle,\n viewport: read.viewport\n }\n };\n };\n //#endregion\n //#region src/internal/page/overlay.inpage.ts\n const overlay = (names) => {\n const svgNamespace = \"http://www.w3.org/2000/svg\";\n let host;\n let root;\n const mount = () => {\n if (host === void 0 || root === void 0) {\n host = document.createElement(\"div\");\n root = host.attachShadow({ mode: \"closed\" });\n names.adopt(host);\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(\"svg { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible }\");\n root.adoptedStyleSheets = [sheet];\n }\n const zoom = Number(getComputedStyle(document.documentElement).zoom) || 1;\n for (const [name, value] of Object.entries({\n all: \"initial\",\n display: \"block\",\n position: \"fixed\",\n left: \"0\",\n top: \"0\",\n width: \"100vw\",\n height: \"100vh\",\n \"pointer-events\": \"none\",\n \"z-index\": \"2147483647\",\n contain: \"strict\",\n zoom: String(1 / zoom)\n })) host.style.setProperty(name, value, \"important\");\n if (host.parentNode !== document.documentElement) document.documentElement.append(host);\n return root;\n };\n const boxes = (drawing) => Array.from(drawing.children).slice(0, 32).map((part) => {\n const { x, y, width, height } = part.getBoundingClientRect();\n return {\n x,\n y,\n width,\n height\n };\n }).filter((box) => box.width > 0 && box.height > 0);\n /**\n * Draw an SVG document over the viewport, in place of what was drawn, or take the layer away\n * with null. Says where the drawing's parts are. Its scripts and handlers are dropped.\n */\n const draw = (markup) => {\n if (markup === null) {\n host?.remove();\n return [];\n }\n const parsed = new DOMParser().parseFromString(markup, \"image/svg+xml\");\n const drawing = parsed.documentElement;\n if (parsed.getElementsByTagName(\"parsererror\").length > 0 || drawing.namespaceURI !== svgNamespace || drawing.localName !== \"svg\") throw new Error(\"the overlay's markup is not an SVG document\");\n for (const script of Array.from(drawing.getElementsByTagName(\"script\"))) script.remove();\n for (const element of [drawing, ...Array.from(drawing.querySelectorAll(\"*\"))]) for (const attribute of Array.from(element.attributes)) if (/^on/i.test(attribute.name)) element.removeAttribute(attribute.name);\n const shown = document.importNode(drawing, true);\n mount().replaceChildren(shown);\n return boxes(shown);\n };\n return {\n draw,\n mount\n };\n };\n //#endregion\n //#region src/internal/page/pose.inpage.ts\n const pose = (names) => {\n const posed = /* @__PURE__ */ new Map();\n const isHtml = (element) => \"offsetWidth\" in element;\n const laidOut = (element, applied) => {\n const style = getComputedStyle(element);\n const [cx = 0, cy = 0] = style.transformOrigin.split(\" \").map(Number.parseFloat);\n const own = style.transform === \"none\" ? new DOMMatrix() : new DOMMatrix(style.transform);\n const whole = applied === void 0 ? own : new DOMMatrix().translate(applied.x, applied.y).rotate(applied.rotate).scale(applied.sx, applied.sy).multiply(own);\n const drawn = element.getBoundingClientRect();\n const plain = whole.isIdentity;\n const width = plain ? drawn.width : element.offsetWidth;\n const height = plain ? drawn.height : element.offsetHeight;\n let left = Infinity;\n let top = Infinity;\n for (const [x, y] of [\n [0, 0],\n [width, 0],\n [0, height],\n [width, height]\n ]) {\n const corner = whole.transformPoint({\n x: x - cx,\n y: y - cy\n });\n left = Math.min(left, corner.x + cx);\n top = Math.min(top, corner.y + cy);\n }\n const origin = {\n x: drawn.x - left + cx,\n y: drawn.y - top + cy\n };\n const middle = own.transformPoint({\n x: width / 2 - cx,\n y: height / 2 - cy\n });\n return {\n origin,\n middle: {\n x: origin.x + middle.x,\n y: origin.y + middle.y\n }\n };\n };\n const apply = (element, request) => {\n const known = posed.get(element);\n const { origin, middle } = laidOut(element, known?.applied);\n const about = request.origin ?? middle;\n const away = {\n x: about.x - origin.x,\n y: about.y - origin.y\n };\n const turned = new DOMMatrix().rotate(request.rotate).scale(request.sx, request.sy).transformPoint(away);\n const applied = {\n x: request.dx + away.x - turned.x,\n y: request.dy + away.y - turned.y,\n rotate: request.rotate,\n sx: request.sx,\n sy: request.sy\n };\n const frame = {\n translate: `${applied.x}px ${applied.y}px`,\n rotate: `${applied.rotate}deg`,\n scale: `${applied.sx} ${applied.sy}`\n };\n if (known === void 0) {\n const effect = new KeyframeEffect(element, [frame, frame], {\n duration: Infinity,\n fill: \"both\"\n });\n const animation = new Animation(effect, document.timeline);\n animation.play();\n posed.set(element, {\n animation,\n effect,\n applied\n });\n } else {\n known.effect.setKeyframes([frame, frame]);\n known.applied = applied;\n }\n };\n const takeOff = (element) => {\n posed.get(element)?.animation.cancel();\n posed.delete(element);\n };\n /**\n * The elements `requests` name, or the first that names none in the current document, or one\n * that is not an HTML element; then, to apply them, a function that poses them and takes poses\n * off every other element.\n */\n const prepare = (requests) => {\n const elements = [];\n for (const request of requests) {\n const element = names.lookup(request.ref);\n const { dx, dy, sx, sy, rotate, origin } = request;\n if (element === void 0) return { stale: request.ref };\n if (!isHtml(element)) return { invalid: `${request.ref} is not an HTML element` };\n if (![\n dx,\n dy,\n sx,\n sy,\n rotate,\n origin?.x ?? 0,\n origin?.y ?? 0\n ].every(Number.isFinite)) return { invalid: `${request.ref}'s pose is not finite numbers` };\n elements.push(element);\n }\n return { apply: () => {\n for (const element of Array.from(posed.keys())) if (!elements.includes(element)) takeOff(element);\n requests.forEach((request, index) => {\n const element = elements[index];\n if (element !== void 0) apply(element, request);\n });\n } };\n };\n const set = (requests) => {\n const prepared = prepare(requests);\n if (\"apply\" in prepared) {\n prepared.apply();\n return {};\n }\n return prepared;\n };\n const clear = () => {\n for (const element of Array.from(posed.keys())) takeOff(element);\n };\n return {\n prepare,\n set,\n clear\n };\n };\n //#endregion\n //#region src/internal/page/time.inpage.ts\n const time = (overlaid, posing) => {\n const step = (request) => {\n const posed = request.poses === void 0 ? void 0 : posing.prepare(request.poses);\n if (posed !== void 0 && !(\"apply\" in posed)) return {\n told: false,\n drawn: null,\n scroll: {\n x: scrollX,\n y: scrollY\n },\n ...posed\n };\n if (request.scroll !== null) scrollTo({\n left: scrollX,\n top: request.scroll,\n behavior: \"instant\"\n });\n const detail = {\n op: request.op,\n by: request.by\n };\n const told = !document.dispatchEvent(new CustomEvent(request.clock, {\n detail,\n cancelable: true\n }));\n posed?.apply();\n return {\n told,\n drawn: request.markup === void 0 ? null : overlaid.draw(request.markup),\n scroll: {\n x: scrollX,\n y: scrollY\n }\n };\n };\n return { step };\n };\n //#endregion\n //#region src/internal/page/bridge.ts\n const parts = {\n compose,\n elements,\n names,\n walk,\n match,\n context,\n subjects,\n states,\n expectations,\n text,\n layout,\n controls,\n fold,\n history,\n sight,\n marks,\n record,\n changes,\n ready,\n outline,\n targets,\n evidence,\n guard,\n edit,\n overlay,\n pose,\n time,\n addresses\n };\n function install(parts) {\n const source = install.toString() + Object.entries(parts).map(([name, factory]) => name + factory.toString()).join(\"\");\n let version = 2166136261;\n for (let index = 0; index < source.length; index++) version = Math.imul(version ^ source.charCodeAt(index), 16777619);\n version >>>= 0;\n const installed = globalThis.__effectBrowser;\n if (installed !== void 0 && installed.version === version) return installed;\n installed?.dispose?.();\n const { named, walked, placing, overlaid, posing, reads } = parts.compose(parts, installed?.refs?.next);\n const located = parts.targets(named, walked, placing);\n const guarded = parts.guard(named, located, parts.evidence(named, placing));\n const edited = parts.edit(named, guarded, placing);\n const api = {\n ...reads,\n version,\n dispose: reads.stopRecord,\n step: parts.time(overlaid, posing).step,\n point: located.point,\n scrollPlan: located.scrollPlan,\n screenSize: () => ({\n width: screen.width,\n height: screen.height,\n ratio: devicePixelRatio\n }),\n prepareInput: guarded.prepareInput,\n validateInput: guarded.validateInput,\n typeable: edited.typeable,\n focus: edited.focus,\n focusOn: edited.focusOn,\n select: edited.select\n };\n globalThis.__effectBrowser = api;\n return api;\n }\n //#endregion\n return install(parts);\n})();\n\nreturn pageScript;})()";
495
+ const installSource = "(() => {var pageScript = (function() {\n //#region src/internal/input/edit.inpage.ts\n const edit = (names, guard, placing) => {\n const { activeElement, clean, describe, inCurrentDocument, isDisabled, isHtml, isInput, isSecret, isSelect, isTextArea, lookup, nameOf, roleOf } = names;\n const { textEntry, typingRefusal } = guard;\n /** Whether text may be typed into a ref or focus, and, for a `secret`, only into a secret field. */\n const typeable = (ref, secret) => {\n const element = ref === null ? activeElement() : lookup(ref);\n if (element === void 0) return {\n error: \"stale\",\n detail: `${ref ?? \"the focused element\"} is not on the page any more`\n };\n const refusal = element === null ? secret ? \"nothing has focus to type a secret into\" : void 0 : typingRefusal(element, ref !== null) ?? (secret && !isSecret(element) ? `${describe(element)} is not a secret field` : void 0);\n if (refusal !== void 0) return {\n error: \"untypeable\",\n detail: refusal\n };\n if (element === null || ref !== null || !textEntry(element)) return {\n ok: true,\n secret: element !== null && isSecret(element)\n };\n const role = roleOf(element);\n const tag = element.tagName.toLowerCase();\n return {\n ok: true,\n secret: isSecret(element),\n subject: {\n role,\n name: nameOf(element, role),\n tag,\n context: placing.contextOf(element)\n }\n };\n };\n /**\n * The focused field, when it is a text field named `name`: one a page put in place of a field\n * just pressed and gave focus to, as a typeahead does.\n */\n const replacement = (name) => {\n const active = activeElement();\n return active !== null && textEntry(active) && inCurrentDocument(active) && nameOf(active, roleOf(active)) === name ? active : void 0;\n };\n /**\n * Focus a field to type into. `follow` is the field's name when the action pressed it first: a\n * page may answer the press with another field of that name in its place, focused, and the keys\n * follow focus there, as a person's would.\n */\n const focus = (ref, replace, follow) => {\n const element = lookup(ref) ?? (follow === null ? void 0 : replacement(follow));\n if (element === void 0) return {\n error: `${ref} is not on the page any more`,\n stale: true\n };\n if (isDisabled(element)) return { error: `${ref} is disabled` };\n if (!textEntry(element)) return { error: `${ref} is ${describe(element)}, not a text field` };\n if (isHtml(element)) element.focus();\n if (replace) {\n if (isInput(element) || isTextArea(element)) element.select();\n else element.ownerDocument.getSelection()?.selectAllChildren(element);\n }\n return {\n ok: true,\n detail: describe(element),\n secret: isSecret(element)\n };\n };\n /** Focus any element that takes focus, such as a link or a button, for a key pressed on it. */\n const focusOn = (ref) => {\n const element = lookup(ref);\n if (element === void 0) return {\n error: `${ref} is not on the page any more`,\n stale: true\n };\n if (isDisabled(element)) return { error: `${ref} is disabled` };\n if (isHtml(element)) element.focus();\n return activeElement() === element ? {\n ok: true,\n detail: describe(element)\n } : { error: `${ref} is ${describe(element)}, which does not take focus` };\n };\n const select = (ref, values) => {\n const element = lookup(ref);\n if (element === void 0) return {\n error: `${ref} is not on the page any more`,\n stale: true\n };\n if (!isSelect(element)) return { error: `${ref} is ${describe(element)}, not a <select>; click it and pick an option` };\n const wanted = values.map((value) => value.trim().toLowerCase());\n const options = Array.from(element.options);\n const chosen = options.filter((option) => wanted.includes(option.value.toLowerCase()) || wanted.includes(clean(option.text).toLowerCase()));\n if (chosen.length === 0) return { error: `no option matches; the options are ${options.map((option) => JSON.stringify(clean(option.text, 40))).join(\", \")}` };\n for (const option of options) option.selected = chosen.includes(option);\n element.dispatchEvent(new Event(\"input\", { bubbles: true }));\n element.dispatchEvent(new Event(\"change\", { bubbles: true }));\n return {\n ok: true,\n detail: chosen.map((option) => clean(option.text, 40)).join(\", \")\n };\n };\n return {\n focus,\n focusOn,\n select,\n typeable\n };\n };\n //#endregion\n //#region src/internal/input/evidence.inpage.ts\n const evidence = (names, placing) => {\n const { clean, isDocument, isInput, isSelect, isTextArea, nameOf, parentOf, roleOf, textOf } = names;\n const { groups, headingBefore, textBeside, treeOf } = placing;\n /** A field a submission would send. */\n const isField = (element) => (isInput(element) && ![\n \"button\",\n \"submit\",\n \"reset\",\n \"image\"\n ].includes(element.type) || isSelect(element) || isTextArea(element)) && !element.matches(\":disabled\");\n const isFilled = (field) => isInput(field) && (field.type === \"checkbox\" || field.type === \"radio\") ? field.checked : isInput(field) && field.type === \"file\" ? (field.files?.length ?? 0) > 0 : field.value !== \"\";\n const dialogOf = (element) => {\n for (let node = element; node !== null; node = parentOf(node)) if (node.tagName === \"DIALOG\" || /^(?:alert)?dialog$/.test(node.getAttribute(\"role\") ?? \"\")) return node;\n };\n /** What the page says about an input's first target, for a judge. Never a field's value. */\n const evidenceOf = (element, form, method, action) => {\n const name = nameOf(element, roleOf(element));\n const ids = element.getAttribute(\"aria-describedby\");\n const description = clean(ids === null ? element.getAttribute(\"aria-description\") ?? element.getAttribute(\"title\") : ids.split(/\\s+/).map((id) => element.ownerDocument.getElementById(id)?.textContent ?? \"\").join(\" \"), 120);\n const dialog = dialogOf(element);\n const title = dialog?.querySelector(\"h1,h2,h3,h4,h5,h6,[role=heading]\");\n const dialogName = dialog === void 0 ? \"\" : clean(nameOf(dialog, \"dialog\"), 120) || (title === null || title === void 0 ? \"\" : clean(textOf(title), 120));\n const root = element.getRootNode();\n const top = isDocument(root) ? root.body ?? root : root;\n const inTree = element.closest(\"dialog,[role=dialog],[role=alertdialog]\");\n let nearby = \"\";\n for (const scope of /* @__PURE__ */ new Set([\n element.closest(groups),\n inTree,\n top\n ])) if (scope !== null && nearby === \"\") nearby = textBeside(element, scope, true) || textBeside(element, scope, false);\n const heading = headingBefore(element, treeOf(element));\n const fields = form === null ? [] : Array.from(form.elements).filter(isField).slice(0, 16).map((field) => {\n const autocomplete = clean(field.getAttribute(\"autocomplete\"), 40);\n return {\n type: isInput(field) ? field.type : field.tagName.toLowerCase(),\n name: clean(isInput(field) && field.type === \"hidden\" ? field.getAttribute(\"name\") : nameOf(field, roleOf(field)), 40),\n ...autocomplete === \"\" ? {} : { autocomplete },\n filled: isFilled(field)\n };\n });\n return {\n title: clean(document.title, 120),\n ...description === \"\" || description === name ? {} : { description },\n ...dialogName === \"\" ? {} : { dialog: dialogName },\n ...heading === void 0 ? {} : { heading },\n ...nearby === \"\" ? {} : { nearby },\n ...form === null ? {} : { form: {\n method: method ?? form.method,\n action: action ?? form.action,\n fields\n } }\n };\n };\n return {\n evidenceOf,\n isField,\n isFilled\n };\n };\n //#endregion\n //#region src/internal/input/guard.inpage.ts\n const guard = (names, targets, evidence) => {\n const { activeElement, textEntry, clean, describe, inCurrentDocument, interactiveRoles, isButton, isDisabled, isHtml, isInput, isLabel, isRoot, isSecret, isSelect, isTextArea, lookup, parentOf, refFor, roleOf } = names;\n const { controlOf, details, hitAt, hrefAttribute, linkOf, receives, within } = targets;\n const { evidenceOf, isField, isFilled } = evidence;\n const nativeActivation = (element) => hrefAttribute(element) !== null || element.tagName === \"BUTTON\" || element.tagName === \"SUMMARY\" || isInput(element) && element.type !== \"hidden\";\n /**\n * The element whose activation behaviour a click or key on `element` runs, as the browser\n * resolves it along the composed path: a link, button, input, summary or a label's control.\n */\n const activationTarget = (element) => {\n for (let node = element; node !== null; node = parentOf(node)) {\n if (nativeActivation(node)) return node;\n if (isLabel(node) && node.control !== null) return node.control;\n }\n };\n /**\n * A control between a press's hit and the approved target that is not the target's own\n * activation, such as a link or button a hover handler nested into it. The approval inspected\n * the target, so that control would act unapproved.\n */\n const nestedControl = (element, hit) => {\n if (!within(element, hit)) return void 0;\n const own = activationTarget(element);\n for (let node = hit; node !== null && node !== element; node = parentOf(node) ?? node.ownerDocument.defaultView?.frameElement ?? null) if (node !== own && (nativeActivation(node) || isSelect(node) || isTextArea(node) || isLabel(node) && node.control !== null && node.control !== own || activatingRoles.has(roleOf(node) ?? \"\"))) return node;\n };\n const activatingRoles = /* @__PURE__ */ new Set([\n \"button\",\n \"link\",\n \"checkbox\",\n \"radio\",\n \"switch\",\n \"tab\",\n \"menuitem\",\n \"menuitemcheckbox\",\n \"menuitemradio\",\n \"option\",\n \"treeitem\"\n ]);\n const typingRefusal = (element, explicit) => textEntry(element) ? void 0 : explicit ? `${describe(element)} is not a text field` : activationTarget(element) !== void 0 || isSelect(element) || activatingRoles.has(roleOf(element) ?? \"\") ? `focus is on ${describe(element)}, which typed text could activate or change; type into a text field by ref, or use press for keys` : void 0;\n const isSubmitter = (element) => isButton(element) && element.type === \"submit\" || isInput(element) && (element.type === \"submit\" || element.type === \"image\");\n const defaultSubmitter = (form) => {\n const root = form.getRootNode();\n return isRoot(root) ? Array.from(root.querySelectorAll(\"button,input\")).find((candidate) => isSubmitter(candidate) && candidate.form === form) : void 0;\n };\n const purpose = (control, form) => [\n control.getAttribute(\"id\"),\n control.getAttribute(\"name\"),\n control.getAttribute(\"inputmode\"),\n control.getAttribute(\"autocomplete\"),\n control.getAttribute(\"aria-label\"),\n form?.getAttribute(\"id\"),\n form?.getAttribute(\"name\"),\n form?.getAttribute(\"aria-label\")\n ];\n const boundUrl = (url) => {\n const hash = url.indexOf(\"#\");\n return hash === -1 || /^#[/!]/.test(url.slice(hash)) ? url : url.slice(0, hash);\n };\n const inspectInput = (element, plan) => {\n const metadata = details(element, element, 0, 0);\n const control = activationTarget(element) ?? element;\n const form = isInput(control) || isButton(control) || isTextArea(control) || isSelect(control) ? control.form : null;\n const key = plan.keys === null ? void 0 : /(?:^|\\+)(\\+|[^+]+)$/.exec(plan.keys)?.[1];\n const enter = key === \"Enter\";\n const activation = plan.action === \"click\" || plan.action === \"press\" && (enter || key === \"Space\");\n const fieldEnter = isInput(control) && ![\n \"button\",\n \"reset\",\n \"submit\",\n \"image\",\n \"file\",\n \"color\",\n \"hidden\"\n ].includes(control.type) && (plan.action === \"press\" && enter || plan.action === \"type\" && plan.submit);\n const submits = form !== null && (activation && isSubmitter(control) || fieldEnter);\n const submitter = isSubmitter(control) ? control : form === null ? void 0 : defaultSubmitter(form);\n const formValue = (attribute, property) => form === null ? void 0 : submitter?.hasAttribute(`form${attribute}`) === true ? submitter[property] : form[attribute];\n const formDestination = formValue(\"action\", \"formAction\");\n const formMethod = formValue(\"method\", \"formMethod\");\n const formTarget = formValue(\"target\", \"formTarget\");\n const link = linkOf(element);\n const href = link === void 0 ? null : hrefAttribute(link);\n const sends = submits && formMethod !== \"dialog\";\n const destination = sends ? formDestination : activation ? metadata.href : void 0;\n const acts = plan.action !== \"hover\" && plan.action !== \"scroll\";\n const builtIn = sends || href !== null && !/^\\s*(?:#\\s*|javascript:[^]*)$/i.test(href) || isInput(control) && ![\n \"button\",\n \"submit\",\n \"image\",\n \"reset\"\n ].includes(control.type) || (isInput(control) || isButton(control)) && control.type === \"reset\" && form !== null || control.tagName === \"SUMMARY\" || control.closest(\"select\") !== null || textEntry(control);\n const facts = [];\n if (sends) facts.push(\"form-submit\");\n if (activation && link?.hasAttribute(\"download\") === true) facts.push(\"download\");\n if (activation && isInput(control) && control.type === \"file\") facts.push(\"upload\");\n if (plan.action === \"type\" && isSecret(control) || sends && form !== null && Array.from(form.elements).some((field) => isField(field) && isSecret(field) && isFilled(field))) facts.push(\"secret\");\n if (activation && !builtIn) facts.push(\"scripted\");\n if (acts && (metadata.role === \"canvas\" || metadata.role === \"iframe\" || metadata.name === \"\")) facts.push(\"opaque\");\n const role = metadata.role;\n const boundName = role !== null && (interactiveRoles.has(role) || role === \"canvas\" || role === \"iframe\") && !(isHtml(element) && element.isContentEditable) ? metadata.name : null;\n const fingerprint = JSON.stringify([\n purpose(control, form),\n element.tagName,\n element.id,\n role,\n boundName,\n metadata.href,\n control === element ? null : refFor(control),\n isInput(control) || isButton(control) ? control.type : control.tagName,\n isDisabled(control),\n control.getAttribute(\"readonly\"),\n control.getAttribute(\"aria-readonly\"),\n isHtml(control) && control.isContentEditable,\n control.getAttribute(\"name\"),\n control.getAttribute(\"accept\"),\n control.hasAttribute(\"multiple\"),\n link?.getAttribute(\"download\"),\n form === null ? null : refFor(form),\n form === null ? null : boundUrl(form.action),\n form?.method,\n form?.target,\n submitter === void 0 ? null : refFor(submitter),\n formDestination === void 0 ? void 0 : boundUrl(formDestination),\n formMethod,\n formTarget,\n submitter?.formNoValidate,\n form?.noValidate\n ]);\n return {\n inspected: {\n ref: refFor(element),\n element: metadata.element,\n role: metadata.role,\n name: metadata.name,\n cursor: metadata.cursor,\n ...metadata.href === void 0 ? {} : { href: metadata.href },\n secret: isSecret(control),\n fingerprint\n },\n facts,\n destination,\n explain: () => evidenceOf(element, form, formMethod, formDestination)\n };\n };\n const inspect = (plan) => {\n const targets = [];\n const facts = /* @__PURE__ */ new Set();\n let destination = plan.destination ?? void 0;\n let explain = () => ({ title: clean(document.title, 120) });\n for (const [index, target] of plan.targets.entries()) {\n let element;\n if (target === null) element = activeElement();\n else if (typeof target === \"string\") {\n element = lookup(target);\n if (element === void 0) return {\n error: \"stale\",\n detail: target + \" is not on the page any more\",\n index\n };\n } else {\n if (!Number.isFinite(target.x) || !Number.isFinite(target.y) || target.x < 0 || target.y < 0 || target.x >= window.innerWidth || target.y >= window.innerHeight) return {\n error: \"outside\",\n detail: \"the point is outside the viewport\"\n };\n const hit = hitAt(document, target.x, target.y);\n element = hit === null ? null : controlOf(hit);\n if (element === null) return {\n error: \"offscreen\",\n detail: \"nothing is painted at the point\"\n };\n }\n if (element === null) {\n targets.push(null);\n continue;\n }\n if (!inCurrentDocument(element)) return {\n error: \"stale\",\n detail: \"the input target belongs to a replaced document\",\n index\n };\n const refusal = plan.action === \"type\" ? typingRefusal(element, target !== null) : void 0;\n if (refusal !== void 0) return {\n error: \"untypeable\",\n detail: refusal\n };\n const inspected = inspectInput(element, plan);\n if (index === 0) explain = inspected.explain;\n targets.push(inspected.inspected);\n for (const fact of inspected.facts) facts.add(fact);\n destination ??= inspected.destination;\n if (inspected.destination !== void 0) try {\n if (new URL(inspected.destination, location.href).origin !== location.origin) facts.add(\"cross-origin\");\n } catch {\n return {\n error: \"outside\",\n detail: \"the input destination is not a valid URL\"\n };\n }\n }\n if (destination !== void 0) try {\n destination = new URL(destination, location.href).href;\n if (new URL(destination).origin !== location.origin) facts.add(\"cross-origin\");\n } catch {\n return {\n error: \"outside\",\n detail: \"the input destination is not a valid URL\"\n };\n }\n return {\n url: boundUrl(location.href),\n targets,\n facts: [...facts],\n ...destination === void 0 ? {} : { destination },\n explain\n };\n };\n const prepareInput = (plan) => {\n const inspected = inspect(plan);\n if (\"error\" in inspected) return inspected;\n const { explain, ...prepared } = inspected;\n return {\n ...prepared,\n evidence: explain()\n };\n };\n const bindings = (targets) => targets.map((target) => target === null ? null : [target.ref, target.fingerprint]);\n const validate = (plan, prepared, options) => {\n const current = inspect(plan);\n if (\"error\" in current) return current.error === \"stale\" ? current : {\n error: \"changed\",\n detail: current.detail\n };\n if (current.url !== prepared.url || (current.destination === void 0 || prepared.destination === void 0 ? current.destination !== prepared.destination : boundUrl(current.destination) !== boundUrl(prepared.destination)) || JSON.stringify(current.facts) !== JSON.stringify(prepared.facts) || JSON.stringify(bindings(current.targets)) !== JSON.stringify(bindings(prepared.targets))) return {\n error: \"changed\",\n detail: \"the page or input target changed while the policy was deciding\"\n };\n if (options.focused === true) {\n const active = activeElement();\n const expected = prepared.targets[0];\n if (active === null || expected === null || expected === void 0 || refFor(active) !== expected.ref) return {\n error: \"changed\",\n detail: \"focus moved away from the approved element\"\n };\n }\n for (const press of options.presses ?? []) {\n const expected = prepared.targets[press.index];\n const element = expected === null || expected === void 0 ? void 0 : lookup(expected.ref);\n const hit = hitAt(document, press.x, press.y);\n if (element === void 0 || hit === null || !receives(element, hit)) return {\n error: \"changed\",\n detail: `the approved target is no longer under the pointer at (${press.x}, ${press.y})`\n };\n const nested = nestedControl(element, hit);\n if (nested !== void 0) return {\n error: \"changed\",\n detail: `${describe(nested)} inside the approved target would receive the press at (${press.x}, ${press.y})`\n };\n }\n return { ok: true };\n };\n const validateInput = (plan, prepared, options = {}) => {\n if ((options.presses ?? []).length === 0) return validate(plan, prepared, options);\n const { promise, resolve } = Promise.withResolvers();\n if (document.visibilityState === \"hidden\") resolve();\n else requestAnimationFrame(() => requestAnimationFrame(() => resolve()));\n return promise.then(() => validate(plan, prepared, options));\n };\n return {\n prepareInput,\n textEntry,\n typingRefusal,\n validateInput\n };\n };\n //#endregion\n //#region src/internal/input/targets.inpage.ts\n const targets = (names, walked, placing) => {\n const { describe, isDisabled, lookup, nameOf, parentOf, roleOf } = names;\n const { boxOf, controlOf, hitAt } = walked;\n const { contextOf } = placing;\n /** Whether `node` is `ancestor` or inside it, across shadow roots and same-origin frames. */\n const within = (ancestor, node) => {\n for (let current = node; current !== null;) {\n if (current === ancestor) return true;\n current = parentOf(current) ?? current.ownerDocument.defaultView?.frameElement ?? null;\n }\n return false;\n };\n const receives = (element, hit) => within(element, hit) || within(hit, element);\n const hrefAttribute = (element) => element.localName === \"a\" || element.localName === \"area\" ? element.getAttribute(\"href\") ?? element.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\") : null;\n const linkOf = (element) => {\n for (let node = element; node !== null; node = parentOf(node)) if (hrefAttribute(node) !== null) return node;\n };\n const details = (element, hit, x, y) => {\n const link = linkOf(element);\n let href;\n if (link !== void 0) try {\n href = new URL(hrefAttribute(link) ?? \"\", link.ownerDocument.baseURI).href;\n } catch {\n href = void 0;\n }\n const role = roleOf(element);\n const view = hit.ownerDocument.defaultView ?? window;\n return {\n x,\n y,\n element: describe(element),\n tag: element.tagName.toLowerCase(),\n role,\n name: nameOf(element, role),\n cursor: view.getComputedStyle(hit).cursor,\n ...href === void 0 ? {} : { href }\n };\n };\n const point = (target, scroll = true) => {\n if (typeof target !== \"string\") {\n const { x, y } = target;\n if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x >= window.innerWidth || y >= window.innerHeight) return {\n error: \"outside\",\n detail: `(${x}, ${y}) is outside the viewport`\n };\n const hit = hitAt(document, x, y);\n if (hit === null) return {\n error: \"offscreen\",\n detail: `nothing is painted at (${x}, ${y})`\n };\n const control = controlOf(hit);\n return {\n ...details(control, hit, x, y),\n context: contextOf(control),\n box: boxOf(control)\n };\n }\n const ref = target;\n const element = lookup(ref);\n if (element === void 0) return {\n error: \"stale\",\n detail: `${ref} is not on the page any more`\n };\n if (isDisabled(element)) return {\n error: \"disabled\",\n detail: `${ref} is disabled`\n };\n const rect = element.getBoundingClientRect();\n if (rect.width === 0 && rect.height === 0) return {\n error: \"hidden\",\n detail: `${ref} has no size on the page`\n };\n let box = {\n left: rect.left,\n top: rect.top,\n right: rect.right,\n bottom: rect.bottom\n };\n let visible = { ...box };\n let outside = false;\n for (let inner = element;;) {\n const view = inner.ownerDocument.defaultView ?? window;\n outside ||= box.left < 0 || box.top < 0 || box.right > view.innerWidth || box.bottom > view.innerHeight;\n visible = {\n left: Math.max(visible.left, 0),\n top: Math.max(visible.top, 0),\n right: Math.min(visible.right, view.innerWidth),\n bottom: Math.min(visible.bottom, view.innerHeight)\n };\n for (let ancestor = parentOf(inner); ancestor !== null; ancestor = parentOf(ancestor)) {\n const style = view.getComputedStyle(ancestor);\n const clip = ancestor.getBoundingClientRect();\n if (/(auto|scroll|hidden|clip)/.test(style.overflowX)) {\n visible.left = Math.max(visible.left, clip.left + ancestor.clientLeft);\n visible.right = Math.min(visible.right, clip.left + ancestor.clientLeft + ancestor.clientWidth);\n }\n if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {\n visible.top = Math.max(visible.top, clip.top + ancestor.clientTop);\n visible.bottom = Math.min(visible.bottom, clip.top + ancestor.clientTop + ancestor.clientHeight);\n }\n }\n const frame = view.frameElement;\n if (frame === null) break;\n const frameBox = frame.getBoundingClientRect();\n const dx = frameBox.left + frame.clientLeft;\n const dy = frameBox.top + frame.clientTop;\n box = {\n left: box.left + dx,\n top: box.top + dy,\n right: box.right + dx,\n bottom: box.bottom + dy\n };\n visible = {\n left: Math.max(visible.left + dx, dx),\n top: Math.max(visible.top + dy, dy),\n right: Math.min(visible.right + dx, dx + frame.clientWidth),\n bottom: Math.min(visible.bottom + dy, dy + frame.clientHeight)\n };\n inner = frame;\n }\n if (outside || visible.right <= visible.left || visible.bottom <= visible.top) {\n if (scroll) {\n element.scrollIntoView({\n block: \"center\",\n inline: \"center\",\n behavior: \"instant\"\n });\n return point(target, false);\n }\n return {\n error: \"offscreen\",\n detail: outside ? ref + \" is outside the viewport\" : `${ref} could not be scrolled into view`\n };\n }\n const x = (visible.left + visible.right) / 2;\n const y = (visible.top + visible.bottom) / 2;\n const hit = hitAt(document, x, y);\n if (hit !== null && !receives(element, hit)) return {\n error: \"covered\",\n detail: `${ref} is covered by ${describe(hit)}`\n };\n return {\n ...details(element, hit ?? element, Math.round(x), Math.round(y)),\n context: contextOf(element)\n };\n };\n const scrollPlan = (ref) => {\n const element = lookup(ref);\n if (element === void 0 || element.ownerDocument !== document) return null;\n const target = element.getBoundingClientRect();\n const centerX = (target.left + target.right) / 2;\n const centerY = (target.top + target.bottom) / 2;\n for (let ancestor = parentOf(element); ancestor !== null; ancestor = parentOf(ancestor)) {\n const style = window.getComputedStyle(ancestor);\n const horizontal = /^(auto|scroll)$/.test(style.overflowX) && ancestor.scrollWidth > ancestor.clientWidth;\n const vertical = /^(auto|scroll)$/.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight;\n if (!horizontal && !vertical) continue;\n const box = ancestor.getBoundingClientRect();\n const left = Math.max(0, box.left + ancestor.clientLeft);\n const top = Math.max(0, box.top + ancestor.clientTop);\n const right = Math.min(window.innerWidth, box.left + ancestor.clientLeft + ancestor.clientWidth);\n const bottom = Math.min(window.innerHeight, box.top + ancestor.clientTop + ancestor.clientHeight);\n if (right <= left || bottom <= top) continue;\n const x = (left + right) / 2;\n const y = (top + bottom) / 2;\n const dx = horizontal && (target.left < left || target.right > right) ? centerX - x : 0;\n const dy = vertical && (target.top < top || target.bottom > bottom) ? centerY - y : 0;\n if (dx === 0 && dy === 0) continue;\n const hit = hitAt(document, x, y);\n if (hit !== null && (hit === ancestor || ancestor.contains(hit))) return {\n x,\n y,\n dx,\n dy\n };\n }\n const dx = target.left < 0 || target.right > window.innerWidth ? centerX - window.innerWidth / 2 : 0;\n const dy = target.top < 0 || target.bottom > window.innerHeight ? centerY - window.innerHeight / 2 : 0;\n return dx === 0 && dy === 0 ? null : {\n x: window.innerWidth / 2,\n y: window.innerHeight / 2,\n dx,\n dy\n };\n };\n return {\n controlOf,\n details,\n hitAt,\n hrefAttribute,\n linkOf,\n point,\n receives,\n scrollPlan,\n within\n };\n };\n //#endregion\n //#region src/internal/matching.ts\n const match = () => {\n /**\n * How names, text and context compare: one Unicode form, without invisible format characters,\n * spaces collapsed, and case folded upper first, so that \"ß\" and \"SS\" read the same.\n */\n const normalize = (value) => value.normalize(\"NFKC\").replace(/\\p{Cf}/gu, \"\").replace(/\\s+/g, \" \").trim().toUpperCase().toLowerCase();\n /** A string that reads the same, or, unless `whole`, appears within; or a pattern found within. */\n const rule = (wanted, whole) => {\n if (typeof wanted !== \"string\") {\n const found = new RegExp(wanted.source, wanted.flags.replace(/[gy]/g, \"\"));\n return (value) => found.test(value.replace(/\\s+/g, \" \").trim());\n }\n const target = normalize(wanted);\n return whole ? (value) => normalize(value) === target : (value) => normalize(value).includes(target);\n };\n /** Whether a value's words appear, whole and in order, among a text's: \"BTC\" not in \"WBTC\". */\n const holds = (text, value) => ` ${normalize(text)} `.includes(` ${normalize(value)} `);\n /** Whether a candidate meets every rule a query gives; a rule left out always holds. */\n const compile = (request) => {\n const role = request.role === null ? null : normalize(request.role);\n const name = request.name === null ? null : rule(request.name, true);\n const text = request.text === null ? null : rule(request.text, false);\n const { near } = request;\n return (candidate) => {\n if (role !== null && normalize(candidate.role ?? \"\") !== role) return false;\n if (text !== null && !text(candidate.text())) return false;\n if (name !== null && !name(candidate.name())) return false;\n if (near === null) return true;\n const { row, column, label, heading } = candidate.context();\n return [\n row,\n column,\n label,\n heading\n ].some((value) => value !== void 0 && holds(value, near));\n };\n };\n /** A comparison token for ordered observations, without retaining their text. */\n const mark = (observations) => {\n let hash = 2166136261;\n for (const shown of observations) for (let index = 0; index < shown.length; index++) hash = Math.imul(hash ^ shown.charCodeAt(index), 16777619);\n return `${observations.length}:${(hash >>> 0).toString(16)}`;\n };\n return {\n compile,\n holds,\n normalize,\n mark\n };\n };\n //#endregion\n //#region src/internal/reading/context.inpage.ts\n const context = (names, walked) => {\n const { clean, isButton, isDocument, isHtml, isInput, isRoot } = names;\n const { isSelect, isTextArea, roleOf, textOf } = names;\n const { visible } = walked;\n const known = () => ({\n headers: /* @__PURE__ */ new Map(),\n headings: /* @__PURE__ */ new Map()\n });\n const unspoken = \"button,select,textarea,option,script,style,noscript,template,[role=button],[role=menuitem],[role=option],[role=tab],[role=switch],[role=checkbox],[role=radio],[aria-hidden=true]\";\n const groups = \"tr,li,article,fieldset,form,section,dialog,[role=row],[role=listitem],[role=group],[role=region],[role=dialog],[role=alertdialog]\";\n /** The visible text just before (or after) a target within `scope`, nearest kept, ≤120 characters. */\n const textBeside = (target, scope, backwards) => {\n const walker = target.ownerDocument.createTreeWalker(scope, NodeFilter.SHOW_TEXT);\n const labels = isInput(target) || isTextArea(target) || isSelect(target) || isButton(target) ? Array.from(target.labels ?? []) : [];\n let text = \"\";\n walker.currentNode = target;\n for (let steps = 0; steps < 400 && text.replace(/\\s+/g, \"\").length < 120; steps++) {\n const node = backwards ? walker.previousNode() : walker.nextNode();\n if (node === null) break;\n const parent = node.parentElement;\n if (parent === null || target.contains(parent) || parent.closest(unspoken) !== null || isHtml(parent) && parent.isContentEditable || labels.some((label) => label.contains(parent)) || !visible(parent)) continue;\n text = backwards ? `${node.textContent ?? \"\"} ${text}` : `${text} ${node.textContent ?? \"\"}`;\n }\n const words = text.replace(/\\s+/g, \" \").trim();\n return words.length <= 120 ? words : backwards ? `…${words.slice(-119).trimStart()}` : `${words.slice(0, 119).trimEnd()}…`;\n };\n /** The nearest visible heading before `target` in tree order, within `scope`. */\n const headingBefore = (target, scope, read = known()) => {\n let headings = read.headings.get(scope);\n if (headings === void 0) {\n headings = Array.from(scope.querySelectorAll(\"h1,h2,h3,h4,h5,h6,[role=heading]\")).filter((element) => roleOf(element) === \"heading\");\n read.headings.set(scope, headings);\n }\n for (const heading of headings.toReversed()) {\n if ((heading.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING) === 0) continue;\n const text = visible(heading) ? clean(textOf(heading), 120) : \"\";\n if (text !== \"\") return text;\n }\n };\n /** Whether an element is pinned to the viewport, where the markup around it says nothing. */\n const pinned = (element) => {\n if (!isHtml(element)) return false;\n let top = element;\n while (top.offsetParent !== null && isHtml(top.offsetParent)) top = top.offsetParent;\n return top !== element.ownerDocument.body && top !== element.ownerDocument.documentElement && getComputedStyle(top).position === \"fixed\";\n };\n const span = (cell) => Math.max(1, Number(cell.getAttribute(\"colspan\")) || 1);\n const tables = \"table,[role=table],[role=grid],[role=treegrid]\";\n /** A cell's row and column names, or nothing when it is not in a table with either. */\n const tableContext = (cell, read) => {\n const row = cell.closest(\"tr,[role=row]\");\n const table = row?.closest(tables);\n if (row === null || row === void 0 || table === null || table === void 0) return {};\n let header = read.headers.get(table);\n if (header === void 0) {\n const first = table.querySelector(\"thead tr, tr:has(> th), [role=row]:has(> [role=columnheader])\");\n header = first?.closest(tables) === table ? first : null;\n read.headers.set(table, header);\n }\n if (row === header) return {};\n const cells = Array.from(row.children);\n const index = cells.indexOf(cell);\n const lettered = (other) => /\\p{L}/u.test(textOf(other));\n const named = cells.find((other) => other.matches(\"th,[role=rowheader]\") && lettered(other)) ?? cells.find((other) => other !== cell && lettered(other));\n let left = cells.slice(0, index).reduce((sum, other) => sum + span(other), 0);\n const over = index === -1 || header === null ? void 0 : Array.from(header.children).find((candidate) => (left -= span(candidate)) < 0);\n return {\n row: named === void 0 || named === cell ? void 0 : clean(textOf(named), 60) || void 0,\n column: over === void 0 ? void 0 : clean(textOf(over), 60) || void 0\n };\n };\n /** Where text around an element is read: its dialog, else its own tree, never across a shadow root. */\n const treeOf = (element) => {\n const root = element.getRootNode();\n return element.closest(\"dialog,[role=dialog],[role=alertdialog]\") ?? (isDocument(root) ? root.body ?? root : isRoot(root) ? root : element.ownerDocument);\n };\n /** The words around an element that say which one it is. */\n const contextOf = (element, read = known()) => {\n const cell = element.closest(\"td,th,[role=cell],[role=gridcell],[role=rowheader],[role=columnheader]\");\n const table = cell === null ? {} : tableContext(cell, read);\n const parent = element.parentElement;\n const scope = element.closest(groups) ?? (parent === null || parent === element.ownerDocument.body || parent.tagName === \"HTML\" ? void 0 : parent);\n const beside = table.row !== void 0 || table.column !== void 0 || scope === void 0 ? \"\" : textBeside(element, scope, true);\n const heading = pinned(element) ? void 0 : headingBefore(element, treeOf(element), read);\n return {\n ...table,\n label: beside.length > 40 ? `…${beside.slice(-39).trimStart()}` : beside || void 0,\n heading: heading === void 0 ? void 0 : clean(heading, 60)\n };\n };\n return {\n contextOf,\n groups,\n headingBefore,\n known,\n textBeside,\n treeOf\n };\n };\n //#endregion\n //#region src/internal/reading/controls.inpage.ts\n const controls = (names, subjects, texts) => {\n const { clean, isInput, isSelect, isTextArea, refFor, textEntry } = names;\n const { stateOf } = subjects;\n const { shown } = texts;\n const states = (element, role) => {\n const { level, ...flags } = stateOf(element, role);\n const held = Object.entries(flags).flatMap(([name, value]) => value === true ? [name] : []);\n return [...level === void 0 ? [] : [`level=${level}`], ...held].map((name) => ` [${name}]`).join(\"\");\n };\n const valueOf = (element) => {\n if (isSelect(element)) {\n const selected = Array.from(element.selectedOptions, (option) => clean(option.text, 40));\n const options = Array.from(element.options).slice(0, 12).map((option) => clean(option.text, 40));\n const more = element.options.length > 12 ? ` +${element.options.length - 12} more` : \"\";\n return ` value=${JSON.stringify(selected.join(\", \"))} options=${JSON.stringify(options.join(\" | \") + more)}`;\n }\n const value = isInput(element) || isTextArea(element) ? shown(element, true) : void 0;\n return value === void 0 || value === \"\" ? \"\" : ` value=${JSON.stringify(clean(value, 80))}`;\n };\n /** A control as a value, as its outline line shows it. */\n const controlOf = (element, role, kind, name) => {\n const { disabled, checked } = stateOf(element, role);\n const select = isSelect(element) ? element : void 0;\n const value = select !== void 0 ? Array.from(select.selectedOptions, (option) => clean(option.text, 80)).join(\", \") : isInput(element) || isTextArea(element) ? clean(shown(element, true), 200) : \"\";\n const editable = textEntry(element);\n return {\n ref: refFor(element),\n kind,\n name,\n value,\n ...select === void 0 ? {} : {\n options: Array.from(select.options).slice(0, 64).map((option) => clean(option.text, 80)),\n optionCount: select.options.length\n },\n ...disabled ? { disabled } : {},\n ...checked === void 0 ? {} : { checked },\n ...editable ? { editable } : {}\n };\n };\n /**\n * The elements a selector matches, each read whole, so one inside another that matched is left\n * to it; or why the selector is not CSS.\n */\n const rootsOf = (selector) => {\n let matched;\n try {\n matched = Array.from(document.querySelectorAll(selector));\n } catch {\n return { invalid: `${JSON.stringify(selector)} is not a CSS selector` };\n }\n return matched.filter((root) => !matched.some((other) => other !== root && other.contains(root)));\n };\n return {\n controlOf,\n rootsOf,\n states,\n valueOf\n };\n };\n //#endregion\n //#region src/internal/reading/expect.inpage.ts\n const expectations = (names, subjected, matching) => {\n const { isInput, isSelect, isTextArea, roleOf, textOf } = names;\n const { elementsOf, stateOf } = subjected;\n const markOf = (elements) => matching.mark(elements.map((element) => {\n const { focused: _focused, ...state } = stateOf(element, roleOf(element));\n const value = isInput(element) || isSelect(element) || isTextArea(element) ? element.value : \"\";\n return `${textOf(element)}\\u0000${value}\\u0000${JSON.stringify(state)}\\u0001`;\n }));\n /**\n * What `find` matches, looked at every 100 ms until `want` holds of it or `millis` have passed,\n * with its mark then. It gives no refs.\n */\n const until = async (request, want, millis) => {\n const deadline = performance.now() + millis;\n for (;;) {\n const elements = elementsOf(request);\n if (\"invalid\" in elements) return elements;\n const mark = markOf(elements);\n const met = want === \"some\" ? elements.length > 0 : want === \"none\" ? elements.length === 0 : mark !== want.other;\n const left = deadline - performance.now();\n if (met || left <= 0) return {\n met,\n mark\n };\n const { promise, resolve } = Promise.withResolvers();\n setTimeout(resolve, Math.min(100, left));\n await promise;\n }\n };\n return { until };\n };\n //#endregion\n //#region src/internal/reading/layout.inpage.ts\n const layout = (names, walked, subjected, matching, placing) => {\n const { isDisabled, isOwn, nameOf, refFor, roleOf, textOf } = names;\n const { boxOf, inView, visible } = walked;\n const most = 200;\n const area = (element) => {\n const { width, height } = element.getBoundingClientRect();\n return width * height;\n };\n const chosen = (elements, choose) => choose === \"first\" ? elements[0] : choose === \"last\" ? elements.at(-1) : elements.reduce((best, element) => best === void 0 || (choose === \"smallest\" ? area(element) < area(best) : area(element) > area(best)) ? element : best, void 0);\n const fixed = (element) => {\n for (let at = element; at !== null; at = at.parentElement) if (getComputedStyle(at).position === \"fixed\") return true;\n return false;\n };\n const words = (element, wanted, dx, dy) => {\n const parts = [];\n let text = \"\";\n const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_TEXT);\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n parts.push({\n node,\n start: text.length\n });\n text += node.nodeValue ?? \"\";\n }\n const pattern = typeof wanted === \"string\" ? new RegExp(wanted.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"), \"giu\") : new RegExp(wanted.source, wanted.flags.replace(/[gy]/g, \"\") + \"g\");\n const at = (index, end) => {\n const part = parts.findLast(({ start }) => end ? start < index : start <= index) ?? parts[0];\n return part === void 0 ? [element, 0] : [part.node, index - part.start];\n };\n const found = [];\n for (const match of text.matchAll(pattern)) {\n if (found.length === most) break;\n if (match[0] === \"\") continue;\n const range = element.ownerDocument.createRange();\n range.setStart(...at(match.index, false));\n range.setEnd(...at(match.index + match[0].length, true));\n const { x, y, width, height } = range.getBoundingClientRect();\n if (width > 0 || height > 0) found.push({\n text: match[0],\n box: {\n x: x + dx,\n y: y + dy,\n width,\n height\n }\n });\n }\n return found;\n };\n const selected = (pick) => {\n let elements;\n try {\n elements = Array.from(document.querySelectorAll(pick.selector));\n } catch {\n return { invalid: `${JSON.stringify(pick.selector)} is not a CSS selector` };\n }\n const rules = matching.compile(pick);\n return elements.filter((element) => {\n const role = roleOf(element, pick.role !== null);\n const box = boxOf(element);\n return !isOwn(element) && box.width * box.height > 0 && visible(element) && (pick.scope === \"document\" || inView(new DOMRect(box.x, box.y, box.width, box.height))) && (pick.state !== \"enabled\" || !isDisabled(element)) && rules({\n role,\n name: () => nameOf(element, role),\n text: () => textOf(element),\n context: () => placing.contextOf(element)\n });\n });\n };\n const read = (picks) => {\n const places = [];\n const missing = [];\n for (const pick of picks) {\n const elements = pick.selector === null ? subjected.elementsOf(pick) : selected({\n ...pick,\n selector: pick.selector\n });\n if (\"invalid\" in elements) return { invalid: `${pick.id}: ${elements.invalid}` };\n const element = chosen(elements, pick.choose);\n if (element === void 0) {\n missing.push(pick.id);\n continue;\n }\n const role = roleOf(element, pick.role !== null);\n const box = boxOf(element);\n const own = element.getBoundingClientRect();\n places.push({\n id: pick.id,\n ref: refFor(element),\n subject: {\n role,\n name: nameOf(element, role),\n tag: element.tagName.toLowerCase(),\n context: placing.contextOf(element)\n },\n box,\n fixed: fixed(element),\n words: pick.words === null ? void 0 : words(element, pick.words, box.x - own.x, box.y - own.y)\n });\n }\n return { layout: {\n url: location.href,\n viewport: {\n width: innerWidth,\n height: innerHeight\n },\n scroll: {\n x: scrollX,\n y: scrollY\n },\n scale: devicePixelRatio,\n places,\n missing\n } };\n };\n return { read };\n };\n //#endregion\n //#region src/internal/reading/names.inpage.ts\n const elements = () => {\n const isInput = (element) => element.tagName === \"INPUT\";\n const isTextArea = (element) => element.tagName === \"TEXTAREA\";\n const isSelect = (element) => element.tagName === \"SELECT\";\n const isFrame = (element) => element.tagName === \"IFRAME\";\n const isHtml = (element) => \"innerText\" in element;\n const isButton = (element) => element.tagName === \"BUTTON\";\n const isLabel = (element) => element.tagName === \"LABEL\";\n const textOf = (element) => isHtml(element) ? element.innerText : element.textContent ?? \"\";\n const isElement = (node) => node.nodeType === Node.ELEMENT_NODE;\n const isDocument = (node) => node.nodeType === Node.DOCUMENT_NODE;\n /** The native fields and editable regions that can receive typed text. */\n const textEntry = (element) => isInput(element) && ![\n \"button\",\n \"reset\",\n \"submit\",\n \"image\",\n \"checkbox\",\n \"radio\",\n \"file\",\n \"range\",\n \"color\",\n \"hidden\"\n ].includes(element.type) || isTextArea(element) || isHtml(element) && element.isContentEditable;\n const own = /* @__PURE__ */ new WeakSet();\n const adopt = (node) => own.add(node);\n /** Whether a node is the library's own, or inside a shadow root of one of its own. */\n const isOwn = (node) => {\n const root = node.getRootNode();\n return own.has(node) || root instanceof ShadowRoot && own.has(root.host);\n };\n const clean = (value, max = 160) => {\n const text = (value ?? \"\").replace(/\\s+/g, \" \").trim();\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n };\n return {\n adopt,\n clean,\n isInput,\n isTextArea,\n isSelect,\n isFrame,\n isHtml,\n isButton,\n isLabel,\n textOf,\n isElement,\n isDocument,\n isOwn,\n textEntry\n };\n };\n const names = (native) => {\n const { clean, isInput, isTextArea, isSelect, isFrame, textOf, isElement } = native;\n const byElement = /* @__PURE__ */ new WeakMap();\n const byRef = /* @__PURE__ */ new Map();\n const refs = { next: 1 };\n const interactiveRoles = new Set(\"button link checkbox radio tab menuitem menuitemcheckbox menuitemradio option switch slider combobox listbox textbox searchbox spinbutton treeitem\".split(\" \"));\n const containers = {\n HEADER: \"banner\",\n NAV: \"navigation\",\n MAIN: \"main\",\n ASIDE: \"complementary\",\n FOOTER: \"contentinfo\",\n FORM: \"form\",\n DIALOG: \"dialog\"\n };\n const valueRoles = new Set(\"combobox listbox option textbox searchbox spinbutton slider\".split(\" \"));\n /**\n * A label's own words, without the options or values of the controls inside it, native or\n * scripted, such as the custom select Browserbase puts in place of a native one.\n */\n const labelText = (label) => {\n let text = \"\";\n const collect = (node) => {\n for (const child of Array.from(node.childNodes)) if (child.nodeType === Node.TEXT_NODE) text += child.textContent ?? \"\";\n else if (isElement(child) && ![\n \"SELECT\",\n \"TEXTAREA\",\n \"INPUT\",\n \"SCRIPT\",\n \"STYLE\"\n ].includes(child.tagName) && !valueRoles.has(roleOf(child) ?? \"\")) collect(child);\n };\n collect(label);\n return text;\n };\n const roleOf = (element, structural = false) => {\n const explicit = element.getAttribute(\"role\");\n if (explicit !== null && explicit.trim() !== \"\") return explicit.trim().split(/\\s+/)[0] ?? null;\n const tag = element.tagName;\n if (tag === \"A\") return element.hasAttribute(\"href\") ? \"link\" : null;\n if (tag === \"BUTTON\" || tag === \"SUMMARY\") return \"button\";\n if (isSelect(element)) return element.multiple ? \"listbox\" : \"combobox\";\n if (tag === \"TEXTAREA\") return \"textbox\";\n if (isInput(element)) {\n const type = element.type;\n if (type === \"hidden\" || type === \"color\" || type === \"file\") return null;\n if (type === \"checkbox\" || type === \"radio\") return type;\n if (type === \"range\") return \"slider\";\n if (type === \"number\") return \"spinbutton\";\n if (type === \"search\") return \"searchbox\";\n if (type === \"button\" || type === \"submit\" || type === \"reset\" || type === \"image\") return \"button\";\n return \"textbox\";\n }\n if (/^H[1-6]$/.test(tag)) return \"heading\";\n if (tag === \"IMG\") return \"img\";\n if (tag === \"CANVAS\") return \"canvas\";\n if (tag === \"IFRAME\") return \"iframe\";\n if (element.getAttribute(\"contenteditable\") === \"true\") return \"textbox\";\n if (structural) {\n if (tag === \"TH\") return element.getAttribute(\"scope\") === \"row\" ? \"rowheader\" : \"columnheader\";\n const roles = {\n TABLE: \"table\",\n TR: \"row\",\n TD: \"cell\",\n TBODY: \"rowgroup\",\n THEAD: \"rowgroup\",\n TFOOT: \"rowgroup\",\n UL: \"list\",\n OL: \"list\",\n MENU: \"list\",\n LI: \"listitem\"\n };\n if (roles[tag] !== void 0) return roles[tag];\n }\n return containers[tag] ?? null;\n };\n const nameOf = (element, role) => {\n const labelledBy = element.getAttribute(\"aria-labelledby\");\n if (labelledBy !== null) {\n const text = labelledBy.split(/\\s+/).map((id) => {\n const labelling = element.ownerDocument.getElementById(id);\n return labelling === null ? \"\" : labelText(labelling);\n }).join(\" \");\n if (clean(text) !== \"\") return clean(text);\n }\n const label = element.getAttribute(\"aria-label\");\n if (label !== null && clean(label) !== \"\") return clean(label);\n if (isInput(element) || isTextArea(element) || isSelect(element)) {\n const labels = element.labels === null ? \"\" : Array.from(element.labels, labelText).join(\" \");\n if (clean(labels) !== \"\") return clean(labels);\n if (isInput(element) && (element.type === \"button\" || element.type === \"submit\" || element.type === \"reset\")) return clean(element.value);\n return clean(element.getAttribute(\"placeholder\") ?? element.getAttribute(\"title\") ?? element.getAttribute(\"name\"));\n }\n if (role === \"img\") return clean(element.getAttribute(\"alt\") ?? element.getAttribute(\"title\"));\n if (role === \"iframe\") return clean(element.getAttribute(\"title\") ?? element.getAttribute(\"name\"));\n if (role === null || interactiveRoles.has(role) || role === \"heading\") {\n const text = isSecret(element) ? \"\" : clean(textOf(element), 120);\n if (text !== \"\") return text;\n const titled = element.querySelector(\"[title],img[alt],svg title\");\n const fallback = titled === null ? null : titled.tagName === \"IMG\" ? titled.getAttribute(\"alt\") : titled.tagName.toLowerCase() === \"title\" ? titled.textContent : titled.getAttribute(\"title\");\n return clean(element.getAttribute(\"title\") ?? fallback);\n }\n return \"\";\n };\n const isDisabled = (element) => element.matches(\":disabled\") || element.getAttribute(\"aria-disabled\") === \"true\";\n const refFor = (element) => {\n const known = byElement.get(element);\n if (known !== void 0 && byRef.get(known)?.deref() === element) return known;\n const ref = `e${refs.next++}`;\n byElement.set(element, ref);\n byRef.set(ref, new WeakRef(element));\n return ref;\n };\n const lookup = (ref) => {\n const element = byRef.get(ref)?.deref();\n return element !== void 0 && element.isConnected && inCurrentDocument(element) ? element : void 0;\n };\n const describe = (element) => {\n const id = element.id === \"\" ? \"\" : `#${element.id}`;\n const name = clean(nameOf(element, roleOf(element)), 40);\n return `<${element.tagName.toLowerCase()}${id}>${name === \"\" ? \"\" : ` \"${name}\"`}`;\n };\n const isRoot = (node) => node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n const parentOf = (element) => {\n const root = element.getRootNode();\n return element.parentElement ?? (isRoot(root) && \"host\" in root ? root.host : null);\n };\n const activeElement = () => {\n let active = document.activeElement;\n while (active !== null) {\n const inner = active.shadowRoot?.activeElement ?? (isFrame(active) ? active.contentDocument?.activeElement : null);\n if (inner === null || inner === void 0 || inner === active) return active;\n active = inner;\n }\n return null;\n };\n const inCurrentDocument = (element) => {\n let owner = element.ownerDocument;\n while (owner !== document) {\n const frame = owner.defaultView?.frameElement;\n if (frame === null || frame === void 0 || !frame.isConnected || isFrame(frame) && frame.contentDocument !== owner) return false;\n owner = frame.ownerDocument;\n }\n return true;\n };\n const secretToken = /(?:^|\\s)(?:current-password|new-password|one-time-code|cc-number|cc-csc|cc-exp(?:-month|-year)?)(?=\\s|$)/i;\n const secrets = /* @__PURE__ */ new WeakSet();\n /**\n * A field the DOM marks as secret, now or before: by its type, its autocomplete tokens, or a\n * style that shows dots for what it holds, as a PIN field may.\n */\n const isSecret = (element) => {\n if (isInput(element) && element.type === \"password\" || secretToken.test(element.getAttribute(\"autocomplete\") ?? \"\") || (isInput(element) || isTextArea(element)) && !/^(none)?$/.test(getComputedStyle(element).getPropertyValue(\"-webkit-text-security\"))) secrets.add(element);\n return secrets.has(element);\n };\n return {\n ...native,\n activeElement,\n containers,\n describe,\n inCurrentDocument,\n interactiveRoles,\n isDisabled,\n isRoot,\n isSecret,\n lookup,\n nameOf,\n parentOf,\n refFor,\n refs,\n roleOf\n };\n };\n //#endregion\n //#region src/internal/reading/outline.inpage.ts\n const outline = (names, walked, subjects, texts, controlling, url) => {\n const { clean, containers, isFrame, nameOf, refFor, roleOf, textOf } = names;\n const { visit } = walked;\n const { isControl } = subjects;\n const { cut } = texts;\n const textBlocks = /^(?:P|LI|TD|TH|DT|DD|LABEL|SPAN|BLOCKQUOTE|FIGCAPTION|CAPTION|PRE|STRONG|EM|B|I|SMALL|TIME|CODE|LEGEND)$/;\n const nested = \"a[href],button,input,select,textarea,summary,[role],[onclick],[tabindex],[contenteditable],canvas,iframe\";\n const noise = /^[\\s|•·\\-–—,.:;()[\\]{}\"'/\\\\]*$/;\n /** Text inside a control's label is already that control's name. */\n const inControlLabel = (element) => {\n const label = element.closest(\"label\");\n return label !== null && label.control !== null;\n };\n const hrefOf = (element) => {\n if (element.tagName !== \"A\") return \"\";\n const raw = element.getAttribute(\"href\") ?? \"\";\n if (raw === \"\" || raw.startsWith(\"javascript:\")) return \"\";\n try {\n const { origin, href } = new URL(raw, element.ownerDocument.baseURI);\n const reported = url.redact(href);\n const own = origin === location.origin && reported.startsWith(origin);\n return ` -> ${clean(own ? reported.slice(origin.length) : reported, 80)}`;\n } catch {\n return \"\";\n }\n };\n const snapshot = (request) => {\n const roots = request.within === null ? [null] : controlling.rootsOf(request.within);\n if (\"invalid\" in roots) return roots;\n const width = window.innerWidth;\n const height = window.innerHeight;\n const query = request.query === null ? null : request.query.toLowerCase();\n const lines = [];\n const controls = [];\n let above = 0;\n let below = 0;\n const placement = (rect) => {\n if (request.full) return \"in\";\n if (rect.bottom <= 0) return \"above\";\n if (rect.top >= height) return \"below\";\n if (rect.right <= 0 || rect.left >= width) return \"aside\";\n return \"in\";\n };\n const count = (rect) => {\n const where = placement(rect);\n if (where === \"above\") above++;\n if (where === \"below\") below++;\n return where;\n };\n const emit = (depth, line, rect) => {\n if (count(rect) !== \"in\") return false;\n if (query !== null && !line.toLowerCase().includes(query)) return false;\n lines.push(`${\" \".repeat(Math.min(depth, 8))}- ${line}`);\n return true;\n };\n const control = (element, rect, role, depth) => {\n const name = nameOf(element, role);\n const kind = role ?? \"clickable\";\n const box = request.boxes || role === \"canvas\" || role === \"iframe\" ? ` ${Math.round(rect.width)}x${Math.round(rect.height)} at (${Math.round(rect.x)},${Math.round(rect.y)})` : \"\";\n const line = placement(rect) === \"in\" ? `${kind}${name === \"\" ? \"\" : ` ${JSON.stringify(name)}`} [ref=${refFor(element)}]${controlling.states(element, role)}${controlling.valueOf(element)}${hrefOf(element)}${box}` : kind;\n if (emit(depth, line, rect)) controls.push(controlling.controlOf(element, role, kind, name));\n if (isFrame(element)) {\n const body = element.contentDocument?.body;\n if ((body === null || body === void 0) && placement(rect) === \"in\") lines.push(`${\" \".repeat(Math.min(depth + 1, 8))}- (another site's frame: use a screenshot and coordinates)`);\n return {\n depth: depth + 1,\n insidePointer: false,\n controls: false\n };\n }\n if ([\n \"INPUT\",\n \"SELECT\",\n \"TEXTAREA\",\n \"CANVAS\",\n \"IMG\"\n ].includes(element.tagName)) return void 0;\n return {\n depth: depth + 1,\n insidePointer: true,\n controls: true\n };\n };\n const enter = (element, style, rect, { depth, insidePointer }) => {\n const role = roleOf(element);\n if (isControl(element, role, style, rect, insidePointer)) return control(element, rect, role, depth);\n if (role === \"heading\") {\n emit(depth, `heading ${JSON.stringify(nameOf(element, role))}${controlling.states(element, role)}`, rect);\n return;\n }\n if (role === \"img\") {\n const alt = nameOf(element, role);\n if (alt !== \"\") emit(depth, `img ${JSON.stringify(alt)}`, rect);\n return;\n }\n let inner = depth;\n if (role !== null && (containers[element.tagName] !== void 0 || role === \"dialog\")) {\n const label = element.getAttribute(\"aria-label\");\n if (emit(depth, `${role}${label === null ? \"\" : ` ${JSON.stringify(clean(label))}`}:`, rect)) inner = depth + 1;\n }\n if (textBlocks.test(element.tagName) && element.querySelector(nested) === null) {\n if (inControlLabel(element)) return void 0;\n const text = clean(textOf(element), 300);\n if (text !== \"\" && !noise.test(text)) emit(inner, `text: ${text}`, rect);\n return;\n }\n let own = \"\";\n for (const node of Array.from(element.childNodes)) if (node.nodeType === Node.TEXT_NODE) own += node.textContent ?? \"\";\n own = clean(own, 300);\n if (own !== \"\" && !noise.test(own) && !inControlLabel(element)) emit(inner, `text: ${own}`, rect);\n return {\n depth: inner,\n insidePointer: insidePointer || style.cursor === \"pointer\",\n controls: false\n };\n };\n const visitor = {\n enter,\n admit: (child, place) => !place.controls || child.matches(nested) || child.querySelector(nested) !== null,\n outside: count\n };\n for (const root of roots) visit(root, !request.full, {\n depth: 0,\n insidePointer: false,\n controls: false\n }, visitor);\n const outlined = cut(lines.join(\"\\n\"), request.maxChars);\n return { snapshot: {\n ...outlined,\n url: location.href,\n title: document.title,\n above,\n below,\n viewport: {\n width,\n height\n },\n scroll: {\n y: Math.round(window.scrollY),\n height: Math.round(document.documentElement.scrollHeight)\n },\n controls: controls.filter((control) => outlined.text.includes(`[ref=${control.ref}]`))\n } };\n };\n const viewport = () => ({\n width: window.innerWidth,\n height: window.innerHeight\n });\n return {\n snapshot,\n viewport\n };\n };\n //#endregion\n //#region src/internal/reading/ready.inpage.ts\n const ready = (walked, texts, kept) => {\n const { inView, visible } = walked;\n let copy;\n const boxed = (element) => {\n const rect = element.getBoundingClientRect();\n return rect.width * rect.height > 0 && inView(rect);\n };\n const showing = (elements) => Array.from(elements).filter((element) => boxed(element) && visible(element));\n const drawn = (canvas) => {\n copy ??= new OffscreenCanvas(32, 32).getContext(\"2d\", { willReadFrequently: true });\n if (copy === null) return true;\n try {\n copy.clearRect(0, 0, 32, 32);\n copy.imageSmoothingQuality = \"high\";\n copy.drawImage(canvas, 0, 0, 32, 32);\n return new Uint32Array(copy.getImageData(0, 0, 32, 32).data.buffer).some((pixel) => pixel !== 0);\n } catch {\n return true;\n }\n };\n const content = () => showing(document.querySelectorAll(\"video, iframe, embed, object\")).length > 0 || showing(document.querySelectorAll(\"img, svg\")).some((picture) => {\n const { width, height } = picture.getBoundingClientRect();\n return width > 64 && height > 64;\n }) || (texts.read({\n ref: null,\n maxChars: 1,\n unmask: false\n })?.text ?? \"\") !== \"\" || showing(document.querySelectorAll(\"canvas\")).some(drawn);\n const painted = () => {\n const { promise, resolve } = Promise.withResolvers();\n if (document.visibilityState === \"hidden\") resolve(false);\n else requestAnimationFrame(() => resolve(true));\n return promise;\n };\n const check = (quietMillis, clock) => painted().then((paints) => {\n const waiting = [];\n const held = clock !== null && !document.dispatchEvent(new CustomEvent(clock, {\n detail: { op: \"holds\" },\n cancelable: true\n }));\n if (document.readyState === \"loading\") waiting.push(\"load\");\n if (!paints) waiting.push(\"paint\");\n if (document.getAnimations().some((animation) => {\n const effect = animation.effect;\n return (animation.playState === \"running\" || held && animation.playState === \"paused\") && effect !== null && Number.isFinite(effect.getComputedTiming().endTime) && \"target\" in effect && effect.target instanceof Element && boxed(effect.target);\n })) waiting.push(\"animations\");\n if (Array.from(document.images).some((image) => !image.complete && boxed(image))) waiting.push(\"images\");\n if (document.fonts.status !== \"loaded\") waiting.push(\"fonts\");\n if (showing(document.querySelectorAll(\"[aria-busy=true]\")).length > 0) waiting.push(\"busy\");\n if (!content()) waiting.push(\"content\");\n if (kept.changing() > performance.timeOrigin + performance.now() - quietMillis) waiting.push(\"changing\");\n return waiting;\n });\n /**\n * Check until the page is ready, or for `millis`, and say what it is still waiting for; with\n * `quietMillis`, until nothing the record saw in view has changed for that long, too.\n */\n const wait = async (millis, quietMillis = 0, clock = null) => {\n const until = performance.now() + millis;\n for (;;) {\n const waiting = await check(quietMillis, clock);\n if (waiting.length === 0 || performance.now() >= until) return waiting;\n const { promise, resolve } = Promise.withResolvers();\n setTimeout(resolve, Math.min(50, until - performance.now()));\n await promise;\n }\n };\n /**\n * One task, then a frame: what the page's handlers for input did at once has run, a navigation\n * one of them started in a timer has been asked for, and their effect has painted. Says whether\n * the page painted, which a hidden one does not.\n */\n const settle = () => {\n const { promise, resolve } = Promise.withResolvers();\n setTimeout(resolve, 0);\n return promise.then(painted);\n };\n return {\n wait,\n settle\n };\n };\n //#endregion\n //#region src/internal/reading/subjects.inpage.ts\n const states = (names) => (element, role) => {\n const { isDisabled, isInput } = names;\n const given = (attribute) => {\n const value = element.getAttribute(attribute);\n return value === \"true\" || (value === \"false\" ? false : void 0);\n };\n const checkable = element.hasAttribute(\"aria-checked\") || [\n \"checkbox\",\n \"radio\",\n \"switch\",\n \"menuitemcheckbox\",\n \"menuitemradio\"\n ].includes(role ?? \"\");\n return {\n disabled: isDisabled(element),\n checked: checkable ? isInput(element) && element.checked || element.getAttribute(\"aria-checked\") === \"true\" : void 0,\n expanded: given(\"aria-expanded\"),\n selected: given(\"aria-selected\"),\n pressed: given(\"aria-pressed\"),\n focused: element.ownerDocument.activeElement === element,\n level: role === \"heading\" ? Number(element.getAttribute(\"aria-level\")) || Number(/^H([1-6])$/.exec(element.tagName)?.[1]) || 2 : void 0\n };\n };\n const subjects = (names, walked, matching, placing, stateOf) => {\n const { isDisabled, nameOf, refFor, roleOf, textOf } = names;\n const { acts, boxOf, controlOf, hitAt, inView } = walked;\n const { contextOf, known } = placing;\n /** What the outline lists as a control, with a ref: something a person would act on. */\n const isControl = (element, role, style, rect, insidePointer) => acts(element, role) || style.cursor === \"pointer\" && !insidePointer && rect.width > 0 && rect.height > 0;\n /**\n * The elements in scope that match a query, in tree order. Without text, an element matches\n * when it has a role or is a control. With text, any element can, but text inside a control or\n * heading is that control's or heading's, and an element is left out when one inside it\n * matches too: the smallest element showing the text is found, not each one around it.\n */\n const matched = (request) => {\n const { at } = request;\n const matches = matching.compile(request);\n const byText = request.text !== null;\n const viewport = request.scope === \"viewport\";\n const read = known();\n if (request.selector !== null) try {\n document.querySelector(request.selector);\n } catch {\n return { invalid: `${JSON.stringify(request.selector)} is not a CSS selector` };\n }\n const eligible = (element) => (request.selector === null || element.matches(request.selector)) && (request.state !== \"enabled\" || !isDisabled(element));\n const entries = [];\n const open = [];\n const named = (entry) => entry.name ??= nameOf(entry.element, entry.role);\n const placed = (entry) => entry.context ??= contextOf(entry.element, read);\n const judge = (entry, text) => matches({\n role: entry.role,\n name: () => named(entry),\n text,\n context: () => placed(entry)\n });\n const hit = at === null ? null : hitAt(document, at.x, at.y);\n if (hit !== null) {\n const element = controlOf(hit);\n const { x, y, width, height } = boxOf(element);\n const entry = {\n element,\n rect: new DOMRect(x, y, width, height),\n role: roleOf(element, request.role !== null),\n matched: false\n };\n entry.matched = eligible(element) && judge(entry, () => textOf(element));\n entries.push(entry);\n }\n if (at === null) walked.visit(null, viewport, {\n pointer: false,\n owned: false\n }, {\n enter: (element, style, rect, state) => {\n const role = roleOf(element, request.role !== null);\n const control = isControl(element, role, style, rect, state.pointer);\n const unit = control || role === \"heading\";\n const entry = eligible(element) && (byText ? unit || !state.owned : request.selector !== null || role !== null || control) && (!viewport || inView(rect)) ? {\n element,\n rect,\n role,\n matched: false\n } : void 0;\n if (entry !== void 0) entries.push(entry);\n open.push({\n entry,\n inline: style.display === \"inline\",\n parts: [],\n inside: false\n });\n return {\n pointer: state.pointer || style.cursor === \"pointer\",\n owned: state.owned || unit\n };\n },\n text: byText ? (node) => open.at(-1)?.parts.push(node.textContent ?? \"\") : void 0,\n leave: () => {\n const closed = open.pop();\n const parent = open.at(-1);\n if (closed === void 0) return;\n const { entry } = closed;\n const text = closed.parts.join(\"\");\n if (parent !== void 0) parent.parts.push(closed.inline ? text : ` ${text} `);\n if (entry !== void 0 && !(byText && closed.inside)) entry.matched = judge(entry, () => text);\n if (parent !== void 0) parent.inside ||= closed.inside || entry?.matched === true;\n }\n });\n return {\n entries: entries.filter((entry) => entry.matched),\n named,\n placed\n };\n };\n const find = (request) => {\n const result = matched(request);\n if (result.invalid !== void 0) return { invalid: result.invalid };\n const { entries, named, placed } = result;\n return { found: entries.map((entry) => ({\n ref: refFor(entry.element),\n subject: {\n role: entry.role,\n name: named(entry),\n tag: entry.element.tagName.toLowerCase(),\n context: placed(entry)\n },\n box: {\n x: Math.round(entry.rect.x),\n y: Math.round(entry.rect.y),\n width: Math.round(entry.rect.width),\n height: Math.round(entry.rect.height)\n },\n inViewport: inView(entry.rect),\n state: stateOf(entry.element, entry.role)\n })) };\n };\n /** The elements `find` would find, in tree order, with no refs given. */\n const elementsOf = (request) => {\n const result = matched(request);\n return result.invalid !== void 0 ? { invalid: result.invalid } : result.entries.map((entry) => entry.element);\n };\n return {\n find,\n elementsOf,\n isControl,\n stateOf\n };\n };\n //#endregion\n //#region src/internal/reading/text.inpage.ts\n const text = (names, walked) => {\n const { isHtml, isInput, isSecret, isSelect, isTextArea, lookup } = names;\n const valueless = [\n \"checkbox\",\n \"radio\",\n \"button\",\n \"submit\",\n \"reset\",\n \"image\",\n \"file\"\n ];\n /** What a field holds, or undefined for an element that holds nothing entered. */\n const valueOf = (element) => {\n if (isInput(element)) return valueless.includes(element.type) ? void 0 : element.value;\n if (isTextArea(element)) return element.value;\n if (isSelect(element)) return Array.from(element.selectedOptions, (option) => option.text).join(\", \");\n const parent = element.parentElement;\n return isHtml(element) && element.isContentEditable && !(parent !== null && isHtml(parent) && parent.isContentEditable) ? element.innerText : void 0;\n };\n /** What a field shows: `••••` unless `unmask`, and always for a secret field; \"\" when empty. */\n const shown = (element, unmask) => {\n const value = valueOf(element);\n if (value === void 0 || value.trim() === \"\") return value === void 0 ? void 0 : \"\";\n return unmask && !isSecret(element) ? value : \"••••\";\n };\n /** Lines cut after the last whole line within `max` characters, or at `max` when none is. */\n const cut = (lines, max) => {\n if (lines.length <= max) return {\n text: lines,\n truncated: false\n };\n const end = lines.lastIndexOf(\"\\n\", max);\n return {\n text: lines.slice(0, end > 0 ? end : max),\n truncated: true\n };\n };\n /**\n * What the viewport, or one element whole, shows as text: a line per block, table cells apart by\n * a tab, and each field as `shown` gives it.\n */\n const lines = (root, unmask) => {\n const lines = [];\n let line = \"\";\n const end = () => {\n const words = line.replace(/[^\\S\\t]+/g, \" \").replace(/ ?\\t ?/g, \" \").trim();\n if (words !== \"\") lines.push(words);\n line = \"\";\n };\n walked.visit(root, root === null, false, {\n enter: (element, style) => {\n const { display } = style;\n const value = shown(element, unmask);\n const block = !display.startsWith(\"inline\") && display !== \"contents\" && display !== \"table-cell\";\n if (display === \"table-cell\") line += \" \";\n if (block || element.tagName === \"BR\") end();\n if (value === void 0 && !(isInput(element) && valueless.includes(element.type))) return block;\n const label = isInput(element) && /^(button|submit|reset)$/.test(element.type);\n line += ` ${value ?? (label ? element.value : \"\")} `;\n if (block) end();\n },\n text: (node) => {\n line += node.textContent ?? \"\";\n },\n leave: (_, block) => {\n if (block) end();\n }\n });\n end();\n return lines.join(\"\\n\");\n };\n const read = (request) => {\n const root = request.ref === null ? null : lookup(request.ref);\n return root === void 0 ? null : {\n ...cut(lines(root, request.unmask), request.maxChars),\n url: location.href,\n title: document.title\n };\n };\n return {\n cut,\n lines,\n read,\n shown\n };\n };\n //#endregion\n //#region src/internal/reading/walk.inpage.ts\n const walk = (names) => {\n const { interactiveRoles, isElement, isFrame, isInput, parentOf, roleOf } = names;\n const skipped = new Set(\"SCRIPT STYLE NOSCRIPT TEMPLATE HEAD META LINK SVG\".split(\" \"));\n /** Whether a box, in top-document pixels, meets the viewport. */\n const inView = (rect, width = innerWidth, height = innerHeight) => rect.right > 0 && rect.bottom > 0 && rect.left < width && rect.top < height;\n /** Whether an element reached on its own shows, by the walk's rule and its ancestors'. */\n const visible = (element) => {\n if (element.closest(\"[aria-hidden=true]\") !== null) return false;\n if (element.checkVisibility({\n opacityProperty: true,\n visibilityProperty: true\n })) return true;\n if (getComputedStyle(element).display !== \"contents\") return false;\n for (let node = element; node !== null; node = parentOf(node)) {\n const style = getComputedStyle(node);\n if (style.display === \"none\" || style.opacity === \"0\" || node === element && style.visibility !== \"visible\") return false;\n }\n return true;\n };\n const untransformed = (frame, rect) => {\n if (rect.width !== frame.offsetWidth || rect.height !== frame.offsetHeight) return false;\n let ancestor = frame;\n while (ancestor !== null) {\n const style = (ancestor.ownerDocument.defaultView ?? window).getComputedStyle(ancestor);\n if (style.transform !== \"none\" || style.scale !== \"none\" || style.rotate !== \"none\" || style.perspective !== \"none\" || style.zoom !== \"1\") return false;\n ancestor = parentOf(ancestor);\n }\n return true;\n };\n /** The element painted at a point, inside shadow roots and same-origin frames. */\n const hitAt = (root, x, y) => {\n let hit = root.elementFromPoint(x, y);\n while (hit?.shadowRoot !== null && hit?.shadowRoot !== void 0) {\n const inner = hit.shadowRoot.elementFromPoint(x, y);\n if (inner === null || inner === hit) break;\n hit = inner;\n }\n if (hit !== null && isFrame(hit)) {\n const document = hit.contentDocument;\n if (document !== null) {\n const rect = hit.getBoundingClientRect();\n if (untransformed(hit, rect)) return hitAt(document, x - rect.left - hit.clientLeft, y - rect.top - hit.clientTop) ?? hit;\n }\n }\n return hit;\n };\n /** Whether its role or a click handler makes an element a control. */\n const acts = (element, role) => isInput(element) && element.type !== \"hidden\" || role !== null && (interactiveRoles.has(role) || role === \"canvas\" || role === \"iframe\") || element.hasAttribute(\"onclick\");\n const controlOf = (hit) => {\n let element = hit;\n while (element !== null) {\n if (acts(element, roleOf(element))) return element;\n element = parentOf(element);\n }\n return hit;\n };\n /** An element's box in top-document viewport pixels, through the frames around it. */\n const boxOf = (element) => {\n const { x, y, width, height } = element.getBoundingClientRect();\n const frame = element.ownerDocument.defaultView?.frameElement ?? null;\n if (frame === null) return {\n x,\n y,\n width,\n height\n };\n const outer = boxOf(frame);\n return {\n x: x + outer.x + frame.clientLeft,\n y: y + outer.y + frame.clientTop,\n width,\n height\n };\n };\n /** What is painted where pinned things sit, what is pinned in view, and every element holding it. */\n const painted = (width, height) => {\n const keep = /* @__PURE__ */ new Set();\n const hold = (element) => {\n for (let node = element; node !== null && !keep.has(node); node = parentOf(node) ?? node.ownerDocument.defaultView?.frameElement ?? null) keep.add(node);\n };\n for (const y of [\n 8,\n 48,\n height / 2,\n height - 48,\n height - 8\n ]) for (const x of [\n 8,\n 48,\n width / 4,\n width / 2,\n width * 3 / 4,\n width - 48,\n width - 8\n ]) if (x >= 0 && y >= 0 && x < width && y < height) {\n hold(hitAt(document, x, y));\n for (const beneath of document.elementsFromPoint(x, y)) hold(beneath);\n }\n for (const element of Array.from(document.querySelectorAll(\":modal, :popover-open\"))) hold(element);\n for (const element of Array.from(document.querySelectorAll(\"[style*=\\\"fixed\\\" i]\"))) if (inView(element.getBoundingClientRect(), width, height)) hold(element);\n return keep;\n };\n /**\n * Visit `root` and what it holds, or the whole document when `root` is null. With `viewport`,\n * a subtree outside the viewport is skipped, as described above.\n */\n const visit = (root, viewport, state, visitor) => {\n const { innerWidth: width, innerHeight: height } = window;\n let keep;\n const children = (parent, inner, dx, dy) => {\n const nodes = visitor.text === void 0 ? parent.children : parent.childNodes;\n for (const node of Array.from(nodes)) if (node.nodeType === Node.TEXT_NODE) visitor.text?.(node, inner);\n else if (isElement(node) && (visitor.admit === void 0 || visitor.admit(node, inner))) one(node, inner, dx, dy);\n };\n const one = (element, outer, dx, dy) => {\n if (skipped.has(element.tagName.toUpperCase())) return;\n const local = element.getBoundingClientRect();\n const rect = new DOMRect(local.x + dx, local.y + dy, local.width, local.height);\n if (viewport && local.width > 0 && local.height > 0 && !inView(rect, width, height) && !(keep ??= painted(width, height)).has(element)) {\n visitor.outside?.(rect);\n return;\n }\n const style = getComputedStyle(element);\n if (style.display === \"none\" || style.opacity === \"0\" || element.getAttribute(\"aria-hidden\") === \"true\") return;\n if (!visible(element)) {\n for (const child of Array.from(element.children)) one(child, outer, dx, dy);\n return;\n }\n const inner = visitor.enter(element, style, rect, outer);\n if (inner === void 0) return;\n if (isFrame(element)) {\n const body = element.contentDocument?.body;\n if (body !== null && body !== void 0) children(body, inner, rect.x, rect.y);\n } else {\n if (element.shadowRoot !== null) children(element.shadowRoot, inner, dx, dy);\n children(element, inner, dx, dy);\n }\n visitor.leave?.(element, inner);\n };\n if (root === null) children(document, state, 0, 0);\n else one(root, state, 0, 0);\n };\n return {\n acts,\n boxOf,\n controlOf,\n hitAt,\n inView,\n visible,\n visit\n };\n };\n //#endregion\n //#region src/internal/timeline/changes.inpage.ts\n const changes = (names, walked, placing, kept, seeing, marking, recorder) => {\n const { clean, isInput, roleOf, nameOf } = names;\n const groups = \"tr,[role=row],form,dialog,[role=dialog],[role=alertdialog]\";\n /** Whether `element` lies in what an input on `target` acted on, its group, or what it controls. */\n const local = (target, element) => {\n const controls = target.closest(\"[aria-controls]\")?.getAttribute(\"aria-controls\") ?? \"\";\n const group = target.closest(groups);\n return target.contains(element) || group?.contains(element) === true || controls.split(/\\s+/).some((id) => id !== \"\" && document.getElementById(id)?.contains(element) === true);\n };\n /** What an element sits in, or sat in as it went. */\n const parentOf = (key) => key instanceof Element ? key.isConnected ? key.parentElement : marking.placeOf(key) ?? null : null;\n const fluxMillis = 1e4;\n const stillMillis = 2e3;\n /**\n * Each input a change may follow, with what the page did before it: what changed in the 10 s\n * before, the parents that gained or lost a child then, and whether nothing changed, and nothing\n * was let go, in the 2 s before. What holds the input's target, as a menu holds its item, came\n * with it, so it counts only as changing itself.\n */\n const before = () => {\n const inputs = recorder.inputs();\n if (inputs.length === 0) return [];\n const { tracks, losses } = kept.recent();\n return inputs.map(({ at, target }) => {\n const changed = /* @__PURE__ */ new Set();\n const moved = /* @__PURE__ */ new Set();\n let still = losses.every((lost) => lost >= at || lost < at - stillMillis);\n for (const { key, kind, initial, samples } of tracks) {\n const prior = samples.flatMap(({ at: when, shown }, index) => kind === \"value\" || when >= at || when < at - fluxMillis ? [] : [shown === null || (index === 0 ? initial : samples[index - 1]?.shown) === null]);\n if (prior.length > 0) changed.add(key);\n if (prior.length === 0 || key instanceof Element && key.contains(target)) continue;\n if (prior.includes(true)) moved.add(parentOf(key));\n if (samples.some(({ at: when }) => when < at && when >= at - stillMillis)) still = false;\n }\n return {\n at,\n target,\n changed,\n moved,\n still\n };\n });\n };\n /** The input a change followed, on the page's clock, where `Change.cause`'s rule names one. */\n const causeOf = (one, element, inputs) => {\n const parent = parentOf(one.track.key);\n for (const input of inputs.toReversed()) {\n const after = one.startedAt - input.at;\n if (after < 0) continue;\n if (after > 3e3) break;\n if (!(one.track.known >= input.at - fluxMillis || input.changed.has(one.track.key) || parent !== null && input.moved.has(parent)) && (local(input.target, element) || after <= 500 && input.still)) return input.at;\n }\n };\n const describe = (one, known, unmask, inputs) => {\n const { track, kind, before, after, lowest, highest, ...times } = one;\n const element = track.key instanceof Element ? track.key : null;\n const where = element?.isConnected === true ? element : marking.placeOf(track.key) ?? null;\n const box = where === null ? void 0 : walked.boxOf(where);\n const role = element === null ? null : roleOf(element);\n const field = kind === \"value\";\n const checkable = element !== null && isInput(element) && /^(checkbox|radio)$/.test(element.type);\n const masked = (value) => value === void 0 || !field || unmask || checkable || value === \"\" ? value : \"••••\";\n return {\n ...times,\n kind,\n subject: {\n role,\n name: element === null ? \"\" : field ? nameOf(element, role) : clean(element.getAttribute(\"aria-label\"), 120),\n tag: element === null ? \"title\" : element.tagName.toLowerCase(),\n context: kind === \"title\" || where === null ? {} : placing.contextOf(where, known)\n },\n box: box === void 0 || box.width === 0 && box.height === 0 ? void 0 : box,\n before: masked(before),\n after: masked(after),\n lowest: field ? void 0 : lowest,\n highest: field ? void 0 : highest,\n cause: field || where === null ? void 0 : causeOf(one, where, inputs)\n };\n };\n /** What changed after `since`, up to `until`, and no later than now. */\n const read = (request) => {\n const now = performance.timeOrigin + performance.now();\n recorder.start();\n seeing.settle();\n const until = Math.min(request.until ?? now, now);\n const { from, dropped, folded } = kept.read(request.since ?? Number.NEGATIVE_INFINITY, until, now);\n const known = placing.known();\n const inputs = before();\n return {\n until,\n from,\n dropped,\n records: folded.map((one) => describe(one, known, request.unmask, inputs))\n };\n };\n return { read };\n };\n //#endregion\n //#region src/internal/timeline/fold.inpage.ts\n const fold = () => {\n /** The one number some words show, such as 61240 in \"$61,240\"; none for none or several. */\n const number = (words) => {\n const found = words.match(/[-+−]?\\d[\\d,]*(?:\\.\\d+)?/g);\n const value = Number(found?.length === 1 ? found[0]?.replaceAll(\",\", \"\").replace(\"−\", \"-\") : \"\");\n return found?.length === 1 && Number.isFinite(value) ? [value] : [];\n };\n /** A track's changes after `since`, up to `until`, if one was seen in view. */\n const over = (track, since, until) => {\n const inside = track.samples.filter((sample) => sample.at > since && sample.at <= until);\n const first = inside[0];\n const last = inside.at(-1);\n if (first === void 0 || last === void 0 || !inside.some((sample) => sample.seen === true)) return void 0;\n const prior = track.samples[track.samples.indexOf(first) - 1];\n const lost = track.known <= since ? track.known : void 0;\n const start = prior === void 0 ? lost === void 0 ? void 0 : track.initial : prior.shown;\n const words = [start, ...inside.map((sample) => sample.shown)].filter((each) => typeof each === \"string\");\n const numbers = words.flatMap(number);\n const ranged = inside.length > 1 && numbers.length === words.length;\n const kind = track.kind !== \"content\" ? track.kind : last.shown === null ? start === null ? \"brief\" : \"disappeared\" : start === null ? \"appeared\" : \"text\";\n return {\n track,\n kind,\n startedAt: first.at,\n at: last.at,\n before: kind === \"disappeared\" ? words.at(-1) : start ?? void 0,\n after: kind === \"brief\" ? words.at(-1) : last.shown ?? void 0,\n count: inside.length,\n lowest: ranged ? words[numbers.indexOf(Math.min(...numbers))] : void 0,\n highest: ranged ? words[numbers.indexOf(Math.max(...numbers))] : void 0,\n earlier: prior?.at ?? (lost === Number.NEGATIVE_INFINITY ? void 0 : lost)\n };\n };\n /**\n * How readily a track gives way when the record is full: one that holds no change first, then\n * one that keeps changing, one never seen in view and one that has gone; news never does.\n */\n const rank = ({ samples: [only, ...more] }) => only === void 0 ? 4 : more.length > 0 ? 3 : only.seen === false ? 2 : only.shown === null ? 1 : 0;\n return {\n number,\n over,\n rank\n };\n };\n //#endregion\n //#region src/internal/timeline/history.inpage.ts\n const history = (folding, bounds = {\n tracks: 256,\n samples: 32,\n retention: 6e4\n }) => {\n const { tracks: maxTracks, samples: maxSamples, retention } = bounds;\n const tracks = /* @__PURE__ */ new Map();\n let refused = /* @__PURE__ */ new WeakSet();\n let losses = [];\n let lastLoss = Number.NEGATIVE_INFINITY;\n const gone = [];\n let begun;\n const lose = (at, count) => {\n const last = losses.at(-1);\n if (count <= 0) return;\n lastLoss = Math.max(lastLoss, at);\n if (last?.[0] === at) last[1] += count;\n else losses.push([at, count]);\n if (losses.length > 256) losses.shift();\n };\n const latest = (track) => track.samples.at(-1)?.at ?? Number.NEGATIVE_INFINITY;\n const drop = (track) => {\n tracks.delete(track.key);\n gone.push(track.key);\n };\n let version = 0;\n let barren = -1;\n /** What gives way for a newcomer: one that holds no change, then one that keeps changing. */\n const victim = () => {\n let chosen;\n let rank = 0;\n for (const track of barren === version ? [] : tracks.values()) {\n const next = folding.rank(track);\n if (next > rank) [chosen, rank] = [track, next];\n if (rank === 4) break;\n }\n if (chosen === void 0) barren = version;\n return chosen;\n };\n const evict = (track) => {\n drop(track);\n if (track.samples.length > 0) refused.add(track.key);\n for (const sample of track.samples) lose(sample.at, 1);\n };\n /** A key the record cannot keep: its change is counted. */\n const refuse = (key, at) => {\n refused.add(key);\n lose(at, 1);\n };\n /**\n * A new state for `key` at `at`: its sample, or none when it is no change or finds no room.\n * `initial` says what a key not yet kept showed before.\n */\n const note = (key, kind, at, shown, initial) => {\n let track = tracks.get(key);\n if (track === void 0) {\n const full = !refused.has(key) && tracks.size >= maxTracks;\n const out = full ? victim() : void 0;\n if (refused.has(key) || full && out === void 0) return refuse(key, at);\n const before = initial();\n if (shown !== void 0 && shown === before) return void 0;\n if (out !== void 0) evict(out);\n track = {\n key,\n kind,\n initial: before,\n known: Number.NEGATIVE_INFINITY,\n samples: []\n };\n tracks.set(key, track);\n }\n const { samples } = track;\n version++;\n if (samples.at(-1)?.at === at) samples.pop();\n const previous = samples.length === 0 ? track.initial : samples.at(-1)?.shown;\n if (shown !== void 0 && shown === previous) return void 0;\n const oldest = samples.length >= maxSamples ? samples.shift() : void 0;\n if (oldest !== void 0) {\n track.initial = oldest.shown;\n track.known = oldest.at;\n lose(oldest.at, 1);\n }\n const sample = {\n at,\n shown,\n seen: void 0\n };\n samples.push(sample);\n return sample;\n };\n /** Judge a sample as the page rendered it; a state that repeats the one before is no change. */\n const settle = (key, sample, shown, seen) => {\n const track = tracks.get(key);\n version++;\n if (sample.shown === void 0) sample.shown = shown;\n if (sample.seen === void 0) sample.seen = seen;\n if (track === void 0) return;\n let previous = track.initial;\n const changes = track.samples.filter((each) => {\n const same = each.shown !== void 0 && each.shown === previous;\n if (!same) previous = each.shown;\n return !same;\n });\n track.samples.splice(0, track.samples.length, ...changes);\n };\n /**\n * The window after `since`, up to `until`: where the record is whole, how many changes in it the\n * record let go, and each element's changes, oldest first by when they began.\n */\n const read = (since, until, now) => {\n for (const track of tracks.values()) if (latest(track) < now - retention) drop(track);\n return {\n from: Math.min(until, Math.max(begun ?? now, now - retention, lastLoss)),\n dropped: losses.reduce((sum, [at, count]) => at > since && at <= until ? sum + count : sum, 0),\n folded: [...tracks.values()].flatMap((track) => folding.over(track, since, until) ?? []).toSorted((left, right) => left.startedAt - right.startedAt)\n };\n };\n /** When something in view last changed, or something not yet judged; for a wait for stillness. */\n const changing = () => Math.max(begun ?? Number.NEGATIVE_INFINITY, ...Array.from(tracks.values(), (track) => track.samples.findLast((sample) => sample.seen !== false)?.at ?? Number.NEGATIVE_INFINITY));\n return {\n begin: (at) => {\n begun = at;\n },\n begun: () => begun !== void 0,\n clear: () => {\n for (const track of tracks.values()) drop(track);\n refused = /* @__PURE__ */ new WeakSet();\n losses = [];\n lastLoss = Number.NEGATIVE_INFINITY;\n begun = void 0;\n },\n changing,\n /** Keys whose tracks went since this was last asked, for the recorder to stop watching. */\n forgotten: () => gone.splice(0),\n has: (key) => tracks.has(key),\n /** Whether the record has let `key` go: its later changes are counted, never kept. */\n refuses: (key) => refused.has(key),\n lose,\n note,\n read,\n /** Each element's history, and when the record let changes go, for a read to judge causes. */\n recent: () => ({\n tracks: [...tracks.values()],\n losses: losses.map(([at]) => at)\n }),\n /** A track moves to the element that took its key's place, as a re-rendered price does. */\n rekey: (from, to) => {\n const track = tracks.get(from);\n if (track === void 0 || tracks.has(to)) return false;\n tracks.delete(from);\n track.key = to;\n tracks.set(to, track);\n return true;\n },\n settle\n };\n };\n //#endregion\n //#region src/internal/timeline/marks.inpage.ts\n const marks = (names, kept, seeing) => {\n const { clean, isElement, isHtml } = names;\n const unwritten = new Set(\"SCRIPT STYLE NOSCRIPT TEMPLATE TITLE\".split(\" \"));\n const hiding = /display\\s*:\\s*none|visibility\\s*:\\s*hidden|opacity\\s*:\\s*0(?![.\\d])/i;\n let places = /* @__PURE__ */ new WeakMap();\n let title = \"\";\n const words = (text) => clean(text, 200) || null;\n const content = (element, at, shown, initial) => {\n const sample = kept.note(element, \"content\", at, shown, initial);\n if (sample !== void 0) seeing.look(element, sample);\n };\n /** What a text-only element said before this batch: its text with the batch undone. */\n const before = (leaf, records) => {\n let nodes = Array.from(leaf.childNodes);\n const old = /* @__PURE__ */ new Map();\n for (const record of records.toReversed()) if (record.type === \"characterData\") old.set(record.target, record.oldValue ?? \"\");\n else {\n const added = new Set(Array.from(record.addedNodes));\n nodes = nodes.filter((node) => !added.has(node));\n const next = record.nextSibling === null ? -1 : nodes.indexOf(record.nextSibling);\n nodes.splice(next === -1 ? nodes.length : next, 0, ...Array.from(record.removedNodes));\n }\n return words(nodes.map((node) => old.get(node) ?? node.textContent).join(\"\"));\n };\n const attribute = (element, { attributeName: name, oldValue: old }, at) => {\n const was = name === \"hidden\" ? old !== null : name === \"aria-hidden\" ? old === \"true\" : name === \"open\" ? element.tagName === \"DIALOG\" && old === null : name === \"style\" && hiding.test(old ?? \"\");\n if (name === \"style\" && !was && !hiding.test(element.getAttribute(\"style\") ?? \"\")) return;\n const state = seeing.state(element);\n if (!kept.has(element) && !was && state === void 0 && name !== \"open\") return seeing.glance(element);\n content(element, at, void 0, () => was || state === false ? null : name === \"open\" && old === null ? words(element.querySelector(\":scope > summary\")?.textContent) : words(element.textContent));\n };\n /** What one mutation added to and removed from `target`. */\n const nodes = (change, target, batch) => {\n const added = Array.from(change.addedNodes).slice(0, 64);\n const removed = Array.from(change.removedNodes).slice(0, 64);\n const text = [...added, ...removed].some((node) => !isElement(node) && /\\S/.test(node.textContent ?? \"\"));\n kept.lose(batch.at, Math.max(change.addedNodes.length, change.removedNodes.length) - 64);\n if (text) batch.owners.add(target);\n removed.forEach((gone, index) => {\n const node = added[index];\n if (!isElement(gone)) return;\n batch.left.add(gone);\n if (node !== void 0 && isElement(node) && kept.rekey(gone, node)) seeing.unwatch(gone);\n else if (kept.has(gone)) {\n places.set(gone, target);\n const sample = kept.note(gone, \"content\", batch.at, null, () => void 0);\n if (sample !== void 0) sample.seen = seeing.viewed(gone);\n seeing.unwatch(gone);\n }\n });\n for (const node of added) if (isElement(node) && isHtml(node) && !unwritten.has(node.tagName) && !node.isContentEditable) {\n if (kept.has(node) || !text && !batch.left.has(node)) {\n batch.arrived.add(node);\n content(node, batch.at, void 0, () => null);\n }\n }\n };\n /** Whether `element` is inside something this batch added, which tells it with its own words. */\n const inside = (element, arrived) => {\n for (let up = element.parentElement; arrived.size > 0 && up !== null; up = up.parentElement) if (arrived.has(up)) return true;\n return false;\n };\n const ownerOf = (change) => change.type === \"characterData\" ? change.target.parentElement : change.target;\n /** Mark what one batch of mutations changed, at `at`. */\n const mark = (records, at) => {\n const batch = {\n at,\n owners: /* @__PURE__ */ new Set(),\n arrived: /* @__PURE__ */ new Set(),\n left: /* @__PURE__ */ new Set()\n };\n let byOwner;\n for (const change of records) {\n const target = ownerOf(change);\n if (target === null || !isElement(target) || inside(target, batch.arrived)) continue;\n const known = kept.has(target) || kept.refuses(target);\n if (change.type !== \"attributes\") if (change.type === \"characterData\" || target.childElementCount === 0 && known) batch.owners.add(target);\n else nodes(change, target, batch);\n else if (isHtml(target) && target !== document.body && target !== document.documentElement) attribute(target, change, at);\n }\n for (const owner of batch.owners) {\n const leaf = owner.childElementCount === 0;\n if (kept.refuses(owner)) kept.lose(at, 1);\n if (kept.refuses(owner) || !isHtml(owner) || unwritten.has(owner.tagName)) continue;\n if (owner === document.body || owner.isContentEditable) continue;\n if (batch.arrived.has(owner) || inside(owner, batch.arrived)) continue;\n content(owner, at, leaf ? words(owner.textContent) : void 0, () => {\n byOwner ??= Map.groupBy(records, ownerOf);\n return leaf ? before(owner, byOwner.get(owner) ?? []) : void 0;\n });\n }\n if (document.title === title) return;\n const previous = words(title);\n const sample = kept.note(document, \"title\", at, words(title = document.title), () => previous);\n if (sample !== void 0) sample.seen = true;\n };\n return {\n mark,\n /** Where a removed element was, which gives its context. */\n placeOf: (key) => places.get(key),\n /** Start afresh, from the document's title now. */\n reset: () => {\n places = /* @__PURE__ */ new WeakMap();\n title = document.title;\n }\n };\n };\n //#endregion\n //#region src/internal/timeline/record.inpage.ts\n const record = (names, texts, kept, seeing, marking) => {\n const { isElement, isInput } = names;\n const epoch = () => performance.timeOrigin + performance.now();\n const declared = \"[role=alert],[role=status],[role=log],[role=dialog],[role=alertdialog],[aria-live],dialog,[popover]\";\n let running = false;\n let lastRead = 0;\n let focused = /* @__PURE__ */ new WeakMap();\n const inputs = [];\n const targetOf = (event) => {\n const target = event.composedPath()[0];\n return target instanceof Node && isElement(target) ? target : void 0;\n };\n /** A field's value as the record keeps it: a secret one's as `••••`, a box's checked or not. */\n const valueOf = (field) => isInput(field) && (field.type === \"checkbox\" || field.type === \"radio\") ? field.checked ? \"checked\" : \"not checked\" : texts.shown(field, true);\n const onFocus = (event) => {\n const field = targetOf(event);\n const value = field === void 0 ? void 0 : valueOf(field);\n if (field !== void 0 && value !== void 0) focused.set(field, value);\n };\n const onValue = (event) => {\n const field = targetOf(event);\n const value = field === void 0 ? void 0 : valueOf(field);\n if (field === void 0 || value === void 0) return;\n const sample = kept.note(field, \"value\", epoch(), value, () => focused.get(field) ?? null);\n if (sample !== void 0) seeing.look(field, sample);\n };\n const note = (target) => {\n inputs.push({\n at: epoch(),\n target\n });\n if (inputs.length > 8) inputs.shift();\n };\n const onInput = (event) => {\n const target = targetOf(event);\n if (event.isTrusted && target !== void 0) note(target);\n };\n const listeners = [\n [\"focusin\", onFocus],\n [\"input\", onValue],\n [\"change\", onValue],\n [\"pointerdown\", onInput],\n [\"keydown\", onInput]\n ];\n const options = {\n capture: true,\n passive: true\n };\n const stop = () => {\n running = false;\n document.removeEventListener(\"DOMContentLoaded\", begin);\n observer.disconnect();\n for (const [type, listener] of listeners) document.removeEventListener(type, listener, options);\n seeing.clear();\n kept.clear();\n kept.forgotten();\n inputs.length = 0;\n focused = /* @__PURE__ */ new WeakMap();\n };\n const observer = new MutationObserver((records) => {\n const at = epoch();\n if (at - lastRead > 12e4) stop();\n else marking.mark(records, at);\n });\n const begin = () => {\n if (!running || kept.begun()) return;\n observer.observe(document, {\n subtree: true,\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributeFilter: [\n \"hidden\",\n \"open\",\n \"aria-hidden\",\n \"class\",\n \"style\"\n ],\n attributeOldValue: true\n });\n for (const [type, listener] of listeners) document.addEventListener(type, listener, options);\n marking.reset();\n for (const element of Array.from(document.querySelectorAll(declared)).slice(0, 64)) seeing.glance(element, true);\n kept.begin(epoch());\n };\n return {\n stop,\n /** Record from now, once the document is parsed; each read keeps the record going. */\n start: () => {\n lastRead = epoch();\n if (running) return;\n running = true;\n if (document.readyState === \"loading\") document.addEventListener(\"DOMContentLoaded\", begin, { once: true });\n else begin();\n },\n /**\n * Keep an input at `target` now, as a trusted one is kept: what a site does through its own\n * app, whose events the page sees as untrusted, so its changes can name their cause.\n */\n note,\n inputs: () => inputs\n };\n };\n //#endregion\n //#region src/internal/timeline/sight.inpage.ts\n const sight = (names, walked, texts, kept) => {\n const { clean } = names;\n const { visible } = walked;\n let viewed = /* @__PURE__ */ new WeakMap();\n let watching = /* @__PURE__ */ new WeakSet();\n let states = /* @__PURE__ */ new WeakMap();\n const waiting = /* @__PURE__ */ new Map();\n /** What an element shows: its words, if its style shows it. */\n const shownBy = (element) => element.isConnected && visible(element) ? clean(texts.lines(element, false), 200) || null : null;\n /** Settle what waited on an element; its words are read once, if one of them needs them. */\n const judge = (element, pending, seen, was) => {\n const shown = pending.some((sample) => sample.shown === void 0) ? shownBy(element) : void 0;\n for (const sample of pending) {\n const now = sample.shown === void 0 ? shown : sample.shown;\n kept.settle(element, sample, now, now === null ? was : seen);\n }\n };\n const observer = new IntersectionObserver((entries) => {\n for (const { target, isIntersecting } of entries) {\n const was = viewed.get(target) ?? false;\n const seen = isIntersecting && visible(target);\n const pending = waiting.get(target);\n viewed.set(target, seen);\n waiting.delete(target);\n if (pending !== void 0) judge(target, pending, seen, was);\n if (!kept.has(target)) {\n states.set(target, visible(target));\n unwatch(target);\n }\n }\n });\n /** Watch an element, asking for a fresh report even if it is watched already. */\n const watch = (element) => {\n watching.add(element);\n observer.unobserve(element);\n observer.observe(element);\n };\n const unwatch = (element) => {\n watching.delete(element);\n observer.unobserve(element);\n };\n return {\n /** Judge a sample at once if what it shows and whether it is in view are known, else on render. */\n look: (element, sample) => {\n const view = viewed.get(element);\n if (sample.shown !== void 0 && view !== void 0 && watching.has(element)) {\n sample.seen = view;\n return;\n }\n waiting.set(element, [...waiting.get(element) ?? [], sample]);\n watch(element);\n },\n /**\n * Look at an element once, for its state when it next changes: as it renders, or `now`, by its\n * style, as for the few the record looks at as it starts.\n */\n glance: (element, now = false) => {\n if (now) states.set(element, visible(element));\n if (!watching.has(element)) watch(element);\n },\n /** Whether the style of an element looked at once showed it, if it was. */\n state: (element) => states.get(element),\n /** Whether a watched element was in view as the page last rendered it. */\n viewed: (element) => viewed.get(element) ?? false,\n unwatch,\n /** Judge now what the page has not rendered since it changed, as a hidden tab never does. */\n settle: () => {\n for (const [element, pending] of waiting) {\n const seen = element.isConnected && walked.inView(element.getBoundingClientRect()) && visible(element);\n judge(element, pending, seen, viewed.get(element) ?? false);\n viewed.set(element, seen);\n }\n waiting.clear();\n for (const key of kept.forgotten()) if (key instanceof Element) unwatch(key);\n },\n clear: () => {\n observer.disconnect();\n waiting.clear();\n viewed = /* @__PURE__ */ new WeakMap();\n watching = /* @__PURE__ */ new WeakSet();\n states = /* @__PURE__ */ new WeakMap();\n }\n };\n };\n //#endregion\n //#region src/internal/url.ts\n const addresses = () => {\n const withheld = \"••••••••\";\n const credential = /token|secret|passw|passcode|passphrase|signature|credential|assertion|verifier|bearer|jwt|hmac|apikey|accesskey|privatekey|sess(?:ion)?id|saml(?:response|art)|(?:sig|otp)$|(?:auth|api|access|private|secret|signing|client|encryption|licen[cs]e|session|master|app|device|verification|verify|confirmation|confirm|activation|activate|reset|recovery|login|security|magic|onetime|mfa|2fa|sms|email|otp|oob)(?:code|key)$|^(?:auth|authorization|pwd|pass)$/;\n const ambiguous = /^(?:code|key|session|sid|ticket)$/;\n const secret = (name, value) => {\n const bare = name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n return value !== \"\" && (credential.test(bare) || ambiguous.test(bare) && value.length >= 16 && /\\d/.test(value) && /[a-z]/i.test(value));\n };\n const masked = (parameters, separator) => parameters.split(separator).map((parameter) => {\n const [name = \"\", value = \"\"] = [...new URLSearchParams(parameter)][0] ?? [];\n return secret(name, value) ? `${parameter.slice(0, parameter.indexOf(\"=\") + 1)}${withheld}` : parameter;\n }).join(separator);\n /**\n * `url` as the library reports it: without userinfo, and with each credential's value withheld,\n * so the rest keeps its identity, such as a chart's `?ticker=ETH`. An address without a host,\n * such as `data:` or `about:blank`, is content or a fixed name, and stays as it is.\n */\n const redact = (url) => {\n const parsed = URL.parse(url);\n if (parsed === null || parsed.host === \"\") return url;\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.pathname = masked(parsed.pathname, \";\");\n parsed.search = masked(parsed.search.slice(1), \"&\");\n if (parsed.hash.includes(\"=\")) {\n const fragment = parsed.hash.slice(1);\n const question = fragment.indexOf(\"?\");\n const start = question >= 0 && question < fragment.indexOf(\"=\") ? question + 1 : 0;\n parsed.hash = fragment.slice(0, start) + masked(fragment.slice(start), \"&\");\n }\n return parsed.href.replaceAll(encodeURIComponent(withheld), withheld);\n };\n return {\n withheld,\n redact\n };\n };\n //#endregion\n //#region src/internal/page/compose.inpage.ts\n const compose = (parts, next) => {\n const named = parts.names(parts.elements());\n if (next !== void 0) named.refs.next = next;\n const walked = parts.walk(named);\n const placing = parts.context(named, walked);\n const matching = parts.match();\n const subjected = parts.subjects(named, walked, matching, placing, parts.states(named));\n const texts = parts.text(named, walked);\n const controlled = parts.controls(named, subjected, texts);\n const kept = parts.history(parts.fold());\n const seeing = parts.sight(named, walked, texts, kept);\n const marking = parts.marks(named, kept, seeing);\n const recorder = parts.record(named, texts, kept, seeing, marking);\n const url = parts.addresses();\n const read = parts.outline(named, walked, subjected, texts, controlled, url);\n const readiness = parts.ready(walked, texts, kept);\n const overlaid = parts.overlay(named);\n const posing = parts.pose(named);\n return {\n named,\n walked,\n placing,\n overlaid,\n posing,\n recorder,\n url,\n reads: {\n refs: named.refs,\n snapshot: read.snapshot,\n find: subjected.find,\n layout: parts.layout(named, walked, subjected, matching, placing).read,\n overlay: overlaid.draw,\n pose: posing.set,\n unpose: posing.clear,\n until: parts.expectations(named, subjected, matching).until,\n text: texts.read,\n record: recorder.start,\n stopRecord: recorder.stop,\n changes: parts.changes(named, walked, placing, kept, seeing, marking, recorder).read,\n ready: readiness.wait,\n settle: readiness.settle,\n viewport: read.viewport\n }\n };\n };\n //#endregion\n //#region src/internal/page/overlay.inpage.ts\n const overlay = (names) => {\n const svgNamespace = \"http://www.w3.org/2000/svg\";\n let host;\n let root;\n const mount = () => {\n if (host === void 0 || root === void 0) {\n host = document.createElement(\"div\");\n root = host.attachShadow({ mode: \"closed\" });\n names.adopt(host);\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(\"svg { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible }\");\n root.adoptedStyleSheets = [sheet];\n }\n const zoom = Number(getComputedStyle(document.documentElement).zoom) || 1;\n for (const [name, value] of Object.entries({\n all: \"initial\",\n display: \"block\",\n position: \"fixed\",\n left: \"0\",\n top: \"0\",\n width: \"100vw\",\n height: \"100vh\",\n \"pointer-events\": \"none\",\n \"z-index\": \"2147483647\",\n contain: \"strict\",\n zoom: String(1 / zoom)\n })) host.style.setProperty(name, value, \"important\");\n if (host.parentNode !== document.documentElement) document.documentElement.append(host);\n return root;\n };\n const boxes = (drawing) => Array.from(drawing.children).slice(0, 32).map((part) => {\n const { x, y, width, height } = part.getBoundingClientRect();\n return {\n x,\n y,\n width,\n height\n };\n }).filter((box) => box.width > 0 && box.height > 0);\n /**\n * Draw an SVG document over the viewport, in place of what was drawn, or take the layer away\n * with null. Says where the drawing's parts are. Its scripts and handlers are dropped.\n */\n const draw = (markup) => {\n if (markup === null) {\n host?.remove();\n return [];\n }\n const parsed = new DOMParser().parseFromString(markup, \"image/svg+xml\");\n const drawing = parsed.documentElement;\n if (parsed.getElementsByTagName(\"parsererror\").length > 0 || drawing.namespaceURI !== svgNamespace || drawing.localName !== \"svg\") throw new Error(\"the overlay's markup is not an SVG document\");\n for (const script of Array.from(drawing.getElementsByTagName(\"script\"))) script.remove();\n for (const element of [drawing, ...Array.from(drawing.querySelectorAll(\"*\"))]) for (const attribute of Array.from(element.attributes)) if (/^on/i.test(attribute.name)) element.removeAttribute(attribute.name);\n const shown = document.importNode(drawing, true);\n mount().replaceChildren(shown);\n return boxes(shown);\n };\n return {\n draw,\n mount\n };\n };\n //#endregion\n //#region src/internal/page/pose.inpage.ts\n const pose = (names) => {\n const posed = /* @__PURE__ */ new Map();\n const isHtml = (element) => \"offsetWidth\" in element;\n const laidOut = (element, applied) => {\n const style = getComputedStyle(element);\n const [cx = 0, cy = 0] = style.transformOrigin.split(\" \").map(Number.parseFloat);\n const own = style.transform === \"none\" ? new DOMMatrix() : new DOMMatrix(style.transform);\n const whole = applied === void 0 ? own : new DOMMatrix().translate(applied.x, applied.y).rotate(applied.rotate).scale(applied.sx, applied.sy).multiply(own);\n const drawn = element.getBoundingClientRect();\n const plain = whole.isIdentity;\n const width = plain ? drawn.width : element.offsetWidth;\n const height = plain ? drawn.height : element.offsetHeight;\n let left = Infinity;\n let top = Infinity;\n for (const [x, y] of [\n [0, 0],\n [width, 0],\n [0, height],\n [width, height]\n ]) {\n const corner = whole.transformPoint({\n x: x - cx,\n y: y - cy\n });\n left = Math.min(left, corner.x + cx);\n top = Math.min(top, corner.y + cy);\n }\n const origin = {\n x: drawn.x - left + cx,\n y: drawn.y - top + cy\n };\n const middle = own.transformPoint({\n x: width / 2 - cx,\n y: height / 2 - cy\n });\n return {\n origin,\n middle: {\n x: origin.x + middle.x,\n y: origin.y + middle.y\n }\n };\n };\n const apply = (element, request) => {\n const known = posed.get(element);\n const { origin, middle } = laidOut(element, known?.applied);\n const about = request.origin ?? middle;\n const away = {\n x: about.x - origin.x,\n y: about.y - origin.y\n };\n const turned = new DOMMatrix().rotate(request.rotate).scale(request.sx, request.sy).transformPoint(away);\n const applied = {\n x: request.dx + away.x - turned.x,\n y: request.dy + away.y - turned.y,\n rotate: request.rotate,\n sx: request.sx,\n sy: request.sy\n };\n const frame = {\n translate: `${applied.x}px ${applied.y}px`,\n rotate: `${applied.rotate}deg`,\n scale: `${applied.sx} ${applied.sy}`\n };\n if (known === void 0) {\n const effect = new KeyframeEffect(element, [frame, frame], {\n duration: Infinity,\n fill: \"both\"\n });\n const animation = new Animation(effect, document.timeline);\n animation.play();\n posed.set(element, {\n animation,\n effect,\n applied\n });\n } else {\n known.effect.setKeyframes([frame, frame]);\n known.applied = applied;\n }\n };\n const takeOff = (element) => {\n posed.get(element)?.animation.cancel();\n posed.delete(element);\n };\n /**\n * The elements `requests` name, or the first that names none in the current document, or one\n * that is not an HTML element; then, to apply them, a function that poses them and takes poses\n * off every other element.\n */\n const prepare = (requests) => {\n const elements = [];\n for (const request of requests) {\n const element = names.lookup(request.ref);\n const { dx, dy, sx, sy, rotate, origin } = request;\n if (element === void 0) return { stale: request.ref };\n if (!isHtml(element)) return { invalid: `${request.ref} is not an HTML element` };\n if (![\n dx,\n dy,\n sx,\n sy,\n rotate,\n origin?.x ?? 0,\n origin?.y ?? 0\n ].every(Number.isFinite)) return { invalid: `${request.ref}'s pose is not finite numbers` };\n elements.push(element);\n }\n return { apply: () => {\n for (const element of Array.from(posed.keys())) if (!elements.includes(element)) takeOff(element);\n requests.forEach((request, index) => {\n const element = elements[index];\n if (element !== void 0) apply(element, request);\n });\n } };\n };\n const set = (requests) => {\n const prepared = prepare(requests);\n if (\"apply\" in prepared) {\n prepared.apply();\n return {};\n }\n return prepared;\n };\n const clear = () => {\n for (const element of Array.from(posed.keys())) takeOff(element);\n };\n return {\n prepare,\n set,\n clear\n };\n };\n //#endregion\n //#region src/internal/page/time.inpage.ts\n const time = (overlaid, posing) => {\n const step = (request) => {\n const posed = request.poses === void 0 ? void 0 : posing.prepare(request.poses);\n if (posed !== void 0 && !(\"apply\" in posed)) return {\n told: false,\n drawn: null,\n scroll: {\n x: scrollX,\n y: scrollY\n },\n ...posed\n };\n if (request.scroll !== null) scrollTo({\n left: scrollX,\n top: request.scroll,\n behavior: \"instant\"\n });\n const detail = {\n op: request.op,\n by: request.by\n };\n const told = !document.dispatchEvent(new CustomEvent(request.clock, {\n detail,\n cancelable: true\n }));\n posed?.apply();\n return {\n told,\n drawn: request.markup === void 0 ? null : overlaid.draw(request.markup),\n scroll: {\n x: scrollX,\n y: scrollY\n }\n };\n };\n return { step };\n };\n //#endregion\n //#region src/internal/page/bridge.ts\n const parts = {\n compose,\n elements,\n names,\n walk,\n match,\n context,\n subjects,\n states,\n expectations,\n text,\n layout,\n controls,\n fold,\n history,\n sight,\n marks,\n record,\n changes,\n ready,\n outline,\n targets,\n evidence,\n guard,\n edit,\n overlay,\n pose,\n time,\n addresses\n };\n function install(parts) {\n const source = install.toString() + Object.entries(parts).map(([name, factory]) => name + factory.toString()).join(\"\");\n let version = 2166136261;\n for (let index = 0; index < source.length; index++) version = Math.imul(version ^ source.charCodeAt(index), 16777619);\n version >>>= 0;\n const installed = globalThis.__effectBrowser;\n if (installed !== void 0 && installed.version === version) return installed;\n installed?.dispose?.();\n const { named, walked, placing, overlaid, posing, reads } = parts.compose(parts, installed?.refs?.next);\n const located = parts.targets(named, walked, placing);\n const guarded = parts.guard(named, located, parts.evidence(named, placing));\n const edited = parts.edit(named, guarded, placing);\n const api = {\n ...reads,\n version,\n dispose: reads.stopRecord,\n step: parts.time(overlaid, posing).step,\n point: located.point,\n scrollPlan: located.scrollPlan,\n screenSize: () => ({\n width: screen.width,\n height: screen.height,\n ratio: devicePixelRatio\n }),\n prepareInput: guarded.prepareInput,\n validateInput: guarded.validateInput,\n typeable: edited.typeable,\n focus: edited.focus,\n focusOn: edited.focusOn,\n select: edited.select\n };\n globalThis.__effectBrowser = api;\n return api;\n }\n //#endregion\n return install(parts);\n})();\n\nreturn pageScript;})()";
492
496
  /**
493
497
  * What new documents run before their own scripts: the page clock under its event name, first, so
494
498
  * a caller's script that keeps a timer keeps the clock's, and then the caller's scripts, each
@@ -571,7 +575,7 @@ const registrationFor = Effect.fnUntraced(function* (page) {
571
575
  removeRecorder
572
576
  };
573
577
  });
574
- const make$28 = Effect.fnUntraced(function* (page) {
578
+ const make$27 = Effect.fnUntraced(function* (page) {
575
579
  const { id, cdp, native, span, publish, now } = page;
576
580
  const { send } = page.protocol;
577
581
  const { ensure, removeRecorder } = yield* registrationFor(page);
@@ -736,7 +740,7 @@ const listen = Effect.fnUntraced(function* (playwright, page, publish, now, answ
736
740
  //#region src/internal/page/identity.ts
737
741
  /** Connection identity uses the supplied SecureRandom service, or the host's Web Crypto on Node/Bun. */
738
742
  const failed = () => undispatched("make", new Failed({ detail: "Could not name connection" }));
739
- const make$27 = Effect.gen(function* () {
743
+ const make$26 = Effect.gen(function* () {
740
744
  const supplied = yield* Effect.serviceOption(SecureRandom.SecureRandom);
741
745
  return yield* Option.isSome(supplied) ? supplied.value.uuidV4() : Effect.try({
742
746
  try: () => globalThis.crypto.randomUUID(),
@@ -746,7 +750,7 @@ const make$27 = Effect.gen(function* () {
746
750
  //#endregion
747
751
  //#region src/internal/page/openings.ts
748
752
  /** A page's input waits for the actual tabs it opened to finish the browser's registration. */
749
- const make$26 = Effect.fnUntraced(function* (playwright, cdp, registrations, closedBy) {
753
+ const make$25 = Effect.fnUntraced(function* (playwright, cdp, registrations, closedBy) {
750
754
  const failed = (reason) => Exit.fail(undispatched("newPage", reason));
751
755
  let active;
752
756
  const gone = Deferred.makeUnsafe();
@@ -810,7 +814,7 @@ const buttonAt = (type, point, button = "left", clickCount = 1) => ({
810
814
  buttons: type === "mousePressed" ? buttonMask[button] : 0,
811
815
  clickCount
812
816
  });
813
- const make$25 = (page) => {
817
+ const make$24 = (page) => {
814
818
  const { id, pointer, publish, now, noteInput, closedBy } = page;
815
819
  const { send } = page.protocol;
816
820
  const inputClocks = /* @__PURE__ */ new WeakMap();
@@ -912,7 +916,7 @@ const inputFailure = (operation, targets, failure) => {
912
916
  return failWith(operation, failure.error === "outside" ? new InvalidRequest({ detail: failure.detail }) : failure.error === "stale" && typeof target === "string" ? new StaleRef({ ref: target }) : new NotActionable({ detail: failure.detail }));
913
917
  };
914
918
  const editFailure = (operation, ref, failure) => failWith(operation, failure.stale === true ? new StaleRef({ ref }) : new NotActionable({ detail: failure.error }));
915
- const make$24 = (page, bridge) => {
919
+ const make$23 = (page, bridge) => {
916
920
  const { id } = page;
917
921
  const { current, evaluateIn, evaluateWithContext } = bridge;
918
922
  const preparePolicy = (asked, info, targets, flags = {}) => Effect.gen(function* () {
@@ -980,7 +984,7 @@ const make$24 = (page, bridge) => {
980
984
  * Keys and typing: a key chord held and released, each typed event, and the document a run of
981
985
  * keys must stay in.
982
986
  */
983
- const make$23 = (page, bridge, dispatch) => {
987
+ const make$22 = (page, bridge, dispatch) => {
984
988
  const { playwright } = page;
985
989
  const key = (direction, part) => {
986
990
  const run = () => playwright.keyboard[direction](part);
@@ -1122,10 +1126,10 @@ const announcing = (page, name, style, acted) => (to) => Effect.gen(function* ()
1122
1126
  });
1123
1127
  /** Close a run on every exit while preserving its native replies for the page's next input. */
1124
1128
  const useRun = (page, sender, name, run, action, canStop) => action.pipe(Effect.tapError((error) => error.reason._tag === "Closed" ? run.close : run.close.pipe(Effect.andThen(sender.flush(name, run)), Effect.ignore)), Effect.tap(() => run.close.pipe(Effect.andThen(sender.flush(name, run)))), Effect.ensuring(run.close.pipe(Effect.andThen(page.openings.clear))), Effect.onError(() => run.recover(page.stopLoading, page.scope).pipe(Effect.when(canStop))), Effect.provideService(Current, run));
1125
- const make$22 = (page, sender) => {
1129
+ const make$21 = (page, sender) => {
1126
1130
  const { id, settings, mapping, lane, publish, now, noteInput, span, owned } = page;
1127
1131
  const { inputClocks } = sender;
1128
- const input = make$30();
1132
+ const input = make$29();
1129
1133
  const admitted = /* @__PURE__ */ new Set();
1130
1134
  const perform = (value, info, timeout, prepare, body) => {
1131
1135
  const name = nameOf(value);
@@ -1246,7 +1250,7 @@ const make$22 = (page, sender) => {
1246
1250
  * plan, published before its first move, from where viewers last saw the pointer when it is
1247
1251
  * shown, and a wheel scroll goes in the style's steps.
1248
1252
  */
1249
- const make$21 = (page, dispatch, viewport) => {
1253
+ const make$20 = (page, dispatch, viewport) => {
1250
1254
  const { id, pointer, publish, now, span } = page;
1251
1255
  const { inputClocks, inputCall, dispatchMouse, sendMouse } = dispatch;
1252
1256
  const moveTo = (operation, marks, to, cursor, travel = "approach") => Effect.gen(function* () {
@@ -1345,7 +1349,7 @@ const make$21 = (page, dispatch, viewport) => {
1345
1349
  * next look's to see. A tab the input opened waits for the browser's registration too.
1346
1350
  */
1347
1351
  const settling = Duration.seconds(5);
1348
- const make$20 = (page, bridge) => {
1352
+ const make$19 = (page, bridge) => {
1349
1353
  const document = () => bridge.frameTag().document;
1350
1354
  let parsed = -1;
1351
1355
  let changed = Deferred.makeUnsafe();
@@ -1385,7 +1389,7 @@ const resolvedTarget = ({ x, y, box, ...target }) => new ResolvedTarget({
1385
1389
  box,
1386
1390
  ...target
1387
1391
  });
1388
- const make$19 = (viewport, guard, pointer, dispatch, settling) => {
1392
+ const make$18 = (viewport, guard, pointer, dispatch, settling) => {
1389
1393
  const { evaluate, mutate } = guard;
1390
1394
  const { moveTo, wheel } = pointer;
1391
1395
  const { flush } = dispatch;
@@ -1432,19 +1436,19 @@ const make$19 = (viewport, guard, pointer, dispatch, settling) => {
1432
1436
  * then waits for the page to settle: a task and a frame, and a document if the input asked for one.
1433
1437
  */
1434
1438
  const partsOf = (page, bridge, viewport) => {
1435
- const dispatch = make$25(page);
1436
- const pointer = make$21(page, dispatch, viewport);
1437
- const guard = make$24(page, bridge);
1438
- const settling = make$20(page, bridge);
1439
+ const dispatch = make$24(page);
1440
+ const pointer = make$20(page, dispatch, viewport);
1441
+ const guard = make$23(page, bridge);
1442
+ const settling = make$19(page, bridge);
1439
1443
  return {
1440
1444
  page,
1441
1445
  ...settling,
1442
1446
  viewportFor: viewport.viewportFor,
1443
- perform: make$22(page, dispatch),
1447
+ perform: make$21(page, dispatch),
1444
1448
  ...guard,
1445
- ...make$19(viewport, guard, pointer, dispatch, settling),
1449
+ ...make$18(viewport, guard, pointer, dispatch, settling),
1446
1450
  ...pointer,
1447
- ...make$23(page, bridge, dispatch),
1451
+ ...make$22(page, bridge, dispatch),
1448
1452
  sendMouse: dispatch.sendMouse,
1449
1453
  flush: dispatch.flush
1450
1454
  };
@@ -1711,7 +1715,7 @@ const select = (input) => {
1711
1715
  return result.detail;
1712
1716
  }));
1713
1717
  };
1714
- const make$18 = (page, bridge, viewport) => {
1718
+ const make$17 = (page, bridge, viewport) => {
1715
1719
  const parts = partsOf(page, bridge, viewport);
1716
1720
  return {
1717
1721
  perform: parts.perform,
@@ -1961,8 +1965,8 @@ const orderedFrame = (frame, previous) => frame.hostTime < previous && frame.tim
1961
1965
  //#region src/internal/pictures/quiescence.ts
1962
1966
  /** Actual native replies outlive callers; bounded transactions retain them without holding teardown. */
1963
1967
  const deadline$1 = Duration.seconds(2);
1964
- const make$17 = (options) => {
1965
- const replies = make$30();
1968
+ const make$16 = (options) => {
1969
+ const replies = make$29();
1966
1970
  const pending = /* @__PURE__ */ new Map();
1967
1971
  const late = (kind) => options.error(/* @__PURE__ */ new Error(`${kind} exceeded its deadline`));
1968
1972
  const track = (operation, actual, failed) => {
@@ -2142,7 +2146,7 @@ const reader = (acquire, leave, why, lost) => (settings = {}) => Effect.acquireR
2142
2146
  current: lease.frame,
2143
2147
  stream: frames(lease.subscription, lease.baseline, why, lost)
2144
2148
  })));
2145
- const make$16 = (options) => Effect.gen(function* () {
2149
+ const make$15 = (options) => Effect.gen(function* () {
2146
2150
  const lock = yield* Semaphore.make(1);
2147
2151
  const replies = /* @__PURE__ */ new Set();
2148
2152
  let generation;
@@ -2204,7 +2208,7 @@ const make$16 = (options) => Effect.gen(function* () {
2204
2208
  const gone = () => options.error(/* @__PURE__ */ new Error("Target page has been closed"));
2205
2209
  const why = told(closed, gone, options.clock);
2206
2210
  const awaitStop = (current) => pictures.wait("screencast stop").pipe(Effect.catch((error) => Effect.sync(() => notifyFailure(current, error))));
2207
- const pictures = make$17({
2211
+ const pictures = make$16({
2208
2212
  clock: options.clock,
2209
2213
  error: options.error,
2210
2214
  closed: isClosed,
@@ -2316,7 +2320,6 @@ const make$16 = (options) => Effect.gen(function* () {
2316
2320
  })))));
2317
2321
  return {
2318
2322
  open,
2319
- stream: (options) => Stream.unwrap(Effect.map(open(options), ({ stream }) => stream)),
2320
2323
  latest: Effect.sync(() => latest),
2321
2324
  recent: Effect.sync(() => history),
2322
2325
  active: Effect.sync(() => generation !== void 0 && generation.state._tag !== "Stopped"),
@@ -2712,13 +2715,10 @@ const camera = (page, viewport, capture, { holdScreen, scaled }) => {
2712
2715
  });
2713
2716
  }).pipe(capture.excluding, within(operation));
2714
2717
  };
2715
- const millisOf = (input) => Option.match(Duration.fromInput(input), {
2716
- onNone: () => NaN,
2717
- onSome: Duration.toMillis
2718
- });
2719
- const reuse = (page, bridge, viewport, capture) => (operation, options) => Effect.gen(function* () {
2718
+ const reuse = (page, bridge, viewport, capture) => (options) => Effect.gen(function* () {
2720
2719
  const maxAge = millisOf(options.maxAge ?? defaultMaxAge);
2721
- if (!(maxAge >= 0)) return yield* refuse(operation, "maxAge must be a duration of zero or more");
2720
+ if (!(maxAge >= 0)) return yield* refuse("frame", "maxAge must be a duration of zero or more");
2721
+ if (options.format === "png" || options.scale === "device") return Option.none();
2722
2722
  const latest = yield* capture.latest;
2723
2723
  const known = viewport.knownViewport();
2724
2724
  const { activity } = page;
@@ -2729,11 +2729,11 @@ const reuse = (page, bridge, viewport, capture) => (operation, options) => Effec
2729
2729
  });
2730
2730
  /** Where a picture came from: a frame the screencast had delivered, or a new screenshot. */
2731
2731
  const sourceOf = (reused) => Option.isSome(reused) ? "frame" : "screenshot";
2732
- const make$15 = Effect.fnUntraced(function* (page, bridge, viewport) {
2732
+ const make$14 = Effect.fnUntraced(function* (page, bridge, viewport) {
2733
2733
  const { id, clock, settings, mapping, now, span, owned, lane, within } = page;
2734
2734
  const calibrateClock = calibrator(page, bridge);
2735
2735
  const error = (cause) => Schema.is(BrowserError)(cause) ? cause : undispatched("screencast", reasonOf(cause, void 0, page.closedBy()));
2736
- const capture = yield* make$16({
2736
+ const capture = yield* make$15({
2737
2737
  id,
2738
2738
  transport: (page.capture === void 0 ? Effect.succeed(own(page, bridge)) : apart(page, bridge, page.capture, error, yield* Effect.scope)).pipe(Effect.provideService(Current$1, yield* Current$1)),
2739
2739
  clock,
@@ -2754,36 +2754,18 @@ const make$15 = Effect.fnUntraced(function* (page, bridge, viewport) {
2754
2754
  const emulated = device(page, bridge);
2755
2755
  const picture = camera(page, viewport, capture, emulated);
2756
2756
  const reusable = reuse(page, bridge, viewport, capture);
2757
- const screenshots = lane.shared("screenshot", false);
2758
2757
  const frames = lane.shared("frame", false);
2759
- const screenshot = (options = {}) => screenshots(JSON.stringify([
2760
- millisOf(options.maxAge ?? defaultMaxAge),
2761
- options.clip,
2762
- options.quality,
2763
- options.format,
2764
- options.scale
2765
- ]), Effect.gen(function* () {
2766
- const reused = options.clip === void 0 && options.format !== "png" && options.scale !== "device" ? yield* reusable("screenshot", {
2767
- maxAge: options.maxAge,
2768
- after: "input"
2769
- }) : Option.none();
2770
- const image = Option.isSome(reused) ? reused.value.image : yield* picture("screenshot", options.quality ?? 80, options.clip, options.format, options.scale);
2771
- yield* Effect.annotateCurrentSpan({
2772
- source: sourceOf(reused),
2773
- bytes: image.data.length
2774
- });
2775
- return image;
2776
- })).pipe(span("Page.screenshot"), owned);
2777
2758
  const taken = (options) => Effect.gen(function* () {
2778
- const reused = yield* reusable("frame", options);
2759
+ const reused = yield* reusable(options);
2779
2760
  yield* Effect.annotateCurrentSpan("source", sourceOf(reused));
2780
2761
  if (Option.isSome(reused)) return reused.value;
2781
2762
  const startedAt = now();
2782
- const image = yield* picture("frame", 80);
2763
+ const image = yield* picture("frame", options.quality ?? 80, void 0, options.format, options.scale);
2783
2764
  const finishedAt = now();
2784
2765
  return new Frame({
2785
2766
  page: id,
2786
2767
  data: image.data,
2768
+ mediaType: image.mediaType,
2787
2769
  timing: new Screenshot({
2788
2770
  hostTime: startedAt + (finishedAt - startedAt) / 2,
2789
2771
  uncertaintyMillis: (finishedAt - startedAt) / 2
@@ -2794,21 +2776,27 @@ const make$15 = Effect.fnUntraced(function* (page, bridge, viewport) {
2794
2776
  ...bridge.frameTag()
2795
2777
  });
2796
2778
  });
2797
- const frame = (options = {}) => (options.after === "input" ? Effect.succeed(Option.none()) : reusable("frame", options)).pipe(Effect.flatMap(Option.match({
2779
+ const frame = (options = {}) => (options.after === "input" ? Effect.succeed(Option.none()) : reusable(options)).pipe(Effect.flatMap(Option.match({
2798
2780
  onSome: (reused) => Effect.as(Effect.annotateCurrentSpan("source", "frame"), reused),
2799
- onNone: () => frames(JSON.stringify([millisOf(options.maxAge ?? defaultMaxAge), options.after]), taken(options))
2800
- })), span("Page.frame"), owned);
2781
+ onNone: () => frames(JSON.stringify([
2782
+ millisOf(options.maxAge ?? defaultMaxAge),
2783
+ options.after,
2784
+ options.quality,
2785
+ options.format,
2786
+ options.scale
2787
+ ]), taken(options))
2788
+ })), span("Frame.read"), owned);
2801
2789
  const zoom = (requested, options = {}) => lane.read("zoom")(Effect.gen(function* () {
2802
2790
  const region = yield* Schema.decodeEffect(Region)(requested).pipe(Effect.mapError((error) => undispatched("zoom", new InvalidRequest({ detail: error.message }))));
2803
2791
  const size = viewport.knownViewport() ?? (yield* viewport.viewportFor("zoom"));
2804
2792
  if (region.x + region.width > size.width || region.y + region.height > size.height) return yield* refuse("zoom", "the crop must fit entirely within the viewport");
2805
- const image = yield* picture("zoom", 80, region, "jpeg", options.scale);
2793
+ const image = yield* picture("zoom", options.quality ?? 80, region, options.format, options.scale);
2806
2794
  return new Zoom({
2807
2795
  page: id,
2808
2796
  region,
2809
2797
  image
2810
2798
  });
2811
- }).pipe(within("zoom"))).pipe(span("Page.zoom"), owned);
2799
+ }).pipe(within("zoom"))).pipe(span("Frame.zoom"), owned);
2812
2800
  const captureStats = (options = {}) => {
2813
2801
  if (options.window === void 0) return capture.stats();
2814
2802
  const millis = millisOf(options.window);
@@ -2816,7 +2804,6 @@ const make$15 = Effect.fnUntraced(function* (page, bridge, viewport) {
2816
2804
  };
2817
2805
  return {
2818
2806
  capture,
2819
- screenshot,
2820
2807
  frame,
2821
2808
  zoom,
2822
2809
  captureStats,
@@ -2827,7 +2814,7 @@ const make$15 = Effect.fnUntraced(function* (page, bridge, viewport) {
2827
2814
  //#endregion
2828
2815
  //#region src/internal/reading/layout.ts
2829
2816
  /**
2830
- * Reading where things are: `Page.layout`, in one call to the page that takes its turn as other
2817
+ * Reading where things are: `Layout.measure`, in one call to the page that takes its turn as other
2831
2818
  * reads do and shares its work with identical ones. The page gives each place's viewport box; the
2832
2819
  * document box is that box moved by the scroll read with it.
2833
2820
  */
@@ -2852,7 +2839,7 @@ const LayoutResult = Schema.Union([Schema.Struct({ layout: Schema.Struct({
2852
2839
  })))
2853
2840
  }))
2854
2841
  }) }), Schema.Struct({ invalid: Schema.String })]);
2855
- const make$14 = (page, bridge) => {
2842
+ const make$13 = (page, bridge) => {
2856
2843
  const { now, span, owned, within, lane } = page;
2857
2844
  const { evaluate } = bridge;
2858
2845
  const layouts = lane.shared("layout", true);
@@ -2890,7 +2877,7 @@ const make$14 = (page, bridge) => {
2890
2877
  return layouts(JSON.stringify(asked), once.pipe(Effect.retry({
2891
2878
  times: 1,
2892
2879
  while: (error) => contextGone(error) || error.reason._tag === "NotActionable" && error.operation === "layout"
2893
- }), within("layout"))).pipe(span("Page.layout", { picks: asked.length }), owned);
2880
+ }), within("layout"))).pipe(span("Layout.measure", { picks: asked.length }), owned);
2894
2881
  };
2895
2882
  return layout;
2896
2883
  };
@@ -2899,7 +2886,7 @@ const make$14 = (page, bridge) => {
2899
2886
  /**
2900
2887
  * Reading a page: its outline with refs, the elements a query finds and the text it shows. Each
2901
2888
  * read takes its turn on the page and shares its work with identical reads, as `lane.ts`
2902
- * describes. The viewport's text as it was last read is kept, for `Page.state`.
2889
+ * describes.
2903
2890
  */
2904
2891
  /** The outline as a `Snapshot` reads it, or why `within` is not a selector. */
2905
2892
  const SnapshotResultSchema = Schema.Union([Schema.Struct({ snapshot: Snapshot }), Schema.Struct({ invalid: Schema.String })]);
@@ -2915,13 +2902,12 @@ const UntilResult = Schema.Union([Schema.Struct({
2915
2902
  met: Schema.Boolean,
2916
2903
  mark: Schema.String
2917
2904
  }), Schema.Struct({ invalid: Schema.String })]);
2918
- const make$13 = (page, bridge) => Effect.sync(() => {
2905
+ const make$12 = (page, bridge) => Effect.sync(() => {
2919
2906
  const { now, span, owned, within, lane } = page;
2920
2907
  const { evaluate } = bridge;
2921
2908
  const snapshots = lane.shared("snapshot", true);
2922
2909
  const finds = lane.shared("find", true);
2923
2910
  const texts = lane.shared("text", true);
2924
- let viewed;
2925
2911
  const snapshot = (snapshotOptions = {}) => {
2926
2912
  const asked = {
2927
2913
  full: snapshotOptions.full ?? false,
@@ -2942,7 +2928,7 @@ const make$13 = (page, bridge) => Effect.sync(() => {
2942
2928
  ...result.snapshot,
2943
2929
  url: redact(url)
2944
2930
  });
2945
- }).pipe(within("snapshot"))).pipe(span("Page.snapshot", { full: asked.full }), owned);
2931
+ }).pipe(within("snapshot"))).pipe(span("Snapshot.read", { full: asked.full }), owned);
2946
2932
  };
2947
2933
  const find = (query = {}) => {
2948
2934
  const asked = request(query, "viewport");
@@ -2951,7 +2937,7 @@ const make$13 = (page, bridge) => Effect.sync(() => {
2951
2937
  if ("invalid" in result) return yield* refuse("find", result.invalid);
2952
2938
  yield* Effect.annotateCurrentSpan({ found: result.found.length });
2953
2939
  return result.found;
2954
- }).pipe(within("find"))).pipe(span("Page.find", {
2940
+ }).pipe(within("find"))).pipe(span("Snapshot.find", {
2955
2941
  scope: asked.scope,
2956
2942
  role: asked.role ?? ""
2957
2943
  }), owned);
@@ -2970,14 +2956,12 @@ const make$13 = (page, bridge) => Effect.sync(() => {
2970
2956
  chars: result.text.length,
2971
2957
  truncated: result.truncated
2972
2958
  });
2973
- const shown = new Text({
2959
+ return new Text({
2974
2960
  ...result,
2975
2961
  url: redact(result.url),
2976
2962
  at: now()
2977
2963
  });
2978
- if (request.ref === null) viewed = shown;
2979
- return shown;
2980
- }).pipe(within("text")))).pipe(span("Page.text", { scope: scope === "viewport" ? "viewport" : "ref" }), owned);
2964
+ }).pipe(within("text")))).pipe(span("Text.read", { scope: scope === "viewport" ? "viewport" : "ref" }), owned);
2981
2965
  };
2982
2966
  const until = (query, want, millis) => {
2983
2967
  if (!Number.isFinite(millis) || millis < 0) return refuse("until", "the wait duration must be finite and nonnegative");
@@ -2992,16 +2976,13 @@ const make$13 = (page, bridge) => Effect.sync(() => {
2992
2976
  mark: ""
2993
2977
  })));
2994
2978
  });
2995
- return lane.read("expect")(Effect.void).pipe(Effect.andThen(look), within("expect", Duration.sum(Duration.millis(millis), page.settings.actionTimeout)), span("Page.expect", { want: typeof want === "string" ? want : "other" }), owned);
2979
+ return lane.read("expect")(Effect.void).pipe(Effect.andThen(look), within("expect", Duration.sum(Duration.millis(millis), page.settings.actionTimeout)), span("Snapshot.until", { want: typeof want === "string" ? want : "other" }), owned);
2996
2980
  };
2997
- /** The viewport's text as it was last read, if after `since`, as a document began. */
2998
- const viewedSince = (since) => viewed !== void 0 && viewed.at > since ? viewed : void 0;
2999
2981
  return {
3000
2982
  snapshot,
3001
2983
  find,
3002
2984
  text,
3003
- until,
3004
- viewedSince
2985
+ until
3005
2986
  };
3006
2987
  });
3007
2988
  //#endregion
@@ -3018,9 +2999,9 @@ const ReadinessSchema = Schema.Array(Schema.Literals([
3018
2999
  "content",
3019
3000
  "changing"
3020
3001
  ]));
3021
- const make$12 = (page, bridge) => (options = {}) => {
3022
- const quietMillis = options.quietMillis ?? 0;
3023
- if (!Number.isFinite(quietMillis) || quietMillis < 0) return refuse("ready", "quietMillis must be finite and nonnegative");
3002
+ const make$11 = (page, bridge) => (options = {}) => {
3003
+ const quietMillis = millisOf(options.quiet ?? 0);
3004
+ if (!Number.isFinite(quietMillis) || quietMillis < 0) return refuse("ready", "quiet must be a finite nonnegative duration");
3024
3005
  const timeout = options.timeout ?? Duration.seconds(15);
3025
3006
  const settled = (until) => Effect.suspend(() => bridge.evaluate("ready", scriptCall("ready", Math.max(0, Math.round(until - page.now())), quietMillis, page.settings.pageTime ?? null))).pipe(Effect.retry({
3026
3007
  while: contextGone,
@@ -3052,7 +3033,7 @@ const ChangesResultSchema = Schema.Struct({
3052
3033
  });
3053
3034
  const isChanges = Schema.is(Changes);
3054
3035
  const markOf = (time) => time === void 0 || typeof time === "number" ? time : isChanges(time) ? `cursor ${time.cursor}` : `frame ${time.timestamp ?? time.hostTime}`;
3055
- const make$11 = (page, bridge, estimate) => {
3036
+ const make$10 = (page, bridge, estimate) => {
3056
3037
  const reads = page.lane.shared("changes", false);
3057
3038
  const recording = Semaphore.makeUnsafe(1);
3058
3039
  const idleMillis = 12e4;
@@ -3110,7 +3091,7 @@ const make$11 = (page, bridge, estimate) => {
3110
3091
  cause: later(one.cause)
3111
3092
  }))
3112
3093
  });
3113
- }).pipe(page.within("changes"))).pipe(page.span("Page.changes"), page.owned);
3094
+ }).pipe(page.within("changes"))).pipe(page.span("Change.read"), page.owned);
3114
3095
  };
3115
3096
  //#endregion
3116
3097
  //#region src/internal/timeline/window.ts
@@ -3143,7 +3124,7 @@ const within = ({ since, until }, events, frames) => ({
3143
3124
  events: events.filter((event) => event.at > since && event.at <= until && !isTrackEvent(event)),
3144
3125
  frames: frames.filter((frame) => frame.hostTime >= since && frame.hostTime <= until)
3145
3126
  });
3146
- const make$10 = (page, read, frames) => ({ since, until, unmask }) => Effect.gen(function* () {
3127
+ const make$9 = (page, read, frames) => ({ since, until, unmask }) => Effect.gen(function* () {
3147
3128
  const asked = boundsOf({
3148
3129
  since,
3149
3130
  until
@@ -3162,7 +3143,7 @@ const make$10 = (page, read, frames) => ({ since, until, unmask }) => Effect.gen
3162
3143
  changes: Result.getOrUndefined(changes),
3163
3144
  missing: Option.toArray(Result.getFailure(changes))
3164
3145
  });
3165
- }).pipe(page.span("Page.window"), page.owned);
3146
+ }).pipe(page.span("Window.read"), page.owned);
3166
3147
  //#endregion
3167
3148
  //#region src/internal/page/navigation.ts
3168
3149
  /**
@@ -3170,7 +3151,7 @@ const make$10 = (page, read, frames) => ({ since, until, unmask }) => Effect.gen
3170
3151
  * Each move is an action, so it takes the page's turn, goes through the input guard and is
3171
3152
  * recorded, but it sends no input.
3172
3153
  */
3173
- const make$9 = (page, perform, preparePolicy) => {
3154
+ const make$8 = (page, perform, preparePolicy) => {
3174
3155
  const { playwright, settings, native } = page;
3175
3156
  const { send } = page.protocol;
3176
3157
  const navigation = (value, run, address) => {
@@ -3263,7 +3244,7 @@ const make$9 = (page, perform, preparePolicy) => {
3263
3244
  * has loaded; the lease's scope takes the layer away.
3264
3245
  */
3265
3246
  const Drawn = Schema.Array(Box);
3266
- const make$8 = (page, bridge) => {
3247
+ const make$7 = (page, bridge) => {
3267
3248
  const { lane, owned, span, within } = page;
3268
3249
  const turns = Semaphore.makeUnsafe(1);
3269
3250
  let open = false;
@@ -3310,7 +3291,7 @@ const Posed = Schema.Struct({
3310
3291
  stale: Schema.optional(Schema.String),
3311
3292
  invalid: Schema.optional(Schema.String)
3312
3293
  });
3313
- const make$7 = (page, bridge) => {
3294
+ const make$6 = (page, bridge) => {
3314
3295
  const { lane, owned, span, within } = page;
3315
3296
  let open = false;
3316
3297
  /** The page's requests for `poses`, each part left out made the one that changes nothing. */
@@ -3338,7 +3319,7 @@ const make$7 = (page, bridge) => {
3338
3319
  //#endregion
3339
3320
  //#region src/internal/page/scripts.ts
3340
3321
  /** Main-world scripts with the page lane, document binding, policy and dispatch accounting. */
3341
- const make$6 = (page, bridge, input) => {
3322
+ const make$5 = (page, bridge, input) => {
3342
3323
  const document = () => bridge.frameTag().document;
3343
3324
  const changed = (operation) => failWith(operation, new NotActionable({ detail: "the script's document changed" }));
3344
3325
  const evaluate = (operation, script, arg) => page.native(operation, () => Promise.resolve(Reflect.apply(page.playwright.evaluate.bind(page.playwright), void 0, [script, arg])));
@@ -3405,7 +3386,7 @@ const Stepped = Schema.Struct({
3405
3386
  drawn: Schema.NullOr(Schema.Array(Box)),
3406
3387
  scroll: Point
3407
3388
  });
3408
- const make$5 = (page, bridge, overlays, posing) => {
3389
+ const make$4 = (page, bridge, overlays, posing) => {
3409
3390
  const { lane, owned, span, within } = page;
3410
3391
  let holding = false;
3411
3392
  const step = (operation, request) => {
@@ -3474,7 +3455,7 @@ const ViewportResultSchema = Schema.Struct({
3474
3455
  width: Schema.Finite,
3475
3456
  height: Schema.Finite
3476
3457
  });
3477
- const make$4 = (page, bridge) => {
3458
+ const make$3 = (page, bridge) => {
3478
3459
  const { playwright } = page;
3479
3460
  let measuredViewport = null;
3480
3461
  const knownViewport = () => playwright.viewportSize() ?? measuredViewport;
@@ -3506,22 +3487,22 @@ const make$4 = (page, bridge) => {
3506
3487
  * navigation.
3507
3488
  * Features use the same documented Page contract as consumers.
3508
3489
  */
3509
- const make$3 = Effect.fnUntraced(function* (options) {
3510
- const page = make$29(options, yield* Effect.scope);
3490
+ const make$2 = Effect.fnUntraced(function* (options) {
3491
+ const page = make$28(options, yield* Effect.scope);
3511
3492
  const { id, playwright, native, owned, within, lane, span } = page;
3512
- const bridge = yield* make$28(page);
3513
- const viewport = make$4(page, bridge);
3514
- const input = make$18(page, bridge, viewport);
3515
- const pictures = yield* make$15(page, bridge, viewport);
3516
- const reading = yield* make$13(page, bridge);
3517
- const navigation = make$9(page, input.perform, input.preparePolicy);
3493
+ const bridge = yield* make$27(page);
3494
+ const viewport = make$3(page, bridge);
3495
+ const input = make$17(page, bridge, viewport);
3496
+ const pictures = yield* make$14(page, bridge, viewport);
3497
+ const reading = yield* make$12(page, bridge);
3498
+ const navigation = make$8(page, input.perform, input.preparePolicy);
3518
3499
  const { capture } = pictures;
3519
- const changes = make$11(page, bridge, pictures.estimate);
3520
- const overlay = make$8(page, bridge);
3521
- const poses = make$7(page, bridge);
3500
+ const changes = make$10(page, bridge, pictures.estimate);
3501
+ const overlay = make$7(page, bridge);
3502
+ const poses = make$6(page, bridge);
3522
3503
  const titles = lane.shared("title", true);
3523
3504
  const viewports = lane.shared("viewport", true);
3524
- const state = Effect.map(capture.latest, (latest) => {
3505
+ const state = Effect.sync(() => {
3525
3506
  const { document, url } = bridge.frameTag();
3526
3507
  const committedAt = page.activity.documentAt;
3527
3508
  return new State({
@@ -3531,10 +3512,7 @@ const make$3 = Effect.fnUntraced(function* (options) {
3531
3512
  url,
3532
3513
  document,
3533
3514
  committedAt: Number.isFinite(committedAt) ? committedAt : void 0,
3534
- load: bridge.loaded(),
3535
- frame: Option.getOrUndefined(latest),
3536
- overlay: overlay.drawn(),
3537
- text: reading.viewedSince(committedAt)
3515
+ load: bridge.loaded()
3538
3516
  });
3539
3517
  });
3540
3518
  const current = (frame) => capture.current(frame) && bridge.frameTag().document === frame.document && frame.hostTime - frame.timing.uncertaintyMillis > page.activity.documentAt;
@@ -3545,43 +3523,43 @@ const make$3 = Effect.fnUntraced(function* (options) {
3545
3523
  ...navigation
3546
3524
  }, action));
3547
3525
  return {
3548
- ...make$6(page, bridge, input),
3526
+ [key]: new Implementation({
3527
+ snapshot: reading.snapshot,
3528
+ find: reading.find,
3529
+ until: reading.until,
3530
+ text: reading.text,
3531
+ layout: make$13(page, bridge),
3532
+ changes,
3533
+ window: make$9(page, changes, capture.recent),
3534
+ overlay: overlay.lease,
3535
+ drawn: Effect.sync(() => Option.fromUndefinedOr(overlay.drawn())),
3536
+ poses: poses.lease,
3537
+ hold: make$4(page, bridge, overlay, poses).hold,
3538
+ frame: pictures.frame,
3539
+ zoom: pictures.zoom,
3540
+ capture: (options) => capture.open(options).pipe(Effect.map((lease) => ({
3541
+ ...lease,
3542
+ isCurrent: current,
3543
+ confirm,
3544
+ sync: capture.sync,
3545
+ stats: pictures.captureStats
3546
+ }))),
3547
+ recentFrames: capture.recent,
3548
+ paint: pictures.paint
3549
+ }),
3550
+ ...make$5(page, bridge, input),
3549
3551
  ...methods(perform),
3550
3552
  perform,
3551
- clock: page.clock,
3553
+ hostClock: page.clock,
3552
3554
  afterInput,
3553
- until: reading.until,
3554
- capture: (options) => capture.open(options).pipe(Effect.map((lease) => ({
3555
- ...lease,
3556
- isCurrent: current,
3557
- confirm,
3558
- sync: capture.sync,
3559
- stats: pictures.captureStats
3560
- }))),
3561
3555
  id,
3562
3556
  url: Effect.sync(() => redact(playwright.url())),
3563
3557
  title: titles("", navigation.title.pipe(within("title"))).pipe(span("Page.title"), owned),
3564
3558
  bringToFront: native("bringToFront", () => playwright.bringToFront()),
3565
3559
  close: native("close", () => playwright.close()),
3566
- snapshot: reading.snapshot,
3567
- screenshot: pictures.screenshot,
3568
- frame: pictures.frame,
3569
- zoom: pictures.zoom,
3570
- paint: pictures.paint,
3571
3560
  viewport: viewports("", viewport.viewportFor("viewport").pipe(within("viewport"))).pipe(span("Page.viewport"), owned),
3572
- find: reading.find,
3573
- layout: make$14(page, bridge),
3574
- overlay: overlay.lease,
3575
- poses: poses.lease,
3576
- hold: make$5(page, bridge, overlay, poses).hold,
3577
- text: reading.text,
3578
- changes,
3579
- window: make$10(page, changes, capture.recent),
3580
3561
  state,
3581
- ready: make$12(page, bridge),
3582
- screencast: capture.stream,
3583
- captureStats: pictures.captureStats,
3584
- recentFrames: capture.recent,
3562
+ ready: make$11(page, bridge),
3585
3563
  recentEvents: options.recentEvents
3586
3564
  };
3587
3565
  });
@@ -3649,7 +3627,7 @@ const queryTarget = async (chrome, target, method, params, signal, session, hook
3649
3627
  await chrome.send("Target.detachFromTarget", { sessionId });
3650
3628
  }
3651
3629
  };
3652
- const make$2 = Effect.fnUntraced(function* (context, chrome, native, closing) {
3630
+ const make$1 = Effect.fnUntraced(function* (context, chrome, native, closing) {
3653
3631
  const clock = yield* Clock.Clock;
3654
3632
  const hooks = yield* Current$1;
3655
3633
  const protocol = yield* Effect.context();
@@ -3821,7 +3799,7 @@ const install = Effect.fnUntraced(function* (context, policy, clock, publish, no
3821
3799
  return session;
3822
3800
  })), (chrome) => native(() => chrome.detach(), true).pipe(Effect.orDie));
3823
3801
  let closing = false;
3824
- const owner = yield* make$2(context, chrome, native, () => closing);
3802
+ const owner = yield* make$1(context, chrome, native, () => closing);
3825
3803
  const held = /* @__PURE__ */ new Map();
3826
3804
  const pending = yield* Queue.unbounded();
3827
3805
  const workers = yield* Scope.make();
@@ -3877,94 +3855,49 @@ const install = Effect.fnUntraced(function* (context, policy, clock, publish, no
3877
3855
  yield* owner.refresh;
3878
3856
  });
3879
3857
  //#endregion
3880
- //#region src/internal/timeline/events.ts
3881
- /**
3882
- * The browser's bounded event history and replay cursors. Readers share the same records and
3883
- * wakeup generation, so a delayed reader cannot block input or retain an unbounded private queue.
3884
- */
3885
- /** The owning Browser validates capacity and closes this timeline with its scope. */
3886
- const make$1 = (capacity) => {
3887
- const records = Array.from({ length: capacity });
3888
- let start = 0;
3889
- let size = 0;
3890
- let sequence = 0;
3891
- let closed = false;
3892
- let changed = Deferred.makeUnsafe();
3893
- const wake = () => {
3894
- const previous = changed;
3895
- changed = Deferred.makeUnsafe();
3896
- Deferred.doneUnsafe(previous, Effect.void);
3897
- };
3898
- const publish = (event) => {
3899
- if (closed) return sequence;
3900
- sequence += 1;
3901
- const recorded = new RecordedEvent({
3902
- sequence,
3903
- event
3904
- });
3905
- records[(start + size) % capacity] = recorded;
3906
- if (size < capacity) size++;
3907
- else start = (start + 1) % capacity;
3908
- wake();
3909
- return sequence;
3910
- };
3911
- const stream = (after) => Stream.unwrap(Effect.sync(() => {
3912
- let cursor = after ?? sequence;
3913
- if (!Number.isSafeInteger(cursor) || cursor < 0 || cursor > sequence) return Stream.fromEffect(refuse("events", "the event cursor must be a nonnegative integer no greater than the latest sequence"));
3914
- return Stream.fromEffectRepeat(Effect.gen(function* () {
3915
- while (true) {
3916
- const oldest = sequence - size + 1;
3917
- if (cursor < oldest - 1) return yield* undispatched("events", new EventHistoryExpired({
3918
- after: cursor,
3919
- oldest,
3920
- latest: sequence
3921
- }));
3922
- const next = cursor < sequence ? records[(start + cursor - oldest + 1) % capacity] : void 0;
3923
- if (next !== void 0) {
3924
- cursor = next.sequence;
3925
- return next;
3926
- }
3927
- if (closed) return yield* Cause.done();
3928
- const waiting = changed;
3929
- yield* Deferred.await(waiting);
3930
- }
3931
- }));
3932
- }));
3933
- return {
3934
- publish,
3935
- sequence: () => sequence,
3936
- recent: Effect.sync(() => Array.from({ length: size }, (_, index) => records[(start + index) % capacity]).filter((record) => record !== void 0)),
3937
- stream,
3938
- close: Effect.sync(() => {
3939
- if (closed) return;
3940
- closed = true;
3941
- wake();
3942
- })
3943
- };
3944
- };
3945
- //#endregion
3946
3858
  //#region src/Browser.ts
3947
3859
  /**
3948
3860
  * A live browser: its pages and what happens in it.
3949
3861
  *
3950
3862
  * `Browser` is a service with one implementation, built by a provider over a Playwright browser
3951
3863
  * context: `Chromium` launches one locally, `Cdp` connects to any DevTools endpoint and
3952
- * `effect-browserbase` allocates a hosted one. Code written against `Browser` runs on all three.
3864
+ * `@effect-browser/browserbase` allocates a hosted one. Code written against `Browser` runs on all three.
3953
3865
  * A page is named by its CDP target id, so a new connection to the same browser finds it again.
3954
3866
  *
3867
+ * @stability stable
3955
3868
  * @since 0.3.0
3956
3869
  */
3957
3870
  var Browser_exports = /* @__PURE__ */ __exportAll({
3958
3871
  Browser: () => Browser,
3959
3872
  Suspension: () => Suspension,
3960
- make: () => make
3873
+ make: () => make,
3874
+ newPage: () => newPage
3961
3875
  });
3962
- /** When admitted input finished; events after `since` describe the handoff interval. */
3963
- var Suspension = class extends Schema.Class("effect-browser/Suspension")({
3876
+ /**
3877
+ * When admitted input finished; events after `since` describe the handoff interval.
3878
+ *
3879
+ * @stability stable
3880
+ * @category schemas
3881
+ * @since 0.3.0
3882
+ */
3883
+ var Suspension = class extends Schema.Class("effect-browser/Browser/Suspension")({
3964
3884
  since: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
3965
3885
  at: Schema.Finite
3966
3886
  }) {};
3887
+ /**
3888
+ * @stability stable
3889
+ * @category services
3890
+ * @since 0.3.0
3891
+ */
3967
3892
  var Browser = class extends Context.Service()("effect-browser/Browser") {};
3893
+ /**
3894
+ * Open a page in the context's `Browser`, at `url` when given.
3895
+ *
3896
+ * @stability stable
3897
+ * @category constructors
3898
+ * @since 0.3.0
3899
+ */
3900
+ const newPage = (url) => Effect.flatMap(Browser, (browser) => browser.newPage(url));
3968
3901
  /** The settings every page shares, and how many events the browser keeps, from its options. */
3969
3902
  const settingsOf = Effect.fnUntraced(function* (options) {
3970
3903
  const invalid = (detail) => undispatched("make", new InvalidRequest({ detail }));
@@ -3978,7 +3911,7 @@ const settingsOf = Effect.fnUntraced(function* (options) {
3978
3911
  frameHistory: yield* bound("frameHistory", options.frameHistory, Duration.seconds(5)),
3979
3912
  guard: options.guard,
3980
3913
  policyTimeout: yield* bound("policyTimeout", options.policyTimeout, Duration.minutes(5)),
3981
- pageTime: options.pageTime === true ? `effect-browser-time-${yield* make$27}` : void 0
3914
+ pageTime: options.pageTime === true ? `effect-browser-time-${yield* make$26}` : void 0
3982
3915
  };
3983
3916
  if (options.viewport !== void 0 && ![options.viewport.width, options.viewport.height].every((size) => Number.isSafeInteger(size) && size > 0)) return yield* invalid("viewport dimensions must be positive safe integers");
3984
3917
  const eventHistory = options.eventHistory ?? 4096;
@@ -4146,14 +4079,14 @@ const tabs = (context, registry, budget, native, register, release, firstPageLoc
4146
4079
  /** One connection owns clocks, loss, authority and its bounded timeline. */
4147
4080
  const runtime = Effect.fnUntraced(function* (context, expiresAt, options) {
4148
4081
  const clock = yield* Clock.Clock;
4149
- const connection = yield* make$27;
4082
+ const connection = yield* make$26;
4150
4083
  const protocol = yield* Current$1;
4151
4084
  const releasePort = protocol.browser?.(connection, context);
4152
4085
  yield* Effect.addFinalizer(() => Effect.sync(() => releasePort?.()));
4153
4086
  const now = () => monotonicMillis(clock);
4154
4087
  const { settings, eventHistory, maxPages } = yield* settingsOf(options);
4155
4088
  const mapping$1 = mapping(now);
4156
- const timeline = make$1(eventHistory);
4089
+ const timeline = make$32(eventHistory);
4157
4090
  yield* Effect.addFinalizer(() => timeline.close);
4158
4091
  const publish = timeline.publish;
4159
4092
  if (expiresAt !== void 0) publish(new SessionEnding({
@@ -4180,7 +4113,7 @@ const runtime = Effect.fnUntraced(function* (context, expiresAt, options) {
4180
4113
  lose,
4181
4114
  untilLost,
4182
4115
  native,
4183
- inputGate: make$31({
4116
+ inputGate: make$30({
4184
4117
  now,
4185
4118
  sequence: timeline.sequence,
4186
4119
  closedBy: lostBy,
@@ -4195,6 +4128,10 @@ const runtime = Effect.fnUntraced(function* (context, expiresAt, options) {
4195
4128
  * tracks its pages and events, for as long as the surrounding scope is open. Each page's protocol
4196
4129
  * session, capture and listeners end when that page closes or when the scope does, so a closed
4197
4130
  * tab retains nothing and the context keeps none of them afterwards.
4131
+ *
4132
+ * @stability stable
4133
+ * @category constructors
4134
+ * @since 0.3.0
4198
4135
  */
4199
4136
  const make = Effect.fn("Browser.make")(function* (context, info, options = {}) {
4200
4137
  const { clock, connection, protocol, now, settings, maxPages, mapping, timeline, publish, lostBy, lost, lose, untilLost, native, inputGate } = yield* runtime(context, info.expiresAt, options);
@@ -4220,7 +4157,7 @@ const make = Effect.fn("Browser.make")(function* (context, info, options = {}) {
4220
4157
  const paging = sentNow(send("Page.enable"));
4221
4158
  const { targetInfo } = yield* native("newPage", () => send("Target.getTargetInfo"));
4222
4159
  const id = targetInfo.targetId;
4223
- const page = yield* make$3({
4160
+ const page = yield* make$2({
4224
4161
  id,
4225
4162
  session,
4226
4163
  connection,
@@ -4235,7 +4172,7 @@ const make = Effect.fn("Browser.make")(function* (context, info, options = {}) {
4235
4172
  mapping,
4236
4173
  publish,
4237
4174
  recentEvents: eventsOf(timeline.recent, id),
4238
- openings: yield* make$26(playwright, cdp, registrations, closedBy),
4175
+ openings: yield* make$25(playwright, cdp, registrations, closedBy),
4239
4176
  focused: call("focus", () => focusing, closedBy).pipe(Effect.asVoid),
4240
4177
  paging: (operation) => call(operation, () => paging, closedBy).pipe(Effect.asVoid),
4241
4178
  closedBy,
@@ -4297,6 +4234,6 @@ const make = Effect.fn("Browser.make")(function* (context, info, options = {}) {
4297
4234
  return Browser.of(service);
4298
4235
  });
4299
4236
  //#endregion
4300
- export { make$1 as a, make as i, Browser_exports as n, make$31 as o, Suspension as r, Browser as t };
4237
+ export { newPage as a, make as i, Browser_exports as n, make$30 as o, Suspension as r, Browser as t };
4301
4238
 
4302
- //# sourceMappingURL=Browser-CAQFhTkM.mjs.map
4239
+ //# sourceMappingURL=Browser-vzD7i2oj.mjs.map