effect-browser 0.2.0-beta.9 → 0.3.0-beta.5

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 (202) hide show
  1. package/README.md +705 -1184
  2. package/dist/Browser-CM65Uo7f.mjs +437 -0
  3. package/dist/Browser-CM65Uo7f.mjs.map +1 -0
  4. package/dist/Browser.d.mts +115 -3
  5. package/dist/Browser.mjs +2 -22
  6. package/dist/BrowserError-DXXIA6Rk.d.mts +135 -0
  7. package/dist/BrowserError.d.mts +2 -0
  8. package/dist/BrowserError.mjs +202 -0
  9. package/dist/BrowserError.mjs.map +1 -0
  10. package/dist/BrowserEvent-DzdNdvoh.d.mts +277 -0
  11. package/dist/BrowserEvent.d.mts +2 -0
  12. package/dist/BrowserEvent.mjs +295 -0
  13. package/dist/BrowserEvent.mjs.map +1 -0
  14. package/dist/Cdp.d.mts +32 -0
  15. package/dist/Cdp.mjs +61 -0
  16. package/dist/Cdp.mjs.map +1 -0
  17. package/dist/Change-DNvztNLu.mjs +138 -0
  18. package/dist/Change-DNvztNLu.mjs.map +1 -0
  19. package/dist/Change-DVP2IJWm.d.mts +71 -0
  20. package/dist/Change.d.mts +2 -0
  21. package/dist/Change.mjs +2 -0
  22. package/dist/Chromium.d.mts +29 -81
  23. package/dist/Chromium.mjs +57 -392
  24. package/dist/Chromium.mjs.map +1 -1
  25. package/dist/Expect.d.mts +62 -0
  26. package/dist/Expect.mjs +114 -0
  27. package/dist/Expect.mjs.map +1 -0
  28. package/dist/Frame-BERmf_gM.d.mts +117 -0
  29. package/dist/Frame.d.mts +2 -0
  30. package/dist/Frame.mjs +123 -0
  31. package/dist/Frame.mjs.map +1 -0
  32. package/dist/Moment.d.mts +2 -0
  33. package/dist/Moment.mjs +288 -0
  34. package/dist/Moment.mjs.map +1 -0
  35. package/dist/Motion.d.mts +40 -0
  36. package/dist/Motion.mjs +122 -0
  37. package/dist/Motion.mjs.map +1 -0
  38. package/dist/Page-D4281dIi.mjs +618 -0
  39. package/dist/Page-D4281dIi.mjs.map +1 -0
  40. package/dist/Page-DYTdVhYa.d.mts +593 -0
  41. package/dist/Page.d.mts +2 -0
  42. package/dist/Page.mjs +2 -0
  43. package/dist/Plan-CNNOU1Tx.d.mts +112 -0
  44. package/dist/Plan-Dtrb-8im.mjs +311 -0
  45. package/dist/Plan-Dtrb-8im.mjs.map +1 -0
  46. package/dist/Plan.d.mts +2 -3
  47. package/dist/Plan.mjs +2 -2
  48. package/dist/Policy.d.mts +76 -0
  49. package/dist/Policy.mjs +237 -0
  50. package/dist/Policy.mjs.map +1 -0
  51. package/dist/Presentation.d.mts +48 -0
  52. package/dist/Presentation.mjs +117 -0
  53. package/dist/Presentation.mjs.map +1 -0
  54. package/dist/Snapshot-B34hZ4Jl.d.mts +68 -0
  55. package/dist/Snapshot.d.mts +2 -0
  56. package/dist/Snapshot.mjs +79 -0
  57. package/dist/Snapshot.mjs.map +1 -0
  58. package/dist/Stage.d.mts +54 -0
  59. package/dist/Stage.mjs +133 -0
  60. package/dist/Stage.mjs.map +1 -0
  61. package/dist/Supervisor-BtEG93gR.mjs +420 -0
  62. package/dist/Supervisor-BtEG93gR.mjs.map +1 -0
  63. package/dist/Supervisor-Im6-wbg5.d.mts +230 -0
  64. package/dist/Supervisor.d.mts +2 -0
  65. package/dist/Supervisor.mjs +2 -0
  66. package/dist/context-DAYjATgC.mjs +137 -0
  67. package/dist/context-DAYjATgC.mjs.map +1 -0
  68. package/dist/index.d.mts +17 -14
  69. package/dist/index.mjs +18 -13
  70. package/dist/match.inpage-xOe9LNO0.mjs +48 -0
  71. package/dist/match.inpage-xOe9LNO0.mjs.map +1 -0
  72. package/dist/page-Banfm_zc.mjs +5097 -0
  73. package/dist/page-Banfm_zc.mjs.map +1 -0
  74. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  75. package/dist/url-CcL0K7S0.mjs +262 -0
  76. package/dist/url-CcL0K7S0.mjs.map +1 -0
  77. package/package.json +96 -61
  78. package/src/Browser.ts +625 -0
  79. package/src/BrowserError.ts +225 -0
  80. package/src/BrowserEvent.ts +294 -0
  81. package/src/Cdp.ts +101 -0
  82. package/src/Change.ts +88 -0
  83. package/src/Chromium.ts +102 -0
  84. package/src/Expect.ts +180 -0
  85. package/src/Frame.ts +130 -0
  86. package/src/Moment.ts +479 -0
  87. package/src/Motion.ts +166 -0
  88. package/src/Page.ts +520 -0
  89. package/src/Plan.ts +350 -0
  90. package/src/Policy.ts +325 -0
  91. package/src/Presentation.ts +195 -0
  92. package/src/Snapshot.ts +89 -0
  93. package/src/Stage.ts +223 -0
  94. package/src/Supervisor.ts +353 -0
  95. package/src/index.ts +20 -0
  96. package/src/internal/input/actions.ts +607 -0
  97. package/src/internal/input/dispatch.ts +161 -0
  98. package/src/internal/input/edit.inpage.ts +162 -0
  99. package/src/internal/input/evidence.inpage.ts +164 -0
  100. package/src/internal/input/guard.inpage.ts +605 -0
  101. package/src/internal/input/guard.ts +183 -0
  102. package/src/internal/input/keyboard.ts +112 -0
  103. package/src/internal/input/keys.ts +127 -0
  104. package/src/internal/input/perform.ts +322 -0
  105. package/src/internal/input/pointer.ts +153 -0
  106. package/src/internal/input/replies.ts +159 -0
  107. package/src/internal/input/settle.ts +50 -0
  108. package/src/internal/input/style.ts +186 -0
  109. package/src/internal/input/targets.inpage.ts +293 -0
  110. package/src/internal/input/targets.ts +148 -0
  111. package/src/internal/page/bridge.ts +386 -0
  112. package/src/internal/page/context.ts +302 -0
  113. package/src/internal/page/lane.ts +301 -0
  114. package/src/internal/page/navigation.ts +183 -0
  115. package/src/internal/page/openings.ts +87 -0
  116. package/src/internal/page/page.ts +137 -0
  117. package/src/internal/page/url.ts +100 -0
  118. package/src/internal/page/viewport.ts +43 -0
  119. package/src/internal/pictures/capture.ts +778 -0
  120. package/src/internal/pictures/clock.ts +141 -0
  121. package/src/internal/pictures/pictures.ts +520 -0
  122. package/src/internal/pictures/transport.ts +242 -0
  123. package/src/internal/reading/choose.ts +100 -0
  124. package/src/internal/reading/context.inpage.ts +201 -0
  125. package/src/internal/reading/controls.inpage.ts +158 -0
  126. package/src/internal/reading/expect.inpage.ts +70 -0
  127. package/src/internal/reading/match.inpage.ts +92 -0
  128. package/src/internal/reading/names.inpage.ts +306 -0
  129. package/src/internal/reading/outline.inpage.ts +260 -0
  130. package/src/internal/reading/reading.ts +223 -0
  131. package/src/internal/reading/ready.inpage.ts +154 -0
  132. package/src/internal/reading/ready.ts +105 -0
  133. package/src/internal/reading/subjects.inpage.ts +188 -0
  134. package/src/internal/reading/text.inpage.ts +135 -0
  135. package/src/internal/reading/walk.inpage.ts +220 -0
  136. package/src/internal/supervisor/lifecycle.ts +265 -0
  137. package/src/internal/timeline/changes.inpage.ts +216 -0
  138. package/src/internal/timeline/changes.ts +100 -0
  139. package/src/internal/timeline/events.ts +93 -0
  140. package/src/internal/timeline/fold.inpage.ts +123 -0
  141. package/src/internal/timeline/history.inpage.ts +229 -0
  142. package/src/internal/timeline/marks.inpage.ts +207 -0
  143. package/src/internal/timeline/record.inpage.ts +133 -0
  144. package/src/internal/timeline/sight.inpage.ts +122 -0
  145. package/src/internal/timeline/window.ts +96 -0
  146. package/src/internal/timeline/words.ts +65 -0
  147. package/dist/Bootstrap-B9UUXsvF.d.mts +0 -183
  148. package/dist/Bootstrap-CeQOWBy6.mjs +0 -189
  149. package/dist/Bootstrap-CeQOWBy6.mjs.map +0 -1
  150. package/dist/Bootstrap.d.mts +0 -3
  151. package/dist/Bootstrap.mjs +0 -2
  152. package/dist/Browser-BF9_sORP.d.mts +0 -388
  153. package/dist/Browser.mjs.map +0 -1
  154. package/dist/BrowserData-CPIIIHol.d.mts +0 -585
  155. package/dist/BrowserData.d.mts +0 -3
  156. package/dist/BrowserData.mjs +0 -695
  157. package/dist/BrowserData.mjs.map +0 -1
  158. package/dist/BrowserRuntime-B6nT1G4X.d.mts +0 -148
  159. package/dist/BrowserRuntime-C1r2aSRK.mjs +0 -6820
  160. package/dist/BrowserRuntime-C1r2aSRK.mjs.map +0 -1
  161. package/dist/BrowserRuntime.d.mts +0 -3
  162. package/dist/BrowserRuntime.mjs +0 -3
  163. package/dist/Capture.d.mts +0 -56
  164. package/dist/Capture.mjs +0 -678
  165. package/dist/Capture.mjs.map +0 -1
  166. package/dist/CaptureData-CYriZHX1.mjs +0 -201
  167. package/dist/CaptureData-CYriZHX1.mjs.map +0 -1
  168. package/dist/CaptureData.d.mts +0 -219
  169. package/dist/CaptureData.mjs +0 -2
  170. package/dist/Errors.d.mts +0 -158
  171. package/dist/Errors.mjs +0 -207
  172. package/dist/Errors.mjs.map +0 -1
  173. package/dist/Images-yCG9BmRU.mjs +0 -76
  174. package/dist/Images-yCG9BmRU.mjs.map +0 -1
  175. package/dist/OperationOptions-DAeRS6O9.mjs +0 -55
  176. package/dist/OperationOptions-DAeRS6O9.mjs.map +0 -1
  177. package/dist/PageControl.d.mts +0 -15
  178. package/dist/PageControl.mjs +0 -34
  179. package/dist/PageControl.mjs.map +0 -1
  180. package/dist/PageRegistry-B3q9DS3g.mjs +0 -164
  181. package/dist/PageRegistry-B3q9DS3g.mjs.map +0 -1
  182. package/dist/Plan-Dyxu2q8C.mjs +0 -543
  183. package/dist/Plan-Dyxu2q8C.mjs.map +0 -1
  184. package/dist/PlanData-B668RxbQ.d.mts +0 -4831
  185. package/dist/PlanData.d.mts +0 -3
  186. package/dist/PlanData.mjs +0 -268
  187. package/dist/PlanData.mjs.map +0 -1
  188. package/dist/PlanInput-BJcPPncs.mjs +0 -75
  189. package/dist/PlanInput-BJcPPncs.mjs.map +0 -1
  190. package/dist/PublicSession-DCSMMqOj.mjs +0 -5602
  191. package/dist/PublicSession-DCSMMqOj.mjs.map +0 -1
  192. package/dist/Testing.d.mts +0 -479
  193. package/dist/Testing.mjs +0 -2147
  194. package/dist/Testing.mjs.map +0 -1
  195. package/dist/Timeline-fV22Xk-S.d.mts +0 -29
  196. package/dist/Timeline.d.mts +0 -4
  197. package/dist/Timeline.mjs +0 -20
  198. package/dist/Timeline.mjs.map +0 -1
  199. package/dist/TimelineData-BsOn-YGZ.d.mts +0 -3818
  200. package/dist/TimelineData.d.mts +0 -3
  201. package/dist/TimelineData.mjs +0 -482
  202. package/dist/TimelineData.mjs.map +0 -1
