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

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