effect-browser 0.3.0-beta.21 → 0.3.0-beta.23

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 (249) hide show
  1. package/README.md +130 -159
  2. package/dist/Action-24sLOubi.d.mts +110 -0
  3. package/dist/Action.d.mts +2 -0
  4. package/dist/Action.mjs +141 -0
  5. package/dist/Action.mjs.map +1 -0
  6. package/dist/ActionPort.d.mts +15 -0
  7. package/dist/ActionPort.mjs +101 -0
  8. package/dist/ActionPort.mjs.map +1 -0
  9. package/dist/Browser-BKPAbyys.mjs +4076 -0
  10. package/dist/Browser-BKPAbyys.mjs.map +1 -0
  11. package/dist/{Browser-CiXHT1yO.d.mts → Browser-wZhwZSlG.d.mts} +51 -13
  12. package/dist/Browser.d.mts +2 -2
  13. package/dist/Browser.mjs +1 -1
  14. package/dist/{BrowserError-Coy7EW1N.d.mts → BrowserError-BlcmLVzn.d.mts} +22 -7
  15. package/dist/BrowserError.d.mts +2 -2
  16. package/dist/BrowserError.mjs +46 -9
  17. package/dist/BrowserError.mjs.map +1 -1
  18. package/dist/{BrowserEvent-dq6FRT8w.d.mts → BrowserEvent-lLqJ3GJS.d.mts} +93 -37
  19. package/dist/BrowserEvent.d.mts +2 -2
  20. package/dist/BrowserEvent.mjs +29 -24
  21. package/dist/BrowserEvent.mjs.map +1 -1
  22. package/dist/{Change-DqING3tr.d.mts → Change-Ba7INmay.d.mts} +4 -6
  23. package/dist/Change.d.mts +2 -2
  24. package/dist/Change.mjs +97 -2
  25. package/dist/Change.mjs.map +1 -0
  26. package/dist/Clock.d.mts +57 -0
  27. package/dist/Clock.mjs +80 -0
  28. package/dist/Clock.mjs.map +1 -0
  29. package/dist/{Frame-DkNdjjjr.d.mts → Frame-UEH2hO5T.d.mts} +10 -3
  30. package/dist/Frame.d.mts +2 -2
  31. package/dist/Frame.mjs +10 -2
  32. package/dist/Frame.mjs.map +1 -1
  33. package/dist/{Motion-DND6I-64.d.mts → Geometry-DJx9qrYy.d.mts} +7 -10
  34. package/dist/Geometry.d.mts +2 -0
  35. package/dist/Geometry.mjs +32 -0
  36. package/dist/Geometry.mjs.map +1 -0
  37. package/dist/Matching.d.mts +37 -0
  38. package/dist/Matching.mjs +72 -0
  39. package/dist/Matching.mjs.map +1 -0
  40. package/dist/Page-BF5izr8R.mjs +795 -0
  41. package/dist/Page-BF5izr8R.mjs.map +1 -0
  42. package/dist/{Page-ku6j5t-v.d.mts → Page-CvsOEorc.d.mts} +158 -185
  43. package/dist/Page.d.mts +2 -2
  44. package/dist/Page.mjs +1 -1
  45. package/dist/Released-tURbFmal.d.mts +15 -0
  46. package/dist/{Snapshot-B34hZ4Jl.d.mts → Snapshot-CtBVOtuu.d.mts} +6 -1
  47. package/dist/Snapshot.d.mts +1 -1
  48. package/dist/Snapshot.mjs.map +1 -1
  49. package/dist/Stillness-CNlvayIo.mjs +136 -0
  50. package/dist/Stillness-CNlvayIo.mjs.map +1 -0
  51. package/dist/Style-AO4V7Czt.mjs +357 -0
  52. package/dist/Style-AO4V7Czt.mjs.map +1 -0
  53. package/dist/Style.d.mts +72 -0
  54. package/dist/Style.mjs +2 -0
  55. package/dist/Url.d.mts +26 -0
  56. package/dist/Url.mjs +74 -0
  57. package/dist/Url.mjs.map +1 -0
  58. package/dist/Window-CMddGMt1.d.mts +34 -0
  59. package/dist/Window.d.mts +2 -0
  60. package/dist/Window.mjs +35 -0
  61. package/dist/Window.mjs.map +1 -0
  62. package/dist/{cdp-DL7XfEj5.d.mts → connection-2KHI4_KN.d.mts} +4 -4
  63. package/dist/{cdp-BMpYMWYe.mjs → connection-CK83pvqP.mjs} +5 -6
  64. package/dist/connection-CK83pvqP.mjs.map +1 -0
  65. package/dist/index.d.mts +15 -18
  66. package/dist/index.mjs +11 -15
  67. package/dist/moment/Moment.d.mts +86 -0
  68. package/dist/{Moment.mjs → moment/Moment.mjs} +44 -38
  69. package/dist/moment/Moment.mjs.map +1 -0
  70. package/dist/{Plan-DJ4hEEna.d.mts → plan/index.d.mts} +169 -64
  71. package/dist/{Plan-BG1WifW2.mjs → plan/index.mjs} +122 -199
  72. package/dist/plan/index.mjs.map +1 -0
  73. package/dist/{Policy-BGWjbqCl.d.mts → policy/Policy.d.mts} +16 -20
  74. package/dist/{Policy.mjs → policy/Policy.mjs} +11 -21
  75. package/dist/policy/Policy.mjs.map +1 -0
  76. package/dist/presentation/Motion.d.mts +12 -0
  77. package/dist/{Motion.mjs → presentation/Motion.mjs} +4 -27
  78. package/dist/presentation/Motion.mjs.map +1 -0
  79. package/dist/presentation/Presentation.d.mts +30 -0
  80. package/dist/presentation/Presentation.mjs +105 -0
  81. package/dist/presentation/Presentation.mjs.map +1 -0
  82. package/dist/{Stage-NHp8N81k.d.mts → presentation/Stage.d.mts} +12 -15
  83. package/dist/{Stage.mjs → presentation/Stage.mjs} +68 -76
  84. package/dist/presentation/Stage.mjs.map +1 -0
  85. package/dist/presentation/feed.d.mts +20 -0
  86. package/dist/presentation/feed.mjs +18 -0
  87. package/dist/presentation/feed.mjs.map +1 -0
  88. package/dist/providers/Cdp.d.mts +9 -0
  89. package/dist/{Cdp.mjs → providers/Cdp.mjs} +3 -8
  90. package/dist/providers/Cdp.mjs.map +1 -0
  91. package/dist/{Chromium.d.mts → providers/Chromium.d.mts} +6 -7
  92. package/dist/{Chromium.mjs → providers/Chromium.mjs} +6 -15
  93. package/dist/providers/Chromium.mjs.map +1 -0
  94. package/dist/providers/Released.d.mts +2 -0
  95. package/dist/providers/Released.mjs +12 -0
  96. package/dist/providers/Released.mjs.map +1 -0
  97. package/dist/stillness/Stillness.d.mts +12 -0
  98. package/dist/stillness/Stillness.mjs +2 -0
  99. package/dist/supervisor/Supervisor.d.mts +104 -0
  100. package/dist/supervisor/Supervisor.mjs +515 -0
  101. package/dist/supervisor/Supervisor.mjs.map +1 -0
  102. package/dist/testing/index.d.mts +337 -0
  103. package/dist/testing/index.mjs +515 -0
  104. package/dist/testing/index.mjs.map +1 -0
  105. package/dist/workerd/Cdp.d.mts +8 -3
  106. package/dist/workerd/Cdp.mjs +2 -7
  107. package/dist/workerd/Cdp.mjs.map +1 -1
  108. package/package.json +89 -39
  109. package/src/Action.ts +127 -0
  110. package/src/ActionPort.ts +128 -0
  111. package/src/Browser.ts +352 -201
  112. package/src/BrowserError.ts +63 -6
  113. package/src/BrowserEvent.ts +26 -25
  114. package/src/Change.ts +0 -2
  115. package/src/{internal/pictures/clock.ts → Clock.ts} +17 -6
  116. package/src/Frame.ts +14 -0
  117. package/src/Geometry.ts +48 -0
  118. package/src/{internal/reading/match.inpage.ts → Matching.ts} +34 -4
  119. package/src/Page.ts +111 -92
  120. package/src/Snapshot.ts +5 -0
  121. package/src/{internal/input/style.ts → Style.ts} +121 -14
  122. package/src/Window.ts +30 -0
  123. package/src/index.ts +15 -6
  124. package/src/internal/input/actions.ts +61 -119
  125. package/src/internal/input/dispatch.ts +3 -3
  126. package/src/internal/input/gate.ts +21 -18
  127. package/src/internal/input/guard.inpage.ts +25 -58
  128. package/src/internal/input/guard.ts +11 -20
  129. package/src/internal/input/keyboard.ts +12 -3
  130. package/src/internal/input/perform.ts +78 -60
  131. package/src/internal/input/pointer.ts +4 -2
  132. package/src/internal/input/settle.ts +7 -5
  133. package/src/internal/input/targets.inpage.ts +1 -1
  134. package/src/internal/input/targets.ts +4 -9
  135. package/src/internal/page/bridge.ts +209 -113
  136. package/src/internal/page/context.ts +12 -59
  137. package/src/internal/page/dialogs.ts +58 -0
  138. package/src/internal/page/identity.ts +6 -5
  139. package/src/internal/page/lane.ts +14 -15
  140. package/src/internal/page/navigation.ts +50 -42
  141. package/src/internal/page/openings.ts +11 -5
  142. package/src/internal/page/page.ts +44 -81
  143. package/src/internal/page/port.ts +125 -0
  144. package/src/internal/{input → page}/replies.ts +1 -1
  145. package/src/internal/page/request-owner.ts +269 -0
  146. package/src/internal/page/requests.ts +357 -0
  147. package/src/internal/page/scripts.ts +124 -0
  148. package/src/internal/pictures/capture.ts +255 -332
  149. package/src/internal/pictures/dimensions.ts +162 -0
  150. package/src/internal/pictures/frame.ts +68 -0
  151. package/src/internal/pictures/pictures.ts +57 -23
  152. package/src/internal/pictures/quiescence.ts +1 -1
  153. package/src/internal/pictures/state.ts +26 -0
  154. package/src/internal/pictures/transport.ts +21 -4
  155. package/src/internal/reading/controls.inpage.ts +5 -70
  156. package/src/internal/reading/expect.inpage.ts +13 -17
  157. package/src/internal/reading/names.inpage.ts +89 -45
  158. package/src/internal/reading/outline.inpage.ts +6 -7
  159. package/src/internal/reading/reading.ts +144 -176
  160. package/src/internal/reading/ready.inpage.ts +6 -17
  161. package/src/internal/reading/ready.ts +13 -135
  162. package/src/internal/reading/subjects.inpage.ts +83 -43
  163. package/src/internal/reading/walk.inpage.ts +33 -13
  164. package/src/internal/timeline/changes.ts +55 -6
  165. package/src/internal/timeline/events.ts +15 -5
  166. package/src/internal/timeline/history.inpage.ts +1 -1
  167. package/src/internal/timeline/record.inpage.ts +4 -1
  168. package/src/internal/timeline/window.ts +2 -1
  169. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  170. package/src/{internal/timeline → moment}/words.ts +2 -2
  171. package/src/{internal/reading → plan}/choose.ts +3 -3
  172. package/src/plan/data.ts +117 -0
  173. package/src/plan/execute.ts +411 -0
  174. package/src/plan/index.ts +36 -0
  175. package/src/plan/record.ts +71 -0
  176. package/src/plan/targets.ts +71 -0
  177. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  178. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  179. package/src/presentation/Presentation.ts +176 -0
  180. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  181. package/src/presentation/feed.ts +21 -0
  182. package/src/{Cdp.ts → providers/Cdp.ts} +2 -2
  183. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  184. package/src/providers/Released.ts +13 -0
  185. package/src/{internal/cdp.ts → providers/connection.ts} +2 -2
  186. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +1 -1
  187. package/src/stillness/Stillness.ts +166 -0
  188. package/src/supervisor/Supervisor.ts +170 -0
  189. package/src/supervisor/contract.ts +105 -0
  190. package/src/supervisor/lifecycle.ts +272 -0
  191. package/src/supervisor/runtime.ts +238 -0
  192. package/src/testing/TestBrowser.ts +115 -0
  193. package/src/testing/TestPage.ts +10 -0
  194. package/src/testing/evidence.ts +154 -0
  195. package/src/testing/index.ts +3 -0
  196. package/src/testing/model.ts +222 -0
  197. package/src/testing/page.ts +360 -0
  198. package/src/workerd/Cdp.ts +2 -2
  199. package/dist/Browser-CxXUjxOp.mjs +0 -619
  200. package/dist/Browser-CxXUjxOp.mjs.map +0 -1
  201. package/dist/Cdp-CzCRnMlM.d.mts +0 -10
  202. package/dist/Cdp.d.mts +0 -11
  203. package/dist/Cdp.mjs.map +0 -1
  204. package/dist/Change-DNvztNLu.mjs +0 -138
  205. package/dist/Change-DNvztNLu.mjs.map +0 -1
  206. package/dist/Chromium.mjs.map +0 -1
  207. package/dist/Expect-u3P_ENLX.d.mts +0 -62
  208. package/dist/Expect.d.mts +0 -2
  209. package/dist/Expect.mjs +0 -114
  210. package/dist/Expect.mjs.map +0 -1
  211. package/dist/Moment.d.mts +0 -2
  212. package/dist/Moment.mjs.map +0 -1
  213. package/dist/Motion.d.mts +0 -2
  214. package/dist/Motion.mjs.map +0 -1
  215. package/dist/Page-BP02bmNv.mjs +0 -264
  216. package/dist/Page-BP02bmNv.mjs.map +0 -1
  217. package/dist/Plan-BG1WifW2.mjs.map +0 -1
  218. package/dist/Plan.d.mts +0 -2
  219. package/dist/Plan.mjs +0 -2
  220. package/dist/Policy.d.mts +0 -2
  221. package/dist/Policy.mjs.map +0 -1
  222. package/dist/Presentation-DxVikn9_.d.mts +0 -48
  223. package/dist/Presentation.d.mts +0 -2
  224. package/dist/Presentation.mjs +0 -118
  225. package/dist/Presentation.mjs.map +0 -1
  226. package/dist/Stage.d.mts +0 -2
  227. package/dist/Stage.mjs.map +0 -1
  228. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  229. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  230. package/dist/Supervisor-CfRxbaso.d.mts +0 -317
  231. package/dist/Supervisor.d.mts +0 -2
  232. package/dist/Supervisor.mjs +0 -2
  233. package/dist/cdp-BMpYMWYe.mjs.map +0 -1
  234. package/dist/context-EGhOqjNN.mjs +0 -335
  235. package/dist/context-EGhOqjNN.mjs.map +0 -1
  236. package/dist/page-PTM8m5wC.mjs +0 -4057
  237. package/dist/page-PTM8m5wC.mjs.map +0 -1
  238. package/dist/url-Bsp2y55M.mjs +0 -264
  239. package/dist/url-Bsp2y55M.mjs.map +0 -1
  240. package/dist/workerd/index.d.mts +0 -16
  241. package/dist/workerd/index.mjs +0 -17
  242. package/src/Expect.ts +0 -180
  243. package/src/Plan.ts +0 -674
  244. package/src/Presentation.ts +0 -196
  245. package/src/Supervisor.ts +0 -632
  246. package/src/internal/supervisor/lifecycle.ts +0 -484
  247. package/src/workerd/index.ts +0 -17
  248. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  249. /package/src/{internal/pictures → stillness}/utilsBundle.d.ts +0 -0