package/src/Browser.ts ADDED
@@ -0,0 +1,625 @@
1
+ /**
2
+ * A live browser: its pages and what happens in it.
3
+ *
4
+ * `Browser` is a service with one implementation, built by a provider over a Playwright browser
5
+ * context: `Chromium` launches one locally, `Cdp` connects to any DevTools endpoint and
6
+ * `effect-browserbase` allocates a hosted one. Code written against `Browser` runs on all three.
7
+ * A page is named by its CDP target id, so a new connection to the same browser finds it again.
8
+ *
9
+ * @since 0.3.0
10
+ */
11
+ import {
12
+ Clock,
13
+ Context,
14
+ DateTime,
15
+ Deferred,
16
+ Duration,
17
+ Effect,
18
+ Exit,
19
+ Option,
20
+ Queue,
21
+ Scope,
22
+ Semaphore,
23
+ type Stream,
24
+ } from "effect";
25
+ import type { BrowserContext, Dialog, Page as PlaywrightPage } from "playwright-core";
26
+
27
+ import { type BrowserError, Failed, InvalidRequest, Limit } from "./BrowserError.ts";
28
+ import {
29
+ type BrowserEvent,
30
+ DialogShown,
31
+ Disconnected,
32
+ type DisconnectCause,
33
+ PageClosed,
34
+ PageOpened,
35
+ PageUntracked,
36
+ type RecordedEvent,
37
+ SessionEnding,
38
+ } from "./BrowserEvent.ts";
39
+ import { call, failWith, type Settings, undispatched } from "./internal/page/context.ts";
40
+ import { FailFast } from "./internal/page/lane.ts";
41
+ import * as Openings from "./internal/page/openings.ts";
42
+ import * as PageImpl from "./internal/page/page.ts";
43
+ import * as Url from "./internal/page/url.ts";
44
+ import * as BrowserClock from "./internal/pictures/clock.ts";
45
+ import * as Timeline from "./internal/timeline/events.ts";
46
+ import type * as Page from "./Page.ts";
47
+
48
+ /** A script that documents run before their own, such as a consent-banner remover. */
49
+ export interface InitScript {
50
+ /**
51
+ * The documents that run it, by a pattern their address (`location.href`) matches; every
52
+ * document and frame when left out. Under a `match`, the source runs as a block, so its own
53
+ * top-level `let`, `const` and classes stay its own.
54
+ */
55
+ readonly match?: RegExp | undefined;
56
+ readonly source: string;
57
+ }
58
+
59
+ export interface Options {
60
+ /**
61
+ * Bound on each action; finite and positive. Defaults to 10 seconds. What a presenter's view
62
+ * takes to show an action, such as its glides and typing at a person's pace, does not count
63
+ * against it.
64
+ */
65
+ readonly actionTimeout?: Duration.Input | undefined;
66
+ /** Bound on each navigation; finite and positive. Defaults to 30 seconds. */
67
+ readonly navigationTimeout?: Duration.Input | undefined;
68
+ /**
69
+ * How long each page keeps screencast frames for `recentFrames`, measured back from the newest;
70
+ * finite and positive. Defaults to 5 seconds, a moment's default window.
71
+ */
72
+ readonly frameHistory?: Duration.Input | undefined;
73
+ /** Events retained for replay and `recentEvents`. A positive safe integer, defaulting to 4,096. */
74
+ readonly eventHistory?: number | undefined;
75
+ /** Allow, deny or hold each input or navigation before it reaches the page. Defaults to allow. */
76
+ readonly guard?: Page.InputGuard | undefined;
77
+ /** A separate bound for policy holds, outside action timeouts. Defaults to 5 minutes. */
78
+ readonly policyTimeout?: Duration.Input | undefined;
79
+ /** Scripts that new documents run before their own, each where its `match` allows. */
80
+ readonly initScripts?: ReadonlyArray<InitScript> | undefined;
81
+ /**
82
+ * The most pages the browser keeps open, those a site opens included, which are never refused. At
83
+ * it, `newPage` waits for one to close, within the action timeout, then fails `Limit`; under
84
+ * `Page.failFast` it fails at once. A positive safe integer; no limit when left out.
85
+ */
86
+ readonly maxPages?: number | undefined;
87
+ }
88
+
89
+ export interface EventOptions {
90
+ /** Resume after this sequence; 0 replays from the beginning if it is still retained. */
91
+ readonly after?: number | undefined;
92
+ }
93
+
94
+ /**
95
+ * A connection to the browser apart from the one that drives its pages, for their screencasts,
96
+ * as a provider that reaches the browser over a network supplies it: a frame and its
97
+ * acknowledgement then never wait behind a large message, such as an upload or a read's answer,
98
+ * on the connection that drives the page. It is read-only. A page's session on it sends the
99
+ * capture's commands alone, and the page's own session keeps its focus emulation, which keeps a
100
+ * tab behind painting.
101
+ */
102
+ export interface CaptureSource {
103
+ /**
104
+ * A session on the page's target, for the scope. `event` gets the session's events in the order
105
+ * the browser sent them, its target's detach among them, until the scope closes; `lost` gets
106
+ * the connection's failure, once, if it fails first. Its calls never throw: a failure rejects.
107
+ */
108
+ readonly attach: (
109
+ target: string,
110
+ listener: {
111
+ readonly event: (method: string, params: unknown) => void;
112
+ readonly lost: (error: BrowserError) => void;
113
+ },
114
+ ) => Effect.Effect<
115
+ (
116
+ method:
117
+ | "Page.enable"
118
+ | "Page.getFrameTree"
119
+ | "Page.startScreencast"
120
+ | "Page.screencastFrameAck"
121
+ | "Page.stopScreencast",
122
+ params?: Record<string, unknown>,
123
+ ) => Promise<unknown>,
124
+ BrowserError,
125
+ Scope.Scope
126
+ >;
127
+ }
128
+
129
+ export interface Service {
130
+ /** The provider's session id, or a local id. */
131
+ readonly id: string;
132
+ readonly provider: string;
133
+ /** When the provider ends the session on its own, as a hosted session's timeout does. */
134
+ readonly expiresAt: DateTime.Utc | undefined;
135
+ /** Host monotonic milliseconds on the clock shared by this browser’s events and frames. */
136
+ readonly now: Effect.Effect<number>;
137
+ /** The Playwright context, for anything this API does not cover. Never give it to a model. */
138
+ readonly context: BrowserContext;
139
+ /** Open pages in the order this browser began tracking them. */
140
+ readonly pages: Effect.Effect<ReadonlyArray<Page.Page>>;
141
+ /** The open page with this id, its CDP target id, as stored before a reconnect. */
142
+ readonly page: (id: string) => Effect.Effect<Option.Option<Page.Page>>;
143
+ /** The first open page, opening one when there is none. */
144
+ readonly firstPage: Effect.Effect<Page.Page, BrowserError>;
145
+ readonly newPage: (url?: string) => Effect.Effect<Page.Page, BrowserError>;
146
+ /**
147
+ * Completes once the browser is lost to its owner, with why: its connection dropped, its
148
+ * provider ended its session, or its owner's scope released it.
149
+ */
150
+ readonly disconnected: Effect.Effect<DisconnectCause>;
151
+ /** Live events, or replay after a cursor. A reader that falls behind fails with EventHistoryExpired. */
152
+ readonly events: (options?: EventOptions) => Stream.Stream<RecordedEvent, BrowserError>;
153
+ /** The latest `eventHistory` events, oldest first. */
154
+ readonly recentEvents: Effect.Effect<ReadonlyArray<BrowserEvent>>;
155
+ }
156
+
157
+ export class Browser extends Context.Service<Browser, Service>()("effect-browser/Browser") {}
158
+
159
+ /** The settings every page shares, and how many events the browser keeps, from its options. */
160
+ const settingsOf = Effect.fnUntraced(function* (options: Options) {
161
+ const invalid = (detail: string) => undispatched("make", new InvalidRequest({ detail }));
162
+
163
+ // Every bound guards a lock or a held key, so each must be a real, finite deadline.
164
+ const bound = (name: string, input: Duration.Input | undefined, fallback: Duration.Duration) => {
165
+ const decoded = Duration.fromInput(input ?? fallback);
166
+
167
+ return Option.isSome(decoded) &&
168
+ Number.isFinite(Duration.toMillis(decoded.value)) &&
169
+ Duration.isPositive(decoded.value)
170
+ ? Effect.succeed(decoded.value)
171
+ : Effect.fail(invalid(`${name} must be finite and greater than zero`));
172
+ };
173
+
174
+ const settings: Settings = {
175
+ actionTimeout: yield* bound("actionTimeout", options.actionTimeout, Duration.seconds(10)),
176
+ navigationTimeout: yield* bound(
177
+ "navigationTimeout",
178
+ options.navigationTimeout,
179
+ Duration.seconds(30),
180
+ ),
181
+ frameHistory: yield* bound("frameHistory", options.frameHistory, Duration.seconds(5)),
182
+ guard: options.guard,
183
+ policyTimeout: yield* bound("policyTimeout", options.policyTimeout, Duration.minutes(5)),
184
+ };
185
+
186
+ const eventHistory = options.eventHistory ?? 4096;
187
+ const { maxPages } = options;
188
+
189
+ if (!Number.isSafeInteger(eventHistory) || eventHistory < 1)
190
+ return yield* invalid("eventHistory must be a positive safe integer");
191
+ if (maxPages !== undefined && (!Number.isSafeInteger(maxPages) || maxPages < 1))
192
+ return yield* invalid("maxPages must be a positive safe integer");
193
+
194
+ return { settings, eventHistory, maxPages };
195
+ });
196
+
197
+ /**
198
+ * A provider that ends a session at `expiresAt` by its own clock can cut the connection a little
199
+ * before this host's clock gets there.
200
+ */
201
+ const endMargin = Duration.seconds(5);
202
+
203
+ /**
204
+ * The browser's loss, once: its context closing from the other side, at or after the session's
205
+ * end or before it, or `lose`, as the owner's scope releases it. Playwright leaves the calls in
206
+ * flight on the library's own sessions unanswered when the connection drops, so `untilLost` fails
207
+ * each with the browser, as a closed page's call fails.
208
+ */
209
+ const watchLoss = Effect.fnUntraced(function* (
210
+ context: BrowserContext,
211
+ expiresAt: DateTime.Utc | undefined,
212
+ clock: Clock.Clock,
213
+ disconnected: (cause: DisconnectCause) => void,
214
+ ) {
215
+ let lostBy: DisconnectCause | undefined;
216
+ const lost = yield* Deferred.make<DisconnectCause>();
217
+ const inFlight = new Set<(cause: Error) => void>();
218
+ const gone = () => new Error("Target page, context or browser has been closed");
219
+
220
+ const lose = (cause: DisconnectCause) => {
221
+ if (lostBy !== undefined) return;
222
+ lostBy = cause;
223
+ for (const reject of inFlight) reject(gone());
224
+ disconnected(cause);
225
+ Deferred.doneUnsafe(lost, Exit.succeed(cause));
226
+ };
227
+
228
+ const untilLost = <A>(reply: Promise<A>): Promise<A> => {
229
+ if (lostBy !== undefined) {
230
+ void reply.catch(() => undefined);
231
+
232
+ return Promise.reject(gone());
233
+ }
234
+
235
+ return new Promise<A>((resolve, reject) => {
236
+ inFlight.add(reject);
237
+ void reply.then(resolve, reject).finally(() => inFlight.delete(reject));
238
+ });
239
+ };
240
+
241
+ const ended = () =>
242
+ expiresAt !== undefined &&
243
+ clock.currentTimeMillisUnsafe() >=
244
+ DateTime.toEpochMillis(expiresAt) - Duration.toMillis(endMargin);
245
+
246
+ const onClose = () => lose(ended() ? "session" : "connection");
247
+
248
+ context.on("close", onClose);
249
+ yield* Effect.addFinalizer(() => Effect.sync(() => context.off("close", onClose)));
250
+ if (context.browser()?.isConnected() === false) onClose();
251
+
252
+ const native = <A>(operation: string, run: () => Promise<A>) =>
253
+ call(operation, run, () => lostBy ?? "page");
254
+
255
+ return { lostBy: () => lostBy, lost: Deferred.await(lost), lose, untilLost, native };
256
+ });
257
+
258
+ /**
259
+ * What a page's own Playwright events publish, its close and crash aside, while its scope is
260
+ * open. Dialogs are answered: alerts accepted, others dismissed. The page's own session tells its
261
+ * documents' commits and loads.
262
+ */
263
+ const listen = (
264
+ playwright: PlaywrightPage,
265
+ page: string,
266
+ publish: (event: BrowserEvent) => number,
267
+ now: () => number,
268
+ on: { readonly close: () => void; readonly crash: () => void },
269
+ ) => {
270
+ const dialog = (shown: Dialog) => {
271
+ const kind = shown.type();
272
+ const answer = kind === "alert" || kind === "beforeunload" ? "accepted" : "dismissed";
273
+ const message = shown.message().slice(0, 500);
274
+
275
+ publish(new DialogShown({ at: now(), page, kind, message, answer }));
276
+ (answer === "accepted" ? shown.accept() : shown.dismiss()).catch(() => undefined);
277
+ };
278
+
279
+ return Effect.acquireRelease(
280
+ Effect.sync(() => {
281
+ playwright.on("close", on.close);
282
+ playwright.on("crash", on.crash);
283
+ playwright.on("dialog", dialog);
284
+ }),
285
+ () =>
286
+ Effect.sync(() => {
287
+ playwright.off("close", on.close);
288
+ playwright.off("crash", on.crash);
289
+ playwright.off("dialog", dialog);
290
+ }),
291
+ );
292
+ };
293
+
294
+ /**
295
+ * Register each page the site opens, such as a popup, as Playwright reports it, for as long as the
296
+ * scope is open. One that could not be tracked is published, unless it closed as it opened.
297
+ */
298
+ const followOpened = Effect.fnUntraced(function* (
299
+ context: BrowserContext,
300
+ register: (playwright: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,
301
+ publish: (event: BrowserEvent) => number,
302
+ now: () => number,
303
+ registrations: Openings.Registrations,
304
+ ) {
305
+ const opened = yield* Queue.unbounded<PlaywrightPage>();
306
+
307
+ const onPage = (playwright: PlaywrightPage) => {
308
+ registrations.set(playwright, Deferred.makeUnsafe<void, BrowserError>());
309
+ Queue.offerUnsafe(opened, playwright);
310
+ };
311
+
312
+ const untracked = (playwright: PlaywrightPage) => (error: BrowserError) =>
313
+ Effect.sync(() => {
314
+ const url = Url.redact(playwright.url());
315
+
316
+ if (!playwright.isClosed())
317
+ publish(new PageUntracked({ at: now(), url, detail: error.message }));
318
+ });
319
+
320
+ context.on("page", onPage);
321
+ yield* Effect.addFinalizer(() => Effect.sync(() => context.off("page", onPage)));
322
+ yield* Queue.take(opened).pipe(
323
+ Effect.flatMap((playwright) =>
324
+ register(playwright).pipe(
325
+ Effect.asVoid,
326
+ Effect.onExit((exit) =>
327
+ Effect.sync(() => {
328
+ const done = registrations.get(playwright);
329
+
330
+ if (done !== undefined) Deferred.doneUnsafe(done, exit);
331
+ }),
332
+ ),
333
+ Effect.catch(untracked(playwright)),
334
+ ),
335
+ ),
336
+ Effect.forever,
337
+ Effect.forkScoped,
338
+ );
339
+ });
340
+
341
+ /** Release something native, on the owner's clock, giving up after a second: cleanup only. */
342
+ const releaseNative = (clock: Clock.Clock) => (run: () => Promise<unknown>) =>
343
+ Effect.tryPromise(run).pipe(
344
+ Effect.interruptible,
345
+ Effect.timeoutOrElse({ duration: Duration.seconds(1), orElse: () => Effect.void }),
346
+ Effect.provideService(Clock.Clock, clock),
347
+ Effect.ignore,
348
+ );
349
+
350
+ /** A page's own events among the browser's retained ones, and the openings of tabs it opened. */
351
+ const eventsOf = (recent: Effect.Effect<ReadonlyArray<RecordedEvent>>, page: string) =>
352
+ Effect.map(recent, (records) =>
353
+ records.flatMap(({ event }) =>
354
+ ("page" in event && event.page === page) ||
355
+ (event._tag === "PageOpened" && event.opener === page)
356
+ ? [event]
357
+ : [],
358
+ ),
359
+ );
360
+
361
+ /** A script as its documents run it: everywhere, or as a block where its `match` allows. */
362
+ const scoped = ({ match, source }: InitScript) =>
363
+ match === undefined ? source : `if (${String(match)}.test(location.href)) {\n${source}\n}`;
364
+
365
+ /**
366
+ * At most `maxPages` open pages, those a site opened included, which are never refused: an open
367
+ * past it waits for one to close, within `wait` on the owner's clock, then fails `Limit`, or fails
368
+ * at once under `FailFast`. An open counts until its page is tracked.
369
+ */
370
+ const pageBudget = (
371
+ maxPages: number | undefined,
372
+ tracked: () => number,
373
+ wait: Duration.Duration,
374
+ clock: Clock.Clock,
375
+ ) => {
376
+ let opening = 0;
377
+ // Completed as a page closes or an open ends, so the opens waiting look again.
378
+ let roomMade = Deferred.makeUnsafe<void>();
379
+
380
+ const makeRoom = () => {
381
+ Deferred.doneUnsafe(roomMade, Exit.void);
382
+ roomMade = Deferred.makeUnsafe<void>();
383
+ };
384
+
385
+ const full = (limit: number) => tracked() + opening >= limit;
386
+
387
+ const room = (limit: number) =>
388
+ Effect.gen(function* () {
389
+ const refused = undispatched("newPage", new Limit({ maxPages: limit }));
390
+
391
+ if ((yield* FailFast) && full(limit)) return yield* refused;
392
+ yield* Effect.gen(function* () {
393
+ while (full(limit)) yield* Deferred.await(roomMade);
394
+ opening += 1;
395
+ }).pipe(
396
+ Effect.timeoutOrElse({ duration: wait, orElse: () => Effect.fail(refused) }),
397
+ Effect.provideService(Clock.Clock, clock),
398
+ );
399
+ });
400
+
401
+ const open = <A, E, R>(opened: Effect.Effect<A, E, R>) =>
402
+ maxPages === undefined
403
+ ? opened
404
+ : Effect.uninterruptibleMask((restore) =>
405
+ restore(room(maxPages)).pipe(
406
+ Effect.andThen(
407
+ restore(opened).pipe(
408
+ Effect.ensuring(
409
+ Effect.sync(() => {
410
+ opening -= 1;
411
+ makeRoom();
412
+ }),
413
+ ),
414
+ ),
415
+ ),
416
+ ),
417
+ );
418
+
419
+ return { makeRoom, open };
420
+ };
421
+
422
+ /** A call sent now and awaited later, by whatever needs its answer. */
423
+ const sentNow = <A>(sent: Promise<A>) => {
424
+ void sent.catch(() => undefined);
425
+
426
+ return sent;
427
+ };
428
+
429
+ /**
430
+ * Build the service over a context the provider owns. The provider closes the context; this only
431
+ * tracks its pages and events, for as long as the surrounding scope is open. Each page's protocol
432
+ * session, capture and listeners end when that page closes or when the scope does, so a closed
433
+ * tab retains nothing and the context keeps none of them afterwards.
434
+ */
435
+ export const make = Effect.fn("Browser.make")(function* (
436
+ context: BrowserContext,
437
+ info: {
438
+ readonly id: string;
439
+ readonly provider: string;
440
+ readonly expiresAt?: DateTime.Utc | undefined;
441
+ /** Where pages' screencasts run, if not on each page's own session. */
442
+ readonly capture?: CaptureSource | undefined;
443
+ },
444
+ options: Options = {},
445
+ ) {
446
+ const clock = yield* Clock.Clock;
447
+ const now = () => Number(clock.monotonicTimeNanosUnsafe()) / 1e6;
448
+ const { settings, eventHistory, maxPages } = yield* settingsOf(options);
449
+ // Measured on first need: the first capture of any page measures it, and input never waits.
450
+ const mapping = BrowserClock.mapping(now);
451
+
452
+ const timeline = Timeline.make(eventHistory);
453
+
454
+ yield* Effect.addFinalizer(() => timeline.close);
455
+ const publish = timeline.publish;
456
+
457
+ if (info.expiresAt !== undefined)
458
+ publish(new SessionEnding({ at: now(), expiresAt: info.expiresAt }));
459
+
460
+ const { lostBy, lost, lose, untilLost, native } = yield* watchLoss(
461
+ context,
462
+ info.expiresAt,
463
+ clock,
464
+ (cause) => publish(new Disconnected({ at: now(), cause })),
465
+ );
466
+
467
+ const registry = new Map<PlaywrightPage, Page.Page>();
468
+ const registrations: Openings.Registrations = new WeakMap();
469
+ const registering = yield* Semaphore.make(1);
470
+ // The pages' scopes close after the browser is marked released, so what fails as they close
471
+ // says why.
472
+ const pagesScope = yield* Scope.fork(yield* Scope.Scope);
473
+
474
+ const release = releaseNative(clock);
475
+ const budget = pageBudget(maxPages, () => registry.size, settings.actionTimeout, clock);
476
+
477
+ // Each tab's scope closes with the tab or the browser. A dropped connection closes every page,
478
+ // then the context, and `Disconnected` stands for all of them: the queue hands a close to its
479
+ // fiber in a later turn, once Playwright has reported the context's.
480
+ const closing = yield* Queue.unbounded<{
481
+ readonly scope: Scope.Closeable;
482
+ readonly page: string;
483
+ readonly cause: PageClosed["cause"];
484
+ }>();
485
+
486
+ yield* Queue.take(closing).pipe(
487
+ Effect.tap(({ page, cause }) =>
488
+ Effect.sync(() => {
489
+ if (lostBy() === undefined) publish(new PageClosed({ at: now(), page, cause }));
490
+ }),
491
+ ),
492
+ Effect.flatMap(({ scope }) => Scope.close(scope, Exit.void)),
493
+ Effect.forever,
494
+ Effect.forkScoped,
495
+ );
496
+
497
+ const register = (playwright: PlaywrightPage) =>
498
+ registering.withPermits(1)(
499
+ Effect.gen(function* () {
500
+ const known = registry.get(playwright);
501
+
502
+ if (known !== undefined) return known;
503
+ if (playwright.isClosed())
504
+ return yield* failWith("newPage", new Failed({ detail: "the page closed as it opened" }));
505
+ const scope = yield* Scope.fork(pagesScope);
506
+
507
+ return yield* Effect.gen(function* () {
508
+ let crashed = false;
509
+ const closedBy = () => lostBy() ?? (crashed ? "crashed" : "page");
510
+ const cdp = yield* native("newPage", () => context.newCDPSession(playwright));
511
+
512
+ yield* Effect.addFinalizer(() => release(() => cdp.detach()));
513
+ // The page's name, its target id, costs one round trip, which the calls that keep it
514
+ // painting behind other tabs and report its documents share. A renderer busy with its
515
+ // first script answers those two late, so what needs them waits, and registering does not.
516
+ const send: typeof cdp.send = (method, params) => untilLost(cdp.send(method, params));
517
+ const focusing = sentNow(send("Emulation.setFocusEmulationEnabled", { enabled: true }));
518
+ const paging = sentNow(send("Page.enable"));
519
+ const { targetInfo } = yield* native("newPage", () => send("Target.getTargetInfo"));
520
+ const id = targetInfo.targetId;
521
+
522
+ const page = yield* PageImpl.make({
523
+ id,
524
+ session: info.id,
525
+ url: targetInfo.url,
526
+ playwright,
527
+ cdp,
528
+ untilLost,
529
+ settings,
530
+ clock,
531
+ mapping,
532
+ publish,
533
+ recentEvents: eventsOf(timeline.recent, id),
534
+ openings: yield* Openings.make(playwright, cdp, registrations, closedBy),
535
+ focused: call("focus", () => focusing, closedBy).pipe(Effect.asVoid),
536
+ paging: (operation) => call(operation, () => paging, closedBy).pipe(Effect.asVoid),
537
+ closedBy,
538
+ capture: info.capture,
539
+ });
540
+
541
+ const close = () => {
542
+ if (registry.get(playwright) !== page) return;
543
+ registry.delete(playwright);
544
+ budget.makeRoom();
545
+ Queue.offerUnsafe(closing, { scope, page: id, cause: crashed ? "crashed" : "page" });
546
+ };
547
+
548
+ // Playwright drives a crashed page no more and its calls never return, so it is closed:
549
+ // they fail at once, `Closed` because it crashed.
550
+ const crash = () => {
551
+ crashed = true;
552
+ void playwright.close().catch(() => undefined);
553
+ };
554
+
555
+ registry.set(playwright, page);
556
+ publish(
557
+ new PageOpened({
558
+ at: now(),
559
+ page: id,
560
+ url: Url.redact(targetInfo.url),
561
+ opener: targetInfo.openerId,
562
+ }),
563
+ );
564
+ yield* listen(playwright, id, publish, now, { close, crash });
565
+ if (playwright.isClosed()) close();
566
+
567
+ return page;
568
+ }).pipe(
569
+ Scope.provide(scope),
570
+ Effect.onError(() => Scope.close(scope, Exit.void)),
571
+ );
572
+ }),
573
+ );
574
+
575
+ // Playwright registers its init scripts as it sets up each page, before a popup's first document
576
+ // runs, and they cost no call per document.
577
+ for (const script of options.initScripts ?? [])
578
+ yield* native("initScripts", () => context.addInitScript({ content: scoped(script) }));
579
+ yield* followOpened(context, register, publish, now, registrations);
580
+ for (const existing of context.pages()) yield* register(existing);
581
+
582
+ const pages = Effect.sync(() => [...registry.values()]);
583
+
584
+ const newPage = Effect.fn("Browser.newPage")(function* (url?: string) {
585
+ const page = yield* budget.open(
586
+ native("newPage", () => context.newPage()).pipe(
587
+ Effect.flatMap((playwright) =>
588
+ register(playwright).pipe(Effect.onError(() => release(() => playwright.close()))),
589
+ ),
590
+ ),
591
+ );
592
+
593
+ // A rejected or interrupted navigation must not leave the newly allocated blank tab behind.
594
+ if (url !== undefined)
595
+ yield* page.goto(url).pipe(Effect.onError(() => page.close.pipe(Effect.ignore)));
596
+
597
+ return page;
598
+ });
599
+
600
+ // Added last, so it runs first as the owner's scope closes.
601
+ yield* Effect.addFinalizer(() => Effect.sync(() => lose("released")));
602
+
603
+ const service: Service = {
604
+ id: info.id,
605
+ provider: info.provider,
606
+ expiresAt: info.expiresAt,
607
+ now: Effect.sync(now),
608
+ context,
609
+ pages,
610
+ page: (id) =>
611
+ Effect.map(pages, (open) => Option.fromNullishOr(open.find((page) => page.id === id))),
612
+ firstPage: pages.pipe(
613
+ Effect.map((open) => Option.fromNullishOr(open[0])),
614
+ Effect.flatMap(Option.match({ onNone: () => newPage(), onSome: Effect.succeed })),
615
+ ),
616
+ newPage,
617
+ disconnected: lost,
618
+ events: (eventOptions = {}) => timeline.stream(eventOptions.after),
619
+ recentEvents: timeline.recent.pipe(
620
+ Effect.map((records) => records.map((record) => record.event)),
621
+ ),
622
+ };
623
+
624
+ return Browser.of(service);
625
+ });