effect-browser 0.3.0-beta.7 → 0.3.0-beta.9

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 (64) hide show
  1. package/README.md +114 -19
  2. package/dist/{Browser-CNwK0r0q.mjs → Browser-Bc_LIqTC.mjs} +184 -16
  3. package/dist/Browser-Bc_LIqTC.mjs.map +1 -0
  4. package/dist/Browser.d.mts +16 -4
  5. package/dist/Browser.mjs +2 -2
  6. package/dist/{BrowserError-DXXIA6Rk.d.mts → BrowserError-Coy7EW1N.d.mts} +10 -5
  7. package/dist/BrowserError.d.mts +2 -2
  8. package/dist/BrowserError.mjs +10 -1
  9. package/dist/BrowserError.mjs.map +1 -1
  10. package/dist/Cdp.d.mts +1 -1
  11. package/dist/Cdp.mjs +3 -3
  12. package/dist/Chromium.d.mts +1 -1
  13. package/dist/Chromium.mjs +2 -2
  14. package/dist/Expect.d.mts +2 -2
  15. package/dist/Expect.mjs +2 -2
  16. package/dist/Moment.d.mts +1 -1
  17. package/dist/Moment.mjs +1 -1
  18. package/dist/{Page-D4281dIi.mjs → Page-B5cjaUp5.mjs} +2 -2
  19. package/dist/{Page-D4281dIi.mjs.map → Page-B5cjaUp5.mjs.map} +1 -1
  20. package/dist/{Page-C30aG2RQ.d.mts → Page-BlPjfibv.d.mts} +2 -2
  21. package/dist/Page.d.mts +1 -1
  22. package/dist/Page.mjs +1 -1
  23. package/dist/{Plan-BvCS9qAf.d.mts → Plan-BI8XGvDu.d.mts} +3 -3
  24. package/dist/{Plan-CyQNv49C.mjs → Plan-D1wrJVs8.mjs} +3 -3
  25. package/dist/{Plan-CyQNv49C.mjs.map → Plan-D1wrJVs8.mjs.map} +1 -1
  26. package/dist/Plan.d.mts +1 -1
  27. package/dist/Plan.mjs +1 -1
  28. package/dist/Policy.d.mts +1 -1
  29. package/dist/Policy.mjs +1 -1
  30. package/dist/Presentation.d.mts +1 -1
  31. package/dist/Presentation.mjs +1 -1
  32. package/dist/Stage.d.mts +2 -2
  33. package/dist/Stage.mjs +2 -2
  34. package/dist/{Supervisor-CLJaT7rG.d.mts → Supervisor-CYWFK3vM.d.mts} +105 -55
  35. package/dist/Supervisor-TNKNOVzu.mjs +599 -0
  36. package/dist/Supervisor-TNKNOVzu.mjs.map +1 -0
  37. package/dist/Supervisor.d.mts +2 -2
  38. package/dist/Supervisor.mjs +2 -2
  39. package/dist/{context-DAYjATgC.mjs → context-B6xr8nVi.mjs} +134 -10
  40. package/dist/context-B6xr8nVi.mjs.map +1 -0
  41. package/dist/index.d.mts +4 -4
  42. package/dist/index.mjs +4 -4
  43. package/dist/{page-DHeYWEs-.mjs → page-D-OedyBw.mjs} +59 -126
  44. package/dist/page-D-OedyBw.mjs.map +1 -0
  45. package/dist/{url-CcL0K7S0.mjs → url-Cd04Okid.mjs} +6 -4
  46. package/dist/url-Cd04Okid.mjs.map +1 -0
  47. package/package.json +1 -1
  48. package/src/Browser.ts +57 -16
  49. package/src/BrowserError.ts +9 -0
  50. package/src/Supervisor.ts +384 -138
  51. package/src/internal/input/gate.ts +224 -0
  52. package/src/internal/input/guard.ts +3 -2
  53. package/src/internal/input/perform.ts +84 -32
  54. package/src/internal/input/replies.ts +52 -16
  55. package/src/internal/page/context.ts +21 -11
  56. package/src/internal/page/lane.ts +20 -10
  57. package/src/internal/supervisor/lifecycle.ts +291 -140
  58. package/src/internal/timeline/events.ts +1 -0
  59. package/dist/Browser-CNwK0r0q.mjs.map +0 -1
  60. package/dist/Supervisor-BtEG93gR.mjs +0 -420
  61. package/dist/Supervisor-BtEG93gR.mjs.map +0 -1
  62. package/dist/context-DAYjATgC.mjs.map +0 -1
  63. package/dist/page-DHeYWEs-.mjs.map +0 -1
  64. package/dist/url-CcL0K7S0.mjs.map +0 -1