@@ -0,0 +1,4076 @@
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, 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$28, 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-BF5izr8R.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 { d as parts$1, l as validated, t as Current$2, u as description } from "./Style-AO4V7Czt.mjs";
13
+ import { request } from "./Matching.mjs";
14
+ import { Change, Changes } from "./Change.mjs";
15
+ import { Window } from "./Window.mjs";
16
+ 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";
17
+ import { SecureRandom } from "effect/crypto";
18
+ import { Base64 } from "effect/encoding";
19
+ //#region src/internal/input/gate.ts
20
+ /**
21
+ * A browser's input authority: stop admitting writes, drain admitted operations through their
22
+ * records and native replies, then retain the stop for its scopes. Reads never enter this gate.
23
+ */
24
+ const without = (set, id) => new Set([...set].filter((each) => each !== id));
25
+ const step$1 = (state, input, stopped) => {
26
+ switch (input._tag) {
27
+ case "Enter": return state._tag === "Open" ? {
28
+ ...state,
29
+ inputs: /* @__PURE__ */ new Set([...state.inputs, input.id])
30
+ } : state;
31
+ case "End": {
32
+ if (state._tag === "Held") return state;
33
+ const inputs = without(state.inputs, input.id);
34
+ return state._tag === "Draining" && inputs.size === 0 ? {
35
+ _tag: "Held",
36
+ claims: state.claims,
37
+ stopped
38
+ } : {
39
+ ...state,
40
+ inputs
41
+ };
42
+ }
43
+ case "Suspend":
44
+ if (state._tag !== "Open") return {
45
+ ...state,
46
+ claims: /* @__PURE__ */ new Set([...state.claims, input.id])
47
+ };
48
+ return state.inputs.size === 0 ? {
49
+ _tag: "Held",
50
+ claims: /* @__PURE__ */ new Set([input.id]),
51
+ stopped
52
+ } : {
53
+ _tag: "Draining",
54
+ inputs: state.inputs,
55
+ claims: /* @__PURE__ */ new Set([input.id]),
56
+ startedAt: stopped.at,
57
+ deadline: stopped.at + input.drain
58
+ };
59
+ case "Leave": {
60
+ if (state._tag === "Open" || !state.claims.has(input.id)) return state;
61
+ const claims = without(state.claims, input.id);
62
+ return claims.size > 0 ? {
63
+ ...state,
64
+ claims
65
+ } : {
66
+ _tag: "Open",
67
+ inputs: state._tag === "Draining" ? state.inputs : /* @__PURE__ */ new Set()
68
+ };
69
+ }
70
+ case "Expire": return state._tag === "Draining" && stopped.at >= state.deadline ? {
71
+ _tag: "Open",
72
+ inputs: state.inputs
73
+ } : state;
74
+ }
75
+ };
76
+ const make$27 = (options) => {
77
+ let state = {
78
+ _tag: "Open",
79
+ inputs: /* @__PURE__ */ new Set()
80
+ };
81
+ let next = 0;
82
+ let refused = Deferred.makeUnsafe();
83
+ let ready = Deferred.makeUnsafe();
84
+ const error = (operation) => undispatched(operation, options.closedBy() === void 0 ? new Suspended() : new Closed({ cause: options.closedBy() ?? "connection" }));
85
+ const stopped = () => ({
86
+ since: options.sequence(),
87
+ at: options.now()
88
+ });
89
+ const apply = (input) => {
90
+ if (input._tag !== "Expire" && state._tag === "Draining" && options.now() >= state.deadline) apply({ _tag: "Expire" });
91
+ const before = state;
92
+ state = step$1(state, input, stopped());
93
+ if (input._tag === "Expire" && before._tag === "Draining" && state._tag === "Open") Deferred.doneUnsafe(ready, Exit.fail(undispatched("suspend", new Busy({
94
+ waitedMillis: Math.round(options.now() - before.startedAt),
95
+ ahead: before.inputs.size
96
+ }))));
97
+ if (before._tag === "Open" && state._tag !== "Open") Deferred.doneUnsafe(refused, Exit.void);
98
+ if (before._tag === "Draining" && state._tag === "Held") Deferred.doneUnsafe(ready, Exit.succeed(state.stopped));
99
+ if (before._tag !== "Open" && state._tag === "Open") {
100
+ refused = Deferred.makeUnsafe();
101
+ ready = Deferred.makeUnsafe();
102
+ }
103
+ return state;
104
+ };
105
+ const check = (operation) => Effect.suspend(() => state._tag === "Open" && options.closedBy() === void 0 ? Effect.void : Effect.fail(error(operation)));
106
+ const suspend = (drain = options.drain) => Effect.suspend(() => {
107
+ const duration = Duration.fromInput(drain);
108
+ if (Option.isNone(duration) || !Duration.isFinite(duration.value) || Duration.toMillis(duration.value) < 0) return Effect.fail(undispatched("suspend", new InvalidRequest({ detail: "drain must be a finite nonnegative duration" })));
109
+ const id = ++next;
110
+ const leave = Effect.sync(() => apply({
111
+ _tag: "Leave",
112
+ id
113
+ }));
114
+ return Effect.acquireRelease(Effect.gen(function* () {
115
+ if (options.closedBy() !== void 0) return yield* error("suspend");
116
+ const current = apply({
117
+ _tag: "Suspend",
118
+ id,
119
+ drain: Duration.toMillis(duration.value)
120
+ });
121
+ if (current._tag === "Held") return current.stopped;
122
+ if (current._tag !== "Draining") return yield* Effect.die("suspension did not retain authority");
123
+ const pending = ready;
124
+ const expire = Effect.suspend(() => {
125
+ const left = current.deadline - options.now();
126
+ return left > 0 ? Effect.sleep(Duration.millis(left)).pipe(Effect.andThen(expire)) : Effect.sync(() => apply({ _tag: "Expire" })).pipe(Effect.andThen(Deferred.await(pending)));
127
+ });
128
+ const wait = Effect.raceFirst(Deferred.await(pending), expire);
129
+ return yield* Effect.raceFirst(wait, options.lost.pipe(Effect.flatMap(() => Effect.fail(error("suspend"))))).pipe(Effect.interruptible, Effect.filterOrFail(() => options.closedBy() === void 0, () => error("suspend")), Effect.onError(() => leave));
130
+ }), () => leave);
131
+ }).pipe(Effect.provideService(Clock.Clock, options.clock));
132
+ return {
133
+ check,
134
+ suspend,
135
+ refused: (operation) => Effect.suspend(() => state._tag === "Open" ? Deferred.await(refused).pipe(Effect.andThen(Effect.fail(error(operation)))) : Effect.fail(error(operation))),
136
+ enter: (operation) => Effect.suspend(() => {
137
+ if (state._tag !== "Open" || options.closedBy() !== void 0) return Effect.fail(error(operation));
138
+ const id = ++next;
139
+ apply({
140
+ _tag: "Enter",
141
+ id
142
+ });
143
+ return Effect.succeed(() => {
144
+ apply({
145
+ _tag: "End",
146
+ id
147
+ });
148
+ });
149
+ })
150
+ };
151
+ };
152
+ //#endregion
153
+ //#region src/internal/page/port.ts
154
+ /** Scoped protocol interception at the owned session boundary; native is the default. */
155
+ const Operation = Context.Reference("effect-browser/ProtocolOperation", { defaultValue: () => void 0 });
156
+ const Script = Context.Reference("effect-browser/ProtocolScript", { defaultValue: () => void 0 });
157
+ const Current$1 = Context.Reference("effect-browser/ProtocolPort", { defaultValue: () => ({}) });
158
+ /** The provider owns creation and passes its session to an optional scoped test adapter. */
159
+ const openSession = Effect.fnUntraced(function* (open, nativePage, channel = "page") {
160
+ const hooks = yield* Current$1;
161
+ const session = {
162
+ channel,
163
+ clock: yield* Clock.Clock,
164
+ page: void 0,
165
+ nativePage
166
+ };
167
+ const beforeOpen = hooks.beforeOpen;
168
+ const operation = channel === "browser" ? "requests" : "newPage";
169
+ if (beforeOpen !== void 0) yield* call(operation, () => beforeOpen(session), () => "connection");
170
+ const native = yield* call(operation, open, () => "connection");
171
+ return hooks.page?.(session, native) ?? native;
172
+ });
173
+ /** The dedicated capture connection uses the same interception and injection rules. */
174
+ const openCapture = Effect.fnUntraced(function* (page, source, handlers) {
175
+ const hooks = yield* Current$1;
176
+ const session = {
177
+ channel: "capture",
178
+ page,
179
+ clock: yield* Clock.Clock
180
+ };
181
+ const beforeOpen = hooks.beforeOpen;
182
+ if (beforeOpen !== void 0) yield* call("screencast", () => beforeOpen(session), () => "connection");
183
+ const deliver = ({ method, params }) => {
184
+ const run = ({ method, params }) => handlers.event(method, params);
185
+ if (hooks.event === void 0) run({
186
+ method,
187
+ params
188
+ });
189
+ else hooks.event(session, {
190
+ method,
191
+ params
192
+ }, run);
193
+ };
194
+ const release = hooks.opened?.(session, ({ method, params }) => handlers.event(method, params));
195
+ yield* Effect.addFinalizer(() => Effect.sync(() => release?.()));
196
+ const send = yield* source.attach(page, {
197
+ ...handlers,
198
+ event: (method, params) => deliver({
199
+ method,
200
+ params
201
+ })
202
+ });
203
+ return hooks.capture?.(session, send) ?? send;
204
+ });
205
+ var InputFailure = class extends Data.TaggedError("InputFailure") {};
206
+ /** Native page calls join their operation's reply ownership, including script mutations. */
207
+ const Current = Context.Reference("effect-browser/internal/input/Current", { defaultValue: () => void 0 });
208
+ const make$26 = () => {
209
+ const outstanding = /* @__PURE__ */ new Set();
210
+ const idle = Effect.gen(function* () {
211
+ while (outstanding.size > 0) yield* Effect.promise(() => Promise.all(outstanding));
212
+ });
213
+ /** `idle` lets an action wait, in its page's turn, for the page's earlier replies. */
214
+ return {
215
+ idle,
216
+ begin: Effect.gen(function* () {
217
+ yield* idle;
218
+ const pending = /* @__PURE__ */ new Set();
219
+ const held = [];
220
+ let failure;
221
+ let reserved = 0;
222
+ let closed = false;
223
+ const observed = /* @__PURE__ */ new WeakMap();
224
+ const endings = /* @__PURE__ */ new Set();
225
+ const track = (response, input = false) => {
226
+ const existing = observed.get(response);
227
+ if (existing !== void 0) {
228
+ existing.input ||= input;
229
+ return response;
230
+ }
231
+ const entry = { input };
232
+ observed.set(response, entry);
233
+ const reply = response.then(() => void 0, (cause) => {
234
+ if (entry.input) failure ??= new InputFailure({ cause });
235
+ }).then(() => {
236
+ pending.delete(reply);
237
+ outstanding.delete(reply);
238
+ if (pending.size === 0) {
239
+ for (const end of endings) end();
240
+ endings.clear();
241
+ }
242
+ });
243
+ pending.add(reply);
244
+ outstanding.add(reply);
245
+ return response;
246
+ };
247
+ const requireOpen = Effect.suspend(() => closed ? Effect.fail(new InputFailure({ cause: /* @__PURE__ */ new Error("the input run has stopped") })) : Effect.void);
248
+ const requireSuccess = Effect.suspend(() => failure === void 0 ? Effect.void : Effect.fail(failure));
249
+ const submit = (command) => {
250
+ if (reserved < 1) throw new Error("input must reserve capacity before dispatch");
251
+ reserved--;
252
+ try {
253
+ track(command(), true);
254
+ } catch (cause) {
255
+ failure ??= new InputFailure({ cause });
256
+ }
257
+ };
258
+ const reserve = (commands, maximum, limit) => Effect.gen(function* () {
259
+ yield* requireOpen;
260
+ yield* requireSuccess;
261
+ if (!Number.isInteger(commands) || commands < 1 || commands > maximum) return yield* Effect.die(/* @__PURE__ */ new Error("invalid input reservation"));
262
+ while (outstanding.size + reserved + commands > limit) {
263
+ yield* Effect.promise(() => Promise.race(outstanding));
264
+ yield* requireOpen;
265
+ yield* requireSuccess;
266
+ }
267
+ reserved += commands;
268
+ });
269
+ const run = {
270
+ track,
271
+ afterIdle: (end) => {
272
+ if (pending.size === 0) end();
273
+ else endings.add(end);
274
+ },
275
+ recover: (cleanup, scope) => Effect.gen(function* () {
276
+ const replies = [...pending];
277
+ const done = Promise.withResolvers();
278
+ track(done.promise);
279
+ yield* Effect.promise(() => Promise.all(replies)).pipe(Effect.andThen(cleanup), Effect.ensuring(Effect.sync(() => done.resolve())), Effect.provideService(Current, run), Effect.interruptible, Effect.forkIn(scope));
280
+ }),
281
+ reserve: (commands) => reserve(commands, 64, 64),
282
+ reserveMotion: (commands) => reserve(commands, maximumSamples, 64 + maximumSamples),
283
+ send: (command) => Effect.gen(function* () {
284
+ yield* requireOpen;
285
+ yield* requireSuccess;
286
+ yield* Effect.sync(() => submit(command));
287
+ yield* requireSuccess;
288
+ }),
289
+ down: (key, press, release) => Effect.gen(function* () {
290
+ yield* requireOpen;
291
+ yield* requireSuccess;
292
+ yield* Effect.sync(() => {
293
+ held.push({
294
+ key,
295
+ release
296
+ });
297
+ submit(press);
298
+ });
299
+ yield* requireSuccess;
300
+ }),
301
+ up: (key) => Effect.gen(function* () {
302
+ yield* requireOpen;
303
+ yield* Effect.sync(() => {
304
+ const index = held.findLastIndex((entry) => entry.key === key);
305
+ const entry = held[index];
306
+ if (entry === void 0) return;
307
+ held.splice(index, 1);
308
+ submit(entry.release);
309
+ });
310
+ yield* requireSuccess;
311
+ }),
312
+ drain: Effect.gen(function* () {
313
+ while (pending.size > 0) yield* Effect.promise(() => Promise.all(pending));
314
+ yield* requireSuccess;
315
+ }),
316
+ close: Effect.sync(() => {
317
+ if (closed) return;
318
+ closed = true;
319
+ for (const entry of held.toReversed()) submit(entry.release);
320
+ held.length = 0;
321
+ reserved = 0;
322
+ })
323
+ };
324
+ return run;
325
+ })
326
+ };
327
+ };
328
+ //#endregion
329
+ //#region src/internal/page/context.ts
330
+ /**
331
+ * What a page's parts share: the browser state they act on, the page's own lane, pointer and
332
+ * clock, and how they call the browser and report its failures. The assembly in `page.ts` builds
333
+ * one context per page.
334
+ */
335
+ const contextGone = (error) => error.reason._tag === "Failed" && /Cannot find context|Execution context was destroyed|__effectBrowser|Inspected target navigated/i.test(error.reason.detail);
336
+ /** The cost of the page operation the current fiber runs, if any. */
337
+ const CurrentCost = Context.Reference("effect-browser/internal/page/CurrentCost", { defaultValue: () => void 0 });
338
+ /** Track the promise returned to the action, after tracing wraps it, so input counts once. */
339
+ const track = (reply) => Fiber.getCurrent()?.getRef(Current)?.track(reply) ?? reply;
340
+ const sizeOf = (value) => value === void 0 ? 0 : new TextEncoder().encode(JSON.stringify(value)).byteLength;
341
+ const decodeWith = (operation, schema) => (value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError((error) => undispatched(operation, new Failed({ detail: error.message }))));
342
+ const make$25 = (options, scope) => {
343
+ const { id, clock } = options;
344
+ const now = () => monotonicMillis(clock);
345
+ const owned = Effect.provideService(Clock.Clock, clock);
346
+ const span = (name, attributes = {}, level) => (effect) => Effect.gen(function* () {
347
+ const cost = {
348
+ enclosing: yield* CurrentCost,
349
+ calls: 0,
350
+ bytesOut: 0,
351
+ bytesIn: 0,
352
+ waitedMillis: 0,
353
+ awaiting: 0,
354
+ awaitingSince: 0
355
+ };
356
+ return yield* effect.pipe(Effect.provideService(CurrentCost, cost), Effect.ensuring(Effect.suspend(() => Effect.annotateCurrentSpan({
357
+ calls: cost.calls,
358
+ bytesOut: cost.bytesOut,
359
+ bytesIn: cost.bytesIn,
360
+ waitedMillis: Math.round(cost.waitedMillis * 10) / 10
361
+ }))));
362
+ }).pipe(Effect.withSpan(name, {
363
+ attributes: {
364
+ page: id,
365
+ ...attributes
366
+ },
367
+ ...level === void 0 ? {} : { level }
368
+ }, { captureStackTrace: false }));
369
+ const send = (method, params) => {
370
+ const cost = Fiber.getCurrent()?.getRef(CurrentCost);
371
+ const sentAt = now();
372
+ const bytesOut = sizeOf(params);
373
+ for (let each = cost; each !== void 0; each = each.enclosing) {
374
+ each.calls++;
375
+ each.bytesOut += bytesOut;
376
+ if (each.awaiting++ === 0) each.awaitingSince = sentAt;
377
+ }
378
+ const reply = options.untilLost(options.cdp.send(method, params));
379
+ if (cost === void 0) return track(reply);
380
+ const settle = (bytesIn) => {
381
+ const at = now();
382
+ for (let each = cost; each !== void 0; each = each.enclosing) {
383
+ each.bytesIn += bytesIn;
384
+ if (--each.awaiting === 0) each.waitedMillis += at - each.awaitingSince;
385
+ }
386
+ };
387
+ return track(reply.then((result) => {
388
+ settle(sizeOf(result));
389
+ return result;
390
+ }, (cause) => {
391
+ settle(0);
392
+ return Promise.reject(cause);
393
+ }));
394
+ };
395
+ const native = (operation, run, timeoutMillis) => call(operation, () => options.untilLost(track(run())), options.closedBy, timeoutMillis).pipe(Effect.provideService(Operation, operation));
396
+ /** Fail with `Timeout` once `duration` has passed, the action timeout unless another is given. */
397
+ const within = (operation, duration = options.settings.actionTimeout) => (effect) => Effect.timeoutOrElse(effect, {
398
+ duration,
399
+ orElse: () => failWith(operation, new Timeout({ millis: Duration.toMillis(duration) }))
400
+ });
401
+ const stopLoading = native("stopLoading", () => send("Page.stopLoading")).pipe(within("stopLoading", options.settings.navigationTimeout), Effect.ignore);
402
+ const activity = {
403
+ inputAt: 0,
404
+ documentAt: Number.NEGATIVE_INFINITY
405
+ };
406
+ const noteInput = () => {
407
+ activity.inputAt = Math.max(activity.inputAt, now());
408
+ };
409
+ const lane = make$28({
410
+ now,
411
+ actionTimeout: options.settings.actionTimeout,
412
+ documentAt: () => activity.documentAt,
413
+ gone: (operation) => undispatched(operation, new Closed({ cause: options.closedBy() })),
414
+ scope,
415
+ beforeWrite: options.inputGate?.check,
416
+ refusal: options.inputGate?.refused
417
+ });
418
+ const pointer = MutableRef.make(Option.none());
419
+ const protocol = { send };
420
+ return {
421
+ ...options,
422
+ lane,
423
+ pointer,
424
+ now,
425
+ scope,
426
+ owned,
427
+ span,
428
+ protocol,
429
+ native,
430
+ within,
431
+ stopLoading,
432
+ activity,
433
+ noteInput
434
+ };
435
+ };
436
+ //#endregion
437
+ //#region src/internal/page/dialogs.ts
438
+ /** Scoped dialog responses publish their actual outcome and invalidate their page after failed answers. */
439
+ /**
440
+ * What a page's own Playwright events publish, its close and crash aside, while its scope is
441
+ * open. Dialogs are answered: alerts accepted, others dismissed. The page's own session tells its
442
+ * documents' commits and loads.
443
+ */
444
+ const listen = Effect.fnUntraced(function* (playwright, page, publish, now, answer, on) {
445
+ const dialogs = yield* Queue.bounded(8);
446
+ const dialog = (shown) => {
447
+ if (!Queue.offerUnsafe(dialogs, {
448
+ kind: shown.type(),
449
+ message: shown.message().slice(0, 500)
450
+ })) on.failed();
451
+ };
452
+ yield* Queue.take(dialogs).pipe(Effect.flatMap(({ kind, message }) => {
453
+ const accept = kind === "alert" || kind === "beforeunload";
454
+ const record = (answer) => Effect.sync(() => {
455
+ publish(new DialogShown({
456
+ at: now(),
457
+ page,
458
+ kind,
459
+ message,
460
+ answer
461
+ }));
462
+ });
463
+ return answer(accept).pipe(Effect.tap(() => record(accept ? "accepted" : "dismissed")), Effect.tapError(() => record("failed").pipe(Effect.andThen(Effect.sync(on.failed)))));
464
+ }), Effect.forever, Effect.forkScoped);
465
+ yield* Effect.acquireRelease(Effect.sync(() => {
466
+ playwright.on("close", on.close);
467
+ playwright.on("crash", on.crash);
468
+ playwright.on("dialog", dialog);
469
+ }), () => Effect.sync(() => {
470
+ playwright.off("close", on.close);
471
+ playwright.off("crash", on.crash);
472
+ playwright.off("dialog", dialog);
473
+ }));
474
+ });
475
+ //#endregion
476
+ //#region src/internal/page/identity.ts
477
+ /** Connection identity uses the supplied SecureRandom service, or the host's Web Crypto on Node/Bun. */
478
+ const failed = () => undispatched("make", new Failed({ detail: "Could not name connection" }));
479
+ const make$24 = Effect.gen(function* () {
480
+ const supplied = yield* Effect.serviceOption(SecureRandom.SecureRandom);
481
+ return yield* Option.isSome(supplied) ? supplied.value.uuidV4() : Effect.try({
482
+ try: () => globalThis.crypto.randomUUID(),
483
+ catch: failed
484
+ });
485
+ });
486
+ //#endregion
487
+ //#region src/internal/page/openings.ts
488
+ /** A page's input waits for the actual tabs it opened to finish the browser's registration. */
489
+ const make$23 = Effect.fnUntraced(function* (playwright, cdp, registrations, closedBy) {
490
+ const failed = (reason) => Exit.fail(undispatched("newPage", reason));
491
+ let active;
492
+ const gone = Deferred.makeUnsafe();
493
+ const windowOpened = () => {
494
+ if (active !== void 0) active.windows += 1;
495
+ };
496
+ const popup = (opened) => {
497
+ if (active === void 0) return;
498
+ const registered = registrations.get(opened);
499
+ active.registrations.push(registered === void 0 ? failed(new Failed({ detail: "the popup has no registration" })) : Deferred.await(registered).pipe(Effect.asVoid));
500
+ Deferred.doneUnsafe(active.changed, Exit.void);
501
+ active.changed = Deferred.makeUnsafe();
502
+ };
503
+ const clear = Effect.sync(() => {
504
+ active = void 0;
505
+ });
506
+ yield* Effect.acquireRelease(Effect.sync(() => {
507
+ cdp.on("Page.windowOpen", windowOpened);
508
+ playwright.on("popup", popup);
509
+ }), () => Effect.sync(() => {
510
+ active = void 0;
511
+ cdp.off("Page.windowOpen", windowOpened);
512
+ playwright.off("popup", popup);
513
+ Deferred.doneUnsafe(gone, failed(new Closed({ cause: closedBy() })));
514
+ }));
515
+ return {
516
+ mark: () => {
517
+ const mark = {
518
+ windows: 0,
519
+ registrations: [],
520
+ changed: Deferred.makeUnsafe()
521
+ };
522
+ active = mark;
523
+ return mark;
524
+ },
525
+ clear,
526
+ settle: (mark) => Effect.gen(function* () {
527
+ while (mark.registrations.length < mark.windows) yield* Deferred.await(mark.changed);
528
+ yield* Effect.forEach(mark.registrations, (registration) => registration);
529
+ }).pipe(Effect.raceFirst(Deferred.await(gone)), Effect.ensuring(clear))
530
+ };
531
+ });
532
+ const TypeableResultSchema = Schema.Union([Schema.Struct({
533
+ ok: Schema.Literal(true),
534
+ secret: Schema.Boolean,
535
+ subject: Schema.optional(Subject)
536
+ }), Schema.Struct({
537
+ error: Schema.Literals(["stale", "untypeable"]),
538
+ detail: Schema.String
539
+ })]);
540
+ const EditFailure = Schema.Struct({
541
+ error: Schema.String,
542
+ stale: Schema.optional(Schema.Boolean)
543
+ });
544
+ const FocusResultSchema = Schema.Union([Schema.Struct({
545
+ ok: Schema.Literal(true),
546
+ detail: Schema.String,
547
+ secret: Schema.Boolean
548
+ }), EditFailure]);
549
+ const EditResultSchema = Schema.Union([Schema.Struct({
550
+ ok: Schema.Literal(true),
551
+ detail: Schema.String
552
+ }), EditFailure]);
553
+ const ResolvedPointSchema = Schema.Struct({
554
+ ...Point.fields,
555
+ ...Subject.fields,
556
+ element: Schema.String,
557
+ box: Schema.optional(Box),
558
+ cursor: Schema.String,
559
+ href: Schema.optional(Schema.String)
560
+ });
561
+ const PointResultSchema = Schema.Union([ResolvedPointSchema, Schema.Struct({
562
+ error: Schema.Literals([
563
+ "stale",
564
+ "hidden",
565
+ "offscreen",
566
+ "disabled",
567
+ "covered",
568
+ "outside"
569
+ ]),
570
+ detail: Schema.String
571
+ })]);
572
+ const ScrollPlanSchema = Schema.NullOr(Schema.Struct({
573
+ ...Point.fields,
574
+ dx: Schema.Finite,
575
+ dy: Schema.Finite
576
+ }));
577
+ const SnapshotResultSchema = Schema.Union([Schema.Struct({ snapshot: Snapshot }), Schema.Struct({ invalid: Schema.String })]);
578
+ const ViewportResultSchema = Schema.Struct({
579
+ width: Schema.Finite,
580
+ height: Schema.Finite
581
+ });
582
+ //#endregion
583
+ //#region src/internal/reading/ready.inpage.ts
584
+ /**
585
+ * In the page: whether it is ready to be shown, checked until it is or until a deadline. Its
586
+ * document is parsed and has painted since, nothing that ends is animating in view, its fonts and
587
+ * the images in view have loaded, nothing in view is marked busy (`aria-busy`), and the viewport
588
+ * shows something: text, a canvas drawn on, a picture or drawing larger than an icon, a video or a
589
+ * frame. So a canvas mounted blank, or a spinner alone, is still loading. A screen that only says
590
+ * "Loading…" in words reads as ready, and a WebGL canvas drawn once, without keeping its drawing,
591
+ * reads as blank. Asked for a quiet spell, where the page's changes are recorded, nothing in view
592
+ * may have changed for that long either. After input, it waits a task and a frame. See `names.inpage.ts` for what a page-side part may use.
593
+ */
594
+ /** What the page is still waiting for; none when it is ready. */
595
+ const ReadinessSchema = Schema.Array(Schema.Literals([
596
+ "load",
597
+ "paint",
598
+ "animations",
599
+ "images",
600
+ "fonts",
601
+ "busy",
602
+ "content",
603
+ "changing"
604
+ ]));
605
+ //#endregion
606
+ //#region src/internal/reading/text.inpage.ts
607
+ /**
608
+ * In the page: the text a page shows, and the one rule for what a field shows. A field's value
609
+ * reads `••••` unless a caller unmasks it, and a secret field's always does, including a field
610
+ * that was secret when the library saw it, such as a password its page now reveals. Text, and the
611
+ * outline, are cut at a line. See `names.inpage.ts` for what a page-side part may use.
612
+ */
613
+ /** What `read` sends back, or null when its ref no longer names an element. */
614
+ const TextResultSchema = Schema.NullOr(Schema.Struct({
615
+ text: Schema.String,
616
+ truncated: Schema.Boolean,
617
+ url: Schema.String,
618
+ title: Schema.String
619
+ }));
620
+ //#endregion
621
+ //#region src/internal/timeline/changes.inpage.ts
622
+ /**
623
+ * In the page: what changed after `since`, up to `until`, as a read returns it. A read starts the
624
+ * record if it has not, and keeps it going. What waited for the page to render is judged first, as
625
+ * it stands; then each element's history is folded over the window (`history.inpage.ts`), and only
626
+ * now named: its role, its name when something else names it, its tag, and its context, where it
627
+ * is or, for what was removed, where it was. A field's value reads `••••` unless the read unmasks
628
+ * it, and a secret field's always does. A change names the input it followed only where it was
629
+ * the input's own doing, by `Change.cause`'s rule. See `names.inpage.ts` for what a page-side part
630
+ * may use.
631
+ */
632
+ /**
633
+ * What a read sends back: its window and the record's state, and each change as `Change` encodes
634
+ * it, all on the page's clock.
635
+ */
636
+ const ChangesResultSchema = Schema.Struct({
637
+ until: Schema.Finite,
638
+ from: Schema.Finite,
639
+ dropped: Schema.Int,
640
+ records: Schema.Array(Change)
641
+ });
642
+ //#endregion
643
+ //#region src/internal/timeline/fold.inpage.ts
644
+ const fold = () => {
645
+ /** The one number some words show, such as 61240 in "$61,240"; none for none or several. */
646
+ const number = (words) => {
647
+ const found = words.match(/[-+−]?\d[\d,]*(?:\.\d+)?/g);
648
+ const value = Number(found?.length === 1 ? found[0]?.replaceAll(",", "").replace("−", "-") : "");
649
+ return found?.length === 1 && Number.isFinite(value) ? [value] : [];
650
+ };
651
+ /** A track's changes after `since`, up to `until`, if one was seen in view. */
652
+ const over = (track, since, until) => {
653
+ const inside = track.samples.filter((sample) => sample.at > since && sample.at <= until);
654
+ const first = inside[0];
655
+ const last = inside.at(-1);
656
+ if (first === void 0 || last === void 0 || !inside.some((sample) => sample.seen === true)) return void 0;
657
+ const prior = track.samples[track.samples.indexOf(first) - 1];
658
+ const lost = track.known <= since ? track.known : void 0;
659
+ const start = prior === void 0 ? lost === void 0 ? void 0 : track.initial : prior.shown;
660
+ const words = [start, ...inside.map((sample) => sample.shown)].filter((each) => typeof each === "string");
661
+ const numbers = words.flatMap(number);
662
+ const ranged = inside.length > 1 && numbers.length === words.length;
663
+ const kind = track.kind !== "content" ? track.kind : last.shown === null ? start === null ? "brief" : "disappeared" : start === null ? "appeared" : "text";
664
+ return {
665
+ track,
666
+ kind,
667
+ startedAt: first.at,
668
+ at: last.at,
669
+ before: kind === "disappeared" ? words.at(-1) : start ?? void 0,
670
+ after: kind === "brief" ? words.at(-1) : last.shown ?? void 0,
671
+ count: inside.length,
672
+ lowest: ranged ? words[numbers.indexOf(Math.min(...numbers))] : void 0,
673
+ highest: ranged ? words[numbers.indexOf(Math.max(...numbers))] : void 0,
674
+ earlier: prior?.at ?? (lost === Number.NEGATIVE_INFINITY ? void 0 : lost)
675
+ };
676
+ };
677
+ /**
678
+ * How readily a track gives way when the record is full: one that holds no change first, then
679
+ * one that keeps changing, one never seen in view and one that has gone; news never does.
680
+ */
681
+ const rank = ({ samples: [only, ...more] }) => only === void 0 ? 4 : more.length > 0 ? 3 : only.seen === false ? 2 : only.shown === null ? 1 : 0;
682
+ return {
683
+ number,
684
+ over,
685
+ rank
686
+ };
687
+ };
688
+ /** The expression that installs the script and evaluates to its API; packaging freezes it. */
689
+ 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/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 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 clean,\n isInput,\n isTextArea,\n isSelect,\n isFrame,\n isHtml,\n isButton,\n isLabel,\n textOf,\n isElement,\n isDocument,\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) => painted().then((paints) => {\n const waiting = [];\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\" && 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) => {\n const until = performance.now() + millis;\n for (;;) {\n const waiting = await check(quietMillis);\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, 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 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 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 onInput = (event) => {\n const target = targetOf(event);\n if (!event.isTrusted || target === void 0) return;\n inputs.push({\n at: epoch(),\n target\n });\n if (inputs.length > 8) inputs.shift();\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 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/bridge.ts\n const parts = {\n elements,\n names,\n walk,\n match,\n context,\n subjects,\n states,\n expectations,\n text,\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 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 = parts.names(parts.elements());\n if (installed?.refs !== void 0) named.refs.next = installed.refs.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 read = parts.outline(named, walked, subjected, texts, controlled, parts.addresses());\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 readiness = parts.ready(walked, texts, kept);\n const api = {\n version,\n refs: named.refs,\n dispose: () => recorder.stop(),\n snapshot: read.snapshot,\n find: subjected.find,\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, placing, kept, seeing, marking, recorder).read,\n ready: readiness.wait,\n settle: readiness.settle,\n point: located.point,\n scrollPlan: located.scrollPlan,\n viewport: read.viewport,\n screenSize: () => ({\n width: screen.width,\n height: screen.height\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;})()";
690
+ const worldName = "effect-browser";
691
+ const recorderSource = `if (globalThis === globalThis.top) globalThis.__effectBrowser?.record();`;
692
+ const missing = "effect-browser: no __effectBrowser in this world";
693
+ const missingSource = Schema.encodeSync(Schema.fromJsonString(Schema.String))(missing);
694
+ const isMissing = (error) => error.reason._tag === "Failed" && error.reason.detail === missing;
695
+ const Evaluated = Schema.Struct({
696
+ value: Schema.optionalKey(Schema.Unknown),
697
+ error: Schema.optionalKey(Schema.String),
698
+ nextRef: Schema.Finite
699
+ });
700
+ /** A frame as a page session reports its commit. */
701
+ const Commit = Schema.Struct({
702
+ parentId: Schema.optionalKey(Schema.String),
703
+ loaderId: Schema.String,
704
+ url: Schema.String,
705
+ urlFragment: Schema.optionalKey(Schema.String)
706
+ });
707
+ /** `Page.frameNavigated` or `Page.navigatedWithinDocument`, as far as `mainFrame` reads them. */
708
+ const MainFrameEvent = Schema.Union([Schema.Struct({ frame: Commit }), Schema.Struct({
709
+ frameId: Schema.String,
710
+ url: Schema.String
711
+ })]);
712
+ /** A commit's loader and its address, redacted. */
713
+ const commitOf = ({ loaderId, url, urlFragment = "" }) => ({
714
+ loader: loaderId,
715
+ url: redact(url + urlFragment)
716
+ });
717
+ /**
718
+ * What a page session's commit or move says of `page`'s main frame: a new document's `loader` and
719
+ * its address, or a move's address; nothing for another frame. Only a commit is a new document:
720
+ * `frameStartedLoading` also fires on `pushState`, a move within the document.
721
+ */
722
+ const mainFrame = (page, event) => "frame" in event ? event.frame.parentId === void 0 ? commitOf(event.frame) : void 0 : event.frameId === page ? {
723
+ loader: void 0,
724
+ url: redact(event.url)
725
+ } : void 0;
726
+ /** A call to the page script, its arguments quoted as JavaScript literals. */
727
+ const scriptCall = (name, ...args) => `${name}(${args.map((arg) => JSON.stringify(arg)).join(", ")})`;
728
+ const runIn = (page, operation, expression, contextId) => page.native(operation, () => page.protocol.send("Runtime.evaluate", {
729
+ contextId,
730
+ expression,
731
+ returnByValue: true,
732
+ awaitPromise: true
733
+ })).pipe(Effect.flatMap(({ result, exceptionDetails: thrown }) => thrown === void 0 ? Effect.succeed(result.value) : failWith(operation, new Failed({ detail: thrown.exception?.description ?? thrown.text }))));
734
+ /** Session-owned registrations; the recorder can expire independently of the page script. */
735
+ const registrationFor = Effect.fnUntraced(function* (page) {
736
+ const { native, span } = page;
737
+ const { send } = page.protocol;
738
+ const registration = yield* SynchronizedRef.make({ script: false });
739
+ const addScript = (operation, source) => native(operation, () => send("Page.addScriptToEvaluateOnNewDocument", {
740
+ source,
741
+ worldName,
742
+ runImmediately: true
743
+ }));
744
+ const register = (operation) => Effect.all([page.paging(operation), addScript(operation, `if (globalThis === globalThis.top) ${installSource};`)], { concurrency: "unbounded" }).pipe(span("Page.register", {}, "Debug"));
745
+ /** Register the script once; the change-reader lifetime owns its removable registration. */
746
+ const ensure = (operation, recorder) => SynchronizedRef.updateEffect(registration, (state) => Effect.gen(function* () {
747
+ if (!state.script) yield* register(operation);
748
+ if (recorder && state.recorder === void 0) return {
749
+ script: true,
750
+ recorder: (yield* addScript(operation, recorderSource)).identifier
751
+ };
752
+ return {
753
+ ...state,
754
+ script: true
755
+ };
756
+ }));
757
+ const removeRecorder = (operation) => SynchronizedRef.updateEffect(registration, (state) => {
758
+ const identifier = state.recorder;
759
+ return identifier === void 0 ? Effect.succeed(state) : native(operation, () => send("Page.removeScriptToEvaluateOnNewDocument", { identifier })).pipe(Effect.as({ script: true }));
760
+ });
761
+ return {
762
+ ensure,
763
+ removeRecorder
764
+ };
765
+ });
766
+ const make$22 = Effect.fnUntraced(function* (page) {
767
+ const { id, cdp, native, span, publish, now } = page;
768
+ const { send } = page.protocol;
769
+ const { ensure, removeRecorder } = yield* registrationFor(page);
770
+ let world;
771
+ let documents = 0;
772
+ let nextDocument = Deferred.makeUnsafe();
773
+ let url = redact(page.url);
774
+ let loaded;
775
+ let nextRef = 1;
776
+ const loaders = /* @__PURE__ */ new Map();
777
+ const onMainFrame = (event) => {
778
+ const seen = mainFrame(id, event);
779
+ if (seen === void 0) return;
780
+ if (seen.loader !== void 0) {
781
+ documents++;
782
+ loaders.delete(seen.loader);
783
+ loaders.set(seen.loader, documents);
784
+ const [oldest] = loaders.keys();
785
+ if (loaders.size > 8 && oldest !== void 0) loaders.delete(oldest);
786
+ page.activity.documentAt = now();
787
+ world = void 0;
788
+ loaded = void 0;
789
+ Deferred.doneUnsafe(nextDocument, Effect.void);
790
+ nextDocument = Deferred.makeUnsafe();
791
+ }
792
+ url = seen.url;
793
+ const sameDocument = seen.loader === void 0;
794
+ publish(new Navigated({
795
+ at: now(),
796
+ page: id,
797
+ url,
798
+ document: documents,
799
+ sameDocument
800
+ }));
801
+ };
802
+ const onLoaded = (state) => () => {
803
+ loaded = new PageLoaded({
804
+ at: now(),
805
+ page: id,
806
+ state
807
+ });
808
+ publish(loaded);
809
+ };
810
+ cdp.on("Page.frameNavigated", onMainFrame);
811
+ cdp.on("Page.navigatedWithinDocument", onMainFrame);
812
+ cdp.on("Page.domContentEventFired", onLoaded("domcontentloaded"));
813
+ cdp.on("Page.loadEventFired", onLoaded("load"));
814
+ /**
815
+ * The main-frame commits seen so far, once the Page domain, which registration turned on, has
816
+ * answered, so that every later one counts. A commit within about one round trip of the count
817
+ * can still be missed.
818
+ */
819
+ const currentDocument = (operation) => page.paging(operation).pipe(Effect.map(() => documents));
820
+ /** What a frame that arrives now shows: its session, the page's current document and address. */
821
+ const frameTag = () => ({
822
+ session: page.session,
823
+ connection: page.connection,
824
+ document: documents,
825
+ url
826
+ });
827
+ /** The document the main frame's latest commit of `loader` began, if this session counted it. */
828
+ const documentOf = (loader) => loaders.get(loader);
829
+ const createWorld = (operation) => Effect.gen(function* () {
830
+ yield* ensure(operation, false);
831
+ const document = documents;
832
+ const created = yield* native(operation, () => send("Page.createIsolatedWorld", {
833
+ frameId: id,
834
+ worldName
835
+ }));
836
+ if (document === documents) world = created.executionContextId;
837
+ return created.executionContextId;
838
+ }).pipe(span("Page.createWorld", {}, "Debug"));
839
+ /** The current document's world, created if it has none yet. */
840
+ const current = (operation) => Effect.suspend(() => world === void 0 ? createWorld(operation) : Effect.succeed(world));
841
+ /** A world of the current document without the page script, as the clock probe needs. */
842
+ const bareWorld = (operation) => native(operation, () => send("Page.createIsolatedWorld", {
843
+ frameId: id,
844
+ worldName: `${worldName}-clock`
845
+ })).pipe(Effect.map((created) => created.executionContextId));
846
+ const run = (operation, expression, contextId) => runIn(page, operation, expression, contextId);
847
+ const evaluateIn = (operation, call, contextId) => Effect.gen(function* () {
848
+ const result = yield* run(operation, `(async () => {
849
+ const api = globalThis.__effectBrowser;
850
+ if (api === undefined) return ${missingSource};
851
+ api.refs.next = Math.max(api.refs.next, ${nextRef});
852
+ try { return { value: await globalThis.__effectBrowser.${call}, nextRef: api.refs.next }; }
853
+ catch (error) { return { error: error instanceof Error ? error.message : String(error), nextRef: api.refs.next }; }
854
+ })()`, contextId);
855
+ if (result === missing) return yield* failWith(operation, new Failed({ detail: missing }));
856
+ const evaluated = yield* decodeWith(operation, Evaluated)(result);
857
+ nextRef = Math.max(nextRef, evaluated.nextRef);
858
+ return evaluated.error === void 0 ? evaluated.value : yield* failWith(operation, new Failed({ detail: evaluated.error }));
859
+ }).pipe(span("Page.evaluate", { function: call.split("(")[0] }, "Trace"), Effect.provideService(Script, call.split("(")[0]));
860
+ const evaluateWithContext = (operation, call) => {
861
+ const attempt = (contextId) => evaluateIn(operation, call, contextId).pipe(Effect.map((value) => ({
862
+ contextId,
863
+ value
864
+ })));
865
+ const again = createWorld(operation).pipe(Effect.flatMap((contextId) => attempt(contextId).pipe(Effect.catchIf(isMissing, () => run(operation, `${installSource}.version`, contextId).pipe(Effect.andThen(attempt(contextId)))))));
866
+ return current(operation).pipe(Effect.flatMap(attempt), Effect.catchIf(contextGone, () => again));
867
+ };
868
+ const evaluate = (operation, call) => evaluateWithContext(operation, call).pipe(Effect.map(({ value }) => value));
869
+ return {
870
+ current,
871
+ bareWorld,
872
+ evaluate,
873
+ evaluateIn,
874
+ evaluateWithContext,
875
+ currentDocument,
876
+ /** Wait for the owning protocol session to observe a replacement before retrying its read. */
877
+ waitForDocument: (before) => Effect.suspend(() => documents === before ? Deferred.await(nextDocument) : Effect.void),
878
+ frameTag,
879
+ documentOf,
880
+ /** How far the current document has loaded, as this session heard; nothing until parsed. */
881
+ loaded: () => loaded,
882
+ /** Register the recorder, so every later document records from its start. */
883
+ registerRecorder: (operation) => ensure(operation, true),
884
+ /** Stop future documents and the current recorder at the host idle deadline. */
885
+ unregisterRecorder: (operation) => removeRecorder(operation).pipe(Effect.andThen(evaluate(operation, scriptCall("stopRecord"))))
886
+ };
887
+ });
888
+ //#endregion
889
+ //#region src/internal/input/dispatch.ts
890
+ /**
891
+ * Sending input to the browser. Each mouse event, key and inserted text goes out on the page's
892
+ * protocol session, stamped with the browser's clock when its run has a mapping, and is published
893
+ * as it is submitted.
894
+ */
895
+ const buttonMask = {
896
+ none: 0,
897
+ left: 1,
898
+ right: 2,
899
+ middle: 4
900
+ };
901
+ /** A mouse button going down or up at a point, as the `clickCount`th click. */
902
+ const buttonAt = (type, point, button = "left", clickCount = 1) => ({
903
+ type,
904
+ ...point,
905
+ button,
906
+ buttons: type === "mousePressed" ? buttonMask[button] : 0,
907
+ clickCount
908
+ });
909
+ const make$21 = (page) => {
910
+ const { id, pointer, publish, now, noteInput, closedBy } = page;
911
+ const { send } = page.protocol;
912
+ const inputClocks = /* @__PURE__ */ new WeakMap();
913
+ const stamp = (estimate, at) => estimate === void 0 ? {} : { timestamp: toBrowserSeconds(estimate, at) };
914
+ const inputCall = (operation, effect) => effect.pipe(Effect.mapError((error) => undispatched(operation, reasonOf(error.cause, void 0, closedBy()))));
915
+ const dispatchMouse = (event, estimate, submitted) => {
916
+ const at = now();
917
+ const point = {
918
+ x: event.x,
919
+ y: event.y
920
+ };
921
+ const button = event.button ?? "left";
922
+ const ButtonEvent = event.type === "mousePressed" ? PointerPressed : PointerReleased;
923
+ const track = (event.type === "mousePressed" || event.type === "mouseReleased") && button !== "none" ? new ButtonEvent({
924
+ at,
925
+ page: id,
926
+ ...point,
927
+ button,
928
+ clickCount: event.clickCount ?? 1
929
+ }) : event.type === "mouseWheel" ? new WheelScrolled({
930
+ at,
931
+ page: id,
932
+ ...point,
933
+ dx: event.deltaX ?? 0,
934
+ dy: event.deltaY ?? 0
935
+ }) : void 0;
936
+ const response = send("Input.dispatchMouseEvent", {
937
+ ...event,
938
+ ...stamp(estimate, at)
939
+ });
940
+ noteInput();
941
+ if (event.type === "mouseMoved") MutableRef.set(pointer, Option.some(point));
942
+ if (track !== void 0) publish(track);
943
+ submitted?.();
944
+ return response;
945
+ };
946
+ const sendMouse = (operation, run, event, submitted) => inputCall(operation, Effect.gen(function* () {
947
+ const held = `mouse:${event.button ?? "left"}`;
948
+ const estimate = inputClocks.get(run);
949
+ if (event.type === "mouseReleased") return yield* run.up(held);
950
+ if (event.type === "mousePressed") {
951
+ yield* run.reserve(2);
952
+ yield* run.down(held, () => dispatchMouse(event, estimate, submitted), () => dispatchMouse(buttonAt("mouseReleased", Option.getOrElse(MutableRef.get(pointer), () => ({
953
+ x: event.x,
954
+ y: event.y
955
+ })), event.button, event.clickCount), estimate));
956
+ } else {
957
+ yield* run.reserve(1);
958
+ yield* run.send(() => dispatchMouse(event, estimate, submitted));
959
+ }
960
+ }));
961
+ const dispatchKey = (key, phase, command, run, secret = false) => {
962
+ const at = now();
963
+ const event = new KeyChanged({
964
+ at,
965
+ page: id,
966
+ key: secret ? "Unidentified" : key,
967
+ phase
968
+ });
969
+ const response = command(at, inputClocks.get(run));
970
+ noteInput();
971
+ publish(event);
972
+ return response;
973
+ };
974
+ const dispatchText = (text, secret) => {
975
+ const track = new TextInserted({
976
+ at: now(),
977
+ page: id,
978
+ text: secret ? "•" : text
979
+ });
980
+ const response = send("Input.insertText", { text });
981
+ noteInput();
982
+ publish(track);
983
+ return response;
984
+ };
985
+ const flush = (operation, run) => inputCall(operation, run.drain);
986
+ return {
987
+ inputClocks,
988
+ stamp,
989
+ inputCall,
990
+ dispatchMouse,
991
+ sendMouse,
992
+ dispatchKey,
993
+ dispatchText,
994
+ flush
995
+ };
996
+ };
997
+ //#endregion
998
+ //#region src/internal/input/guard.ts
999
+ /**
1000
+ * The input guard's host side. It asks the page what an action would touch, builds the request a
1001
+ * policy decides on, binds an approval to the document and targets it saw, and runs the page
1002
+ * script's changes in the approved document only.
1003
+ */
1004
+ /** Recheck an approval, after any pending input it must see; neither runs without a guard. */
1005
+ const check = (approval, options = {}, before = Effect.void) => approval === void 0 ? Effect.void : before.pipe(Effect.andThen(approval.check(options)));
1006
+ const inputFailure = (operation, targets, failure) => {
1007
+ const target = failure.index === void 0 ? void 0 : targets[failure.index];
1008
+ 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 }));
1009
+ };
1010
+ const editFailure = (operation, ref, failure) => failWith(operation, failure.stale === true ? new StaleRef({ ref }) : new NotActionable({ detail: failure.error }));
1011
+ const make$20 = (page, bridge) => {
1012
+ const { id } = page;
1013
+ const { current, evaluateIn, evaluateWithContext } = bridge;
1014
+ const preparePolicy = (asked, info, targets, flags = {}) => Effect.gen(function* () {
1015
+ const action = nameOf(asked);
1016
+ const input = {
1017
+ action,
1018
+ targets,
1019
+ submit: flags.submit ?? false,
1020
+ keys: flags.keys ?? null,
1021
+ destination: flags.destination ?? null
1022
+ };
1023
+ const { contextId, value } = yield* evaluateWithContext(action, scriptCall("prepareInput", input));
1024
+ const prepared = yield* decodeWith(action, PreparedInputResultSchema)(value);
1025
+ if ("error" in prepared) return yield* inputFailure(action, targets, prepared);
1026
+ const first = prepared.targets[0];
1027
+ const target = targets[0];
1028
+ const { title, description, dialog, heading, nearby, form } = prepared.evidence;
1029
+ const safe = recorded(asked, first?.secret !== true);
1030
+ const request = new InputRequest({
1031
+ page: id,
1032
+ url: redact(prepared.url),
1033
+ title,
1034
+ action: safe,
1035
+ target: info.target,
1036
+ text: safe._tag === "Type" ? safe.text : info.text,
1037
+ element: first?.element,
1038
+ role: first?.role,
1039
+ name: first?.name,
1040
+ description,
1041
+ href: first?.href === void 0 ? void 0 : redact(first.href),
1042
+ point: target !== null && typeof target === "object" ? target : void 0,
1043
+ destination: prepared.destination === void 0 ? void 0 : redact(prepared.destination),
1044
+ facts: prepared.facts,
1045
+ context: {
1046
+ dialog,
1047
+ heading,
1048
+ nearby
1049
+ },
1050
+ form: form === void 0 ? void 0 : {
1051
+ ...form,
1052
+ action: redact(form.action)
1053
+ }
1054
+ });
1055
+ const check = (options = {}) => evaluateIn(action, scriptCall("validateInput", input, prepared, options), contextId).pipe(Effect.catchIf(contextGone, () => failWith(action, new NotActionable({ detail: "the page changed while input policy was pending" }))), Effect.flatMap(decodeWith(action, ValidatedInputResultSchema)), Effect.flatMap((result) => "error" in result ? inputFailure(action, targets, result) : Effect.void));
1056
+ return {
1057
+ request,
1058
+ validate: check().pipe(Effect.as({
1059
+ contextId,
1060
+ check
1061
+ }))
1062
+ };
1063
+ });
1064
+ const mutate = (operation, call, approval, mayHaveRun = Effect.void) => (approval === void 0 ? current(operation) : Effect.succeed(approval.contextId)).pipe(Effect.flatMap((contextId) => evaluateIn(operation, call, contextId).pipe(Effect.onInterrupt(() => mayHaveRun), Effect.tapError((error) => error.reason._tag === "Failed" && /Cannot find context|__effectBrowser/i.test(error.reason.detail) ? Effect.void : mayHaveRun))), Effect.catchIf(contextGone, () => failWith(operation, new NotActionable({ detail: "the page changed before the approved input could run" }))));
1065
+ /** A read may follow the current document only when no approval binds it to one. */
1066
+ const evaluate = (operation, call, approval) => approval === void 0 ? bridge.evaluate(operation, call) : mutate(operation, call, approval);
1067
+ return {
1068
+ preparePolicy,
1069
+ mutate,
1070
+ evaluate
1071
+ };
1072
+ };
1073
+ //#endregion
1074
+ //#region src/internal/input/keyboard.ts
1075
+ /**
1076
+ * Keys and typing: a key chord held and released, each typed event, and the document a run of
1077
+ * keys must stay in.
1078
+ */
1079
+ const make$19 = (page, bridge, dispatch) => {
1080
+ const { playwright } = page;
1081
+ const key = (direction, part) => {
1082
+ const run = () => playwright.keyboard[direction](part);
1083
+ return page.nativePort === void 0 ? run() : page.nativePort(page.id, `keyboard.${direction}`, { key: part }, run);
1084
+ };
1085
+ const { send } = page.protocol;
1086
+ const { currentDocument } = bridge;
1087
+ const { stamp, inputCall, dispatchKey, dispatchText } = dispatch;
1088
+ const sameDocument = (operation, since) => currentDocument(operation).pipe(Effect.flatMap((now) => now === since ? Effect.void : failWith(operation, new NotActionable({ detail: "the page moved to another document, so the remaining keys were not sent" }))));
1089
+ const keyStroke = (operation, run, parts, holdMillis = 0) => Effect.gen(function* () {
1090
+ yield* inputCall(operation, run.reserve(parts.length * 2));
1091
+ for (const part of parts) yield* inputCall(operation, run.down(`playwright:${part}`, () => dispatchKey(part, "down", () => key("down", part), run), () => dispatchKey(part, "up", () => key("up", part), run)));
1092
+ if (holdMillis > 0) yield* Effect.sleep(Duration.millis(holdMillis));
1093
+ for (const part of parts.toReversed()) yield* inputCall(operation, run.up(`playwright:${part}`));
1094
+ });
1095
+ const typeEvent = (run, event, secret) => inputCall("type", Effect.gen(function* () {
1096
+ if (event.phase === "insert") {
1097
+ yield* run.reserve(1);
1098
+ yield* run.send(() => dispatchText(event.key, secret));
1099
+ return;
1100
+ }
1101
+ const description$1 = description(event.key);
1102
+ if (description$1 === void 0) return yield* Effect.die("invalid planned key");
1103
+ const { key, code, keyCode, text } = description$1;
1104
+ const held = "raw:" + code;
1105
+ if (event.phase === "up") return yield* run.up(held);
1106
+ const keyEvent = (phase) => () => dispatchKey(key, phase, (at, estimate) => send("Input.dispatchKeyEvent", {
1107
+ type: phase === "down" ? "keyDown" : "keyUp",
1108
+ ...stamp(estimate, at),
1109
+ modifiers: 0,
1110
+ windowsVirtualKeyCode: keyCode,
1111
+ code,
1112
+ key,
1113
+ location: 0,
1114
+ ...phase === "down" ? {
1115
+ commands: [],
1116
+ text,
1117
+ unmodifiedText: text,
1118
+ autoRepeat: false,
1119
+ isKeypad: false
1120
+ } : {}
1121
+ }), run, secret);
1122
+ yield* run.reserve(2);
1123
+ yield* run.down(held, keyEvent("down"), keyEvent("up"));
1124
+ }));
1125
+ return {
1126
+ currentDocument,
1127
+ sameDocument,
1128
+ keyStroke,
1129
+ typeEvent
1130
+ };
1131
+ };
1132
+ //#endregion
1133
+ //#region src/internal/input/perform.ts
1134
+ /**
1135
+ * Performing one action: its turn on the page, the input guard's step, the input run that owns its
1136
+ * replies, and the action's record. Its deadline leaves out the time its style takes to show it.
1137
+ */
1138
+ const subjectOf = (target) => new Subject({
1139
+ role: target.role,
1140
+ name: target.name,
1141
+ tag: target.tag,
1142
+ context: target.context
1143
+ });
1144
+ /** What an action records of what it acted on: subjects, and a point target's box. */
1145
+ const actedOn = (subject, to) => ({
1146
+ subject: subjectOf(subject),
1147
+ box: subject.box,
1148
+ ...to === void 0 ? {} : { to: subjectOf(to) }
1149
+ });
1150
+ /** A subject as span attributes under `prefix`, without a role it does not have. */
1151
+ const subjectAttributes = (prefix, subject) => subject === void 0 ? {} : {
1152
+ ...subject.role === null ? {} : { [`${prefix}.role`]: subject.role },
1153
+ [`${prefix}.name`]: subject.name,
1154
+ [`${prefix}.tag`]: subject.tag
1155
+ };
1156
+ const timedOut = (operation, timeout) => failWith(operation, new Timeout({ millis: Duration.toMillis(timeout) }));
1157
+ /** Trace summaries carry lengths and subjects, never typed text. */
1158
+ const annotate = (dispatched, queuedMillis, info, revealed, subject, to, failure) => Effect.annotateCurrentSpan({
1159
+ dispatched,
1160
+ ...queuedMillis === void 0 ? {} : { queuedMillis },
1161
+ ...info.text !== void 0 && revealed ? { chars: info.text.length } : {},
1162
+ ...subjectAttributes("subject", subject),
1163
+ ...subjectAttributes("to", to),
1164
+ ...Option.match(failure, {
1165
+ onNone: () => ({}),
1166
+ onSome: (error) => ({ "error.type": error.reason._tag })
1167
+ })
1168
+ });
1169
+ /**
1170
+ * Fail `effect` with `Timeout` once `timeout` has passed, and as much later again as `presented`
1171
+ * says presentation has planned meanwhile.
1172
+ */
1173
+ const deadline$3 = (operation, timeout, now, presented) => (effect) => Effect.suspend(() => {
1174
+ const due = now() + Duration.toMillis(timeout);
1175
+ const expiry = Effect.suspend(() => {
1176
+ const left = due + presented() - now();
1177
+ return left <= 0 ? timedOut(operation, timeout) : Effect.sleep(Duration.millis(left)).pipe(Effect.andThen(expiry));
1178
+ });
1179
+ return Effect.raceFirst(effect, expiry);
1180
+ });
1181
+ /** An admitted operation stays owned through its Action and any unanswered native replies. */
1182
+ const admission = (page, pending, name) => {
1183
+ let run;
1184
+ let end;
1185
+ return {
1186
+ enter: Effect.uninterruptible(Effect.gen(function* () {
1187
+ const released = page.inputGate === void 0 ? void 0 : yield* page.inputGate.enter(name);
1188
+ const done = Deferred.makeUnsafe();
1189
+ pending.add(done);
1190
+ end = () => {
1191
+ const finish = () => {
1192
+ released?.();
1193
+ pending.delete(done);
1194
+ Deferred.doneUnsafe(done, Exit.void);
1195
+ };
1196
+ if (run === void 0) finish();
1197
+ else run.afterIdle(finish);
1198
+ };
1199
+ })),
1200
+ using: (current) => {
1201
+ run = current;
1202
+ },
1203
+ end: Effect.sync(() => end?.())
1204
+ };
1205
+ };
1206
+ /** Close a run on every exit while preserving its native replies for the page's next input. */
1207
+ 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));
1208
+ const make$18 = (page, sender) => {
1209
+ const { id, settings, mapping, lane, publish, now, noteInput, span, owned } = page;
1210
+ const { inputClocks } = sender;
1211
+ const input = make$26();
1212
+ const admitted = /* @__PURE__ */ new Set();
1213
+ const perform = (value, info, timeout, prepare, body) => {
1214
+ const name = nameOf(value);
1215
+ const sendsInput = value._tag !== "Goto" && value._tag !== "Back" && value._tag !== "Reload";
1216
+ return Effect.gen(function* () {
1217
+ const style = validated(yield* Current$2);
1218
+ const failFast = yield* FailFast;
1219
+ const styled = style.withInput?.({
1220
+ operation: name,
1221
+ wait: timeout,
1222
+ failFast
1223
+ }) ?? ((effect) => effect);
1224
+ const startedAt = now();
1225
+ const sent = yield* Ref.make(false);
1226
+ const at = yield* Ref.make(Option.none());
1227
+ const acted = yield* Ref.make({});
1228
+ const touch = Effect.sync(noteInput);
1229
+ let revealed = value._tag !== "Type";
1230
+ let presented = 0;
1231
+ const ticket = admission(page, admitted, name);
1232
+ const marks = {
1233
+ style,
1234
+ present: (millis) => Effect.sync(() => {
1235
+ presented += Math.max(0, millis);
1236
+ }),
1237
+ sent: Ref.set(sent, true).pipe(Effect.andThen(touch)),
1238
+ touched: touch,
1239
+ at: (point) => Ref.set(at, Option.some(point)),
1240
+ on: (subject, to) => Ref.set(acted, actedOn(subject, to)),
1241
+ reveal: Effect.sync(() => {
1242
+ revealed = true;
1243
+ })
1244
+ };
1245
+ let estimate;
1246
+ const admit = input.idle.pipe(Effect.tap(() => Effect.sync(() => {
1247
+ estimate = sendsInput ? mapping.latest() : void 0;
1248
+ })));
1249
+ const useInput = (action) => input.begin.pipe(Effect.tap((current) => Effect.sync(() => {
1250
+ ticket.using(current);
1251
+ if (estimate !== void 0) inputClocks.set(current, estimate);
1252
+ })), Effect.flatMap((run) => useRun(page, sender, name, run, action(run), sendsInput ? Ref.get(sent) : Effect.succeed(false))));
1253
+ let queuedMillis;
1254
+ const dispatch = (action) => Effect.suspend(() => {
1255
+ const asked = now();
1256
+ return styled(lane.write(name, timeout)(ticket.enter.pipe(Effect.andThen(Effect.suspend(() => admit.pipe(Effect.timeoutOrElse({
1257
+ duration: Duration.millis(Math.max(0, Duration.toMillis(timeout) - (now() - asked))),
1258
+ orElse: () => timedOut(name, timeout)
1259
+ })))), Effect.tap(() => Effect.sync(() => {
1260
+ queuedMillis = Math.round(now() - asked);
1261
+ })), Effect.andThen(deadline$3(name, timeout, now, () => presented)(action)))));
1262
+ });
1263
+ const guard = settings.guard;
1264
+ const action = guard === void 0 ? dispatch(useInput((run) => body({
1265
+ ...marks,
1266
+ input: run
1267
+ }, void 0))) : Effect.gen(function* () {
1268
+ const plan = yield* lane.read(name)(deadline$3(name, settings.actionTimeout, now, () => 0)(prepare(value))).pipe(span("Page.prepare", {}, "Debug"));
1269
+ yield* guard(plan.request).pipe(Effect.mapError((reason) => undispatched(name, reason)), Effect.timeoutOrElse({
1270
+ duration: settings.policyTimeout,
1271
+ orElse: () => failWith(name, new PolicyTimeout({ millis: Duration.toMillis(settings.policyTimeout) }))
1272
+ }), span("Page.guard"));
1273
+ return yield* dispatch(useInput((run) => plan.validate.pipe(Effect.flatMap((approval) => body({
1274
+ ...marks,
1275
+ input: run
1276
+ }, approval)))));
1277
+ });
1278
+ return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
1279
+ const exit = yield* Effect.exit(restore((page.inputGate?.check(name) ?? Effect.void).pipe(Effect.andThen(action))));
1280
+ const dispatched = yield* Ref.get(sent);
1281
+ const point = yield* Ref.get(at);
1282
+ const { subject, to, box } = yield* Ref.get(acted);
1283
+ const failure = Exit.isFailure(exit) ? Exit.findErrorOption(exit) : Option.none();
1284
+ yield* annotate(dispatched, queuedMillis, info, revealed, subject, to, failure);
1285
+ publish(new Action({
1286
+ at: now(),
1287
+ startedAt,
1288
+ page: id,
1289
+ name,
1290
+ value: recorded(value, revealed),
1291
+ url: redact(page.playwright.url()),
1292
+ correlation: yield* Correlation,
1293
+ target: info.target,
1294
+ subject,
1295
+ to,
1296
+ box,
1297
+ text: info.text === void 0 ? void 0 : revealed ? info.text.slice(0, 200) : redacted,
1298
+ x: Option.getOrUndefined(Option.map(point, (p) => p.x)),
1299
+ y: Option.getOrUndefined(Option.map(point, (p) => p.y)),
1300
+ ok: Exit.isSuccess(exit),
1301
+ dispatched,
1302
+ error: Option.match(failure, {
1303
+ onNone: () => Exit.hasInterrupts(exit) ? "interrupted" : void 0,
1304
+ onSome: (error) => error.message
1305
+ })
1306
+ }));
1307
+ if (Exit.isSuccess(exit)) return exit.value;
1308
+ if (dispatched) return yield* Exit.mapError(exit, (error) => error.dispatched ? error : new BrowserError({
1309
+ operation: error.operation,
1310
+ reason: error.reason,
1311
+ dispatched: true
1312
+ }));
1313
+ return yield* exit;
1314
+ })).pipe(Effect.ensuring(ticket.end));
1315
+ }).pipe(span(`Page.${name}`, info.target === void 0 ? {} : { target: info.target }), owned);
1316
+ };
1317
+ return Object.assign(perform, { idle: Effect.suspend(() => Effect.forEach(admitted, Deferred.await, { discard: true })) });
1318
+ };
1319
+ //#endregion
1320
+ //#region src/internal/input/pointer.ts
1321
+ /**
1322
+ * The pointer's travel and the wheel, as the action's style sends them. Travel follows a motion
1323
+ * plan, published before its first move, from where viewers last saw the pointer when it is
1324
+ * shown, and a wheel scroll goes in the style's steps.
1325
+ */
1326
+ const make$17 = (page, dispatch, viewport) => {
1327
+ const { id, pointer, publish, now, span } = page;
1328
+ const { inputClocks, inputCall, dispatchMouse, sendMouse } = dispatch;
1329
+ const moveTo = (operation, marks, to, cursor, travel = "approach") => Effect.gen(function* () {
1330
+ const dragging = travel === "drag";
1331
+ const { style } = marks;
1332
+ const drawn = style.pointer ?? pointer;
1333
+ const size = yield* viewport.viewportFor(operation);
1334
+ const previous = Option.getOrElse(MutableRef.get(drawn), () => ({
1335
+ x: Math.round(size.width / 2),
1336
+ y: Math.round(size.height / 2)
1337
+ }));
1338
+ const from = {
1339
+ x: Math.max(0, Math.min(size.width - 1, previous.x)),
1340
+ y: Math.max(0, Math.min(size.height - 1, previous.y))
1341
+ };
1342
+ const planned = yield* style.glide(from, to, dragging);
1343
+ const invalid = refuse(operation, "motion must be a bounded, ordered schedule ending at the target");
1344
+ const samples = yield* Schema.decodeEffect(Plan)(planned).pipe(Effect.catch(() => invalid));
1345
+ if (samples.at(-1)?.x !== to.x || samples.at(-1)?.y !== to.y) return yield* invalid;
1346
+ yield* Effect.annotateCurrentSpan("samples", samples.length);
1347
+ yield* marks.present(samples.at(-1)?.afterMillis ?? 0);
1348
+ const run = marks.input;
1349
+ yield* inputCall(operation, run.reserveMotion(samples.length));
1350
+ MutableRef.set(pointer, Option.some(from));
1351
+ const estimate = inputClocks.get(run);
1352
+ const at = now();
1353
+ let dispatched = 0;
1354
+ let last = from;
1355
+ yield* Effect.acquireUseRelease(Effect.sync(() => publish(new TrackPlanned({
1356
+ at,
1357
+ page: id,
1358
+ from,
1359
+ samples
1360
+ }))), () => Effect.gen(function* () {
1361
+ for (const sample of samples) {
1362
+ const remaining = at + sample.afterMillis - now();
1363
+ if (remaining > 0) yield* Effect.sleep(Duration.millis(remaining));
1364
+ yield* travel === "approach" ? marks.touched : marks.sent;
1365
+ yield* inputCall(operation, run.send(() => dispatchMouse({
1366
+ type: "mouseMoved",
1367
+ x: sample.x,
1368
+ y: sample.y,
1369
+ button: dragging ? "left" : "none",
1370
+ ...dragging ? { buttons: 1 } : {}
1371
+ }, estimate, () => {
1372
+ dispatched++;
1373
+ last = {
1374
+ x: sample.x,
1375
+ y: sample.y
1376
+ };
1377
+ MutableRef.set(drawn, Option.some(last));
1378
+ if (dispatched === samples.length && cursor !== void 0) publish(new CursorChanged({
1379
+ at: now(),
1380
+ page: id,
1381
+ cursor
1382
+ }));
1383
+ })));
1384
+ }
1385
+ }), (plan) => Effect.sync(() => publish(new TrackPerformed({
1386
+ at: now(),
1387
+ page: id,
1388
+ plan,
1389
+ dispatched,
1390
+ ...last,
1391
+ complete: dispatched === samples.length
1392
+ }))));
1393
+ }).pipe(span("Page.move", {}, "Debug"));
1394
+ return {
1395
+ moveTo,
1396
+ wheel: Effect.fnUntraced(function* (operation, marks, point, dx, dy, planned) {
1397
+ const steps = planned ?? (yield* marks.style.wheel(dx, dy));
1398
+ const at = now();
1399
+ yield* marks.present(steps.at(-1)?.afterMillis ?? 0);
1400
+ for (const step of steps) {
1401
+ const remaining = at + step.afterMillis - now();
1402
+ if (remaining > 0) yield* Effect.sleep(Duration.millis(remaining));
1403
+ yield* sendMouse(operation, marks.input, {
1404
+ type: "mouseWheel",
1405
+ ...point,
1406
+ deltaX: step.dx,
1407
+ deltaY: step.dy
1408
+ });
1409
+ }
1410
+ })
1411
+ };
1412
+ };
1413
+ //#endregion
1414
+ //#region src/internal/input/settle.ts
1415
+ /**
1416
+ * The wait after input: one task and one frame in the page, in one call, then a document only if
1417
+ * one committed meanwhile, until it is parsed. Chromium answers a call to a page that a link, a form
1418
+ * or a script's timer has asked to navigate only once the new document commits, or the navigation
1419
+ * stops without one, as on a 204, so the call spans the navigation the input asked for. A
1420
+ * `pushState` asks for no document, and a navigation a handler starts after a fetch answers is the
1421
+ * next look's to see. A tab the input opened waits for the browser's registration too.
1422
+ */
1423
+ const settling = Duration.seconds(5);
1424
+ const make$16 = (page, bridge) => {
1425
+ const document = () => bridge.frameTag().document;
1426
+ let parsed = -1;
1427
+ let changed = Deferred.makeUnsafe();
1428
+ page.cdp.on("Page.domContentEventFired", () => {
1429
+ parsed = document();
1430
+ Deferred.doneUnsafe(changed, Exit.void);
1431
+ changed = Deferred.makeUnsafe();
1432
+ });
1433
+ /** The page's document before input, which `settle` measures from. */
1434
+ const mark = () => ({
1435
+ document: document(),
1436
+ openings: page.openings.mark()
1437
+ });
1438
+ /** Wait for the page to settle after input sent since `before`. */
1439
+ const settle = (operation, before) => Effect.gen(function* () {
1440
+ yield* bridge.evaluate(operation, scriptCall("settle")).pipe(Effect.provideService(Current, void 0), Effect.catchIf(contextGone, () => Effect.void));
1441
+ while (document() > before.document && parsed < document()) yield* Deferred.await(changed);
1442
+ }).pipe(Effect.timeoutOption(settling), Effect.flatMap((result) => Option.isSome(result) ? Effect.void : page.stopLoading.pipe(Effect.andThen(Effect.annotateCurrentSpan("settled", false)))), Effect.andThen(page.openings.settle(before.openings)), page.span("Page.settle", {}, "Debug"));
1443
+ return {
1444
+ mark,
1445
+ settle
1446
+ };
1447
+ };
1448
+ //#endregion
1449
+ //#region src/internal/input/targets.ts
1450
+ /**
1451
+ * Where an action's input goes: a ref or a point resolved to a control and a viewport point,
1452
+ * scrolled into view first when it is outside the viewport: at once, or with the wheel where
1453
+ * viewers watch.
1454
+ */
1455
+ const pointFailure = (operation, target, result) => failWith(operation, result.error === "stale" && typeof target === "string" ? new StaleRef({ ref: target }) : result.error === "outside" ? new InvalidRequest({ detail: result.detail }) : new NotActionable({ detail: result.detail }));
1456
+ const resolvedTarget = ({ x, y, box, ...target }) => new ResolvedTarget({
1457
+ point: {
1458
+ x,
1459
+ y
1460
+ },
1461
+ box,
1462
+ ...target
1463
+ });
1464
+ const make$15 = (viewport, guard, pointer, dispatch, settling) => {
1465
+ const { evaluate, mutate } = guard;
1466
+ const { moveTo, wheel } = pointer;
1467
+ const { flush } = dispatch;
1468
+ const readPoint = (operation, target, approval, scroll) => evaluate(operation, scriptCall("point", target, scroll), approval).pipe(Effect.flatMap(decodeWith(operation, PointResultSchema)));
1469
+ const resolve = (operation, target, approval, scroll = true) => readPoint(operation, target, approval, scroll).pipe(Effect.flatMap((result) => "error" in result ? pointFailure(operation, target, result) : Effect.succeed(resolvedTarget(result))));
1470
+ return {
1471
+ resolve,
1472
+ targetFor: Effect.fnUntraced(function* (operation, target, approval, marks) {
1473
+ if (!marks.style.shown || typeof target !== "string") return yield* resolve(operation, target, approval);
1474
+ for (let attempt = 0; attempt < 3; attempt++) {
1475
+ const result = yield* readPoint(operation, target, approval, false);
1476
+ if (!("error" in result)) return resolvedTarget(result);
1477
+ if (result.error !== "offscreen") return yield* pointFailure(operation, target, result);
1478
+ const plan = yield* mutate(operation, scriptCall("scrollPlan", target), approval).pipe(Effect.flatMap(decodeWith(operation, ScrollPlanSchema)));
1479
+ if (plan === null) break;
1480
+ const size = yield* viewport.viewportFor(operation);
1481
+ const point = {
1482
+ x: plan.x,
1483
+ y: plan.y
1484
+ };
1485
+ yield* marks.at(point);
1486
+ yield* moveTo(operation, marks, point);
1487
+ const before = settling.mark();
1488
+ yield* wheel(operation, marks, point, Math.max(-size.width * .9, Math.min(size.width * .9, plan.dx)), Math.max(-size.height * .9, Math.min(size.height * .9, plan.dy)));
1489
+ yield* flush(operation, marks.input);
1490
+ yield* settling.settle(operation, before);
1491
+ yield* check(approval);
1492
+ }
1493
+ yield* marks.touched;
1494
+ const before = settling.mark();
1495
+ yield* resolve(operation, target, approval);
1496
+ yield* settling.settle(operation, before);
1497
+ yield* check(approval);
1498
+ return yield* resolve(operation, target, approval, false);
1499
+ })
1500
+ };
1501
+ };
1502
+ //#endregion
1503
+ //#region src/internal/input/actions.ts
1504
+ /**
1505
+ * The page's actions: click, hover, drag, type, press, scroll and select, each sent in a style,
1506
+ * plainly or performed for viewers. Each runs through
1507
+ * `perform`, which admits it, puts it to the input guard and records it. A click, a key or a scroll
1508
+ * then waits for the page to settle: a task and a frame, and a document if the input asked for one.
1509
+ */
1510
+ const partsOf = (page, bridge, viewport) => {
1511
+ const dispatch = make$21(page);
1512
+ const pointer = make$17(page, dispatch, viewport);
1513
+ const guard = make$20(page, bridge);
1514
+ const settling = make$16(page, bridge);
1515
+ return {
1516
+ page,
1517
+ ...settling,
1518
+ viewportFor: viewport.viewportFor,
1519
+ perform: make$18(page, dispatch),
1520
+ ...guard,
1521
+ ...make$15(viewport, guard, pointer, dispatch, settling),
1522
+ ...pointer,
1523
+ ...make$19(page, bridge, dispatch),
1524
+ sendMouse: dispatch.sendMouse,
1525
+ flush: dispatch.flush
1526
+ };
1527
+ };
1528
+ const named = (target) => typeof target === "string" ? target : `${target.x},${target.y}`;
1529
+ /** The ref a target names, if it names one rather than a point. */
1530
+ const refOf = (target) => typeof target === "string" ? target : void 0;
1531
+ /** Key names have a finite vocabulary beyond the action's structural schema. */
1532
+ const pressed = (keys) => {
1533
+ const parts = parts$1(keys);
1534
+ return parts === void 0 ? refuse("press", `"${keys}" is not a key; try Enter, Space, ArrowLeft or Control+A`) : Effect.succeed(parts);
1535
+ };
1536
+ const click = (input) => {
1537
+ const { settings } = input.page;
1538
+ const { perform, preparePolicy, targetFor, moveTo, sendMouse, flush, mark, settle } = input;
1539
+ return (target, clickOptions = {}) => perform({
1540
+ _tag: "Click",
1541
+ target,
1542
+ options: clickOptions
1543
+ }, { target: named(target) }, settings.actionTimeout, (action) => preparePolicy(action, { target: refOf(target) }, [target]), (marks, approval) => Effect.gen(function* () {
1544
+ const resolved = yield* targetFor("click", target, approval, marks);
1545
+ const { point } = resolved;
1546
+ const button = clickOptions.button ?? "left";
1547
+ const count = Math.max(1, Math.min(3, clickOptions.clickCount ?? 1));
1548
+ yield* marks.at(point);
1549
+ yield* marks.on(resolved);
1550
+ yield* moveTo("click", marks, point, resolved.cursor);
1551
+ yield* check(approval, { presses: [{
1552
+ index: 0,
1553
+ ...point
1554
+ }] });
1555
+ const before = mark();
1556
+ yield* marks.sent;
1557
+ for (let index = 1; index <= count; index++) {
1558
+ if (index > 1) yield* check(approval, { presses: [{
1559
+ index: 0,
1560
+ ...point
1561
+ }] }, flush("click", marks.input)).pipe(Effect.catchIf((error) => error.reason._tag === "StaleRef", () => failWith("click", new NotActionable({ detail: "an earlier click removed the approved target, so no further press was sent" }))));
1562
+ yield* sendMouse("click", marks.input, buttonAt("mousePressed", point, button, index));
1563
+ const hold = clickOptions.holdMillis ?? (yield* marks.style.hold);
1564
+ if (clickOptions.holdMillis === void 0) yield* marks.present(hold);
1565
+ if (hold > 0) yield* Effect.sleep(Duration.millis(hold));
1566
+ yield* sendMouse("click", marks.input, buttonAt("mouseReleased", point, button, index));
1567
+ }
1568
+ yield* flush("click", marks.input);
1569
+ yield* settle("click", before);
1570
+ return resolved;
1571
+ }));
1572
+ };
1573
+ const hover = (input) => {
1574
+ const { settings } = input.page;
1575
+ const { perform, preparePolicy, targetFor, moveTo, flush } = input;
1576
+ return (target) => perform({
1577
+ _tag: "Hover",
1578
+ target
1579
+ }, { target: named(target) }, settings.actionTimeout, (action) => preparePolicy(action, { target: refOf(target) }, [target]), (marks, approval) => Effect.gen(function* () {
1580
+ const resolved = yield* targetFor("hover", target, approval, marks);
1581
+ const { point } = resolved;
1582
+ yield* marks.at(point);
1583
+ yield* marks.on(resolved);
1584
+ yield* moveTo("hover", marks, point, resolved.cursor, "hover");
1585
+ yield* flush("hover", marks.input);
1586
+ }));
1587
+ };
1588
+ const drag = (input) => {
1589
+ const { settings } = input.page;
1590
+ const { perform, preparePolicy, targetFor, resolve, moveTo, sendMouse, flush } = input;
1591
+ return (from, to) => perform({
1592
+ _tag: "Drag",
1593
+ from,
1594
+ to
1595
+ }, { target: `${JSON.stringify(from)} -> ${JSON.stringify(to)}` }, settings.actionTimeout, (action) => preparePolicy(action, {}, [from, to]), (marks, approval) => Effect.gen(function* () {
1596
+ yield* targetFor("drag", from, approval, marks);
1597
+ yield* targetFor("drag", to, approval, marks);
1598
+ const start = yield* resolve("drag", from, approval, false);
1599
+ const end = yield* resolve("drag", to, approval, false);
1600
+ yield* marks.at(end.point);
1601
+ yield* marks.on(start, end);
1602
+ yield* moveTo("drag", marks, start.point, start.cursor);
1603
+ yield* check(approval, { presses: [{
1604
+ index: 0,
1605
+ ...start.point
1606
+ }, {
1607
+ index: 1,
1608
+ ...end.point
1609
+ }] });
1610
+ yield* marks.sent;
1611
+ yield* sendMouse("drag", marks.input, buttonAt("mousePressed", start.point));
1612
+ yield* moveTo("drag", marks, end.point, end.cursor, "drag");
1613
+ yield* sendMouse("drag", marks.input, buttonAt("mouseReleased", end.point));
1614
+ yield* flush("drag", marks.input);
1615
+ }));
1616
+ };
1617
+ const typeText = (input) => {
1618
+ const { settings, now } = input.page;
1619
+ const { perform, preparePolicy, mutate, targetFor, moveTo, sendMouse, flush, evaluate } = input;
1620
+ const { currentDocument, sameDocument, keyStroke, typeEvent, mark, settle } = input;
1621
+ return (text, typeOptions = {}) => perform({
1622
+ _tag: "Type",
1623
+ text,
1624
+ options: typeOptions
1625
+ }, {
1626
+ target: typeOptions.into,
1627
+ text
1628
+ }, settings.actionTimeout, (action) => preparePolicy(action, {
1629
+ target: typeOptions.into,
1630
+ text
1631
+ }, [typeOptions.into ?? null], { submit: typeOptions.submit ?? false }), (marks, approval) => Effect.gen(function* () {
1632
+ const events = yield* marks.style.typing(text, approval !== void 0);
1633
+ const replace = typeOptions.replace ?? true;
1634
+ const into = typeOptions.into;
1635
+ const asked = scriptCall("typeable", into ?? null, typeOptions.secret === true);
1636
+ const typeable = yield* evaluate("type", asked, approval).pipe(Effect.flatMap(decodeWith("type", TypeableResultSchema)));
1637
+ if ("error" in typeable) return yield* failWith("type", typeable.error === "stale" && into !== void 0 ? new StaleRef({ ref: into }) : new NotActionable({ detail: typeable.detail }));
1638
+ if (typeable.subject !== void 0) yield* marks.on(typeable.subject);
1639
+ const since = yield* currentDocument("type");
1640
+ let secret = typeable.secret;
1641
+ if (into !== void 0) {
1642
+ const target = yield* targetFor("type", into, approval, marks);
1643
+ yield* marks.at(target.point);
1644
+ yield* marks.on(target);
1645
+ if (marks.style.shown) {
1646
+ yield* moveTo("type", marks, target.point, target.cursor);
1647
+ yield* check(approval, { presses: [{
1648
+ index: 0,
1649
+ ...target.point
1650
+ }] });
1651
+ yield* marks.sent;
1652
+ for (const type of ["mousePressed", "mouseReleased"]) yield* sendMouse("type", marks.input, buttonAt(type, target.point));
1653
+ yield* flush("type", marks.input);
1654
+ }
1655
+ yield* marks.sent;
1656
+ const follow = marks.style.shown && approval === void 0 && !secret && target.name !== "" ? target.name : null;
1657
+ const focused = yield* mutate("type", scriptCall("focus", into, replace, follow), approval).pipe(Effect.flatMap(decodeWith("type", FocusResultSchema)));
1658
+ if ("error" in focused) return yield* editFailure("type", into, focused);
1659
+ secret ||= focused.secret;
1660
+ }
1661
+ if (!secret) yield* marks.reveal;
1662
+ yield* check(approval, { focused: true });
1663
+ yield* marks.sent;
1664
+ const focusHeld = check(approval, { focused: true }, flush("type", marks.input));
1665
+ if (text === "" && replace && into !== void 0) {
1666
+ yield* sameDocument("type", since);
1667
+ yield* keyStroke("type", marks.input, ["Delete"]);
1668
+ } else {
1669
+ const keyed = events.some((event) => event.phase === "down");
1670
+ const checks = approval !== void 0 && keyed ? (text.match(/\s/gu)?.length ?? 0) + 1 : 0;
1671
+ const started = now();
1672
+ yield* marks.present((events.at(-1)?.afterMillis ?? 0) + checks * 250);
1673
+ for (const event of events) {
1674
+ const remaining = started + event.afterMillis - now();
1675
+ if (remaining > 0) yield* Effect.sleep(Duration.millis(remaining));
1676
+ if (event.phase === "down" && /\s/u.test(event.key)) yield* focusHeld;
1677
+ if (event.phase !== "up") yield* sameDocument("type", since);
1678
+ yield* typeEvent(marks.input, event, secret);
1679
+ }
1680
+ if (keyed) yield* focusHeld;
1681
+ }
1682
+ yield* flush("type", marks.input);
1683
+ if (typeOptions.submit === true) {
1684
+ yield* check(approval, { focused: true });
1685
+ yield* sameDocument("type", since);
1686
+ const before = mark();
1687
+ yield* keyStroke("type", marks.input, ["Enter"]);
1688
+ yield* flush("type", marks.input);
1689
+ yield* settle("type", before);
1690
+ }
1691
+ }));
1692
+ };
1693
+ const press = (input) => {
1694
+ const { settings, now } = input.page;
1695
+ const { perform, preparePolicy, currentDocument, sameDocument, keyStroke, flush } = input;
1696
+ const { mark, settle, targetFor, mutate } = input;
1697
+ return (keys, pressOptions = {}) => perform({
1698
+ _tag: "Press",
1699
+ keys,
1700
+ options: pressOptions
1701
+ }, { target: keys }, settings.actionTimeout, (action) => Effect.suspend(() => pressed(keys)).pipe(Effect.flatMap((parts) => preparePolicy(action, {
1702
+ target: pressOptions.on,
1703
+ text: parts.join("+")
1704
+ }, [pressOptions.on ?? null], { keys: parts.join("+") }))), (marks, approval) => Effect.gen(function* () {
1705
+ const parts = yield* pressed(keys);
1706
+ const times = Math.max(1, Math.min(50, pressOptions.times ?? 1));
1707
+ const hold = Math.max(0, pressOptions.holdMillis ?? 0);
1708
+ const gaps = yield* Effect.all(Array.from({ length: times - 1 }, () => marks.style.keyGap));
1709
+ const pacing = gaps.reduce((sum, gap) => sum + gap, 0);
1710
+ if (times * hold + pacing > 1e4) return yield* refuse("press", "the key sequence exceeds the maximum duration");
1711
+ yield* marks.present(pacing);
1712
+ const activates = parts.at(-1) === "Enter" || parts.at(-1) === "Space";
1713
+ const since = yield* currentDocument("press");
1714
+ const on = pressOptions.on;
1715
+ if (on !== void 0) {
1716
+ yield* marks.on(yield* targetFor("press", on, approval, marks));
1717
+ yield* marks.sent;
1718
+ const focused = yield* mutate("press", scriptCall("focusOn", on), approval).pipe(Effect.flatMap(decodeWith("press", EditResultSchema)));
1719
+ if ("error" in focused) return yield* editFailure("press", on, focused);
1720
+ yield* check(approval, { focused: true });
1721
+ }
1722
+ const before = mark();
1723
+ let due = now();
1724
+ yield* marks.sent;
1725
+ for (let index = 0; index < times; index++) {
1726
+ if (index > 0 && activates) yield* check(approval, { focused: true }, flush("press", marks.input));
1727
+ yield* sameDocument("press", since);
1728
+ yield* keyStroke("press", marks.input, parts, hold);
1729
+ if (index + 1 < times) {
1730
+ due += hold + (gaps[index] ?? 0);
1731
+ if (due > now()) yield* Effect.sleep(Duration.millis(due - now()));
1732
+ }
1733
+ }
1734
+ yield* flush("press", marks.input);
1735
+ yield* settle("press", before);
1736
+ }));
1737
+ };
1738
+ const scroll = (input) => {
1739
+ const { settings } = input.page;
1740
+ const { perform, preparePolicy, viewportFor, targetFor, resolve, moveTo, wheel, flush } = input;
1741
+ const { mark, settle } = input;
1742
+ return (scrollOptions = {}) => {
1743
+ const target = scrollOptions.at;
1744
+ return perform({
1745
+ _tag: "Scroll",
1746
+ options: scrollOptions
1747
+ }, { target: target === void 0 ? void 0 : named(target) }, settings.actionTimeout, (action) => preparePolicy(action, { target: refOf(target) }, target === void 0 ? [] : [target]), (marks, approval) => Effect.gen(function* () {
1748
+ const viewport = yield* viewportFor("scroll");
1749
+ const middle = {
1750
+ x: Math.round(viewport.width / 2),
1751
+ y: Math.round(viewport.height / 2)
1752
+ };
1753
+ const dx = scrollOptions.dx ?? 0;
1754
+ const dy = scrollOptions.dy ?? (scrollOptions.dx === void 0 ? Math.round(viewport.height * .8) : 0);
1755
+ const steps = yield* marks.style.wheel(dx, dy);
1756
+ const resolved = target !== void 0 ? yield* targetFor("scroll", target, approval, marks) : marks.style.shown ? yield* resolve("scroll", middle, approval).pipe(Effect.orElseSucceed(() => void 0)) : void 0;
1757
+ const point = resolved?.point ?? middle;
1758
+ yield* marks.at(point);
1759
+ if (target !== void 0 && resolved !== void 0) yield* marks.on(resolved);
1760
+ yield* moveTo("scroll", marks, point, resolved?.cursor);
1761
+ const before = mark();
1762
+ yield* marks.sent;
1763
+ yield* wheel("scroll", marks, point, dx, dy, steps);
1764
+ yield* flush("scroll", marks.input);
1765
+ yield* settle("scroll", before);
1766
+ }));
1767
+ };
1768
+ };
1769
+ const select = (input) => {
1770
+ const { settings } = input.page;
1771
+ const { perform, preparePolicy, targetFor, mutate } = input;
1772
+ return (ref, values) => perform({
1773
+ _tag: "Select",
1774
+ ref,
1775
+ values
1776
+ }, {
1777
+ target: ref,
1778
+ text: values.join(", ")
1779
+ }, settings.actionTimeout, (action) => preparePolicy(action, {
1780
+ target: ref,
1781
+ text: values.join(", ")
1782
+ }, [ref]), (marks, approval) => Effect.gen(function* () {
1783
+ yield* marks.on(yield* targetFor("select", ref, approval, marks));
1784
+ const result = yield* mutate("select", scriptCall("select", ref, values), approval, marks.sent).pipe(Effect.flatMap((value) => decodeWith("select", EditResultSchema)(value).pipe(Effect.tapError(() => marks.sent))));
1785
+ if ("error" in result) return yield* editFailure("select", ref, result);
1786
+ yield* marks.sent;
1787
+ return result.detail;
1788
+ }));
1789
+ };
1790
+ const make$14 = (page, bridge, viewport) => {
1791
+ const parts = partsOf(page, bridge, viewport);
1792
+ return {
1793
+ perform: parts.perform,
1794
+ preparePolicy: parts.preparePolicy,
1795
+ click: click(parts),
1796
+ hover: hover(parts),
1797
+ drag: drag(parts),
1798
+ type: typeText(parts),
1799
+ press: press(parts),
1800
+ scroll: scroll(parts),
1801
+ select: select(parts)
1802
+ };
1803
+ };
1804
+ //#endregion
1805
+ //#region src/internal/pictures/counts.ts
1806
+ /** Bounded capture-loss and paint-gap statistics on the owning host clock. */
1807
+ const paintGaps = () => {
1808
+ let count = 0;
1809
+ let totalMillis = 0;
1810
+ let minMillis = null;
1811
+ let maxMillis = null;
1812
+ let lastMillis = null;
1813
+ return {
1814
+ add: (gap) => {
1815
+ count++;
1816
+ totalMillis += gap;
1817
+ minMillis = minMillis === null ? gap : Math.min(minMillis, gap);
1818
+ maxMillis = maxMillis === null ? gap : Math.max(maxMillis, gap);
1819
+ lastMillis = gap;
1820
+ },
1821
+ snapshot: () => ({
1822
+ count,
1823
+ totalMillis,
1824
+ minMillis,
1825
+ maxMillis,
1826
+ lastMillis
1827
+ })
1828
+ };
1829
+ };
1830
+ const none = () => ({
1831
+ received: 0,
1832
+ accepted: 0,
1833
+ late: 0,
1834
+ missingTimestamp: 0,
1835
+ foreignSize: 0,
1836
+ duringPictures: 0,
1837
+ lost: 0
1838
+ });
1839
+ /** How far back a window of capture counts can reach. */
1840
+ const countsKept = Duration.minutes(1);
1841
+ /**
1842
+ * A capture's counts and paint gaps over its page's life, and each with when it happened on the
1843
+ * owner's clock for the latest minute, so a window of them can be read.
1844
+ */
1845
+ const tally = (now) => {
1846
+ const totals = none();
1847
+ const gaps = paintGaps();
1848
+ let recent = [];
1849
+ let oldest = 0;
1850
+ const note = (counted, n) => {
1851
+ const at = now();
1852
+ recent.push({
1853
+ at,
1854
+ counted,
1855
+ n
1856
+ });
1857
+ while ((recent[oldest]?.at ?? at) < at - Duration.toMillis(countsKept)) oldest++;
1858
+ if (oldest > recent.length / 2) {
1859
+ recent = recent.slice(oldest);
1860
+ oldest = 0;
1861
+ }
1862
+ };
1863
+ return {
1864
+ count: (counted, n = 1) => {
1865
+ totals[counted] += n;
1866
+ note(counted, n);
1867
+ },
1868
+ gap: (millis) => {
1869
+ gaps.add(millis);
1870
+ note("gap", millis);
1871
+ },
1872
+ /** Lifetime counts, or those of the latest `windowMillis`, at most a minute. */
1873
+ read: (windowMillis) => {
1874
+ if (windowMillis === void 0) return {
1875
+ ...totals,
1876
+ gaps: gaps.snapshot()
1877
+ };
1878
+ const counts = none();
1879
+ const windowed = paintGaps();
1880
+ const since = now() - windowMillis;
1881
+ for (const { at, counted, n } of recent.slice(oldest)) {
1882
+ if (at < since) continue;
1883
+ if (counted === "gap") windowed.add(n);
1884
+ else counts[counted] += n;
1885
+ }
1886
+ return {
1887
+ ...counts,
1888
+ gaps: windowed.snapshot()
1889
+ };
1890
+ }
1891
+ };
1892
+ };
1893
+ //#endregion
1894
+ //#region src/internal/pictures/dimensions.ts
1895
+ /** Viewport evidence and bounded foreign-picture filtering for one capture. */
1896
+ const deadline$2 = Duration.seconds(2);
1897
+ const sameSize = (left, right) => Math.abs(left.width - right.width) < 1 && Math.abs(left.height - right.height) < 1;
1898
+ const sameShape = (image, device) => Math.abs(image.width * device.height - image.height * device.width) < device.width + device.height;
1899
+ const outlasting = Duration.seconds(1);
1900
+ const readViewport = (options) => options.viewport.pipe(Effect.interruptible, Effect.timeoutOrElse({
1901
+ duration: deadline$2,
1902
+ orElse: () => Effect.succeed(null)
1903
+ }), Effect.orElseSucceed(() => null), Effect.provideService(Clock.Clock, options.clock));
1904
+ /**
1905
+ * Keeps other captures' frames from readers. A clipped or scaled screenshot of the page, taken
1906
+ * from any session, draws frames into its running screencast without resizing the page, until
1907
+ * Chromium returns to the page's size. Either their picture has another shape than their device,
1908
+ * and they are dropped, or their device has another size than the page's frames.
1909
+ *
1910
+ * A frame of the expected device size goes to readers at once and drops any run of frames of
1911
+ * another size before it, as another capture's. A run waits, in order, until the page reports a
1912
+ * viewport of its size or until it outlasts any capture: then it was a real resize, so it goes to
1913
+ * readers and its size is expected. The page's report only shortens the wait, so a page too busy
1914
+ * to answer, or one measuring in other units as under browser zoom, never stalls the stream.
1915
+ */
1916
+ const sizeFilter = (options, deliver, drop, resized) => Effect.gen(function* () {
1917
+ let expected = null;
1918
+ let run;
1919
+ const wake = yield* Queue.sliding(1);
1920
+ const end = () => {
1921
+ if (run === void 0) return;
1922
+ drop(run.frames.length);
1923
+ run = void 0;
1924
+ Queue.offerUnsafe(wake, void 0);
1925
+ };
1926
+ const now = () => monotonicMillis(options.clock);
1927
+ const adopt = (adopted) => {
1928
+ run = void 0;
1929
+ expected = adopted.device;
1930
+ resized(adopted.device);
1931
+ for (const held of adopted.frames) deliver(held.frame, held.timestamp);
1932
+ };
1933
+ const decide = Effect.suspend(() => {
1934
+ const deciding = run;
1935
+ if (deciding === void 0) return Effect.void;
1936
+ return readViewport(options).pipe(Effect.flatMap((viewport) => {
1937
+ if (run !== deciding) return decide;
1938
+ if (viewport !== null && sameSize(viewport, deciding.device)) return Effect.sync(() => adopt(deciding));
1939
+ return outlast(deciding);
1940
+ }));
1941
+ });
1942
+ const outlast = (waiting) => Effect.suspend(() => {
1943
+ if (run !== waiting) return decide;
1944
+ const remaining = waiting.since + Duration.toMillis(outlasting) - now();
1945
+ if (remaining <= 0) return Effect.sync(() => adopt(waiting));
1946
+ return Effect.sleep(Duration.millis(remaining)).pipe(Effect.provideService(Clock.Clock, options.clock), Effect.race(Queue.take(wake)), Effect.andThen(outlast(waiting)));
1947
+ });
1948
+ yield* Queue.take(wake).pipe(Effect.andThen(decide), Effect.forever, Effect.forkScoped);
1949
+ return {
1950
+ /** Drops the frames still waiting; their capture has stopped. */
1951
+ end,
1952
+ /** A new capture expects the viewport it read, if any. */
1953
+ restart: (viewport) => {
1954
+ end();
1955
+ expected = viewport;
1956
+ },
1957
+ /** Whether a frame of this device size shows the page, as far as the capture knows. */
1958
+ offer: (frame, timestamp, image, device) => {
1959
+ if (image !== void 0 && !sameShape(image, device)) {
1960
+ drop(1);
1961
+ return;
1962
+ }
1963
+ expected ??= device;
1964
+ if (sameSize(device, expected)) {
1965
+ end();
1966
+ deliver(frame, timestamp);
1967
+ return;
1968
+ }
1969
+ if (run !== void 0 && !sameSize(run.device, device)) end();
1970
+ if (run === void 0) {
1971
+ run = {
1972
+ device,
1973
+ since: now(),
1974
+ frames: []
1975
+ };
1976
+ Queue.offerUnsafe(wake, void 0);
1977
+ }
1978
+ run.frames.push({
1979
+ frame,
1980
+ timestamp
1981
+ });
1982
+ if (run.frames.length > 16) {
1983
+ run.frames.shift();
1984
+ drop(1);
1985
+ }
1986
+ }
1987
+ };
1988
+ });
1989
+ //#endregion
1990
+ //#region src/internal/pictures/frame.ts
1991
+ /**
1992
+ * A native frame as readers get it: its picture's size, else the capture's or its device's, and
1993
+ * its paint mapped by the browser's newest estimate, which may be older than the frame and says
1994
+ * less about later paint.
1995
+ */
1996
+ const timed = (options, native, timestamp, generation, data) => {
1997
+ const image = options.imageSize(data);
1998
+ const device = {
1999
+ width: native.metadata.deviceWidth,
2000
+ height: native.metadata.deviceHeight
2001
+ };
2002
+ const size = image ?? generation.size ?? device;
2003
+ const estimate = options.latest() ?? generation.calibration;
2004
+ const hostTime = toHostTime(estimate, timestamp);
2005
+ return {
2006
+ frame: new Frame({
2007
+ page: options.id,
2008
+ capture: {
2009
+ generation: generation.id,
2010
+ sequence: generation.sequence
2011
+ },
2012
+ data,
2013
+ timing: new BrowserPaint({
2014
+ timestamp,
2015
+ hostTime,
2016
+ uncertaintyMillis: uncertaintyAt(estimate, hostTime)
2017
+ }),
2018
+ receivedAt: monotonicMillis(options.clock),
2019
+ width: size.width,
2020
+ height: size.height,
2021
+ ...generation.transport.frameTag()
2022
+ }),
2023
+ image,
2024
+ device
2025
+ };
2026
+ };
2027
+ /** Clamp only the estimate's centre, widening its interval by the correction. */
2028
+ const orderedFrame = (frame, previous) => frame.hostTime < previous && frame.timing._tag === "BrowserPaint" ? new Frame({
2029
+ ...frame,
2030
+ timing: new BrowserPaint({
2031
+ ...frame.timing,
2032
+ hostTime: previous,
2033
+ uncertaintyMillis: frame.timing.uncertaintyMillis + previous - frame.hostTime
2034
+ })
2035
+ }) : frame;
2036
+ //#endregion
2037
+ //#region src/internal/pictures/quiescence.ts
2038
+ /** Actual native replies outlive callers; bounded transactions retain them without holding teardown. */
2039
+ const deadline$1 = Duration.seconds(2);
2040
+ const make$13 = (options) => {
2041
+ const replies = make$26();
2042
+ const pending = /* @__PURE__ */ new Map();
2043
+ const late = (kind) => options.error(/* @__PURE__ */ new Error(`${kind} exceeded its deadline`));
2044
+ const track = (operation, actual, failed) => {
2045
+ const reply = actual.then(() => void 0, failed);
2046
+ pending.set(operation, reply);
2047
+ return reply.finally(() => {
2048
+ if (pending.get(operation) === reply) pending.delete(operation);
2049
+ });
2050
+ };
2051
+ const wait = (operation) => (operation === void 0 ? replies.idle.pipe(Effect.andThen(Effect.promise(() => Promise.all(pending.values())))) : Effect.promise(() => pending.get(operation) ?? Promise.resolve())).pipe(Effect.asVoid, Effect.interruptible, Effect.timeoutOrElse({
2052
+ duration: deadline$1,
2053
+ orElse: () => Effect.fail(late(operation ?? pending.keys().next().value ?? "picture restoration"))
2054
+ }), Effect.provideService(Clock.Clock, options.clock));
2055
+ const excluding = (picture) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
2056
+ yield* restore(wait());
2057
+ if (options.closed()) return yield* options.error(/* @__PURE__ */ new Error("Target page has been closed"));
2058
+ const current = options.current();
2059
+ const run = yield* replies.begin;
2060
+ const result = yield* restore(options.pause(current).pipe(Effect.andThen(picture), Effect.provideService(Current, run))).pipe(Effect.exit);
2061
+ const cleaned = yield* wait().pipe(Effect.andThen(options.resume(current)), Effect.timeoutOrElse({
2062
+ duration: deadline$1,
2063
+ orElse: () => Effect.fail(late("picture restoration"))
2064
+ }), Effect.provideService(Clock.Clock, options.clock), Effect.exit, Effect.forkChild, Effect.flatMap(Fiber.join));
2065
+ if (Exit.isFailure(cleaned)) options.fail(current, options.error(Cause.squash(cleaned.cause)));
2066
+ if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
2067
+ if (Exit.isFailure(cleaned)) return yield* Effect.failCause(cleaned.cause);
2068
+ return result.value;
2069
+ }));
2070
+ return {
2071
+ excluding,
2072
+ idle: wait(),
2073
+ wait,
2074
+ track
2075
+ };
2076
+ };
2077
+ //#endregion
2078
+ //#region src/internal/pictures/state.ts
2079
+ const initial = { _tag: "Capturing" };
2080
+ const step = (state, input) => {
2081
+ if (input._tag === "Stop") return {
2082
+ _tag: "Stopped",
2083
+ failure: state._tag === "Stopped" ? state.failure ?? input.failure : input.failure
2084
+ };
2085
+ if (state._tag === "Stopped") return state;
2086
+ return { _tag: input._tag === "Pause" ? "Paused" : "Capturing" };
2087
+ };
2088
+ const failureOf = (state) => state._tag === "Stopped" ? state.failure : void 0;
2089
+ //#endregion
2090
+ //#region src/internal/pictures/capture.ts
2091
+ /**
2092
+ * One CDP screencast per page, with bounded transport replies and per-reader loss accounting.
2093
+ * Native callbacks own synchronous bookkeeping; the page scope owns startup and teardown.
2094
+ */
2095
+ const replyCapacity = 32;
2096
+ const subscriberCapacity = 16;
2097
+ const deadline = Duration.seconds(2);
2098
+ /**
2099
+ * What a new capture starts with: where it runs, the clock's estimate, and the viewport unless
2100
+ * the reader gave a size. A capture connection attaches while the page's own session maps the
2101
+ * clock, and a page too busy to report its viewport is still captured, at device size.
2102
+ */
2103
+ const prepare = (options, screencast) => Effect.all([options.transport.pipe(Effect.interruptible), Effect.gen(function* () {
2104
+ return {
2105
+ calibration: yield* options.calibrate.pipe(Effect.interruptible),
2106
+ viewport: screencast.size === void 0 ? yield* readViewport(options) : null
2107
+ };
2108
+ })], { concurrency: 2 });
2109
+ /**
2110
+ * A running capture's failure, told once its page's fate is known. A capture can fail before the
2111
+ * page's own session hears why: a capture connection hears the browser's end before the connection
2112
+ * that drives the page does, and an acknowledgement can be refused before the browser's loss is
2113
+ * known. So the failure waits for the page's scope to close, `closed`, and is then the page's own
2114
+ * end or its browser's loss, as `gone` reads it; or, if the page still stands after `deadline`,
2115
+ * the capture's own.
2116
+ */
2117
+ const told = (closed, gone, clock) => (failure) => Deferred.await(closed).pipe(Effect.map(gone), Effect.timeoutOrElse({
2118
+ duration: deadline,
2119
+ orElse: () => Effect.succeed(failure)
2120
+ }), Effect.provideService(Clock.Clock, clock), Effect.flatMap(Effect.fail));
2121
+ /**
2122
+ * Once every frame the running capture's transport sent before now has arrived; a capture that
2123
+ * has failed, or whose round trip fails, fails as `why` tells it.
2124
+ */
2125
+ const synced = (current, why, error) => {
2126
+ if (current === void 0) return Effect.void;
2127
+ const failure = failureOf(current.state);
2128
+ if (failure !== void 0) return why(failure);
2129
+ return Effect.tryPromise({
2130
+ try: () => current.transport.sync(),
2131
+ catch: error
2132
+ }).pipe(Effect.catch(why), Effect.asVoid);
2133
+ };
2134
+ const confirmation = (read, current, why, error) => (frame) => Effect.suspend(() => {
2135
+ const { generation } = read();
2136
+ if (generation === void 0) return Effect.succeed(false);
2137
+ return synced(generation, why, error).pipe(Effect.map(() => {
2138
+ const after = read();
2139
+ return after.generation === generation && after.replies === 0 && current(frame);
2140
+ }));
2141
+ });
2142
+ const isCurrent = (frame, generation, latest) => generation !== void 0 && generation.state._tag === "Capturing" && frame.capture !== void 0 && sameCapture(frame, Option.getOrUndefined(latest)) && generation.transport.frameTag().document === frame.document;
2143
+ const currentFrame = (generation, latest) => Option.getOrUndefined(Option.filter(latest, (frame) => isCurrent(frame, generation, latest)));
2144
+ /** One reader counts its own missed envelopes without hiding gaps inside stream chunks. */
2145
+ const frames = (subscription, baseline, why, missed) => {
2146
+ let previous = baseline;
2147
+ return Stream.fromEffectRepeat(Queue.take(subscription).pipe(Effect.flatMap((envelope) => {
2148
+ if (envelope._tag === "Failure") return why(envelope.error);
2149
+ return Effect.sync(() => {
2150
+ if (envelope.sequence > previous + 1) missed(envelope.sequence - previous - 1);
2151
+ previous = envelope.sequence;
2152
+ return envelope.frame;
2153
+ });
2154
+ })));
2155
+ };
2156
+ const renewals = Effect.fnUntraced(function* (options) {
2157
+ const renewing = yield* Queue.sliding(1);
2158
+ yield* Queue.take(renewing).pipe(Effect.andThen(options.renew), Effect.andThen(Effect.sleep(Duration.seconds(1))), Effect.provideService(Clock.Clock, options.clock), Effect.forever, Effect.forkScoped);
2159
+ return renewing;
2160
+ });
2161
+ const receive = (options, current, replies, counts, sizes, renewing, fail) => (native) => {
2162
+ if (current.state._tag === "Stopped") return;
2163
+ counts.count("received");
2164
+ if (replies.size >= replyCapacity) {
2165
+ fail(current, options.error(/* @__PURE__ */ new Error("screencast acknowledgement capacity exceeded")));
2166
+ return;
2167
+ }
2168
+ const reply = current.transport.acknowledge(native.sessionId).then(() => void 0, (cause) => {
2169
+ if (current.state._tag !== "Stopped") fail(current, options.error(cause));
2170
+ }).then(() => void replies.delete(reply));
2171
+ replies.add(reply);
2172
+ const browserSeconds = native.metadata.timestamp;
2173
+ const timestamp = browserSeconds === void 0 ? NaN : browserSeconds * 1e3;
2174
+ if (!Number.isFinite(timestamp)) return counts.count("missingTimestamp");
2175
+ if (current.predecessor !== void 0 && timestamp <= current.predecessor) return counts.count("late");
2176
+ Queue.offerUnsafe(renewing, void 0);
2177
+ const decoded = Base64.decode(native.data);
2178
+ if (Result.isFailure(decoded)) {
2179
+ fail(current, options.error(/* @__PURE__ */ new Error("the capture connection sent invalid base64 picture data")));
2180
+ return;
2181
+ }
2182
+ current.sequence++;
2183
+ const { frame, image, device } = timed(options, native, timestamp, current, decoded.success);
2184
+ if (current.state._tag === "Paused") return counts.count("duringPictures");
2185
+ sizes.offer(frame, timestamp, image, device);
2186
+ };
2187
+ const settingsOf$1 = (current) => ({
2188
+ format: "jpeg",
2189
+ quality: current.quality,
2190
+ ...current.size === null ? {} : {
2191
+ maxWidth: current.size.width,
2192
+ maxHeight: current.size.height
2193
+ }
2194
+ });
2195
+ const healthy = (current) => Effect.suspend(() => {
2196
+ const failure = failureOf(current.state);
2197
+ return failure === void 0 ? Effect.void : Effect.fail(failure);
2198
+ });
2199
+ const followGrowth = (changes, lock, generation, pictures, fail) => Queue.take(changes).pipe(Effect.flatMap((size) => lock.withPermits(1)(Effect.suspend(() => {
2200
+ const current = generation();
2201
+ if (current === void 0 || current.explicitSize || current.state._tag !== "Capturing" || current.size !== null && size.width <= current.size.width && size.height <= current.size.height) return Effect.void;
2202
+ return pictures.excluding(Effect.sync(() => {
2203
+ current.size = size;
2204
+ })).pipe(Effect.catch((error) => Effect.sync(() => fail(current, error))));
2205
+ }))), Effect.forever, Effect.forkScoped);
2206
+ /** The first subscription must exist before the native start can emit its only frame. */
2207
+ const subscribe = (current) => Effect.gen(function* () {
2208
+ const subscription = yield* Queue.sliding(subscriberCapacity);
2209
+ current.subscribers.add(subscription);
2210
+ const failure = failureOf(current.state);
2211
+ if (failure !== void 0) Queue.offerUnsafe(subscription, {
2212
+ _tag: "Failure",
2213
+ error: failure
2214
+ });
2215
+ return subscription;
2216
+ });
2217
+ const reader = (acquire, leave, why, lost) => (settings = {}) => Effect.acquireRelease(acquire(settings).pipe(Effect.interruptible), leave).pipe(Effect.map((lease) => ({
2218
+ current: lease.frame,
2219
+ stream: frames(lease.subscription, lease.baseline, why, lost)
2220
+ })));
2221
+ const make$12 = (options) => Effect.gen(function* () {
2222
+ const lock = yield* Semaphore.make(1);
2223
+ const replies = /* @__PURE__ */ new Set();
2224
+ let generation;
2225
+ let generations = 0;
2226
+ let lastHostTime = Number.NEGATIVE_INFINITY;
2227
+ const closed = yield* Deferred.make();
2228
+ const pageScope = yield* Effect.scope;
2229
+ const isClosed = () => pageScope.state._tag === "Closed" || Deferred.isDoneUnsafe(closed);
2230
+ let latest = Option.none();
2231
+ let history = [];
2232
+ const counts = tally(() => monotonicMillis(options.clock));
2233
+ let delivered = 0;
2234
+ const deliver = (frame, timestamp) => {
2235
+ const current = generation;
2236
+ if (current === void 0) return;
2237
+ if (current.predecessor !== void 0 && timestamp <= current.predecessor) return counts.count("late");
2238
+ if (current.predecessor !== void 0) counts.gap(timestamp - current.predecessor);
2239
+ current.predecessor = timestamp;
2240
+ frame = orderedFrame(frame, lastHostTime);
2241
+ lastHostTime = frame.hostTime;
2242
+ delivered++;
2243
+ counts.count("accepted");
2244
+ latest = Option.some(frame);
2245
+ history = [...history.filter((kept) => kept.hostTime >= frame.hostTime - Duration.toMillis(options.frameHistory)), frame];
2246
+ for (const subscriber of current.subscribers) Queue.offerUnsafe(subscriber, {
2247
+ _tag: "Frame",
2248
+ sequence: delivered,
2249
+ frame
2250
+ });
2251
+ };
2252
+ const resized = yield* Queue.sliding(1);
2253
+ const sizes = yield* sizeFilter(options, deliver, (frames) => counts.count("foreignSize", frames), (size) => {
2254
+ Queue.offerUnsafe(resized, size);
2255
+ });
2256
+ const renewing = yield* renewals(options);
2257
+ const notifyFailure = (current, failure) => {
2258
+ if (failureOf(current.state) !== void 0) return;
2259
+ for (const subscriber of current.subscribers) Queue.offerUnsafe(subscriber, {
2260
+ _tag: "Failure",
2261
+ error: failure
2262
+ });
2263
+ stop(current, failure);
2264
+ };
2265
+ const failed = (current) => (cause) => notifyFailure(current, options.error(cause));
2266
+ const stopNative = (current) => pictures.track("screencast stop", current.transport.stop(), failed(current));
2267
+ const startNative = (current) => pictures.track("screencast start", current.transport.start(settingsOf$1(current)), failed(current));
2268
+ const stop = (current, failure) => {
2269
+ const stopped = current.state._tag === "Stopped";
2270
+ const paused = current.state._tag === "Paused";
2271
+ current.state = step(current.state, {
2272
+ _tag: "Stop",
2273
+ failure
2274
+ });
2275
+ if (stopped) return;
2276
+ sizes.end();
2277
+ current.unlisten();
2278
+ if (!paused) stopNative(current);
2279
+ };
2280
+ const gone = () => options.error(/* @__PURE__ */ new Error("Target page has been closed"));
2281
+ const why = told(closed, gone, options.clock);
2282
+ const awaitStop = (current) => pictures.wait("screencast stop").pipe(Effect.catch((error) => Effect.sync(() => notifyFailure(current, error))));
2283
+ const pictures = make$13({
2284
+ clock: options.clock,
2285
+ error: options.error,
2286
+ closed: isClosed,
2287
+ current: () => generation,
2288
+ fail: (current, error) => {
2289
+ if (current !== void 0) notifyFailure(current, error);
2290
+ },
2291
+ pause: (current) => Effect.gen(function* () {
2292
+ if (current?.state._tag !== "Capturing") return;
2293
+ current.state = step(current.state, { _tag: "Pause" });
2294
+ latest = Option.none();
2295
+ sizes.end();
2296
+ stopNative(current);
2297
+ yield* pictures.wait("screencast stop").pipe(Effect.tapError((error) => Effect.sync(() => notifyFailure(current, error))));
2298
+ yield* healthy(current);
2299
+ }),
2300
+ resume: (current) => Effect.gen(function* () {
2301
+ const resumable = () => {
2302
+ if (current === void 0 || generation !== current) return false;
2303
+ if (current.subscribers.size === 0) {
2304
+ stop(current);
2305
+ generation = void 0;
2306
+ }
2307
+ return current.state._tag !== "Stopped" && !isClosed();
2308
+ };
2309
+ if (current === void 0 || !resumable()) return;
2310
+ pictures.track("picture restoration", options.restore(), failed(current));
2311
+ yield* pictures.wait("picture restoration");
2312
+ yield* healthy(current);
2313
+ const viewport = yield* readViewport(options);
2314
+ if (!resumable()) return;
2315
+ sizes.restart(viewport);
2316
+ current.state = step(current.state, { _tag: "Resume" });
2317
+ startNative(current);
2318
+ yield* pictures.wait("screencast start");
2319
+ yield* healthy(current);
2320
+ })
2321
+ });
2322
+ yield* followGrowth(resized, lock, () => generation, pictures, notifyFailure);
2323
+ const leave = (current, subscription) => Effect.gen(function* () {
2324
+ current.subscribers.delete(subscription);
2325
+ yield* Queue.shutdown(subscription);
2326
+ if (current.subscribers.size !== 0) return;
2327
+ yield* Effect.sync(() => stop(current));
2328
+ yield* awaitStop(current);
2329
+ if (generation === current) generation = void 0;
2330
+ });
2331
+ const acquire = (screencast) => lock.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
2332
+ if (isClosed()) return yield* gone();
2333
+ let current = generation;
2334
+ const starting = current === void 0;
2335
+ if (current === void 0) {
2336
+ yield* pictures.idle;
2337
+ const [transport, { calibration, viewport }] = yield* prepare(options, screencast);
2338
+ const size = screencast.size ?? viewport;
2339
+ if (isClosed()) return yield* gone();
2340
+ current = {
2341
+ id: ++generations,
2342
+ sequence: 0,
2343
+ subscribers: /* @__PURE__ */ new Set(),
2344
+ transport,
2345
+ unlisten: () => void 0,
2346
+ calibration,
2347
+ quality: screencast.quality ?? 80,
2348
+ size,
2349
+ explicitSize: screencast.size !== void 0,
2350
+ state: initial,
2351
+ predecessor: void 0
2352
+ };
2353
+ generation = current;
2354
+ latest = Option.none();
2355
+ sizes.restart(viewport);
2356
+ } else if (screencast.quality !== void 0 && screencast.quality !== current.quality || screencast.size !== void 0 && (screencast.size.width !== current.size?.width || screencast.size.height !== current.size.height)) return yield* undispatched("screencast", new InvalidRequest({ detail: `a screencast with quality ${current.quality}${current.size === null ? "" : ` and size ${current.size.width}x${current.size.height}`} is already running on this page; read it without options or with the same ones` }));
2357
+ const subscription = yield* subscribe(current);
2358
+ const baseline = delivered;
2359
+ const frame = currentFrame(current, latest);
2360
+ if (starting) {
2361
+ const listening = current;
2362
+ current.unlisten = listening.transport.listen({
2363
+ frame: receive(options, current, replies, counts, sizes, renewing, notifyFailure),
2364
+ lost: (error) => notifyFailure(listening, error)
2365
+ });
2366
+ const screencast = Effect.promise(() => startNative(listening)).pipe(Effect.andThen(healthy(listening)));
2367
+ const started = yield* options.watch.pipe(Effect.zip(screencast, { concurrent: true }), Effect.interruptible, Effect.timeoutOrElse({
2368
+ duration: deadline,
2369
+ orElse: () => Effect.fail(options.error(/* @__PURE__ */ new Error("screencast start exceeded its deadline")))
2370
+ }), Effect.provideService(Clock.Clock, options.clock), Effect.exit);
2371
+ if (Exit.isFailure(started)) {
2372
+ yield* leave(current, subscription);
2373
+ return yield* Effect.failCause(started.cause);
2374
+ }
2375
+ }
2376
+ return {
2377
+ current,
2378
+ subscription,
2379
+ baseline,
2380
+ frame
2381
+ };
2382
+ })));
2383
+ const open = reader(acquire, ({ current, subscription }) => Effect.suspend(() => {
2384
+ current.subscribers.delete(subscription);
2385
+ return current.subscribers.size > 0 ? Queue.shutdown(subscription) : lock.withPermits(1)(leave(current, subscription));
2386
+ }), why, (count) => counts.count("lost", count));
2387
+ yield* Effect.addFinalizer(() => Effect.sync(() => Deferred.doneUnsafe(closed, Exit.void)).pipe(Effect.andThen(lock.withPermits(1)(Effect.suspend(() => {
2388
+ const current = generation;
2389
+ if (current === void 0) return Effect.void;
2390
+ notifyFailure(current, gone());
2391
+ return awaitStop(current);
2392
+ })))));
2393
+ return {
2394
+ open,
2395
+ stream: (options) => Stream.unwrap(Effect.map(open(options), ({ stream }) => stream)),
2396
+ latest: Effect.sync(() => latest),
2397
+ recent: Effect.sync(() => history),
2398
+ active: Effect.sync(() => generation !== void 0 && generation.state._tag !== "Stopped"),
2399
+ sync: Effect.suspend(() => synced(generation, why, options.error)),
2400
+ current: (frame) => isCurrent(frame, generation, latest),
2401
+ confirm: confirmation(() => ({
2402
+ generation,
2403
+ replies: replies.size
2404
+ }), (frame) => isCurrent(frame, generation, latest), why, options.error),
2405
+ excluding: (picture) => lock.withPermits(1)(pictures.excluding(picture)),
2406
+ stats: (windowMillis) => Effect.sync(() => new CaptureStats({
2407
+ ...counts.read(windowMillis),
2408
+ ackBacklog: replies.size
2409
+ }))
2410
+ };
2411
+ });
2412
+ //#endregion
2413
+ //#region src/internal/pictures/transport.ts
2414
+ /**
2415
+ * Where a page's screencast runs: on the page's own session, or on a capture connection that the
2416
+ * provider supplies, where frames and their acknowledgements never wait behind a large message on
2417
+ * the connection that drives the page. There the page's session attaches as its first capture
2418
+ * starts, with the Page domain on, and stays until the page closes or the session ends; the next
2419
+ * capture then attaches again.
2420
+ *
2421
+ * Frames take their document from the commits their own session reports, in the order the browser
2422
+ * sent them, so a frame never shows a document after the one it carries, as on the page's own
2423
+ * session. They are numbered as the page's own session counts documents: a commit it has counted
2424
+ * keeps its number, and one the capture connection sees first takes the next, until it is counted.
2425
+ */
2426
+ /** The page's own session. */
2427
+ const own = (page, bridge) => {
2428
+ const { send } = page.protocol;
2429
+ return {
2430
+ start: (settings) => send("Page.startScreencast", settings),
2431
+ acknowledge: (frame) => send("Page.screencastFrameAck", { sessionId: frame }),
2432
+ stop: () => send("Page.stopScreencast"),
2433
+ sync: () => Promise.resolve(),
2434
+ listen: (on) => {
2435
+ const frame = (value) => Option.match(Schema.decodeUnknownOption(ScreencastFrame)(value), {
2436
+ onNone: () => on.lost(undispatched("screencast", new Failed({ detail: "the page connection sent an unreadable screencast frame" }))),
2437
+ onSome: on.frame
2438
+ });
2439
+ page.cdp.on("Page.screencastFrame", frame);
2440
+ return () => {
2441
+ page.cdp.off("Page.screencastFrame", frame);
2442
+ };
2443
+ },
2444
+ frameTag: bridge.frameTag
2445
+ };
2446
+ };
2447
+ const FrameTree$1 = Schema.Struct({ frameTree: Schema.Struct({ frame: Commit }) });
2448
+ /** A native screencast frame, as Chromium sends it. */
2449
+ const ScreencastFrame = Schema.Struct({
2450
+ data: Schema.String,
2451
+ sessionId: Schema.Int,
2452
+ metadata: Schema.Struct({
2453
+ timestamp: Schema.optionalKey(Schema.Finite),
2454
+ deviceWidth: Schema.Finite,
2455
+ deviceHeight: Schema.Finite
2456
+ })
2457
+ });
2458
+ /**
2459
+ * The document and address a capture connection's frames show, from the commits its session
2460
+ * reports after `first`, the main frame's document as the session began.
2461
+ */
2462
+ const documents = (bridge, first) => {
2463
+ const counted = (loader) => bridge.documentOf(loader) ?? -1;
2464
+ const latest = bridge.frameTag().document;
2465
+ const shown = {
2466
+ ...first,
2467
+ document: counted(first.loader) >= 0 ? counted(first.loader) : latest === 0 ? 0 : latest + 1
2468
+ };
2469
+ return {
2470
+ /** A commit or a move the session reported, in the order the browser sent them. */
2471
+ see: (seen) => {
2472
+ if (seen?.loader !== void 0) {
2473
+ shown.document = Math.max(shown.document + 1, counted(seen.loader));
2474
+ shown.loader = seen.loader;
2475
+ }
2476
+ if (seen !== void 0) shown.url = seen.url;
2477
+ },
2478
+ tag: () => {
2479
+ shown.document = Math.max(shown.document, counted(shown.loader));
2480
+ return {
2481
+ document: shown.document,
2482
+ url: shown.url
2483
+ };
2484
+ }
2485
+ };
2486
+ };
2487
+ /**
2488
+ * The page's session on the capture connection, attached when a capture asks for it and kept for
2489
+ * the page's scope. Its state changes only here: attaching, attached, or ended by the session's
2490
+ * end, which also ends the capture listening to it.
2491
+ */
2492
+ const apart = (page, bridge, source, error, pageScope) => {
2493
+ const lock = Semaphore.makeUnsafe(1);
2494
+ let state = { _tag: "Detached" };
2495
+ let listening;
2496
+ const latest = () => state;
2497
+ const end = (scope, ended) => {
2498
+ if (state._tag !== "Attaching" && state._tag !== "Attached" || state.scope !== scope) return;
2499
+ const attached = state._tag === "Attached";
2500
+ state = {
2501
+ _tag: "Ended",
2502
+ scope,
2503
+ error: ended
2504
+ };
2505
+ if (attached) listening?.lost(ended);
2506
+ };
2507
+ const unreadable = undispatched("screencast", new Failed({ detail: "the capture connection sent an event it could not read" }));
2508
+ const attach = (scope) => Effect.gen(function* () {
2509
+ let shown;
2510
+ const event = (method, params) => {
2511
+ const decoded = (schema, act) => Option.match(Schema.decodeUnknownOption(schema)(params), {
2512
+ onNone: () => end(scope, unreadable),
2513
+ onSome: act
2514
+ });
2515
+ if (method === "Page.screencastFrame") decoded(ScreencastFrame, (frame) => listening?.frame(frame));
2516
+ else if (method === "Page.frameNavigated" || method === "Page.navigatedWithinDocument") decoded(MainFrameEvent, (event) => shown?.see(mainFrame(page.id, event)));
2517
+ else if (method === "Target.detachedFromTarget") end(scope, error(/* @__PURE__ */ new Error("Target page has been closed")));
2518
+ };
2519
+ const send = yield* openCapture(page.id, source, {
2520
+ event,
2521
+ lost: (lost) => end(scope, lost)
2522
+ });
2523
+ const tracked = yield* Effect.tryPromise({
2524
+ try: () => Promise.all([send("Page.enable"), send("Page.getFrameTree")]).then(([, tree]) => Option.match(Schema.decodeUnknownOption(FrameTree$1)(tree), {
2525
+ onNone: () => Promise.reject(unreadable),
2526
+ onSome: ({ frameTree }) => shown = documents(bridge, commitOf(frameTree.frame))
2527
+ })),
2528
+ catch: error
2529
+ });
2530
+ return {
2531
+ start: (settings) => send("Page.startScreencast", settings),
2532
+ acknowledge: (frame) => send("Page.screencastFrameAck", { sessionId: frame }),
2533
+ stop: () => send("Page.stopScreencast"),
2534
+ sync: () => send("Page.getFrameTree"),
2535
+ listen: (on) => {
2536
+ listening = on;
2537
+ return () => {
2538
+ if (listening === on) listening = void 0;
2539
+ };
2540
+ },
2541
+ frameTag: () => ({
2542
+ session: page.session,
2543
+ connection: page.connection,
2544
+ ...tracked.tag()
2545
+ })
2546
+ };
2547
+ }).pipe(Scope.provide(scope));
2548
+ const current = Effect.suspend(() => {
2549
+ switch (state._tag) {
2550
+ case "Attached": return Effect.succeed(state.transport);
2551
+ case "Ended": {
2552
+ const { scope } = state;
2553
+ state = { _tag: "Detached" };
2554
+ return Scope.close(scope, Exit.void).pipe(Effect.andThen(current));
2555
+ }
2556
+ case "Detached":
2557
+ case "Attaching": return Effect.gen(function* () {
2558
+ const scope = yield* Scope.fork(pageScope);
2559
+ state = {
2560
+ _tag: "Attaching",
2561
+ scope
2562
+ };
2563
+ const attached = yield* Effect.exit(attach(scope).pipe(page.within("screencast")));
2564
+ const settled = latest();
2565
+ if (Exit.isSuccess(attached) && settled._tag === "Attaching" && settled.scope === scope) {
2566
+ state = {
2567
+ _tag: "Attached",
2568
+ scope,
2569
+ transport: attached.value
2570
+ };
2571
+ return attached.value;
2572
+ }
2573
+ state = { _tag: "Detached" };
2574
+ yield* Scope.close(scope, Exit.void);
2575
+ if (Exit.isFailure(attached)) return yield* attached;
2576
+ return yield* settled._tag === "Ended" ? settled.error : unreadable;
2577
+ });
2578
+ }
2579
+ });
2580
+ return lock.withPermits(1)(current);
2581
+ };
2582
+ //#endregion
2583
+ //#region src/internal/pictures/pictures.ts
2584
+ /**
2585
+ * Pictures of a page: screenshots, frames of a stated age, zooms, and its screencast with the clock
2586
+ * that times its frames. A new picture is taken on the page's own protocol session, one at a time:
2587
+ * one call where a device pixel is a CSS pixel and nothing is cropped, and two otherwise, unless
2588
+ * Playwright emulates the viewport. The page's first clipped picture also holds the screen it reads.
2589
+ */
2590
+ /** Read a JPEG's dimensions from its start-of-frame marker. */
2591
+ const jpegSize = (bytes) => {
2592
+ let offset = 2;
2593
+ while (offset + 9 < bytes.length) {
2594
+ if (bytes[offset] !== 255) return void 0;
2595
+ const marker = bytes[offset + 1] ?? 0;
2596
+ const length = (bytes[offset + 2] ?? 0) << 8 | (bytes[offset + 3] ?? 0);
2597
+ if (marker >= 192 && marker <= 195) return {
2598
+ height: (bytes[offset + 5] ?? 0) << 8 | (bytes[offset + 6] ?? 0),
2599
+ width: (bytes[offset + 7] ?? 0) << 8 | (bytes[offset + 8] ?? 0)
2600
+ };
2601
+ offset += 2 + length;
2602
+ }
2603
+ };
2604
+ /** Read a PNG's dimensions from its header chunk. */
2605
+ const pngSize = (bytes) => {
2606
+ if (bytes.length < 24 || bytes[1] !== 80 || bytes[2] !== 78 || bytes[3] !== 71) return void 0;
2607
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2608
+ return {
2609
+ width: view.getUint32(16),
2610
+ height: view.getUint32(20)
2611
+ };
2612
+ };
2613
+ const LayoutMetrics = Schema.Struct({
2614
+ cssVisualViewport: Schema.Struct({
2615
+ pageX: Schema.Finite,
2616
+ pageY: Schema.Finite,
2617
+ scale: Schema.Finite.check(Schema.isGreaterThan(0))
2618
+ }),
2619
+ contentSize: Schema.Struct({ width: Schema.Finite }),
2620
+ cssContentSize: Schema.Struct({ width: Schema.Finite })
2621
+ });
2622
+ const defaultMaxAge = Duration.millis(250);
2623
+ const surfaceless = (error) => error.reason._tag === "Failed" && error.reason.detail.includes("Unable to capture screenshot");
2624
+ const untilPainted = (capture) => capture.pipe(Effect.retry({
2625
+ while: surfaceless,
2626
+ schedule: Schedule.spaced("16 millis")
2627
+ }));
2628
+ /**
2629
+ * Measure this page's clock against the browser's, in a world without the page script: no DOM
2630
+ * markers, input, navigation or extra tabs. Each of three probes reads the browser's time between
2631
+ * two stamps of the owner's clock, and the fastest bounds the offset best. A busy page answers each
2632
+ * probe late, behind its own work, so the probes that answered within two seconds serve, and the
2633
+ * measurement fails only if none did: a wide estimate keeps a capture going, and a renewal while
2634
+ * its frames flow narrows it.
2635
+ */
2636
+ const calibrator = (page, bridge) => {
2637
+ const { native, now, within } = page;
2638
+ const { send } = page.protocol;
2639
+ const probe = (contextId) => Effect.gen(function* () {
2640
+ const hostStart = now();
2641
+ const { result, exceptionDetails } = yield* native("calibrate", () => send("Runtime.evaluate", {
2642
+ contextId,
2643
+ expression: "performance.timeOrigin + performance.now()",
2644
+ returnByValue: true
2645
+ })).pipe(page.span("Page.evaluate", { function: "clock" }, "Trace"));
2646
+ const hostEnd = now();
2647
+ const browserTime = result.value;
2648
+ if (exceptionDetails !== void 0 || typeof browserTime !== "number") return yield* failWith("calibrate", new Failed({ detail: "the browser clock probe did not return a timestamp" }));
2649
+ return {
2650
+ hostStart,
2651
+ hostEnd,
2652
+ browserTime
2653
+ };
2654
+ });
2655
+ const answered = (contextId) => Effect.gen(function* () {
2656
+ const probes = [];
2657
+ yield* Effect.forEach([
2658
+ 1,
2659
+ 2,
2660
+ 3
2661
+ ], () => Effect.map(probe(contextId), (one) => probes.push(one)), { discard: true }).pipe(within("calibrate", Duration.seconds(2)), Effect.catch((error) => probes.length === 0 ? Effect.fail(error) : Effect.void));
2662
+ return probes;
2663
+ });
2664
+ return bridge.bareWorld("calibrate").pipe(Effect.flatMap(answered), Effect.flatMap((probes) => Option.match(estimate(probes), {
2665
+ onNone: () => failWith("calibrate", new Failed({ detail: "the browser clock probes did not define a finite interval" })),
2666
+ onSome: Effect.succeed
2667
+ })), within("calibrate", Duration.seconds(4)), Effect.tap((estimate) => Effect.annotateCurrentSpan("roundTripMillis", Math.round(estimate.roundTripMillis * 10) / 10)), page.span("Page.calibrateClock", {}, "Debug"), page.owned);
2668
+ };
2669
+ const ScreenSize = Schema.Struct({
2670
+ width: Schema.Int,
2671
+ height: Schema.Int
2672
+ });
2673
+ const camera = (page, bridge, viewport, capture) => {
2674
+ const { playwright, native, within } = page;
2675
+ const { send } = page.protocol;
2676
+ let ratio = 1;
2677
+ let screenHeld = false;
2678
+ const holdScreen = Effect.fnUntraced(function* (operation) {
2679
+ if (screenHeld) return;
2680
+ const { width, height } = yield* bridge.evaluate(operation, scriptCall("screenSize")).pipe(Effect.flatMap(decodeWith(operation, ScreenSize)));
2681
+ yield* native(operation, () => send("Emulation.setDeviceMetricsOverride", {
2682
+ width: 0,
2683
+ height: 0,
2684
+ deviceScaleFactor: 0,
2685
+ mobile: false,
2686
+ screenWidth: width,
2687
+ screenHeight: height
2688
+ }));
2689
+ screenHeld = true;
2690
+ });
2691
+ const decoded = (operation, data, format) => {
2692
+ const size = format === "png" ? pngSize(data) : jpegSize(data);
2693
+ return size === void 0 ? failWith(operation, new Failed({ detail: `the browser's picture is not a ${format.toUpperCase()}` })) : Effect.succeed(new Image({
2694
+ data,
2695
+ mediaType: `image/${format}`,
2696
+ ...size
2697
+ }));
2698
+ };
2699
+ const take = (operation, format, run) => native(operation, run).pipe(untilPainted, Effect.flatMap((data) => decoded(operation, data, format)));
2700
+ const shot = (operation, format, quality, clip) => take(operation, format, () => send("Page.captureScreenshot", {
2701
+ format,
2702
+ ...format === "jpeg" ? { quality } : {},
2703
+ ...clip === void 0 ? {} : { clip }
2704
+ }).then(({ data }) => {
2705
+ const decoded = Base64.decode(data);
2706
+ return Result.isSuccess(decoded) ? decoded.success : Promise.reject(/* @__PURE__ */ new Error("the browser sent invalid base64 picture data"));
2707
+ }));
2708
+ const emulatedShot = (operation, format, quality, scale, crop) => take(operation, format, () => playwright.screenshot({
2709
+ type: format,
2710
+ ...format === "jpeg" ? { quality } : {},
2711
+ scale,
2712
+ timeout: 0,
2713
+ ...crop === void 0 ? {} : { clip: crop }
2714
+ }));
2715
+ return (operation, quality, crop, format = "jpeg", pixels = "css") => Effect.gen(function* () {
2716
+ const known = viewport.knownViewport();
2717
+ let whole;
2718
+ if (crop === void 0 && ratio === 1 && pixels === "css") {
2719
+ whole = yield* shot(operation, format, quality);
2720
+ if (whole.width === known?.width && whole.height === known.height) return whole;
2721
+ }
2722
+ const emulated = playwright.viewportSize();
2723
+ if (emulated !== null) {
2724
+ if (whole !== void 0) ratio = whole.width / emulated.width;
2725
+ return yield* emulatedShot(operation, format, quality, pixels, crop);
2726
+ }
2727
+ const [metrics] = yield* native(operation, () => send("Page.getLayoutMetrics")).pipe(Effect.flatMap(decodeWith(operation, LayoutMetrics)), Effect.zip(crop === void 0 ? Effect.void : holdScreen(operation), { concurrent: true }));
2728
+ const measured = metrics.contentSize.width / metrics.cssContentSize.width;
2729
+ ratio = Number.isFinite(measured) && measured > 0 ? measured : 1;
2730
+ if (crop === void 0 && ratio === 1) {
2731
+ const image = whole ?? (yield* shot(operation, format, quality));
2732
+ viewport.remember(image);
2733
+ return image;
2734
+ }
2735
+ const rect = crop ?? {
2736
+ x: 0,
2737
+ y: 0,
2738
+ ...known ?? (yield* viewport.viewportFor(operation))
2739
+ };
2740
+ const { pageX, pageY, scale } = metrics.cssVisualViewport;
2741
+ yield* holdScreen(operation);
2742
+ return yield* shot(operation, format, quality, {
2743
+ x: pageX + rect.x,
2744
+ y: pageY + rect.y,
2745
+ width: Math.floor(rect.width / scale + .001),
2746
+ height: Math.floor(rect.height / scale + .001),
2747
+ scale: pixels === "device" ? scale : scale / ratio
2748
+ });
2749
+ }).pipe(capture.excluding, within(operation));
2750
+ };
2751
+ const millisOf = (input) => Option.match(Duration.fromInput(input), {
2752
+ onNone: () => NaN,
2753
+ onSome: Duration.toMillis
2754
+ });
2755
+ const reuse = (page, bridge, viewport, capture) => (operation, options) => Effect.gen(function* () {
2756
+ const maxAge = millisOf(options.maxAge ?? defaultMaxAge);
2757
+ if (!(maxAge >= 0)) return yield* refuse(operation, "maxAge must be a duration of zero or more");
2758
+ const latest = yield* capture.latest;
2759
+ const known = viewport.knownViewport();
2760
+ const { activity } = page;
2761
+ return Option.filter(latest, (frame) => {
2762
+ const earliest = frame.hostTime - frame.timing.uncertaintyMillis;
2763
+ return frame.document === bridge.frameTag().document && page.now() - earliest <= maxAge && earliest > activity.documentAt && (options.after !== "input" || earliest > activity.inputAt) && frame.width === known?.width && frame.height === known.height;
2764
+ });
2765
+ });
2766
+ /** Where a picture came from: a frame the screencast had delivered, or a new screenshot. */
2767
+ const sourceOf = (reused) => Option.isSome(reused) ? "frame" : "screenshot";
2768
+ const make$11 = Effect.fnUntraced(function* (page, bridge, viewport) {
2769
+ const { id, clock, settings, mapping, now, span, owned, lane, within } = page;
2770
+ const calibrateClock = calibrator(page, bridge);
2771
+ const error = (cause) => Schema.is(BrowserError)(cause) ? cause : undispatched("screencast", reasonOf(cause, void 0, page.closedBy()));
2772
+ const capture = yield* make$12({
2773
+ id,
2774
+ 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)),
2775
+ clock,
2776
+ calibrate: page.focused.pipe(within("focus"), Effect.andThen(mapping.current(calibrateClock))),
2777
+ latest: mapping.latest,
2778
+ renew: mapping.renew(calibrateClock),
2779
+ watch: bridge.currentDocument("screencast"),
2780
+ frameHistory: settings.frameHistory,
2781
+ viewport: Effect.suspend(() => viewport.viewportFor("screencast")),
2782
+ restore: () => page.protocol.send("Page.captureScreenshot", {
2783
+ format: "jpeg",
2784
+ quality: 0,
2785
+ optimizeForSpeed: true
2786
+ }),
2787
+ imageSize: jpegSize,
2788
+ error
2789
+ });
2790
+ const picture = camera(page, bridge, viewport, capture);
2791
+ const reusable = reuse(page, bridge, viewport, capture);
2792
+ const screenshots = lane.shared("screenshot", false);
2793
+ const frames = lane.shared("frame", false);
2794
+ const screenshot = (options = {}) => screenshots(JSON.stringify([
2795
+ millisOf(options.maxAge ?? defaultMaxAge),
2796
+ options.clip,
2797
+ options.quality,
2798
+ options.format,
2799
+ options.scale
2800
+ ]), Effect.gen(function* () {
2801
+ const reused = options.clip === void 0 && options.format !== "png" && options.scale !== "device" ? yield* reusable("screenshot", {
2802
+ maxAge: options.maxAge,
2803
+ after: "input"
2804
+ }) : Option.none();
2805
+ const image = Option.isSome(reused) ? reused.value.image : yield* picture("screenshot", options.quality ?? 80, options.clip, options.format, options.scale);
2806
+ yield* Effect.annotateCurrentSpan({
2807
+ source: sourceOf(reused),
2808
+ bytes: image.data.length
2809
+ });
2810
+ return image;
2811
+ })).pipe(span("Page.screenshot"), owned);
2812
+ const taken = (options) => Effect.gen(function* () {
2813
+ const reused = yield* reusable("frame", options);
2814
+ yield* Effect.annotateCurrentSpan("source", sourceOf(reused));
2815
+ if (Option.isSome(reused)) return reused.value;
2816
+ const startedAt = now();
2817
+ const image = yield* picture("frame", 80);
2818
+ const finishedAt = now();
2819
+ return new Frame({
2820
+ page: id,
2821
+ data: image.data,
2822
+ timing: new Screenshot({
2823
+ hostTime: startedAt + (finishedAt - startedAt) / 2,
2824
+ uncertaintyMillis: (finishedAt - startedAt) / 2
2825
+ }),
2826
+ receivedAt: finishedAt,
2827
+ width: image.width,
2828
+ height: image.height,
2829
+ ...bridge.frameTag()
2830
+ });
2831
+ });
2832
+ const frame = (options = {}) => (options.after === "input" ? Effect.succeed(Option.none()) : reusable("frame", options)).pipe(Effect.flatMap(Option.match({
2833
+ onSome: (reused) => Effect.as(Effect.annotateCurrentSpan("source", "frame"), reused),
2834
+ onNone: () => frames(JSON.stringify([millisOf(options.maxAge ?? defaultMaxAge), options.after]), taken(options))
2835
+ })), span("Page.frame"), owned);
2836
+ const zoom = (requested, options = {}) => lane.read("zoom")(Effect.gen(function* () {
2837
+ const region = yield* Schema.decodeEffect(Region)(requested).pipe(Effect.mapError((error) => undispatched("zoom", new InvalidRequest({ detail: error.message }))));
2838
+ const size = viewport.knownViewport() ?? (yield* viewport.viewportFor("zoom"));
2839
+ 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");
2840
+ const image = yield* picture("zoom", 80, region, "jpeg", options.scale);
2841
+ return new Zoom({
2842
+ page: id,
2843
+ region,
2844
+ image
2845
+ });
2846
+ }).pipe(within("zoom"))).pipe(span("Page.zoom"), owned);
2847
+ const captureStats = (options = {}) => {
2848
+ if (options.window === void 0) return capture.stats();
2849
+ const millis = millisOf(options.window);
2850
+ return millis > 0 && millis <= Duration.toMillis(countsKept) ? capture.stats(millis) : refuse("captureStats", "window must be over zero and at most a minute");
2851
+ };
2852
+ return {
2853
+ capture,
2854
+ screenshot,
2855
+ frame,
2856
+ zoom,
2857
+ captureStats,
2858
+ estimate: mapping.current(calibrateClock)
2859
+ };
2860
+ });
2861
+ //#endregion
2862
+ //#region src/internal/reading/reading.ts
2863
+ /**
2864
+ * Reading a page: its outline with refs, the elements a query finds and the text it shows. Each
2865
+ * read takes its turn on the page and shares its work with identical reads, as `lane.ts`
2866
+ * describes. The viewport's text as it was last read is kept, for `Page.state`.
2867
+ */
2868
+ const FindResults = Schema.Union([Schema.Struct({ found: Schema.Array(Found) }), Schema.Struct({ invalid: Schema.String })]);
2869
+ const UntilResult = Schema.Union([Schema.Struct({
2870
+ met: Schema.Boolean,
2871
+ mark: Schema.String
2872
+ }), Schema.Struct({ invalid: Schema.String })]);
2873
+ const make$10 = (page, bridge) => Effect.sync(() => {
2874
+ const { now, span, owned, within, lane } = page;
2875
+ const { evaluate } = bridge;
2876
+ const snapshots = lane.shared("snapshot", true);
2877
+ const finds = lane.shared("find", true);
2878
+ const texts = lane.shared("text", true);
2879
+ let viewed;
2880
+ const snapshot = (snapshotOptions = {}) => {
2881
+ const asked = {
2882
+ full: snapshotOptions.full ?? false,
2883
+ query: snapshotOptions.query ?? null,
2884
+ within: snapshotOptions.within ?? null,
2885
+ maxChars: snapshotOptions.maxChars ?? 12e3,
2886
+ boxes: snapshotOptions.boxes ?? false
2887
+ };
2888
+ return snapshots(JSON.stringify(asked), Effect.gen(function* () {
2889
+ const result = yield* evaluate("snapshot", scriptCall("snapshot", asked)).pipe(Effect.flatMap(decodeWith("snapshot", SnapshotResultSchema)));
2890
+ if ("invalid" in result) return yield* refuse("snapshot", result.invalid);
2891
+ const { text, truncated, url } = result.snapshot;
2892
+ yield* Effect.annotateCurrentSpan({
2893
+ chars: text.length,
2894
+ truncated
2895
+ });
2896
+ return new Snapshot({
2897
+ ...result.snapshot,
2898
+ url: redact(url)
2899
+ });
2900
+ }).pipe(within("snapshot"))).pipe(span("Page.snapshot", { full: asked.full }), owned);
2901
+ };
2902
+ const find = (query = {}) => {
2903
+ const asked = request(query, "viewport");
2904
+ return finds(JSON.stringify(asked), Effect.gen(function* () {
2905
+ const result = yield* evaluate("find", scriptCall("find", asked)).pipe(Effect.flatMap(decodeWith("find", FindResults)));
2906
+ if ("invalid" in result) return yield* refuse("find", result.invalid);
2907
+ yield* Effect.annotateCurrentSpan({ found: result.found.length });
2908
+ return result.found;
2909
+ }).pipe(within("find"))).pipe(span("Page.find", {
2910
+ scope: asked.scope,
2911
+ role: asked.role ?? ""
2912
+ }), owned);
2913
+ };
2914
+ const text = (options = {}) => {
2915
+ const scope = options.scope ?? "viewport";
2916
+ const request = {
2917
+ ref: scope === "viewport" ? null : scope,
2918
+ maxChars: options.maxChars ?? 12e3,
2919
+ unmask: options.unmask ?? false
2920
+ };
2921
+ return (scope !== "viewport" && !/^e\d+$/.test(scope) ? refuse("text", `${scope} is neither "viewport" nor a ref such as e12`) : texts(JSON.stringify(request), Effect.gen(function* () {
2922
+ const result = yield* evaluate("text", scriptCall("text", request)).pipe(Effect.flatMap(decodeWith("text", TextResultSchema)));
2923
+ if (result === null) return yield* failWith("text", new StaleRef({ ref: scope }));
2924
+ yield* Effect.annotateCurrentSpan({
2925
+ chars: result.text.length,
2926
+ truncated: result.truncated
2927
+ });
2928
+ const shown = new Text({
2929
+ ...result,
2930
+ url: redact(result.url),
2931
+ at: now()
2932
+ });
2933
+ if (request.ref === null) viewed = shown;
2934
+ return shown;
2935
+ }).pipe(within("text")))).pipe(span("Page.text", { scope: scope === "viewport" ? "viewport" : "ref" }), owned);
2936
+ };
2937
+ const until = (query, want, millis) => {
2938
+ if (!Number.isFinite(millis) || millis < 0) return refuse("until", "the wait duration must be finite and nonnegative");
2939
+ const look = Effect.gen(function* () {
2940
+ const deadline = now() + millis;
2941
+ const request$1 = request(query, "document");
2942
+ return yield* Effect.suspend(() => evaluate("expect", scriptCall("until", request$1, want, Math.max(0, deadline - now())))).pipe(Effect.flatMap(decodeWith("expect", UntilResult)), Effect.filterOrElse((result) => "met" in result, (result) => refuse("expect", result.invalid)), Effect.retry({
2943
+ while: (error) => contextGone(error) && now() < deadline,
2944
+ schedule: Schedule.spaced("10 millis")
2945
+ }), Effect.catchIf((error) => millis > 0 && contextGone(error) && now() >= deadline, () => Effect.succeed({
2946
+ met: false,
2947
+ mark: ""
2948
+ })));
2949
+ });
2950
+ 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);
2951
+ };
2952
+ /** The viewport's text as it was last read, if after `since`, as a document began. */
2953
+ const viewedSince = (since) => viewed !== void 0 && viewed.at > since ? viewed : void 0;
2954
+ return {
2955
+ snapshot,
2956
+ find,
2957
+ text,
2958
+ until,
2959
+ viewedSince
2960
+ };
2961
+ });
2962
+ //#endregion
2963
+ //#region src/internal/reading/ready.ts
2964
+ /** Document readiness and content quiet, independent of screen-capture features. */
2965
+ const make$9 = (page, bridge) => (options = {}) => {
2966
+ const quietMillis = options.quietMillis ?? 0;
2967
+ if (!Number.isFinite(quietMillis) || quietMillis < 0) return refuse("ready", "quietMillis must be finite and nonnegative");
2968
+ const timeout = options.timeout ?? Duration.seconds(15);
2969
+ const settled = (until) => Effect.suspend(() => bridge.evaluate("ready", scriptCall("ready", Math.max(0, Math.round(until - page.now())), quietMillis))).pipe(Effect.retry({
2970
+ while: contextGone,
2971
+ schedule: Schedule.spaced(Duration.millis(10))
2972
+ }), Effect.flatMap(decodeWith("ready", ReadinessSchema)), Effect.tap((waiting) => Effect.annotateCurrentSpan({ waiting: waiting.join(",") })), Effect.filterOrElse((waiting) => waiting.length === 0, () => failWith("ready", new Timeout({ millis: Duration.toMillis(timeout) }))));
2973
+ return page.lane.read("ready")(Effect.void).pipe(Effect.andThen(Effect.suspend(() => settled(page.now() + Duration.toMillis(timeout))).pipe(page.within("ready", timeout))), page.span("Page.ready"), page.owned);
2974
+ };
2975
+ //#endregion
2976
+ //#region src/internal/timeline/changes.ts
2977
+ /**
2978
+ * Reading a page's record of what changed. The first read also registers the recorder with the
2979
+ * page's own session so that every later document records from its start, until the idle lifetime
2980
+ * expires. The page's times map to the owner's clock through the browser's one
2981
+ * clock mapping, as frames' do, which a browser's first read measures, once, where no capture has;
2982
+ * and a window can begin on the page's own clock where the previous one ended, so consecutive
2983
+ * reads neither miss nor repeat a change. A read takes its turn on the page as other reads do, and
2984
+ * identical ones in flight share it; none is kept for a later caller, since its window ends when
2985
+ * it was read.
2986
+ */
2987
+ const isChanges = Schema.is(Changes);
2988
+ const markOf = (time) => time === void 0 || typeof time === "number" ? time : isChanges(time) ? `cursor ${time.cursor}` : `frame ${time.timestamp ?? time.hostTime}`;
2989
+ const make$8 = (page, bridge, estimate) => {
2990
+ const reads = page.lane.shared("changes", false);
2991
+ const recording = Semaphore.makeUnsafe(1);
2992
+ const idleMillis = 12e4;
2993
+ let readAt = Number.NEGATIVE_INFINITY;
2994
+ let lifetime;
2995
+ let expired;
2996
+ const expiry = Effect.suspend(() => {
2997
+ const left = readAt + idleMillis - page.now();
2998
+ if (left > 0) return Effect.sleep(Duration.millis(left)).pipe(Effect.andThen(expiry));
2999
+ return recording.withPermits(1)(Effect.suspend(() => {
3000
+ if (page.now() < readAt + idleMillis) return Effect.void;
3001
+ return bridge.unregisterRecorder("changes").pipe(page.within("changes"), Effect.ensuring(Effect.sync(() => {
3002
+ lifetime = void 0;
3003
+ })));
3004
+ })).pipe(page.lane.read("changes", Duration.infinity), Effect.andThen(Effect.suspend(() => lifetime === void 0 ? Effect.void : expiry)));
3005
+ });
3006
+ const register = recording.withPermits(1)(Effect.gen(function* () {
3007
+ if (expired !== void 0) return yield* expired;
3008
+ readAt = page.now();
3009
+ yield* bridge.registerRecorder("changes");
3010
+ lifetime ??= yield* expiry.pipe(Effect.tapError((error) => Effect.sync(() => {
3011
+ expired = error;
3012
+ })), Effect.provideService(Clock.Clock, page.clock), Effect.forkIn(page.scope));
3013
+ }));
3014
+ return (options = {}) => reads(JSON.stringify([
3015
+ markOf(options.since),
3016
+ markOf(options.until),
3017
+ options.unmask ?? false
3018
+ ]), Effect.gen(function* () {
3019
+ const mapping = yield* estimate;
3020
+ const host = (epoch) => toHostTime(mapping, epoch);
3021
+ const onPage = (time) => typeof time === "number" ? time + mapping.offsetMillis : time.timestamp ?? time.hostTime + mapping.offsetMillis;
3022
+ const request = {
3023
+ since: options.since === void 0 ? null : isChanges(options.since) ? options.since.cursor : onPage(options.since),
3024
+ until: options.until === void 0 ? null : onPage(options.until),
3025
+ unmask: options.unmask ?? false
3026
+ };
3027
+ const [, result] = yield* Effect.all([register, bridge.evaluate("changes", scriptCall("changes", request)).pipe(Effect.flatMap(decodeWith("changes", ChangesResultSchema)))], { concurrency: "unbounded" });
3028
+ yield* Effect.annotateCurrentSpan({
3029
+ changes: result.records.length,
3030
+ dropped: result.dropped
3031
+ });
3032
+ const later = (epoch) => epoch === void 0 ? void 0 : host(epoch);
3033
+ return new Changes({
3034
+ document: bridge.frameTag().document,
3035
+ from: host(result.from),
3036
+ until: host(result.until),
3037
+ cursor: result.until,
3038
+ dropped: result.dropped,
3039
+ changes: result.records.map((one) => new Change({
3040
+ ...one,
3041
+ startedAt: host(one.startedAt),
3042
+ at: host(one.at),
3043
+ earlier: later(one.earlier),
3044
+ cause: later(one.cause)
3045
+ }))
3046
+ });
3047
+ }).pipe(page.within("changes"))).pipe(page.span("Page.changes"), page.owned);
3048
+ };
3049
+ //#endregion
3050
+ //#region src/internal/timeline/window.ts
3051
+ /**
3052
+ * A page's window over its three tracks on the browser's host clock: the events and frames it
3053
+ * keeps, at no call, and one read of its changes, the first starting its record. A read that fails
3054
+ * is missing, with why, and the window is still made.
3055
+ */
3056
+ const isWindow = Schema.is(Window);
3057
+ const isFrame = Schema.is(Frame);
3058
+ const isTrackEvent = Schema.is(TrackEvent);
3059
+ /**
3060
+ * Where a window asked at `now` starts and ends: never after now, nor starting after it ends.
3061
+ * Nothing for a bound that is not finite, or a negative reach back.
3062
+ */
3063
+ const boundsOf = ({ since, until }, now) => {
3064
+ const end = until === void 0 ? now : isFrame(until) ? until.hostTime : Math.min(until, now);
3065
+ const start = isWindow(since) ? since.until : isFrame(since) ? since.hostTime : !Duration.isDuration(since) ? since : Duration.isNegative(since) ? NaN : end - Duration.toMillis(since);
3066
+ return Number.isFinite(start) && Number.isFinite(end) ? Option.some({
3067
+ since: Math.min(start, end),
3068
+ until: end
3069
+ }) : Option.none();
3070
+ };
3071
+ /**
3072
+ * A window's share of the kept tracks: events after its start, frames painted from it, both up to
3073
+ * its end, so consecutive windows hold each event once and the next begins with the frame the last
3074
+ * ended on. Pointer, key and wheel input is the presentation track, not an event here.
3075
+ */
3076
+ const within = ({ since, until }, events, frames) => ({
3077
+ events: events.filter((event) => event.at > since && event.at <= until && !isTrackEvent(event)),
3078
+ frames: frames.filter((frame) => frame.hostTime >= since && frame.hostTime <= until)
3079
+ });
3080
+ const make$7 = (page, read, frames) => ({ since, until, unmask }) => Effect.gen(function* () {
3081
+ const asked = boundsOf({
3082
+ since,
3083
+ until
3084
+ }, page.now());
3085
+ if (Option.isNone(asked)) return yield* refuse("window", "a window's bounds must be finite, its reach not negative");
3086
+ const bounds = asked.value;
3087
+ const changes = yield* Effect.result(read({
3088
+ since: isWindow(since) ? since.changes ?? bounds.since : isFrame(since) ? since : bounds.since,
3089
+ until: isFrame(until) ? until : bounds.until,
3090
+ unmask
3091
+ }));
3092
+ return new Window({
3093
+ page: page.id,
3094
+ ...bounds,
3095
+ ...within(bounds, yield* page.recentEvents, yield* frames),
3096
+ changes: Result.getOrUndefined(changes),
3097
+ missing: Option.toArray(Result.getFailure(changes))
3098
+ });
3099
+ }).pipe(page.span("Page.window"), page.owned);
3100
+ //#endregion
3101
+ //#region src/internal/page/navigation.ts
3102
+ /**
3103
+ * Moving a page between documents: going to an address, back through its history, or reloading.
3104
+ * Each move is an action, so it takes the page's turn, goes through the input guard and is
3105
+ * recorded, but it sends no input.
3106
+ */
3107
+ const make$6 = (page, perform, preparePolicy) => {
3108
+ const { playwright, settings, native } = page;
3109
+ const { send } = page.protocol;
3110
+ const navigation = (value, run, address) => {
3111
+ const name = nameOf(value);
3112
+ const url = redact(address);
3113
+ return perform(value, { target: url }, settings.navigationTimeout, (action) => preparePolicy(action, { target: url }, [], { destination: url }), (marks) => marks.sent.pipe(Effect.andThen(native(name, run).pipe(Effect.onError(() => page.stopLoading))), Effect.mapError((error) => error.reason._tag === "Failed" && /net::|NS_ERROR|Cannot navigate/i.test(error.reason.detail) ? new BrowserError({
3114
+ operation: name,
3115
+ reason: new NavigationFailed({
3116
+ url,
3117
+ detail: error.reason.detail
3118
+ }),
3119
+ dispatched: true
3120
+ }) : error), Effect.asVoid));
3121
+ };
3122
+ const history = native("back", () => send("Page.getNavigationHistory"));
3123
+ const traversingHistory = history.pipe(Effect.retry({
3124
+ schedule: Schedule.spaced(Duration.millis(50)),
3125
+ while: (error) => error.reason._tag === "Failed" && /not attached to an active page/i.test(error.reason.detail)
3126
+ }));
3127
+ const title = native("title", () => send("Page.getNavigationHistory")).pipe(Effect.map(({ entries, currentIndex }) => entries[currentIndex]?.title ?? ""));
3128
+ const noPrevious = failWith("back", new NotFound({ target: "a previous page in this tab" }));
3129
+ const prepareBack = (action) => Effect.gen(function* () {
3130
+ const before = yield* history;
3131
+ const current = before.entries[before.currentIndex];
3132
+ const previous = before.entries[before.currentIndex - 1];
3133
+ if (previous === void 0) return yield* noPrevious;
3134
+ const plan = yield* preparePolicy(action, {}, [], { destination: redact(previous.url) });
3135
+ return {
3136
+ request: plan.request,
3137
+ validate: Effect.gen(function* () {
3138
+ const approval = yield* plan.validate;
3139
+ const latest = yield* history;
3140
+ if (latest.currentIndex !== before.currentIndex || latest.entries[latest.currentIndex]?.id !== current?.id || latest.entries[latest.currentIndex - 1]?.id !== previous.id || latest.entries[latest.currentIndex - 1]?.url !== previous.url) return yield* failWith("back", new NotActionable({ detail: "the navigation history changed while input policy was pending" }));
3141
+ return approval;
3142
+ })
3143
+ };
3144
+ });
3145
+ const goBack = (marks) => Effect.gen(function* () {
3146
+ const before = yield* history;
3147
+ const current = before.entries[before.currentIndex];
3148
+ const previous = before.entries[before.currentIndex - 1];
3149
+ if (current === void 0 || previous === void 0) return yield* noPrevious;
3150
+ const navigated = yield* Deferred.make();
3151
+ const onNavigation = () => {
3152
+ Deferred.doneUnsafe(navigated, Effect.void);
3153
+ };
3154
+ yield* Effect.acquireUseRelease(Effect.sync(() => playwright.on("framenavigated", onNavigation)), () => marks.sent.pipe(Effect.andThen(Effect.gen(function* () {
3155
+ yield* native("back", () => send("Page.navigateToHistoryEntry", { entryId: previous.id }));
3156
+ yield* traversingHistory.pipe(Effect.repeat({
3157
+ schedule: Schedule.spaced(Duration.millis(50)),
3158
+ until: (latest) => latest.entries[latest.currentIndex]?.id !== current.id
3159
+ }));
3160
+ yield* Deferred.await(navigated);
3161
+ yield* native("back", () => playwright.waitForLoadState("domcontentloaded", { timeout: 0 })).pipe(Effect.provideService(Current, void 0));
3162
+ }).pipe(Effect.onError(() => page.stopLoading)))), () => Effect.sync(() => playwright.off("framenavigated", onNavigation)));
3163
+ });
3164
+ const goto = (url) => {
3165
+ const parsed = parse(url);
3166
+ if (parsed === null || ![
3167
+ "http:",
3168
+ "https:",
3169
+ "about:",
3170
+ "data:",
3171
+ "file:"
3172
+ ].includes(parsed.protocol)) return refuse("navigate", `"${redact(url)}" is not a URL`);
3173
+ const run = () => playwright.goto(parsed.href, {
3174
+ waitUntil: "domcontentloaded",
3175
+ timeout: 0
3176
+ });
3177
+ return navigation({
3178
+ _tag: "Goto",
3179
+ url
3180
+ }, () => page.nativePort === void 0 ? run() : page.nativePort(page.id, "goto", { url: parsed.href }, run), parsed.href);
3181
+ };
3182
+ return {
3183
+ goto,
3184
+ back: perform({ _tag: "Back" }, { target: "back" }, settings.navigationTimeout, prepareBack, goBack),
3185
+ reload: Effect.suspend(() => navigation({ _tag: "Reload" }, () => playwright.reload({
3186
+ waitUntil: "domcontentloaded",
3187
+ timeout: 0
3188
+ }), playwright.url())),
3189
+ title
3190
+ };
3191
+ };
3192
+ //#endregion
3193
+ //#region src/internal/page/scripts.ts
3194
+ /** Main-world scripts with the page lane, document binding, policy and dispatch accounting. */
3195
+ const make$5 = (page, bridge, input) => {
3196
+ const document = () => bridge.frameTag().document;
3197
+ const changed = (operation) => failWith(operation, new NotActionable({ detail: "the script's document changed" }));
3198
+ const evaluate = (operation, script, arg) => page.native(operation, () => Promise.resolve(Reflect.apply(page.playwright.evaluate.bind(page.playwright), void 0, [script, arg])));
3199
+ const scriptFailure = (error) => contextGone(error) ? undispatched(error.operation, new NotActionable({ detail: "the script's document changed" })) : error.reason._tag === "Failed" ? undispatched(error.operation, new Threw({})) : error;
3200
+ const decode = (operation, result, value) => Schema.decodeUnknownEffect(result)(value).pipe(Effect.mapError(() => undispatched(operation, new Failed({ detail: "script result did not match its schema" }))));
3201
+ const read = (script, options) => page.lane.read("read")(Effect.gen(function* () {
3202
+ for (let attempt = 0; attempt < 2; attempt++) {
3203
+ const before = document();
3204
+ const value = yield* Effect.result(evaluate("read", script, options.arg));
3205
+ if (value._tag === "Failure" && contextGone(value.failure)) {
3206
+ if (attempt === 1) return yield* changed("read");
3207
+ yield* bridge.waitForDocument(before);
3208
+ continue;
3209
+ }
3210
+ if (document() !== before) continue;
3211
+ if (value._tag === "Failure") return yield* scriptFailure(value.failure);
3212
+ return {
3213
+ value: yield* decode("read", options.result, value.success),
3214
+ document: before,
3215
+ connection: page.connection
3216
+ };
3217
+ }
3218
+ return yield* changed("read");
3219
+ }).pipe(page.within("read"))).pipe(page.span("Page.read"), page.owned);
3220
+ const act = (script, options) => Effect.suspend(() => {
3221
+ if (!Number.isSafeInteger(options.document) || options.document < 0) return refuse("act", "document must be a nonnegative safe integer");
3222
+ const same = Effect.suspend(() => document() === options.document && (options.connection === void 0 || options.connection === page.connection) ? Effect.void : changed("act"));
3223
+ const prepare = same.pipe(Effect.as({
3224
+ request: new InputRequest({
3225
+ page: page.id,
3226
+ url: redact(page.playwright.url()),
3227
+ title: "",
3228
+ action: {
3229
+ _tag: "Act",
3230
+ document: options.document
3231
+ },
3232
+ facts: ["scripted", "opaque"],
3233
+ context: {}
3234
+ }),
3235
+ validate: same.pipe(Effect.as({
3236
+ contextId: 0,
3237
+ check: () => same
3238
+ }))
3239
+ }));
3240
+ return input.perform({
3241
+ _tag: "Act",
3242
+ document: options.document
3243
+ }, {}, page.settings.actionTimeout, () => prepare, (marks) => same.pipe(Effect.andThen(marks.sent), Effect.andThen(evaluate("act", script, options.arg).pipe(Effect.mapError(scriptFailure))), Effect.flatMap((value) => same.pipe(Effect.andThen(decode("act", options.result, value))))));
3244
+ });
3245
+ return {
3246
+ read,
3247
+ act
3248
+ };
3249
+ };
3250
+ //#endregion
3251
+ //#region src/internal/page/viewport.ts
3252
+ /**
3253
+ * The viewport's size in CSS pixels. Playwright knows it only for a context it created; over CDP it
3254
+ * reports none, so the page answers, and so does a picture taken at one device pixel per CSS
3255
+ * pixel. Pointer bounds, page scrolls, crops, capture size and frame reuse all read this one
3256
+ * source; the latest answer serves checks that cannot wait for the page.
3257
+ */
3258
+ const make$4 = (page, bridge) => {
3259
+ const { playwright } = page;
3260
+ let measuredViewport = null;
3261
+ const knownViewport = () => playwright.viewportSize() ?? measuredViewport;
3262
+ const viewportFor = (operation) => Effect.suspend(() => {
3263
+ const known = playwright.viewportSize();
3264
+ return known === null ? bridge.evaluate(operation, scriptCall("viewport")).pipe(Effect.flatMap(decodeWith(operation, ViewportResultSchema)), Effect.tap((measured) => Effect.sync(() => {
3265
+ measuredViewport = measured;
3266
+ }))) : Effect.succeed(known);
3267
+ });
3268
+ /** The size of an unscaled picture of the whole viewport, which is the viewport's own. */
3269
+ const remember = (size) => {
3270
+ measuredViewport = {
3271
+ width: size.width,
3272
+ height: size.height
3273
+ };
3274
+ };
3275
+ return {
3276
+ knownViewport,
3277
+ viewportFor,
3278
+ remember
3279
+ };
3280
+ };
3281
+ //#endregion
3282
+ //#region src/internal/page/page.ts
3283
+ /**
3284
+ * The page implementation behind `Page.Page`. `Browser` constructs pages and owns the state they
3285
+ * share (the clock mapping and event publication), so construction stays internal. A page is
3286
+ * assembled here from its domains: the script bridge, pictures, reading, its timeline, input and
3287
+ * navigation.
3288
+ * Features use the same documented Page contract as consumers.
3289
+ */
3290
+ const make$3 = Effect.fnUntraced(function* (options) {
3291
+ const page = make$25(options, yield* Effect.scope);
3292
+ const { id, playwright, native, owned, within, lane, span } = page;
3293
+ const bridge = yield* make$22(page);
3294
+ const viewport = make$4(page, bridge);
3295
+ const input = make$14(page, bridge, viewport);
3296
+ const pictures = yield* make$11(page, bridge, viewport);
3297
+ const reading = yield* make$10(page, bridge);
3298
+ const navigation = make$6(page, input.perform, input.preparePolicy);
3299
+ const { capture } = pictures;
3300
+ const changes = make$8(page, bridge, pictures.estimate);
3301
+ const titles = lane.shared("title", true);
3302
+ const viewports = lane.shared("viewport", true);
3303
+ const state = Effect.map(capture.latest, (latest) => {
3304
+ const { document, url } = bridge.frameTag();
3305
+ const committedAt = page.activity.documentAt;
3306
+ return new State({
3307
+ page: id,
3308
+ connection: page.connection,
3309
+ at: page.now(),
3310
+ url,
3311
+ document,
3312
+ committedAt: Number.isFinite(committedAt) ? committedAt : void 0,
3313
+ load: bridge.loaded(),
3314
+ frame: Option.getOrUndefined(latest),
3315
+ text: reading.viewedSince(committedAt)
3316
+ });
3317
+ });
3318
+ const current = (frame) => capture.current(frame) && bridge.frameTag().document === frame.document && frame.hostTime - frame.timing.uncertaintyMillis > page.activity.documentAt;
3319
+ const afterInput = (effect) => lane.read("inputEnded", page.settings.navigationTimeout)(Effect.andThen(input.perform.idle, effect)).pipe(within("inputEnded", page.settings.navigationTimeout), owned);
3320
+ const confirm = (frame) => native("shown", () => page.protocol.send("Page.getFrameTree")).pipe(Effect.flatMap(() => capture.confirm(frame)), Effect.map((confirmed) => confirmed && current(frame)), within("shown", "2 seconds"), owned);
3321
+ const perform = checked((action) => execute({
3322
+ ...input,
3323
+ ...navigation
3324
+ }, action));
3325
+ return {
3326
+ ...make$5(page, bridge, input),
3327
+ ...methods(perform),
3328
+ perform,
3329
+ clock: page.clock,
3330
+ afterInput,
3331
+ until: reading.until,
3332
+ capture: (options) => capture.open(options).pipe(Effect.map((lease) => ({
3333
+ ...lease,
3334
+ isCurrent: current,
3335
+ confirm,
3336
+ sync: capture.sync,
3337
+ stats: pictures.captureStats
3338
+ }))),
3339
+ id,
3340
+ url: Effect.sync(() => redact(playwright.url())),
3341
+ title: titles("", navigation.title.pipe(within("title"))).pipe(span("Page.title"), owned),
3342
+ bringToFront: native("bringToFront", () => playwright.bringToFront()),
3343
+ close: native("close", () => playwright.close()),
3344
+ snapshot: reading.snapshot,
3345
+ screenshot: pictures.screenshot,
3346
+ frame: pictures.frame,
3347
+ zoom: pictures.zoom,
3348
+ viewport: viewports("", viewport.viewportFor("viewport").pipe(within("viewport"))).pipe(span("Page.viewport"), owned),
3349
+ find: reading.find,
3350
+ text: reading.text,
3351
+ changes,
3352
+ window: make$7(page, changes, capture.recent),
3353
+ state,
3354
+ ready: make$9(page, bridge),
3355
+ screencast: capture.stream,
3356
+ captureStats: pictures.captureStats,
3357
+ recentFrames: capture.recent,
3358
+ recentEvents: options.recentEvents
3359
+ };
3360
+ });
3361
+ //#endregion
3362
+ //#region src/internal/page/request-owner.ts
3363
+ /** Proves a paused request's context before the connection's policy may see it. */
3364
+ const Tree = Schema.Struct({
3365
+ frame: Schema.Struct({ id: Schema.String }),
3366
+ childFrames: Schema.optional(Schema.Array(Schema.suspend(() => Tree)))
3367
+ });
3368
+ const FrameTree = Schema.Struct({ frameTree: Tree });
3369
+ const Reply = Schema.fromJsonString(Schema.Struct({
3370
+ id: Schema.optional(Schema.Finite),
3371
+ result: Schema.optional(Schema.Unknown),
3372
+ error: Schema.optional(Schema.Struct({ message: Schema.String }))
3373
+ }));
3374
+ const contains = (tree, frame) => tree.frame.id === frame || tree.childFrames?.some((child) => contains(child, frame)) === true;
3375
+ const queryTarget = async (chrome, target, method, params, signal, session, hooks) => {
3376
+ const { sessionId } = await chrome.send("Target.attachToTarget", {
3377
+ targetId: target,
3378
+ flatten: false
3379
+ });
3380
+ if (signal.aborted) {
3381
+ await chrome.send("Target.detachFromTarget", { sessionId });
3382
+ throw new Error("request ownership query was interrupted");
3383
+ }
3384
+ const response = Promise.withResolvers();
3385
+ const interruption = Promise.withResolvers();
3386
+ const receive = (event) => {
3387
+ if (event.sessionId !== sessionId) return;
3388
+ const reply = Schema.decodeOption(Reply)(event.message);
3389
+ if (Option.isNone(reply)) {
3390
+ response.reject(/* @__PURE__ */ new Error("request ownership query received an invalid response"));
3391
+ return;
3392
+ }
3393
+ if (reply.value.id !== 1) return;
3394
+ if (reply.value.error !== void 0) response.reject(new Error(reply.value.error.message));
3395
+ else response.resolve(reply.value.result);
3396
+ };
3397
+ const detached = (event) => {
3398
+ if (event.sessionId === sessionId) interruption.reject(/* @__PURE__ */ new Error("request ownership target detached"));
3399
+ };
3400
+ const aborted = () => interruption.reject(/* @__PURE__ */ new Error("request ownership query was interrupted"));
3401
+ chrome.on("Target.receivedMessageFromTarget", receive);
3402
+ chrome.on("Target.detachedFromTarget", detached);
3403
+ signal.addEventListener("abort", aborted, { once: true });
3404
+ try {
3405
+ const send = () => {
3406
+ chrome.send("Target.sendMessageToTarget", {
3407
+ sessionId,
3408
+ message: JSON.stringify({
3409
+ id: 1,
3410
+ method,
3411
+ params
3412
+ })
3413
+ }).catch(response.reject);
3414
+ return response.promise;
3415
+ };
3416
+ const query = hooks.query;
3417
+ return await Promise.race([query === void 0 ? send() : query(session, method, send), interruption.promise]);
3418
+ } finally {
3419
+ chrome.off("Target.receivedMessageFromTarget", receive);
3420
+ chrome.off("Target.detachedFromTarget", detached);
3421
+ signal.removeEventListener("abort", aborted);
3422
+ await chrome.send("Target.detachFromTarget", { sessionId });
3423
+ }
3424
+ };
3425
+ const make$2 = Effect.fnUntraced(function* (context, chrome, native, closing) {
3426
+ const clock = yield* Clock.Clock;
3427
+ const hooks = yield* Current$1;
3428
+ const protocol = yield* Effect.context();
3429
+ const owned = yield* native(async (signal) => {
3430
+ const existing = context.pages()[0];
3431
+ const page = existing ?? await context.newPage();
3432
+ let cdp;
3433
+ try {
3434
+ if (signal.aborted) throw new Error("request ownership setup was interrupted");
3435
+ cdp = await Effect.runPromiseWith(protocol)(openSession(async () => {
3436
+ if (signal.aborted) throw new Error("request ownership setup was interrupted");
3437
+ const created = await context.newCDPSession(page);
3438
+ if (signal.aborted) {
3439
+ await created.detach();
3440
+ throw new Error("request ownership setup was interrupted");
3441
+ }
3442
+ cdp = created;
3443
+ return created;
3444
+ }, page, "page"), { signal });
3445
+ if (signal.aborted) throw new Error("request ownership setup was interrupted");
3446
+ const { targetInfo } = await cdp.send("Target.getTargetInfo");
3447
+ if (targetInfo.browserContextId === void 0) throw new Error("request ownership requires an identifiable browser context");
3448
+ return targetInfo.browserContextId;
3449
+ } finally {
3450
+ try {
3451
+ if (cdp !== void 0) await cdp.detach();
3452
+ } finally {
3453
+ if (existing === void 0) await page.close();
3454
+ }
3455
+ }
3456
+ });
3457
+ const refresh = native(() => chrome.send("Target.getTargets")).pipe(Effect.flatMap(({ targetInfos }) => {
3458
+ const targets = targetInfos.filter((target) => target.browserContextId === owned);
3459
+ if (targets.some((target) => target.type === "shared_worker")) return undispatched("requests", new InvalidRequest({ detail: "request policies cannot protect preexisting shared workers" }));
3460
+ return Effect.forEach(targets.filter((target) => [
3461
+ "page",
3462
+ "iframe",
3463
+ "service_worker"
3464
+ ].includes(target.type)), (target) => native((signal) => queryTarget(chrome, target.targetId, "Fetch.enable", { patterns: [] }, signal, {
3465
+ channel: "browser",
3466
+ page: target.targetId,
3467
+ clock
3468
+ }, hooks)), {
3469
+ concurrency: 8,
3470
+ discard: true
3471
+ });
3472
+ }));
3473
+ const ownership = yield* Cache.makeWith((frame) => native(async (signal) => {
3474
+ const direct = await chrome.send("Target.getTargetInfo", { targetId: frame }).catch((cause) => {
3475
+ if (cause instanceof Error && /No target with given id found/.test(cause.message)) return void 0;
3476
+ throw cause;
3477
+ });
3478
+ if (signal.aborted) throw new Error("request ownership query was interrupted");
3479
+ if (direct?.targetInfo.browserContextId !== void 0) return direct.targetInfo.browserContextId === owned ? { page: direct.targetInfo.type === "page" ? direct.targetInfo.targetId : void 0 } : false;
3480
+ const { targetInfos } = await chrome.send("Target.getTargets");
3481
+ for (const target of targetInfos) {
3482
+ if (signal.aborted) throw new Error("request ownership query was interrupted");
3483
+ if (target.type !== "page" && target.type !== "iframe") continue;
3484
+ const result = await queryTarget(chrome, target.targetId, "Page.getFrameTree", {}, signal, {
3485
+ channel: "browser",
3486
+ page: target.targetId,
3487
+ clock
3488
+ }, hooks);
3489
+ const { frameTree } = Schema.decodeUnknownSync(FrameTree)(result);
3490
+ if (contains(frameTree, frame)) {
3491
+ if (target.browserContextId === void 0) throw new Error("request frame has no browser context evidence");
3492
+ return target.browserContextId === owned ? { page: target.type === "page" ? frameTree.frame.id : void 0 } : false;
3493
+ }
3494
+ }
3495
+ throw new Error("request frame ownership could not be established");
3496
+ }, closing()), {
3497
+ capacity: 1024,
3498
+ timeToLive: (exit, frame) => Exit.isSuccess(exit) && (exit.value === false || exit.value.page === void 0 || exit.value.page === frame) ? Duration.infinity : Duration.zero
3499
+ });
3500
+ const owns = (frame) => frame === void 0 ? Effect.fail(undispatched("requests", new InvalidRequest({ detail: "request has no frame ownership evidence" }))) : Cache.get(ownership, frame);
3501
+ return {
3502
+ owns,
3503
+ refresh
3504
+ };
3505
+ });
3506
+ //#endregion
3507
+ //#region src/internal/page/requests.ts
3508
+ /** Context-owned request decisions over bounded CDP interception, including every redirect hop. */
3509
+ const responseOf = (decision) => Number.isInteger(decision.status) && decision.status >= 100 && decision.status <= 599 && new TextEncoder().encode(decision.body).byteLength <= 8e6 && !/[\r\n]/.test(decision.contentType) && Object.entries(decision.headers ?? {}).every(([name, value]) => name !== "" && !/[\r\n]/.test(name + value)) ? {
3510
+ responseCode: decision.status,
3511
+ responseHeaders: [{
3512
+ name: "Content-Type",
3513
+ value: decision.contentType
3514
+ }, ...Object.entries(decision.headers ?? {}).map(([name, value]) => ({
3515
+ name,
3516
+ value
3517
+ }))],
3518
+ body: Base64.encode(decision.body)
3519
+ } : void 0;
3520
+ const bounded = (clock, duration) => (run, closing = false) => {
3521
+ const bound = closing ? Duration.min(duration, Duration.seconds(1)) : duration;
3522
+ return Effect.tryPromise({
3523
+ try: run,
3524
+ catch: (cause) => undispatched("requests", reasonOf(cause, void 0, "connection"))
3525
+ }).pipe(Effect.timeoutOrElse({
3526
+ duration: bound,
3527
+ orElse: () => Effect.fail(undispatched("requests", new Timeout({ millis: Duration.toMillis(bound) })))
3528
+ }), Effect.provideService(Clock.Clock, clock));
3529
+ };
3530
+ const bodyOf = (request) => {
3531
+ if (!(request.hasPostData === true || request.postData !== void 0 || (request.postDataEntries?.length ?? 0) > 0 || Object.entries(request.headers ?? {}).some(([name, value]) => name.toLowerCase() === "content-length" && Number(value) > 0))) return null;
3532
+ if (request.postData === void 0 || request.postDataEntries === void 0) return void 0;
3533
+ const chunks = [];
3534
+ for (const entry of request.postDataEntries) {
3535
+ if (entry.bytes === void 0) return void 0;
3536
+ const decoded = Base64.decode(entry.bytes);
3537
+ if (Result.isFailure(decoded)) return void 0;
3538
+ chunks.push(decoded.success);
3539
+ }
3540
+ const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));
3541
+ let offset = 0;
3542
+ for (const chunk of chunks) {
3543
+ bytes.set(chunk, offset);
3544
+ offset += chunk.length;
3545
+ }
3546
+ try {
3547
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
3548
+ return text === request.postData ? text : void 0;
3549
+ } catch {
3550
+ return;
3551
+ }
3552
+ };
3553
+ const deciding = (policy, clock, duration, closing, lost, deny, reply) => (paused) => Effect.suspend(() => {
3554
+ const body = bodyOf(paused.request);
3555
+ if (body === void 0) return Effect.succeed({
3556
+ _tag: "Refused",
3557
+ reason: "request body was not fully observable as UTF-8 text"
3558
+ });
3559
+ return policy.decide({
3560
+ url: paused.request.url,
3561
+ method: paused.request.method,
3562
+ body
3563
+ });
3564
+ }).pipe(Effect.timeoutOrElse({
3565
+ duration,
3566
+ orElse: () => Effect.fail(undispatched("requests", new Timeout({ millis: Duration.toMillis(duration) })))
3567
+ }), Effect.catchCause((cause) => {
3568
+ if (closing() && Cause.hasInterrupts(cause)) return Effect.failCause(cause);
3569
+ const error = Option.getOrElse(Cause.findErrorOption(cause), () => undispatched("requests", new Threw({})));
3570
+ lost();
3571
+ return deny(paused, error.reason._tag === "Timeout" ? "request decision timed out" : `request decision failed: ${error.reason._tag}`, error).pipe(Effect.andThen(Effect.fail(error)));
3572
+ }), Effect.flatMap((decision) => {
3573
+ if (decision._tag === "Allowed") return reply(paused, "Fetch.continueRequest", {}, true);
3574
+ if (decision._tag === "Refused") return deny(paused, decision.reason);
3575
+ const response = responseOf(decision);
3576
+ return response === void 0 ? deny(paused, "request fulfillment is invalid or exceeds 8MB") : reply(paused, "Fetch.fulfillRequest", response, true);
3577
+ }), Effect.provideService(Clock.Clock, clock));
3578
+ const retire = (owner, held, reply) => Effect.forEach(held.values(), (paused) => owner.owns(paused.frameId).pipe(Effect.matchEffect({
3579
+ onFailure: () => reply(paused, "Fetch.failRequest", { errorReason: "BlockedByClient" }),
3580
+ onSuccess: (owned) => reply(paused, owned ? "Fetch.failRequest" : "Fetch.continueRequest", owned ? { errorReason: "BlockedByClient" } : {})
3581
+ })), {
3582
+ concurrency: 8,
3583
+ discard: true
3584
+ });
3585
+ const install = Effect.fnUntraced(function* (context, policy, clock, publish, now, lost, unavailable) {
3586
+ const browser = context.browser();
3587
+ if (browser === null) return yield* refuse("requests", "this provider cannot intercept browser requests");
3588
+ const bound = Duration.fromInput(policy.timeout ?? "5 seconds");
3589
+ if (bound._tag === "None" || !Duration.isFinite(bound.value) || !Duration.isPositive(bound.value) || policy.patterns.length === 0) return yield* refuse("requests", "request patterns and a finite positive timeout are required");
3590
+ const native = bounded(clock, bound.value);
3591
+ const protocol = yield* Effect.context();
3592
+ const chrome = yield* Effect.acquireRelease(native((signal) => Effect.runPromiseWith(protocol)(openSession(() => browser.newBrowserCDPSession(), void 0, "browser"), { signal }).then(async (session) => {
3593
+ if (signal.aborted) await session.detach().catch(() => void 0);
3594
+ return session;
3595
+ })), (chrome) => native(() => chrome.detach(), true).pipe(Effect.orDie));
3596
+ let closing = false;
3597
+ const owner = yield* make$2(context, chrome, native, () => closing);
3598
+ const held = /* @__PURE__ */ new Map();
3599
+ const pending = yield* Queue.unbounded();
3600
+ const workers = yield* Scope.make();
3601
+ const record = (paused, reason, failure) => publish(new RequestRefused({
3602
+ at: now(),
3603
+ page: paused.page,
3604
+ method: paused.request.method,
3605
+ url: redact(paused.request.url),
3606
+ reason: redactWithin(reason).slice(0, 2e3),
3607
+ ...failure === void 0 ? {} : { failure: {
3608
+ reason: failure.reason._tag,
3609
+ ...failure.reason._tag === "Timeout" ? { timeoutMillis: failure.reason.millis } : {}
3610
+ } }
3611
+ }));
3612
+ const reply = (paused, method, params = {}, authorize = false) => native(async () => {
3613
+ const ended = authorize && (closing || unavailable());
3614
+ if (ended) record(paused, "request authority has ended");
3615
+ try {
3616
+ await chrome.send(ended ? "Fetch.failRequest" : method, {
3617
+ requestId: paused.requestId,
3618
+ ...ended ? { errorReason: "BlockedByClient" } : params
3619
+ });
3620
+ } catch (cause) {
3621
+ if (!(cause instanceof Error && /Invalid InterceptionId\.?$/.test(cause.message))) throw cause;
3622
+ }
3623
+ held.delete(paused.requestId);
3624
+ }, closing).pipe(Effect.uninterruptible);
3625
+ const deny = (paused, reason, failure) => Effect.sync(() => record(paused, reason, failure)).pipe(Effect.andThen(reply(paused, "Fetch.failRequest", { errorReason: "BlockedByClient" })));
3626
+ const decide = deciding(policy, clock, bound.value, () => closing, lost, deny, reply);
3627
+ const handle = (paused) => owner.owns(paused.frameId).pipe(Effect.matchEffect({
3628
+ onFailure: () => deny(paused, "request ownership could not be established"),
3629
+ onSuccess: (owned) => !owned ? reply(paused, "Fetch.continueRequest") : closing || unavailable() ? deny({
3630
+ ...paused,
3631
+ page: owned.page
3632
+ }, "request authority has ended") : decide({
3633
+ ...paused,
3634
+ page: owned.page
3635
+ })
3636
+ }), Effect.catchCauseIf((cause) => !Cause.hasInterrupts(cause), (cause) => {
3637
+ const error = Option.getOrElse(Cause.findErrorOption(cause), () => undispatched("requests", new Threw({})));
3638
+ return (unavailable() ? Effect.void : Effect.sync(() => record(paused, "request control failed", error))).pipe(Effect.andThen(Effect.sync(lost)));
3639
+ }));
3640
+ const onRequest = (paused) => {
3641
+ held.set(paused.requestId, paused);
3642
+ Queue.offerUnsafe(pending, paused);
3643
+ };
3644
+ chrome.on("Fetch.requestPaused", onRequest);
3645
+ yield* Effect.addFinalizer(() => Effect.sync(() => {
3646
+ closing = true;
3647
+ }).pipe(Effect.andThen(native(() => chrome.send("Fetch.enable", { patterns: [] }), true)), Effect.ensuring(Scope.close(workers, Exit.void)), Effect.andThen(Effect.suspend(() => retire(owner, held, reply))), Effect.ensuring(Effect.sync(() => chrome.off("Fetch.requestPaused", onRequest))), Effect.orDie));
3648
+ for (let index = 0; index < 8; index++) yield* Queue.take(pending).pipe(Effect.flatMap(handle), Effect.forever, Effect.forkScoped, Scope.provide(workers));
3649
+ yield* native(() => chrome.send("Fetch.enable", { patterns: policy.patterns.map((urlPattern) => ({ urlPattern })) }));
3650
+ yield* owner.refresh;
3651
+ });
3652
+ //#endregion
3653
+ //#region src/internal/timeline/events.ts
3654
+ /**
3655
+ * The browser's bounded event history and replay cursors. Readers share the same records and
3656
+ * wakeup generation, so a delayed reader cannot block input or retain an unbounded private queue.
3657
+ */
3658
+ /** The owning Browser validates capacity and closes this timeline with its scope. */
3659
+ const make$1 = (capacity) => {
3660
+ const records = Array.from({ length: capacity });
3661
+ let start = 0;
3662
+ let size = 0;
3663
+ let sequence = 0;
3664
+ let closed = false;
3665
+ let changed = Deferred.makeUnsafe();
3666
+ const wake = () => {
3667
+ const previous = changed;
3668
+ changed = Deferred.makeUnsafe();
3669
+ Deferred.doneUnsafe(previous, Effect.void);
3670
+ };
3671
+ const publish = (event) => {
3672
+ if (closed) return sequence;
3673
+ sequence += 1;
3674
+ const recorded = new RecordedEvent({
3675
+ sequence,
3676
+ event
3677
+ });
3678
+ records[(start + size) % capacity] = recorded;
3679
+ if (size < capacity) size++;
3680
+ else start = (start + 1) % capacity;
3681
+ wake();
3682
+ return sequence;
3683
+ };
3684
+ const stream = (after) => Stream.unwrap(Effect.sync(() => {
3685
+ let cursor = after ?? sequence;
3686
+ 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"));
3687
+ return Stream.fromEffectRepeat(Effect.gen(function* () {
3688
+ while (true) {
3689
+ const oldest = sequence - size + 1;
3690
+ if (cursor < oldest - 1) return yield* undispatched("events", new EventHistoryExpired({
3691
+ after: cursor,
3692
+ oldest,
3693
+ latest: sequence
3694
+ }));
3695
+ const next = cursor < sequence ? records[(start + cursor - oldest + 1) % capacity] : void 0;
3696
+ if (next !== void 0) {
3697
+ cursor = next.sequence;
3698
+ return next;
3699
+ }
3700
+ if (closed) return yield* Cause.done();
3701
+ const waiting = changed;
3702
+ yield* Deferred.await(waiting);
3703
+ }
3704
+ }));
3705
+ }));
3706
+ return {
3707
+ publish,
3708
+ sequence: () => sequence,
3709
+ recent: Effect.sync(() => Array.from({ length: size }, (_, index) => records[(start + index) % capacity]).filter((record) => record !== void 0)),
3710
+ stream,
3711
+ close: Effect.sync(() => {
3712
+ if (closed) return;
3713
+ closed = true;
3714
+ wake();
3715
+ })
3716
+ };
3717
+ };
3718
+ //#endregion
3719
+ //#region src/Browser.ts
3720
+ /**
3721
+ * A live browser: its pages and what happens in it.
3722
+ *
3723
+ * `Browser` is a service with one implementation, built by a provider over a Playwright browser
3724
+ * context: `Chromium` launches one locally, `Cdp` connects to any DevTools endpoint and
3725
+ * `effect-browserbase` allocates a hosted one. Code written against `Browser` runs on all three.
3726
+ * A page is named by its CDP target id, so a new connection to the same browser finds it again.
3727
+ *
3728
+ * @since 0.3.0
3729
+ */
3730
+ var Browser_exports = /* @__PURE__ */ __exportAll({
3731
+ Browser: () => Browser,
3732
+ Suspension: () => Suspension,
3733
+ make: () => make
3734
+ });
3735
+ /** When admitted input finished; events after `since` describe the handoff interval. */
3736
+ var Suspension = class extends Schema.Class("effect-browser/Suspension")({
3737
+ since: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
3738
+ at: Schema.Finite
3739
+ }) {};
3740
+ var Browser = class extends Context.Service()("effect-browser/Browser") {};
3741
+ /** The settings every page shares, and how many events the browser keeps, from its options. */
3742
+ const settingsOf = Effect.fnUntraced(function* (options) {
3743
+ const invalid = (detail) => undispatched("make", new InvalidRequest({ detail }));
3744
+ const bound = (name, input, fallback) => {
3745
+ const decoded = Duration.fromInput(input ?? fallback);
3746
+ return Option.isSome(decoded) && Number.isFinite(Duration.toMillis(decoded.value)) && Duration.isPositive(decoded.value) ? Effect.succeed(decoded.value) : Effect.fail(invalid(`${name} must be finite and greater than zero`));
3747
+ };
3748
+ const settings = {
3749
+ actionTimeout: yield* bound("actionTimeout", options.actionTimeout, Duration.seconds(10)),
3750
+ navigationTimeout: yield* bound("navigationTimeout", options.navigationTimeout, Duration.seconds(30)),
3751
+ frameHistory: yield* bound("frameHistory", options.frameHistory, Duration.seconds(5)),
3752
+ guard: options.guard,
3753
+ policyTimeout: yield* bound("policyTimeout", options.policyTimeout, Duration.minutes(5))
3754
+ };
3755
+ 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");
3756
+ const eventHistory = options.eventHistory ?? 4096;
3757
+ const { maxPages } = options;
3758
+ if (!Number.isSafeInteger(eventHistory) || eventHistory < 1) return yield* invalid("eventHistory must be a positive safe integer");
3759
+ if (maxPages !== void 0 && (!Number.isSafeInteger(maxPages) || maxPages < 1)) return yield* invalid("maxPages must be a positive safe integer");
3760
+ return {
3761
+ settings,
3762
+ eventHistory,
3763
+ maxPages
3764
+ };
3765
+ });
3766
+ /**
3767
+ * A provider that ends a session at `expiresAt` by its own clock can cut the connection a little
3768
+ * before this host's clock gets there.
3769
+ */
3770
+ const endMargin = Duration.seconds(5);
3771
+ /**
3772
+ * The browser's loss, once: its context closing from the other side, at or after the session's
3773
+ * end or before it, or `lose`, as the owner's scope releases it. Playwright leaves the calls in
3774
+ * flight on the library's own sessions unanswered when the connection drops, so `untilLost` fails
3775
+ * each with the browser, as a closed page's call fails.
3776
+ */
3777
+ const watchLoss = Effect.fnUntraced(function* (context, expiresAt, clock, disconnected) {
3778
+ let lostBy;
3779
+ const lost = yield* Deferred.make();
3780
+ const inFlight = /* @__PURE__ */ new Set();
3781
+ const gone = () => /* @__PURE__ */ new Error("Target page, context or browser has been closed");
3782
+ const lose = (cause) => {
3783
+ if (lostBy !== void 0) return;
3784
+ lostBy = cause;
3785
+ for (const reject of inFlight) reject(gone());
3786
+ disconnected(cause);
3787
+ Deferred.doneUnsafe(lost, Exit.succeed(cause));
3788
+ };
3789
+ const untilLost = (reply) => {
3790
+ if (lostBy !== void 0) {
3791
+ reply.catch(() => void 0);
3792
+ return Promise.reject(gone());
3793
+ }
3794
+ return new Promise((resolve, reject) => {
3795
+ inFlight.add(reject);
3796
+ reply.then(resolve, reject).finally(() => inFlight.delete(reject));
3797
+ });
3798
+ };
3799
+ const ended = () => expiresAt !== void 0 && clock.currentTimeMillisUnsafe() >= DateTime.toEpochMillis(expiresAt) - Duration.toMillis(endMargin);
3800
+ const onClose = () => lose(ended() ? "session" : "connection");
3801
+ context.on("close", onClose);
3802
+ yield* Effect.addFinalizer(() => Effect.sync(() => context.off("close", onClose)));
3803
+ if (context.browser()?.isConnected() === false) onClose();
3804
+ const native = (operation, run) => Effect.suspend(() => lostBy === void 0 ? call(operation, () => untilLost(run()), () => lostBy ?? "page") : failWith(operation, new Closed({ cause: lostBy })));
3805
+ return {
3806
+ lostBy: () => lostBy,
3807
+ lost: Deferred.await(lost),
3808
+ lose,
3809
+ untilLost,
3810
+ native
3811
+ };
3812
+ });
3813
+ /**
3814
+ * Register each page the site opens, such as a popup, as Playwright reports it, for as long as the
3815
+ * scope is open. One that could not be tracked is published, unless it closed as it opened.
3816
+ */
3817
+ const followOpened = Effect.fnUntraced(function* (context, registrations, registerPage, publish, now) {
3818
+ const registrationSlots = Semaphore.makeUnsafe(8);
3819
+ const runRegistration = yield* FiberSet.makeRuntime();
3820
+ const register = (playwright) => {
3821
+ const known = registrations.get(playwright);
3822
+ if (known !== void 0) return Deferred.await(known);
3823
+ const done = Deferred.makeUnsafe();
3824
+ registrations.set(playwright, done);
3825
+ runRegistration(registrationSlots.withPermits(1)(registerPage(playwright)).pipe(Effect.onExit((exit) => Deferred.done(done, exit)), Effect.catch((error) => Effect.sync(() => {
3826
+ if (!playwright.isClosed()) publish(new PageUntracked({
3827
+ at: now(),
3828
+ url: redact(playwright.url()),
3829
+ detail: error.message
3830
+ }));
3831
+ }))));
3832
+ return Deferred.await(done);
3833
+ };
3834
+ context.on("page", register);
3835
+ yield* Effect.addFinalizer(() => Effect.sync(() => context.off("page", register)));
3836
+ return register;
3837
+ });
3838
+ /** Release something native, on the owner's clock, giving up after a second: cleanup only. */
3839
+ const releaseNative = (clock) => (run) => Effect.tryPromise(run).pipe(Effect.interruptible, Effect.timeoutOrElse({
3840
+ duration: Duration.seconds(1),
3841
+ orElse: () => Effect.void
3842
+ }), Effect.provideService(Clock.Clock, clock), Effect.ignore);
3843
+ /** A page's own events among the browser's retained ones, and the openings of tabs it opened. */
3844
+ const eventsOf = (recent, page) => Effect.map(recent, (records) => records.flatMap(({ event }) => "page" in event && event.page === page || event._tag === "PageOpened" && event.opener === page ? [event] : []));
3845
+ /** A script as its documents run it: everywhere, or as a block where its `match` allows. */
3846
+ const scoped = ({ match, source }) => match === void 0 ? source : `if (${String(match)}.test(location.href)) {\n${source}\n}`;
3847
+ /**
3848
+ * At most `maxPages` open pages, those a site opened included, which are never refused: an open
3849
+ * past it waits for one to close, within `wait` on the owner's clock, then fails `Limit`, or fails
3850
+ * at once under `FailFast`. An open counts until its page is tracked.
3851
+ */
3852
+ const pageBudget = (maxPages, tracked, wait, clock) => {
3853
+ let opening = 0;
3854
+ let roomMade = Deferred.makeUnsafe();
3855
+ const makeRoom = () => {
3856
+ Deferred.doneUnsafe(roomMade, Exit.void);
3857
+ roomMade = Deferred.makeUnsafe();
3858
+ };
3859
+ const full = (limit) => tracked() + opening >= limit;
3860
+ const room = (limit) => Effect.gen(function* () {
3861
+ const refused = undispatched("newPage", new Limit({ maxPages: limit }));
3862
+ if ((yield* FailFast) && full(limit)) return yield* refused;
3863
+ yield* Effect.gen(function* () {
3864
+ while (full(limit)) yield* Deferred.await(roomMade);
3865
+ opening += 1;
3866
+ }).pipe(Effect.timeoutOrElse({
3867
+ duration: wait,
3868
+ orElse: () => Effect.fail(refused)
3869
+ }), Effect.provideService(Clock.Clock, clock));
3870
+ });
3871
+ const open = (opened) => maxPages === void 0 ? opened : Effect.uninterruptibleMask((restore) => restore(room(maxPages)).pipe(Effect.andThen(restore(opened).pipe(Effect.ensuring(Effect.sync(() => {
3872
+ opening -= 1;
3873
+ makeRoom();
3874
+ }))))));
3875
+ return {
3876
+ makeRoom,
3877
+ open
3878
+ };
3879
+ };
3880
+ /** A call sent now and awaited later, by whatever needs its answer. */
3881
+ const sentNow = (sent) => {
3882
+ sent.catch(() => void 0);
3883
+ return sent;
3884
+ };
3885
+ /** Close tab resources after publishing their close; a browser loss speaks for all its tabs. */
3886
+ const closures = (lostBy, publish, now) => Effect.gen(function* () {
3887
+ const closing = yield* Queue.unbounded();
3888
+ yield* Queue.take(closing).pipe(Effect.tap(({ page, cause }) => Effect.sync(() => {
3889
+ if (lostBy() === void 0) publish(new PageClosed({
3890
+ at: now(),
3891
+ page,
3892
+ cause
3893
+ }));
3894
+ })), Effect.flatMap(({ scope }) => Scope.close(scope, Exit.void)), Effect.forever, Effect.forkScoped);
3895
+ return closing;
3896
+ });
3897
+ /** Cookie checks disclose presence only, within the browser's native deadline. */
3898
+ const cookieQuery = (context, native, timeout, clock) => ({ name, url }) => native("hasCookie", () => context.cookies(url)).pipe(Effect.map((cookies) => cookies.some((cookie) => cookie.name === name)), Effect.timeoutOrElse({
3899
+ duration: timeout,
3900
+ orElse: () => failWith("hasCookie", new Timeout({ millis: Duration.toMillis(timeout) }))
3901
+ }), Effect.provideService(Clock.Clock, clock));
3902
+ /** Tab allocation shares its budget, registration and first-tab lock. */
3903
+ const tabs = (context, registry, budget, native, register, release, firstPageLock) => {
3904
+ const pages = Effect.sync(() => [...registry.values()]);
3905
+ const newPage = Effect.fn("Browser.newPage")(function* (url) {
3906
+ const page = yield* budget.open(native("newPage", () => context.newPage()).pipe(Effect.flatMap((playwright) => register(playwright).pipe(Effect.onError(() => release(() => playwright.close()))))));
3907
+ if (url !== void 0) yield* page.goto(url).pipe(Effect.onError(() => page.close.pipe(Effect.ignore)));
3908
+ return page;
3909
+ });
3910
+ return {
3911
+ pages,
3912
+ page: (id) => Effect.map(pages, (open) => Option.fromNullishOr(open.find((page) => page.id === id))),
3913
+ firstPage: firstPageLock.withPermits(1)(pages.pipe(Effect.map((open) => Option.fromNullishOr(open[0])), Effect.flatMap(Option.match({
3914
+ onNone: () => newPage(),
3915
+ onSome: Effect.succeed
3916
+ })))),
3917
+ newPage
3918
+ };
3919
+ };
3920
+ /** One connection owns clocks, loss, authority and its bounded timeline. */
3921
+ const runtime = Effect.fnUntraced(function* (context, expiresAt, options) {
3922
+ const clock = yield* Clock.Clock;
3923
+ const connection = yield* make$24;
3924
+ const protocol = yield* Current$1;
3925
+ const releasePort = protocol.browser?.(connection, context);
3926
+ yield* Effect.addFinalizer(() => Effect.sync(() => releasePort?.()));
3927
+ const now = () => monotonicMillis(clock);
3928
+ const { settings, eventHistory, maxPages } = yield* settingsOf(options);
3929
+ const mapping$1 = mapping(now);
3930
+ const timeline = make$1(eventHistory);
3931
+ yield* Effect.addFinalizer(() => timeline.close);
3932
+ const publish = timeline.publish;
3933
+ if (expiresAt !== void 0) publish(new SessionEnding({
3934
+ at: now(),
3935
+ expiresAt
3936
+ }));
3937
+ const { lostBy, lost, lose, untilLost, native } = yield* watchLoss(context, expiresAt, clock, (cause) => publish(new Disconnected({
3938
+ at: now(),
3939
+ cause
3940
+ })));
3941
+ if (options.requests !== void 0) yield* install(context, options.requests, clock, publish, now, () => lose("connection"), () => lostBy() !== void 0);
3942
+ return {
3943
+ clock,
3944
+ connection,
3945
+ protocol,
3946
+ now,
3947
+ settings,
3948
+ maxPages,
3949
+ mapping: mapping$1,
3950
+ timeline,
3951
+ publish,
3952
+ lostBy,
3953
+ lost,
3954
+ lose,
3955
+ untilLost,
3956
+ native,
3957
+ inputGate: make$27({
3958
+ now,
3959
+ sequence: timeline.sequence,
3960
+ closedBy: lostBy,
3961
+ lost,
3962
+ clock,
3963
+ drain: settings.navigationTimeout
3964
+ })
3965
+ };
3966
+ });
3967
+ /**
3968
+ * Build the service over a context the provider owns. The provider closes the context; this only
3969
+ * tracks its pages and events, for as long as the surrounding scope is open. Each page's protocol
3970
+ * session, capture and listeners end when that page closes or when the scope does, so a closed
3971
+ * tab retains nothing and the context keeps none of them afterwards.
3972
+ */
3973
+ const make = Effect.fn("Browser.make")(function* (context, info, options = {}) {
3974
+ const { clock, connection, protocol, now, settings, maxPages, mapping, timeline, publish, lostBy, lost, lose, untilLost, native, inputGate } = yield* runtime(context, info.expiresAt, options);
3975
+ const session = info.id ?? connection;
3976
+ const registry = /* @__PURE__ */ new Map();
3977
+ const registrations = /* @__PURE__ */ new WeakMap();
3978
+ const pagesScope = yield* Scope.fork(yield* Scope.Scope);
3979
+ const release = releaseNative(clock);
3980
+ const budget = pageBudget(maxPages, () => registry.size, settings.actionTimeout, clock);
3981
+ const closing = yield* closures(lostBy, publish, now);
3982
+ const registerPage = (playwright) => Effect.gen(function* () {
3983
+ if (playwright.isClosed()) return yield* failWith("newPage", new Failed({ detail: "the page closed as it opened" }));
3984
+ const viewport = options.viewport;
3985
+ if (viewport !== void 0) yield* native("viewport", () => playwright.setViewportSize(viewport));
3986
+ const scope = yield* Scope.fork(pagesScope);
3987
+ return yield* Effect.gen(function* () {
3988
+ let crashed = false;
3989
+ const closedBy = () => lostBy() ?? (crashed ? "crashed" : "page");
3990
+ const cdp = yield* openSession(() => context.newCDPSession(playwright), playwright).pipe(Effect.provideService(Current$1, protocol));
3991
+ yield* Effect.addFinalizer(() => release(() => cdp.detach()));
3992
+ const send = (method, params) => untilLost(cdp.send(method, params));
3993
+ const focusing = sentNow(send("Emulation.setFocusEmulationEnabled", { enabled: true }));
3994
+ const paging = sentNow(send("Page.enable"));
3995
+ const { targetInfo } = yield* native("newPage", () => send("Target.getTargetInfo"));
3996
+ const id = targetInfo.targetId;
3997
+ const page = yield* make$3({
3998
+ id,
3999
+ session,
4000
+ connection,
4001
+ url: targetInfo.url,
4002
+ playwright,
4003
+ cdp,
4004
+ nativePort: protocol.native,
4005
+ untilLost,
4006
+ settings,
4007
+ inputGate,
4008
+ clock,
4009
+ mapping,
4010
+ publish,
4011
+ recentEvents: eventsOf(timeline.recent, id),
4012
+ openings: yield* make$23(playwright, cdp, registrations, closedBy),
4013
+ focused: call("focus", () => focusing, closedBy).pipe(Effect.asVoid),
4014
+ paging: (operation) => call(operation, () => paging, closedBy).pipe(Effect.asVoid),
4015
+ closedBy,
4016
+ capture: info.capture
4017
+ }).pipe(Effect.provideService(Current$1, protocol));
4018
+ const close = () => {
4019
+ if (registry.get(playwright) !== page) return;
4020
+ registry.delete(playwright);
4021
+ registrations.delete(playwright);
4022
+ budget.makeRoom();
4023
+ Queue.offerUnsafe(closing, {
4024
+ scope,
4025
+ page: id,
4026
+ cause: crashed ? "crashed" : "page"
4027
+ });
4028
+ };
4029
+ const crash = () => {
4030
+ crashed = true;
4031
+ playwright.close().catch(() => void 0);
4032
+ };
4033
+ registry.set(playwright, page);
4034
+ publish(new PageOpened({
4035
+ at: now(),
4036
+ page: id,
4037
+ url: redact(targetInfo.url),
4038
+ opener: targetInfo.openerId
4039
+ }));
4040
+ yield* listen(playwright, id, publish, now, (accept) => native("dialog", () => send("Page.handleJavaScriptDialog", { accept })).pipe(Effect.asVoid, Effect.timeoutOrElse({
4041
+ duration: settings.actionTimeout,
4042
+ orElse: () => failWith("dialog", new Failed({ detail: "dialog answer timed out" }))
4043
+ }), Effect.provideService(Clock.Clock, clock)), {
4044
+ close,
4045
+ crash,
4046
+ failed: () => {
4047
+ playwright.close().catch(() => void 0);
4048
+ }
4049
+ });
4050
+ if (playwright.isClosed()) close();
4051
+ return page;
4052
+ }).pipe(Scope.provide(scope), Effect.onError(() => Scope.close(scope, Exit.void)));
4053
+ });
4054
+ for (const script of options.initScripts ?? []) yield* native("initScripts", () => context.addInitScript({ content: scoped(script) }));
4055
+ const register = yield* followOpened(context, registrations, registerPage, publish, now);
4056
+ for (const existing of context.pages()) yield* register(existing);
4057
+ yield* Effect.addFinalizer(() => Effect.sync(() => lose("released")));
4058
+ const service = {
4059
+ id: session,
4060
+ connection,
4061
+ provider: info.provider,
4062
+ expiresAt: info.expiresAt,
4063
+ now: Effect.sync(now),
4064
+ suspend: (options = {}) => Effect.map(inputGate.suspend(options.drain), (held) => new Suspension(held)),
4065
+ ...tabs(context, registry, budget, native, register, release, Semaphore.makeUnsafe(1)),
4066
+ hasCookie: cookieQuery(context, native, settings.actionTimeout, clock),
4067
+ disconnected: lost,
4068
+ events: (eventOptions = {}) => timeline.stream(eventOptions.after),
4069
+ recentEvents: timeline.recent.pipe(Effect.map((records) => records.map((record) => record.event)))
4070
+ };
4071
+ return Browser.of(service);
4072
+ });
4073
+ //#endregion
4074
+ export { make$1 as a, make as i, Browser_exports as n, fold as o, Suspension as r, make$27 as s, Browser as t };
4075
+
4076
+ //# sourceMappingURL=Browser-BKPAbyys.mjs.map