@@ -1,420 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { DisconnectCause } from "./BrowserEvent.mjs";
3
- import { Cause, Clock, DateTime, Duration, Effect, Exit, Fiber, FiberHandle, FiberMap, Option, Predicate, PubSub, Schedule, Schema, Scope, Stream, SubscriptionRef } from "effect";
4
- //#region src/internal/supervisor/lifecycle.ts
5
- /**
6
- * A supervisor's life as one state and one transition function, and the generation states it
7
- * publishes. The transition has no effects: `Supervisor.make` applies each input under one lock,
8
- * publishes the events in order and runs the commands, so the rules here are tested alone.
9
- */
10
- /** The provider confirmed that the generation's browser ended. */
11
- var Settled = class extends Schema.TaggedClass()("Settled", {}) {};
12
- /** The provider could not confirm the end by its deadline, so the browser may still run, and bill. */
13
- var Unconfirmed = class extends Schema.TaggedClass()("Unconfirmed", { detail: Schema.String }) {};
14
- const Released = Schema.Union([Settled, Unconfirmed]);
15
- /** Opening, but not after a loss: the first generation, a rotation, or the one after `Down`. */
16
- var Opening = class extends Schema.TaggedClass()("Opening", {}) {};
17
- /** Opening after the generation before it was lost. */
18
- var Reopening = class extends Schema.TaggedClass()("Reopening", {}) {};
19
- /** Open: `browser` gives this generation until the next one opens. */
20
- var Open = class extends Schema.TaggedClass()("Open", {}) {};
21
- /** Lost: its connection dropped, or its provider ended its session, as `cause` says. */
22
- var Lost = class extends Schema.TaggedClass()("Lost", { cause: DisconnectCause }) {};
23
- /**
24
- * It never opened: its last try failed with `cause`, which the provider deems definite, or after
25
- * which the reopen schedule gave up.
26
- */
27
- var Down = class extends Schema.TaggedClass()("Down", {
28
- detail: Schema.String,
29
- cause: Schema.Defect()
30
- }) {};
31
- /** It ended. `released` says how its release went; one retired while opening has none. */
32
- var Closed = class extends Schema.TaggedClass()("Closed", { released: Schema.optional(Released) }) {};
33
- /**
34
- * It was serving as the supervisor's scope closed, and was left running, not released: its scope
35
- * closed, and its provider runs it on, and bills, until something adopts and releases it.
36
- */
37
- var Kept = class extends Schema.TaggedClass()("Kept", {}) {};
38
- const GenerationState = Schema.Union([
39
- Opening,
40
- Reopening,
41
- Open,
42
- Lost,
43
- Down,
44
- Closed,
45
- Kept
46
- ]);
47
- const start = () => ({
48
- state: {
49
- _tag: "Opening",
50
- number: 1,
51
- serving: void 0
52
- },
53
- events: [[1, new Opening()]],
54
- commands: [{
55
- _tag: "Open",
56
- number: 1,
57
- after: void 0
58
- }]
59
- });
60
- const servingOf = (state) => state._tag === "Retired" ? void 0 : state.serving;
61
- /** The state after `input`, with the events to publish and the commands to run. */
62
- const transition = (state, input, exclusive) => {
63
- const release = (live) => ({
64
- _tag: "Release",
65
- live
66
- });
67
- const stay = {
68
- state,
69
- events: [],
70
- commands: []
71
- };
72
- /**
73
- * Open `number`, ending `current` now if it `ends`; exclusive generations open only once its
74
- * release has finished. Otherwise `current` serves until the next one opens.
75
- */
76
- const next = (number, reopen, current, ends) => ({
77
- state: {
78
- _tag: "Opening",
79
- number,
80
- serving: ends ? void 0 : current
81
- },
82
- events: [[number, reopen ? new Reopening() : new Opening()]],
83
- commands: [...ends && current !== void 0 ? [release(current)] : [], {
84
- _tag: "Open",
85
- number,
86
- after: ends && exclusive ? current?.number : void 0
87
- }]
88
- });
89
- switch (input._tag) {
90
- case "Opened": {
91
- const { live } = input;
92
- if (state._tag !== "Opening" || state.number !== live.number) return {
93
- ...stay,
94
- commands: [release(live)]
95
- };
96
- return {
97
- state: {
98
- _tag: "Open",
99
- serving: live
100
- },
101
- events: [[live.number, new Open()]],
102
- commands: [{
103
- _tag: "Watch",
104
- live
105
- }, ...state.serving === void 0 ? [] : [release(state.serving)]]
106
- };
107
- }
108
- case "Failed": {
109
- const { number, detail, cause } = input;
110
- const events = [[number, new Down({
111
- detail,
112
- cause
113
- })]];
114
- if (state._tag !== "Opening" || state.number !== input.number) return {
115
- ...stay,
116
- events
117
- };
118
- return {
119
- state: {
120
- _tag: "Down",
121
- number,
122
- detail,
123
- cause,
124
- serving: state.serving
125
- },
126
- events,
127
- commands: []
128
- };
129
- }
130
- case "Abandoned": return {
131
- ...stay,
132
- events: [[input.number, new Closed({})]]
133
- };
134
- case "Released": return {
135
- ...stay,
136
- events: [[input.number, new Closed({ released: input.released })]]
137
- };
138
- case "Lost": {
139
- const lost = servingOf(state);
140
- if (state._tag === "Retired" || lost?.number !== input.number) return stay;
141
- const events = [[lost.number, new Lost({ cause: input.cause })]];
142
- if (state._tag === "Opening") return {
143
- state: {
144
- ...state,
145
- serving: void 0
146
- },
147
- events,
148
- commands: [release(lost)]
149
- };
150
- const reopened = next((state._tag === "Open" ? lost.number : state.number) + 1, true, lost, true);
151
- return {
152
- ...reopened,
153
- events: [...events, ...reopened.events]
154
- };
155
- }
156
- case "Rotate": {
157
- if (state._tag === "Retired") return stay;
158
- if (input.due !== void 0 && (state._tag !== "Open" || state.serving.number !== input.due)) return stay;
159
- if (state._tag === "Opening") return {
160
- ...stay,
161
- reply: state.number
162
- };
163
- const number = (state._tag === "Open" ? state.serving.number : state.number) + 1;
164
- return {
165
- ...next(number, false, state.serving, exclusive),
166
- reply: number
167
- };
168
- }
169
- case "Retire":
170
- case "Keep": {
171
- const current = servingOf(state);
172
- if (state._tag === "Retired") return stay;
173
- if (current === void 0) return {
174
- state: { _tag: "Retired" },
175
- events: [],
176
- commands: []
177
- };
178
- return input._tag === "Retire" ? {
179
- state: { _tag: "Retired" },
180
- events: [],
181
- commands: [release(current)]
182
- } : {
183
- state: { _tag: "Retired" },
184
- events: [[current.number, new Kept()]],
185
- commands: [{
186
- _tag: "Leave",
187
- live: current
188
- }]
189
- };
190
- }
191
- }
192
- };
193
- /**
194
- * What a caller waiting for generation `target`, or for any when it is undefined, gets in
195
- * `state`; undefined while it should go on waiting.
196
- */
197
- const resolve = (state, target) => {
198
- const serve = (live) => ({
199
- _tag: "Serve",
200
- live
201
- });
202
- switch (state._tag) {
203
- case "Retired": return {
204
- _tag: "Unavailable",
205
- reason: "retired",
206
- detail: "the supervisor was retired"
207
- };
208
- case "Open": return target === void 0 || state.serving.number >= target ? serve(state.serving) : void 0;
209
- case "Opening": return target === void 0 && state.serving !== void 0 ? serve(state.serving) : void 0;
210
- case "Down":
211
- if (target === void 0 && state.serving !== void 0) return serve(state.serving);
212
- return target === void 0 || state.number >= target ? {
213
- _tag: "Unavailable",
214
- reason: "down",
215
- detail: state.detail,
216
- cause: state.cause
217
- } : void 0;
218
- }
219
- };
220
- //#endregion
221
- //#region src/Supervisor.ts
222
- /**
223
- * A browser kept open across losses and session ends, as a series of generations, each a new
224
- * browser from the same provider. Pages don't carry over from one generation to the next.
225
- *
226
- * `make` opens the first generation at once with the provider's `open`, in a scope of its own, so
227
- * a caller that stops waiting never interrupts a half-open browser. `browser` gives the current
228
- * generation; callers wait, bounded, and share one open. A loss is published at once and the next
229
- * generation opens on the `reopen` schedule, which also retries a failed open, unless the provider
230
- * deems its failure `definite`: that goes `Down` at once, with its cause. `rotate` opens the
231
- * next generation now, and so does the time `rotateBefore` ahead of a generation's `expiresAt`. A
232
- * rotation makes the next generation before it breaks the current one, unless generations are
233
- * `exclusive`, as sessions saving to one stored context must be: then the current one is released
234
- * first. `retire` stops reopening at once and releases what is open; the scope's close retires
235
- * too, unless the supervisor `keep`s: then it leaves the serving generation running, `Kept`. `states`
236
- * publishes each generation's changes, with the provider's release outcome last.
237
- *
238
- * Providers supply the specifics: `Browserbase.supervise` opens hosted sessions this way.
239
- *
240
- * @since 0.3.0
241
- */
242
- var Supervisor_exports = /* @__PURE__ */ __exportAll({
243
- Closed: () => Closed,
244
- Down: () => Down,
245
- Generation: () => Generation,
246
- GenerationState: () => GenerationState,
247
- Kept: () => Kept,
248
- Lost: () => Lost,
249
- Open: () => Open,
250
- Opening: () => Opening,
251
- Released: () => Released,
252
- Reopening: () => Reopening,
253
- Settled: () => Settled,
254
- Unavailable: () => Unavailable,
255
- Unconfirmed: () => Unconfirmed,
256
- make: () => make
257
- });
258
- /** One change in a generation's life. `at` is wall-clock epoch milliseconds from the Effect `Clock`. */
259
- var Generation = class extends Schema.Class("effect-browser/Generation")({
260
- number: Schema.Int.check(Schema.isGreaterThan(0)),
261
- at: Schema.Finite,
262
- state: GenerationState
263
- }) {};
264
- /**
265
- * No browser to give: none opened within `waitTimeout` (`opening`), the latest generation failed
266
- * to open (`down`, with what it failed with as `cause`), or the supervisor was retired.
267
- */
268
- var Unavailable = class extends Schema.TaggedError()("Unavailable", {
269
- reason: Schema.Literals([
270
- "opening",
271
- "down",
272
- "retired"
273
- ]),
274
- detail: Schema.String,
275
- cause: Schema.optional(Schema.Defect())
276
- }) {
277
- get message() {
278
- return `no browser: ${this.detail}`;
279
- }
280
- };
281
- const retired = () => new Unavailable({
282
- reason: "retired",
283
- detail: "the supervisor was retired"
284
- });
285
- const describe = (cause) => {
286
- const error = Cause.squash(cause);
287
- return Predicate.isError(error) ? error.message : String(error);
288
- };
289
- /**
290
- * Wait up to `waitTimeout` for generation `target`, or for any when it is undefined, as `state`
291
- * changes.
292
- */
293
- const waitFor = (state, waitTimeout, target) => SubscriptionRef.changes(state).pipe(Stream.map((current) => resolve(current, target)), Stream.filter(Predicate.isNotUndefined), Stream.runHead, Effect.flatMap(Option.match({
294
- onNone: () => Effect.fail(retired()),
295
- onSome: (resolution) => resolution._tag === "Serve" ? Effect.succeed(resolution.live.value.opened.browser) : Effect.fail(new Unavailable({
296
- reason: resolution.reason,
297
- detail: resolution.detail,
298
- cause: resolution.cause
299
- }))
300
- })), Effect.timeoutOrElse({
301
- duration: waitTimeout,
302
- orElse: () => Effect.fail(new Unavailable({
303
- reason: "opening",
304
- detail: `no generation opened within ${Duration.format(waitTimeout)}`
305
- }))
306
- }));
307
- /** Sleep until `before` ahead of `expiresAt`, but no sooner than halfway there from now. */
308
- const untilRotation = (expiresAt, before) => Clock.currentTimeMillis.pipe(Effect.flatMap((now) => {
309
- const left = DateTime.toEpochMillis(expiresAt) - now;
310
- return Effect.sleep(Duration.millis(Math.max(left - Duration.toMillis(before), left / 2, 0)));
311
- }));
312
- /** Supervise generations of a provider's browser for as long as the scope is open. */
313
- const make = Effect.fn("Supervisor.make")(function* (options) {
314
- const clock = yield* Clock.Clock;
315
- const context = yield* Effect.context();
316
- const own = yield* Scope.fork(yield* Effect.scope);
317
- const exclusive = options.exclusive ?? false;
318
- const definite = options.definite ?? (() => false);
319
- const reopen = options.reopen ?? Schedule.exponential("1 second").pipe(Schedule.upTo({ duration: Duration.minutes(5) }));
320
- const rotateBefore = options.rotateBefore === void 0 ? void 0 : Duration.fromInputUnsafe(options.rotateBefore);
321
- const waitTimeout = Duration.fromInputUnsafe(options.waitTimeout ?? Duration.minutes(2));
322
- const started = start();
323
- const state = yield* SubscriptionRef.make(started.state);
324
- const events = yield* PubSub.unbounded({ replay: 64 });
325
- const opening = yield* FiberHandle.make();
326
- const releases = yield* FiberMap.make();
327
- const runOpen = yield* FiberHandle.runtime(opening)();
328
- const runRelease = yield* FiberMap.runtime(releases)();
329
- const apply = (input) => SubscriptionRef.modifyEffect(state, (current) => {
330
- const step = transition(current, input, exclusive);
331
- return Effect.as(perform(step), [step.reply, step.state]);
332
- }).pipe(Effect.uninterruptible);
333
- const perform = (step) => Effect.gen(function* () {
334
- for (const [number, generation] of step.events) PubSub.publishUnsafe(events, [new Generation({
335
- number,
336
- at: clock.currentTimeMillisUnsafe(),
337
- state: generation
338
- })]);
339
- for (const command of step.commands) switch (command._tag) {
340
- case "Open":
341
- runOpen(openGeneration(command.number, command.after));
342
- break;
343
- case "Watch":
344
- yield* Effect.forkIn(Effect.provideContext(watch(command.live), context), command.live.value.scope);
345
- break;
346
- case "Release":
347
- runRelease(command.live.number, release(command.live));
348
- break;
349
- case "Leave": runRelease(command.live.number, Scope.close(command.live.value.scope, Exit.void));
350
- }
351
- });
352
- const openOnce = Effect.uninterruptibleMask((restore) => Effect.flatMap(Scope.fork(own), (scope) => restore(options.open.pipe(Scope.provide(scope), Effect.provideContext(context))).pipe(Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))), Effect.map((opened) => ({
353
- opened,
354
- scope
355
- })))));
356
- const openGeneration = (number, after) => Effect.uninterruptibleMask((restore) => {
357
- const previous = after === void 0 ? Effect.void : FiberMap.get(releases, after).pipe(Effect.flatMap(Option.match({
358
- onNone: () => Effect.void,
359
- onSome: Fiber.await
360
- })));
361
- const tries = Effect.retry(openOnce, {
362
- schedule: reopen,
363
- while: (error) => !definite(error)
364
- });
365
- return restore(previous.pipe(Effect.andThen(tries))).pipe(Effect.exit, Effect.flatMap((exit) => {
366
- if (Exit.isSuccess(exit)) return apply({
367
- _tag: "Opened",
368
- live: {
369
- number,
370
- value: exit.value
371
- }
372
- });
373
- return Cause.hasInterruptsOnly(exit.cause) ? apply({
374
- _tag: "Abandoned",
375
- number
376
- }) : apply({
377
- _tag: "Failed",
378
- number,
379
- detail: describe(exit.cause),
380
- cause: Cause.squash(exit.cause)
381
- });
382
- }));
383
- });
384
- const watch = (live) => {
385
- const { browser } = live.value.opened;
386
- const loss = browser.disconnected.pipe(Effect.flatMap((cause) => apply({
387
- _tag: "Lost",
388
- number: live.number,
389
- cause
390
- })));
391
- const rotation = browser.expiresAt === void 0 || rotateBefore === void 0 ? Effect.void : untilRotation(browser.expiresAt, rotateBefore).pipe(Effect.andThen(apply({
392
- _tag: "Rotate",
393
- due: live.number
394
- })));
395
- return Effect.all([loss, rotation], {
396
- concurrency: 2,
397
- discard: true
398
- });
399
- };
400
- const release = (live) => (live.value.opened.release ?? Effect.succeed(new Settled())).pipe(Effect.catchCause((cause) => Effect.succeed(new Unconfirmed({ detail: `the release failed: ${describe(cause)}` }))), Effect.ensuring(Scope.close(live.value.scope, Exit.void)), Effect.flatMap((released) => apply({
401
- _tag: "Released",
402
- number: live.number,
403
- released
404
- })));
405
- const end = yield* Effect.cached(PubSub.publish(events, Exit.void));
406
- const stop = (input) => apply(input).pipe(Effect.andThen(FiberHandle.clear(opening)), Effect.andThen(FiberMap.awaitEmpty(releases)), Effect.andThen(end), Effect.asVoid);
407
- const retire = yield* Effect.cached(stop({ _tag: "Retire" }));
408
- yield* Effect.addFinalizer(() => options.keep === true ? stop({ _tag: "Keep" }) : retire);
409
- yield* perform(started);
410
- return {
411
- browser: waitFor(state, waitTimeout, void 0),
412
- states: Stream.fromPubSubTake(events),
413
- rotate: apply({ _tag: "Rotate" }).pipe(Effect.flatMap((target) => target === void 0 ? Effect.fail(retired()) : waitFor(state, waitTimeout, target))),
414
- retire
415
- };
416
- });
417
- //#endregion
418
- export { Closed as a, Kept as c, Opening as d, Released as f, Unconfirmed as h, make as i, Lost as l, Settled as m, Supervisor_exports as n, Down as o, Reopening as p, Unavailable as r, GenerationState as s, Generation as t, Open as u };
419
-
420
- //# sourceMappingURL=Supervisor-BtEG93gR.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Supervisor-BtEG93gR.mjs","names":["Lifecycle.GenerationState","Lifecycle.resolve","Lifecycle.start","Lifecycle.transition","Lifecycle.Settled","Lifecycle.Unconfirmed"],"sources":["../src/internal/supervisor/lifecycle.ts","../src/Supervisor.ts"],"sourcesContent":["/**\n * A supervisor's life as one state and one transition function, and the generation states it\n * publishes. The transition has no effects: `Supervisor.make` applies each input under one lock,\n * publishes the events in order and runs the commands, so the rules here are tested alone.\n */\nimport { Schema } from \"effect\";\n\nimport { DisconnectCause } from \"../../BrowserEvent.ts\";\n\n/** The provider confirmed that the generation's browser ended. */\nexport class Settled extends Schema.TaggedClass<Settled>()(\"Settled\", {}) {}\n\n/** The provider could not confirm the end by its deadline, so the browser may still run, and bill. */\nexport class Unconfirmed extends Schema.TaggedClass<Unconfirmed>()(\"Unconfirmed\", {\n detail: Schema.String,\n}) {}\n\nexport const Released = Schema.Union([Settled, Unconfirmed]);\n\nexport type Released = typeof Released.Type;\n\n/** Opening, but not after a loss: the first generation, a rotation, or the one after `Down`. */\nexport class Opening extends Schema.TaggedClass<Opening>()(\"Opening\", {}) {}\n\n/** Opening after the generation before it was lost. */\nexport class Reopening extends Schema.TaggedClass<Reopening>()(\"Reopening\", {}) {}\n\n/** Open: `browser` gives this generation until the next one opens. */\nexport class Open extends Schema.TaggedClass<Open>()(\"Open\", {}) {}\n\n/** Lost: its connection dropped, or its provider ended its session, as `cause` says. */\nexport class Lost extends Schema.TaggedClass<Lost>()(\"Lost\", {\n cause: DisconnectCause,\n}) {}\n\n/**\n * It never opened: its last try failed with `cause`, which the provider deems definite, or after\n * which the reopen schedule gave up.\n */\nexport class Down extends Schema.TaggedClass<Down>()(\"Down\", {\n detail: Schema.String,\n cause: Schema.Defect(),\n}) {}\n\n/** It ended. `released` says how its release went; one retired while opening has none. */\nexport class Closed extends Schema.TaggedClass<Closed>()(\"Closed\", {\n released: Schema.optional(Released),\n}) {}\n\n/**\n * It was serving as the supervisor's scope closed, and was left running, not released: its scope\n * closed, and its provider runs it on, and bills, until something adopts and releases it.\n */\nexport class Kept extends Schema.TaggedClass<Kept>()(\"Kept\", {}) {}\n\nexport const GenerationState = Schema.Union([Opening, Reopening, Open, Lost, Down, Closed, Kept]);\n\nexport type GenerationState = typeof GenerationState.Type;\n\n/** A generation that opened: its number, and what the runtime keeps to serve and end it. */\nexport interface Live<A> {\n readonly number: number;\n readonly value: A;\n}\n\n/**\n * At most one generation opens and at most one serves. Both do while a rotation makes the next\n * before it breaks the current, and `Down` keeps serving one that a rotation failed to replace.\n */\nexport type State<A> =\n | { readonly _tag: \"Opening\"; readonly number: number; readonly serving: Live<A> | undefined }\n | { readonly _tag: \"Open\"; readonly serving: Live<A> }\n | {\n readonly _tag: \"Down\";\n readonly number: number;\n readonly detail: string;\n readonly cause: unknown;\n readonly serving: Live<A> | undefined;\n }\n | { readonly _tag: \"Retired\" };\n\nexport type Input<A> =\n | { readonly _tag: \"Opened\"; readonly live: Live<A> }\n /** The open of `number` failed for good. */\n | {\n readonly _tag: \"Failed\";\n readonly number: number;\n readonly detail: string;\n readonly cause: unknown;\n }\n /** The open of `number` was stopped, as on retiring, before it opened. */\n | { readonly _tag: \"Abandoned\"; readonly number: number }\n | { readonly _tag: \"Lost\"; readonly number: number; readonly cause: DisconnectCause }\n /** A caller asks for the next generation, or the rotation time of `due` came. */\n | { readonly _tag: \"Rotate\"; readonly due?: number | undefined }\n | { readonly _tag: \"Retire\" }\n /** Stop as `Retire` does, but leave the serving generation running. */\n | { readonly _tag: \"Keep\" }\n | { readonly _tag: \"Released\"; readonly number: number; readonly released: Released };\n\nexport type Command<A> =\n /** Open `number`, after the release of `after` has finished. */\n | { readonly _tag: \"Open\"; readonly number: number; readonly after: number | undefined }\n /** Watch a generation that opened for its loss and its rotation time. */\n | { readonly _tag: \"Watch\"; readonly live: Live<A> }\n | { readonly _tag: \"Release\"; readonly live: Live<A> }\n /** Close its scope without asking its provider to release it. */\n | { readonly _tag: \"Leave\"; readonly live: Live<A> };\n\nexport interface Step<A> {\n readonly state: State<A>;\n /** Generation numbers and their new states, to publish in this order. */\n readonly events: ReadonlyArray<readonly [number, GenerationState]>;\n readonly commands: ReadonlyArray<Command<A>>;\n /** For `Rotate`, the generation to wait for, unless retired. */\n readonly reply?: number | undefined;\n}\n\nexport const start = <A>(): Step<A> => ({\n state: { _tag: \"Opening\", number: 1, serving: undefined },\n events: [[1, new Opening()]],\n commands: [{ _tag: \"Open\", number: 1, after: undefined }],\n});\n\nconst servingOf = <A>(state: State<A>) => (state._tag === \"Retired\" ? undefined : state.serving);\n\n/** The state after `input`, with the events to publish and the commands to run. */\nexport const transition = <A>(state: State<A>, input: Input<A>, exclusive: boolean): Step<A> => {\n const release = (live: Live<A>): Command<A> => ({ _tag: \"Release\", live });\n const stay: Step<A> = { state, events: [], commands: [] };\n\n /**\n * Open `number`, ending `current` now if it `ends`; exclusive generations open only once its\n * release has finished. Otherwise `current` serves until the next one opens.\n */\n const next = (\n number: number,\n reopen: boolean,\n current: Live<A> | undefined,\n ends: boolean,\n ): Step<A> => ({\n state: { _tag: \"Opening\", number, serving: ends ? undefined : current },\n events: [[number, reopen ? new Reopening() : new Opening()]],\n commands: [\n ...(ends && current !== undefined ? [release(current)] : []),\n { _tag: \"Open\", number, after: ends && exclusive ? current?.number : undefined },\n ],\n });\n\n switch (input._tag) {\n case \"Opened\": {\n const { live } = input;\n\n // A generation nobody waits for any more, as after `Retire`, is released at once.\n if (state._tag !== \"Opening\" || state.number !== live.number)\n return { ...stay, commands: [release(live)] };\n\n return {\n state: { _tag: \"Open\", serving: live },\n events: [[live.number, new Open()]],\n commands: [\n { _tag: \"Watch\", live },\n ...(state.serving === undefined ? [] : [release(state.serving)]),\n ],\n };\n }\n case \"Failed\": {\n const { number, detail, cause } = input;\n const events = [[number, new Down({ detail, cause })] as const];\n\n if (state._tag !== \"Opening\" || state.number !== input.number) return { ...stay, events };\n\n return {\n state: { _tag: \"Down\", number, detail, cause, serving: state.serving },\n events,\n commands: [],\n };\n }\n case \"Abandoned\":\n return { ...stay, events: [[input.number, new Closed({})]] };\n case \"Released\":\n return { ...stay, events: [[input.number, new Closed({ released: input.released })]] };\n case \"Lost\": {\n const lost = servingOf(state);\n\n if (state._tag === \"Retired\" || lost?.number !== input.number) return stay;\n const events = [[lost.number, new Lost({ cause: input.cause })] as const];\n\n // A rotation already opening the next generation carries on without the lost one.\n if (state._tag === \"Opening\")\n return { state: { ...state, serving: undefined }, events, commands: [release(lost)] };\n\n const reopened = next(\n (state._tag === \"Open\" ? lost.number : state.number) + 1,\n true,\n lost,\n true,\n );\n\n return { ...reopened, events: [...events, ...reopened.events] };\n }\n case \"Rotate\": {\n if (state._tag === \"Retired\") return stay;\n // A rotation time comes only for the generation still serving with nothing opening.\n if (input.due !== undefined && (state._tag !== \"Open\" || state.serving.number !== input.due))\n return stay;\n if (state._tag === \"Opening\") return { ...stay, reply: state.number };\n const number = (state._tag === \"Open\" ? state.serving.number : state.number) + 1;\n\n return { ...next(number, false, state.serving, exclusive), reply: number };\n }\n case \"Retire\":\n case \"Keep\": {\n const current = servingOf(state);\n\n if (state._tag === \"Retired\") return stay;\n if (current === undefined) return { state: { _tag: \"Retired\" }, events: [], commands: [] };\n\n return input._tag === \"Retire\"\n ? { state: { _tag: \"Retired\" }, events: [], commands: [release(current)] }\n : {\n state: { _tag: \"Retired\" },\n events: [[current.number, new Kept()]],\n commands: [{ _tag: \"Leave\", live: current }],\n };\n }\n }\n};\n\nexport type Resolution<A> =\n | { readonly _tag: \"Serve\"; readonly live: Live<A> }\n | {\n readonly _tag: \"Unavailable\";\n readonly reason: \"down\" | \"retired\";\n readonly detail: string;\n readonly cause?: unknown;\n };\n\n/**\n * What a caller waiting for generation `target`, or for any when it is undefined, gets in\n * `state`; undefined while it should go on waiting.\n */\nexport const resolve = <A>(\n state: State<A>,\n target: number | undefined,\n): Resolution<A> | undefined => {\n const serve = (live: Live<A>) => ({ _tag: \"Serve\" as const, live });\n\n switch (state._tag) {\n case \"Retired\":\n return { _tag: \"Unavailable\", reason: \"retired\", detail: \"the supervisor was retired\" };\n case \"Open\":\n return target === undefined || state.serving.number >= target\n ? serve(state.serving)\n : undefined;\n case \"Opening\":\n return target === undefined && state.serving !== undefined ? serve(state.serving) : undefined;\n case \"Down\":\n if (target === undefined && state.serving !== undefined) return serve(state.serving);\n\n return target === undefined || state.number >= target\n ? { _tag: \"Unavailable\", reason: \"down\", detail: state.detail, cause: state.cause }\n : undefined;\n }\n};\n","/**\n * A browser kept open across losses and session ends, as a series of generations, each a new\n * browser from the same provider. Pages don't carry over from one generation to the next.\n *\n * `make` opens the first generation at once with the provider's `open`, in a scope of its own, so\n * a caller that stops waiting never interrupts a half-open browser. `browser` gives the current\n * generation; callers wait, bounded, and share one open. A loss is published at once and the next\n * generation opens on the `reopen` schedule, which also retries a failed open, unless the provider\n * deems its failure `definite`: that goes `Down` at once, with its cause. `rotate` opens the\n * next generation now, and so does the time `rotateBefore` ahead of a generation's `expiresAt`. A\n * rotation makes the next generation before it breaks the current one, unless generations are\n * `exclusive`, as sessions saving to one stored context must be: then the current one is released\n * first. `retire` stops reopening at once and releases what is open; the scope's close retires\n * too, unless the supervisor `keep`s: then it leaves the serving generation running, `Kept`. `states`\n * publishes each generation's changes, with the provider's release outcome last.\n *\n * Providers supply the specifics: `Browserbase.supervise` opens hosted sessions this way.\n *\n * @since 0.3.0\n */\nimport {\n Cause,\n Clock,\n DateTime,\n Duration,\n Effect,\n Exit,\n Fiber,\n FiberHandle,\n FiberMap,\n Option,\n Predicate,\n PubSub,\n Schedule,\n Schema,\n Scope,\n Stream,\n SubscriptionRef,\n type Take,\n} from \"effect\";\n\nimport type * as Browser from \"./Browser.ts\";\nimport * as Lifecycle from \"./internal/supervisor/lifecycle.ts\";\n\nexport {\n Closed,\n Down,\n GenerationState,\n Kept,\n Lost,\n Open,\n Opening,\n Released,\n Reopening,\n Settled,\n Unconfirmed,\n} from \"./internal/supervisor/lifecycle.ts\";\n\n/** One change in a generation's life. `at` is wall-clock epoch milliseconds from the Effect `Clock`. */\nexport class Generation extends Schema.Class<Generation>(\"effect-browser/Generation\")({\n number: Schema.Int.check(Schema.isGreaterThan(0)),\n at: Schema.Finite,\n state: Lifecycle.GenerationState,\n}) {}\n\n/**\n * No browser to give: none opened within `waitTimeout` (`opening`), the latest generation failed\n * to open (`down`, with what it failed with as `cause`), or the supervisor was retired.\n */\nexport class Unavailable extends Schema.TaggedError<Unavailable>()(\"Unavailable\", {\n reason: Schema.Literals([\"opening\", \"down\", \"retired\"]),\n detail: Schema.String,\n cause: Schema.optional(Schema.Defect()),\n}) {\n override get message() {\n return `no browser: ${this.detail}`;\n }\n}\n\n/** One generation, as a provider opened it in the scope the supervisor gave it. */\nexport interface Opened {\n readonly browser: Browser.Service;\n /**\n * End the generation, and say whether the provider confirmed its end. The supervisor asks it\n * before it closes the generation's scope; without it, closing the scope ends the generation,\n * which counts as `Settled`.\n */\n readonly release?: Effect.Effect<Lifecycle.Released> | undefined;\n}\n\nexport interface Options<E, R> {\n /** Opens one generation in the scope it is given. */\n readonly open: Effect.Effect<Opened, E, R>;\n /** When to try a failed open again. Defaults to exponential from 1 second, for 5 minutes. */\n readonly reopen?: Schedule.Schedule<unknown, E> | undefined;\n /**\n * Failures no new try mends, such as a refused key: an open that fails so is `Down` at once.\n * Defaults to none.\n */\n readonly definite?: ((error: E) => boolean) | undefined;\n /**\n * Rotate this long ahead of a generation's `expiresAt`, but no sooner than halfway through its\n * life. Without it, a generation's end is a loss.\n */\n readonly rotateBefore?: Duration.Input | undefined;\n /** Generations must not overlap: a rotation releases the current one before it opens the next. */\n readonly exclusive?: boolean | undefined;\n /**\n * Closing the scope leaves the serving generation running, `Kept`: it closes the generation's\n * scope but never asks `release`. For providers whose scope only disconnects, such as\n * `Browserbase.supervise` with `keep`. `retire` still releases it.\n */\n readonly keep?: boolean | undefined;\n /** How long `browser` and `rotate` wait for a generation to open. Defaults to 2 minutes. */\n readonly waitTimeout?: Duration.Input | undefined;\n}\n\nexport interface Supervisor {\n /** The current generation's browser, waiting up to `waitTimeout` while none is open. */\n readonly browser: Effect.Effect<Browser.Service, Unavailable>;\n /** Each generation's changes, in order. A new reader first gets the latest 64; ends on retiring. */\n readonly states: Stream.Stream<Generation>;\n /** Open the next generation now, or join the one opening, and wait for it. */\n readonly rotate: Effect.Effect<Browser.Service, Unavailable>;\n /** Stop opening at once, release every generation, and wait until each release has finished. */\n readonly retire: Effect.Effect<void>;\n}\n\ninterface Held {\n readonly opened: Opened;\n readonly scope: Scope.Closeable;\n}\n\nconst retired = () => new Unavailable({ reason: \"retired\", detail: \"the supervisor was retired\" });\n\nconst describe = (cause: Cause.Cause<unknown>) => {\n const error = Cause.squash(cause);\n\n return Predicate.isError(error) ? error.message : String(error);\n};\n\n/**\n * Wait up to `waitTimeout` for generation `target`, or for any when it is undefined, as `state`\n * changes.\n */\nconst waitFor = <A extends { readonly opened: Opened }>(\n state: SubscriptionRef.SubscriptionRef<Lifecycle.State<A>>,\n waitTimeout: Duration.Duration,\n target: number | undefined,\n) =>\n SubscriptionRef.changes(state).pipe(\n Stream.map((current) => Lifecycle.resolve(current, target)),\n Stream.filter(Predicate.isNotUndefined),\n Stream.runHead,\n // The state's changes never end, so the first resolution always comes.\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.fail(retired()),\n onSome: (resolution) =>\n resolution._tag === \"Serve\"\n ? Effect.succeed(resolution.live.value.opened.browser)\n : Effect.fail(\n new Unavailable({\n reason: resolution.reason,\n detail: resolution.detail,\n cause: resolution.cause,\n }),\n ),\n }),\n ),\n Effect.timeoutOrElse({\n duration: waitTimeout,\n orElse: () =>\n Effect.fail(\n new Unavailable({\n reason: \"opening\",\n detail: `no generation opened within ${Duration.format(waitTimeout)}`,\n }),\n ),\n }),\n );\n\n/** Sleep until `before` ahead of `expiresAt`, but no sooner than halfway there from now. */\nconst untilRotation = (expiresAt: DateTime.Utc, before: Duration.Duration) =>\n Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => {\n const left = DateTime.toEpochMillis(expiresAt) - now;\n\n return Effect.sleep(Duration.millis(Math.max(left - Duration.toMillis(before), left / 2, 0)));\n }),\n );\n\n/** Supervise generations of a provider's browser for as long as the scope is open. */\nexport const make = Effect.fn(\"Supervisor.make\")(function* <E, R>(\n options: Options<E, R>,\n): Effect.fn.Return<Supervisor, never, Scope.Scope | Exclude<R, Scope.Scope>> {\n const clock = yield* Clock.Clock;\n const context = yield* Effect.context<Exclude<R, Scope.Scope>>();\n const own = yield* Scope.fork(yield* Effect.scope);\n const exclusive = options.exclusive ?? false;\n const definite = options.definite ?? (() => false);\n\n const reopen: Schedule.Schedule<unknown, E> =\n options.reopen ??\n Schedule.exponential(\"1 second\").pipe(Schedule.upTo({ duration: Duration.minutes(5) }));\n\n const rotateBefore =\n options.rotateBefore === undefined ? undefined : Duration.fromInputUnsafe(options.rotateBefore);\n\n const waitTimeout = Duration.fromInputUnsafe(options.waitTimeout ?? Duration.minutes(2));\n const started = Lifecycle.start<Held>();\n const state = yield* SubscriptionRef.make(started.state);\n const events = yield* PubSub.unbounded<Take.Take<Generation>>({ replay: 64 });\n const opening = yield* FiberHandle.make<unknown, never>();\n const releases = yield* FiberMap.make<number, unknown, never>();\n const runOpen = yield* FiberHandle.runtime(opening)();\n const runRelease = yield* FiberMap.runtime(releases)();\n\n // Each input changes the state under one lock, which also publishes its events and starts its\n // work, so neither can be reordered against another input's.\n const apply = (input: Lifecycle.Input<Held>): Effect.Effect<number | undefined> =>\n SubscriptionRef.modifyEffect(state, (current) => {\n const step = Lifecycle.transition(current, input, exclusive);\n\n return Effect.as(perform(step), [step.reply, step.state] as const);\n }).pipe(Effect.uninterruptible);\n\n const perform = (step: Lifecycle.Step<Held>) =>\n Effect.gen(function* () {\n for (const [number, generation] of step.events)\n PubSub.publishUnsafe(events, [\n new Generation({ number, at: clock.currentTimeMillisUnsafe(), state: generation }),\n ]);\n for (const command of step.commands)\n switch (command._tag) {\n case \"Open\":\n runOpen(openGeneration(command.number, command.after));\n break;\n case \"Watch\":\n yield* Effect.forkIn(\n Effect.provideContext(watch(command.live), context),\n command.live.value.scope,\n );\n break;\n case \"Release\":\n runRelease(command.live.number, release(command.live));\n break;\n case \"Leave\":\n runRelease(command.live.number, Scope.close(command.live.value.scope, Exit.void));\n }\n });\n\n const openOnce = Effect.uninterruptibleMask((restore) =>\n Effect.flatMap(Scope.fork(own), (scope) =>\n restore(options.open.pipe(Scope.provide(scope), Effect.provideContext(context))).pipe(\n Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),\n Effect.map((opened): Held => ({ opened, scope })),\n ),\n ),\n );\n\n // Retiring interrupts the open between tries or during one; the provider releases what an\n // interrupted try had made, as its scope closes.\n const openGeneration = (number: number, after: number | undefined) =>\n Effect.uninterruptibleMask((restore) => {\n const previous =\n after === undefined\n ? Effect.void\n : FiberMap.get(releases, after).pipe(\n Effect.flatMap(Option.match({ onNone: () => Effect.void, onSome: Fiber.await })),\n );\n\n const tries = Effect.retry(openOnce, {\n schedule: reopen,\n while: (error) => !definite(error),\n });\n\n return restore(previous.pipe(Effect.andThen(tries))).pipe(\n Effect.exit,\n Effect.flatMap((exit) => {\n if (Exit.isSuccess(exit))\n return apply({ _tag: \"Opened\", live: { number, value: exit.value } });\n\n return Cause.hasInterruptsOnly(exit.cause)\n ? apply({ _tag: \"Abandoned\", number })\n : apply({\n _tag: \"Failed\",\n number,\n detail: describe(exit.cause),\n cause: Cause.squash(exit.cause),\n });\n }),\n );\n });\n\n // A generation's own release loses its browser too, which the transition ignores.\n const watch = (live: Lifecycle.Live<Held>) => {\n const { browser } = live.value.opened;\n\n const loss = browser.disconnected.pipe(\n Effect.flatMap((cause) => apply({ _tag: \"Lost\", number: live.number, cause })),\n );\n\n const rotation =\n browser.expiresAt === undefined || rotateBefore === undefined\n ? Effect.void\n : untilRotation(browser.expiresAt, rotateBefore).pipe(\n Effect.andThen(apply({ _tag: \"Rotate\", due: live.number })),\n );\n\n return Effect.all([loss, rotation], { concurrency: 2, discard: true });\n };\n\n // The provider releases before the scope closes, so what the scope holds, such as a stored\n // context's lease, goes only once the release has reported.\n const release = (live: Lifecycle.Live<Held>) =>\n (live.value.opened.release ?? Effect.succeed(new Lifecycle.Settled())).pipe(\n Effect.catchCause((cause) =>\n Effect.succeed(\n new Lifecycle.Unconfirmed({ detail: `the release failed: ${describe(cause)}` }),\n ),\n ),\n Effect.ensuring(Scope.close(live.value.scope, Exit.void)),\n Effect.flatMap((released) => apply({ _tag: \"Released\", number: live.number, released })),\n );\n\n const end = yield* Effect.cached(PubSub.publish(events, Exit.void));\n\n // Stop at once, end or leave what is open, and wait for every release.\n const stop = (input: Lifecycle.Input<Held>) =>\n apply(input).pipe(\n Effect.andThen(FiberHandle.clear(opening)),\n Effect.andThen(FiberMap.awaitEmpty(releases)),\n Effect.andThen(end),\n Effect.asVoid,\n );\n\n const retire = yield* Effect.cached(stop({ _tag: \"Retire\" }));\n\n yield* Effect.addFinalizer(() => (options.keep === true ? stop({ _tag: \"Keep\" }) : retire));\n yield* perform(started);\n\n return {\n browser: waitFor(state, waitTimeout, undefined),\n states: Stream.fromPubSubTake(events),\n rotate: apply({ _tag: \"Rotate\" }).pipe(\n Effect.flatMap((target) =>\n target === undefined ? Effect.fail(retired()) : waitFor(state, waitTimeout, target),\n ),\n ),\n retire,\n } satisfies Supervisor;\n});\n"],"mappings":";;;;;;;;;;AAUA,IAAa,UAAb,cAA6B,OAAO,YAAqB,CAAC,CAAC,WAAW,CAAC,CAAC,CAA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AK,IAAI,CAAC,GACxD,OAAO,SAAS,aAAa,MAAM;EAAE,MAAM;EAAY,QAAQ,KAAK;EAAQ;CAAS,CAAC,CAAC,CACzF;CAEF,MAAM,MAAM,OAAO,OAAO,OAAO,OAAO,QAAQ,QAAQ,KAAK,IAAI,CAAC;CAGlE,MAAM,QAAQ,UACZ,MAAM,KAAK,CAAC,CAAC,KACX,OAAO,QAAQ,YAAY,MAAM,OAAO,CAAC,GACzC,OAAO,QAAQ,SAAS,WAAW,QAAQ,CAAC,GAC5C,OAAO,QAAQ,GAAG,GAClB,OAAO,MACT;CAEF,MAAM,SAAS,OAAO,OAAO,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC,CAAC;CAE5D,OAAO,OAAO,mBAAoB,QAAQ,SAAS,OAAO,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,MAAO;CAC1F,OAAO,QAAQ,OAAO;CAEtB,OAAO;EACL,SAAS,QAAQ,OAAO,aAAa,KAAA,CAAS;EAC9C,QAAQ,OAAO,eAAe,MAAM;EACpC,QAAQ,MAAM,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC,KAChC,OAAO,SAAS,WACd,WAAW,KAAA,IAAY,OAAO,KAAK,QAAQ,CAAC,IAAI,QAAQ,OAAO,aAAa,MAAM,CACpF,CACF;EACA;CACF;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-DAYjATgC.mjs","names":["Url.redactWithin","Lane.make"],"sources":["../src/internal/page/context.ts"],"sourcesContent":["/**\n * What a page's parts share: the browser state they act on, the page's own lane, pointer and\n * clock, and how they call the browser and report its failures. The assembly in `page.ts` builds\n * one context per page.\n */\nimport {\n Clock,\n Context,\n Duration,\n Effect,\n Fiber,\n MutableRef,\n Option,\n Schema,\n type Scope,\n} from \"effect\";\nimport type { CDPSession, Page as PlaywrightPage } from \"playwright-core\";\n\nimport type { CaptureSource } from \"../../Browser.ts\";\nimport { BrowserError, Closed, Failed, type Reason, Timeout } from \"../../BrowserError.ts\";\nimport type { BrowserEvent } from \"../../BrowserEvent.ts\";\nimport type { InputGuard, Point } from \"../../Page.ts\";\nimport type * as BrowserClock from \"../pictures/clock.ts\";\nimport * as Lane from \"./lane.ts\";\nimport type { Openings } from \"./openings.ts\";\nimport * as Url from \"./url.ts\";\n\n/** Why a page is gone. */\nexport type ClosedCause = Closed[\"cause\"];\n\n/** What every page of a browser shares, from its options. */\nexport interface Settings {\n readonly actionTimeout: Duration.Duration;\n readonly policyTimeout: Duration.Duration;\n readonly navigationTimeout: Duration.Duration;\n /** How long screencast frames stay in `recentFrames`, measured back from the newest. */\n readonly frameHistory: Duration.Duration;\n readonly guard: InputGuard | undefined;\n}\n\nexport interface MakeOptions {\n /** The page's CDP target id, which is also its main frame's id. */\n readonly id: string;\n /** The id of the browser's session, which its frames carry. */\n readonly session: string;\n /** The page's address when the browser began tracking it. */\n readonly url: string;\n readonly playwright: PlaywrightPage;\n readonly cdp: CDPSession;\n /** A call's reply, or a failure as for a closed page once the browser is lost first. */\n readonly untilLost: <A>(reply: Promise<A>) => Promise<A>;\n readonly settings: Settings;\n readonly clock: Clock.Clock;\n /** The browser's epoch mapping: its first capture measures it, and later ones renew it. */\n readonly mapping: BrowserClock.Mapping;\n readonly publish: (event: BrowserEvent) => number;\n /** This page's retained events, oldest first. */\n readonly recentEvents: Effect.Effect<ReadonlyArray<BrowserEvent>>;\n /** Registration of the actual popups this page's current input opened. */\n readonly openings: Openings;\n /** Succeeds once the page's own session holds focus emulation, which keeps it painting behind. */\n readonly focused: Effect.Effect<void, BrowserError>;\n /** Succeeds once the page's own session has the Page domain on, so it sees every later commit. */\n readonly paging: (operation: string) => Effect.Effect<void, BrowserError>;\n /** Why the page is gone, once it is: its browser's loss, else its own close or crash. */\n readonly closedBy: () => ClosedCause;\n /** Where the page's screencast runs, if not on its own session. */\n readonly capture?: CaptureSource | undefined;\n}\n\nconst messageOf = (cause: unknown): string =>\n cause instanceof Error ? cause.message : typeof cause === \"string\" ? cause : \"unknown error\";\n\nconst closedPattern =\n /has been closed|Target closed|Session closed|browser has disconnected|Target page, context or browser/i;\n\n/**\n * Map a Playwright or protocol failure to a reason, `Closed` with `closed` as its cause for a page\n * or browser that is gone. A call that gives Playwright a timeout passes the same bound, so its\n * `Timeout` reports it; without one, Playwright's own message stays.\n */\nexport const reasonOf = (\n cause: unknown,\n timeoutMillis?: number,\n closed: ClosedCause = \"connection\",\n): Reason => {\n const message = messageOf(cause);\n\n if (closedPattern.test(message)) return new Closed({ cause: closed });\n if (cause instanceof Error && cause.name === \"TimeoutError\" && timeoutMillis !== undefined)\n return new Timeout({ millis: timeoutMillis });\n const line = message.split(\"\\n\")[0] ?? message;\n\n return new Failed({ detail: Url.redactWithin(line.replace(/^[\\w.]+: /, \"\")) });\n};\n\n/**\n * One Playwright or protocol call, failing undispatched. A closed page says why it is gone as the\n * browser knows then: the library's own calls fail with the browser's loss, and Playwright fails\n * its calls on a dropped connection after reporting the context closed.\n */\nexport const call = <A>(\n operation: string,\n run: () => Promise<A>,\n closedBy: () => ClosedCause,\n timeoutMillis?: number,\n) =>\n Effect.tryPromise({\n try: run,\n catch: (cause) => undispatched(operation, reasonOf(cause, timeoutMillis, closedBy())),\n });\n\nexport const contextGone = (error: BrowserError) =>\n error.reason._tag === \"Failed\" &&\n /Cannot find context|Execution context was destroyed|__effectBrowser|Inspected target navigated/i.test(\n error.reason.detail,\n );\n\n/**\n * What a page operation spent on the page's own protocol session: its calls, the bytes of their\n * parameters and results, and how long at least one of them awaited its reply. An operation inside\n * another counts toward both.\n */\ninterface Cost {\n readonly enclosing: Cost | undefined;\n calls: number;\n bytesOut: number;\n bytesIn: number;\n waitedMillis: number;\n awaiting: number;\n awaitingSince: number;\n}\n\n/** The cost of the page operation the current fiber runs, if any. */\nconst CurrentCost = Context.Reference<Cost | undefined>(\n \"effect-browser/internal/page/CurrentCost\",\n {\n defaultValue: () => undefined,\n },\n);\n\n// A message's size on the wire, give or take its envelope.\nconst sizeOf = (value: unknown) =>\n value === undefined ? 0 : Buffer.byteLength(JSON.stringify(value));\n\n/** A failure of `operation` before any of its input reached the browser. */\nexport const undispatched = (operation: string, reason: Reason) =>\n new BrowserError({ operation, reason, dispatched: false });\n\nexport const failWith = (operation: string, reason: Reason) =>\n Effect.fail(undispatched(operation, reason));\n\nexport const decodeWith =\n <A>(operation: string, schema: Schema.Codec<A, unknown>) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError((error) => undispatched(operation, new Failed({ detail: error.message }))),\n );\n\nexport const make = (options: MakeOptions, scope: Scope.Scope) => {\n const { id, clock } = options;\n const now = () => Number(clock.monotonicTimeNanosUnsafe()) / 1e6;\n // Deadlines and pacing guard the page's lane, so page operations run on the owner's clock; a\n // caller's clock, such as a TestClock, cannot stall or stretch them.\n const owned = Effect.provideService(Clock.Clock, clock);\n\n // This page's spans name it and report what the operation cost on the protocol. Fine-grained\n // ones carry a level below the default Info, so an application keeps only the coarse ones by\n // raising `Tracer.MinimumTraceLevel`.\n const span =\n (name: string, attributes: Record<string, unknown> = {}, level?: \"Debug\" | \"Trace\") =>\n <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const cost: Cost = {\n enclosing: yield* CurrentCost,\n calls: 0,\n bytesOut: 0,\n bytesIn: 0,\n waitedMillis: 0,\n awaiting: 0,\n awaitingSince: 0,\n };\n\n return yield* effect.pipe(\n Effect.provideService(CurrentCost, cost),\n Effect.ensuring(\n Effect.suspend(() =>\n Effect.annotateCurrentSpan({\n calls: cost.calls,\n bytesOut: cost.bytesOut,\n bytesIn: cost.bytesIn,\n waitedMillis: Math.round(cost.waitedMillis * 10) / 10,\n }),\n ),\n ),\n );\n }).pipe(\n Effect.withSpan(\n name,\n { attributes: { page: id, ...attributes }, ...(level === undefined ? {} : { level }) },\n { captureStackTrace: false },\n ),\n );\n\n // Every call on the page's own protocol session, counted into the operation that sends it and\n // the operations around that one. It is looked up when the call is sent, so input pipelined\n // from inside an operation counts toward it too.\n const send: CDPSession[\"send\"] = (method, params) => {\n const cost = Fiber.getCurrent()?.getRef(CurrentCost);\n const sentAt = now();\n const bytesOut = sizeOf(params);\n\n for (let each = cost; each !== undefined; each = each.enclosing) {\n each.calls++;\n each.bytesOut += bytesOut;\n if (each.awaiting++ === 0) each.awaitingSince = sentAt;\n }\n const reply = options.untilLost(options.cdp.send(method, params));\n\n if (cost === undefined) return reply;\n\n const settle = (bytesIn: number) => {\n const at = now();\n\n for (let each: Cost | undefined = cost; each !== undefined; each = each.enclosing) {\n each.bytesIn += bytesIn;\n if (--each.awaiting === 0) each.waitedMillis += at - each.awaitingSince;\n }\n };\n\n return reply.then(\n (result) => {\n settle(sizeOf(result));\n\n return result;\n },\n (cause: unknown) => {\n settle(0);\n\n return Promise.reject(cause);\n },\n );\n };\n\n // Every protocol or Playwright call. Errors are undispatched here; `perform` marks them\n // dispatched once input has gone out.\n const native = <A>(operation: string, run: () => Promise<A>, timeoutMillis?: number) =>\n call(operation, run, options.closedBy, timeoutMillis);\n\n /** Fail with `Timeout` once `duration` has passed, the action timeout unless another is given. */\n const within =\n (operation: string, duration: Duration.Input = options.settings.actionTimeout) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.timeoutOrElse(effect, {\n duration,\n orElse: () => failWith(operation, new Timeout({ millis: Duration.toMillis(duration) })),\n });\n\n // The latest submitted input or page change. A read that must follow it waits for the action in\n // flight, so only paint from after its latest input is current. An action ends after its input\n // was handled, so if that input changed the page, newer paint follows; a lost final paint is\n // bounded by recency instead. Paint from before the current document began, when the page's own\n // session saw the main frame commit it, shows a page the tab has left, so no read reuses it,\n // whatever it asks.\n const activity = { inputAt: 0, documentAt: Number.NEGATIVE_INFINITY };\n\n const noteInput = () => {\n activity.inputAt = Math.max(activity.inputAt, now());\n };\n\n const lane = Lane.make({\n now,\n actionTimeout: options.settings.actionTimeout,\n documentAt: () => activity.documentAt,\n gone: (operation) => undispatched(operation, new Closed({ cause: options.closedBy() })),\n scope,\n });\n\n // Where this page's latest move left its pointer, which is where its next plain glide starts and\n // where a held button is released. Its lane orders the page's input, and Chromium keeps a\n // pointer per page too.\n const pointer = MutableRef.make(Option.none<Point>());\n\n // Named, so that the declarations of what holds it need not spell out Playwright's protocol types.\n const protocol: Pick<CDPSession, \"send\"> = { send };\n\n return {\n ...options,\n lane,\n pointer,\n now,\n owned,\n span,\n protocol,\n native,\n within,\n activity,\n noteInput,\n };\n};\n\nexport type PageContext = ReturnType<typeof make>;\n"],"mappings":";;;;;;;;;AAsEA,MAAM,aAAa,UACjB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,UAAU,WAAW,QAAQ;AAE/E,MAAM,gBACJ;;;;;;AAOF,MAAa,YACX,OACA,eACA,SAAsB,iBACX;CACX,MAAM,UAAU,UAAU,KAAK;CAE/B,IAAI,cAAc,KAAK,OAAO,GAAG,OAAO,IAAI,OAAO,EAAE,OAAO,OAAO,CAAC;CACpE,IAAI,iBAAiB,SAAS,MAAM,SAAS,kBAAkB,kBAAkB,KAAA,GAC/E,OAAO,IAAI,QAAQ,EAAE,QAAQ,cAAc,CAAC;CAC9C,MAAM,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAC,MAAM;CAEvC,OAAO,IAAI,OAAO,EAAE,QAAQA,aAAiB,KAAK,QAAQ,aAAa,EAAE,CAAC,EAAE,CAAC;AAC/E;;;;;;AAOA,MAAa,QACX,WACA,KACA,UACA,kBAEA,OAAO,WAAW;CAChB,KAAK;CACL,QAAQ,UAAU,aAAa,WAAW,SAAS,OAAO,eAAe,SAAS,CAAC,CAAC;AACtF,CAAC;AAEH,MAAa,eAAe,UAC1B,MAAM,OAAO,SAAS,YACtB,kGAAkG,KAChG,MAAM,OAAO,MACf;;AAkBF,MAAM,cAAc,QAAQ,UAC1B,4CACA,EACE,oBAAoB,KAAA,EACtB,CACF;AAGA,MAAM,UAAU,UACd,UAAU,KAAA,IAAY,IAAI,OAAO,WAAW,KAAK,UAAU,KAAK,CAAC;;AAGn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