effect-browser 0.3.0-beta.24 → 0.3.0-beta.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +333 -157
- package/dist/Action.d.mts +1 -1
- package/dist/Action.mjs +61 -9
- package/dist/Action.mjs.map +1 -1
- package/dist/Browser.d.mts +2 -2
- package/dist/Browser.mjs +2 -2
- package/dist/BrowserError.d.mts +2 -2
- package/dist/BrowserError.mjs +194 -41
- package/dist/BrowserError.mjs.map +1 -1
- package/dist/BrowserEvent.d.mts +1 -1
- package/dist/BrowserEvent.mjs +166 -35
- package/dist/BrowserEvent.mjs.map +1 -1
- package/dist/Cdp.d.mts +15 -0
- package/dist/Cdp.mjs +22 -0
- package/dist/Cdp.mjs.map +1 -0
- package/dist/Change.d.mts +2 -2
- package/dist/Change.mjs +33 -6
- package/dist/Change.mjs.map +1 -1
- package/dist/Frame.d.mts +2 -2
- package/dist/Frame.mjs +132 -14
- package/dist/Frame.mjs.map +1 -1
- package/dist/{Style.d.mts → InputStyle.d.mts} +93 -25
- package/dist/{Style.mjs → InputStyle.mjs} +1 -1
- package/dist/Layout.d.mts +2 -2
- package/dist/Layout.mjs +58 -16
- package/dist/Layout.mjs.map +1 -1
- package/dist/Overlay.d.mts +2 -2
- package/dist/Overlay.mjs +33 -5
- package/dist/Overlay.mjs.map +1 -1
- package/dist/Page.d.mts +2 -2
- package/dist/Page.mjs +2 -2
- package/dist/PageTime.d.mts +2 -2
- package/dist/PageTime.mjs +13 -3
- package/dist/PageTime.mjs.map +1 -1
- package/dist/Pose.d.mts +2 -2
- package/dist/Pose.mjs +30 -9
- package/dist/Pose.mjs.map +1 -1
- package/dist/Site.d.mts +288 -18
- package/dist/Site.mjs +11 -3
- package/dist/Site.mjs.map +1 -1
- package/dist/Snapshot.d.mts +2 -2
- package/dist/Snapshot.mjs +87 -6
- package/dist/Snapshot.mjs.map +1 -1
- package/dist/Text.d.mts +2 -0
- package/dist/Text.mjs +45 -0
- package/dist/Text.mjs.map +1 -0
- package/dist/Window.d.mts +2 -2
- package/dist/Window.mjs +31 -6
- package/dist/Window.mjs.map +1 -1
- package/dist/ai/BrowserTools.d.mts +4987 -0
- package/dist/ai/BrowserTools.mjs +3 -0
- package/dist/ai/PageControl.d.mts +286 -0
- package/dist/ai/PageControl.mjs +426 -0
- package/dist/ai/PageControl.mjs.map +1 -0
- package/dist/ai/PromptCache.d.mts +16 -0
- package/dist/ai/PromptCache.mjs +72 -0
- package/dist/ai/PromptCache.mjs.map +1 -0
- package/dist/ai/Tabs.d.mts +2 -0
- package/dist/ai/Tabs.mjs +72 -0
- package/dist/ai/Tabs.mjs.map +1 -0
- package/dist/ai/ToolError.d.mts +34 -0
- package/dist/ai/ToolError.mjs +2 -0
- package/dist/ai/index.d.mts +6 -0
- package/dist/ai/index.mjs +6 -0
- package/dist/index.d.mts +7 -18
- package/dist/index.mjs +6 -9
- package/dist/{Action-24sLOubi.d.mts → internal/Action-CkanNTUw.d.mts} +64 -4
- package/dist/{Browser-DGR6ZEYo.d.mts → internal/Browser-DD9Vm1c-.d.mts} +75 -11
- package/dist/{Browser-CAQFhTkM.mjs → internal/Browser-vzD7i2oj.mjs} +174 -237
- package/dist/internal/Browser-vzD7i2oj.mjs.map +1 -0
- package/dist/{BrowserError-BlcmLVzn.d.mts → internal/BrowserError-CsuRYcDX.d.mts} +187 -28
- package/dist/{BrowserEvent-C2p-NwuU.d.mts → internal/BrowserEvent-tGPYYf6R.d.mts} +168 -13
- package/dist/internal/BrowserTools-Yi3lOX4h.mjs +497 -0
- package/dist/internal/BrowserTools-Yi3lOX4h.mjs.map +1 -0
- package/dist/{Style-T3ezDYLI.mjs → internal/InputStyle-CPzxoN4g.mjs} +75 -20
- package/dist/internal/InputStyle-CPzxoN4g.mjs.map +1 -0
- package/dist/{moment/Moment.mjs → internal/Moment-CstaX1mR.mjs} +49 -16
- package/dist/internal/Moment-CstaX1mR.mjs.map +1 -0
- package/dist/{moment/Moment.d.mts → internal/Moment-DOcldBdf.d.mts} +53 -20
- package/dist/internal/Page-BfGxn7oN.d.mts +1553 -0
- package/dist/{Page-BaAOshxo.mjs → internal/Page-DqF-tuTx.mjs} +62 -74
- package/dist/internal/Page-DqF-tuTx.mjs.map +1 -0
- package/dist/internal/Release-CFONkPDP.d.mts +39 -0
- package/dist/internal/Stage-D5ymSXDT.mjs +298 -0
- package/dist/internal/Stage-D5ymSXDT.mjs.map +1 -0
- package/dist/internal/Stillness-DCPeAN1a.mjs +1124 -0
- package/dist/internal/Stillness-DCPeAN1a.mjs.map +1 -0
- package/dist/internal/Supervisor-BcY_QNIY.d.mts +108 -0
- package/dist/internal/Supervisor-BcglY23c.mjs +531 -0
- package/dist/internal/Supervisor-BcglY23c.mjs.map +1 -0
- package/dist/internal/Tabs-dXMscIUQ.d.mts +52 -0
- package/dist/internal/TestPage-CYiYbh63.d.mts +159 -0
- package/dist/internal/ToolError-DArsRS2m.mjs +117 -0
- package/dist/internal/ToolError-DArsRS2m.mjs.map +1 -0
- package/dist/{plan/index.d.mts → internal/Walk-BNXcfZ2z.d.mts} +59 -35
- package/dist/{plan/index.mjs → internal/Walk-C5ky7uSf.mjs} +83 -51
- package/dist/internal/Walk-C5ky7uSf.mjs.map +1 -0
- package/dist/{ActionPort.mjs → internal/action-port-B5EkeGOR.mjs} +6 -12
- package/dist/internal/action-port-B5EkeGOR.mjs.map +1 -0
- package/dist/internal/cdp/workerd.d.mts +13 -0
- package/dist/internal/cdp/workerd.mjs +19 -0
- package/dist/internal/cdp/workerd.mjs.map +1 -0
- package/dist/{Clock.mjs → internal/clock-BKSAEf00.mjs} +13 -13
- package/dist/internal/clock-BKSAEf00.mjs.map +1 -0
- package/dist/{connection-Db-YtlbE.d.mts → internal/connection-BaB0vp1o.d.mts} +6 -6
- package/dist/{connection-C_jWYIwe.mjs → internal/connection-C2X4GmXM.mjs} +19 -15
- package/dist/internal/connection-C2X4GmXM.mjs.map +1 -0
- package/dist/internal/events-DzCrww-y.mjs +72 -0
- package/dist/internal/events-DzCrww-y.mjs.map +1 -0
- package/dist/internal/fold.inpage-uhrT-dOB.mjs +49 -0
- package/dist/internal/fold.inpage-uhrT-dOB.mjs.map +1 -0
- package/dist/internal/functions-jBOs6GKv.mjs +27 -0
- package/dist/internal/functions-jBOs6GKv.mjs.map +1 -0
- package/dist/{Geometry-DJx9qrYy.d.mts → internal/geometry-Dhj_ztJs.d.mts} +3 -3
- package/dist/{Geometry.mjs → internal/geometry-Lxyflb9J.mjs} +3 -12
- package/dist/internal/geometry-Lxyflb9J.mjs.map +1 -0
- package/dist/{Matching.mjs → internal/matching-Cs-UeOY0.mjs} +3 -3
- package/dist/internal/matching-Cs-UeOY0.mjs.map +1 -0
- package/dist/internal/page-DFQb-YOK.mjs +436 -0
- package/dist/internal/page-DFQb-YOK.mjs.map +1 -0
- package/dist/{pose.inpage-CLq7Mfdr.mjs → internal/pose.inpage-CBFeWcVa.mjs} +2 -48
- package/dist/internal/pose.inpage-CBFeWcVa.mjs.map +1 -0
- package/dist/{Url.mjs → internal/url-DB0pQYk6.mjs} +3 -12
- package/dist/internal/url-DB0pQYk6.mjs.map +1 -0
- package/dist/policy/Policy.d.mts +60 -6
- package/dist/policy/Policy.mjs +52 -9
- package/dist/policy/Policy.mjs.map +1 -1
- package/dist/policy/index.d.mts +2 -0
- package/dist/policy/index.mjs +2 -0
- package/dist/{film → presentation}/Film.d.mts +83 -16
- package/dist/{film → presentation}/Film.mjs +82 -30
- package/dist/presentation/Film.mjs.map +1 -0
- package/dist/presentation/Motion.d.mts +5 -1
- package/dist/presentation/Motion.mjs +16 -2
- package/dist/presentation/Motion.mjs.map +1 -1
- package/dist/presentation/Presentation.d.mts +42 -7
- package/dist/presentation/Presentation.mjs +26 -9
- package/dist/presentation/Presentation.mjs.map +1 -1
- package/dist/presentation/Stage.d.mts +40 -6
- package/dist/presentation/Stage.mjs +1 -262
- package/dist/presentation/index.d.mts +5 -0
- package/dist/presentation/index.mjs +5 -0
- package/dist/supervisor/Release.d.mts +2 -0
- package/dist/supervisor/Release.mjs +40 -0
- package/dist/supervisor/Release.mjs.map +1 -0
- package/dist/supervisor/Supervisor.d.mts +2 -104
- package/dist/supervisor/Supervisor.mjs +2 -515
- package/dist/supervisor/index.d.mts +3 -0
- package/dist/supervisor/index.mjs +3 -0
- package/dist/testing/HttpCassette.d.mts +98 -0
- package/dist/testing/HttpCassette.mjs +146 -0
- package/dist/testing/HttpCassette.mjs.map +1 -0
- package/dist/testing/Story.d.mts +31 -0
- package/dist/testing/Story.mjs +76 -0
- package/dist/testing/Story.mjs.map +1 -0
- package/dist/testing/TestBrowser.d.mts +191 -0
- package/dist/testing/TestBrowser.mjs +105 -0
- package/dist/testing/TestBrowser.mjs.map +1 -0
- package/dist/testing/TestModel.d.mts +133 -0
- package/dist/testing/TestModel.mjs +209 -0
- package/dist/testing/TestModel.mjs.map +1 -0
- package/dist/testing/TestPage.d.mts +2 -0
- package/dist/testing/TestPage.mjs +47 -0
- package/dist/testing/TestPage.mjs.map +1 -0
- package/dist/testing/index.d.mts +6 -311
- package/dist/testing/index.mjs +6 -521
- package/dist/timeline/Moment.d.mts +3 -0
- package/dist/timeline/Moment.mjs +3 -0
- package/dist/timeline/Stillness.d.mts +34 -0
- package/dist/timeline/Stillness.mjs +2 -0
- package/dist/timeline/index.d.mts +3 -0
- package/dist/timeline/index.mjs +3 -0
- package/dist/walk/Walk.d.mts +2 -0
- package/dist/walk/Walk.mjs +2 -0
- package/dist/walk/index.d.mts +2 -0
- package/dist/walk/index.mjs +2 -0
- package/package.json +54 -163
- package/src/Action.ts +73 -8
- package/src/Browser.ts +75 -9
- package/src/BrowserError.ts +258 -63
- package/src/BrowserEvent.ts +252 -55
- package/src/Cdp.ts +42 -0
- package/src/Change.ts +68 -3
- package/src/Frame.ts +247 -14
- package/src/{Style.ts → InputStyle.ts} +98 -22
- package/src/Layout.ts +95 -24
- package/src/Overlay.ts +42 -3
- package/src/Page.ts +144 -320
- package/src/PageTime.ts +29 -4
- package/src/Pose.ts +38 -7
- package/src/Site.ts +15 -3
- package/src/Snapshot.ts +179 -3
- package/src/Text.ts +60 -0
- package/src/Window.ts +53 -3
- package/src/ai/BrowserTools.ts +778 -0
- package/src/ai/PageControl.ts +702 -0
- package/src/ai/PromptCache.ts +87 -0
- package/src/ai/Tabs.ts +84 -0
- package/src/ai/ToolError.ts +50 -0
- package/src/ai/index.ts +36 -0
- package/src/ai/internal/crops.ts +38 -0
- package/src/ai/internal/points.ts +57 -0
- package/src/ai/internal/receipts.ts +107 -0
- package/src/index.ts +83 -6
- package/src/{ActionPort.ts → internal/action-port.ts} +3 -3
- package/src/{providers → internal/cdp}/connection.ts +19 -12
- package/src/internal/cdp/workerd.ts +36 -0
- package/src/{Clock.ts → internal/clock.ts} +20 -0
- package/src/internal/input/actions.ts +1 -1
- package/src/internal/input/dispatch.ts +2 -2
- package/src/internal/input/guard.inpage.ts +1 -1
- package/src/internal/input/guard.ts +1 -1
- package/src/internal/input/perform.ts +5 -5
- package/src/internal/input/pointer.ts +2 -2
- package/src/internal/input/targets.inpage.ts +3 -3
- package/src/{Matching.ts → internal/matching.ts} +6 -6
- package/src/internal/page/bridge.ts +2 -2
- package/src/internal/page/clock.inpage.ts +1 -1
- package/src/internal/page/compose.inpage.ts +2 -2
- package/src/internal/page/context.ts +2 -2
- package/src/internal/page/functions.ts +84 -0
- package/src/internal/page/navigation.ts +1 -1
- package/src/internal/page/openings.ts +2 -2
- package/src/internal/page/page.ts +33 -35
- package/src/internal/page/port.ts +14 -8
- package/src/internal/page/replies.ts +1 -1
- package/src/internal/page/requests.ts +1 -1
- package/src/internal/page/scripts.ts +1 -1
- package/src/internal/page/time.ts +1 -1
- package/src/internal/pictures/capture.ts +1 -4
- package/src/internal/pictures/dimensions.ts +1 -1
- package/src/internal/pictures/frame.ts +1 -1
- package/src/internal/pictures/pictures.ts +53 -61
- package/src/internal/reading/context.inpage.ts +2 -2
- package/src/internal/reading/expect.inpage.ts +1 -1
- package/src/internal/reading/layout.inpage.ts +3 -3
- package/src/internal/reading/layout.ts +5 -5
- package/src/internal/reading/outline.inpage.ts +3 -3
- package/src/internal/reading/reading.ts +11 -19
- package/src/internal/reading/ready.inpage.ts +2 -2
- package/src/internal/reading/ready.ts +3 -2
- package/src/internal/reading/subjects.inpage.ts +3 -3
- package/src/internal/reading/text.inpage.ts +2 -2
- package/src/internal/reading/walk.inpage.ts +1 -1
- package/src/internal/timeline/changes.inpage.ts +2 -2
- package/src/internal/timeline/changes.ts +3 -4
- package/src/internal/timeline/sight.inpage.ts +2 -2
- package/src/internal/timeline/window.ts +3 -4
- package/src/policy/Policy.ts +70 -16
- package/src/policy/index.ts +12 -0
- package/src/{film → presentation}/Film.ts +104 -37
- package/src/presentation/Motion.ts +45 -3
- package/src/presentation/Presentation.ts +47 -14
- package/src/presentation/Stage.ts +73 -35
- package/src/presentation/index.ts +30 -0
- package/src/presentation/{feed.ts → internal/feed.ts} +1 -1
- package/src/supervisor/Release.ts +45 -0
- package/src/supervisor/Supervisor.ts +80 -5
- package/src/supervisor/index.ts +18 -0
- package/src/supervisor/{contract.ts → internal/contract.ts} +14 -10
- package/src/supervisor/{lifecycle.ts → internal/lifecycle.ts} +7 -7
- package/src/supervisor/{runtime.ts → internal/runtime.ts} +7 -7
- package/src/testing/HttpCassette.ts +260 -0
- package/src/testing/Story.ts +103 -0
- package/src/testing/TestBrowser.ts +14 -4
- package/src/testing/TestModel.ts +297 -0
- package/src/testing/TestPage.ts +92 -4
- package/src/testing/index.ts +35 -1
- package/src/testing/{evidence.ts → internal/evidence.ts} +19 -11
- package/src/testing/{model.ts → internal/model.ts} +14 -8
- package/src/testing/{page.ts → internal/page.ts} +55 -56
- package/src/{moment → timeline}/Moment.ts +79 -29
- package/src/{stillness → timeline}/Stillness.ts +61 -43
- package/src/timeline/index.ts +18 -0
- package/src/{stillness/Pixels.ts → timeline/internal/pixels.ts} +2 -2
- package/src/{moment → timeline/internal}/words.ts +2 -2
- package/src/walk/Walk.ts +165 -0
- package/src/walk/index.ts +12 -0
- package/src/{plan → walk/internal}/choose.ts +23 -14
- package/src/{plan → walk/internal}/data.ts +37 -14
- package/src/{plan → walk/internal}/execute.ts +79 -36
- package/src/{plan → walk/internal}/record.ts +6 -6
- package/src/{plan → walk/internal}/targets.ts +35 -25
- package/dist/ActionPort.d.mts +0 -15
- package/dist/ActionPort.mjs.map +0 -1
- package/dist/Browser-CAQFhTkM.mjs.map +0 -1
- package/dist/Change-CxT1mp2e.d.mts +0 -80
- package/dist/Clock-Du5nP-nK.d.mts +0 -57
- package/dist/Clock.d.mts +0 -2
- package/dist/Clock.mjs.map +0 -1
- package/dist/Frame-UEH2hO5T.d.mts +0 -124
- package/dist/Geometry.d.mts +0 -2
- package/dist/Geometry.mjs.map +0 -1
- package/dist/Matching-MtcWZ_hA.d.mts +0 -266
- package/dist/Matching.d.mts +0 -2
- package/dist/Matching.mjs.map +0 -1
- package/dist/Overlay-CoGw5tL_.d.mts +0 -27
- package/dist/Page-BaAOshxo.mjs.map +0 -1
- package/dist/Page-CLzh5E9w.d.mts +0 -718
- package/dist/PageTime-68UPUZpZ.d.mts +0 -29
- package/dist/Pose-2qqGzPvb.d.mts +0 -32
- package/dist/Released-tURbFmal.d.mts +0 -15
- package/dist/Snapshot-CtBVOtuu.d.mts +0 -73
- package/dist/Stillness-BwP0RdI4.mjs +0 -157
- package/dist/Stillness-BwP0RdI4.mjs.map +0 -1
- package/dist/Style-T3ezDYLI.mjs.map +0 -1
- package/dist/Url-B7P-TWwL.d.mts +0 -26
- package/dist/Url.d.mts +0 -2
- package/dist/Url.mjs.map +0 -1
- package/dist/Window-BDa8MtNP.d.mts +0 -34
- package/dist/connection-C_jWYIwe.mjs.map +0 -1
- package/dist/film/Film.mjs.map +0 -1
- package/dist/moment/Moment.mjs.map +0 -1
- package/dist/plan/index.mjs.map +0 -1
- package/dist/pose.inpage-CLq7Mfdr.mjs.map +0 -1
- package/dist/presentation/Stage.mjs.map +0 -1
- package/dist/presentation/feed.d.mts +0 -20
- package/dist/presentation/feed.mjs +0 -18
- package/dist/presentation/feed.mjs.map +0 -1
- package/dist/providers/Cdp.d.mts +0 -9
- package/dist/providers/Cdp.mjs +0 -15
- package/dist/providers/Cdp.mjs.map +0 -1
- package/dist/providers/Chromium.d.mts +0 -32
- package/dist/providers/Chromium.mjs +0 -55
- package/dist/providers/Chromium.mjs.map +0 -1
- package/dist/providers/Released.d.mts +0 -2
- package/dist/providers/Released.mjs +0 -12
- package/dist/providers/Released.mjs.map +0 -1
- package/dist/stillness/Stillness.d.mts +0 -12
- package/dist/stillness/Stillness.mjs +0 -2
- package/dist/supervisor/Supervisor.mjs.map +0 -1
- package/dist/testing/index.mjs.map +0 -1
- package/dist/workerd/Cdp.d.mts +0 -8
- package/dist/workerd/Cdp.mjs +0 -13
- package/dist/workerd/Cdp.mjs.map +0 -1
- package/src/plan/index.ts +0 -36
- package/src/providers/Cdp.ts +0 -16
- package/src/providers/Chromium.ts +0 -99
- package/src/providers/Released.ts +0 -13
- package/src/workerd/Cdp.ts +0 -11
- /package/dist/{fold.inpage-CyVZQHZL.d.mts → internal/fold.inpage-CyVZQHZL.d.mts} +0 -0
- /package/dist/{rolldown-runtime-D7D4PA-g.mjs → internal/rolldown-runtime-D7D4PA-g.mjs} +0 -0
- /package/src/{Geometry.ts → internal/geometry.ts} +0 -0
- /package/src/{Url.ts → internal/url.ts} +0 -0
- /package/src/{stillness → timeline/internal}/utilsBundle.d.ts +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Browser-CAQFhTkM.mjs","names":["step","make","Current","make","Errors.Failed","make","BrowserClock.monotonicMillis","Port.Operation","Errors.Timeout","Lane.make","Errors.Closed","Url.addresses","Url.redact","make","Events.DialogShown","make","make","make","BrowserClock.toBrowserSeconds","make","Script.PreparedInputResultSchema","Url.redact","Script.ValidatedInputResultSchema","make","description","Keys.description","deadline","Replies.Current","make","Replies.make","Current","make","Motion.Plan","make","make","Script.PointResultSchema","Script.ScrollPlanSchema","Dispatch.make","Pointer.make","Guard.make","Settle.make","Perform.make","Targets.make","Keyboard.make","Keys.parts","Guard.check","Script.TypeableResultSchema","Script.FocusResultSchema","Guard.editFailure","Script.EditResultSchema","make","deadline","deadline","make","Replies.make","Replies.Current","settingsOf","make","Quiescence.make","FrameTree","Port.openCapture","BrowserClock.estimate","make","Capture.make","Transport.own","Transport.apart","Port.Current","make","Url.redact","make","request","Url.redact","askedOf","make","make","BrowserClock.toHostTime","make","make","Url.redact","Url.parse","make","make","make","Url.redact","make","make","make","Context.make","Bridge.make","Viewport.make","Actions.make","Pictures.make","Reading.make","Navigation.make","Changes.make","Overlay.make","Poses.make","ActionPort.checked","ActionPort.execute","Scripts.make","ActionPort.methods","Url.redact","Layouts.make","Time.make","Window.make","Ready.make","make","Port.Current","Port.openSession","Port.openSession","Owner.make","Url.redact","Url.redactWithin","make","Identity.make","Events.PageUntracked","Url.redact","Events.PageClosed","Port.Current","BrowserClock.monotonicMillis","mapping","BrowserClock.mapping","Timeline.make","Events.SessionEnding","Events.Disconnected","Requests.install","Gate.make","Port.openSession","PageImpl.make","Openings.make","Events.PageOpened"],"sources":["../src/internal/input/gate.ts","../src/internal/input/edit.inpage.ts","../src/internal/input/targets.inpage.ts","../src/internal/page/port.ts","../src/internal/page/replies.ts","../src/internal/page/context.ts","../src/internal/page/time.inpage.ts","../src/internal/page/bridge.ts","../src/internal/page/dialogs.ts","../src/internal/page/identity.ts","../src/internal/page/openings.ts","../src/internal/input/dispatch.ts","../src/internal/input/guard.ts","../src/internal/input/keyboard.ts","../src/internal/input/perform.ts","../src/internal/input/pointer.ts","../src/internal/input/settle.ts","../src/internal/input/targets.ts","../src/internal/input/actions.ts","../src/internal/pictures/counts.ts","../src/internal/pictures/dimensions.ts","../src/internal/pictures/frame.ts","../src/internal/pictures/quiescence.ts","../src/internal/pictures/state.ts","../src/internal/pictures/capture.ts","../src/internal/pictures/transport.ts","../src/internal/pictures/pictures.ts","../src/internal/reading/layout.ts","../src/internal/reading/reading.ts","../src/internal/reading/ready.ts","../src/internal/timeline/changes.ts","../src/internal/timeline/window.ts","../src/internal/page/navigation.ts","../src/internal/page/overlay.ts","../src/internal/page/pose.ts","../src/internal/page/scripts.ts","../src/internal/page/time.ts","../src/internal/page/viewport.ts","../src/internal/page/page.ts","../src/internal/page/request-owner.ts","../src/internal/page/requests.ts","../src/internal/timeline/events.ts","../src/Browser.ts"],"sourcesContent":["/**\n * A browser's input authority: stop admitting writes, drain admitted operations through their\n * records and native replies, then retain the stop for its scopes. Reads never enter this gate.\n */\nimport { Clock, Deferred, Duration, Effect, Exit, Option, type Scope } from \"effect\";\n\nimport {\n undispatched,\n type BrowserError,\n Busy,\n Closed,\n InvalidRequest,\n Suspended,\n} from \"../../BrowserError.ts\";\nimport type { DisconnectCause } from \"../../BrowserEvent.ts\";\n\ninterface Stopped {\n readonly since: number;\n readonly at: number;\n}\n\ntype State =\n | { readonly _tag: \"Open\"; readonly inputs: ReadonlySet<number> }\n | {\n readonly _tag: \"Draining\";\n readonly inputs: ReadonlySet<number>;\n readonly claims: ReadonlySet<number>;\n readonly startedAt: number;\n readonly deadline: number;\n }\n | { readonly _tag: \"Held\"; readonly claims: ReadonlySet<number>; readonly stopped: Stopped };\n\ntype Input =\n | { readonly _tag: \"Enter\" | \"End\" | \"Leave\"; readonly id: number }\n | { readonly _tag: \"Suspend\"; readonly id: number; readonly drain: number }\n | { readonly _tag: \"Expire\" };\n\nconst without = (set: ReadonlySet<number>, id: number) =>\n new Set([...set].filter((each) => each !== id));\n\nconst step = (state: State, input: Input, stopped: Stopped): State => {\n switch (input._tag) {\n case \"Enter\":\n return state._tag === \"Open\"\n ? { ...state, inputs: new Set([...state.inputs, input.id]) }\n : state;\n case \"End\": {\n if (state._tag === \"Held\") return state;\n const inputs = without(state.inputs, input.id);\n\n return state._tag === \"Draining\" && inputs.size === 0\n ? { _tag: \"Held\", claims: state.claims, stopped }\n : { ...state, inputs };\n }\n case \"Suspend\":\n if (state._tag !== \"Open\") return { ...state, claims: new Set([...state.claims, input.id]) };\n\n return state.inputs.size === 0\n ? { _tag: \"Held\", claims: new Set([input.id]), stopped }\n : {\n _tag: \"Draining\",\n inputs: state.inputs,\n claims: new Set([input.id]),\n startedAt: stopped.at,\n deadline: stopped.at + input.drain,\n };\n case \"Leave\": {\n if (state._tag === \"Open\" || !state.claims.has(input.id)) return state;\n const claims = without(state.claims, input.id);\n\n return claims.size > 0\n ? { ...state, claims }\n : { _tag: \"Open\", inputs: state._tag === \"Draining\" ? state.inputs : new Set() };\n }\n case \"Expire\":\n return state._tag === \"Draining\" && stopped.at >= state.deadline\n ? { _tag: \"Open\", inputs: state.inputs }\n : state;\n }\n};\n\nexport const make = (options: {\n readonly now: () => number;\n readonly sequence: () => number;\n readonly closedBy: () => DisconnectCause | undefined;\n readonly lost: Effect.Effect<DisconnectCause>;\n readonly clock: Clock.Clock;\n readonly drain: Duration.Duration;\n}) => {\n let state: State = { _tag: \"Open\", inputs: new Set() };\n let next = 0;\n let refused = Deferred.makeUnsafe<void>();\n let ready = Deferred.makeUnsafe<Stopped, BrowserError>();\n\n const error = (operation: string) =>\n undispatched(\n operation,\n options.closedBy() === undefined\n ? new Suspended()\n : new Closed({ cause: options.closedBy() ?? \"connection\" }),\n );\n\n const stopped = (): Stopped => ({ since: options.sequence(), at: options.now() });\n\n // Every change to authority happens here, synchronously with its admission or scope closure.\n const apply = (input: Input): State => {\n if (input._tag !== \"Expire\" && state._tag === \"Draining\" && options.now() >= state.deadline)\n apply({ _tag: \"Expire\" });\n const before = state;\n\n state = step(state, input, stopped());\n if (input._tag === \"Expire\" && before._tag === \"Draining\" && state._tag === \"Open\")\n Deferred.doneUnsafe(\n ready,\n Exit.fail(\n undispatched(\n \"suspend\",\n new Busy({\n waitedMillis: Math.round(options.now() - before.startedAt),\n ahead: before.inputs.size,\n }),\n ),\n ),\n );\n if (before._tag === \"Open\" && state._tag !== \"Open\") Deferred.doneUnsafe(refused, Exit.void);\n if (before._tag === \"Draining\" && state._tag === \"Held\")\n Deferred.doneUnsafe(ready, Exit.succeed(state.stopped));\n if (before._tag !== \"Open\" && state._tag === \"Open\") {\n refused = Deferred.makeUnsafe();\n ready = Deferred.makeUnsafe();\n }\n\n return state;\n };\n\n const check = (operation: string) =>\n Effect.suspend(() =>\n state._tag === \"Open\" && options.closedBy() === undefined\n ? Effect.void\n : Effect.fail(error(operation)),\n );\n\n const suspend = (\n drain: Duration.Input = options.drain,\n ): Effect.Effect<Stopped, BrowserError, Scope.Scope> =>\n Effect.suspend(() => {\n const duration = Duration.fromInput(drain);\n\n if (\n Option.isNone(duration) ||\n !Duration.isFinite(duration.value) ||\n Duration.toMillis(duration.value) < 0\n )\n return Effect.fail(\n undispatched(\n \"suspend\",\n new InvalidRequest({ detail: \"drain must be a finite nonnegative duration\" }),\n ),\n );\n const id = ++next;\n const leave = Effect.sync(() => apply({ _tag: \"Leave\", id }));\n\n return Effect.acquireRelease(\n Effect.gen(function* () {\n if (options.closedBy() !== undefined) return yield* error(\"suspend\");\n const current = apply({ _tag: \"Suspend\", id, drain: Duration.toMillis(duration.value) });\n\n if (current._tag === \"Held\") return current.stopped;\n if (current._tag !== \"Draining\")\n return yield* Effect.die(\"suspension did not retain authority\");\n const pending = ready;\n\n // Native completion and timer callbacks both check the same monotonic deadline. A\n // timer may wake a fraction early, so it sleeps the remaining time instead of hanging.\n const expire: Effect.Effect<Stopped, BrowserError> = Effect.suspend(() => {\n const left = current.deadline - options.now();\n\n return left > 0\n ? Effect.sleep(Duration.millis(left)).pipe(Effect.andThen(expire))\n : Effect.sync(() => apply({ _tag: \"Expire\" })).pipe(\n Effect.andThen(Deferred.await(pending)),\n );\n });\n\n const wait = Effect.raceFirst(Deferred.await(pending), expire);\n\n return yield* Effect.raceFirst(\n wait,\n options.lost.pipe(Effect.flatMap(() => Effect.fail(error(\"suspend\")))),\n ).pipe(\n Effect.interruptible,\n Effect.filterOrFail(\n () => options.closedBy() === undefined,\n () => error(\"suspend\"),\n ),\n Effect.onError(() => leave),\n );\n }),\n () => leave,\n );\n }).pipe(Effect.provideService(Clock.Clock, options.clock));\n\n return {\n check,\n suspend,\n refused: (operation: string): Effect.Effect<never, BrowserError> =>\n Effect.suspend(() =>\n state._tag === \"Open\"\n ? Deferred.await(refused).pipe(Effect.andThen(Effect.fail(error(operation))))\n : Effect.fail(error(operation)),\n ),\n enter: (operation: string): Effect.Effect<() => void, BrowserError> =>\n Effect.suspend(() => {\n if (state._tag !== \"Open\" || options.closedBy() !== undefined)\n return Effect.fail(error(operation));\n const id = ++next;\n\n apply({ _tag: \"Enter\", id });\n\n return Effect.succeed(() => {\n apply({ _tag: \"End\", id });\n });\n }),\n };\n};\n\nexport type Gate = ReturnType<typeof make>;\n","/**\n * In the page: editing a field. It refuses text that a focused control could act on, focuses a\n * field and chooses a select's options. See `reading/names.inpage.ts` for what a page-side part\n * may use.\n */\nimport { Schema } from \"effect\";\n\nimport { Subject } from \"../../BrowserEvent.ts\";\nimport type { ContextReader } from \"../reading/context.inpage.ts\";\nimport type { Names } from \"../reading/names.inpage.ts\";\nimport type { Guard } from \"./guard.inpage.ts\";\n\nexport type EditResult = typeof EditResultSchema.Encoded;\n\n/** A focused field, and whether it is secret. */\nexport type FocusResult = typeof FocusResultSchema.Encoded;\n\n/**\n * Whether text may be typed, and whether its field is secret. Typing into focus also names the\n * focused field, when it is one, so the action records what it typed into.\n */\nexport type TypeableResult = typeof TypeableResultSchema.Encoded;\n\nexport const edit = (names: Names, guard: Guard, placing: ContextReader) => {\n const {\n activeElement,\n clean,\n describe,\n inCurrentDocument,\n isDisabled,\n isHtml,\n isInput,\n isSecret,\n isSelect,\n isTextArea,\n lookup,\n nameOf,\n roleOf,\n } = names;\n\n const { textEntry, typingRefusal } = guard;\n\n /** Whether text may be typed into a ref or focus, and, for a `secret`, only into a secret field. */\n const typeable = (ref: string | null, secret: boolean): TypeableResult => {\n const element = ref === null ? activeElement() : lookup(ref);\n\n if (element === undefined)\n return {\n error: \"stale\",\n detail: `${ref ?? \"the focused element\"} is not on the page any more`,\n };\n\n const refusal =\n element === null\n ? secret\n ? \"nothing has focus to type a secret into\"\n : undefined\n : (typingRefusal(element, ref !== null) ??\n (secret && !isSecret(element)\n ? `${describe(element)} is not a secret field`\n : undefined));\n\n if (refusal !== undefined) return { error: \"untypeable\", detail: refusal };\n if (element === null || ref !== null || !textEntry(element))\n return { ok: true, secret: element !== null && isSecret(element) };\n const role = roleOf(element);\n const tag = element.tagName.toLowerCase();\n\n return {\n ok: true,\n secret: isSecret(element),\n subject: { role, name: nameOf(element, role), tag, context: placing.contextOf(element) },\n };\n };\n\n /**\n * The focused field, when it is a text field named `name`: one a page put in place of a field\n * just pressed and gave focus to, as a typeahead does.\n */\n const replacement = (name: string): Element | undefined => {\n const active = activeElement();\n\n return active !== null &&\n textEntry(active) &&\n inCurrentDocument(active) &&\n nameOf(active, roleOf(active)) === name\n ? active\n : undefined;\n };\n\n /**\n * Focus a field to type into. `follow` is the field's name when the action pressed it first: a\n * page may answer the press with another field of that name in its place, focused, and the keys\n * follow focus there, as a person's would.\n */\n const focus = (ref: string, replace: boolean, follow: string | null): FocusResult => {\n const element = lookup(ref) ?? (follow === null ? undefined : replacement(follow));\n\n if (element === undefined) return { error: `${ref} is not on the page any more`, stale: true };\n if (isDisabled(element)) return { error: `${ref} is disabled` };\n if (!textEntry(element)) return { error: `${ref} is ${describe(element)}, not a text field` };\n if (isHtml(element)) element.focus();\n if (replace) {\n if (isInput(element) || isTextArea(element)) element.select();\n else element.ownerDocument.getSelection()?.selectAllChildren(element);\n }\n\n // Decided after focusing: a focus handler can mark the field secret.\n return { ok: true, detail: describe(element), secret: isSecret(element) };\n };\n\n /** Focus any element that takes focus, such as a link or a button, for a key pressed on it. */\n const focusOn = (ref: string): EditResult => {\n const element = lookup(ref);\n\n if (element === undefined) return { error: `${ref} is not on the page any more`, stale: true };\n if (isDisabled(element)) return { error: `${ref} is disabled` };\n if (isHtml(element)) element.focus();\n\n return activeElement() === element\n ? { ok: true, detail: describe(element) }\n : { error: `${ref} is ${describe(element)}, which does not take focus` };\n };\n\n const select = (ref: string, values: ReadonlyArray<string>): EditResult => {\n const element = lookup(ref);\n\n if (element === undefined) return { error: `${ref} is not on the page any more`, stale: true };\n if (!isSelect(element))\n return {\n error: `${ref} is ${describe(element)}, not a <select>; click it and pick an option`,\n };\n const wanted = values.map((value) => value.trim().toLowerCase());\n const options = Array.from(element.options);\n\n const chosen = options.filter(\n (option) =>\n wanted.includes(option.value.toLowerCase()) ||\n wanted.includes(clean(option.text).toLowerCase()),\n );\n\n if (chosen.length === 0)\n return {\n error: `no option matches; the options are ${options.map((option) => JSON.stringify(clean(option.text, 40))).join(\", \")}`,\n };\n for (const option of options) option.selected = chosen.includes(option);\n element.dispatchEvent(new Event(\"input\", { bubbles: true }));\n element.dispatchEvent(new Event(\"change\", { bubbles: true }));\n\n return { ok: true, detail: chosen.map((option) => clean(option.text, 40)).join(\", \") };\n };\n\n return { focus, focusOn, select, typeable };\n};\n\nexport type Edit = ReturnType<typeof edit>;\n\nexport const TypeableResultSchema = Schema.Union([\n Schema.Struct({\n ok: Schema.Literal(true),\n secret: Schema.Boolean,\n subject: Schema.optional(Subject),\n }),\n Schema.Struct({ error: Schema.Literals([\"stale\", \"untypeable\"]), detail: Schema.String }),\n]);\n\nconst EditFailure = Schema.Struct({ error: Schema.String, stale: Schema.optional(Schema.Boolean) });\n\nexport const FocusResultSchema = Schema.Union([\n Schema.Struct({ ok: Schema.Literal(true), detail: Schema.String, secret: Schema.Boolean }),\n EditFailure,\n]);\n\nexport const EditResultSchema = Schema.Union([\n Schema.Struct({ ok: Schema.Literal(true), detail: Schema.String }),\n EditFailure,\n]);\n","/**\n * In the page: where input lands. It resolves a ref or a point to the control under it, in\n * top-document viewport pixels, with the subject's context, and plans a wheel scroll that brings a\n * ref into view. See `reading/names.inpage.ts` for what a page-side part may use.\n */\nimport { Schema } from \"effect\";\n\nimport { Box, Subject } from \"../../BrowserEvent.ts\";\nimport { Point } from \"../../Geometry.ts\";\nimport type { ContextReader } from \"../reading/context.inpage.ts\";\nimport type { Names } from \"../reading/names.inpage.ts\";\nimport type { Walk } from \"../reading/walk.inpage.ts\";\n\nexport type ResolvedPoint = typeof ResolvedPointSchema.Type;\nexport type PointResult = typeof PointResultSchema.Type;\n\nexport const targets = (names: Names, walked: Walk, placing: ContextReader) => {\n const { describe, isDisabled, lookup, nameOf, parentOf, roleOf } = names;\n const { boxOf, controlOf, hitAt } = walked;\n const { contextOf } = placing;\n\n /** Whether `node` is `ancestor` or inside it, across shadow roots and same-origin frames. */\n const within = (ancestor: Element, node: Element): boolean => {\n for (let current: Element | null = node; current !== null;) {\n if (current === ancestor) return true;\n current = parentOf(current) ?? current.ownerDocument.defaultView?.frameElement ?? null;\n }\n\n return false;\n };\n\n // A press at a point reaches the element when the top-document hit is the element, inside it,\n // or one of its containers (whose activation the element's own facts already cover).\n const receives = (element: Element, hit: Element): boolean =>\n within(element, hit) || within(hit, element);\n\n // HTML links, SVG links and image-map areas all navigate; SVG keeps lowercase tag names.\n const hrefAttribute = (element: Element): string | null =>\n element.localName === \"a\" || element.localName === \"area\"\n ? (element.getAttribute(\"href\") ??\n element.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\"))\n : null;\n\n const linkOf = (element: Element): Element | undefined => {\n for (let node: Element | null = element; node !== null; node = parentOf(node))\n if (hrefAttribute(node) !== null) return node;\n\n return undefined;\n };\n\n const details = (\n element: Element,\n hit: Element,\n x: number,\n y: number,\n ): Omit<ResolvedPoint, \"context\"> => {\n const link = linkOf(element);\n let href: string | undefined;\n\n if (link !== undefined) {\n try {\n href = new URL(hrefAttribute(link) ?? \"\", link.ownerDocument.baseURI).href;\n } catch {\n href = undefined;\n }\n }\n const role = roleOf(element);\n const view = hit.ownerDocument.defaultView ?? window;\n\n return {\n x,\n y,\n element: describe(element),\n tag: element.tagName.toLowerCase(),\n role,\n name: nameOf(element, role),\n cursor: view.getComputedStyle(hit).cursor,\n ...(href === undefined ? {} : { href }),\n };\n };\n\n const point = (target: string | Point, scroll = true): PointResult => {\n if (typeof target !== \"string\") {\n const { x, y } = target;\n\n if (\n !Number.isFinite(x) ||\n !Number.isFinite(y) ||\n x < 0 ||\n y < 0 ||\n x >= window.innerWidth ||\n y >= window.innerHeight\n )\n return { error: \"outside\", detail: `(${x}, ${y}) is outside the viewport` };\n const hit = hitAt(document, x, y);\n\n if (hit === null) return { error: \"offscreen\", detail: `nothing is painted at (${x}, ${y})` };\n const control = controlOf(hit);\n\n return { ...details(control, hit, x, y), context: contextOf(control), box: boxOf(control) };\n }\n const ref = target;\n const element = lookup(ref);\n\n if (element === undefined)\n return { error: \"stale\", detail: `${ref} is not on the page any more` };\n if (isDisabled(element)) return { error: \"disabled\", detail: `${ref} is disabled` };\n const rect = element.getBoundingClientRect();\n\n if (rect.width === 0 && rect.height === 0)\n return { error: \"hidden\", detail: `${ref} has no size on the page` };\n\n // Input arrives in top-document viewport pixels, so geometry and occlusion are measured\n // there: a frame's own viewport cannot say whether the frame is scrolled away or covered.\n let box = { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom };\n let visible = { ...box };\n let outside = false;\n\n for (let inner: Element = element; ;) {\n const view = inner.ownerDocument.defaultView ?? window;\n\n outside ||=\n box.left < 0 || box.top < 0 || box.right > view.innerWidth || box.bottom > view.innerHeight;\n visible = {\n left: Math.max(visible.left, 0),\n top: Math.max(visible.top, 0),\n right: Math.min(visible.right, view.innerWidth),\n bottom: Math.min(visible.bottom, view.innerHeight),\n };\n\n // A field can be inside the viewport and still clipped by a nested scrolling panel.\n for (let ancestor = parentOf(inner); ancestor !== null; ancestor = parentOf(ancestor)) {\n const style = view.getComputedStyle(ancestor);\n const clip = ancestor.getBoundingClientRect();\n\n if (/(auto|scroll|hidden|clip)/.test(style.overflowX)) {\n visible.left = Math.max(visible.left, clip.left + ancestor.clientLeft);\n visible.right = Math.min(\n visible.right,\n clip.left + ancestor.clientLeft + ancestor.clientWidth,\n );\n }\n if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {\n visible.top = Math.max(visible.top, clip.top + ancestor.clientTop);\n visible.bottom = Math.min(\n visible.bottom,\n clip.top + ancestor.clientTop + ancestor.clientHeight,\n );\n }\n }\n\n const frame = view.frameElement;\n\n if (frame === null) break;\n const frameBox = frame.getBoundingClientRect();\n const dx = frameBox.left + frame.clientLeft;\n const dy = frameBox.top + frame.clientTop;\n\n box = {\n left: box.left + dx,\n top: box.top + dy,\n right: box.right + dx,\n bottom: box.bottom + dy,\n };\n visible = {\n left: Math.max(visible.left + dx, dx),\n top: Math.max(visible.top + dy, dy),\n right: Math.min(visible.right + dx, dx + frame.clientWidth),\n bottom: Math.min(visible.bottom + dy, dy + frame.clientHeight),\n };\n inner = frame;\n }\n\n if (outside || visible.right <= visible.left || visible.bottom <= visible.top) {\n if (scroll) {\n element.scrollIntoView({ block: \"center\", inline: \"center\", behavior: \"instant\" });\n\n return point(target, false);\n }\n\n return {\n error: \"offscreen\",\n detail: outside\n ? ref + \" is outside the viewport\"\n : `${ref} could not be scrolled into view`,\n };\n }\n const x = (visible.left + visible.right) / 2;\n const y = (visible.top + visible.bottom) / 2;\n const hit = hitAt(document, x, y);\n\n if (hit !== null && !receives(element, hit))\n return { error: \"covered\", detail: `${ref} is covered by ${describe(hit)}` };\n\n return {\n ...details(element, hit ?? element, Math.round(x), Math.round(y)),\n context: contextOf(element),\n };\n };\n\n // Suggest one visible wheel origin. Unsupported frame geometry and fully clipped panels use\n // the bounded instant fallback; guessing their coordinates could scroll an unrelated control.\n const scrollPlan = (ref: string) => {\n const element = lookup(ref);\n\n if (element === undefined || element.ownerDocument !== document) return null;\n const target = element.getBoundingClientRect();\n const centerX = (target.left + target.right) / 2;\n const centerY = (target.top + target.bottom) / 2;\n\n for (let ancestor = parentOf(element); ancestor !== null; ancestor = parentOf(ancestor)) {\n const style = window.getComputedStyle(ancestor);\n\n const horizontal =\n /^(auto|scroll)$/.test(style.overflowX) && ancestor.scrollWidth > ancestor.clientWidth;\n\n const vertical =\n /^(auto|scroll)$/.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight;\n\n if (!horizontal && !vertical) continue;\n const box = ancestor.getBoundingClientRect();\n const left = Math.max(0, box.left + ancestor.clientLeft);\n const top = Math.max(0, box.top + ancestor.clientTop);\n\n const right = Math.min(\n window.innerWidth,\n box.left + ancestor.clientLeft + ancestor.clientWidth,\n );\n\n const bottom = Math.min(\n window.innerHeight,\n box.top + ancestor.clientTop + ancestor.clientHeight,\n );\n\n if (right <= left || bottom <= top) continue;\n const x = (left + right) / 2;\n const y = (top + bottom) / 2;\n const dx = horizontal && (target.left < left || target.right > right) ? centerX - x : 0;\n const dy = vertical && (target.top < top || target.bottom > bottom) ? centerY - y : 0;\n\n if (dx === 0 && dy === 0) continue;\n const hit = hitAt(document, x, y);\n\n if (hit !== null && (hit === ancestor || ancestor.contains(hit))) return { x, y, dx, dy };\n }\n\n const dx =\n target.left < 0 || target.right > window.innerWidth ? centerX - window.innerWidth / 2 : 0;\n\n const dy =\n target.top < 0 || target.bottom > window.innerHeight ? centerY - window.innerHeight / 2 : 0;\n\n return dx === 0 && dy === 0\n ? null\n : { x: window.innerWidth / 2, y: window.innerHeight / 2, dx, dy };\n };\n\n return { controlOf, details, hitAt, hrefAttribute, linkOf, point, receives, scrollPlan, within };\n};\n\nexport type Targets = ReturnType<typeof targets>;\n\nconst ResolvedPointSchema = Schema.Struct({\n ...Point.fields,\n ...Subject.fields,\n element: Schema.String,\n box: Schema.optional(Box),\n cursor: Schema.String,\n href: Schema.optional(Schema.String),\n});\n\nexport const PointResultSchema = Schema.Union([\n ResolvedPointSchema,\n Schema.Struct({\n error: Schema.Literals([\"stale\", \"hidden\", \"offscreen\", \"disabled\", \"covered\", \"outside\"]),\n detail: Schema.String,\n }),\n]);\n\nexport const ScrollPlanSchema = Schema.NullOr(\n Schema.Struct({\n ...Point.fields,\n dx: Schema.Finite,\n dy: Schema.Finite,\n }),\n);\n","/** Scoped protocol interception at the owned session boundary; native is the default. */\nimport { Clock, Context, Effect, Fiber } from \"effect\";\nimport type { BrowserContext, CDPSession, Page as NativePage } from \"playwright-core\";\n\nimport type { CaptureSource } from \"../../Browser.ts\";\nimport { call } from \"../../BrowserError.ts\";\n\nexport const Operation = Context.Reference<string | undefined>(\"effect-browser/ProtocolOperation\", {\n defaultValue: () => undefined,\n});\n\nexport const Script = Context.Reference<string | undefined>(\"effect-browser/ProtocolScript\", {\n defaultValue: () => undefined,\n});\n\nexport interface Session {\n readonly channel: \"page\" | \"capture\" | \"browser\";\n readonly clock: Clock.Clock;\n page: string | undefined;\n readonly nativePage?: NativePage | undefined;\n}\n\nexport interface Event {\n readonly method: string;\n readonly params: unknown;\n}\n\nexport type CaptureSend = Effect.Success<ReturnType<CaptureSource[\"attach\"]>>;\n\nexport interface Hooks {\n readonly query?:\n | ((session: Session, method: string, run: () => Promise<unknown>) => Promise<unknown>)\n | undefined;\n readonly page?: ((session: Session, native: CDPSession) => CDPSession) | undefined;\n readonly native?:\n | (<A>(\n page: string,\n method: \"keyboard.down\" | \"keyboard.up\" | \"goto\",\n params: Readonly<Record<string, unknown>>,\n run: () => Promise<A>,\n ) => Promise<A>)\n | undefined;\n readonly browser?: ((connection: string, context: BrowserContext) => () => void) | undefined;\n readonly beforeOpen?: ((session: Session) => Promise<void>) | undefined;\n readonly send?: ((session: Session, send: CDPSession[\"send\"]) => CDPSession[\"send\"]) | undefined;\n readonly capture?: ((session: Session, send: CaptureSend) => CaptureSend) | undefined;\n readonly event?:\n | ((session: Session, event: Event, deliver: (event: Event) => void) => void)\n | undefined;\n readonly opened?: ((session: Session, inject: (event: Event) => void) => () => void) | undefined;\n}\n\nexport const Current = Context.Reference<Hooks>(\"effect-browser/ProtocolPort\", {\n defaultValue: () => ({}),\n});\n\nexport const labels = () => ({\n operation: Fiber.getCurrent()?.getRef(Operation),\n script: Fiber.getCurrent()?.getRef(Script),\n});\n\n/** The provider owns creation and passes its session to an optional scoped test adapter. */\nexport const openSession = Effect.fnUntraced(function* (\n open: () => Promise<CDPSession>,\n nativePage?: NativePage,\n channel: \"page\" | \"browser\" = \"page\",\n) {\n const hooks = yield* Current;\n\n const session: Session = {\n channel,\n clock: yield* Clock.Clock,\n page: undefined,\n nativePage,\n };\n\n const beforeOpen = hooks.beforeOpen;\n const operation = channel === \"browser\" ? \"requests\" : \"newPage\";\n\n if (beforeOpen !== undefined)\n yield* call(\n operation,\n () => beforeOpen(session),\n () => \"connection\",\n );\n const native = yield* call(operation, open, () => \"connection\");\n\n return hooks.page?.(session, native) ?? native;\n});\n\n/** The dedicated capture connection uses the same interception and injection rules. */\nexport const openCapture = Effect.fnUntraced(function* (\n page: string,\n source: CaptureSource,\n handlers: Parameters<CaptureSource[\"attach\"]>[1],\n) {\n const hooks = yield* Current;\n const session: Session = { channel: \"capture\", page, clock: yield* Clock.Clock };\n const beforeOpen = hooks.beforeOpen;\n\n if (beforeOpen !== undefined)\n yield* call(\n \"screencast\",\n () => beforeOpen(session),\n () => \"connection\",\n );\n\n const deliver = ({ method, params }: Event) => {\n const run = ({ method, params }: Event) => handlers.event(method, params);\n\n if (hooks.event === undefined) run({ method, params });\n else hooks.event(session, { method, params }, run);\n };\n\n const release = hooks.opened?.(session, ({ method, params }) => handlers.event(method, params));\n\n yield* Effect.addFinalizer(() => Effect.sync(() => release?.()));\n\n const send = yield* source.attach(page, {\n ...handlers,\n event: (method, params) => deliver({ method, params }),\n });\n\n return hooks.capture?.(session, send) ?? send;\n});\n","/**\n * Bounded input replies owned by the page, including after an action is interrupted.\n * Canceling a caller cannot cancel a protocol command already sent. The next action waits for\n * those replies, while a stopped run releases only held keys or buttons whose release was never submitted.\n */\nimport { Context, Data, Effect, type Scope } from \"effect\";\n\nimport { maximumSamples } from \"../../Geometry.ts\";\n\nexport const capacity = 64;\n\nexport class InputFailure extends Data.TaggedError(\"InputFailure\")<{\n readonly cause: unknown;\n}> {}\n\nexport interface Run {\n /** A native call made by this operation: cancellation cannot cancel its actual reply. */\n readonly track: <A>(reply: Promise<A>) => Promise<A>;\n /** End ownership after the record and all this operation's native replies have settled. */\n readonly afterIdle: (ended: () => void) => void;\n /** Retain authority through scoped cleanup after the replies already submitted. */\n readonly recover: (cleanup: Effect.Effect<void>, scope: Scope.Scope) => Effect.Effect<void>;\n /** Reserve a complete stroke, including its releases, before sending its first event. */\n readonly reserve: (commands: number) => Effect.Effect<void, InputFailure>;\n /** Admit every sample before a motion starts its published clock; ordinary input stays bounded separately. */\n readonly reserveMotion: (commands: number) => Effect.Effect<void, InputFailure>;\n readonly send: (command: () => Promise<unknown>) => Effect.Effect<void, InputFailure>;\n readonly down: (\n key: string,\n press: () => Promise<unknown>,\n release: () => Promise<unknown>,\n ) => Effect.Effect<void, InputFailure>;\n readonly up: (key: string) => Effect.Effect<void, InputFailure>;\n readonly drain: Effect.Effect<void, InputFailure>;\n /** Stop future input and submit missing releases without waiting indefinitely for replies. */\n readonly close: Effect.Effect<void>;\n}\n\n/** Native page calls join their operation's reply ownership, including script mutations. */\nexport const Current = Context.Reference<Run | undefined>(\"effect-browser/internal/input/Current\", {\n defaultValue: () => undefined,\n});\n\nexport const make = () => {\n const outstanding = new Set<Promise<void>>();\n\n // A timed-out action keeps capacity until its real replies arrive. Waiting for them sends\n // nothing, so cancellation here cannot leave a detached continuation that later types.\n const idle = Effect.gen(function* () {\n while (outstanding.size > 0) yield* Effect.promise(() => Promise.all(outstanding));\n });\n\n const begin = Effect.gen(function* () {\n yield* idle;\n const pending = new Set<Promise<void>>();\n const held: Array<{ readonly key: string; readonly release: () => Promise<unknown> }> = [];\n let failure: InputFailure | undefined;\n let reserved = 0;\n let closed = false;\n const observed = new WeakMap<Promise<unknown>, { input: boolean }>();\n const endings = new Set<() => void>();\n\n const track = <A>(response: Promise<A>, input = false): Promise<A> => {\n const existing = observed.get(response);\n\n if (existing !== undefined) {\n existing.input ||= input;\n\n return response;\n }\n const entry = { input };\n\n observed.set(response, entry);\n\n const reply = response\n .then(\n () => undefined,\n (cause: unknown) => {\n if (entry.input) failure ??= new InputFailure({ cause });\n },\n )\n .then(() => {\n pending.delete(reply);\n outstanding.delete(reply);\n if (pending.size === 0) {\n for (const end of endings) end();\n endings.clear();\n }\n });\n\n pending.add(reply);\n outstanding.add(reply);\n\n return response;\n };\n\n const requireOpen = Effect.suspend(() =>\n closed\n ? Effect.fail(new InputFailure({ cause: new Error(\"the input run has stopped\") }))\n : Effect.void,\n );\n\n const requireSuccess = Effect.suspend(() =>\n failure === undefined ? Effect.void : Effect.fail(failure),\n );\n\n const submit = (command: () => Promise<unknown>) => {\n if (reserved < 1) throw new Error(\"input must reserve capacity before dispatch\");\n reserved--;\n try {\n void track(command(), true);\n } catch (cause) {\n failure ??= new InputFailure({ cause });\n }\n };\n\n const reserve = (commands: number, maximum: number, limit: number) =>\n Effect.gen(function* () {\n yield* requireOpen;\n yield* requireSuccess;\n if (!Number.isInteger(commands) || commands < 1 || commands > maximum)\n return yield* Effect.die(new Error(\"invalid input reservation\"));\n while (outstanding.size + reserved + commands > limit) {\n yield* Effect.promise(() => Promise.race(outstanding));\n yield* requireOpen;\n yield* requireSuccess;\n }\n reserved += commands;\n });\n\n const run: Run = {\n track,\n afterIdle: (end) => {\n if (pending.size === 0) end();\n else endings.add(end);\n },\n recover: (cleanup, scope) =>\n Effect.gen(function* () {\n const replies = [...pending];\n const done = Promise.withResolvers<void>();\n\n // This reservation prevents a new action or suspension from overtaking cleanup.\n void track(done.promise);\n yield* Effect.promise(() => Promise.all(replies)).pipe(\n Effect.andThen(cleanup),\n Effect.ensuring(Effect.sync(() => done.resolve())),\n Effect.provideService(Current, run),\n Effect.interruptible,\n Effect.forkIn(scope),\n );\n }),\n reserve: (commands) => reserve(commands, capacity, capacity),\n // A dense stroke cannot wait for replies midway without changing its published timing.\n // Its finite reservation also leaves room for the ordinary pool's already-owned releases.\n reserveMotion: (commands) => reserve(commands, maximumSamples, capacity + maximumSamples),\n send: (command) =>\n Effect.gen(function* () {\n yield* requireOpen;\n yield* requireSuccess;\n yield* Effect.sync(() => submit(command));\n yield* requireSuccess;\n }),\n down: (key, press, release) =>\n Effect.gen(function* () {\n yield* requireOpen;\n yield* requireSuccess;\n yield* Effect.sync(() => {\n held.push({ key, release });\n submit(press);\n });\n yield* requireSuccess;\n }),\n up: (key) =>\n Effect.gen(function* () {\n yield* requireOpen;\n yield* Effect.sync(() => {\n const index = held.findLastIndex((entry) => entry.key === key);\n const entry = held[index];\n\n if (entry === undefined) return;\n // Submission owns the release, even if its reply fails. Retrying an uncertain\n // release could run page handlers twice, so cleanup never sends it again.\n held.splice(index, 1);\n submit(entry.release);\n });\n yield* requireSuccess;\n }),\n drain: Effect.gen(function* () {\n while (pending.size > 0) yield* Effect.promise(() => Promise.all(pending));\n yield* requireSuccess;\n }),\n close: Effect.sync(() => {\n if (closed) return;\n closed = true;\n for (const entry of held.toReversed()) submit(entry.release);\n held.length = 0;\n reserved = 0;\n }),\n };\n\n return run;\n });\n\n /** `idle` lets an action wait, in its page's turn, for the page's earlier replies. */\n return { idle, begin };\n};\n","/**\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 * as Errors from \"../../BrowserError.ts\";\nimport type { BrowserEvent } from \"../../BrowserEvent.ts\";\nimport * as BrowserClock from \"../../Clock.ts\";\nimport type { InputGuard, Point } from \"../../Page.ts\";\nimport type { Gate } from \"../input/gate.ts\";\nimport * as Lane from \"./lane.ts\";\nimport type { Openings } from \"./openings.ts\";\nimport * as Port from \"./port.ts\";\nimport { Current } from \"./replies.ts\";\n\n/** Why a page is gone. */\nexport type ClosedCause = Errors.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 /** The page clock's event name, when the browser runs one in each document. */\n readonly pageTime?: string | 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 /** This tracking connection, distinct from the provider session and capture socket. */\n readonly connection: 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 readonly nativePort?: Port.Hooks[\"native\"] | undefined;\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 /** Browser-wide input authority; direct internal page fixtures need not provide one. */\n readonly inputGate?: Gate | undefined;\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, Errors.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, Errors.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\nexport { call, reasonOf, undispatched, failWith, refuse } from \"../../BrowserError.ts\";\nimport { call, failWith, undispatched } from \"../../BrowserError.ts\";\n\nexport const contextGone = (error: Errors.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/** Track the promise returned to the action, after tracing wraps it, so input counts once. */\nconst track = <A>(reply: Promise<A>) => Fiber.getCurrent()?.getRef(Current)?.track(reply) ?? reply;\n\n// A message's size on the wire, give or take its envelope.\nconst sizeOf = (value: unknown) =>\n value === undefined ? 0 : new TextEncoder().encode(JSON.stringify(value)).byteLength;\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) =>\n undispatched(operation, new Errors.Failed({ detail: error.message })),\n ),\n );\n\nexport const make = (options: MakeOptions, scope: Scope.Scope) => {\n const { id, clock } = options;\n const now = () => BrowserClock.monotonicMillis(clock);\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 track(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 track(\n 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\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, () => options.untilLost(track(run())), options.closedBy, timeoutMillis).pipe(\n Effect.provideService(Port.Operation, operation),\n );\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: () =>\n failWith(operation, new Errors.Timeout({ millis: Duration.toMillis(duration) })),\n });\n\n // Stop a navigation whose bounded wait failed. The stop and original mutation keep their\n // actual replies owned; this cleanup does not turn an unanswered acknowledgement into success.\n const stopLoading = native(\"stopLoading\", () => send(\"Page.stopLoading\")).pipe(\n within(\"stopLoading\", options.settings.navigationTimeout),\n Effect.ignore,\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 Errors.Closed({ cause: options.closedBy() })),\n scope,\n beforeWrite: options.inputGate?.check,\n refusal: options.inputGate?.refused,\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 scope,\n owned,\n span,\n protocol,\n native,\n within,\n stopLoading,\n activity,\n noteInput,\n };\n};\n\nexport type PageContext = ReturnType<typeof make>;\n","/**\n * In the page: one step of what a held page shows, in one call. The document is scrolled first,\n * then the page clock in the main world is told what to do, so the page's own handlers see the\n * scroll as its time moves, then elements are posed and the overlay is drawn. A pose naming an\n * element the document no longer has is found before any of it, and the step does nothing. The\n * clock hears an event only it and the\n * library know the name of (see `clock.inpage.ts`), and acknowledges it. See `names.inpage.ts` for\n * what a page-side part may use.\n */\nimport type { Overlay } from \"./overlay.inpage.ts\";\nimport type { PoseRequest, Posing } from \"./pose.inpage.ts\";\n\nexport interface StepRequest {\n /** The page clock's event name. */\n readonly clock: string;\n readonly op: \"hold\" | \"advance\" | \"release\";\n readonly by: number;\n /** Where to scroll the document to, in CSS pixels down it, or null to leave it. */\n readonly scroll: number | null;\n /** What the overlay shows, null for nothing; left out, the overlay is left alone. */\n readonly markup?: string | null | undefined;\n /** The elements to pose, and no others; left out, poses are left alone. */\n readonly poses?: ReadonlyArray<PoseRequest> | undefined;\n}\n\nexport const time = (overlaid: Overlay, posing: Posing) => {\n const step = (request: StepRequest) => {\n const posed = request.poses === undefined ? undefined : posing.prepare(request.poses);\n\n if (posed !== undefined && !(\"apply\" in posed))\n return { told: false, drawn: null, scroll: { x: scrollX, y: scrollY }, ...posed };\n if (request.scroll !== null)\n scrollTo({ left: scrollX, top: request.scroll, behavior: \"instant\" });\n const detail = { op: request.op, by: request.by };\n\n const told = !document.dispatchEvent(\n new CustomEvent(request.clock, { detail, cancelable: true }),\n );\n\n posed?.apply();\n const drawn = request.markup === undefined ? null : overlaid.draw(request.markup);\n\n return { told, drawn, scroll: { x: scrollX, y: scrollY } };\n };\n\n return { step };\n};\n\nexport type Time = ReturnType<typeof time>;\n","/**\n * The bridge to the page script, and the page's documents as its own session sees them commit and\n * load, so a load follows its commit. At the library's first read of a page, its own protocol\n * session registers the script, so every later document runs it in an isolated world from its\n * start; calls go to the current document's world. The script is composed from the domains'\n * page-side parts, the `*.inpage.ts` modules, in the order they depend on one another. At the first\n * read of a page's changes, its session registers the recorder too, so every later document\n * records from its start.\n */\nimport { Deferred, Effect, Schema, SynchronizedRef } from \"effect\";\n\nimport type { InitScript } from \"../../Browser.ts\";\nimport { type BrowserError, Failed } from \"../../BrowserError.ts\";\nimport { Navigated, PageLoaded } from \"../../BrowserEvent.ts\";\nimport { match } from \"../../Matching.ts\";\nimport * as Url from \"../../Url.ts\";\nimport { edit, type Edit } from \"../input/edit.inpage.ts\";\nimport { evidence } from \"../input/evidence.inpage.ts\";\nimport { guard, type Guard } from \"../input/guard.inpage.ts\";\nimport { targets, type Targets } from \"../input/targets.inpage.ts\";\nimport { context } from \"../reading/context.inpage.ts\";\nimport { controls } from \"../reading/controls.inpage.ts\";\nimport { expectations, type Expectations } from \"../reading/expect.inpage.ts\";\nimport { layout, type Layouts } from \"../reading/layout.inpage.ts\";\nimport { elements, names } from \"../reading/names.inpage.ts\";\nimport { outline, type Outline } from \"../reading/outline.inpage.ts\";\nimport { ready } from \"../reading/ready.inpage.ts\";\nimport { states, subjects, type Subjects } from \"../reading/subjects.inpage.ts\";\nimport { text, type Texts } from \"../reading/text.inpage.ts\";\nimport { walk } from \"../reading/walk.inpage.ts\";\nimport { changes, type Changes } from \"../timeline/changes.inpage.ts\";\nimport { fold } from \"../timeline/fold.inpage.ts\";\nimport { history } from \"../timeline/history.inpage.ts\";\nimport { marks } from \"../timeline/marks.inpage.ts\";\nimport { record, type Recorder } from \"../timeline/record.inpage.ts\";\nimport { sight } from \"../timeline/sight.inpage.ts\";\nimport { animations, clock, timers } from \"./clock.inpage.ts\";\nimport { compose } from \"./compose.inpage.ts\";\nimport { contextGone, decodeWith, failWith, type PageContext } from \"./context.ts\";\nimport { overlay, type Overlay } from \"./overlay.inpage.ts\";\nimport { Script } from \"./port.ts\";\nimport { pose, type Posing } from \"./pose.inpage.ts\";\nimport { time, type Time } from \"./time.inpage.ts\";\n\n/** What the script installs: a version, and a function of one of its parts for each call. */\nexport interface PageApi {\n readonly version: number;\n readonly refs: { next: number };\n dispose: () => void;\n snapshot: Outline[\"snapshot\"];\n find: Subjects[\"find\"];\n layout: Layouts[\"read\"];\n overlay: Overlay[\"draw\"];\n pose: Posing[\"set\"];\n unpose: Posing[\"clear\"];\n step: Time[\"step\"];\n until: Expectations[\"until\"];\n text: Texts[\"read\"];\n record: Recorder[\"start\"];\n stopRecord: Recorder[\"stop\"];\n changes: Changes[\"read\"];\n ready: ReturnType<typeof ready>[\"wait\"];\n settle: ReturnType<typeof ready>[\"settle\"];\n point: Targets[\"point\"];\n scrollPlan: Targets[\"scrollPlan\"];\n viewport: Outline[\"viewport\"];\n /** The screen as the page reads it, which another session may emulate. */\n screenSize: () => {\n readonly width: number;\n readonly height: number;\n readonly ratio: number;\n };\n prepareInput: Guard[\"prepareInput\"];\n validateInput: Guard[\"validateInput\"];\n typeable: Edit[\"typeable\"];\n focus: Edit[\"focus\"];\n focusOn: Edit[\"focusOn\"];\n select: Edit[\"select\"];\n}\n\ndeclare global {\n // The API this script installs, which exists only inside the library's isolated world.\n var __effectBrowser: PageApi | undefined;\n}\n\n/** Named factories make the composition contract independent of their declaration order. */\nexport const parts = {\n compose,\n elements,\n names,\n walk,\n match,\n context,\n subjects,\n states,\n expectations,\n text,\n layout,\n controls,\n fold,\n history,\n sight,\n marks,\n record,\n changes,\n ready,\n outline,\n targets,\n evidence,\n guard,\n edit,\n overlay,\n pose,\n time,\n addresses: Url.addresses,\n};\n\n// Like the parts it receives, this is evaluated from its source text. The named function also\n// hashes its own source, so changing the composition invalidates an installation too.\ntype Parts = typeof parts;\n\nexport function install(parts: Parts): PageApi {\n const source =\n install.toString() +\n Object.entries(parts)\n .map(([name, factory]) => name + factory.toString())\n .join(\"\");\n\n let version = 0x811c9dc5;\n\n for (let index = 0; index < source.length; index++)\n version = Math.imul(version ^ source.charCodeAt(index), 0x01000193);\n version >>>= 0;\n const installed = globalThis.__effectBrowser;\n\n if (installed !== undefined && installed.version === version) return installed;\n installed?.dispose?.();\n\n const { named, walked, placing, overlaid, posing, reads } = parts.compose(\n parts,\n installed?.refs?.next,\n );\n\n const located = parts.targets(named, walked, placing);\n const guarded = parts.guard(named, located, parts.evidence(named, placing));\n const edited = parts.edit(named, guarded, placing);\n\n const api: PageApi = {\n ...reads,\n version,\n dispose: reads.stopRecord,\n step: parts.time(overlaid, posing).step,\n point: located.point,\n scrollPlan: located.scrollPlan,\n screenSize: () => ({ width: screen.width, height: screen.height, ratio: devicePixelRatio }),\n prepareInput: guarded.prepareInput,\n validateInput: guarded.validateInput,\n typeable: edited.typeable,\n focus: edited.focus,\n focusOn: edited.focusOn,\n select: edited.select,\n };\n\n globalThis.__effectBrowser = api;\n\n return api;\n}\n\nconst encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));\n\nexport const clockParts = { timers, animations };\n\n// A factory applied to its parts, as one expression of their sources.\nconst applied = (factory: { toString(): string }, given: Record<string, { toString(): string }>) =>\n `(${factory.toString()})({${Object.entries(given)\n .map(([name, part]) => `${name}: ${part.toString()}`)\n .join(\", \")}})`;\n\n/**\n * The expression of the page clock, a function of its event name, which the page's main world runs\n * before its own scripts; packaging freezes it.\n */\nexport const clockSource = applied(clock, clockParts);\n\n/** The expression that installs the script and evaluates to its API; packaging freezes it. */\nexport const installSource = applied(install, parts);\n\n/**\n * What new documents run before their own scripts: the page clock under its event name, first, so\n * a caller's script that keeps a timer keeps the clock's, and then the caller's scripts, each\n * everywhere or as a block where its `match` allows.\n */\nexport const documentScripts = (\n clockName: string | undefined,\n scripts: ReadonlyArray<InitScript>,\n): ReadonlyArray<string> => [\n ...(clockName === undefined ? [] : [`${clockSource}(${encodeString(clockName)})`]),\n ...scripts.map(({ match, source }) =>\n match === undefined ? source : `if (${String(match)}.test(location.href)) {\\n${source}\\n}`,\n ),\n];\n\nconst worldName = \"effect-browser\";\n\n// What starts the recorder in each new document, after the script installed itself there.\nconst recorderSource = `if (globalThis === globalThis.top) globalThis.__effectBrowser?.record();`;\n\n// What a call reads in a world without the script's API. A context id can name another world once\n// the page has moved to a new process, so a cached id that reads this is not the library's world.\nconst missing = \"effect-browser: no __effectBrowser in this world\";\nconst missingSource = encodeString(missing);\n\nconst isMissing = (error: BrowserError) =>\n error.reason._tag === \"Failed\" && error.reason.detail === missing;\n\nconst Evaluated = Schema.Struct({\n value: Schema.optionalKey(Schema.Unknown),\n error: Schema.optionalKey(Schema.String),\n nextRef: Schema.Finite,\n});\n\n/** A frame as a page session reports its commit. */\nexport const Commit = Schema.Struct({\n parentId: Schema.optionalKey(Schema.String),\n loaderId: Schema.String,\n url: Schema.String,\n urlFragment: Schema.optionalKey(Schema.String),\n});\n\n/** `Page.frameNavigated` or `Page.navigatedWithinDocument`, as far as `mainFrame` reads them. */\nexport const MainFrameEvent = Schema.Union([\n Schema.Struct({ frame: Commit }),\n Schema.Struct({ frameId: Schema.String, url: Schema.String }),\n]);\n\n/** A commit's loader and its address, redacted. */\nexport const commitOf = ({ loaderId, url, urlFragment = \"\" }: typeof Commit.Type) => ({\n loader: loaderId,\n url: Url.redact(url + urlFragment),\n});\n\n/**\n * What a page session's commit or move says of `page`'s main frame: a new document's `loader` and\n * its address, or a move's address; nothing for another frame. Only a commit is a new document:\n * `frameStartedLoading` also fires on `pushState`, a move within the document.\n */\nexport const mainFrame = (page: string, event: typeof MainFrameEvent.Type) =>\n \"frame\" in event\n ? event.frame.parentId === undefined\n ? commitOf(event.frame)\n : undefined\n : event.frameId === page\n ? { loader: undefined, url: Url.redact(event.url) }\n : undefined;\n\n/** A call to the page script, its arguments quoted as JavaScript literals. */\nexport const scriptCall = (name: string, ...args: ReadonlyArray<unknown>): string =>\n `${name}(${args.map((arg) => JSON.stringify(arg)).join(\", \")})`;\n\nconst runIn = (page: PageContext, operation: string, expression: string, contextId: number) =>\n page\n .native(operation, () =>\n page.protocol.send(\"Runtime.evaluate\", {\n contextId,\n expression,\n returnByValue: true,\n awaitPromise: true,\n }),\n )\n .pipe(\n Effect.flatMap(({ result, exceptionDetails: thrown }) =>\n thrown === undefined\n ? Effect.succeed<unknown>(result.value)\n : failWith(\n operation,\n new Failed({ detail: thrown.exception?.description ?? thrown.text }),\n ),\n ),\n );\n\n/** Session-owned registrations; the recorder can expire independently of the page script. */\nconst registrationFor = Effect.fnUntraced(function* (page: PageContext) {\n const { native, span } = page;\n const { send } = page.protocol;\n\n // How far this session has registered: the script, then the recorder, which the first read of\n // changes asks for. One caller takes each step, once, while the others wait.\n const registration = yield* SynchronizedRef.make<{\n readonly script: boolean;\n readonly recorder?: string | undefined;\n }>({ script: false });\n\n // The registration belongs to this session and the world to the page, so a session that attaches\n // later, as after a reconnect, registers again and finds the script already installed. With the\n // Page domain enabled, a source runs in each new document, in the order registered;\n // `runImmediately` runs it now.\n const addScript = (operation: string, source: string) =>\n native(operation, () =>\n send(\"Page.addScriptToEvaluateOnNewDocument\", { source, worldName, runImmediately: true }),\n );\n\n const register = (operation: string) =>\n Effect.all(\n [\n page.paging(operation),\n addScript(operation, `if (globalThis === globalThis.top) ${installSource};`),\n ],\n { concurrency: \"unbounded\" },\n ).pipe(span(\"Page.register\", {}, \"Debug\"));\n\n /** Register the script once; the change-reader lifetime owns its removable registration. */\n const ensure = (operation: string, recorder: boolean) =>\n SynchronizedRef.updateEffect(registration, (state) =>\n Effect.gen(function* () {\n if (!state.script) yield* register(operation);\n if (recorder && state.recorder === undefined) {\n const registered = yield* addScript(operation, recorderSource);\n\n return { script: true, recorder: registered.identifier };\n }\n\n return { ...state, script: true };\n }),\n );\n\n const removeRecorder = (operation: string) =>\n SynchronizedRef.updateEffect(registration, (state) => {\n const identifier = state.recorder;\n\n return identifier === undefined\n ? Effect.succeed(state)\n : native(operation, () =>\n send(\"Page.removeScriptToEvaluateOnNewDocument\", { identifier }),\n ).pipe(Effect.as({ script: true }));\n });\n\n return { ensure, removeRecorder };\n});\n\nexport const make = Effect.fnUntraced(function* (page: PageContext) {\n const { id, cdp, native, span, publish, now } = page;\n const { send } = page.protocol;\n const { ensure, removeRecorder } = yield* registrationFor(page);\n\n // The current document's world, forgotten when the main frame commits another document; the\n // commits this session has seen, the latest marked on the page; the page's address; and how far\n // the current document has loaded.\n let world: number | undefined;\n let documents = 0;\n let nextDocument = Deferred.makeUnsafe<void>();\n let url = Url.redact(page.url);\n let loaded: PageLoaded | undefined;\n // Every script call can allocate refs (including guards and point input), so the bridge,\n // rather than individual readers, owns the floor across the page's documents.\n let nextRef = 1;\n // The latest commits' loaders and the documents they began, newest last: a capture connection\n // sees the same commits, and numbers its frames by them.\n const loaders = new Map<string, number>();\n\n const onMainFrame = (event: typeof MainFrameEvent.Type) => {\n const seen = mainFrame(id, event);\n\n if (seen === undefined) return;\n if (seen.loader !== undefined) {\n documents++;\n loaders.delete(seen.loader);\n loaders.set(seen.loader, documents);\n const [oldest] = loaders.keys();\n\n if (loaders.size > 8 && oldest !== undefined) loaders.delete(oldest);\n page.activity.documentAt = now();\n world = undefined;\n loaded = undefined;\n Deferred.doneUnsafe(nextDocument, Effect.void);\n nextDocument = Deferred.makeUnsafe<void>();\n }\n url = seen.url;\n const sameDocument = seen.loader === undefined;\n\n publish(new Navigated({ at: now(), page: id, url, document: documents, sameDocument }));\n };\n\n // The session tells these of the main frame alone.\n const onLoaded = (state: PageLoaded[\"state\"]) => () => {\n loaded = new PageLoaded({ at: now(), page: id, state });\n publish(loaded);\n };\n\n cdp.on(\"Page.frameNavigated\", onMainFrame);\n cdp.on(\"Page.navigatedWithinDocument\", onMainFrame);\n cdp.on(\"Page.domContentEventFired\", onLoaded(\"domcontentloaded\"));\n cdp.on(\"Page.loadEventFired\", onLoaded(\"load\"));\n\n /**\n * The main-frame commits seen so far, once the Page domain, which registration turned on, has\n * answered, so that every later one counts. A commit within about one round trip of the count\n * can still be missed.\n */\n const currentDocument = (operation: string) =>\n page.paging(operation).pipe(Effect.map(() => documents));\n\n /** What a frame that arrives now shows: its session, the page's current document and address. */\n const frameTag = () => ({\n session: page.session,\n connection: page.connection,\n document: documents,\n url,\n });\n\n /** The document the main frame's latest commit of `loader` began, if this session counted it. */\n const documentOf = (loader: string) => loaders.get(loader);\n\n const createWorld = (operation: string) =>\n Effect.gen(function* () {\n yield* ensure(operation, false);\n const document = documents;\n\n // The main frame's id is the page's target id.\n const created = yield* native(operation, () =>\n send(\"Page.createIsolatedWorld\", { frameId: id, worldName }),\n );\n\n // A world the page replaced while it was being looked up serves this call, not later ones.\n if (document === documents) world = created.executionContextId;\n\n return created.executionContextId;\n }).pipe(span(\"Page.createWorld\", {}, \"Debug\"));\n\n /** The current document's world, created if it has none yet. */\n const current = (operation: string) =>\n Effect.suspend(() => (world === undefined ? createWorld(operation) : Effect.succeed(world)));\n\n /** A world of the current document without the page script, as the clock probe needs. */\n const bareWorld = (operation: string) =>\n native(operation, () =>\n send(\"Page.createIsolatedWorld\", { frameId: id, worldName: `${worldName}-clock` }),\n ).pipe(Effect.map((created) => created.executionContextId));\n\n const run = (operation: string, expression: string, contextId: number) =>\n runIn(page, operation, expression, contextId);\n\n const evaluateIn = (operation: string, call: string, contextId: number) =>\n Effect.gen(function* () {\n const result = yield* run(\n operation,\n `(async () => {\n const api = globalThis.__effectBrowser;\n if (api === undefined) return ${missingSource};\n api.refs.next = Math.max(api.refs.next, ${nextRef});\n try { return { value: await globalThis.__effectBrowser.${call}, nextRef: api.refs.next }; }\n catch (error) { return { error: error instanceof Error ? error.message : String(error), nextRef: api.refs.next }; }\n })()`,\n contextId,\n );\n\n if (result === missing) return yield* failWith(operation, new Failed({ detail: missing }));\n const evaluated = yield* decodeWith(operation, Evaluated)(result);\n\n nextRef = Math.max(nextRef, evaluated.nextRef);\n\n return evaluated.error === undefined\n ? evaluated.value\n : yield* failWith(operation, new Failed({ detail: evaluated.error }));\n }).pipe(\n // One round trip to the page. Its arguments can hold typed text, so only the call is named.\n span(\"Page.evaluate\", { function: call.split(\"(\")[0] }, \"Trace\"),\n Effect.provideService(Script, call.split(\"(\")[0]),\n );\n\n // Ordinary reads can recreate a document's world. Approval validation deliberately cannot. A\n // world found by its name that lacks the script, in a document the registration missed, gets it.\n const evaluateWithContext = (operation: string, call: string) => {\n const attempt = (contextId: number) =>\n evaluateIn(operation, call, contextId).pipe(Effect.map((value) => ({ contextId, value })));\n\n const again = createWorld(operation).pipe(\n Effect.flatMap((contextId) =>\n attempt(contextId).pipe(\n Effect.catchIf(isMissing, () =>\n run(operation, `${installSource}.version`, contextId).pipe(\n Effect.andThen(attempt(contextId)),\n ),\n ),\n ),\n ),\n );\n\n return current(operation).pipe(\n Effect.flatMap(attempt),\n Effect.catchIf(contextGone, () => again),\n );\n };\n\n const evaluate = (operation: string, call: string) =>\n evaluateWithContext(operation, call).pipe(Effect.map(({ value }) => value));\n\n return {\n current,\n bareWorld,\n evaluate,\n evaluateIn,\n evaluateWithContext,\n currentDocument,\n /** Wait for the owning protocol session to observe a replacement before retrying its read. */\n waitForDocument: (before: number) =>\n Effect.suspend(() => (documents === before ? Deferred.await(nextDocument) : Effect.void)),\n frameTag,\n documentOf,\n /** How far the current document has loaded, as this session heard; nothing until parsed. */\n loaded: () => loaded,\n /** Register the recorder, so every later document records from its start. */\n registerRecorder: (operation: string) => ensure(operation, true),\n /** Stop future documents and the current recorder at the host idle deadline. */\n unregisterRecorder: (operation: string) =>\n removeRecorder(operation).pipe(Effect.andThen(evaluate(operation, scriptCall(\"stopRecord\")))),\n };\n});\n\nexport type Bridge = Effect.Success<ReturnType<typeof make>>;\n","/** Scoped dialog responses publish their actual outcome and invalidate their page after failed answers. */\nimport { Effect, Queue } from \"effect\";\nimport type { Dialog, Page as PlaywrightPage } from \"playwright-core\";\n\nimport type { BrowserError } from \"../../BrowserError.ts\";\nimport * as Events from \"../../BrowserEvent.ts\";\n\n/**\n * What a page's own Playwright events publish, its close and crash aside, while its scope is\n * open. Dialogs are answered: alerts accepted, others dismissed. The page's own session tells its\n * documents' commits and loads.\n */\nexport const listen = Effect.fnUntraced(function* (\n playwright: PlaywrightPage,\n page: string,\n publish: (event: Events.BrowserEvent) => number,\n now: () => number,\n answer: (accept: boolean) => Effect.Effect<void, BrowserError>,\n on: { readonly close: () => void; readonly crash: () => void; readonly failed: () => void },\n) {\n const dialogs = yield* Queue.bounded<Pick<Events.DialogShown, \"kind\" | \"message\">>(8);\n\n const dialog = (shown: Dialog) => {\n if (!Queue.offerUnsafe(dialogs, { kind: shown.type(), message: shown.message().slice(0, 500) }))\n on.failed();\n };\n\n yield* Queue.take(dialogs).pipe(\n Effect.flatMap(({ kind, message }) => {\n const accept = kind === \"alert\" || kind === \"beforeunload\";\n\n const record = (answer: Events.DialogShown[\"answer\"]) =>\n Effect.sync(() => {\n publish(new Events.DialogShown({ at: now(), page, kind, message, answer }));\n });\n\n return answer(accept).pipe(\n Effect.tap(() => record(accept ? \"accepted\" : \"dismissed\")),\n Effect.tapError(() => record(\"failed\").pipe(Effect.andThen(Effect.sync(on.failed)))),\n );\n }),\n Effect.forever,\n Effect.forkScoped,\n );\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n playwright.on(\"close\", on.close);\n playwright.on(\"crash\", on.crash);\n playwright.on(\"dialog\", dialog);\n }),\n () =>\n Effect.sync(() => {\n playwright.off(\"close\", on.close);\n playwright.off(\"crash\", on.crash);\n playwright.off(\"dialog\", dialog);\n }),\n );\n});\n","/** Connection identity uses the supplied SecureRandom service, or the host's Web Crypto on Node/Bun. */\nimport { Effect, Option } from \"effect\";\nimport { SecureRandom } from \"effect/crypto\";\n\nimport { Failed } from \"../../BrowserError.ts\";\nimport { undispatched } from \"./context.ts\";\n\nconst failed = () => undispatched(\"make\", new Failed({ detail: \"Could not name connection\" }));\n\nexport const make = Effect.gen(function* () {\n const supplied = yield* Effect.serviceOption(SecureRandom.SecureRandom);\n\n return yield* Option.isSome(supplied)\n ? supplied.value.uuidV4()\n : // oxlint-disable-next-line no-restricted-properties -- this host fallback runs only when the captured SecureRandom service is absent\n Effect.try({ try: () => globalThis.crypto.randomUUID(), catch: failed });\n});\n","/** A page's input waits for the actual tabs it opened to finish the browser's registration. */\nimport { Deferred, Effect, Exit } from \"effect\";\nimport type { CDPSession, Page as PlaywrightPage } from \"playwright-core\";\n\nimport {\n undispatched,\n type BrowserError,\n Closed,\n Failed,\n type Reason,\n} from \"../../BrowserError.ts\";\nimport type * as Page from \"../../Page.ts\";\n\n/** How the browser's registration of each tab it was told of ended, once it has. */\nexport type Registrations = WeakMap<PlaywrightPage, Deferred.Deferred<Page.Page, BrowserError>>;\n\nexport interface Mark {\n windows: number;\n readonly registrations: Array<Effect.Effect<void, BrowserError>>;\n changed: Deferred.Deferred<void>;\n}\n\nexport const make = Effect.fnUntraced(function* (\n playwright: PlaywrightPage,\n cdp: CDPSession,\n registrations: Registrations,\n closedBy: () => Closed[\"cause\"],\n) {\n const failed = (reason: Reason) => Exit.fail(undispatched(\"newPage\", reason));\n\n let active: Mark | undefined;\n const gone = Deferred.makeUnsafe<never, BrowserError>();\n\n const windowOpened = () => {\n if (active !== undefined) active.windows += 1;\n };\n\n const popup = (opened: PlaywrightPage) => {\n if (active === undefined) return;\n // Playwright emits the context's page event first, so its owner already has this exact\n // popup's registration. A window notification alone has no target id and cannot name it.\n const registered = registrations.get(opened);\n\n active.registrations.push(\n registered === undefined\n ? failed(new Failed({ detail: \"the popup has no registration\" }))\n : Deferred.await(registered).pipe(Effect.asVoid),\n );\n Deferred.doneUnsafe(active.changed, Exit.void);\n active.changed = Deferred.makeUnsafe<void>();\n };\n\n const clear = Effect.sync(() => {\n active = undefined;\n });\n\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n cdp.on(\"Page.windowOpen\", windowOpened);\n playwright.on(\"popup\", popup);\n }),\n () =>\n Effect.sync(() => {\n active = undefined;\n cdp.off(\"Page.windowOpen\", windowOpened);\n playwright.off(\"popup\", popup);\n Deferred.doneUnsafe(gone, failed(new Closed({ cause: closedBy() })));\n }),\n );\n\n return {\n mark: () => {\n const mark: Mark = { windows: 0, registrations: [], changed: Deferred.makeUnsafe<void>() };\n\n active = mark;\n\n return mark;\n },\n clear,\n settle: (mark: Mark) =>\n Effect.gen(function* () {\n // A blocked window or a tab that closes as it opens may never become a Playwright popup.\n // Discovery and registration both share the input's deadline, so an unresolved opening\n // fails with potentially dispatched input rather than claiming the tab has been tracked.\n while (mark.registrations.length < mark.windows) yield* Deferred.await(mark.changed);\n // A real popup has a known registration; its failure stays a failure, and its wait shares\n // the input's deadline rather than quietly returning before the browser tracks it.\n yield* Effect.forEach(mark.registrations, (registration) => registration);\n }).pipe(Effect.raceFirst(Deferred.await(gone)), Effect.ensuring(clear)),\n };\n});\n\nexport type Openings = Effect.Success<ReturnType<typeof make>>;\n","/**\n * Sending input to the browser. Each mouse event, key and inserted text goes out on the page's\n * protocol session, stamped with the browser's clock when its run has a mapping, and is published\n * as it is submitted.\n */\nimport { Effect, MutableRef, Option } from \"effect\";\n\nimport {\n KeyChanged,\n PointerPressed,\n PointerReleased,\n TextInserted,\n WheelScrolled,\n} from \"../../BrowserEvent.ts\";\nimport * as BrowserClock from \"../../Clock.ts\";\nimport type { Point } from \"../../Geometry.ts\";\nimport { type PageContext, reasonOf, undispatched } from \"../page/context.ts\";\nimport type * as Replies from \"../page/replies.ts\";\n\nexport interface MouseEvent extends Point {\n readonly type: \"mouseMoved\" | \"mousePressed\" | \"mouseReleased\" | \"mouseWheel\";\n readonly button?: \"none\" | \"left\" | \"right\" | \"middle\";\n readonly buttons?: number;\n readonly clickCount?: number;\n readonly deltaX?: number;\n readonly deltaY?: number;\n}\n\nconst buttonMask = { none: 0, left: 1, right: 2, middle: 4 } as const;\n\n/** A mouse button going down or up at a point, as the `clickCount`th click. */\nexport const buttonAt = (\n type: \"mousePressed\" | \"mouseReleased\",\n point: Point,\n button: keyof typeof buttonMask = \"left\",\n clickCount = 1,\n): MouseEvent => ({\n type,\n ...point,\n button,\n buttons: type === \"mousePressed\" ? buttonMask[button] : 0,\n clickCount,\n});\n\nexport const make = (page: PageContext) => {\n const { id, pointer, publish, now, noteInput, closedBy } = page;\n const { send } = page.protocol;\n // Each run's clock mapping, recorded when it begins.\n const inputClocks = new WeakMap<Replies.Run, BrowserClock.Estimate>();\n\n // Every run records its mapping when it begins; a missing one leaves Chromium's own receipt time.\n const stamp = (estimate: BrowserClock.Estimate | undefined, at: number) =>\n estimate === undefined ? {} : { timestamp: BrowserClock.toBrowserSeconds(estimate, at) };\n\n const inputCall = <A>(operation: string, effect: Effect.Effect<A, Replies.InputFailure>) =>\n effect.pipe(\n Effect.mapError((error) =>\n undispatched(operation, reasonOf(error.cause, undefined, closedBy())),\n ),\n );\n\n const dispatchMouse = (\n event: MouseEvent,\n estimate: BrowserClock.Estimate | undefined,\n submitted?: () => void,\n ): Promise<unknown> => {\n const at = now();\n const point = { x: event.x, y: event.y };\n const button = event.button ?? \"left\";\n\n // Construct boundary data before dispatch: validation must never abandon the native reply.\n const ButtonEvent = event.type === \"mousePressed\" ? PointerPressed : PointerReleased;\n\n const track =\n (event.type === \"mousePressed\" || event.type === \"mouseReleased\") && button !== \"none\"\n ? new ButtonEvent({ at, page: id, ...point, button, clickCount: event.clickCount ?? 1 })\n : event.type === \"mouseWheel\"\n ? new WheelScrolled({\n at,\n page: id,\n ...point,\n dx: event.deltaX ?? 0,\n dy: event.deltaY ?? 0,\n })\n : undefined;\n\n const response = send(\"Input.dispatchMouseEvent\", { ...event, ...stamp(estimate, at) });\n\n noteInput();\n if (event.type === \"mouseMoved\") MutableRef.set(pointer, Option.some(point));\n if (track !== undefined) publish(track);\n submitted?.();\n\n return response;\n };\n\n const sendMouse = (\n operation: string,\n run: Replies.Run,\n event: MouseEvent,\n submitted?: () => void,\n ) =>\n inputCall(\n operation,\n Effect.gen(function* () {\n const held = `mouse:${event.button ?? \"left\"}`;\n const estimate = inputClocks.get(run);\n\n if (event.type === \"mouseReleased\") return yield* run.up(held);\n if (event.type === \"mousePressed\") {\n yield* run.reserve(2);\n yield* run.down(\n held,\n () => dispatchMouse(event, estimate, submitted),\n () =>\n dispatchMouse(\n buttonAt(\n \"mouseReleased\",\n Option.getOrElse(MutableRef.get(pointer), () => ({ x: event.x, y: event.y })),\n event.button,\n event.clickCount,\n ),\n estimate,\n ),\n );\n } else {\n yield* run.reserve(1);\n yield* run.send(() => dispatchMouse(event, estimate, submitted));\n }\n }),\n );\n\n // Keys and text bound for a secret field are recorded without their content.\n const dispatchKey = (\n key: string,\n phase: \"down\" | \"up\",\n command: (at: number, estimate: BrowserClock.Estimate | undefined) => Promise<unknown>,\n run: Replies.Run,\n secret = false,\n ) => {\n const at = now();\n const event = new KeyChanged({ at, page: id, key: secret ? \"Unidentified\" : key, phase });\n const response = command(at, inputClocks.get(run));\n\n noteInput();\n publish(event);\n\n return response;\n };\n\n const dispatchText = (text: string, secret: boolean): Promise<unknown> => {\n const track = new TextInserted({ at: now(), page: id, text: secret ? \"•\" : text });\n const response = send(\"Input.insertText\", { text });\n\n noteInput();\n publish(track);\n\n return response;\n };\n\n const flush = (operation: string, run: Replies.Run) => inputCall(operation, run.drain);\n\n return {\n inputClocks,\n stamp,\n inputCall,\n dispatchMouse,\n sendMouse,\n dispatchKey,\n dispatchText,\n flush,\n };\n};\n\nexport type Dispatch = ReturnType<typeof make>;\n","/**\n * The input guard's host side. It asks the page what an action would touch, builds the request a\n * policy decides on, binds an approval to the document and targets it saw, and runs the page\n * script's changes in the approved document only.\n */\nimport { Effect } from \"effect\";\n\nimport { recorded, nameOf, type Action } from \"../../Action.ts\";\nimport { type BrowserError, InvalidRequest, NotActionable, StaleRef } from \"../../BrowserError.ts\";\nimport { InputRequest } from \"../../Page.ts\";\nimport * as Url from \"../../Url.ts\";\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport { contextGone, decodeWith, failWith, type PageContext } from \"../page/context.ts\";\nimport * as Script from \"./guard.inpage.ts\";\n\nexport interface Approval {\n readonly contextId: number;\n readonly check: (options?: Script.ValidationOptions) => Effect.Effect<void, BrowserError>;\n}\n\nexport interface PolicyPlan {\n readonly request: InputRequest;\n readonly validate: Effect.Effect<Approval, BrowserError>;\n}\n\n/** Recheck an approval, after any pending input it must see; neither runs without a guard. */\nexport const check = (\n approval: Approval | undefined,\n options: Script.ValidationOptions = {},\n before: Effect.Effect<void, BrowserError> = Effect.void,\n) => (approval === undefined ? Effect.void : before.pipe(Effect.andThen(approval.check(options))));\n\n// A ref that names nothing is stale on every path, named by the target that failed.\nexport const inputFailure = (\n operation: string,\n targets: Script.InputPlan[\"targets\"],\n failure: Script.InputFailure,\n) => {\n const target = failure.index === undefined ? undefined : targets[failure.index];\n\n return failWith(\n operation,\n failure.error === \"outside\"\n ? new InvalidRequest({ detail: failure.detail })\n : failure.error === \"stale\" && typeof target === \"string\"\n ? new StaleRef({ ref: target })\n : new NotActionable({ detail: failure.detail }),\n );\n};\n\nexport const editFailure = (\n operation: string,\n ref: string,\n failure: { readonly error: string; readonly stale?: boolean | undefined },\n) =>\n failWith(\n operation,\n failure.stale === true ? new StaleRef({ ref }) : new NotActionable({ detail: failure.error }),\n );\n\nexport const make = (page: PageContext, bridge: Bridge) => {\n const { id } = page;\n const { current, evaluateIn, evaluateWithContext } = bridge;\n\n const preparePolicy = (\n asked: Action,\n info: { readonly target?: string | undefined; readonly text?: string | undefined },\n targets: Script.InputPlan[\"targets\"],\n flags: {\n readonly submit?: boolean;\n readonly keys?: string;\n readonly destination?: string;\n } = {},\n ): Effect.Effect<PolicyPlan, BrowserError> =>\n Effect.gen(function* () {\n const action = nameOf(asked);\n\n const input: Script.InputPlan = {\n action,\n targets,\n submit: flags.submit ?? false,\n keys: flags.keys ?? null,\n destination: flags.destination ?? null,\n };\n\n const { contextId, value } = yield* evaluateWithContext(\n action,\n scriptCall(\"prepareInput\", input),\n );\n\n const prepared = yield* decodeWith(action, Script.PreparedInputResultSchema)(value);\n\n if (\"error\" in prepared) return yield* inputFailure(action, targets, prepared);\n const first = prepared.targets[0];\n const target = targets[0];\n const { title, description, dialog, heading, nearby, form } = prepared.evidence;\n\n const safe = recorded(asked, first?.secret !== true);\n\n // A guard may hand the request to a judge's model, so its addresses keep no secrets.\n const request = new InputRequest({\n page: id,\n url: Url.redact(prepared.url),\n title,\n action: safe,\n target: info.target,\n text: safe._tag === \"Type\" ? safe.text : info.text,\n element: first?.element,\n role: first?.role,\n name: first?.name,\n description,\n href: first?.href === undefined ? undefined : Url.redact(first.href),\n point: target !== null && typeof target === \"object\" ? target : undefined,\n destination:\n prepared.destination === undefined ? undefined : Url.redact(prepared.destination),\n facts: prepared.facts,\n context: { dialog, heading, nearby },\n form: form === undefined ? undefined : { ...form, action: Url.redact(form.action) },\n });\n\n const check = (options: Script.ValidationOptions = {}) =>\n evaluateIn(action, scriptCall(\"validateInput\", input, prepared, options), contextId).pipe(\n Effect.catchIf(contextGone, () =>\n failWith(\n action,\n new NotActionable({ detail: \"the page changed while input policy was pending\" }),\n ),\n ),\n Effect.flatMap(decodeWith(action, Script.ValidatedInputResultSchema)),\n Effect.flatMap((result) =>\n \"error\" in result ? inputFailure(action, targets, result) : Effect.void,\n ),\n );\n\n const validate = check().pipe(\n Effect.as<Approval>({\n contextId,\n check,\n }),\n );\n\n return { request, validate };\n });\n\n // `mayHaveRun` hears of a failure or interruption after the script may have started. A known\n // missing context or API means it never ran; acquiring the context itself sends no mutation.\n const mutate = (\n operation: string,\n call: string,\n approval: Approval | undefined,\n mayHaveRun: Effect.Effect<void> = Effect.void,\n ) =>\n (approval === undefined ? current(operation) : Effect.succeed(approval.contextId)).pipe(\n Effect.flatMap((contextId) =>\n evaluateIn(operation, call, contextId).pipe(\n Effect.onInterrupt(() => mayHaveRun),\n Effect.tapError((error) =>\n error.reason._tag === \"Failed\" &&\n /Cannot find context|__effectBrowser/i.test(error.reason.detail)\n ? Effect.void\n : mayHaveRun,\n ),\n ),\n ),\n Effect.catchIf(contextGone, () =>\n failWith(\n operation,\n new NotActionable({ detail: \"the page changed before the approved input could run\" }),\n ),\n ),\n );\n\n /** A read may follow the current document only when no approval binds it to one. */\n const evaluate = (operation: string, call: string, approval: Approval | undefined) =>\n approval === undefined ? bridge.evaluate(operation, call) : mutate(operation, call, approval);\n\n return { preparePolicy, mutate, evaluate };\n};\n\nexport type Guard = ReturnType<typeof make>;\n","/**\n * Keys and typing: a key chord held and released, each typed event, and the document a run of\n * keys must stay in.\n */\nimport { Duration, Effect } from \"effect\";\n\nimport { NotActionable } from \"../../BrowserError.ts\";\nimport type { Bridge } from \"../page/bridge.ts\";\nimport { failWith, type PageContext } from \"../page/context.ts\";\nimport type * as Replies from \"../page/replies.ts\";\nimport type { Dispatch } from \"./dispatch.ts\";\nimport * as Keys from \"./keys.ts\";\n\nexport const make = (page: PageContext, bridge: Bridge, dispatch: Dispatch) => {\n const { playwright } = page;\n\n const key = (direction: \"down\" | \"up\", part: string) => {\n const run = () => playwright.keyboard[direction](part);\n\n return page.nativePort === undefined\n ? run()\n : page.nativePort(page.id, `keyboard.${direction}`, { key: part }, run);\n };\n\n const { send } = page.protocol;\n const { currentDocument } = bridge;\n const { stamp, inputCall, dispatchKey, dispatchText } = dispatch;\n\n // A multi-key action stops before its next key once the page has moved to another document. The\n // page's own session counts main-frame commits as the browser reports them, so a key sent within\n // about one protocol round trip of a commit can still reach the new document.\n const sameDocument = (operation: string, since: number) =>\n currentDocument(operation).pipe(\n Effect.flatMap((now) =>\n now === since\n ? Effect.void\n : failWith(\n operation,\n new NotActionable({\n detail: \"the page moved to another document, so the remaining keys were not sent\",\n }),\n ),\n ),\n );\n\n const keyStroke = (\n operation: string,\n run: Replies.Run,\n parts: ReadonlyArray<string>,\n holdMillis = 0,\n ) =>\n Effect.gen(function* () {\n yield* inputCall(operation, run.reserve(parts.length * 2));\n for (const part of parts)\n yield* inputCall(\n operation,\n run.down(\n `playwright:${part}`,\n () => dispatchKey(part, \"down\", () => key(\"down\", part), run),\n () => dispatchKey(part, \"up\", () => key(\"up\", part), run),\n ),\n );\n if (holdMillis > 0) yield* Effect.sleep(Duration.millis(holdMillis));\n for (const part of parts.toReversed())\n yield* inputCall(operation, run.up(`playwright:${part}`));\n });\n\n const typeEvent = (\n run: Replies.Run,\n event: { readonly phase: \"down\" | \"up\" | \"insert\"; readonly key: string },\n secret: boolean,\n ) =>\n inputCall(\n \"type\",\n Effect.gen(function* () {\n if (event.phase === \"insert\") {\n yield* run.reserve(1);\n yield* run.send(() => dispatchText(event.key, secret));\n\n return;\n }\n\n const description = Keys.description(event.key);\n\n if (description === undefined) return yield* Effect.die(\"invalid planned key\");\n const { key, code, keyCode, text } = description;\n const held = \"raw:\" + code;\n\n if (event.phase === \"up\") return yield* run.up(held);\n\n // The key going down carries its text; going up, only the key.\n const keyEvent = (phase: \"down\" | \"up\") => () =>\n dispatchKey(\n key,\n phase,\n (at, estimate) =>\n send(\"Input.dispatchKeyEvent\", {\n type: phase === \"down\" ? \"keyDown\" : \"keyUp\",\n ...stamp(estimate, at),\n modifiers: 0,\n windowsVirtualKeyCode: keyCode,\n code,\n key,\n location: 0,\n ...(phase === \"down\"\n ? { commands: [], text, unmodifiedText: text, autoRepeat: false, isKeypad: false }\n : {}),\n }),\n run,\n secret,\n );\n\n yield* run.reserve(2);\n yield* run.down(held, keyEvent(\"down\"), keyEvent(\"up\"));\n }),\n );\n\n return { currentDocument, sameDocument, keyStroke, typeEvent };\n};\n\nexport type Keyboard = ReturnType<typeof make>;\n","/**\n * Performing one action: its turn on the page, the input guard's step, the input run that owns its\n * replies, and the action's record. Its deadline leaves out the time its style takes to show it.\n */\nimport { Deferred, Duration, Effect, Exit, Option, Ref } from \"effect\";\n\nimport { recorded, nameOf, type Action as ActionValue } from \"../../Action.ts\";\nimport { BrowserError, PolicyTimeout, Timeout } from \"../../BrowserError.ts\";\nimport { Action, ActionAnnounced, Subject } from \"../../BrowserEvent.ts\";\nimport type * as BrowserClock from \"../../Clock.ts\";\nimport { type Point, redacted, type ResolvedTarget } from \"../../Page.ts\";\nimport { Current, type Style, validated } from \"../../Style.ts\";\nimport { redact } from \"../../Url.ts\";\nimport { failWith, type PageContext, undispatched } from \"../page/context.ts\";\nimport { Correlation, FailFast } from \"../page/lane.ts\";\nimport * as Replies from \"../page/replies.ts\";\nimport type { Dispatch } from \"./dispatch.ts\";\nimport type { Approval, PolicyPlan } from \"./guard.ts\";\n\nexport interface InputMarks {\n /** How the action's input is sent: plainly, or performed for viewers. */\n readonly style: Style;\n /**\n * Time the style spends showing the input, such as a glide or typing at a person's pace, planned\n * from now: the deadline moves back by as much, so presentation has a budget of its own.\n */\n readonly present: (millis: number) => Effect.Effect<void>;\n /** The action's own input, such as a press, key or wheel, has reached the page. */\n readonly sent: Effect.Effect<void>;\n /** Preparatory input, such as the pointer travelling to a target, has reached the page. */\n readonly touched: Effect.Effect<void>;\n readonly at: (point: Point) => Effect.Effect<void>;\n /** What the input acts on, and for a drag where it ends, as the page names them now. */\n readonly on: (subject: Named, to?: Named) => Effect.Effect<void>;\n /**\n * The pointer is about to travel to the action's target at `to`: announce what the action acts\n * on, and wait for the style's lead.\n */\n readonly announce: (to: Point) => Effect.Effect<void>;\n /** The action's text is not bound for a secret field, so its record may keep it. */\n readonly reveal: Effect.Effect<void>;\n readonly input: Replies.Run;\n}\n\n/** What the page names a target: a resolved one, or the field that has focus. */\ntype Named = Pick<ResolvedTarget, \"role\" | \"name\" | \"tag\" | \"context\" | \"box\">;\n\nconst subjectOf = (target: Named) =>\n new Subject({ role: target.role, name: target.name, tag: target.tag, context: target.context });\n\n/** What an action records of what it acted on: subjects, and a point target's box. */\nconst actedOn = (subject: Named, to?: Named) => ({\n subject: subjectOf(subject),\n box: subject.box,\n ...(to === undefined ? {} : { to: subjectOf(to) }),\n});\n\n/** A subject as span attributes under `prefix`, without a role it does not have. */\nconst subjectAttributes = (prefix: string, subject: Subject | undefined) =>\n subject === undefined\n ? {}\n : {\n ...(subject.role === null ? {} : { [`${prefix}.role`]: subject.role }),\n [`${prefix}.name`]: subject.name,\n [`${prefix}.tag`]: subject.tag,\n };\n\n/** What an action's record keeps of its call. */\nexport interface Call {\n readonly target?: string | undefined;\n readonly text?: string | undefined;\n}\n\nconst timedOut = (operation: string, timeout: Duration.Duration) =>\n failWith(operation, new Timeout({ millis: Duration.toMillis(timeout) }));\n\n/** Trace summaries carry lengths and subjects, never typed text. */\nconst annotate = (\n dispatched: boolean,\n queuedMillis: number | undefined,\n info: Call,\n revealed: boolean,\n subject: Subject | undefined,\n to: Subject | undefined,\n failure: Option.Option<BrowserError>,\n) =>\n Effect.annotateCurrentSpan({\n dispatched,\n ...(queuedMillis === undefined ? {} : { queuedMillis }),\n ...(info.text !== undefined && revealed ? { chars: info.text.length } : {}),\n ...subjectAttributes(\"subject\", subject),\n ...subjectAttributes(\"to\", to),\n ...Option.match(failure, {\n onNone: () => ({}),\n onSome: (error) => ({ \"error.type\": error.reason._tag }),\n }),\n });\n\n/**\n * Fail `effect` with `Timeout` once `timeout` has passed, and as much later again as `presented`\n * says presentation has planned meanwhile.\n */\nconst deadline =\n (operation: string, timeout: Duration.Duration, now: () => number, presented: () => number) =>\n <A>(effect: Effect.Effect<A, BrowserError>) =>\n Effect.suspend(() => {\n const due = now() + Duration.toMillis(timeout);\n\n const expiry: Effect.Effect<never, BrowserError> = Effect.suspend(() => {\n const left = due + presented() - now();\n\n return left <= 0\n ? timedOut(operation, timeout)\n : Effect.sleep(Duration.millis(left)).pipe(Effect.andThen(expiry));\n });\n\n return Effect.raceFirst(effect, expiry);\n });\n\n/** An admitted operation stays owned through its Action and any unanswered native replies. */\nconst admission = (page: PageContext, pending: Set<Deferred.Deferred<void>>, name: string) => {\n let run: Replies.Run | undefined;\n let end: (() => void) | undefined;\n\n const enter = Effect.uninterruptible(\n Effect.gen(function* () {\n const released = page.inputGate === undefined ? undefined : yield* page.inputGate.enter(name);\n const done = Deferred.makeUnsafe<void>();\n\n pending.add(done);\n end = () => {\n const finish = () => {\n released?.();\n pending.delete(done);\n Deferred.doneUnsafe(done, Exit.void);\n };\n\n if (run === undefined) finish();\n else run.afterIdle(finish);\n };\n }),\n );\n\n return {\n enter,\n using: (current: Replies.Run) => {\n run = current;\n },\n end: Effect.sync(() => end?.()),\n };\n};\n\n/** Announce an action from what it has found, then wait for its style's lead. */\nconst announcing =\n (\n page: PageContext,\n name: Action[\"name\"],\n style: Style,\n acted: Ref.Ref<Pick<Action, \"subject\" | \"to\" | \"box\">>,\n ) =>\n (to: Point) =>\n Effect.gen(function* () {\n const event = new ActionAnnounced({\n at: page.now(),\n page: page.id,\n name,\n correlation: yield* Correlation,\n ...(yield* Ref.get(acted)),\n ...to,\n });\n\n page.publish(event);\n if (style.lead !== undefined) yield* style.lead(event);\n });\n\n/** Close a run on every exit while preserving its native replies for the page's next input. */\nconst useRun = <A>(\n page: PageContext,\n sender: Dispatch,\n name: string,\n run: Replies.Run,\n action: Effect.Effect<A, BrowserError>,\n canStop: Effect.Effect<boolean>,\n) =>\n action.pipe(\n Effect.tapError((error) =>\n error.reason._tag === \"Closed\"\n ? run.close\n : run.close.pipe(Effect.andThen(sender.flush(name, run)), Effect.ignore),\n ),\n Effect.tap(() => run.close.pipe(Effect.andThen(sender.flush(name, run)))),\n // Cleanup submits missing releases; the page retains replies after caller interruption.\n Effect.ensuring(run.close.pipe(Effect.andThen(page.openings.clear))),\n Effect.onError(() => run.recover(page.stopLoading, page.scope).pipe(Effect.when(canStop))),\n Effect.provideService(Replies.Current, run),\n );\n\nexport const make = (page: PageContext, sender: Dispatch) => {\n const { id, settings, mapping, lane, publish, now, noteInput, span, owned } = page;\n const { inputClocks } = sender;\n const input = Replies.make();\n const admitted = new Set<Deferred.Deferred<void>>();\n\n // Record the whole operation, but never hold the page's turn or spend its action timeout while\n // a policy is waiting. Validation binds approval to the document and targets it saw.\n const perform = <A>(\n value: ActionValue,\n info: Call,\n timeout: Duration.Duration,\n prepare: (action: ActionValue) => Effect.Effect<PolicyPlan, BrowserError>,\n body: (marks: InputMarks, approval: Approval | undefined) => Effect.Effect<A, BrowserError>,\n ): Effect.Effect<A, BrowserError> => {\n const name = nameOf(value);\n const sendsInput = value._tag !== \"Goto\" && value._tag !== \"Back\" && value._tag !== \"Reload\";\n\n return Effect.gen(function* () {\n const style = validated(yield* Current);\n const failFast = yield* FailFast;\n\n const styled =\n style.withInput?.({ operation: name, wait: timeout, failFast }) ??\n (<Value, Error, Requirements>(effect: Effect.Effect<Value, Error, Requirements>) => effect);\n\n const startedAt = now();\n const sent = yield* Ref.make(false);\n const at = yield* Ref.make(Option.none<Point>());\n const acted = yield* Ref.make<Pick<Action, \"subject\" | \"to\" | \"box\">>({});\n\n // The page may react to preparatory input, as to script changes such as a selection, so\n // paint from before either is not current; only the action's own input can have given it\n // effect.\n const touch = Effect.sync(noteInput);\n\n // A failure before the action checks its field, a denial included, records no text.\n let revealed = value._tag !== \"Type\";\n // The time the style has planned to show the input, which the deadline leaves out.\n let presented = 0;\n const ticket = admission(page, admitted, name);\n\n const marks = {\n style,\n present: (millis: number) =>\n Effect.sync(() => {\n presented += Math.max(0, millis);\n }),\n sent: Ref.set(sent, true).pipe(Effect.andThen(touch)),\n touched: touch,\n at: (point: Point) => Ref.set(at, Option.some(point)),\n on: (subject: Named, to?: Named) => Ref.set(acted, actedOn(subject, to)),\n announce: announcing(page, name, style, acted),\n reveal: Effect.sync(() => {\n revealed = true;\n }),\n };\n\n // Admission waits only on this page's own unresolved replies, in its turn, so a stalled page\n // cannot delay input on other pages. Input never waits for the clock mapping: until a\n // capture has measured one, it keeps Chromium's own receipt time.\n let estimate: BrowserClock.Estimate | undefined;\n\n const admit = input.idle.pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n estimate = sendsInput ? mapping.latest() : undefined;\n }),\n ),\n );\n\n const useInput = <Value>(action: (run: Replies.Run) => Effect.Effect<Value, BrowserError>) =>\n input.begin.pipe(\n // A capture can recalibrate while input is running. One run, including delayed cleanup\n // releases, keeps one mapping so epoch stamps cannot jump backwards during a stroke.\n Effect.tap((current) =>\n Effect.sync(() => {\n ticket.using(current);\n if (estimate !== undefined) inputClocks.set(current, estimate);\n }),\n ),\n Effect.flatMap((run) =>\n useRun(\n page,\n sender,\n name,\n run,\n action(run),\n sendsInput ? Ref.get(sent) : Effect.succeed(false),\n ),\n ),\n );\n\n // How long its turn and the page's replies kept the action waiting, once it had both.\n let queuedMillis: number | undefined;\n\n // The page's turn and its earlier input's replies are waited for within the action's\n // deadline, undispatched: a turn not given by then is `Busy`, and replies not answered by\n // then a `Timeout`. The turn starts a full deadline of its own, so a wait never truncates\n // input under way.\n const dispatch = <Value>(action: Effect.Effect<Value, BrowserError>) =>\n Effect.suspend(() => {\n const asked = now();\n\n return styled(\n lane.write(\n name,\n timeout,\n )(\n ticket.enter.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n admit.pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(\n Math.max(0, Duration.toMillis(timeout) - (now() - asked)),\n ),\n orElse: () => timedOut(name, timeout),\n }),\n ),\n ),\n ),\n Effect.tap(() =>\n Effect.sync(() => {\n queuedMillis = Math.round(now() - asked);\n }),\n ),\n Effect.andThen(deadline(name, timeout, now, () => presented)(action)),\n ),\n ),\n );\n });\n\n const guard = settings.guard;\n\n // Only an approval needs binding: without a guard, input goes straight to the page.\n const action =\n guard === undefined\n ? dispatch(useInput((run) => body({ ...marks, input: run }, undefined)))\n : Effect.gen(function* () {\n const plan = yield* lane\n .read(name)(deadline(name, settings.actionTimeout, now, () => 0)(prepare(value)))\n .pipe(span(\"Page.prepare\", {}, \"Debug\"));\n\n // A hold lasts as long as this span; a judge's model call is its child.\n yield* guard(plan.request).pipe(\n Effect.mapError((reason) => undispatched(name, reason)),\n Effect.timeoutOrElse({\n duration: settings.policyTimeout,\n orElse: () =>\n failWith(\n name,\n new PolicyTimeout({ millis: Duration.toMillis(settings.policyTimeout) }),\n ),\n }),\n span(\"Page.guard\"),\n );\n\n return yield* dispatch(\n useInput((run) =>\n plan.validate.pipe(\n Effect.flatMap((approval) => body({ ...marks, input: run }, approval)),\n ),\n ),\n );\n });\n\n // Record the outcome even when the caller interrupts: its input may already be in the page.\n return yield* Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const exit = yield* Effect.exit(\n restore((page.inputGate?.check(name) ?? Effect.void).pipe(Effect.andThen(action))),\n );\n\n const dispatched = yield* Ref.get(sent);\n const point = yield* Ref.get(at);\n const { subject, to, box } = yield* Ref.get(acted);\n const failure = Exit.isFailure(exit) ? Exit.findErrorOption(exit) : Option.none();\n\n yield* annotate(dispatched, queuedMillis, info, revealed, subject, to, failure);\n\n publish(\n new Action({\n at: now(),\n startedAt,\n page: id,\n name,\n value: recorded(value, revealed),\n url: redact(page.playwright.url()),\n correlation: yield* Correlation,\n target: info.target,\n subject,\n to,\n box,\n text:\n info.text === undefined ? undefined : revealed ? info.text.slice(0, 200) : redacted,\n ...Option.match(point, { onNone: () => ({}), onSome: ({ x, y }) => ({ x, y }) }),\n ok: Exit.isSuccess(exit),\n dispatched,\n error: Option.match(failure, {\n onNone: () => (Exit.hasInterrupts(exit) ? \"interrupted\" : undefined),\n onSome: (error) => error.message,\n }),\n }),\n );\n if (Exit.isSuccess(exit)) return exit.value;\n if (dispatched)\n return yield* Exit.mapError(exit, (error) =>\n error.dispatched\n ? error\n : new BrowserError({\n operation: error.operation,\n reason: error.reason,\n dispatched: true,\n }),\n );\n\n return yield* exit;\n }),\n ).pipe(Effect.ensuring(ticket.end));\n }).pipe(span(`Page.${name}`, info.target === undefined ? {} : { target: info.target }), owned);\n };\n\n return Object.assign(perform, {\n idle: Effect.suspend(() => Effect.forEach(admitted, Deferred.await, { discard: true })),\n });\n};\n\nexport type Perform = ReturnType<typeof make>;\n","/**\n * The pointer's travel and the wheel, as the action's style sends them. Travel follows a motion\n * plan, published before its first move, from where viewers last saw the pointer when it is\n * shown, and a wheel scroll goes in the style's steps.\n */\nimport { Duration, Effect, MutableRef, Option, Schema } from \"effect\";\n\nimport { CursorChanged, TrackPerformed, TrackPlanned } from \"../../BrowserEvent.ts\";\nimport * as Motion from \"../../Geometry.ts\";\nimport type { Point } from \"../../Page.ts\";\nimport type { WheelStep } from \"../../Style.ts\";\nimport { type PageContext, refuse } from \"../page/context.ts\";\nimport type { Viewport } from \"../page/viewport.ts\";\nimport type { Dispatch } from \"./dispatch.ts\";\nimport type { InputMarks } from \"./perform.ts\";\n\nexport const make = (page: PageContext, dispatch: Dispatch, viewport: Viewport) => {\n const { id, pointer, publish, now, span } = page;\n const { inputClocks, inputCall, dispatchMouse, sendMouse } = dispatch;\n\n // Travel toward a press only prepares the action, as does travel that reveals a target out of\n // view before it is found; a hover is its travel, and a drag holds the button it has already\n // pressed. Travel to the action's own target announces it first.\n const moveTo = (\n operation: string,\n marks: InputMarks,\n to: Point,\n cursor?: string,\n travel: \"approach\" | \"reveal\" | \"hover\" | \"drag\" = \"approach\",\n ) =>\n Effect.gen(function* () {\n const dragging = travel === \"drag\";\n const { style } = marks;\n\n if (travel === \"approach\" || travel === \"hover\") yield* marks.announce(to);\n const drawn = style.pointer ?? pointer;\n const size = yield* viewport.viewportFor(operation);\n\n const previous = Option.getOrElse(MutableRef.get(drawn), () => ({\n x: Math.round(size.width / 2),\n y: Math.round(size.height / 2),\n }));\n\n const from = {\n x: Math.max(0, Math.min(size.width - 1, previous.x)),\n y: Math.max(0, Math.min(size.height - 1, previous.y)),\n };\n\n const planned = yield* style.glide(from, to, dragging);\n\n // A custom planner is a boundary. Decoding reads each sample once into a fresh copy and\n // checks that copy, so neither accessors nor later mutation can change what is admitted.\n const invalid = refuse(\n operation,\n \"motion must be a bounded, ordered schedule ending at the target\",\n );\n\n const samples = yield* Schema.decodeEffect(Motion.Plan)(planned).pipe(\n Effect.catch(() => invalid),\n );\n\n if (samples.at(-1)?.x !== to.x || samples.at(-1)?.y !== to.y) return yield* invalid;\n yield* Effect.annotateCurrentSpan(\"samples\", samples.length);\n yield* marks.present(samples.at(-1)?.afterMillis ?? 0);\n const run = marks.input;\n\n // Admit the whole motion before starting its clock. Dense original samples must not be\n // stretched by per-sample reply backpressure; unsent reservations belong to this run.\n yield* inputCall(operation, run.reserveMotion(samples.length));\n MutableRef.set(pointer, Option.some(from));\n const estimate = inputClocks.get(run);\n const at = now();\n let dispatched = 0;\n let last = from;\n\n // The complete plan exists before its first move. A canceled performer always clips\n // that future to the prefix it actually submitted, including interruption during sleep.\n yield* Effect.acquireUseRelease(\n Effect.sync(() => publish(new TrackPlanned({ at, page: id, from, samples }))),\n () =>\n Effect.gen(function* () {\n for (const sample of samples) {\n const remaining = at + sample.afterMillis - now();\n\n if (remaining > 0) yield* Effect.sleep(Duration.millis(remaining));\n yield* travel === \"approach\" || travel === \"reveal\" ? marks.touched : marks.sent;\n yield* inputCall(\n operation,\n run.send(() =>\n dispatchMouse(\n {\n type: \"mouseMoved\",\n x: sample.x,\n y: sample.y,\n button: dragging ? \"left\" : \"none\",\n ...(dragging ? { buttons: 1 } : {}),\n },\n estimate,\n () => {\n dispatched++;\n last = { x: sample.x, y: sample.y };\n MutableRef.set(drawn, Option.some(last));\n if (dispatched === samples.length && cursor !== undefined)\n publish(new CursorChanged({ at: now(), page: id, cursor }));\n },\n ),\n ),\n );\n }\n }),\n (plan) =>\n Effect.sync(() =>\n publish(\n new TrackPerformed({\n at: now(),\n page: id,\n plan,\n dispatched,\n ...last,\n complete: dispatched === samples.length,\n }),\n ),\n ),\n );\n }).pipe(span(\"Page.move\", {}, \"Debug\"));\n\n const wheel = Effect.fnUntraced(function* (\n operation: string,\n marks: InputMarks,\n point: Point,\n dx: number,\n dy: number,\n planned?: ReadonlyArray<WheelStep>,\n ) {\n const steps = planned ?? (yield* marks.style.wheel(dx, dy));\n const at = now();\n\n yield* marks.present(steps.at(-1)?.afterMillis ?? 0);\n for (const step of steps) {\n const remaining = at + step.afterMillis - now();\n\n if (remaining > 0) yield* Effect.sleep(Duration.millis(remaining));\n yield* sendMouse(operation, marks.input, {\n type: \"mouseWheel\",\n ...point,\n deltaX: step.dx,\n deltaY: step.dy,\n });\n }\n });\n\n return { moveTo, wheel };\n};\n\nexport type Pointer = ReturnType<typeof make>;\n","/**\n * The wait after input: one task and one frame in the page, in one call, then a document only if\n * one committed meanwhile, until it is parsed. Chromium answers a call to a page that a link, a form\n * or a script's timer has asked to navigate only once the new document commits, or the navigation\n * stops without one, as on a 204, so the call spans the navigation the input asked for. A\n * `pushState` asks for no document, and a navigation a handler starts after a fetch answers is the\n * next look's to see. A tab the input opened waits for the browser's registration too.\n */\nimport { Deferred, Duration, Effect, Exit, Option } from \"effect\";\n\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport { contextGone, type PageContext } from \"../page/context.ts\";\nimport { Current } from \"../page/replies.ts\";\n\n// A document still loading after this, or a closed page, is the next look's to show.\nconst settling = Duration.seconds(5);\n\nexport const make = (page: PageContext, bridge: Bridge) => {\n const document = () => bridge.frameTag().document;\n // The latest document whose DOMContentLoaded came, and what wakes a wait for the next.\n let parsed = -1;\n let changed = Deferred.makeUnsafe<void>();\n\n page.cdp.on(\"Page.domContentEventFired\", () => {\n parsed = document();\n Deferred.doneUnsafe(changed, Exit.void);\n changed = Deferred.makeUnsafe<void>();\n });\n\n /** The page's document before input, which `settle` measures from. */\n const mark = () => ({ document: document(), openings: page.openings.mark() });\n\n /** Wait for the page to settle after input sent since `before`. */\n const settle = (operation: string, before: ReturnType<typeof mark>) =>\n Effect.gen(function* () {\n // A commit ends the call's world; the loop then waits for that document.\n yield* bridge.evaluate(operation, scriptCall(\"settle\")).pipe(\n // This is a read, not an input acknowledgement. A pending navigation may hold the\n // evaluate after the settling deadline, without retaining browser input authority.\n Effect.provideService(Current, undefined),\n Effect.catchIf(contextGone, () => Effect.void),\n );\n while (document() > before.document && parsed < document()) yield* Deferred.await(changed);\n }).pipe(\n Effect.timeoutOption(settling),\n Effect.flatMap((result) =>\n Option.isSome(result)\n ? Effect.void\n : page.stopLoading.pipe(Effect.andThen(Effect.annotateCurrentSpan(\"settled\", false))),\n ),\n Effect.andThen(page.openings.settle(before.openings)),\n page.span(\"Page.settle\", {}, \"Debug\"),\n );\n\n return { mark, settle };\n};\n\nexport type Settle = ReturnType<typeof make>;\n","/**\n * Where an action's input goes: a ref or a point resolved to a control and a viewport point,\n * scrolled into view first when it is outside the viewport: at once, or with the wheel where\n * viewers watch.\n */\nimport { Effect } from \"effect\";\n\nimport { InvalidRequest, NotActionable, StaleRef } from \"../../BrowserError.ts\";\nimport { ResolvedTarget, type Target } from \"../../Page.ts\";\nimport { scriptCall } from \"../page/bridge.ts\";\nimport { decodeWith, failWith } from \"../page/context.ts\";\nimport type { Viewport } from \"../page/viewport.ts\";\nimport type { Dispatch } from \"./dispatch.ts\";\nimport { type Approval, check, type Guard } from \"./guard.ts\";\nimport type { InputMarks } from \"./perform.ts\";\nimport type { Pointer } from \"./pointer.ts\";\nimport type { Settle } from \"./settle.ts\";\nimport * as Script from \"./targets.inpage.ts\";\n\nconst pointFailure = (\n operation: string,\n target: Target,\n result: Extract<Script.PointResult, { readonly error: string }>,\n) =>\n failWith(\n operation,\n result.error === \"stale\" && typeof target === \"string\"\n ? new StaleRef({ ref: target })\n : result.error === \"outside\"\n ? new InvalidRequest({ detail: result.detail })\n : new NotActionable({ detail: result.detail }),\n );\n\nconst resolvedTarget = ({ x, y, box, ...target }: Script.ResolvedPoint): ResolvedTarget =>\n new ResolvedTarget({ point: { x, y }, box, ...target });\n\nexport const make = (\n viewport: Viewport,\n guard: Guard,\n pointer: Pointer,\n dispatch: Dispatch,\n settling: Settle,\n) => {\n const { evaluate, mutate } = guard;\n const { moveTo, wheel } = pointer;\n const { flush } = dispatch;\n\n const readPoint = (\n operation: string,\n target: Target,\n approval: Approval | undefined,\n scroll: boolean,\n ) =>\n evaluate(operation, scriptCall(\"point\", target, scroll), approval).pipe(\n Effect.flatMap(decodeWith(operation, Script.PointResultSchema)),\n );\n\n // Every input reaches this phase through ActionPort's decoded Target schema.\n const resolve = (operation: string, target: Target, approval?: Approval, scroll = true) =>\n readPoint(operation, target, approval, scroll).pipe(\n Effect.flatMap((result) =>\n \"error\" in result\n ? pointFailure(operation, target, result)\n : Effect.succeed(resolvedTarget(result)),\n ),\n );\n\n const targetFor = Effect.fnUntraced(function* (\n operation: string,\n target: Target,\n approval: Approval | undefined,\n marks: InputMarks,\n ) {\n if (!marks.style.shown || typeof target !== \"string\")\n return yield* resolve(operation, target, approval);\n\n // Inspection and policy approval happen before this point. Every retry is geometry only;\n // scrolling never obtains a fresh approval or silently follows a replacement document.\n for (let attempt = 0; attempt < 3; attempt++) {\n const result = yield* readPoint(operation, target, approval, false);\n\n if (!(\"error\" in result)) return resolvedTarget(result);\n if (result.error !== \"offscreen\") return yield* pointFailure(operation, target, result);\n\n const plan = yield* mutate(operation, scriptCall(\"scrollPlan\", target), approval).pipe(\n Effect.flatMap(decodeWith(operation, Script.ScrollPlanSchema)),\n );\n\n if (plan === null) break;\n const size = yield* viewport.viewportFor(operation);\n const point = { x: plan.x, y: plan.y };\n\n yield* marks.at(point);\n yield* moveTo(operation, marks, point, undefined, \"reveal\");\n const before = settling.mark();\n\n yield* wheel(\n operation,\n marks,\n point,\n Math.max(-size.width * 0.9, Math.min(size.width * 0.9, plan.dx)),\n Math.max(-size.height * 0.9, Math.min(size.height * 0.9, plan.dy)),\n );\n yield* flush(operation, marks.input);\n yield* settling.settle(operation, before);\n yield* check(approval);\n }\n\n // Wheels may be prevented or the target may need unsupported nested/frame geometry. One\n // explicit fallback preserves reachability without a distance-dependent protocol loop.\n yield* marks.touched;\n const before = settling.mark();\n\n yield* resolve(operation, target, approval);\n yield* settling.settle(operation, before);\n yield* check(approval);\n\n return yield* resolve(operation, target, approval, false);\n });\n\n return { resolve, targetFor };\n};\n\nexport type Targets = ReturnType<typeof make>;\n","/**\n * The page's actions: click, hover, drag, type, press, scroll and select, each sent in a style,\n * plainly or performed for viewers. Each runs through\n * `perform`, which admits it, puts it to the input guard and records it. A click, a key or a scroll\n * then waits for the page to settle: a task and a frame, and a document if the input asked for one.\n */\nimport { Duration, Effect } from \"effect\";\n\nimport { NotActionable, StaleRef } from \"../../BrowserError.ts\";\nimport type { ClickOptions, PressOptions, ScrollOptions, Target, TypeOptions } from \"../../Page.ts\";\nimport { maximumDurationMillis } from \"../../Style.ts\";\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport { decodeWith, failWith, type PageContext, refuse } from \"../page/context.ts\";\nimport type { Viewport } from \"../page/viewport.ts\";\nimport * as Dispatch from \"./dispatch.ts\";\nimport { buttonAt } from \"./dispatch.ts\";\nimport * as Script from \"./edit.inpage.ts\";\nimport * as Guard from \"./guard.ts\";\nimport * as Keyboard from \"./keyboard.ts\";\nimport * as Keys from \"./keys.ts\";\nimport * as Perform from \"./perform.ts\";\nimport * as Pointer from \"./pointer.ts\";\nimport * as Settle from \"./settle.ts\";\nimport * as Targets from \"./targets.ts\";\n\nconst partsOf = (page: PageContext, bridge: Bridge, viewport: Viewport) => {\n const dispatch = Dispatch.make(page);\n const pointer = Pointer.make(page, dispatch, viewport);\n const guard = Guard.make(page, bridge);\n const settling = Settle.make(page, bridge);\n\n return {\n page,\n ...settling,\n viewportFor: viewport.viewportFor,\n perform: Perform.make(page, dispatch),\n ...guard,\n ...Targets.make(viewport, guard, pointer, dispatch, settling),\n ...pointer,\n ...Keyboard.make(page, bridge, dispatch),\n sendMouse: dispatch.sendMouse,\n flush: dispatch.flush,\n };\n};\n\ntype Parts = ReturnType<typeof partsOf>;\n\nconst named = (target: Target) => (typeof target === \"string\" ? target : `${target.x},${target.y}`);\n\n/** The ref a target names, if it names one rather than a point. */\nconst refOf = (target: Target | undefined) => (typeof target === \"string\" ? target : undefined);\n\n/** Key names have a finite vocabulary beyond the action's structural schema. */\nconst pressed = (keys: string) => {\n const parts = Keys.parts(keys);\n\n return parts === undefined\n ? refuse(\"press\", `\"${keys}\" is not a key; try Enter, Space, ArrowLeft or Control+A`)\n : Effect.succeed(parts);\n};\n\nconst click = (input: Parts) => {\n const { settings } = input.page;\n const { perform, preparePolicy, targetFor, moveTo, sendMouse, flush, mark, settle } = input;\n\n return (target: Target, clickOptions: ClickOptions = {}) =>\n perform(\n { _tag: \"Click\", target, options: clickOptions },\n {\n target: named(target),\n },\n settings.actionTimeout,\n (action) => preparePolicy(action, { target: refOf(target) }, [target]),\n (marks, approval) =>\n Effect.gen(function* () {\n const resolved = yield* targetFor(\"click\", target, approval, marks);\n const { point } = resolved;\n const button = clickOptions.button ?? \"left\";\n const count = Math.max(1, Math.min(3, clickOptions.clickCount ?? 1));\n\n yield* marks.at(point);\n yield* marks.on(resolved);\n yield* moveTo(\"click\", marks, point, resolved.cursor);\n yield* Guard.check(approval, { presses: [{ index: 0, ...point }] });\n const before = mark();\n\n yield* marks.sent;\n for (let index = 1; index <= count; index++) {\n // An earlier click of a multi-click can replace the approved control under the\n // pointer. Under a guard, its handlers run before the next press is checked and sent.\n if (index > 1)\n yield* Guard.check(\n approval,\n { presses: [{ index: 0, ...point }] },\n flush(\"click\", marks.input),\n ).pipe(\n Effect.catchIf(\n (error) => error.reason._tag === \"StaleRef\",\n () =>\n failWith(\n \"click\",\n new NotActionable({\n detail:\n \"an earlier click removed the approved target, so no further press was sent\",\n }),\n ),\n ),\n );\n yield* sendMouse(\"click\", marks.input, buttonAt(\"mousePressed\", point, button, index));\n\n // A hold the caller asks for is the click's own; the style's is presentation.\n const hold = clickOptions.holdMillis ?? (yield* marks.style.hold);\n\n if (clickOptions.holdMillis === undefined) yield* marks.present(hold);\n if (hold > 0) yield* Effect.sleep(Duration.millis(hold));\n yield* sendMouse(\"click\", marks.input, buttonAt(\"mouseReleased\", point, button, index));\n }\n yield* flush(\"click\", marks.input);\n yield* settle(\"click\", before);\n\n return resolved;\n }),\n );\n};\n\nconst hover = (input: Parts) => {\n const { settings } = input.page;\n const { perform, preparePolicy, targetFor, moveTo, flush } = input;\n\n return (target: Target) =>\n perform(\n { _tag: \"Hover\", target },\n { target: named(target) },\n settings.actionTimeout,\n (action) => preparePolicy(action, { target: refOf(target) }, [target]),\n (marks, approval) =>\n Effect.gen(function* () {\n const resolved = yield* targetFor(\"hover\", target, approval, marks);\n const { point } = resolved;\n\n yield* marks.at(point);\n yield* marks.on(resolved);\n yield* moveTo(\"hover\", marks, point, resolved.cursor, \"hover\");\n yield* flush(\"hover\", marks.input);\n }),\n );\n};\n\nconst drag = (input: Parts) => {\n const { settings } = input.page;\n const { perform, preparePolicy, targetFor, resolve, moveTo, sendMouse, flush } = input;\n\n return (from: Target, to: Target) =>\n perform(\n { _tag: \"Drag\", from, to },\n { target: `${JSON.stringify(from)} -> ${JSON.stringify(to)}` },\n settings.actionTimeout,\n (action) => preparePolicy(action, {}, [from, to]),\n (marks, approval) =>\n Effect.gen(function* () {\n yield* targetFor(\"drag\", from, approval, marks);\n yield* targetFor(\"drag\", to, approval, marks);\n // Bringing the second endpoint into view may move the first. Both must still be\n // actionable in the final viewport before the first button press.\n const start = yield* resolve(\"drag\", from, approval, false);\n const end = yield* resolve(\"drag\", to, approval, false);\n\n yield* marks.at(end.point);\n yield* marks.on(start, end);\n yield* moveTo(\"drag\", marks, start.point, start.cursor);\n // Both ends are checked before the button goes down: once it is down, a release cannot\n // be withheld, and a dragged element under the pointer would hide the drop target.\n yield* Guard.check(approval, {\n presses: [\n { index: 0, ...start.point },\n { index: 1, ...end.point },\n ],\n });\n yield* marks.sent;\n yield* sendMouse(\"drag\", marks.input, buttonAt(\"mousePressed\", start.point));\n yield* moveTo(\"drag\", marks, end.point, end.cursor, \"drag\");\n yield* sendMouse(\"drag\", marks.input, buttonAt(\"mouseReleased\", end.point));\n yield* flush(\"drag\", marks.input);\n }),\n );\n};\n\nconst typeText = (input: Parts) => {\n const { settings, now } = input.page;\n const { perform, preparePolicy, mutate, targetFor, moveTo, sendMouse, flush, evaluate } = input;\n const { currentDocument, sameDocument, keyStroke, typeEvent, mark, settle } = input;\n\n return (text: string, typeOptions: TypeOptions = {}) =>\n perform(\n { _tag: \"Type\", text, options: typeOptions },\n {\n target: typeOptions.into,\n text,\n },\n settings.actionTimeout,\n (action) =>\n preparePolicy(action, { target: typeOptions.into, text }, [typeOptions.into ?? null], {\n submit: typeOptions.submit ?? false,\n }),\n (marks, approval) =>\n Effect.gen(function* () {\n const events = yield* marks.style.typing(text, approval !== undefined);\n const replace = typeOptions.replace ?? true;\n const into = typeOptions.into;\n\n // A typed space or letter can press a focused button or change a control. Refuse\n // those before any input, on every path.\n const asked = scriptCall(\"typeable\", into ?? null, typeOptions.secret === true);\n\n const typeable = yield* evaluate(\"type\", asked, approval).pipe(\n Effect.flatMap(decodeWith(\"type\", Script.TypeableResultSchema)),\n );\n\n if (\"error\" in typeable)\n return yield* failWith(\n \"type\",\n typeable.error === \"stale\" && into !== undefined\n ? new StaleRef({ ref: into })\n : new NotActionable({ detail: typeable.detail }),\n );\n if (typeable.subject !== undefined) yield* marks.on(typeable.subject);\n\n const since = yield* currentDocument(\"type\");\n let secret = typeable.secret;\n\n if (into !== undefined) {\n const target = yield* targetFor(\"type\", into, approval, marks);\n\n yield* marks.at(target.point);\n yield* marks.on(target);\n // Viewers see the pointer click into the field.\n if (marks.style.shown) {\n yield* moveTo(\"type\", marks, target.point, target.cursor);\n yield* Guard.check(approval, { presses: [{ index: 0, ...target.point }] });\n yield* marks.sent;\n for (const type of [\"mousePressed\", \"mouseReleased\"] as const)\n yield* sendMouse(\"type\", marks.input, buttonAt(type, target.point));\n yield* flush(\"type\", marks.input);\n }\n\n // Focusing can run page handlers, including navigation, before the script returns.\n yield* marks.sent;\n\n // A page may answer the press with another field of the same name in the field's\n // place, focused, as a typeahead does: the keys follow it, unless a guard approved\n // this field and no other, or the field is secret, as its replacement may not be.\n const follow =\n marks.style.shown && approval === undefined && !secret && target.name !== \"\"\n ? target.name\n : null;\n\n const focused = yield* mutate(\n \"type\",\n scriptCall(\"focus\", into, replace, follow),\n approval,\n ).pipe(Effect.flatMap(decodeWith(\"type\", Script.FocusResultSchema)));\n\n if (\"error\" in focused) return yield* Guard.editFailure(\"type\", into, focused);\n secret ||= focused.secret;\n }\n if (!secret) yield* marks.reveal;\n yield* Guard.check(approval, { focused: true });\n yield* marks.sent;\n\n // A key's handlers can move focus, and later keys then reach a control nobody approved.\n // Under a guard, the field is approved once: plain text goes in one insertion, which no\n // handler can split, and keys typed one at a time check that the field still has focus,\n // once the keys before are answered, before each space, which could press a button, and\n // after the last key.\n const focusHeld = Guard.check(approval, { focused: true }, flush(\"type\", marks.input));\n\n if (text === \"\" && replace && into !== undefined) {\n yield* sameDocument(\"type\", since);\n yield* keyStroke(\"type\", marks.input, [\"Delete\"]);\n } else {\n const keyed = events.some((event) => event.phase === \"down\");\n\n const checks =\n approval !== undefined && keyed ? (text.match(/\\s/gu)?.length ?? 0) + 1 : 0;\n\n // Each check is about two round trips, which only keys typed one at a time need.\n const started = now();\n\n yield* marks.present((events.at(-1)?.afterMillis ?? 0) + checks * 250);\n for (const event of events) {\n const remaining = started + event.afterMillis - now();\n\n if (remaining > 0) yield* Effect.sleep(Duration.millis(remaining));\n if (event.phase === \"down\" && /\\s/u.test(event.key)) yield* focusHeld;\n if (event.phase !== \"up\") yield* sameDocument(\"type\", since);\n yield* typeEvent(marks.input, event, secret);\n }\n if (keyed) yield* focusHeld;\n }\n // Public Playwright keys preserve platform editing commands. Drain the raw text\n // session before Enter uses Playwright's session, so submit cannot overtake typing.\n yield* flush(\"type\", marks.input);\n if (typeOptions.submit === true) {\n // Typing can move focus or change the form; Enter goes only to the approved field.\n yield* Guard.check(approval, { focused: true });\n yield* sameDocument(\"type\", since);\n const before = mark();\n\n yield* keyStroke(\"type\", marks.input, [\"Enter\"]);\n yield* flush(\"type\", marks.input);\n yield* settle(\"type\", before);\n }\n }),\n );\n};\n\nconst press = (input: Parts) => {\n const { settings, now } = input.page;\n const { perform, preparePolicy, currentDocument, sameDocument, keyStroke, flush } = input;\n const { mark, settle, targetFor, mutate } = input;\n\n return (keys: string, pressOptions: PressOptions = {}) =>\n perform(\n { _tag: \"Press\", keys, options: pressOptions },\n { target: keys },\n settings.actionTimeout,\n (action) =>\n Effect.suspend(() => pressed(keys)).pipe(\n Effect.flatMap((parts) =>\n preparePolicy(\n action,\n { target: pressOptions.on, text: parts.join(\"+\") },\n [pressOptions.on ?? null],\n { keys: parts.join(\"+\") },\n ),\n ),\n ),\n (marks, approval) =>\n Effect.gen(function* () {\n const parts = yield* pressed(keys);\n const times = Math.max(1, Math.min(50, pressOptions.times ?? 1));\n const hold = Math.max(0, pressOptions.holdMillis ?? 0);\n\n const gaps = yield* Effect.all(\n Array.from({ length: times - 1 }, () => marks.style.keyGap),\n );\n\n const pacing = gaps.reduce((sum, gap) => sum + gap, 0);\n\n if (times * hold + pacing > maximumDurationMillis)\n return yield* refuse(\"press\", \"the key sequence exceeds the maximum duration\");\n yield* marks.present(pacing);\n const activates = parts.at(-1) === \"Enter\" || parts.at(-1) === \"Space\";\n const since = yield* currentDocument(\"press\");\n const on = pressOptions.on;\n\n // The keys go to the element asked for, which must hold focus before the first.\n if (on !== undefined) {\n yield* marks.on(yield* targetFor(\"press\", on, approval, marks));\n\n // Focus handlers may change the page before the protocol reply returns.\n yield* marks.sent;\n\n const focused = yield* mutate(\"press\", scriptCall(\"focusOn\", on), approval).pipe(\n Effect.flatMap(decodeWith(\"press\", Script.EditResultSchema)),\n );\n\n if (\"error\" in focused) return yield* Guard.editFailure(\"press\", on, focused);\n yield* Guard.check(approval, { focused: true });\n }\n const before = mark();\n let due = now();\n\n yield* marks.sent;\n for (let index = 0; index < times; index++) {\n // A repeated key stays in the document it began in. Under a guard, a repeated Enter\n // or Space must also reach the approved element after the previous press settled.\n if (index > 0 && activates)\n yield* Guard.check(approval, { focused: true }, flush(\"press\", marks.input));\n yield* sameDocument(\"press\", since);\n yield* keyStroke(\"press\", marks.input, parts, hold);\n if (index + 1 < times) {\n due += hold + (gaps[index] ?? 0);\n if (due > now()) yield* Effect.sleep(Duration.millis(due - now()));\n }\n }\n yield* flush(\"press\", marks.input);\n yield* settle(\"press\", before);\n }),\n );\n};\n\nconst scroll = (input: Parts) => {\n const { settings } = input.page;\n const { perform, preparePolicy, viewportFor, targetFor, resolve, moveTo, wheel, flush } = input;\n const { mark, settle } = input;\n\n return (scrollOptions: ScrollOptions = {}) => {\n const target = scrollOptions.at;\n\n return perform(\n { _tag: \"Scroll\", options: scrollOptions },\n {\n target: target === undefined ? undefined : named(target),\n },\n settings.actionTimeout,\n (action) =>\n preparePolicy(action, { target: refOf(target) }, target === undefined ? [] : [target]),\n (marks, approval) =>\n Effect.gen(function* () {\n // Over CDP the page reports its own viewport, so the read shares the action's deadline.\n const viewport = yield* viewportFor(\"scroll\");\n\n const middle = {\n x: Math.round(viewport.width / 2),\n y: Math.round(viewport.height / 2),\n };\n\n const dx = scrollOptions.dx ?? 0;\n\n const dy =\n scrollOptions.dy ??\n (scrollOptions.dx === undefined ? Math.round(viewport.height * 0.8) : 0);\n\n const steps = yield* marks.style.wheel(dx, dy);\n\n // A page scroll has no target, but viewers still see the cursor it lands on.\n const resolved =\n target !== undefined\n ? yield* targetFor(\"scroll\", target, approval, marks)\n : marks.style.shown\n ? yield* resolve(\"scroll\", middle, approval).pipe(\n Effect.orElseSucceed(() => undefined),\n )\n : undefined;\n\n const point = resolved?.point ?? middle;\n\n yield* marks.at(point);\n if (target !== undefined && resolved !== undefined) yield* marks.on(resolved);\n yield* moveTo(\"scroll\", marks, point, resolved?.cursor);\n const before = mark();\n\n yield* marks.sent;\n yield* wheel(\"scroll\", marks, point, dx, dy, steps);\n yield* flush(\"scroll\", marks.input);\n yield* settle(\"scroll\", before);\n }),\n );\n };\n};\n\nconst select = (input: Parts) => {\n const { settings } = input.page;\n const { perform, preparePolicy, targetFor, mutate } = input;\n\n return (ref: string, values: ReadonlyArray<string>) =>\n perform(\n { _tag: \"Select\", ref, values },\n { target: ref, text: values.join(\", \") },\n settings.actionTimeout,\n (action) => preparePolicy(action, { target: ref, text: values.join(\", \") }, [ref]),\n (marks, approval) =>\n Effect.gen(function* () {\n yield* marks.on(yield* targetFor(\"select\", ref, approval, marks));\n\n // The script refuses before it changes anything. Only a choice it made, or a script\n // that may have run without an intact answer, may have reached the page.\n const result = yield* mutate(\n \"select\",\n scriptCall(\"select\", ref, values),\n approval,\n marks.sent,\n ).pipe(\n Effect.flatMap((value) =>\n decodeWith(\n \"select\",\n Script.EditResultSchema,\n )(value).pipe(Effect.tapError(() => marks.sent)),\n ),\n );\n\n if (\"error\" in result) return yield* Guard.editFailure(\"select\", ref, result);\n yield* marks.sent;\n\n return result.detail;\n }),\n );\n};\n\nexport const make = (page: PageContext, bridge: Bridge, viewport: Viewport) => {\n const parts = partsOf(page, bridge, viewport);\n\n return {\n perform: parts.perform,\n preparePolicy: parts.preparePolicy,\n click: click(parts),\n hover: hover(parts),\n drag: drag(parts),\n type: typeText(parts),\n press: press(parts),\n scroll: scroll(parts),\n select: select(parts),\n };\n};\n\n/** A page's input, each action in any style. */\nexport type Input = ReturnType<typeof make>;\n","/** Bounded capture-loss and paint-gap statistics on the owning host clock. */\nimport { Duration } from \"effect\";\n\n// Paint-time gaps between consecutive delivered frames.\nconst paintGaps = () => {\n let count = 0;\n let totalMillis = 0;\n let minMillis: number | null = null;\n let maxMillis: number | null = null;\n let lastMillis: number | null = null;\n\n return {\n add: (gap: number) => {\n count++;\n totalMillis += gap;\n minMillis = minMillis === null ? gap : Math.min(minMillis, gap);\n maxMillis = maxMillis === null ? gap : Math.max(maxMillis, gap);\n lastMillis = gap;\n },\n snapshot: () => ({ count, totalMillis, minMillis, maxMillis, lastMillis }),\n };\n};\n\nconst none = () => ({\n received: 0,\n accepted: 0,\n late: 0,\n missingTimestamp: 0,\n foreignSize: 0,\n duringPictures: 0,\n lost: 0,\n});\n\ntype Counted = keyof ReturnType<typeof none>;\n\n/** How far back a window of capture counts can reach. */\nexport const countsKept = Duration.minutes(1);\n\n/**\n * A capture's counts and paint gaps over its page's life, and each with when it happened on the\n * owner's clock for the latest minute, so a window of them can be read.\n */\nexport const tally = (now: () => number) => {\n const totals = none();\n const gaps = paintGaps();\n\n let recent: Array<{\n readonly at: number;\n readonly counted: Counted | \"gap\";\n readonly n: number;\n }> = [];\n\n let oldest = 0;\n\n const note = (counted: Counted | \"gap\", n: number) => {\n const at = now();\n\n recent.push({ at, counted, n });\n while ((recent[oldest]?.at ?? at) < at - Duration.toMillis(countsKept)) oldest++;\n // Shed what is out of reach once it is half the log.\n if (oldest > recent.length / 2) {\n recent = recent.slice(oldest);\n oldest = 0;\n }\n };\n\n return {\n count: (counted: Counted, n = 1) => {\n totals[counted] += n;\n note(counted, n);\n },\n gap: (millis: number) => {\n gaps.add(millis);\n note(\"gap\", millis);\n },\n /** Lifetime counts, or those of the latest `windowMillis`, at most a minute. */\n read: (windowMillis?: number) => {\n if (windowMillis === undefined) return { ...totals, gaps: gaps.snapshot() };\n const counts = none();\n const windowed = paintGaps();\n const since = now() - windowMillis;\n\n for (const { at, counted, n } of recent.slice(oldest)) {\n if (at < since) continue;\n if (counted === \"gap\") windowed.add(n);\n else counts[counted] += n;\n }\n\n return { ...counts, gaps: windowed.snapshot() };\n },\n };\n};\n","/** Viewport evidence and bounded foreign-picture filtering for one capture. */\nimport { Clock, Duration, Effect, Queue } from \"effect\";\n\nimport type { BrowserError } from \"../../BrowserError.ts\";\nimport { monotonicMillis } from \"../../Clock.ts\";\nimport type { Frame } from \"../../Frame.ts\";\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\ninterface Options {\n readonly clock: Clock.Clock;\n readonly viewport: Effect.Effect<Size, BrowserError>;\n}\nconst deadline = Duration.seconds(2);\n\ninterface Held {\n readonly frame: Frame;\n readonly timestamp: number;\n}\n\n/** Consecutive frames of one device size other than the expected one, oldest first. */\ninterface Run {\n readonly device: Size;\n /** When its first frame arrived, on the owner's monotonic clock. */\n readonly since: number;\n readonly frames: Array<Held>;\n}\n\n// Device sizes can be fractional at some scale factors; the page reports whole pixels.\nconst sameSize = (left: Size, right: Size) =>\n Math.abs(left.width - right.width) < 1 && Math.abs(left.height - right.height) < 1;\n\n// A frame is its device scaled to fit, so it keeps the device's shape to within a pixel a side.\nconst sameShape = (image: Size, device: Size) =>\n Math.abs(image.width * device.height - image.height * device.width) <\n device.width + device.height;\n\n// Another capture's frames last only as long as it does; a run of frames that lasts longer is\n// the page's own.\nconst outlasting = Duration.seconds(1);\n\n// A page too busy to report its viewport in time reads as null.\nexport const readViewport = (options: Options) =>\n options.viewport.pipe(\n Effect.interruptible,\n Effect.timeoutOrElse({ duration: deadline, orElse: () => Effect.succeed(null) }),\n Effect.orElseSucceed(() => null),\n Effect.provideService(Clock.Clock, options.clock),\n );\n\n/**\n * Keeps other captures' frames from readers. A clipped or scaled screenshot of the page, taken\n * from any session, draws frames into its running screencast without resizing the page, until\n * Chromium returns to the page's size. Either their picture has another shape than their device,\n * and they are dropped, or their device has another size than the page's frames.\n *\n * A frame of the expected device size goes to readers at once and drops any run of frames of\n * another size before it, as another capture's. A run waits, in order, until the page reports a\n * viewport of its size or until it outlasts any capture: then it was a real resize, so it goes to\n * readers and its size is expected. The page's report only shortens the wait, so a page too busy\n * to answer, or one measuring in other units as under browser zoom, never stalls the stream.\n */\nexport const sizeFilter = (\n options: Options,\n deliver: (frame: Frame, timestamp: number) => void,\n drop: (frames: number) => void,\n resized: (size: Size) => void,\n) =>\n Effect.gen(function* () {\n // Until a capture reads its viewport or delivers a frame, its first frame stands in.\n let expected: Size | null = null;\n let run: Run | undefined;\n // Wakes the decider for a new run or an ended one; wakes while it is busy coalesce.\n const wake = yield* Queue.sliding<void>(1);\n\n const end = () => {\n if (run === undefined) return;\n drop(run.frames.length);\n run = undefined;\n Queue.offerUnsafe(wake, undefined);\n };\n\n const now = () => monotonicMillis(options.clock);\n\n const adopt = (adopted: Run) => {\n run = undefined;\n expected = adopted.device;\n resized(adopted.device);\n for (const held of adopted.frames) deliver(held.frame, held.timestamp);\n };\n\n const decide: Effect.Effect<void> = Effect.suspend(() => {\n const deciding = run;\n\n if (deciding === undefined) return Effect.void;\n\n return readViewport(options).pipe(\n Effect.flatMap((viewport) => {\n if (run !== deciding) return decide;\n if (viewport !== null && sameSize(viewport, deciding.device))\n return Effect.sync(() => adopt(deciding));\n\n return outlast(deciding);\n }),\n );\n });\n\n // Waits until the run outlasts any capture, unless a newer frame decides it first.\n const outlast = (waiting: Run): Effect.Effect<void> =>\n Effect.suspend(() => {\n if (run !== waiting) return decide;\n const remaining = waiting.since + Duration.toMillis(outlasting) - now();\n\n if (remaining <= 0) return Effect.sync(() => adopt(waiting));\n\n return Effect.sleep(Duration.millis(remaining)).pipe(\n Effect.provideService(Clock.Clock, options.clock),\n Effect.race(Queue.take(wake)),\n Effect.andThen(outlast(waiting)),\n );\n });\n\n yield* Queue.take(wake).pipe(Effect.andThen(decide), Effect.forever, Effect.forkScoped);\n\n return {\n /** Drops the frames still waiting; their capture has stopped. */\n end,\n /** A new capture expects the viewport it read, if any. */\n restart: (viewport: Size | null) => {\n end();\n expected = viewport;\n },\n /** Whether a frame of this device size shows the page, as far as the capture knows. */\n offer: (frame: Frame, timestamp: number, image: Size | undefined, device: Size) => {\n if (image !== undefined && !sameShape(image, device)) {\n drop(1);\n\n return;\n }\n expected ??= device;\n if (sameSize(device, expected)) {\n end();\n deliver(frame, timestamp);\n\n return;\n }\n if (run !== undefined && !sameSize(run.device, device)) end();\n if (run === undefined) {\n run = { device, since: now(), frames: [] };\n Queue.offerUnsafe(wake, undefined);\n }\n run.frames.push({ frame, timestamp });\n if (run.frames.length > 16) {\n run.frames.shift();\n drop(1);\n }\n },\n };\n });\n","/** Native frame timing and monotonic evidence across clock recalibration. */\nimport type { Clock } from \"effect\";\n\nimport { type Estimate, monotonicMillis, toHostTime, uncertaintyAt } from \"../../Clock.ts\";\nimport { BrowserPaint, Frame } from \"../../Frame.ts\";\nimport type { NativeFrame, Transport } from \"./transport.ts\";\n\n/**\n * A native frame as readers get it: its picture's size, else the capture's or its device's, and\n * its paint mapped by the browser's newest estimate, which may be older than the frame and says\n * less about later paint.\n */\nexport const timed = (\n options: {\n readonly id: string;\n readonly clock: Clock.Clock;\n readonly imageSize: (\n data: Uint8Array,\n ) => { readonly width: number; readonly height: number } | undefined;\n readonly latest: () => Estimate | undefined;\n },\n native: NativeFrame,\n timestamp: number,\n generation: {\n readonly id: number;\n readonly sequence: number;\n readonly calibration: Estimate;\n readonly size: { readonly width: number; readonly height: number } | null;\n readonly transport: Pick<Transport, \"frameTag\">;\n },\n data: Uint8Array,\n) => {\n const image = options.imageSize(data);\n const device = { width: native.metadata.deviceWidth, height: native.metadata.deviceHeight };\n const size = image ?? generation.size ?? device;\n const estimate = options.latest() ?? generation.calibration;\n const hostTime = toHostTime(estimate, timestamp);\n\n const frame = new Frame({\n page: options.id,\n capture: { generation: generation.id, sequence: generation.sequence },\n data,\n timing: new BrowserPaint({\n timestamp,\n hostTime,\n uncertaintyMillis: uncertaintyAt(estimate, hostTime),\n }),\n receivedAt: monotonicMillis(options.clock),\n width: size.width,\n height: size.height,\n ...generation.transport.frameTag(),\n });\n\n return { frame, image, device };\n};\n\n/** Clamp only the estimate's centre, widening its interval by the correction. */\nexport const orderedFrame = (frame: Frame, previous: number): Frame =>\n frame.hostTime < previous && frame.timing._tag === \"BrowserPaint\"\n ? new Frame({\n ...frame,\n timing: new BrowserPaint({\n ...frame.timing,\n hostTime: previous,\n uncertaintyMillis: frame.timing.uncertaintyMillis + previous - frame.hostTime,\n }),\n })\n : frame;\n","/** Actual native replies outlive callers; bounded transactions retain them without holding teardown. */\nimport { Cause, Clock, Duration, Effect, Exit, Fiber } from \"effect\";\n\nimport type { BrowserError } from \"../../BrowserError.ts\";\nimport * as Replies from \"../page/replies.ts\";\n\nconst deadline = Duration.seconds(2);\n\ntype Operation = \"screencast start\" | \"screencast stop\" | \"picture restoration\";\n\ninterface Options<G> {\n readonly clock: Clock.Clock;\n readonly error: (cause: unknown) => BrowserError;\n readonly closed: () => boolean;\n readonly current: () => G;\n readonly pause: (current: G) => Effect.Effect<void, BrowserError>;\n readonly resume: (current: G) => Effect.Effect<void, BrowserError>;\n readonly fail: (current: G, error: BrowserError) => void;\n}\n\nexport const make = <G>(options: Options<G>) => {\n const replies = Replies.make();\n const pending = new Map<Operation, Promise<void>>();\n\n const late = (kind: Operation) => options.error(new Error(`${kind} exceeded its deadline`));\n\n const track = (\n operation: Operation,\n actual: Promise<unknown>,\n failed: (cause: unknown) => void,\n ) => {\n const reply = actual.then(() => undefined, failed);\n\n pending.set(operation, reply);\n\n return reply.finally(() => {\n if (pending.get(operation) === reply) pending.delete(operation);\n });\n };\n\n const wait = (operation?: Operation) =>\n (operation === undefined\n ? replies.idle.pipe(Effect.andThen(Effect.promise(() => Promise.all(pending.values()))))\n : Effect.promise(() => pending.get(operation) ?? Promise.resolve())\n ).pipe(\n Effect.asVoid,\n Effect.interruptible,\n Effect.timeoutOrElse({\n duration: deadline,\n orElse: () =>\n Effect.fail(late(operation ?? pending.keys().next().value ?? \"picture restoration\")),\n }),\n Effect.provideService(Clock.Clock, options.clock),\n );\n\n const excluding = <A, E, R>(picture: Effect.Effect<A, E, R>) =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n yield* restore(wait());\n if (options.closed()) return yield* options.error(new Error(\"Target page has been closed\"));\n const current = options.current();\n const run = yield* replies.begin;\n\n const result = yield* restore(\n options\n .pause(current)\n .pipe(Effect.andThen(picture), Effect.provideService(Replies.Current, run)),\n ).pipe(Effect.exit);\n\n // Called after the Effect exits: the owner cannot become idle between its commands.\n const cleaned = yield* wait().pipe(\n Effect.andThen(options.resume(current)),\n Effect.timeoutOrElse({\n duration: deadline,\n orElse: () => Effect.fail(late(\"picture restoration\")),\n }),\n Effect.provideService(Clock.Clock, options.clock),\n Effect.exit,\n // A joined child has fresh interruption state. Parent cancellation cannot skip cleanup.\n Effect.forkChild,\n Effect.flatMap(Fiber.join),\n );\n\n if (Exit.isFailure(cleaned))\n options.fail(current, options.error(Cause.squash(cleaned.cause)));\n if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);\n if (Exit.isFailure(cleaned)) return yield* Effect.failCause(cleaned.cause);\n\n return result.value;\n }),\n );\n\n return { excluding, idle: wait(), wait, track };\n};\n","/** The capture's one lifecycle: retirement is absorbing and retains its first failure. */\nimport type { BrowserError } from \"../../BrowserError.ts\";\n\nexport type State =\n | { readonly _tag: \"Capturing\" }\n | { readonly _tag: \"Paused\" }\n | { readonly _tag: \"Stopped\"; readonly failure: BrowserError | undefined };\n\nexport type Input =\n | { readonly _tag: \"Pause\" | \"Resume\" }\n | { readonly _tag: \"Stop\"; readonly failure?: BrowserError | undefined };\n\nexport const initial: State = { _tag: \"Capturing\" };\n\nexport const step = (state: State, input: Input): State => {\n if (input._tag === \"Stop\")\n return {\n _tag: \"Stopped\",\n failure: state._tag === \"Stopped\" ? (state.failure ?? input.failure) : input.failure,\n };\n if (state._tag === \"Stopped\") return state;\n\n return { _tag: input._tag === \"Pause\" ? \"Paused\" : \"Capturing\" };\n};\n\nexport const failureOf = (state: State) => (state._tag === \"Stopped\" ? state.failure : undefined);\n","/**\n * One CDP screencast per page, with bounded transport replies and per-reader loss accounting.\n * Native callbacks own synchronous bookkeeping; the page scope owns startup and teardown.\n */\nimport {\n Clock,\n Deferred,\n Duration,\n Effect,\n Exit,\n Option,\n Queue,\n Result,\n type Scope,\n Semaphore,\n Stream,\n} from \"effect\";\nimport { Base64 } from \"effect/encoding\";\n\nimport { type BrowserError, InvalidRequest } from \"../../BrowserError.ts\";\nimport { type Estimate, monotonicMillis } from \"../../Clock.ts\";\nimport { CaptureStats, type Frame, type ScreencastOptions, sameCapture } from \"../../Frame.ts\";\nimport { undispatched } from \"../page/context.ts\";\nimport { tally } from \"./counts.ts\";\nimport { readViewport, sizeFilter, type Size } from \"./dimensions.ts\";\nimport { orderedFrame, timed } from \"./frame.ts\";\nimport * as Quiescence from \"./quiescence.ts\";\nimport { failureOf, initial, type State, step } from \"./state.ts\";\nimport type { NativeFrame, Transport } from \"./transport.ts\";\n\ninterface Options {\n readonly id: string;\n /** Where each capture's screencast runs, found as it starts. */\n readonly transport: Effect.Effect<Transport, BrowserError>;\n readonly clock: Clock.Clock;\n /** The estimate a capture starts with, once the page can be captured. */\n readonly calibrate: Effect.Effect<Estimate, BrowserError>;\n /** The browser's newest estimate, which times each frame. */\n readonly latest: () => Estimate | undefined;\n /** Measure the clock again if it is due, while frames flow. */\n readonly renew: Effect.Effect<void>;\n /** What the page needs from its own session while frames flow, sent as a capture starts. */\n readonly watch: Effect.Effect<unknown, BrowserError>;\n /** How long frames are kept, measured back from the newest. */\n readonly frameHistory: Duration.Duration;\n /** The viewport in CSS pixels; a capture is scaled to fit it, as screenshots are. */\n readonly viewport: Effect.Effect<Size, BrowserError>;\n /** Copies the restored whole surface before native capture can restart. */\n readonly restore: () => Promise<unknown>;\n readonly imageSize: (data: Uint8Array) => Size | undefined;\n readonly error: (cause: unknown) => BrowserError;\n}\n\ntype Envelope =\n | { readonly _tag: \"Frame\"; readonly sequence: number; readonly frame: Frame }\n | { readonly _tag: \"Failure\"; readonly error: BrowserError };\n\ninterface Generation {\n readonly id: number;\n sequence: number;\n readonly subscribers: Set<Queue.Queue<Envelope>>;\n readonly transport: Transport;\n /** Stops handing the transport's frames to this generation. */\n unlisten: () => void;\n readonly calibration: Estimate;\n /** The native capture's settings; every reader of this generation shares them. */\n readonly quality: number;\n size: Size | null;\n readonly explicitSize: boolean;\n state: State;\n predecessor: number | undefined;\n}\n\nexport interface Controller {\n /** Acquire a running capture now; its stream waits independently for the first frame. */\n readonly open: (options?: ScreencastOptions) => Effect.Effect<\n {\n readonly stream: Stream.Stream<Frame, BrowserError>;\n /** Current before this reader subscribed, never duplicated in its stream. */\n readonly current: Frame | undefined;\n },\n BrowserError,\n Scope.Scope\n >;\n readonly stream: (options?: ScreencastOptions) => Stream.Stream<Frame, BrowserError>;\n readonly latest: Effect.Effect<Option.Option<Frame>>;\n readonly recent: Effect.Effect<ReadonlyArray<Frame>>;\n /** Lifetime counts, or those of the latest `windowMillis`, at most `countsKept`. */\n readonly stats: (windowMillis?: number) => Effect.Effect<CaptureStats>;\n readonly active: Effect.Effect<boolean>;\n /** Once every frame the running capture's connection sent before now has arrived. */\n readonly sync: Effect.Effect<void, BrowserError>;\n /** This exact frame still belongs to the active capture and its current document. */\n readonly current: (frame: Frame) => boolean;\n /** Confirm this exact frame remains current after the capture connection's round trip. */\n readonly confirm: (frame: Frame) => Effect.Effect<boolean, BrowserError>;\n /** Run a clipped or scaled picture of the page, keeping what it draws out of the capture. */\n readonly excluding: <A, E, R>(\n picture: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | BrowserError, R>;\n}\n\nconst replyCapacity = 32;\nconst subscriberCapacity = 16;\nconst deadline = Duration.seconds(2);\n\n/**\n * What a new capture starts with: where it runs, the clock's estimate, and the viewport unless\n * the reader gave a size. A capture connection attaches while the page's own session maps the\n * clock, and a page too busy to report its viewport is still captured, at device size.\n */\nconst prepare = (options: Options, screencast: ScreencastOptions) =>\n Effect.all(\n [\n options.transport.pipe(Effect.interruptible),\n Effect.gen(function* () {\n const calibration = yield* options.calibrate.pipe(Effect.interruptible);\n const viewport = screencast.size === undefined ? yield* readViewport(options) : null;\n\n return { calibration, viewport };\n }),\n ],\n { concurrency: 2 },\n );\n\n/**\n * A running capture's failure, told once its page's fate is known. A capture can fail before the\n * page's own session hears why: a capture connection hears the browser's end before the connection\n * that drives the page does, and an acknowledgement can be refused before the browser's loss is\n * known. So the failure waits for the page's scope to close, `closed`, and is then the page's own\n * end or its browser's loss, as `gone` reads it; or, if the page still stands after `deadline`,\n * the capture's own.\n */\nconst told =\n (closed: Deferred.Deferred<void>, gone: () => BrowserError, clock: Clock.Clock) =>\n (failure: BrowserError) =>\n Deferred.await(closed).pipe(\n Effect.map(gone),\n Effect.timeoutOrElse({ duration: deadline, orElse: () => Effect.succeed(failure) }),\n Effect.provideService(Clock.Clock, clock),\n Effect.flatMap(Effect.fail),\n );\n\n/**\n * Once every frame the running capture's transport sent before now has arrived; a capture that\n * has failed, or whose round trip fails, fails as `why` tells it.\n */\nconst synced = (\n current: Generation | undefined,\n why: (failure: BrowserError) => Effect.Effect<never, BrowserError>,\n error: (cause: unknown) => BrowserError,\n): Effect.Effect<void, BrowserError> => {\n if (current === undefined) return Effect.void;\n const failure = failureOf(current.state);\n\n if (failure !== undefined) return why(failure);\n\n return Effect.tryPromise({ try: () => current.transport.sync(), catch: error }).pipe(\n Effect.catch(why),\n Effect.asVoid,\n );\n};\n\nconst confirmation =\n (\n read: () => {\n readonly generation: Generation | undefined;\n readonly replies: number;\n },\n current: Controller[\"current\"],\n why: (failure: BrowserError) => Effect.Effect<never, BrowserError>,\n error: (cause: unknown) => BrowserError,\n ): Controller[\"confirm\"] =>\n (frame) =>\n Effect.suspend(() => {\n const { generation } = read();\n\n if (generation === undefined) return Effect.succeed(false);\n\n return synced(generation, why, error).pipe(\n Effect.map(() => {\n const after = read();\n\n return after.generation === generation && after.replies === 0 && current(frame);\n }),\n );\n });\n\nconst isCurrent = (\n frame: Frame,\n generation: Generation | undefined,\n latest: Option.Option<Frame>,\n) =>\n generation !== undefined &&\n generation.state._tag === \"Capturing\" &&\n frame.capture !== undefined &&\n sameCapture(frame, Option.getOrUndefined(latest)) &&\n generation.transport.frameTag().document === frame.document;\n\nconst currentFrame = (generation: Generation, latest: Option.Option<Frame>) =>\n Option.getOrUndefined(Option.filter(latest, (frame) => isCurrent(frame, generation, latest)));\n\n/** One reader counts its own missed envelopes without hiding gaps inside stream chunks. */\nconst frames = (\n subscription: Queue.Queue<Envelope>,\n baseline: number,\n why: (failure: BrowserError) => Effect.Effect<never, BrowserError>,\n missed: (count: number) => void,\n) => {\n let previous = baseline;\n\n // Pull one envelope at a time so taking a stream chunk cannot hide a slow reader's loss.\n return Stream.fromEffectRepeat(\n Queue.take(subscription).pipe(\n Effect.flatMap((envelope) => {\n if (envelope._tag === \"Failure\") return why(envelope.error);\n\n return Effect.sync(() => {\n if (envelope.sequence > previous + 1) missed(envelope.sequence - previous - 1);\n previous = envelope.sequence;\n\n return envelope.frame;\n });\n }),\n ),\n );\n};\n\nconst renewals = Effect.fnUntraced(function* (options: Options) {\n const renewing = yield* Queue.sliding<void>(1);\n\n yield* Queue.take(renewing).pipe(\n Effect.andThen(options.renew),\n Effect.andThen(Effect.sleep(Duration.seconds(1))),\n Effect.provideService(Clock.Clock, options.clock),\n Effect.forever,\n Effect.forkScoped,\n );\n\n return renewing;\n});\n\nconst receive =\n (\n options: Options,\n current: Generation,\n replies: Set<Promise<void>>,\n counts: ReturnType<typeof tally>,\n sizes: Effect.Success<ReturnType<typeof sizeFilter>>,\n renewing: Queue.Queue<void>,\n fail: (current: Generation, error: BrowserError) => void,\n ) =>\n (native: NativeFrame) => {\n if (current.state._tag === \"Stopped\") return;\n counts.count(\"received\");\n if (replies.size >= replyCapacity) {\n fail(current, options.error(new Error(\"screencast acknowledgement capacity exceeded\")));\n\n return;\n }\n\n const reply = current.transport\n .acknowledge(native.sessionId)\n .then(\n () => undefined,\n (cause: unknown) => {\n if (current.state._tag !== \"Stopped\") fail(current, options.error(cause));\n },\n )\n .then(() => void replies.delete(reply));\n\n replies.add(reply);\n const browserSeconds = native.metadata.timestamp;\n const timestamp = browserSeconds === undefined ? Number.NaN : browserSeconds * 1000;\n\n if (!Number.isFinite(timestamp)) return counts.count(\"missingTimestamp\");\n if (current.predecessor !== undefined && timestamp <= current.predecessor)\n return counts.count(\"late\");\n Queue.offerUnsafe(renewing, undefined);\n const decoded = Base64.decode(native.data);\n\n if (Result.isFailure(decoded)) {\n fail(\n current,\n options.error(new Error(\"the capture connection sent invalid base64 picture data\")),\n );\n\n return;\n }\n current.sequence++;\n const { frame, image, device } = timed(options, native, timestamp, current, decoded.success);\n\n if (current.state._tag === \"Paused\") return counts.count(\"duringPictures\");\n sizes.offer(frame, timestamp, image, device);\n };\n\nconst settingsOf = (current: Generation) => ({\n format: \"jpeg\" as const,\n quality: current.quality,\n ...(current.size === null\n ? {}\n : { maxWidth: current.size.width, maxHeight: current.size.height }),\n});\n\nconst healthy = (current: Generation) =>\n Effect.suspend(() => {\n const failure = failureOf(current.state);\n\n return failure === undefined ? Effect.void : Effect.fail(failure);\n });\n\n// Native caps must follow implicit viewport growth or every following frame stays scaled down.\nconst followGrowth = (\n changes: Queue.Queue<Size>,\n lock: Semaphore.Semaphore,\n generation: () => Generation | undefined,\n pictures: ReturnType<typeof Quiescence.make<Generation>>,\n fail: (current: Generation, error: BrowserError) => void,\n) =>\n Queue.take(changes).pipe(\n Effect.flatMap((size) =>\n lock.withPermits(1)(\n Effect.suspend(() => {\n const current = generation();\n\n if (\n current === undefined ||\n current.explicitSize ||\n current.state._tag !== \"Capturing\" ||\n (current.size !== null &&\n size.width <= current.size.width &&\n size.height <= current.size.height)\n )\n return Effect.void;\n\n return pictures\n .excluding(\n Effect.sync(() => {\n current.size = size;\n }),\n )\n .pipe(Effect.catch((error) => Effect.sync(() => fail(current, error))));\n }),\n ),\n ),\n Effect.forever,\n Effect.forkScoped,\n );\n\ninterface Lease {\n readonly current: Generation;\n readonly subscription: Queue.Queue<Envelope>;\n readonly baseline: number;\n readonly frame: Frame | undefined;\n}\n\n/** The first subscription must exist before the native start can emit its only frame. */\nconst subscribe = (current: Generation) =>\n Effect.gen(function* () {\n const subscription = yield* Queue.sliding<Envelope>(subscriberCapacity);\n\n current.subscribers.add(subscription);\n const failure = failureOf(current.state);\n\n if (failure !== undefined) Queue.offerUnsafe(subscription, { _tag: \"Failure\", error: failure });\n\n return subscription;\n });\n\nconst reader =\n (\n acquire: (options: ScreencastOptions) => Effect.Effect<Lease, BrowserError>,\n leave: (lease: Lease) => Effect.Effect<void>,\n why: (failure: BrowserError) => Effect.Effect<never, BrowserError>,\n lost: (count: number) => void,\n ): Controller[\"open\"] =>\n (settings = {}) =>\n Effect.acquireRelease(acquire(settings).pipe(Effect.interruptible), leave).pipe(\n Effect.map((lease) => ({\n current: lease.frame,\n stream: frames(lease.subscription, lease.baseline, why, lost),\n })),\n );\n\nexport const make = (options: Options) =>\n Effect.gen(function* () {\n const lock = yield* Semaphore.make(1);\n const replies = new Set<Promise<void>>();\n let generation: Generation | undefined;\n let generations = 0;\n let lastHostTime = Number.NEGATIVE_INFINITY;\n // Done as the page's scope closes, once the page has gone and its browser's loss, if any, is\n // known.\n const closed = yield* Deferred.make<void>();\n const pageScope = yield* Effect.scope;\n const isClosed = () => pageScope.state._tag === \"Closed\" || Deferred.isDoneUnsafe(closed);\n let latest = Option.none<Frame>();\n let history: ReadonlyArray<Frame> = [];\n const counts = tally(() => monotonicMillis(options.clock));\n // Frames delivered, which number them so that a reader can tell what it missed.\n let delivered = 0;\n\n // Frames that show the page go to the running capture's readers.\n const deliver = (frame: Frame, timestamp: number) => {\n const current = generation;\n\n if (current === undefined) return;\n // Held frames are checked again: frames encoded out of order are dropped, never reordered.\n if (current.predecessor !== undefined && timestamp <= current.predecessor)\n return counts.count(\"late\");\n if (current.predecessor !== undefined) counts.gap(timestamp - current.predecessor);\n current.predecessor = timestamp;\n frame = orderedFrame(frame, lastHostTime);\n lastHostTime = frame.hostTime;\n delivered++;\n counts.count(\"accepted\");\n latest = Option.some(frame);\n history = [\n ...history.filter(\n (kept) => kept.hostTime >= frame.hostTime - Duration.toMillis(options.frameHistory),\n ),\n frame,\n ];\n for (const subscriber of current.subscribers)\n Queue.offerUnsafe(subscriber, { _tag: \"Frame\", sequence: delivered, frame });\n };\n\n const resized = yield* Queue.sliding<Size>(1);\n\n const sizes = yield* sizeFilter(\n options,\n deliver,\n (frames) => counts.count(\"foreignSize\", frames),\n (size) => {\n Queue.offerUnsafe(resized, size);\n },\n );\n\n // On air a capture runs for hours, and its frames are timed by the browser's newest estimate,\n // so arriving frames renew it: a check at most each second, a measurement once it is due.\n const renewing = yield* renewals(options);\n\n const notifyFailure = (current: Generation, failure: BrowserError) => {\n if (failureOf(current.state) !== undefined) return;\n for (const subscriber of current.subscribers)\n Queue.offerUnsafe(subscriber, { _tag: \"Failure\", error: failure });\n stop(current, failure);\n };\n\n const failed = (current: Generation) => (cause: unknown) =>\n notifyFailure(current, options.error(cause));\n\n const stopNative = (current: Generation) =>\n pictures.track(\"screencast stop\", current.transport.stop(), failed(current));\n\n const startNative = (current: Generation) =>\n pictures.track(\n \"screencast start\",\n current.transport.start(settingsOf(current)),\n failed(current),\n );\n\n const stop = (current: Generation, failure?: BrowserError) => {\n const stopped = current.state._tag === \"Stopped\";\n const paused = current.state._tag === \"Paused\";\n\n current.state = step(current.state, { _tag: \"Stop\", failure });\n if (stopped) return;\n sizes.end();\n current.unlisten();\n // A paused capture already owns its stop, including a reply still in flight.\n if (!paused) void stopNative(current);\n };\n\n const gone = () => options.error(new Error(\"Target page has been closed\"));\n const why = told(closed, gone, options.clock);\n\n const awaitStop = (current: Generation) =>\n pictures\n .wait(\"screencast stop\")\n .pipe(Effect.catch((error) => Effect.sync(() => notifyFailure(current, error))));\n\n const pictures = Quiescence.make({\n clock: options.clock,\n error: options.error,\n closed: isClosed,\n current: () => generation,\n fail: (current, error) => {\n if (current !== undefined) notifyFailure(current, error);\n },\n pause: (current): Effect.Effect<void, BrowserError> =>\n Effect.gen(function* () {\n if (current?.state._tag !== \"Capturing\") return;\n current.state = step(current.state, { _tag: \"Pause\" });\n latest = Option.none();\n sizes.end();\n void stopNative(current);\n yield* pictures\n .wait(\"screencast stop\")\n .pipe(Effect.tapError((error) => Effect.sync(() => notifyFailure(current, error))));\n yield* healthy(current);\n }),\n resume: (current): Effect.Effect<void, BrowserError> =>\n Effect.gen(function* () {\n const resumable = () => {\n if (current === undefined || generation !== current) return false;\n if (current.subscribers.size === 0) {\n stop(current);\n generation = undefined;\n }\n\n return current.state._tag !== \"Stopped\" && !isClosed();\n };\n\n if (current === undefined || !resumable()) return;\n // Screenshot replies restore emulation before the compositor has necessarily painted\n // it. Copy the whole restored surface while stopped, retaining its actual native reply.\n void pictures.track(\"picture restoration\", options.restore(), failed(current));\n yield* pictures.wait(\"picture restoration\");\n yield* healthy(current);\n const viewport = yield* readViewport(options);\n\n if (!resumable()) return;\n sizes.restart(viewport);\n // Its only quiet-page frame can precede the native start acknowledgement.\n current.state = step(current.state, { _tag: \"Resume\" });\n void startNative(current);\n yield* pictures.wait(\"screencast start\");\n yield* healthy(current);\n }),\n });\n\n yield* followGrowth(resized, lock, () => generation, pictures, notifyFailure);\n\n // A reader leaves; the last one stops its generation.\n const leave = (current: Generation, subscription: Queue.Queue<Envelope>) =>\n Effect.gen(function* () {\n current.subscribers.delete(subscription);\n yield* Queue.shutdown(subscription);\n if (current.subscribers.size !== 0) return;\n yield* Effect.sync(() => stop(current));\n yield* awaitStop(current);\n if (generation === current) generation = undefined;\n });\n\n const acquire = (screencast: ScreencastOptions) =>\n lock.withPermits(1)(\n Effect.uninterruptible(\n Effect.gen(function* () {\n if (isClosed()) return yield* gone();\n let current = generation;\n const starting = current === undefined;\n\n if (current === undefined) {\n yield* pictures.idle;\n const [transport, { calibration, viewport }] = yield* prepare(options, screencast);\n const size = screencast.size ?? viewport;\n\n if (isClosed()) return yield* gone();\n\n current = {\n id: ++generations,\n sequence: 0,\n subscribers: new Set(),\n transport,\n unlisten: () => undefined,\n calibration,\n quality: screencast.quality ?? 80,\n size,\n explicitSize: screencast.size !== undefined,\n state: initial,\n predecessor: undefined,\n };\n\n generation = current;\n latest = Option.none();\n sizes.restart(viewport);\n } else if (\n (screencast.quality !== undefined && screencast.quality !== current.quality) ||\n (screencast.size !== undefined &&\n (screencast.size.width !== current.size?.width ||\n screencast.size.height !== current.size.height))\n )\n // One native capture serves every reader; silently giving a reader other settings\n // than it asked for would misstate its frames.\n return yield* undispatched(\n \"screencast\",\n new InvalidRequest({\n detail: `a screencast with quality ${current.quality}${\n current.size === null\n ? \"\"\n : ` and size ${current.size.width}x${current.size.height}`\n } is already running on this page; read it without options or with the same ones`,\n }),\n );\n // The callback API must apply sliding synchronously; PubSub.publishUnsafe skips it.\n const subscription = yield* subscribe(current);\n const baseline = delivered;\n const frame = currentFrame(current, latest);\n\n if (starting) {\n const listening = current;\n\n current.unlisten = listening.transport.listen({\n frame: receive(options, current, replies, counts, sizes, renewing, notifyFailure),\n lost: (error) => notifyFailure(listening, error),\n });\n\n const screencast = Effect.promise(() => startNative(listening)).pipe(\n Effect.andThen(healthy(listening)),\n );\n\n const started = yield* options.watch.pipe(\n Effect.zip(screencast, { concurrent: true }),\n Effect.interruptible,\n Effect.timeoutOrElse({\n duration: deadline,\n orElse: () =>\n Effect.fail(options.error(new Error(\"screencast start exceeded its deadline\"))),\n }),\n Effect.provideService(Clock.Clock, options.clock),\n Effect.exit,\n );\n\n if (Exit.isFailure(started)) {\n yield* leave(current, subscription);\n\n return yield* Effect.failCause(started.cause);\n }\n }\n\n return { current, subscription, baseline, frame };\n }),\n ),\n );\n\n const open = reader(\n acquire,\n ({ current, subscription }) =>\n Effect.suspend(() => {\n current.subscribers.delete(subscription);\n\n return current.subscribers.size > 0\n ? Queue.shutdown(subscription)\n : lock.withPermits(1)(leave(current, subscription));\n }),\n why,\n (count) => counts.count(\"lost\", count),\n );\n\n // The page's scope closes once the page has gone, when its browser's loss, if any, is known.\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => Deferred.doneUnsafe(closed, Exit.void)).pipe(\n Effect.andThen(\n lock.withPermits(1)(\n Effect.suspend(() => {\n const current = generation;\n\n if (current === undefined) return Effect.void;\n notifyFailure(current, gone());\n\n return awaitStop(current);\n }),\n ),\n ),\n ),\n );\n\n return {\n open,\n stream: (options?: ScreencastOptions) =>\n Stream.unwrap(Effect.map(open(options), ({ stream }) => stream)),\n latest: Effect.sync(() => latest),\n recent: Effect.sync(() => history),\n active: Effect.sync(() => generation !== undefined && generation.state._tag !== \"Stopped\"),\n sync: Effect.suspend(() => synced(generation, why, options.error)),\n current: (frame: Frame) => isCurrent(frame, generation, latest),\n confirm: confirmation(\n () => ({ generation, replies: replies.size }),\n (frame: Frame) => isCurrent(frame, generation, latest),\n why,\n options.error,\n ),\n excluding: (picture) => lock.withPermits(1)(pictures.excluding(picture)),\n stats: (windowMillis?: number) =>\n Effect.sync(\n () => new CaptureStats({ ...counts.read(windowMillis), ackBacklog: replies.size }),\n ),\n } satisfies Controller;\n });\n","/**\n * Where a page's screencast runs: on the page's own session, or on a capture connection that the\n * provider supplies, where frames and their acknowledgements never wait behind a large message on\n * the connection that drives the page. There the page's session attaches as its first capture\n * starts, with the Page domain on, and stays until the page closes or the session ends; the next\n * capture then attaches again.\n *\n * Frames take their document from the commits their own session reports, in the order the browser\n * sent them, so a frame never shows a document after the one it carries, as on the page's own\n * session. They are numbered as the page's own session counts documents: a commit it has counted\n * keeps its number, and one the capture connection sees first takes the next, until it is counted.\n */\nimport { Effect, Exit, Option, Schema, Scope, Semaphore } from \"effect\";\n\nimport type { CaptureSource } from \"../../Browser.ts\";\nimport { type BrowserError, Failed } from \"../../BrowserError.ts\";\nimport { type Bridge, Commit, commitOf, mainFrame, MainFrameEvent } from \"../page/bridge.ts\";\nimport { type PageContext, undispatched } from \"../page/context.ts\";\nimport * as Port from \"../page/port.ts\";\n\n/** Where a capture's screencast runs. Its calls never throw: a failure rejects. */\nexport interface Transport {\n readonly start: (settings: {\n readonly format: \"jpeg\";\n readonly quality: number;\n readonly maxWidth?: number;\n readonly maxHeight?: number;\n }) => Promise<unknown>;\n readonly acknowledge: (frame: number) => Promise<unknown>;\n readonly stop: () => Promise<unknown>;\n /**\n * A round trip whose answer comes behind every frame sent before it. On the page's own session,\n * the page's own calls are such round trips already, so it sends nothing.\n */\n readonly sync: () => Promise<unknown>;\n /**\n * Hand its frames to `on.frame` as they arrive, and its end to `on.lost` should it end, until\n * the returned function is called.\n */\n readonly listen: (on: {\n readonly frame: (frame: NativeFrame) => void;\n readonly lost: (error: BrowserError) => void;\n }) => () => void;\n /** What a frame arriving now shows: its session, the document it followed and the address then. */\n readonly frameTag: () => {\n readonly session: string;\n readonly connection: string;\n readonly document: number;\n readonly url: string;\n };\n}\n\n/** The page's own session. */\nexport const own = (page: PageContext, bridge: Bridge): Transport => {\n const { send } = page.protocol;\n\n return {\n start: (settings) => send(\"Page.startScreencast\", settings),\n acknowledge: (frame) => send(\"Page.screencastFrameAck\", { sessionId: frame }),\n stop: () => send(\"Page.stopScreencast\"),\n sync: () => Promise.resolve(),\n listen: (on) => {\n const frame = (value: unknown) =>\n Option.match(Schema.decodeUnknownOption(ScreencastFrame)(value), {\n onNone: () =>\n on.lost(\n undispatched(\n \"screencast\",\n new Failed({ detail: \"the page connection sent an unreadable screencast frame\" }),\n ),\n ),\n onSome: on.frame,\n });\n\n page.cdp.on(\"Page.screencastFrame\", frame);\n\n return () => {\n page.cdp.off(\"Page.screencastFrame\", frame);\n };\n },\n frameTag: bridge.frameTag,\n };\n};\n\nconst FrameTree = Schema.Struct({ frameTree: Schema.Struct({ frame: Commit }) });\n\n/** A native screencast frame, as Chromium sends it. */\nconst ScreencastFrame = Schema.Struct({\n data: Schema.String,\n sessionId: Schema.Int,\n metadata: Schema.Struct({\n timestamp: Schema.optionalKey(Schema.Finite),\n deviceWidth: Schema.Finite,\n deviceHeight: Schema.Finite,\n }),\n});\n\nexport type NativeFrame = typeof ScreencastFrame.Type;\n\n/**\n * The document and address a capture connection's frames show, from the commits its session\n * reports after `first`, the main frame's document as the session began.\n */\nconst documents = (bridge: Bridge, first: ReturnType<typeof commitOf>) => {\n // The number the page's own session gave the latest commit of `loader`, if it has counted one.\n const counted = (loader: string) => bridge.documentOf(loader) ?? -1;\n const latest = bridge.frameTag().document;\n\n // A loader the page's own session hasn't counted began the document it had from the start, or\n // a commit still on its way to it.\n const shown = {\n ...first,\n document: counted(first.loader) >= 0 ? counted(first.loader) : latest === 0 ? 0 : latest + 1,\n };\n\n return {\n /** A commit or a move the session reported, in the order the browser sent them. */\n see: (seen: ReturnType<typeof mainFrame>) => {\n if (seen?.loader !== undefined) {\n shown.document = Math.max(shown.document + 1, counted(seen.loader));\n shown.loader = seen.loader;\n }\n if (seen !== undefined) shown.url = seen.url;\n },\n tag: () => {\n shown.document = Math.max(shown.document, counted(shown.loader));\n\n return { document: shown.document, url: shown.url };\n },\n };\n};\n\ntype State =\n | { readonly _tag: \"Detached\" }\n | { readonly _tag: \"Attaching\"; readonly scope: Scope.Closeable }\n | { readonly _tag: \"Attached\"; readonly scope: Scope.Closeable; readonly transport: Transport }\n | { readonly _tag: \"Ended\"; readonly scope: Scope.Closeable; readonly error: BrowserError };\n\n/**\n * The page's session on the capture connection, attached when a capture asks for it and kept for\n * the page's scope. Its state changes only here: attaching, attached, or ended by the session's\n * end, which also ends the capture listening to it.\n */\nexport const apart = (\n page: PageContext,\n bridge: Bridge,\n source: CaptureSource,\n error: (cause: unknown) => BrowserError,\n pageScope: Scope.Scope,\n): Effect.Effect<Transport, BrowserError> => {\n const lock = Semaphore.makeUnsafe(1);\n let state: State = { _tag: \"Detached\" };\n let listening: Parameters<Transport[\"listen\"]>[0] | undefined;\n const latest = (): State => state;\n\n const end = (scope: Scope.Closeable, ended: BrowserError) => {\n if ((state._tag !== \"Attaching\" && state._tag !== \"Attached\") || state.scope !== scope) return;\n const attached = state._tag === \"Attached\";\n\n state = { _tag: \"Ended\", scope, error: ended };\n if (attached) listening?.lost(ended);\n };\n\n const unreadable = undispatched(\n \"screencast\",\n new Failed({ detail: \"the capture connection sent an event it could not read\" }),\n );\n\n const attach = (scope: Scope.Closeable) =>\n Effect.gen(function* () {\n let shown: ReturnType<typeof documents> | undefined;\n\n // Commits before the frame tree's answer are in it already.\n const event = (method: string, params: unknown) => {\n const decoded = <A>(schema: Schema.Codec<A, unknown>, act: (value: A) => void) =>\n Option.match(Schema.decodeUnknownOption(schema)(params), {\n onNone: () => end(scope, unreadable),\n onSome: act,\n });\n\n if (method === \"Page.screencastFrame\")\n decoded(ScreencastFrame, (frame: NativeFrame) => listening?.frame(frame));\n else if (method === \"Page.frameNavigated\" || method === \"Page.navigatedWithinDocument\")\n decoded(MainFrameEvent, (event) => shown?.see(mainFrame(page.id, event)));\n else if (method === \"Target.detachedFromTarget\")\n end(scope, error(new Error(\"Target page has been closed\")));\n };\n\n const send = yield* Port.openCapture(page.id, source, {\n event,\n lost: (lost) => end(scope, lost),\n });\n\n // Tracked from the frame tree's answer on, set as it arrives so that no commit after it is\n // missed.\n const tracked = yield* Effect.tryPromise({\n try: () =>\n Promise.all([send(\"Page.enable\"), send(\"Page.getFrameTree\")]).then(([, tree]) =>\n Option.match(Schema.decodeUnknownOption(FrameTree)(tree), {\n onNone: () => Promise.reject(unreadable),\n onSome: ({ frameTree }) => (shown = documents(bridge, commitOf(frameTree.frame))),\n }),\n ),\n catch: error,\n });\n\n return {\n start: (settings) => send(\"Page.startScreencast\", settings),\n acknowledge: (frame) => send(\"Page.screencastFrameAck\", { sessionId: frame }),\n stop: () => send(\"Page.stopScreencast\"),\n sync: () => send(\"Page.getFrameTree\"),\n listen: (on) => {\n listening = on;\n\n return () => {\n if (listening === on) listening = undefined;\n };\n },\n frameTag: () => ({ session: page.session, connection: page.connection, ...tracked.tag() }),\n } satisfies Transport;\n }).pipe(Scope.provide(scope));\n\n const current: Effect.Effect<Transport, BrowserError> = Effect.suspend(() => {\n switch (state._tag) {\n case \"Attached\":\n return Effect.succeed(state.transport);\n case \"Ended\": {\n const { scope } = state;\n\n state = { _tag: \"Detached\" };\n\n return Scope.close(scope, Exit.void).pipe(Effect.andThen(current));\n }\n case \"Detached\":\n case \"Attaching\":\n return Effect.gen(function* () {\n const scope = yield* Scope.fork(pageScope);\n\n state = { _tag: \"Attaching\", scope };\n const attached = yield* Effect.exit(attach(scope).pipe(page.within(\"screencast\")));\n // `end` may have changed it meanwhile.\n const settled = latest();\n\n // A session that ended as it attached is never handed out.\n if (Exit.isSuccess(attached) && settled._tag === \"Attaching\" && settled.scope === scope) {\n state = { _tag: \"Attached\", scope, transport: attached.value };\n\n return attached.value;\n }\n state = { _tag: \"Detached\" };\n yield* Scope.close(scope, Exit.void);\n if (Exit.isFailure(attached)) return yield* attached;\n\n return yield* settled._tag === \"Ended\" ? settled.error : unreadable;\n });\n }\n });\n\n return lock.withPermits(1)(current);\n};\n","/**\n * Pictures of a page: screenshots, frames of a stated age, zooms, and its screencast with the clock\n * that times its frames. A new picture is taken on the page's own protocol session, one at a time:\n * one call where a device pixel is a CSS pixel and nothing is cropped, and two otherwise, unless\n * Playwright emulates the viewport. The page's first clipped picture also holds the screen it reads.\n */\nimport { Duration, Effect, Option, Result, Schedule, Schema, type Scope } from \"effect\";\nimport { Base64 } from \"effect/encoding\";\n\nimport { BrowserError, Failed, InvalidRequest } from \"../../BrowserError.ts\";\nimport * as BrowserClock from \"../../Clock.ts\";\nimport { Frame, Image, Screenshot } from \"../../Frame.ts\";\nimport type { Point } from \"../../Geometry.ts\";\nimport { type FrameOptions, type Paint, Region, type ScreenshotOptions, Zoom } from \"../../Page.ts\";\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport {\n decodeWith,\n failWith,\n type PageContext,\n reasonOf,\n refuse,\n undispatched,\n} from \"../page/context.ts\";\nimport * as Port from \"../page/port.ts\";\nimport type { Viewport } from \"../page/viewport.ts\";\nimport * as Capture from \"./capture.ts\";\nimport { countsKept } from \"./counts.ts\";\nimport type { Size } from \"./dimensions.ts\";\nimport * as Transport from \"./transport.ts\";\n\n/** Read a JPEG's dimensions from its start-of-frame marker. */\nexport const jpegSize = (bytes: Uint8Array): Size | undefined => {\n let offset = 2;\n\n while (offset + 9 < bytes.length) {\n if (bytes[offset] !== 0xff) return undefined;\n const marker = bytes[offset + 1] ?? 0;\n const length = ((bytes[offset + 2] ?? 0) << 8) | (bytes[offset + 3] ?? 0);\n\n if (marker >= 0xc0 && marker <= 0xc3)\n return {\n height: ((bytes[offset + 5] ?? 0) << 8) | (bytes[offset + 6] ?? 0),\n width: ((bytes[offset + 7] ?? 0) << 8) | (bytes[offset + 8] ?? 0),\n };\n offset += 2 + length;\n }\n\n return undefined;\n};\n\n/** Read a PNG's dimensions from its header chunk. */\nexport const pngSize = (bytes: Uint8Array): Size | undefined => {\n if (bytes.length < 24 || bytes[1] !== 0x50 || bytes[2] !== 0x4e || bytes[3] !== 0x47)\n return undefined;\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n\n return { width: view.getUint32(16), height: view.getUint32(20) };\n};\n\n/** The format a new picture is taken in. */\nexport type Format = \"jpeg\" | \"png\";\n\n// A picture's pixels: CSS pixels, or the screen's own.\ntype Scale = NonNullable<ScreenshotOptions[\"scale\"]>;\n\n// The part of `Page.getLayoutMetrics` a clip needs: the visual viewport's place in the document and\n// its pinch scale, and the content's size in device and CSS pixels, whose ratio is the device's.\nconst LayoutMetrics = Schema.Struct({\n cssVisualViewport: Schema.Struct({\n pageX: Schema.Finite,\n pageY: Schema.Finite,\n scale: Schema.Finite.check(Schema.isGreaterThan(0)),\n }),\n contentSize: Schema.Struct({ width: Schema.Finite }),\n cssContentSize: Schema.Struct({ width: Schema.Finite }),\n});\n\n// A screencast frame shows the page as it was when it was painted, and a new picture costs a round\n// trip, so by default a frame painted this recently is reused.\nconst defaultMaxAge = Duration.millis(250);\n\n// Chromium answers this while the page has no surface to copy yet, as just after a navigation. The\n// page has one from its first frame, so the picture is taken again a frame later, within the\n// picture's own deadline.\nconst surfaceless = (error: BrowserError) =>\n error.reason._tag === \"Failed\" && error.reason.detail.includes(\"Unable to capture screenshot\");\n\nconst untilPainted = <A, R>(capture: Effect.Effect<A, BrowserError, R>) =>\n capture.pipe(Effect.retry({ while: surfaceless, schedule: Schedule.spaced(\"16 millis\") }));\n\n/**\n * Measure this page's clock against the browser's, in a world without the page script: no DOM\n * markers, input, navigation or extra tabs. Each of three probes reads the browser's time between\n * two stamps of the owner's clock, and the fastest bounds the offset best. A busy page answers each\n * probe late, behind its own work, so the probes that answered within two seconds serve, and the\n * measurement fails only if none did: a wide estimate keeps a capture going, and a renewal while\n * its frames flow narrows it.\n */\nconst calibrator = (page: PageContext, bridge: Bridge) => {\n const { native, now, within } = page;\n const { send } = page.protocol;\n\n // A round trip to the page like any other read, so traced as one.\n const probe = (contextId: number) =>\n Effect.gen(function* () {\n const hostStart = now();\n\n const { result, exceptionDetails } = yield* native(\"calibrate\", () =>\n send(\"Runtime.evaluate\", {\n contextId,\n expression: \"performance.timeOrigin + performance.now()\",\n returnByValue: true,\n }),\n ).pipe(page.span(\"Page.evaluate\", { function: \"clock\" }, \"Trace\"));\n\n const hostEnd = now();\n const browserTime: unknown = result.value;\n\n if (exceptionDetails !== undefined || typeof browserTime !== \"number\")\n return yield* failWith(\n \"calibrate\",\n new Failed({ detail: \"the browser clock probe did not return a timestamp\" }),\n );\n\n return { hostStart, hostEnd, browserTime };\n });\n\n const answered = (contextId: number) =>\n Effect.gen(function* () {\n const probes: Array<BrowserClock.Probe> = [];\n\n yield* Effect.forEach(\n [1, 2, 3],\n () => Effect.map(probe(contextId), (one) => probes.push(one)),\n { discard: true },\n ).pipe(\n within(\"calibrate\", Duration.seconds(2)),\n Effect.catch((error) => (probes.length === 0 ? Effect.fail(error) : Effect.void)),\n );\n\n return probes;\n });\n\n return bridge.bareWorld(\"calibrate\").pipe(\n Effect.flatMap(answered),\n Effect.flatMap((probes) =>\n Option.match(BrowserClock.estimate(probes), {\n onNone: () =>\n failWith(\n \"calibrate\",\n new Failed({ detail: \"the browser clock probes did not define a finite interval\" }),\n ),\n onSome: Effect.succeed,\n }),\n ),\n within(\"calibrate\", Duration.seconds(4)),\n // The fastest probe's round trip: the transport's, plus a trivial script.\n Effect.tap((estimate) =>\n Effect.annotateCurrentSpan(\"roundTripMillis\", Math.round(estimate.roundTripMillis * 10) / 10),\n ),\n page.span(\"Page.calibrateClock\", {}, \"Debug\"),\n page.owned,\n );\n};\n\n// The screen as the page reads it, and its device pixels to a CSS pixel.\nconst ScreenSize = Schema.Struct({ width: Schema.Int, height: Schema.Int, ratio: Schema.Finite });\n\n// The device as the page's own session emulates it: the screen held for crops (see `camera`), and\n// the device scale factor a paint asks for, 0 for the device's own, in one override that keeps the\n// view's size. Playwright emulates the viewport of a browser this library launched, at the scale of\n// its launch, and puts that back over any other, so there a paint keeps that scale.\nconst device = (page: PageContext, bridge: Bridge) => {\n const { playwright, native, within } = page;\n const { send } = page.protocol;\n let screen: Size | undefined;\n let scaled = 0;\n let painting = false;\n\n const metrics = (operation: string) =>\n native(operation, () =>\n send(\"Emulation.setDeviceMetricsOverride\", {\n width: 0,\n height: 0,\n deviceScaleFactor: scaled,\n mobile: false,\n ...(screen === undefined ? {} : { screenWidth: screen.width, screenHeight: screen.height }),\n }),\n );\n\n const screenOf = (operation: string) =>\n bridge\n .evaluate(operation, scriptCall(\"screenSize\"))\n .pipe(Effect.flatMap(decodeWith(operation, ScreenSize)));\n\n // The copy has the screen alone: the view keeps its own size, and the device its pixel ratio.\n const holdScreen = Effect.fnUntraced(function* (operation: string) {\n if (screen !== undefined) return;\n const { width, height } = yield* screenOf(operation);\n\n screen = { width, height };\n yield* metrics(operation).pipe(Effect.onError(() => Effect.sync(() => (screen = undefined))));\n });\n\n const scrollbarsHidden = (hidden: boolean) =>\n native(\"paint\", () => send(\"Emulation.setScrollbarsHidden\", { hidden }));\n\n const paint = (options: Paint): Effect.Effect<void, BrowserError, Scope.Scope> =>\n Effect.gen(function* () {\n const { scale, scrollbars = true } = options;\n const launched = playwright.viewportSize() !== null;\n\n if (scale !== undefined && !(Number.isFinite(scale) && scale > 0 && scale <= 4))\n return yield* refuse(\"paint\", \"a page paints at more than 0 and at most 4 device pixels\");\n if (painting) return yield* refuse(\"paint\", \"the page is painted for another scope already\");\n if (scale !== undefined && launched && (yield* screenOf(\"paint\")).ratio !== scale)\n return yield* refuse(\n \"paint\",\n \"this browser paints at the scale it was launched with, as Chromium's deviceScaleFactor sets\",\n );\n const rescaled = scale !== undefined && !launched;\n\n painting = true;\n yield* Effect.addFinalizer(() =>\n Effect.gen(function* () {\n scaled = 0;\n if (!scrollbars) yield* scrollbarsHidden(false);\n if (rescaled) yield* metrics(\"paint\");\n }).pipe(Effect.ignore, Effect.ensuring(Effect.sync(() => (painting = false)))),\n );\n if (!scrollbars) yield* scrollbarsHidden(true);\n if (rescaled) {\n scaled = scale;\n yield* metrics(\"paint\");\n }\n }).pipe(within(\"paint\"));\n\n return { holdScreen, paint, scaled: () => scaled };\n};\n\n// A new picture in CSS pixels. Where a device pixel is not a CSS pixel, or for a crop, it is\n// Playwright's clip over fresh layout metrics: document coordinates from the visual viewport's\n// place, and its pinch scale divided by the device's. Chromium draws such a capture into a\n// running screencast, so the native capture pauses for the whole camera operation and restoration.\n//\n// Chromium takes a clipped picture through the device emulation of the session that asks for it,\n// then restores the view's size and what that session emulated. The page's own session emulated\n// nothing, so its crops cleared a screen another session emulates, as Browserbase's own does: so\n// before its first clipped picture, it holds a copy of the screen the page reads, which every later\n// picture restores. And a picture taken during another would restore the other's clip, so they go\n// one at a time.\nconst camera = (\n page: PageContext,\n viewport: Viewport,\n capture: Capture.Controller,\n { holdScreen, scaled }: Pick<ReturnType<typeof device>, \"holdScreen\" | \"scaled\">,\n) => {\n const { playwright, native, within } = page;\n const { send } = page.protocol;\n // Device pixels per CSS pixel, as the page's layout metrics last gave it. A picture taken in one\n // call is checked by its size, so a page whose ratio changes is measured again.\n let ratio = 1;\n\n const layoutMetrics = (operation: string) =>\n native(operation, () => send(\"Page.getLayoutMetrics\")).pipe(\n Effect.flatMap(decodeWith(operation, LayoutMetrics)),\n );\n\n const decoded = (operation: string, data: Uint8Array, format: Format) => {\n const size = format === \"png\" ? pngSize(data) : jpegSize(data);\n\n return size === undefined\n ? failWith(\n operation,\n new Failed({ detail: `the browser's picture is not a ${format.toUpperCase()}` }),\n )\n : Effect.succeed(new Image({ data, mediaType: `image/${format}`, ...size }));\n };\n\n const take = (operation: string, format: Format, run: () => Promise<Uint8Array>) =>\n native(operation, run).pipe(\n untilPainted,\n Effect.flatMap((data) => decoded(operation, data, format)),\n );\n\n const shot = (\n operation: string,\n format: Format,\n quality: number,\n clip?: Size & Point & { readonly scale: number },\n ) =>\n take(operation, format, () =>\n send(\"Page.captureScreenshot\", {\n format,\n ...(format === \"jpeg\" ? { quality } : {}),\n ...(clip === undefined ? {} : { clip }),\n }).then(({ data }) => {\n const decoded = Base64.decode(data);\n\n return Result.isSuccess(decoded)\n ? decoded.success\n : Promise.reject(new Error(\"the browser sent invalid base64 picture data\"));\n }),\n );\n\n // Playwright's promise owns native restoration; the outer Effect alone bounds callers.\n const emulatedShot = (\n operation: string,\n format: Format,\n quality: number,\n scale: Scale,\n crop?: Region,\n ) =>\n take(operation, format, () =>\n playwright.screenshot({\n type: format,\n ...(format === \"jpeg\" ? { quality } : {}),\n scale,\n timeout: 0,\n ...(crop === undefined ? {} : { clip: crop }),\n }),\n );\n\n return (\n operation: string,\n quality: number,\n crop?: Region,\n format: Format = \"jpeg\",\n pixels: Scale = \"css\",\n ) =>\n Effect.gen(function* () {\n const known = viewport.knownViewport();\n let whole: Image | undefined;\n\n // A copy without a clip can come at the viewport's CSS size whatever the device scale\n // factor, so a picture in device pixels always takes a clip.\n if (crop === undefined && ratio === 1 && pixels === \"css\") {\n whole = yield* shot(operation, format, quality);\n if (whole.width === known?.width && whole.height === known.height) return whole;\n }\n // Where Playwright emulates the viewport, on its own session, its own picture restores it.\n const emulated = playwright.viewportSize();\n\n if (emulated !== null) {\n if (whole !== undefined) ratio = whole.width / emulated.width;\n\n return yield* emulatedShot(operation, format, quality, pixels, crop);\n }\n\n const [measured] = yield* layoutMetrics(operation).pipe(\n Effect.zip(crop === undefined ? Effect.void : holdScreen(operation), { concurrent: true }),\n );\n\n const measuredRatio = measured.contentSize.width / measured.cssContentSize.width;\n\n // The layout metrics report the device's own ratio, never the one a paint emulates.\n ratio =\n scaled() > 0\n ? scaled()\n : Number.isFinite(measuredRatio) && measuredRatio > 0\n ? measuredRatio\n : 1;\n if (crop === undefined && ratio === 1) {\n const image = whole ?? (yield* shot(operation, format, quality));\n\n viewport.remember(image);\n\n return image;\n }\n const rect = crop ?? { x: 0, y: 0, ...(known ?? (yield* viewport.viewportFor(operation))) };\n const { pageX, pageY, scale } = measured.cssVisualViewport;\n\n yield* holdScreen(operation);\n\n return yield* shot(operation, format, quality, {\n x: pageX + rect.x,\n y: pageY + rect.y,\n width: Math.floor(rect.width / scale + 1e-3),\n height: Math.floor(rect.height / scale + 1e-3),\n scale: pixels === \"device\" ? scale : scale / ratio,\n });\n }).pipe(capture.excluding, within(operation));\n};\n\n// A duration in milliseconds, or NaN for an input that is no duration.\nconst millisOf = (input: Duration.Input) =>\n Option.match(Duration.fromInput(input), { onNone: () => Number.NaN, onSome: Duration.toMillis });\n\n// The newest screencast frame, if it shows the page as the caller asked: painted at most `maxAge`\n// ago at the earliest its timing allows, after the current document began, and with\n// `after: \"input\"` after the page's latest input, which a read asks in its turn, once the action\n// in flight has ended. It must have the viewport's size, as a new picture would. A screencast sends\n// only changes and can miss a final paint, so a frame is only ever as current as its age, and a\n// page that keeps painting while the next document loads leaves its own frames newest when the\n// navigation returns.\nconst reuse =\n (page: PageContext, bridge: Bridge, viewport: Viewport, capture: Capture.Controller) =>\n (operation: string, options: FrameOptions) =>\n Effect.gen(function* () {\n const maxAge = millisOf(options.maxAge ?? defaultMaxAge);\n\n if (!(maxAge >= 0))\n return yield* refuse(operation, \"maxAge must be a duration of zero or more\");\n const latest = yield* capture.latest;\n const known = viewport.knownViewport();\n const { activity } = page;\n\n return Option.filter(latest, (frame) => {\n const earliest = frame.hostTime - frame.timing.uncertaintyMillis;\n\n return (\n frame.document === bridge.frameTag().document &&\n page.now() - earliest <= maxAge &&\n earliest > activity.documentAt &&\n (options.after !== \"input\" || earliest > activity.inputAt) &&\n frame.width === known?.width &&\n frame.height === known.height\n );\n });\n });\n\n/** Where a picture came from: a frame the screencast had delivered, or a new screenshot. */\nconst sourceOf = (reused: Option.Option<Frame>) => (Option.isSome(reused) ? \"frame\" : \"screenshot\");\n\nexport const make = Effect.fnUntraced(function* (\n page: PageContext,\n bridge: Bridge,\n viewport: Viewport,\n) {\n const { id, clock, settings, mapping, now, span, owned, lane, within } = page;\n const calibrateClock = calibrator(page, bridge);\n\n // A failure from a capture connection is already the capture's own.\n const error = (cause: unknown) =>\n Schema.is(BrowserError)(cause)\n ? cause\n : undispatched(\"screencast\", reasonOf(cause, undefined, page.closedBy()));\n\n // Input and capture share the owner's monotonic clock; caller-provided clocks cannot move it.\n // Registration measures nothing: a page that is busy while it opens, such as a popup running\n // its first script, must still be tracked. The browser's mapping serves every other page, so\n // only a browser with no estimate yet needs this page's renderer to answer.\n const capture = yield* Capture.make({\n id,\n transport: (page.capture === undefined\n ? Effect.succeed(Transport.own(page, bridge))\n : Transport.apart(page, bridge, page.capture, error, yield* Effect.scope)\n ).pipe(Effect.provideService(Port.Current, yield* Port.Current)),\n clock,\n // A capture starts once the page's own session keeps it painting behind other tabs, which a\n // renderer stuck in a script never confirms, and with the browser's clock mapped. Only a\n // browser's first capture waits for a measurement; every frame takes the newest estimate.\n calibrate: page.focused.pipe(within(\"focus\"), Effect.andThen(mapping.current(calibrateClock))),\n latest: mapping.latest,\n // Once the estimate is ten seconds old, the page measures again while its frames flow. A\n // failure there shows in its `Page.calibrateClock` span, and the estimate stays.\n renew: mapping.renew(calibrateClock),\n // Frames are reused only after the current document began, which the page's own session sees\n // only with the Page domain on: a read turns it on, and so does a capture as it starts.\n watch: bridge.currentDocument(\"screencast\"),\n frameHistory: settings.frameHistory,\n viewport: Effect.suspend(() => viewport.viewportFor(\"screencast\")),\n // An uncropped snapshot waits for the restored compositor surface. Its pixels are discarded;\n // a renderer animation frame or viewport size alone cannot prove the compositor caught up.\n restore: () =>\n page.protocol.send(\"Page.captureScreenshot\", {\n format: \"jpeg\",\n quality: 0,\n optimizeForSpeed: true,\n }),\n imageSize: jpegSize,\n error,\n });\n\n const emulated = device(page, bridge);\n const picture = camera(page, viewport, capture, emulated);\n const reusable = reuse(page, bridge, viewport, capture);\n // Pictures in flight are shared, never kept: their callers say how old one may be.\n const screenshots = lane.shared<Image>(\"screenshot\", false);\n const frames = lane.shared<Frame>(\"frame\", false);\n\n // A caller that acts and then looks must see what its action did, so a screenshot waits for the\n // action in flight and reuses only a frame painted after the page's latest input.\n const screenshot = (options: ScreenshotOptions = {}) =>\n screenshots(\n JSON.stringify([\n millisOf(options.maxAge ?? defaultMaxAge),\n options.clip,\n options.quality,\n options.format,\n options.scale,\n ]),\n Effect.gen(function* () {\n // A reused frame is a JPEG of the viewport's CSS size, so a PNG or a device picture is new.\n const reused =\n options.clip === undefined && options.format !== \"png\" && options.scale !== \"device\"\n ? yield* reusable(\"screenshot\", { maxAge: options.maxAge, after: \"input\" })\n : Option.none<Frame>();\n\n const image = Option.isSome(reused)\n ? reused.value.image\n : yield* picture(\n \"screenshot\",\n options.quality ?? 80,\n options.clip,\n options.format,\n options.scale,\n );\n\n yield* Effect.annotateCurrentSpan({ source: sourceOf(reused), bytes: image.data.length });\n\n return image;\n }),\n ).pipe(span(\"Page.screenshot\"), owned);\n\n // A new screenshot has no paint time, only the host interval in which it was taken.\n const taken = (options: FrameOptions) =>\n Effect.gen(function* () {\n const reused = yield* reusable(\"frame\", options);\n\n yield* Effect.annotateCurrentSpan(\"source\", sourceOf(reused));\n if (Option.isSome(reused)) return reused.value;\n const startedAt = now();\n const image = yield* picture(\"frame\", 80);\n const finishedAt = now();\n\n return new Frame({\n page: id,\n data: image.data,\n timing: new Screenshot({\n hostTime: startedAt + (finishedAt - startedAt) / 2,\n uncertaintyMillis: (finishedAt - startedAt) / 2,\n }),\n receivedAt: finishedAt,\n width: image.width,\n height: image.height,\n ...bridge.frameTag(),\n });\n });\n\n // A frame of a stated age that the screencast has costs nothing and waits for no action; one\n // that must follow the latest input, or a new screenshot, waits for the action in flight.\n const frame = (options: FrameOptions = {}) =>\n (options.after === \"input\"\n ? Effect.succeed(Option.none<Frame>())\n : reusable(\"frame\", options)\n ).pipe(\n Effect.flatMap(\n Option.match({\n onSome: (reused) => Effect.as(Effect.annotateCurrentSpan(\"source\", \"frame\"), reused),\n onNone: () =>\n frames(\n JSON.stringify([millisOf(options.maxAge ?? defaultMaxAge), options.after]),\n taken(options),\n ),\n }),\n ),\n span(\"Page.frame\"),\n owned,\n );\n\n const zoom = (requested: Region, options: Pick<ScreenshotOptions, \"scale\"> = {}) =>\n lane\n .read(\"zoom\")(\n Effect.gen(function* () {\n const region = yield* Schema.decodeEffect(Region)(requested).pipe(\n Effect.mapError((error) =>\n undispatched(\"zoom\", new InvalidRequest({ detail: error.message })),\n ),\n );\n\n // The viewport's latest known size, as the pictures the region was chosen from had it.\n const size = viewport.knownViewport() ?? (yield* viewport.viewportFor(\"zoom\"));\n\n if (region.x + region.width > size.width || region.y + region.height > size.height)\n return yield* refuse(\"zoom\", \"the crop must fit entirely within the viewport\");\n const image = yield* picture(\"zoom\", 80, region, \"jpeg\", options.scale);\n\n return new Zoom({ page: id, region, image });\n }).pipe(within(\"zoom\")),\n )\n .pipe(span(\"Page.zoom\"), owned);\n\n const captureStats = (options: { readonly window?: Duration.Input | undefined } = {}) => {\n if (options.window === undefined) return capture.stats();\n const millis = millisOf(options.window);\n\n return millis > 0 && millis <= Duration.toMillis(countsKept)\n ? capture.stats(millis)\n : refuse(\"captureStats\", \"window must be over zero and at most a minute\");\n };\n\n // The browser's clock mapping, measured on this page only while the browser has none, as the\n // change record's times need it.\n const estimate = mapping.current(calibrateClock);\n\n return { capture, screenshot, frame, zoom, captureStats, estimate, paint: emulated.paint };\n});\n","/**\n * Reading where things are: `Page.layout`, in one call to the page that takes its turn as other\n * reads do and shares its work with identical ones. The page gives each place's viewport box; the\n * document box is that box moved by the scroll read with it.\n */\nimport { Effect, Schema } from \"effect\";\n\nimport { NotActionable } from \"../../BrowserError.ts\";\nimport { Box, Subject } from \"../../BrowserEvent.ts\";\nimport { Point } from \"../../Geometry.ts\";\nimport { Layout, type Picks, Place, Word } from \"../../Layout.ts\";\nimport { pickRequests } from \"../../Matching.ts\";\nimport * as Url from \"../../Url.ts\";\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport { contextGone, decodeWith, failWith, type PageContext, refuse } from \"../page/context.ts\";\n\n// What `layout` reads back, before its document boxes are added.\nconst LayoutResult = Schema.Union([\n Schema.Struct({\n layout: Schema.Struct({\n url: Schema.String,\n viewport: Schema.Struct({ width: Schema.Finite, height: Schema.Finite }),\n scroll: Point,\n scale: Schema.Finite,\n missing: Schema.Array(Schema.String),\n places: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n ref: Schema.String,\n subject: Subject,\n box: Box,\n fixed: Schema.Boolean,\n words: Schema.optional(Schema.Array(Schema.Struct({ text: Schema.String, box: Box }))),\n }),\n ),\n }),\n }),\n Schema.Struct({ invalid: Schema.String }),\n]);\n\nexport const make = (page: PageContext, bridge: Bridge) => {\n const { now, span, owned, within, lane } = page;\n const { evaluate } = bridge;\n const layouts = lane.shared<Layout>(\"layout\", true);\n\n const layout = (picks: Picks) => {\n const asked = pickRequests(picks);\n\n // The boxes and the scroll describe the document the call ran in, which is the one current\n // before and after it; a document that replaced it meanwhile is read again, once.\n const once = Effect.gen(function* () {\n const before = bridge.frameTag().document;\n\n const result = yield* evaluate(\"layout\", scriptCall(\"layout\", asked)).pipe(\n Effect.flatMap(decodeWith(\"layout\", LayoutResult)),\n );\n\n if (\"invalid\" in result) return yield* refuse(\"layout\", result.invalid);\n if (bridge.frameTag().document !== before)\n return yield* failWith(\n \"layout\",\n new NotActionable({ detail: \"the page's document changed while it was read\" }),\n );\n const { places, scroll, ...read } = result.layout;\n const moved = (box: Box) => ({ ...box, x: box.x + scroll.x, y: box.y + scroll.y });\n\n return new Layout({\n ...read,\n url: Url.redact(read.url),\n page: page.id,\n connection: page.connection,\n document: before,\n at: now(),\n scroll,\n places: places.map(\n ({ words, ...place }) =>\n new Place({\n ...place,\n page: moved(place.box),\n words: words?.map((word) => new Word({ ...word, page: moved(word.box) })),\n }),\n ),\n });\n });\n\n return layouts(\n JSON.stringify(asked),\n once.pipe(\n Effect.retry({\n times: 1,\n while: (error) =>\n contextGone(error) ||\n (error.reason._tag === \"NotActionable\" && error.operation === \"layout\"),\n }),\n within(\"layout\"),\n ),\n ).pipe(span(\"Page.layout\", { picks: asked.length }), owned);\n };\n\n return layout;\n};\n","/**\n * Reading a page: its outline with refs, the elements a query finds and the text it shows. Each\n * read takes its turn on the page and shares its work with identical reads, as `lane.ts`\n * describes. The viewport's text as it was last read is kept, for `Page.state`.\n */\nimport { Duration, Effect, Schedule, Schema } from \"effect\";\n\nimport { StaleRef } from \"../../BrowserError.ts\";\nimport { request as askedOf, type FindRequest } from \"../../Matching.ts\";\nimport { type FindQuery, Found, Text, type TextOptions } from \"../../Page.ts\";\nimport { Snapshot, type SnapshotOptions } from \"../../Snapshot.ts\";\nimport * as Url from \"../../Url.ts\";\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport { contextGone, decodeWith, failWith, type PageContext, refuse } from \"../page/context.ts\";\nimport type { Want } from \"./expect.inpage.ts\";\nimport type { SnapshotRequest } from \"./outline.inpage.ts\";\nimport type { TextRequest } from \"./text.inpage.ts\";\n\n/** The outline as a `Snapshot` reads it, or why `within` is not a selector. */\nconst SnapshotResultSchema = Schema.Union([\n Schema.Struct({ snapshot: Snapshot }),\n Schema.Struct({ invalid: Schema.String }),\n]);\n\nexport type SnapshotResult = typeof SnapshotResultSchema.Encoded;\n\n/** What `text` sends back, or null when its ref no longer names an element. */\nconst TextResultSchema = Schema.NullOr(\n Schema.Struct({\n text: Schema.String,\n truncated: Schema.Boolean,\n url: Schema.String,\n title: Schema.String,\n }),\n);\n\nexport type TextResult = typeof TextResultSchema.Type;\n\n// What `find` reads back. The bridge envelope owns ref allocation across documents.\nconst FindResults = Schema.Union([\n Schema.Struct({ found: Schema.Array(Found) }),\n Schema.Struct({ invalid: Schema.String }),\n]);\n\nconst UntilResult = Schema.Union([\n Schema.Struct({ met: Schema.Boolean, mark: Schema.String }),\n Schema.Struct({ invalid: Schema.String }),\n]);\n\nexport const make = (page: PageContext, bridge: Bridge) =>\n Effect.sync(() => {\n const { now, span, owned, within, lane } = page;\n const { evaluate } = bridge;\n const snapshots = lane.shared<Snapshot>(\"snapshot\", true);\n const finds = lane.shared<ReadonlyArray<Found>>(\"find\", true);\n const texts = lane.shared<Text>(\"text\", true);\n let viewed: Text | undefined;\n\n const snapshot = (snapshotOptions: SnapshotOptions = {}) => {\n const asked = {\n full: snapshotOptions.full ?? false,\n query: snapshotOptions.query ?? null,\n within: snapshotOptions.within ?? null,\n maxChars: snapshotOptions.maxChars ?? 12_000,\n boxes: snapshotOptions.boxes ?? false,\n };\n\n return snapshots(\n JSON.stringify(asked),\n Effect.gen(function* () {\n const request: SnapshotRequest = asked;\n\n const result = yield* evaluate(\"snapshot\", scriptCall(\"snapshot\", request)).pipe(\n Effect.flatMap(decodeWith(\"snapshot\", SnapshotResultSchema)),\n );\n\n if (\"invalid\" in result) return yield* refuse(\"snapshot\", result.invalid);\n const { text, truncated, url } = result.snapshot;\n\n yield* Effect.annotateCurrentSpan({ chars: text.length, truncated });\n\n return new Snapshot({ ...result.snapshot, url: Url.redact(url) });\n }).pipe(within(\"snapshot\")),\n ).pipe(span(\"Page.snapshot\", { full: asked.full }), owned);\n };\n\n const find = (query: FindQuery = {}) => {\n const asked = askedOf(query, \"viewport\");\n\n return finds(\n JSON.stringify(asked),\n Effect.gen(function* () {\n const request: FindRequest = asked;\n\n const result = yield* evaluate(\"find\", scriptCall(\"find\", request)).pipe(\n Effect.flatMap(decodeWith(\"find\", FindResults)),\n );\n\n if (\"invalid\" in result) return yield* refuse(\"find\", result.invalid);\n\n yield* Effect.annotateCurrentSpan({ found: result.found.length });\n\n return result.found;\n }).pipe(within(\"find\")),\n ).pipe(\n // The query's words are the caller's, and may be anything; only its shape is traced.\n span(\"Page.find\", { scope: asked.scope, role: asked.role ?? \"\" }),\n owned,\n );\n };\n\n const text = (options: TextOptions = {}) => {\n const scope = options.scope ?? \"viewport\";\n\n const request: TextRequest = {\n ref: scope === \"viewport\" ? null : scope,\n maxChars: options.maxChars ?? 12_000,\n unmask: options.unmask ?? false,\n };\n\n return (\n scope !== \"viewport\" && !/^e\\d+$/.test(scope)\n ? refuse(\"text\", `${scope} is neither \"viewport\" nor a ref such as e12`)\n : texts(\n JSON.stringify(request),\n Effect.gen(function* () {\n const result = yield* evaluate(\"text\", scriptCall(\"text\", request)).pipe(\n Effect.flatMap(decodeWith(\"text\", TextResultSchema)),\n );\n\n if (result === null) return yield* failWith(\"text\", new StaleRef({ ref: scope }));\n yield* Effect.annotateCurrentSpan({\n chars: result.text.length,\n truncated: result.truncated,\n });\n const shown = new Text({ ...result, url: Url.redact(result.url), at: now() });\n\n if (request.ref === null) viewed = shown;\n\n return shown;\n }).pipe(within(\"text\")),\n )\n ).pipe(span(\"Page.text\", { scope: scope === \"viewport\" ? \"viewport\" : \"ref\" }), owned);\n };\n\n // One call, which the page answers once `want` holds of what `query` matches, the whole document\n // unless it says otherwise, or at the deadline, with the mark of what matched then. It follows\n // the action in flight, and the page has the action timeout past the deadline\n // to answer.\n const until = (query: FindQuery, want: Want, millis: number) => {\n if (!Number.isFinite(millis) || millis < 0)\n return refuse(\"until\", \"the wait duration must be finite and nonnegative\");\n\n const look = Effect.gen(function* () {\n const deadline = now() + millis;\n const request: FindRequest = askedOf(query, \"document\");\n\n return yield* Effect.suspend(() =>\n evaluate(\"expect\", scriptCall(\"until\", request, want, Math.max(0, deadline - now()))),\n ).pipe(\n Effect.flatMap(decodeWith(\"expect\", UntilResult)),\n Effect.filterOrElse(\n (result) => \"met\" in result,\n (result) => refuse(\"expect\", result.invalid),\n ),\n Effect.retry({\n while: (error) => contextGone(error) && now() < deadline,\n schedule: Schedule.spaced(\"10 millis\"),\n }),\n // No stable document answered by this deadline. An unmet verdict carries no sampled\n // mark; a zero-window baseline still fails rather than inventing comparison evidence.\n Effect.catchIf(\n (error) => millis > 0 && contextGone(error) && now() >= deadline,\n () => Effect.succeed({ met: false, mark: \"\" }),\n ),\n );\n });\n\n return lane\n .read(\"expect\")(Effect.void)\n .pipe(\n Effect.andThen(look),\n within(\"expect\", Duration.sum(Duration.millis(millis), page.settings.actionTimeout)),\n span(\"Page.expect\", { want: typeof want === \"string\" ? want : \"other\" }),\n owned,\n );\n };\n\n /** The viewport's text as it was last read, if after `since`, as a document began. */\n const viewedSince = (since: number) =>\n viewed !== undefined && viewed.at > since ? viewed : undefined;\n\n return { snapshot, find, text, until, viewedSince };\n });\n\nexport type Reading = Effect.Success<ReturnType<typeof make>>;\n","/** Document readiness and content quiet, independent of screen-capture features. */\nimport { Duration, Effect, Schedule, Schema } from \"effect\";\n\nimport { Timeout, failWith, refuse } from \"../../BrowserError.ts\";\nimport type { ReadyOptions } from \"../../Page.ts\";\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport { contextGone, decodeWith, type PageContext } from \"../page/context.ts\";\n\n/** What the page is still waiting for; none when it is ready. */\nconst ReadinessSchema = Schema.Array(\n Schema.Literals([\n \"load\",\n \"paint\",\n \"animations\",\n \"images\",\n \"fonts\",\n \"busy\",\n \"content\",\n \"changing\",\n ]),\n);\n\nexport type Readiness = typeof ReadinessSchema.Type;\n\nexport const make =\n (page: PageContext, bridge: Bridge) =>\n (options: ReadyOptions = {}) => {\n const quietMillis = options.quietMillis ?? 0;\n\n if (!Number.isFinite(quietMillis) || quietMillis < 0)\n return refuse(\"ready\", \"quietMillis must be finite and nonnegative\");\n const timeout = options.timeout ?? Duration.seconds(15);\n\n // The page's own evidence, checked in the page until nothing is left or `until` has come.\n const settled = (until: number) =>\n Effect.suspend(() =>\n bridge.evaluate(\n \"ready\",\n scriptCall(\n \"ready\",\n Math.max(0, Math.round(until - page.now())),\n quietMillis,\n page.settings.pageTime ?? null,\n ),\n ),\n ).pipe(\n Effect.retry({ while: contextGone, schedule: Schedule.spaced(Duration.millis(10)) }),\n Effect.flatMap(decodeWith(\"ready\", ReadinessSchema)),\n Effect.tap((waiting) => Effect.annotateCurrentSpan({ waiting: waiting.join(\",\") })),\n Effect.filterOrElse(\n (waiting) => waiting.length === 0,\n () => failWith(\"ready\", new Timeout({ millis: Duration.toMillis(timeout) })),\n ),\n );\n\n return page.lane\n .read(\"ready\")(Effect.void)\n .pipe(\n Effect.andThen(\n Effect.suspend(() => settled(page.now() + Duration.toMillis(timeout))).pipe(\n page.within(\"ready\", timeout),\n ),\n ),\n page.span(\"Page.ready\"),\n page.owned,\n );\n };\n","/**\n * Reading a page's record of what changed. The first read also registers the recorder with the\n * page's own session so that every later document records from its start, until the idle lifetime\n * expires. The page's times map to the owner's clock through the browser's one\n * clock mapping, as frames' do, which a browser's first read measures, once, where no capture has;\n * and a window can begin on the page's own clock where the previous one ended, so consecutive\n * reads neither miss nor repeat a change. A read takes its turn on the page as other reads do, and\n * identical ones in flight share it; none is kept for a later caller, since its window ends when\n * it was read.\n */\nimport { Clock, Duration, Effect, type Fiber, Schema, Semaphore } from \"effect\";\n\nimport type { BrowserError } from \"../../BrowserError.ts\";\nimport { Change, Changes } from \"../../Change.ts\";\nimport * as BrowserClock from \"../../Clock.ts\";\nimport type { Frame } from \"../../Frame.ts\";\nimport type { ChangesOptions } from \"../../Page.ts\";\nimport { type Bridge, scriptCall } from \"../page/bridge.ts\";\nimport { decodeWith, type PageContext } from \"../page/context.ts\";\nimport type { ChangesRequest } from \"./changes.inpage.ts\";\n\n/**\n * What a read sends back: its window and the record's state, and each change as `Change` encodes\n * it, all on the page's clock.\n */\nconst ChangesResultSchema = Schema.Struct({\n until: Schema.Finite,\n from: Schema.Finite,\n dropped: Schema.Int,\n records: Schema.Array(Change),\n});\n\nexport type ChangesResult = typeof ChangesResultSchema.Encoded;\n\nconst isChanges = Schema.is(Changes);\n\n// Where a window starts or ends as its caller gave it, which tells identical reads apart.\nconst markOf = (time: Changes | Frame | number | undefined) =>\n time === undefined || typeof time === \"number\"\n ? time\n : isChanges(time)\n ? `cursor ${time.cursor}`\n : `frame ${time.timestamp ?? time.hostTime}`;\n\nexport const make = (\n page: PageContext,\n bridge: Bridge,\n estimate: Effect.Effect<BrowserClock.Estimate, BrowserError>,\n) => {\n const reads = page.lane.shared<Changes>(\"changes\", false);\n const recording = Semaphore.makeUnsafe(1);\n const idleMillis = 120_000;\n let readAt = Number.NEGATIVE_INFINITY;\n let lifetime: Fiber.Fiber<void, BrowserError> | undefined;\n let expired: BrowserError | undefined;\n\n const expiry: Effect.Effect<void, BrowserError> = Effect.suspend(() => {\n const left = readAt + idleMillis - page.now();\n\n if (left > 0) return Effect.sleep(Duration.millis(left)).pipe(Effect.andThen(expiry));\n\n return recording\n .withPermits(1)(\n Effect.suspend(() => {\n if (page.now() < readAt + idleMillis) return Effect.void;\n\n return bridge.unregisterRecorder(\"changes\").pipe(\n page.within(\"changes\"),\n Effect.ensuring(\n Effect.sync(() => {\n lifetime = undefined;\n }),\n ),\n );\n }),\n )\n .pipe(\n // Idle cleanup can wait for the page; its native work is bounded once admitted.\n page.lane.read(\"changes\", Duration.infinity),\n Effect.andThen(Effect.suspend(() => (lifetime === undefined ? Effect.void : expiry))),\n );\n });\n\n const register = recording.withPermits(1)(\n Effect.gen(function* () {\n if (expired !== undefined) return yield* expired;\n readAt = page.now();\n yield* bridge.registerRecorder(\"changes\");\n lifetime ??= yield* expiry.pipe(\n Effect.tapError((error) =>\n Effect.sync(() => {\n expired = error;\n }),\n ),\n Effect.provideService(Clock.Clock, page.clock),\n Effect.forkIn(page.scope),\n );\n }),\n );\n\n return (options: ChangesOptions = {}) =>\n reads(\n JSON.stringify([markOf(options.since), markOf(options.until), options.unmask ?? false]),\n Effect.gen(function* () {\n const mapping = yield* estimate;\n const host = (epoch: number) => BrowserClock.toHostTime(mapping, epoch);\n\n // A frame's paint is on the page's clock already; a screenshot has only its host time.\n const onPage = (time: Frame | number) =>\n typeof time === \"number\"\n ? time + mapping.offsetMillis\n : (time.timestamp ?? time.hostTime + mapping.offsetMillis);\n\n const request: ChangesRequest = {\n since:\n options.since === undefined\n ? null\n : isChanges(options.since)\n ? options.since.cursor\n : onPage(options.since),\n until: options.until === undefined ? null : onPage(options.until),\n unmask: options.unmask ?? false,\n };\n\n const [, result] = yield* Effect.all(\n [\n register,\n bridge\n .evaluate(\"changes\", scriptCall(\"changes\", request))\n .pipe(Effect.flatMap(decodeWith(\"changes\", ChangesResultSchema))),\n ],\n { concurrency: \"unbounded\" },\n );\n\n yield* Effect.annotateCurrentSpan({\n changes: result.records.length,\n dropped: result.dropped,\n });\n\n const later = (epoch: number | undefined) =>\n epoch === undefined ? undefined : host(epoch);\n\n return new Changes({\n document: bridge.frameTag().document,\n from: host(result.from),\n until: host(result.until),\n cursor: result.until,\n dropped: result.dropped,\n changes: result.records.map(\n (one) =>\n new Change({\n ...one,\n startedAt: host(one.startedAt),\n at: host(one.at),\n earlier: later(one.earlier),\n cause: later(one.cause),\n }),\n ),\n });\n }).pipe(page.within(\"changes\")),\n ).pipe(page.span(\"Page.changes\"), page.owned);\n};\n","/**\n * A page's window over its three tracks on the browser's host clock: the events and frames it\n * keeps, at no call, and one read of its changes, the first starting its record. A read that fails\n * is missing, with why, and the window is still made.\n */\nimport { Duration, Effect, Option, Result, Schema } from \"effect\";\n\nimport type { BrowserError } from \"../../BrowserError.ts\";\nimport { type BrowserEvent, TrackEvent } from \"../../BrowserEvent.ts\";\nimport type { Changes } from \"../../Change.ts\";\nimport { Frame } from \"../../Frame.ts\";\nimport type { ChangesOptions, WindowOptions } from \"../../Page.ts\";\nimport { Window } from \"../../Window.ts\";\nimport { type PageContext, refuse } from \"../page/context.ts\";\n\nconst isWindow = Schema.is(Window);\n\nconst isFrame = Schema.is(Frame);\nconst isTrackEvent = Schema.is(TrackEvent);\n\n/**\n * Where a window asked at `now` starts and ends: never after now, nor starting after it ends.\n * Nothing for a bound that is not finite, or a negative reach back.\n */\nexport const boundsOf = ({ since, until }: Pick<WindowOptions, \"since\" | \"until\">, now: number) => {\n const end = until === undefined ? now : isFrame(until) ? until.hostTime : Math.min(until, now);\n\n const start = isWindow(since)\n ? since.until\n : isFrame(since)\n ? since.hostTime\n : !Duration.isDuration(since)\n ? since\n : Duration.isNegative(since)\n ? Number.NaN\n : end - Duration.toMillis(since);\n\n return Number.isFinite(start) && Number.isFinite(end)\n ? Option.some({ since: Math.min(start, end), until: end })\n : Option.none();\n};\n\n/**\n * A window's share of the kept tracks: events after its start, frames painted from it, both up to\n * its end, so consecutive windows hold each event once and the next begins with the frame the last\n * ended on. Pointer, key and wheel input is the presentation track, not an event here.\n */\nexport const within = (\n { since, until }: { readonly since: number; readonly until: number },\n events: ReadonlyArray<BrowserEvent>,\n frames: ReadonlyArray<Frame>,\n) => ({\n events: events.filter((event) => event.at > since && event.at <= until && !isTrackEvent(event)),\n frames: frames.filter((frame) => frame.hostTime >= since && frame.hostTime <= until),\n});\n\nexport const make =\n (\n page: PageContext,\n read: (options: ChangesOptions) => Effect.Effect<Changes, BrowserError>,\n frames: Effect.Effect<ReadonlyArray<Frame>>,\n ) =>\n ({ since, until, unmask }: WindowOptions) =>\n Effect.gen(function* () {\n const asked = boundsOf({ since, until }, page.now());\n\n if (Option.isNone(asked))\n return yield* refuse(\"window\", \"a window's bounds must be finite, its reach not negative\");\n const bounds = asked.value;\n\n // A previous window's changes go on exactly where they ended, on the page's own clock, and a\n // frame bounds them at its paint, so that they hold nothing it does not show.\n const changes = yield* Effect.result(\n read({\n since: isWindow(since)\n ? (since.changes ?? bounds.since)\n : isFrame(since)\n ? since\n : bounds.since,\n until: isFrame(until) ? until : bounds.until,\n unmask,\n }),\n );\n\n return new Window({\n page: page.id,\n ...bounds,\n ...within(bounds, yield* page.recentEvents, yield* frames),\n changes: Result.getOrUndefined(changes),\n missing: Option.toArray(Result.getFailure(changes)),\n });\n }).pipe(page.span(\"Page.window\"), page.owned);\n","/**\n * Moving a page between documents: going to an address, back through its history, or reloading.\n * Each move is an action, so it takes the page's turn, goes through the input guard and is\n * recorded, but it sends no input.\n */\nimport { Deferred, Duration, Effect, Schedule } from \"effect\";\n\nimport { type Action, nameOf } from \"../../Action.ts\";\nimport { BrowserError, NavigationFailed, NotActionable, NotFound } from \"../../BrowserError.ts\";\nimport * as Url from \"../../Url.ts\";\nimport type { Guard } from \"../input/guard.ts\";\nimport type { InputMarks, Perform } from \"../input/perform.ts\";\nimport { failWith, type PageContext, refuse } from \"./context.ts\";\nimport { Current } from \"./replies.ts\";\n\nexport const make = (\n page: PageContext,\n perform: Perform,\n preparePolicy: Guard[\"preparePolicy\"],\n) => {\n const { playwright, settings, native } = page;\n const { send } = page.protocol;\n\n // `address` is where `run` goes, as the action, the guard and a failure report it.\n const navigation = (value: Action, run: () => Promise<unknown>, address: string) => {\n const name = nameOf(value);\n const url = Url.redact(address);\n\n return perform(\n value,\n { target: url },\n settings.navigationTimeout,\n (action) => preparePolicy(action, { target: url }, [], { destination: url }),\n (marks) =>\n marks.sent.pipe(\n Effect.andThen(native(name, run).pipe(Effect.onError(() => page.stopLoading))),\n Effect.mapError((error) =>\n error.reason._tag === \"Failed\" &&\n /net::|NS_ERROR|Cannot navigate/i.test(error.reason.detail)\n ? new BrowserError({\n operation: name,\n reason: new NavigationFailed({ url, detail: error.reason.detail }),\n dispatched: true,\n })\n : error,\n ),\n Effect.asVoid,\n ),\n );\n };\n\n const history = native(\"back\", () => send(\"Page.getNavigationHistory\"));\n\n // While a traversal swaps documents, Chromium can briefly route this session to the outgoing\n // document, which has become inactive (for instance after it entered the back-forward cache),\n // so a read during the traversal is retried until the session reaches the active document.\n const traversingHistory = history.pipe(\n Effect.retry({\n schedule: Schedule.spaced(Duration.millis(50)),\n while: (error) =>\n error.reason._tag === \"Failed\" &&\n /not attached to an active page/i.test(error.reason.detail),\n }),\n );\n\n // The current entry's title is the one the page last set, and empty where it set none, so no\n // address stands in for it. The browser answers it, whatever the page's script is doing.\n const title = native(\"title\", () => send(\"Page.getNavigationHistory\")).pipe(\n Effect.map(({ entries, currentIndex }) => entries[currentIndex]?.title ?? \"\"),\n );\n\n const noPrevious = failWith(\"back\", new NotFound({ target: \"a previous page in this tab\" }));\n\n const prepareBack = (action: Action) =>\n Effect.gen(function* () {\n const before = yield* history;\n const current = before.entries[before.currentIndex];\n const previous = before.entries[before.currentIndex - 1];\n\n if (previous === undefined) return yield* noPrevious;\n const plan = yield* preparePolicy(action, {}, [], { destination: Url.redact(previous.url) });\n\n return {\n request: plan.request,\n validate: Effect.gen(function* () {\n const approval = yield* plan.validate;\n const latest = yield* history;\n\n if (\n latest.currentIndex !== before.currentIndex ||\n latest.entries[latest.currentIndex]?.id !== current?.id ||\n latest.entries[latest.currentIndex - 1]?.id !== previous.id ||\n latest.entries[latest.currentIndex - 1]?.url !== previous.url\n )\n return yield* failWith(\n \"back\",\n new NotActionable({\n detail: \"the navigation history changed while input policy was pending\",\n }),\n );\n\n return approval;\n }),\n };\n });\n\n // One protocol traversal on every path. It has committed once the tab leaves its entry, which\n // also covers entries that only an iframe created, where the main frame never navigates, and\n // entries sharing a URL. A frame navigation then shows Playwright has caught up before the\n // main document's readiness is read.\n const goBack = (marks: InputMarks) =>\n Effect.gen(function* () {\n const before = yield* history;\n const current = before.entries[before.currentIndex];\n const previous = before.entries[before.currentIndex - 1];\n\n if (current === undefined || previous === undefined) return yield* noPrevious;\n const navigated = yield* Deferred.make<void>();\n\n const onNavigation = () => {\n Deferred.doneUnsafe(navigated, Effect.void);\n };\n\n yield* Effect.acquireUseRelease(\n Effect.sync(() => playwright.on(\"framenavigated\", onNavigation)),\n () =>\n marks.sent.pipe(\n Effect.andThen(\n Effect.gen(function* () {\n yield* native(\"back\", () =>\n send(\"Page.navigateToHistoryEntry\", { entryId: previous.id }),\n );\n yield* traversingHistory.pipe(\n Effect.repeat({\n schedule: Schedule.spaced(Duration.millis(50)),\n until: (latest) => latest.entries[latest.currentIndex]?.id !== current.id,\n }),\n );\n yield* Deferred.await(navigated);\n yield* native(\"back\", () =>\n playwright.waitForLoadState(\"domcontentloaded\", { timeout: 0 }),\n ).pipe(Effect.provideService(Current, undefined));\n }).pipe(Effect.onError(() => page.stopLoading)),\n ),\n ),\n () => Effect.sync(() => playwright.off(\"framenavigated\", onNavigation)),\n );\n });\n\n const goto = (url: string) => {\n const parsed = Url.parse(url);\n\n if (\n parsed === null ||\n ![\"http:\", \"https:\", \"about:\", \"data:\", \"file:\"].includes(parsed.protocol)\n )\n return refuse(\"navigate\", `\"${Url.redact(url)}\" is not a URL`);\n\n const run = () => playwright.goto(parsed.href, { waitUntil: \"domcontentloaded\", timeout: 0 });\n\n return navigation(\n { _tag: \"Goto\", url },\n () =>\n page.nativePort === undefined\n ? run()\n : page.nativePort(page.id, \"goto\", { url: parsed.href }, run),\n parsed.href,\n );\n };\n\n const back = perform(\n { _tag: \"Back\" },\n { target: \"back\" },\n settings.navigationTimeout,\n prepareBack,\n goBack,\n );\n\n const reload = Effect.suspend(() =>\n navigation(\n { _tag: \"Reload\" },\n () => playwright.reload({ waitUntil: \"domcontentloaded\", timeout: 0 }),\n playwright.url(),\n ),\n );\n\n return { goto, back, reload, title };\n};\n","/**\n * The page's overlay: one lease at a time, each drawing one call to the page, in turn after the\n * actions asked before it, never two at once. Each new document gets what was last drawn once it\n * has loaded; the lease's scope takes the layer away.\n */\nimport { Duration, Effect, Schedule, Schema, type Scope, Semaphore } from \"effect\";\n\nimport type { BrowserError } from \"../../BrowserError.ts\";\nimport { Box } from \"../../BrowserEvent.ts\";\nimport type { Content, Overlay } from \"../../Overlay.ts\";\nimport { type Bridge, scriptCall } from \"./bridge.ts\";\nimport { decodeWith, type PageContext, refuse } from \"./context.ts\";\n\nconst Drawn = Schema.Array(Box);\n\nexport const make = (page: PageContext, bridge: Bridge) => {\n const { lane, owned, span, within } = page;\n const turns = Semaphore.makeUnsafe(1);\n let open = false;\n // What the layer shows, as markup, and where its parts were last drawn.\n let shown: string | null = null;\n let drawn: ReadonlyArray<Box> = [];\n\n // What a call to the page drew, wherever it was drawn from.\n const record = (markup: string | null, boxes: ReadonlyArray<Box>) => {\n shown = markup;\n drawn = boxes;\n page.noteInput();\n };\n\n const send = (markup: string | null) =>\n turns.withPermit(\n lane.read(\"overlay\")(\n bridge.evaluate(\"overlay\", scriptCall(\"overlay\", markup)).pipe(\n Effect.flatMap(decodeWith(\"overlay\", Drawn)),\n Effect.tap((boxes) => Effect.sync(() => record(markup, boxes))),\n within(\"overlay\"),\n ),\n ),\n );\n\n const draw = (content: Content) =>\n send(content._tag === \"Svg\" ? content.markup : null).pipe(span(\"Overlay.draw\"), owned);\n\n // Once the document after `document` has parsed, it is drawn with what was shown. A redraw that\n // fails leaves the layer off until the next draw, which reports its own failure.\n const redraw = (document: number) =>\n bridge.waitForDocument(document).pipe(\n Effect.andThen(\n Effect.void.pipe(\n Effect.repeat({\n schedule: Schedule.spaced(Duration.millis(50)),\n until: () => bridge.loaded() !== undefined,\n }),\n within(\"overlay\", page.settings.navigationTimeout),\n ),\n ),\n Effect.andThen(Effect.suspend(() => (shown === null ? Effect.void : send(shown)))),\n Effect.ignore,\n );\n\n const lease: Effect.Effect<Overlay, BrowserError, Scope.Scope> = Effect.gen(function* () {\n if (open) return yield* refuse(\"overlay\", \"the page has an overlay already\");\n open = true;\n yield* Effect.addFinalizer(() =>\n Effect.suspend(() => {\n open = false;\n\n return shown === null ? Effect.void : send(null).pipe(Effect.ignore);\n }),\n );\n yield* Effect.forkScoped(\n Effect.suspend(() => redraw(bridge.frameTag().document)).pipe(Effect.forever),\n );\n\n return { draw };\n });\n\n return {\n lease,\n drawn: () => (shown === null ? undefined : drawn),\n open: () => open,\n record,\n /** Run a call that draws in the overlay's turn, so no other drawing overtakes it. */\n turn: <A, E, R>(effect: Effect.Effect<A, E, R>) => turns.withPermit(effect),\n };\n};\n\nexport type Overlays = ReturnType<typeof make>;\n","/**\n * The page's poses: one lease at a time, each `set` one call to the page in the page's turn, as an\n * action takes it, so no action resolves a target that a pose then moves. The lease's scope takes\n * every pose off. See `Pose`.\n */\nimport { Effect, Schema, type Scope } from \"effect\";\n\nimport { type BrowserError, StaleRef } from \"../../BrowserError.ts\";\nimport { Pose, type Poses } from \"../../Pose.ts\";\nimport { type Bridge, scriptCall } from \"./bridge.ts\";\nimport { decodeWith, failWith, type PageContext, refuse } from \"./context.ts\";\nimport { poseRequest } from \"./pose.inpage.ts\";\n\n/** What posing answered: nothing, or the ref it could not pose and why. */\nexport const Posed = Schema.Struct({\n stale: Schema.optional(Schema.String),\n invalid: Schema.optional(Schema.String),\n});\n\nexport const make = (page: PageContext, bridge: Bridge) => {\n const { lane, owned, span, within } = page;\n let open = false;\n\n /** The page's requests for `poses`, each part left out made the one that changes nothing. */\n const requests = Effect.fnUntraced(function* (operation: string, poses: ReadonlyArray<Pose>) {\n const decoded = yield* Schema.decodeEffect(Schema.Array(Pose))(poses).pipe(\n Effect.catch(() => refuse(operation, \"each pose is a ref and finite numbers\")),\n );\n\n if (decoded.length > 256)\n return yield* refuse(operation, \"at most 256 elements are posed at once\");\n\n return decoded.map(poseRequest);\n });\n\n /** Fail as the page's answer says, if it posed nothing. */\n const answered = (operation: string, posed: typeof Posed.Type) =>\n posed.stale !== undefined\n ? failWith(operation, new StaleRef({ ref: posed.stale }))\n : posed.invalid !== undefined\n ? refuse(operation, posed.invalid)\n : Effect.void;\n\n const send = (operation: string, script: string) =>\n lane.write(\n operation,\n page.settings.actionTimeout,\n )(\n bridge.evaluate(operation, script).pipe(\n Effect.flatMap(decodeWith(operation, Posed)),\n Effect.flatMap((posed) => answered(operation, posed)),\n Effect.tap(() => Effect.sync(page.noteInput)),\n within(operation),\n ),\n );\n\n const set = (poses: ReadonlyArray<Pose>) =>\n requests(\"pose\", poses).pipe(\n Effect.flatMap((made) => send(\"pose\", scriptCall(\"pose\", made))),\n span(\"Poses.set\"),\n owned,\n );\n\n const lease: Effect.Effect<Poses, BrowserError, Scope.Scope> = Effect.gen(function* () {\n if (open) return yield* refuse(\"pose\", \"the page's poses are open already\");\n open = true;\n yield* Effect.addFinalizer(() =>\n send(\"pose\", scriptCall(\"unpose\")).pipe(\n Effect.ignore,\n Effect.ensuring(Effect.sync(() => (open = false))),\n ),\n );\n\n return { set };\n });\n\n return { lease, open: () => open, requests, answered };\n};\n\nexport type Posing = ReturnType<typeof make>;\n","/** Main-world scripts with the page lane, document binding, policy and dispatch accounting. */\nimport { Effect, Schema } from \"effect\";\n\nimport {\n type BrowserError,\n undispatched,\n Failed,\n NotActionable,\n Threw,\n failWith,\n refuse,\n} from \"../../BrowserError.ts\";\nimport { InputRequest, type Page } from \"../../Page.ts\";\nimport * as Url from \"../../Url.ts\";\nimport type { Input } from \"../input/actions.ts\";\nimport type { Bridge } from \"./bridge.ts\";\nimport { contextGone, type PageContext } from \"./context.ts\";\n\nexport const make = (page: PageContext, bridge: Bridge, input: Input) => {\n const document = () => bridge.frameTag().document;\n\n const changed = (operation: string) =>\n failWith(operation, new NotActionable({ detail: \"the script's document changed\" }));\n\n const evaluate = <Arg>(operation: string, script: (arg: Arg) => unknown, arg: Arg) =>\n page.native(operation, () =>\n Promise.resolve<unknown>(\n Reflect.apply(page.playwright.evaluate.bind(page.playwright), undefined, [script, arg]),\n ),\n );\n\n const scriptFailure = (error: BrowserError) =>\n contextGone(error)\n ? undispatched(\n error.operation,\n new NotActionable({ detail: \"the script's document changed\" }),\n )\n : error.reason._tag === \"Failed\"\n ? undispatched(error.operation, new Threw({}))\n : error;\n\n const decode = <A>(operation: string, result: Schema.Codec<A, unknown>, value: unknown) =>\n Schema.decodeUnknownEffect(result)(value).pipe(\n Effect.mapError(() =>\n undispatched(operation, new Failed({ detail: \"script result did not match its schema\" })),\n ),\n );\n\n const read: Page[\"read\"] = (script, options) =>\n page.lane\n .read(\"read\")(\n Effect.gen(function* () {\n for (let attempt = 0; attempt < 2; attempt++) {\n const before = document();\n const value = yield* Effect.result(evaluate(\"read\", script, options.arg));\n\n if (value._tag === \"Failure\" && contextGone(value.failure)) {\n if (attempt === 1) return yield* changed(\"read\");\n yield* bridge.waitForDocument(before);\n continue;\n }\n if (document() !== before) continue;\n if (value._tag === \"Failure\") return yield* scriptFailure(value.failure);\n\n return {\n value: yield* decode(\"read\", options.result, value.success),\n document: before,\n connection: page.connection,\n };\n }\n\n return yield* changed(\"read\");\n }).pipe(page.within(\"read\")),\n )\n .pipe(page.span(\"Page.read\"), page.owned);\n\n const act: Page[\"act\"] = (script, options) =>\n Effect.suspend(() => {\n if (!Number.isSafeInteger(options.document) || options.document < 0)\n return refuse(\"act\", \"document must be a nonnegative safe integer\");\n\n const same = Effect.suspend(() =>\n document() === options.document &&\n (options.connection === undefined || options.connection === page.connection)\n ? Effect.void\n : changed(\"act\"),\n );\n\n // Scripts have no DOM target. An opaque scripted request must still pass the guard; neither\n // source nor arguments are evidence for a judge or material for the event history.\n const prepare = same.pipe(\n Effect.as({\n request: new InputRequest({\n page: page.id,\n url: Url.redact(page.playwright.url()),\n title: \"\",\n action: { _tag: \"Act\", document: options.document },\n facts: [\"scripted\", \"opaque\"],\n context: {},\n }),\n validate: same.pipe(Effect.as({ contextId: 0, check: () => same })),\n }),\n );\n\n return input.perform(\n { _tag: \"Act\", document: options.document },\n {},\n page.settings.actionTimeout,\n () => prepare,\n (marks) =>\n same.pipe(\n Effect.andThen(marks.sent),\n Effect.andThen(\n evaluate(\"act\", script, options.arg).pipe(Effect.mapError(scriptFailure)),\n ),\n Effect.flatMap((value) =>\n same.pipe(Effect.andThen(decode(\"act\", options.result, value))),\n ),\n ),\n );\n });\n\n return { read, act };\n};\n","/**\n * Holding a page's time: one hold at a time, each step one call to the page that takes the page\n * to itself, as an action does, so no read sees a step half made. See `PageTime`.\n */\nimport { Duration, Effect, Option, Schema, type Scope } from \"effect\";\n\nimport { type BrowserError, NotActionable } from \"../../BrowserError.ts\";\nimport { Box } from \"../../BrowserEvent.ts\";\nimport { Point } from \"../../Geometry.ts\";\nimport type { Held, Step } from \"../../PageTime.ts\";\nimport { type Bridge, scriptCall } from \"./bridge.ts\";\nimport { decodeWith, failWith, type PageContext, refuse } from \"./context.ts\";\nimport type { Overlays } from \"./overlay.ts\";\nimport { Posed, type Posing } from \"./pose.ts\";\nimport type { StepRequest } from \"./time.inpage.ts\";\n\nconst Stepped = Schema.Struct({\n ...Posed.fields,\n told: Schema.Boolean,\n drawn: Schema.NullOr(Schema.Array(Box)),\n scroll: Point,\n});\n\nexport const make = (page: PageContext, bridge: Bridge, overlays: Overlays, posing: Posing) => {\n const { lane, owned, span, within } = page;\n let holding = false;\n\n // One step, the page to itself, the overlay's turn too when it draws.\n const step = (operation: string, request: StepRequest) => {\n const sent = lane\n .write(\n operation,\n page.settings.actionTimeout,\n )(\n bridge.evaluate(operation, scriptCall(\"step\", request)).pipe(\n Effect.flatMap(decodeWith(operation, Stepped)),\n Effect.tap(({ drawn }) =>\n Effect.sync(() => {\n if (drawn !== null && request.markup !== undefined)\n overlays.record(request.markup, drawn);\n page.noteInput();\n }),\n ),\n within(operation),\n ),\n )\n .pipe(span(`PageTime.${operation}`), owned);\n\n return request.markup === undefined ? sent : overlays.turn(sent);\n };\n\n const unclocked = (operation: string) =>\n failWith(operation, new NotActionable({ detail: \"the page's document has no page clock\" }));\n\n const hold: Effect.Effect<Held, BrowserError, Scope.Scope> = Effect.gen(function* () {\n const clock = page.settings.pageTime;\n\n if (clock === undefined)\n return yield* refuse(\"hold\", \"holding page time needs the browser's pageTime option\");\n if (holding) return yield* refuse(\"hold\", \"the page's time is held already\");\n holding = true;\n let ended = false;\n\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => (ended = true)).pipe(\n Effect.andThen(step(\"release\", { clock, op: \"release\", by: 0, scroll: null })),\n Effect.ignore,\n Effect.ensuring(Effect.sync(() => (holding = false))),\n ),\n );\n const held = yield* step(\"hold\", { clock, op: \"hold\", by: 0, scroll: null });\n\n if (!held.told) return yield* unclocked(\"hold\");\n let elapsed = 0;\n\n const advance = (by: Duration.Input, options: Step = {}) =>\n Effect.gen(function* () {\n const millis = Option.map(Duration.fromInput(by), Duration.toMillis).pipe(\n Option.getOrElse(() => Number.NaN),\n );\n\n if (ended) return yield* refuse(\"advance\", \"the hold has ended\");\n if (!Number.isFinite(millis) || millis < 0)\n return yield* refuse(\"advance\", \"page time moves on by a finite, nonnegative duration\");\n if (options.scroll !== undefined && !Number.isFinite(options.scroll))\n return yield* refuse(\"advance\", \"the scroll must be finite\");\n if (options.overlay !== undefined && !overlays.open())\n return yield* refuse(\"advance\", \"drawing needs the page's overlay open\");\n if (options.poses !== undefined && !posing.open())\n return yield* refuse(\"advance\", \"posing needs the page's poses open\");\n\n const poses =\n options.poses === undefined\n ? undefined\n : yield* posing.requests(\"advance\", options.poses);\n\n const stepped = yield* step(\"advance\", {\n clock,\n op: \"advance\",\n by: millis,\n scroll: options.scroll ?? null,\n markup:\n options.overlay === undefined\n ? undefined\n : options.overlay._tag === \"Svg\"\n ? options.overlay.markup\n : null,\n poses,\n });\n\n yield* posing.answered(\"advance\", stepped);\n if (!stepped.told) return yield* unclocked(\"advance\");\n elapsed += millis;\n\n return stepped.scroll;\n });\n\n return { advance, elapsed: Effect.sync(() => Duration.millis(elapsed)) };\n });\n\n return { hold };\n};\n","/**\n * The viewport's size in CSS pixels. Playwright knows it only for a context it created; over CDP it\n * reports none, so the page answers, and so does a picture taken at one device pixel per CSS\n * pixel. Pointer bounds, page scrolls, crops, capture size and frame reuse all read this one\n * source; the latest answer serves checks that cannot wait for the page.\n */\nimport { Effect, Schema } from \"effect\";\n\nimport { type Bridge, scriptCall } from \"./bridge.ts\";\nimport { decodeWith, type PageContext } from \"./context.ts\";\n\nconst ViewportResultSchema = Schema.Struct({ width: Schema.Finite, height: Schema.Finite });\n\nexport const make = (page: PageContext, bridge: Bridge) => {\n const { playwright } = page;\n let measuredViewport: { readonly width: number; readonly height: number } | null = null;\n\n const knownViewport = () => playwright.viewportSize() ?? measuredViewport;\n\n const viewportFor = (operation: string) =>\n Effect.suspend(() => {\n const known = playwright.viewportSize();\n\n return known === null\n ? bridge.evaluate(operation, scriptCall(\"viewport\")).pipe(\n Effect.flatMap(decodeWith(operation, ViewportResultSchema)),\n Effect.tap((measured) =>\n Effect.sync(() => {\n measuredViewport = measured;\n }),\n ),\n )\n : Effect.succeed(known);\n });\n\n /** The size of an unscaled picture of the whole viewport, which is the viewport's own. */\n const remember = (size: { readonly width: number; readonly height: number }) => {\n measuredViewport = { width: size.width, height: size.height };\n };\n\n return { knownViewport, viewportFor, remember };\n};\n\nexport type Viewport = ReturnType<typeof make>;\n","/**\n * The page implementation behind `Page.Page`. `Browser` constructs pages and owns the state they\n * share (the clock mapping and event publication), so construction stays internal. A page is\n * assembled here from its domains: the script bridge, pictures, reading, its timeline, input and\n * navigation.\n * Features use the same documented Page contract as consumers.\n */\nimport { Effect, Option } from \"effect\";\n\nimport * as ActionPort from \"../../ActionPort.ts\";\nimport type { Frame } from \"../../Frame.ts\";\nimport { type Page, State } from \"../../Page.ts\";\nimport * as Url from \"../../Url.ts\";\nimport * as Actions from \"../input/actions.ts\";\nimport * as Pictures from \"../pictures/pictures.ts\";\nimport * as Layouts from \"../reading/layout.ts\";\nimport * as Reading from \"../reading/reading.ts\";\nimport * as Ready from \"../reading/ready.ts\";\nimport * as Changes from \"../timeline/changes.ts\";\nimport * as Window from \"../timeline/window.ts\";\nimport * as Bridge from \"./bridge.ts\";\nimport * as Context from \"./context.ts\";\nimport * as Navigation from \"./navigation.ts\";\nimport * as Overlay from \"./overlay.ts\";\nimport * as Poses from \"./pose.ts\";\nimport * as Scripts from \"./scripts.ts\";\nimport * as Time from \"./time.ts\";\nimport * as Viewport from \"./viewport.ts\";\n\nexport const make = Effect.fnUntraced(function* (options: Context.MakeOptions) {\n const page = Context.make(options, yield* Effect.scope);\n const { id, playwright, native, owned, within, lane, span } = page;\n const bridge = yield* Bridge.make(page);\n const viewport = Viewport.make(page, bridge);\n const input = Actions.make(page, bridge, viewport);\n const pictures = yield* Pictures.make(page, bridge, viewport);\n const reading = yield* Reading.make(page, bridge);\n const navigation = Navigation.make(page, input.perform, input.preparePolicy);\n const { capture } = pictures;\n const changes = Changes.make(page, bridge, pictures.estimate);\n const overlay = Overlay.make(page, bridge);\n const poses = Poses.make(page, bridge);\n const titles = lane.shared<string>(\"title\", true);\n const viewports = lane.shared<Effect.Success<Page[\"viewport\"]>>(\"viewport\", true);\n\n // What the page's parts already know, asking it nothing: its documents as its own session saw\n // them, the newest frame, and the viewport's text as last read since the document began.\n const state = Effect.map(capture.latest, (latest) => {\n const { document, url } = bridge.frameTag();\n const committedAt = page.activity.documentAt;\n\n return new State({\n page: id,\n connection: page.connection,\n at: page.now(),\n url,\n document,\n committedAt: Number.isFinite(committedAt) ? committedAt : undefined,\n load: bridge.loaded(),\n frame: Option.getOrUndefined(latest),\n overlay: overlay.drawn(),\n text: reading.viewedSince(committedAt),\n });\n });\n\n const current = (frame: Frame) =>\n capture.current(frame) &&\n bridge.frameTag().document === frame.document &&\n frame.hostTime - frame.timing.uncertaintyMillis > page.activity.documentAt;\n\n const afterInput: Page[\"afterInput\"] = (effect) =>\n lane\n .read(\n \"inputEnded\",\n page.settings.navigationTimeout,\n )(Effect.andThen(input.perform.idle, effect))\n .pipe(within(\"inputEnded\", page.settings.navigationTimeout), owned);\n\n const confirm = (frame: Frame) =>\n native(\"shown\", () => page.protocol.send(\"Page.getFrameTree\")).pipe(\n Effect.flatMap(() => capture.confirm(frame)),\n Effect.map((confirmed) => confirmed && current(frame)),\n within(\"shown\", \"2 seconds\"),\n owned,\n );\n\n const perform = ActionPort.checked((action) =>\n ActionPort.execute({ ...input, ...navigation }, action),\n );\n\n const assembled: Page = {\n ...Scripts.make(page, bridge, input),\n ...ActionPort.methods(perform),\n perform,\n clock: page.clock,\n afterInput,\n until: reading.until,\n capture: (options) =>\n capture.open(options).pipe(\n Effect.map((lease) => ({\n ...lease,\n isCurrent: current,\n confirm,\n sync: capture.sync,\n stats: pictures.captureStats,\n })),\n ),\n id,\n url: Effect.sync(() => Url.redact(playwright.url())),\n title: titles(\"\", navigation.title.pipe(within(\"title\"))).pipe(span(\"Page.title\"), owned),\n bringToFront: native(\"bringToFront\", () => playwright.bringToFront()),\n // Playwright answers once the page has closed, and at once for one already closed.\n close: native(\"close\", () => playwright.close()),\n snapshot: reading.snapshot,\n screenshot: pictures.screenshot,\n frame: pictures.frame,\n zoom: pictures.zoom,\n paint: pictures.paint,\n viewport: viewports(\"\", viewport.viewportFor(\"viewport\").pipe(within(\"viewport\"))).pipe(\n span(\"Page.viewport\"),\n owned,\n ),\n find: reading.find,\n layout: Layouts.make(page, bridge),\n overlay: overlay.lease,\n poses: poses.lease,\n hold: Time.make(page, bridge, overlay, poses).hold,\n text: reading.text,\n changes,\n window: Window.make(page, changes, capture.recent),\n state,\n ready: Ready.make(page, bridge),\n screencast: capture.stream,\n captureStats: pictures.captureStats,\n recentFrames: capture.recent,\n recentEvents: options.recentEvents,\n };\n\n return assembled;\n});\n","/** Proves a paused request's context before the connection's policy may see it. */\nimport { Cache, Clock, Duration, Effect, Exit, Option, Schema } from \"effect\";\nimport type { BrowserContext, CDPSession } from \"playwright-core\";\n\nimport { type BrowserError, InvalidRequest, undispatched } from \"../../BrowserError.ts\";\nimport * as Port from \"./port.ts\";\n\nexport type Native = <A>(\n run: (signal: AbortSignal) => Promise<A>,\n closing?: boolean,\n) => Effect.Effect<A, BrowserError>;\n\ninterface Tree {\n readonly frame: { readonly id: string };\n readonly childFrames?: ReadonlyArray<Tree> | undefined;\n}\n\nconst Tree: Schema.Codec<Tree> = Schema.Struct({\n frame: Schema.Struct({ id: Schema.String }),\n childFrames: Schema.optional(Schema.Array(Schema.suspend(() => Tree))),\n});\n\nconst FrameTree = Schema.Struct({ frameTree: Tree });\n\nconst Reply = Schema.fromJsonString(\n Schema.Struct({\n id: Schema.optional(Schema.Finite),\n result: Schema.optional(Schema.Unknown),\n error: Schema.optional(Schema.Struct({ message: Schema.String })),\n }),\n);\n\nconst contains = (tree: Tree, frame: string): boolean =>\n tree.frame.id === frame || tree.childFrames?.some((child) => contains(child, frame)) === true;\n\nconst queryTarget = async (\n chrome: CDPSession,\n target: string,\n method: string,\n params: object,\n signal: AbortSignal,\n session: Port.Session,\n hooks: Port.Hooks,\n) => {\n const { sessionId } = await chrome.send(\"Target.attachToTarget\", {\n targetId: target,\n flatten: false,\n });\n\n if (signal.aborted) {\n await chrome.send(\"Target.detachFromTarget\", { sessionId });\n throw new Error(\"request ownership query was interrupted\");\n }\n\n const response = Promise.withResolvers<unknown>();\n const interruption = Promise.withResolvers<never>();\n\n const receive = (event: { sessionId: string; message: string }) => {\n if (event.sessionId !== sessionId) return;\n const reply = Schema.decodeOption(Reply)(event.message);\n\n if (Option.isNone(reply)) {\n response.reject(new Error(\"request ownership query received an invalid response\"));\n\n return;\n }\n if (reply.value.id !== 1) return;\n if (reply.value.error !== undefined) response.reject(new Error(reply.value.error.message));\n else response.resolve(reply.value.result);\n };\n\n const detached = (event: { sessionId: string }) => {\n if (event.sessionId === sessionId)\n interruption.reject(new Error(\"request ownership target detached\"));\n };\n\n const aborted = () => interruption.reject(new Error(\"request ownership query was interrupted\"));\n\n chrome.on(\"Target.receivedMessageFromTarget\", receive);\n chrome.on(\"Target.detachedFromTarget\", detached);\n signal.addEventListener(\"abort\", aborted, { once: true });\n\n try {\n const send = () => {\n void chrome\n .send(\"Target.sendMessageToTarget\", {\n sessionId,\n message: JSON.stringify({ id: 1, method, params }),\n })\n .catch(response.reject);\n\n return response.promise;\n };\n\n // The logical child command stays faultable without inspecting serialized CDP messages.\n const query = hooks.query;\n\n return await Promise.race([\n query === undefined ? send() : query(session, method, send),\n interruption.promise,\n ]);\n } finally {\n chrome.off(\"Target.receivedMessageFromTarget\", receive);\n chrome.off(\"Target.detachedFromTarget\", detached);\n signal.removeEventListener(\"abort\", aborted);\n await chrome.send(\"Target.detachFromTarget\", { sessionId });\n }\n};\n\nexport const make = Effect.fnUntraced(function* (\n context: BrowserContext,\n chrome: CDPSession,\n native: Native,\n closing: () => boolean,\n) {\n const clock = yield* Clock.Clock;\n const hooks = yield* Port.Current;\n const protocol = yield* Effect.context<never>();\n\n const owned = yield* native(async (signal) => {\n const existing = context.pages()[0];\n const page = existing ?? (await context.newPage());\n let cdp: CDPSession | undefined;\n\n try {\n if (signal.aborted) throw new Error(\"request ownership setup was interrupted\");\n cdp = await Effect.runPromiseWith(protocol)(\n Port.openSession(\n async () => {\n if (signal.aborted) throw new Error(\"request ownership setup was interrupted\");\n const created = await context.newCDPSession(page);\n\n if (signal.aborted) {\n await created.detach();\n throw new Error(\"request ownership setup was interrupted\");\n }\n\n cdp = created;\n\n return created;\n },\n page,\n \"page\",\n ),\n { signal },\n );\n if (signal.aborted) throw new Error(\"request ownership setup was interrupted\");\n const { targetInfo } = await cdp.send(\"Target.getTargetInfo\");\n\n if (targetInfo.browserContextId === undefined)\n throw new Error(\"request ownership requires an identifiable browser context\");\n\n return targetInfo.browserContextId;\n } finally {\n try {\n if (cdp !== undefined) await cdp.detach();\n } finally {\n if (existing === undefined) await page.close();\n }\n }\n });\n\n const refresh = native(() => chrome.send(\"Target.getTargets\")).pipe(\n Effect.flatMap(({ targetInfos }) => {\n const targets = targetInfos.filter((target) => target.browserContextId === owned);\n\n if (targets.some((target) => target.type === \"shared_worker\"))\n return undispatched(\n \"requests\",\n new InvalidRequest({\n detail: \"request policies cannot protect preexisting shared workers\",\n }),\n );\n\n // Empty target patterns refresh existing documents under the browser interceptor.\n return Effect.forEach(\n targets.filter((target) => [\"page\", \"iframe\", \"service_worker\"].includes(target.type)),\n (target) =>\n native((signal) =>\n queryTarget(\n chrome,\n target.targetId,\n \"Fetch.enable\",\n { patterns: [] },\n signal,\n { channel: \"browser\", page: target.targetId, clock },\n hooks,\n ),\n ),\n { concurrency: 8, discard: true },\n );\n }),\n );\n\n const ownership = yield* Cache.makeWith(\n (frame: string) =>\n native(async (signal) => {\n const direct = await chrome\n .send(\"Target.getTargetInfo\", { targetId: frame })\n .catch((cause: unknown) => {\n if (cause instanceof Error && /No target with given id found/.test(cause.message))\n return undefined;\n\n throw cause;\n });\n\n if (signal.aborted) throw new Error(\"request ownership query was interrupted\");\n\n if (direct?.targetInfo.browserContextId !== undefined)\n return direct.targetInfo.browserContextId === owned\n ? { page: direct.targetInfo.type === \"page\" ? direct.targetInfo.targetId : undefined }\n : false;\n const { targetInfos } = await chrome.send(\"Target.getTargets\");\n\n for (const target of targetInfos) {\n if (signal.aborted) throw new Error(\"request ownership query was interrupted\");\n if (target.type !== \"page\" && target.type !== \"iframe\") continue;\n\n const result = await queryTarget(\n chrome,\n target.targetId,\n \"Page.getFrameTree\",\n {},\n signal,\n {\n channel: \"browser\",\n page: target.targetId,\n clock,\n },\n hooks,\n );\n\n const { frameTree } = Schema.decodeUnknownSync(FrameTree)(result);\n\n if (contains(frameTree, frame)) {\n if (target.browserContextId === undefined)\n throw new Error(\"request frame has no browser context evidence\");\n\n return target.browserContextId === owned\n ? { page: target.type === \"page\" ? frameTree.frame.id : undefined }\n : false;\n }\n }\n\n throw new Error(\"request frame ownership could not be established\");\n }, closing()),\n {\n capacity: 1024,\n // A child frame may move into its own OOPIF target; do not cache its parent-page label.\n timeToLive: (exit, frame) =>\n Exit.isSuccess(exit) &&\n (exit.value === false || exit.value.page === undefined || exit.value.page === frame)\n ? Duration.infinity\n : Duration.zero,\n },\n );\n\n const owns = (frame: string | undefined) =>\n frame === undefined\n ? Effect.fail(\n undispatched(\n \"requests\",\n new InvalidRequest({ detail: \"request has no frame ownership evidence\" }),\n ),\n )\n : Cache.get(ownership, frame);\n\n return { owns, refresh };\n});\n","/** Context-owned request decisions over bounded CDP interception, including every redirect hop. */\nimport { Cause, Clock, Duration, Effect, Exit, Option, Queue, Result, Scope } from \"effect\";\nimport { Base64 } from \"effect/encoding\";\nimport type { BrowserContext } from \"playwright-core\";\n\nimport type { RequestDecision, RequestPolicy } from \"../../Browser.ts\";\nimport {\n type BrowserError,\n refuse,\n reasonOf,\n Threw,\n Timeout,\n undispatched,\n} from \"../../BrowserError.ts\";\nimport { type BrowserEvent, RequestRefused } from \"../../BrowserEvent.ts\";\nimport * as Url from \"../../Url.ts\";\nimport * as Port from \"./port.ts\";\nimport * as Owner from \"./request-owner.ts\";\n\ninterface Paused {\n readonly requestId: string;\n readonly page?: string | undefined;\n readonly frameId?: string | undefined;\n readonly request: {\n readonly hasPostData?: boolean | undefined;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly url: string;\n readonly method: string;\n readonly postData?: string | undefined;\n readonly postDataEntries?: ReadonlyArray<{ readonly bytes?: string | undefined }> | undefined;\n };\n}\n\nconst responseOf = (decision: Extract<RequestDecision, { readonly _tag: \"Fulfilled\" }>) =>\n Number.isInteger(decision.status) &&\n decision.status >= 100 &&\n decision.status <= 599 &&\n new TextEncoder().encode(decision.body).byteLength <= 8_000_000 &&\n !/[\\r\\n]/.test(decision.contentType) &&\n Object.entries(decision.headers ?? {}).every(\n ([name, value]) => name !== \"\" && !/[\\r\\n]/.test(name + value),\n )\n ? {\n responseCode: decision.status,\n responseHeaders: [\n { name: \"Content-Type\", value: decision.contentType },\n ...Object.entries(decision.headers ?? {}).map(([name, value]) => ({ name, value })),\n ],\n body: Base64.encode(decision.body),\n }\n : undefined;\n\nconst bounded =\n (clock: Clock.Clock, duration: Duration.Duration): Owner.Native =>\n <A>(run: (signal: AbortSignal) => Promise<A>, closing = false) => {\n const bound = closing ? Duration.min(duration, Duration.seconds(1)) : duration;\n\n return Effect.tryPromise({\n try: run,\n catch: (cause) => undispatched(\"requests\", reasonOf(cause, undefined, \"connection\")),\n }).pipe(\n Effect.timeoutOrElse({\n duration: bound,\n orElse: () =>\n Effect.fail(undispatched(\"requests\", new Timeout({ millis: Duration.toMillis(bound) }))),\n }),\n Effect.provideService(Clock.Clock, clock),\n );\n };\n\ntype Reply = (\n paused: Paused,\n method: \"Fetch.continueRequest\" | \"Fetch.failRequest\" | \"Fetch.fulfillRequest\",\n params?: object,\n authorize?: boolean,\n) => Effect.Effect<void, BrowserError>;\n\nconst bodyOf = (request: Paused[\"request\"]): string | null | undefined => {\n const hasBody =\n request.hasPostData === true ||\n request.postData !== undefined ||\n (request.postDataEntries?.length ?? 0) > 0 ||\n Object.entries(request.headers ?? {}).some(\n ([name, value]) => name.toLowerCase() === \"content-length\" && Number(value) > 0,\n );\n\n if (!hasBody) return null;\n if (request.postData === undefined || request.postDataEntries === undefined) return undefined;\n const chunks: Uint8Array[] = [];\n\n for (const entry of request.postDataEntries) {\n if (entry.bytes === undefined) return undefined;\n const decoded = Base64.decode(entry.bytes);\n\n if (Result.isFailure(decoded)) return undefined;\n chunks.push(decoded.success);\n }\n\n const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));\n let offset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n\n try {\n const text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\n return text === request.postData ? text : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst deciding =\n (\n policy: RequestPolicy,\n clock: Clock.Clock,\n duration: Duration.Duration,\n closing: () => boolean,\n lost: () => void,\n deny: (\n paused: Paused,\n reason: string,\n failure?: BrowserError,\n ) => Effect.Effect<void, BrowserError>,\n reply: Reply,\n ) =>\n (paused: Paused) =>\n Effect.suspend(() => {\n const body = bodyOf(paused.request);\n\n if (body === undefined)\n return Effect.succeed({\n _tag: \"Refused\" as const,\n reason: \"request body was not fully observable as UTF-8 text\",\n });\n\n return policy.decide({\n url: paused.request.url,\n method: paused.request.method,\n body,\n });\n }).pipe(\n Effect.timeoutOrElse({\n duration: duration,\n orElse: () =>\n Effect.fail(\n undispatched(\"requests\", new Timeout({ millis: Duration.toMillis(duration) })),\n ),\n }),\n Effect.catchCause((cause) => {\n if (closing() && Cause.hasInterrupts(cause)) return Effect.failCause(cause);\n\n const error = Option.getOrElse(Cause.findErrorOption(cause), () =>\n undispatched(\"requests\", new Threw({})),\n );\n\n lost();\n\n return deny(\n paused,\n error.reason._tag === \"Timeout\"\n ? \"request decision timed out\"\n : `request decision failed: ${error.reason._tag}`,\n error,\n ).pipe(Effect.andThen(Effect.fail(error)));\n }),\n Effect.flatMap((decision) => {\n if (decision._tag === \"Allowed\") return reply(paused, \"Fetch.continueRequest\", {}, true);\n if (decision._tag === \"Refused\") return deny(paused, decision.reason);\n const response = responseOf(decision);\n\n return response === undefined\n ? deny(paused, \"request fulfillment is invalid or exceeds 8MB\")\n : reply(paused, \"Fetch.fulfillRequest\", response, true);\n }),\n Effect.provideService(Clock.Clock, clock),\n );\n\nconst retire = (\n owner: Effect.Success<ReturnType<typeof Owner.make>>,\n held: ReadonlyMap<string, Paused>,\n reply: Reply,\n) =>\n Effect.forEach(\n held.values(),\n (paused) =>\n owner.owns(paused.frameId).pipe(\n Effect.matchEffect({\n onFailure: () => reply(paused, \"Fetch.failRequest\", { errorReason: \"BlockedByClient\" }),\n onSuccess: (owned) =>\n reply(\n paused,\n owned ? \"Fetch.failRequest\" : \"Fetch.continueRequest\",\n owned ? { errorReason: \"BlockedByClient\" } : {},\n ),\n }),\n ),\n { concurrency: 8, discard: true },\n );\n\nexport const install = Effect.fnUntraced(function* (\n context: BrowserContext,\n policy: RequestPolicy,\n clock: Clock.Clock,\n publish: (event: BrowserEvent) => number,\n now: () => number,\n lost: () => void,\n unavailable: () => boolean,\n) {\n const browser = context.browser();\n\n if (browser === null)\n return yield* refuse(\"requests\", \"this provider cannot intercept browser requests\");\n const bound = Duration.fromInput(policy.timeout ?? \"5 seconds\");\n\n if (\n bound._tag === \"None\" ||\n !Duration.isFinite(bound.value) ||\n !Duration.isPositive(bound.value) ||\n policy.patterns.length === 0\n )\n return yield* refuse(\"requests\", \"request patterns and a finite positive timeout are required\");\n\n const native = bounded(clock, bound.value);\n const protocol = yield* Effect.context<never>();\n\n const chrome = yield* Effect.acquireRelease(\n native((signal) =>\n Effect.runPromiseWith(protocol)(\n Port.openSession(() => browser.newBrowserCDPSession(), undefined, \"browser\"),\n { signal },\n ).then(async (session) => {\n if (signal.aborted) await session.detach().catch(() => undefined);\n\n return session;\n }),\n ),\n (chrome) => native(() => chrome.detach(), true).pipe(Effect.orDie),\n );\n\n let closing = false;\n const owner = yield* Owner.make(context, chrome, native, () => closing);\n const held = new Map<string, Paused>();\n const pending = yield* Queue.unbounded<Paused>();\n const workers = yield* Scope.make();\n\n const record = (paused: Paused, reason: string, failure?: BrowserError) =>\n publish(\n new RequestRefused({\n at: now(),\n page: paused.page,\n method: paused.request.method,\n url: Url.redact(paused.request.url),\n reason: Url.redactWithin(reason).slice(0, 2000),\n ...(failure === undefined\n ? {}\n : {\n failure: {\n reason: failure.reason._tag,\n ...(failure.reason._tag === \"Timeout\"\n ? { timeoutMillis: failure.reason.millis }\n : {}),\n },\n }),\n }),\n );\n\n const reply: Reply = (paused, method, params = {}, authorize = false) =>\n native(async () => {\n // Check at dispatch: a policy may finish after a sibling failed or retirement began.\n const ended = authorize && (closing || unavailable());\n\n if (ended) record(paused, \"request authority has ended\");\n try {\n await chrome.send(ended ? \"Fetch.failRequest\" : method, {\n requestId: paused.requestId,\n ...(ended ? { errorReason: \"BlockedByClient\" } : params),\n });\n } catch (cause) {\n // A cancelled request is already settled; it does not revoke the browser's authority.\n if (!(cause instanceof Error && /Invalid InterceptionId\\.?$/.test(cause.message)))\n throw cause;\n }\n held.delete(paused.requestId);\n }, closing).pipe(Effect.uninterruptible);\n\n const deny = (paused: Paused, reason: string, failure?: BrowserError) =>\n Effect.sync(() => record(paused, reason, failure)).pipe(\n Effect.andThen(reply(paused, \"Fetch.failRequest\", { errorReason: \"BlockedByClient\" })),\n );\n\n const decide = deciding(policy, clock, bound.value, () => closing, lost, deny, reply);\n\n const handle = (paused: Paused) =>\n owner.owns(paused.frameId).pipe(\n Effect.matchEffect({\n onFailure: () => deny(paused, \"request ownership could not be established\"),\n onSuccess: (owned) =>\n !owned\n ? reply(paused, \"Fetch.continueRequest\")\n : closing || unavailable()\n ? deny({ ...paused, page: owned.page }, \"request authority has ended\")\n : decide({ ...paused, page: owned.page }),\n }),\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) => {\n const error = Option.getOrElse(Cause.findErrorOption(cause), () =>\n undispatched(\"requests\", new Threw({})),\n );\n\n return (\n unavailable()\n ? Effect.void\n : Effect.sync(() => record(paused, \"request control failed\", error))\n ).pipe(Effect.andThen(Effect.sync(lost)));\n },\n ),\n );\n\n const onRequest = (paused: Paused) => {\n held.set(paused.requestId, paused);\n Queue.offerUnsafe(pending, paused);\n };\n\n chrome.on(\"Fetch.requestPaused\", onRequest);\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n closing = true;\n }).pipe(\n // This stops new pauses without releasing the existing ones, unlike detach or disable.\n Effect.andThen(native(() => chrome.send(\"Fetch.enable\", { patterns: [] }), true)),\n Effect.ensuring(Scope.close(workers, Exit.void)),\n Effect.andThen(Effect.suspend(() => retire(owner, held, reply))),\n Effect.ensuring(Effect.sync(() => chrome.off(\"Fetch.requestPaused\", onRequest))),\n Effect.orDie,\n ),\n );\n\n for (let index = 0; index < 8; index++)\n yield* Queue.take(pending).pipe(\n Effect.flatMap(handle),\n Effect.forever,\n Effect.forkScoped,\n Scope.provide(workers),\n );\n\n yield* native(() =>\n chrome.send(\"Fetch.enable\", {\n patterns: policy.patterns.map((urlPattern) => ({ urlPattern })),\n }),\n );\n yield* owner.refresh;\n});\n","/**\n * The browser's bounded event history and replay cursors. Readers share the same records and\n * wakeup generation, so a delayed reader cannot block input or retain an unbounded private queue.\n */\nimport { Cause, Deferred, Effect, Stream } from \"effect\";\n\nimport { type BrowserError, EventHistoryExpired } from \"../../BrowserError.ts\";\nimport { type BrowserEvent, RecordedEvent } from \"../../BrowserEvent.ts\";\nimport { refuse, undispatched } from \"../page/context.ts\";\n\n/** The owning Browser validates capacity and closes this timeline with its scope. */\nexport const make = (capacity: number) => {\n const records = Array.from<RecordedEvent | undefined>({ length: capacity });\n let start = 0;\n let size = 0;\n let sequence = 0;\n let closed = false;\n let changed = Deferred.makeUnsafe<void>();\n\n const wake = () => {\n const previous = changed;\n\n changed = Deferred.makeUnsafe<void>();\n Deferred.doneUnsafe(previous, Effect.void);\n };\n\n const publish = (event: BrowserEvent): number => {\n // Native callbacks may finish after their owning scope. They must not revive closed readers.\n if (closed) return sequence;\n sequence += 1;\n const recorded = new RecordedEvent({ sequence, event });\n\n records[(start + size) % capacity] = recorded;\n if (size < capacity) size++;\n else start = (start + 1) % capacity;\n wake();\n\n return sequence;\n };\n\n const stream = (after?: number): Stream.Stream<RecordedEvent, BrowserError> =>\n Stream.unwrap(\n Effect.sync(() => {\n // This runs for each subscription, rather than when the reusable stream is constructed.\n let cursor = after ?? sequence;\n\n if (!Number.isSafeInteger(cursor) || cursor < 0 || cursor > sequence)\n return Stream.fromEffect(\n refuse(\n \"events\",\n \"the event cursor must be a nonnegative integer no greater than the latest sequence\",\n ),\n );\n\n return Stream.fromEffectRepeat(\n Effect.gen(function* () {\n while (true) {\n const oldest = sequence - size + 1;\n\n if (cursor < oldest - 1)\n return yield* undispatched(\n \"events\",\n new EventHistoryExpired({ after: cursor, oldest, latest: sequence }),\n );\n\n const next =\n cursor < sequence ? records[(start + cursor - oldest + 1) % capacity] : undefined;\n\n if (next !== undefined) {\n cursor = next.sequence;\n\n return next;\n }\n if (closed) return yield* Cause.done();\n // Capture the generation in the same synchronous read as the empty history check.\n // A publish before await completes this exact Deferred, so no wakeup can be missed.\n const waiting = changed;\n\n yield* Deferred.await(waiting);\n }\n }),\n );\n }),\n );\n\n return {\n publish,\n sequence: () => sequence,\n recent: Effect.sync(() =>\n Array.from({ length: size }, (_, index) => records[(start + index) % capacity]).filter(\n (record): record is RecordedEvent => record !== undefined,\n ),\n ),\n stream,\n close: Effect.sync(() => {\n if (closed) return;\n closed = true;\n wake();\n }),\n };\n};\n","/**\n * A live browser: its pages and what happens in it.\n *\n * `Browser` is a service with one implementation, built by a provider over a Playwright browser\n * context: `Chromium` launches one locally, `Cdp` connects to any DevTools endpoint and\n * `effect-browserbase` allocates a hosted one. Code written against `Browser` runs on all three.\n * A page is named by its CDP target id, so a new connection to the same browser finds it again.\n *\n * @since 0.3.0\n */\nimport {\n Clock,\n Context,\n DateTime,\n Deferred,\n Duration,\n Effect,\n Exit,\n FiberSet,\n Option,\n Queue,\n Schema,\n Scope,\n Semaphore,\n type Stream,\n} from \"effect\";\nimport type { BrowserContext, Page as PlaywrightPage } from \"playwright-core\";\n\nimport {\n type BrowserError,\n Closed,\n Failed,\n InvalidRequest,\n Limit,\n Timeout,\n} from \"./BrowserError.ts\";\nimport * as Events from \"./BrowserEvent.ts\";\nimport * as BrowserClock from \"./Clock.ts\";\nimport * as Gate from \"./internal/input/gate.ts\";\nimport { documentScripts } from \"./internal/page/bridge.ts\";\nimport { call, failWith, type Settings, undispatched } from \"./internal/page/context.ts\";\nimport { listen } from \"./internal/page/dialogs.ts\";\nimport * as Identity from \"./internal/page/identity.ts\";\nimport { FailFast } from \"./internal/page/lane.ts\";\nimport * as Openings from \"./internal/page/openings.ts\";\nimport * as PageImpl from \"./internal/page/page.ts\";\nimport * as Port from \"./internal/page/port.ts\";\nimport * as Requests from \"./internal/page/requests.ts\";\nimport * as Timeline from \"./internal/timeline/events.ts\";\nimport type * as Page from \"./Page.ts\";\nimport * as Url from \"./Url.ts\";\n\n/** A script that documents run before their own, such as a consent-banner remover. */\nexport interface InitScript {\n /**\n * The documents that run it, by a pattern their address (`location.href`) matches; every\n * document and frame when left out. Under a `match`, the source runs as a block, so its own\n * top-level `let`, `const` and classes stay its own.\n */\n readonly match?: RegExp | undefined;\n readonly source: string;\n}\n\n/** Consumer-owned decision for one request caught by a narrow URL pattern. */\nexport type RequestDecision =\n | { readonly _tag: \"Allowed\" }\n | { readonly _tag: \"Refused\"; readonly reason: string }\n | {\n readonly _tag: \"Fulfilled\";\n readonly status: number;\n readonly contentType: string;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly body: string;\n };\n\nexport interface RequestPolicy {\n readonly patterns: ReadonlyArray<string>;\n /**\n * Receives sensitive data for this context only; keep it out of model inputs and logs.\n * Body is exact UTF-8 text, or null when absent. Incomplete/binary body evidence refuses\n * that request. Preexisting shared workers make installation fail InvalidRequest.\n * Enforcement belongs to this connection's scope; it is not a firewall after CDP disconnects.\n */\n readonly decide: (request: {\n readonly url: string;\n readonly method: string;\n readonly body: string | null;\n }) => Effect.Effect<RequestDecision, BrowserError>;\n readonly timeout?: Duration.Input | undefined;\n}\n\nexport interface Options {\n /** Fixed viewport applied before each existing or newly opened page registers. */\n readonly viewport?: { readonly width: number; readonly height: number } | undefined;\n /** This context's policy, installed before pages register; redirects retain ownership. */\n readonly requests?: RequestPolicy | undefined;\n /**\n * Bound on each action; finite and positive. Defaults to 10 seconds. What a presenter's view\n * takes to show an action, such as its glides and typing at a person's pace, does not count\n * against it.\n */\n readonly actionTimeout?: Duration.Input | undefined;\n /** Bound on each navigation; finite and positive. Defaults to 30 seconds. */\n readonly navigationTimeout?: Duration.Input | undefined;\n /**\n * How long each page keeps screencast frames for `recentFrames`, measured back from the newest;\n * finite and positive. Defaults to 5 seconds, a moment's default window.\n */\n readonly frameHistory?: Duration.Input | undefined;\n /** Events retained for replay and `recentEvents`. A positive safe integer, defaulting to 4,096. */\n readonly eventHistory?: number | undefined;\n /** Allow, deny or hold each input or navigation before it reaches the page. Defaults to allow. */\n readonly guard?: Page.InputGuard | undefined;\n /** A separate bound for policy holds, outside action timeouts. Defaults to 5 minutes. */\n readonly policyTimeout?: Duration.Input | undefined;\n /** Scripts that new documents run before their own, each where its `match` allows. */\n readonly initScripts?: ReadonlyArray<InitScript> | undefined;\n /**\n * Run a page clock in each top document before its own scripts, so `Page.hold` can hold and\n * step its time. It keeps real time until held, but replaces the page's timers, animation\n * frames, `Date` and `performance.now`, which a page script can notice. See `PageTime`.\n */\n readonly pageTime?: boolean | undefined;\n /**\n * The most pages the browser keeps open, those a site opens included, which are never refused. At\n * it, `newPage` waits for one to close, within the action timeout, then fails `Limit`; under\n * `Page.failFast` it fails at once. A positive safe integer; no limit when left out.\n */\n readonly maxPages?: number | undefined;\n}\n\nexport interface EventOptions {\n /** Resume after this sequence; 0 replays from the beginning if it is still retained. */\n readonly after?: number | undefined;\n}\n\nexport interface SuspendOptions {\n /** Finite, nonnegative drain bound; defaults to the browser's navigationTimeout. */\n readonly drain?: Duration.Input | undefined;\n}\n\n/** When admitted input finished; events after `since` describe the handoff interval. */\nexport class Suspension extends Schema.Class<Suspension>(\"effect-browser/Suspension\")({\n since: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n at: Schema.Finite,\n}) {}\n\n/**\n * A connection to the browser apart from the one that drives its pages, for their screencasts,\n * as a provider that reaches the browser over a network supplies it: a frame and its\n * acknowledgement then never wait behind a large message, such as an upload or a read's answer,\n * on the connection that drives the page. It is read-only. A page's session on it sends the\n * capture's commands alone, and the page's own session keeps its focus emulation, which keeps a\n * tab behind painting.\n */\nexport interface CaptureSource {\n /**\n * A session on the page's target, for the scope. `event` gets the session's events in the order\n * the browser sent them, its target's detach among them, until the scope closes; `lost` gets\n * the connection's failure, once, if it fails first. Its calls never throw: a failure rejects.\n */\n readonly attach: (\n target: string,\n listener: {\n readonly event: (method: string, params: unknown) => void;\n readonly lost: (error: BrowserError) => void;\n },\n ) => Effect.Effect<\n (\n method:\n | \"Page.enable\"\n | \"Page.getFrameTree\"\n | \"Page.startScreencast\"\n | \"Page.screencastFrameAck\"\n | \"Page.stopScreencast\",\n params?: Record<string, unknown>,\n ) => Promise<unknown>,\n BrowserError,\n Scope.Scope\n >;\n}\n\nexport interface Service {\n /** The provider's session id, or a local id. */\n readonly id: string;\n /** Fresh for this connection, even when reattaching the same provider session and page. */\n readonly connection: string;\n readonly provider: string;\n /** When the provider ends the session on its own, as a hosted session's timeout does. */\n readonly expiresAt: DateTime.Utc | undefined;\n /** Host monotonic milliseconds on the clock shared by this browser’s events and frames. */\n readonly now: Effect.Effect<number>;\n /** Drain admitted input and withhold new input for this scope; reads and capture continue. */\n readonly suspend: (\n options?: SuspendOptions,\n ) => Effect.Effect<Suspension, BrowserError, Scope.Scope>;\n /** Open pages in the order this browser began tracking them. */\n readonly pages: Effect.Effect<ReadonlyArray<Page.Page>>;\n /** The open page with this id, its CDP target id, as stored before a reconnect. */\n readonly page: (id: string) => Effect.Effect<Option.Option<Page.Page>>;\n /** The first open page, opening one when there is none. */\n readonly firstPage: Effect.Effect<Page.Page, BrowserError>;\n readonly newPage: (url?: string) => Effect.Effect<Page.Page, BrowserError>;\n /** Whether an applicable cookie exists; its value never leaves the browser owner. */\n readonly hasCookie: (query: {\n readonly name: string;\n readonly url: string;\n }) => Effect.Effect<boolean, BrowserError>;\n /**\n * Completes once the browser is lost to its owner, with why: its connection dropped, its\n * provider ended its session, or its owner's scope released it.\n */\n readonly disconnected: Effect.Effect<Events.DisconnectCause>;\n /** Live events, or replay after a cursor. A reader that falls behind fails with EventHistoryExpired. */\n readonly events: (options?: EventOptions) => Stream.Stream<Events.RecordedEvent, BrowserError>;\n /** The latest `eventHistory` events, oldest first. */\n readonly recentEvents: Effect.Effect<ReadonlyArray<Events.BrowserEvent>>;\n}\n\nexport class Browser extends Context.Service<Browser, Service>()(\"effect-browser/Browser\") {}\n\n/** The settings every page shares, and how many events the browser keeps, from its options. */\nconst settingsOf = Effect.fnUntraced(function* (options: Options) {\n const invalid = (detail: string) => undispatched(\"make\", new InvalidRequest({ detail }));\n\n // Every bound guards a lock or a held key, so each must be a real, finite deadline.\n const bound = (name: string, input: Duration.Input | undefined, fallback: Duration.Duration) => {\n const decoded = Duration.fromInput(input ?? fallback);\n\n return Option.isSome(decoded) &&\n Number.isFinite(Duration.toMillis(decoded.value)) &&\n Duration.isPositive(decoded.value)\n ? Effect.succeed(decoded.value)\n : Effect.fail(invalid(`${name} must be finite and greater than zero`));\n };\n\n const settings: Settings = {\n actionTimeout: yield* bound(\"actionTimeout\", options.actionTimeout, Duration.seconds(10)),\n navigationTimeout: yield* bound(\n \"navigationTimeout\",\n options.navigationTimeout,\n Duration.seconds(30),\n ),\n frameHistory: yield* bound(\"frameHistory\", options.frameHistory, Duration.seconds(5)),\n guard: options.guard,\n policyTimeout: yield* bound(\"policyTimeout\", options.policyTimeout, Duration.minutes(5)),\n // An event name the page's own scripts cannot guess, which only the clock listens for.\n pageTime: options.pageTime === true ? `effect-browser-time-${yield* Identity.make}` : undefined,\n };\n\n if (\n options.viewport !== undefined &&\n ![options.viewport.width, options.viewport.height].every(\n (size) => Number.isSafeInteger(size) && size > 0,\n )\n )\n return yield* invalid(\"viewport dimensions must be positive safe integers\");\n const eventHistory = options.eventHistory ?? 4096;\n const { maxPages } = options;\n\n if (!Number.isSafeInteger(eventHistory) || eventHistory < 1)\n return yield* invalid(\"eventHistory must be a positive safe integer\");\n if (maxPages !== undefined && (!Number.isSafeInteger(maxPages) || maxPages < 1))\n return yield* invalid(\"maxPages must be a positive safe integer\");\n\n return { settings, eventHistory, maxPages };\n});\n\n/**\n * A provider that ends a session at `expiresAt` by its own clock can cut the connection a little\n * before this host's clock gets there.\n */\nconst endMargin = Duration.seconds(5);\n\n/**\n * The browser's loss, once: its context closing from the other side, at or after the session's\n * end or before it, or `lose`, as the owner's scope releases it. Playwright leaves the calls in\n * flight on the library's own sessions unanswered when the connection drops, so `untilLost` fails\n * each with the browser, as a closed page's call fails.\n */\nconst watchLoss = Effect.fnUntraced(function* (\n context: BrowserContext,\n expiresAt: DateTime.Utc | undefined,\n clock: Clock.Clock,\n disconnected: (cause: Events.DisconnectCause) => void,\n) {\n let lostBy: Events.DisconnectCause | undefined;\n const lost = yield* Deferred.make<Events.DisconnectCause>();\n const inFlight = new Set<(cause: Error) => void>();\n const gone = () => new Error(\"Target page, context or browser has been closed\");\n\n const lose = (cause: Events.DisconnectCause) => {\n if (lostBy !== undefined) return;\n lostBy = cause;\n for (const reject of inFlight) reject(gone());\n disconnected(cause);\n Deferred.doneUnsafe(lost, Exit.succeed(cause));\n };\n\n const untilLost = <A>(reply: Promise<A>): Promise<A> => {\n if (lostBy !== undefined) {\n void reply.catch(() => undefined);\n\n return Promise.reject(gone());\n }\n\n return new Promise<A>((resolve, reject) => {\n inFlight.add(reject);\n void reply.then(resolve, reject).finally(() => inFlight.delete(reject));\n });\n };\n\n const ended = () =>\n expiresAt !== undefined &&\n clock.currentTimeMillisUnsafe() >=\n DateTime.toEpochMillis(expiresAt) - Duration.toMillis(endMargin);\n\n const onClose = () => lose(ended() ? \"session\" : \"connection\");\n\n context.on(\"close\", onClose);\n yield* Effect.addFinalizer(() => Effect.sync(() => context.off(\"close\", onClose)));\n if (context.browser()?.isConnected() === false) onClose();\n\n const native = <A>(operation: string, run: () => Promise<A>) =>\n Effect.suspend(() =>\n lostBy === undefined\n ? call(\n operation,\n () => untilLost(run()),\n () => lostBy ?? \"page\",\n )\n : failWith(operation, new Closed({ cause: lostBy })),\n );\n\n return { lostBy: () => lostBy, lost: Deferred.await(lost), lose, untilLost, native };\n});\n\n/**\n * Register each page the site opens, such as a popup, as Playwright reports it, for as long as the\n * scope is open. One that could not be tracked is published, unless it closed as it opened.\n */\nconst followOpened = Effect.fnUntraced(function* (\n context: BrowserContext,\n registrations: Openings.Registrations,\n registerPage: (playwright: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,\n publish: (event: Events.BrowserEvent) => number,\n now: () => number,\n) {\n const registrationSlots = Semaphore.makeUnsafe(8);\n const runRegistration = yield* FiberSet.makeRuntime();\n\n const register = (playwright: PlaywrightPage) => {\n const known = registrations.get(playwright);\n\n if (known !== undefined) return Deferred.await(known);\n const done = Deferred.makeUnsafe<Page.Page, BrowserError>();\n\n // Publish the cell synchronously: the context's page event precedes its opener's popup event.\n registrations.set(playwright, done);\n runRegistration(\n registrationSlots\n .withPermits(1)(registerPage(playwright))\n .pipe(\n Effect.onExit((exit) => Deferred.done(done, exit)),\n Effect.catch((error) =>\n Effect.sync(() => {\n if (!playwright.isClosed())\n publish(\n new Events.PageUntracked({\n at: now(),\n url: Url.redact(playwright.url()),\n detail: error.message,\n }),\n );\n }),\n ),\n ),\n );\n\n return Deferred.await(done);\n };\n\n context.on(\"page\", register);\n yield* Effect.addFinalizer(() => Effect.sync(() => context.off(\"page\", register)));\n\n return register;\n});\n\n/** Release something native, on the owner's clock, giving up after a second: cleanup only. */\nconst releaseNative = (clock: Clock.Clock) => (run: () => Promise<unknown>) =>\n Effect.tryPromise(run).pipe(\n Effect.interruptible,\n Effect.timeoutOrElse({ duration: Duration.seconds(1), orElse: () => Effect.void }),\n Effect.provideService(Clock.Clock, clock),\n Effect.ignore,\n );\n\n/** A page's own events among the browser's retained ones, and the openings of tabs it opened. */\nconst eventsOf = (recent: Effect.Effect<ReadonlyArray<Events.RecordedEvent>>, page: string) =>\n Effect.map(recent, (records) =>\n records.flatMap(({ event }) =>\n (\"page\" in event && event.page === page) ||\n (event._tag === \"PageOpened\" && event.opener === page)\n ? [event]\n : [],\n ),\n );\n\n/**\n * At most `maxPages` open pages, those a site opened included, which are never refused: an open\n * past it waits for one to close, within `wait` on the owner's clock, then fails `Limit`, or fails\n * at once under `FailFast`. An open counts until its page is tracked.\n */\nconst pageBudget = (\n maxPages: number | undefined,\n tracked: () => number,\n wait: Duration.Duration,\n clock: Clock.Clock,\n) => {\n let opening = 0;\n // Completed as a page closes or an open ends, so the opens waiting look again.\n let roomMade = Deferred.makeUnsafe<void>();\n\n const makeRoom = () => {\n Deferred.doneUnsafe(roomMade, Exit.void);\n roomMade = Deferred.makeUnsafe<void>();\n };\n\n const full = (limit: number) => tracked() + opening >= limit;\n\n const room = (limit: number) =>\n Effect.gen(function* () {\n const refused = undispatched(\"newPage\", new Limit({ maxPages: limit }));\n\n if ((yield* FailFast) && full(limit)) return yield* refused;\n yield* Effect.gen(function* () {\n while (full(limit)) yield* Deferred.await(roomMade);\n opening += 1;\n }).pipe(\n Effect.timeoutOrElse({ duration: wait, orElse: () => Effect.fail(refused) }),\n Effect.provideService(Clock.Clock, clock),\n );\n });\n\n const open = <A, E, R>(opened: Effect.Effect<A, E, R>) =>\n maxPages === undefined\n ? opened\n : Effect.uninterruptibleMask((restore) =>\n restore(room(maxPages)).pipe(\n Effect.andThen(\n restore(opened).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n opening -= 1;\n makeRoom();\n }),\n ),\n ),\n ),\n ),\n );\n\n return { makeRoom, open };\n};\n\n/** A call sent now and awaited later, by whatever needs its answer. */\nconst sentNow = <A>(sent: Promise<A>) => {\n void sent.catch(() => undefined);\n\n return sent;\n};\n\n/** Close tab resources after publishing their close; a browser loss speaks for all its tabs. */\nconst closures = (\n lostBy: () => Events.DisconnectCause | undefined,\n publish: (event: Events.BrowserEvent) => number,\n now: () => number,\n) =>\n Effect.gen(function* () {\n const closing = yield* Queue.unbounded<{\n readonly scope: Scope.Closeable;\n readonly page: string;\n readonly cause: Events.PageClosed[\"cause\"];\n }>();\n\n yield* Queue.take(closing).pipe(\n Effect.tap(({ page, cause }) =>\n Effect.sync(() => {\n if (lostBy() === undefined) publish(new Events.PageClosed({ at: now(), page, cause }));\n }),\n ),\n Effect.flatMap(({ scope }) => Scope.close(scope, Exit.void)),\n Effect.forever,\n Effect.forkScoped,\n );\n\n return closing;\n });\n\n/** Cookie checks disclose presence only, within the browser's native deadline. */\nconst cookieQuery =\n (\n context: BrowserContext,\n native: Effect.Success<ReturnType<typeof watchLoss>>[\"native\"],\n timeout: Duration.Duration,\n clock: Clock.Clock,\n ): Service[\"hasCookie\"] =>\n ({ name, url }) =>\n native(\"hasCookie\", () => context.cookies(url)).pipe(\n Effect.map((cookies) => cookies.some((cookie) => cookie.name === name)),\n Effect.timeoutOrElse({\n duration: timeout,\n orElse: () => failWith(\"hasCookie\", new Timeout({ millis: Duration.toMillis(timeout) })),\n }),\n Effect.provideService(Clock.Clock, clock),\n );\n\n/** Tab allocation shares its budget, registration and first-tab lock. */\nconst tabs = (\n context: BrowserContext,\n registry: Map<PlaywrightPage, Page.Page>,\n budget: ReturnType<typeof pageBudget>,\n native: Effect.Success<ReturnType<typeof watchLoss>>[\"native\"],\n register: (page: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,\n release: ReturnType<typeof releaseNative>,\n firstPageLock: Semaphore.Semaphore,\n) => {\n const pages = Effect.sync(() => [...registry.values()]);\n\n const newPage = Effect.fn(\"Browser.newPage\")(function* (url?: string) {\n const page = yield* budget.open(\n native(\"newPage\", () => context.newPage()).pipe(\n Effect.flatMap((playwright) =>\n register(playwright).pipe(Effect.onError(() => release(() => playwright.close()))),\n ),\n ),\n );\n\n // A rejected or interrupted navigation must not leave the newly allocated blank tab behind.\n if (url !== undefined)\n yield* page.goto(url).pipe(Effect.onError(() => page.close.pipe(Effect.ignore)));\n\n return page;\n });\n\n return {\n pages,\n page: (id: string) =>\n Effect.map(pages, (open) => Option.fromNullishOr(open.find((page) => page.id === id))),\n firstPage: firstPageLock.withPermits(1)(\n pages.pipe(\n Effect.map((open) => Option.fromNullishOr(open[0])),\n Effect.flatMap(Option.match({ onNone: () => newPage(), onSome: Effect.succeed })),\n ),\n ),\n newPage,\n };\n};\n\n/** One connection owns clocks, loss, authority and its bounded timeline. */\nconst runtime = Effect.fnUntraced(function* (\n context: BrowserContext,\n expiresAt: DateTime.Utc | undefined,\n options: Options,\n) {\n const clock = yield* Clock.Clock;\n const connection = yield* Identity.make;\n const protocol = yield* Port.Current;\n const releasePort = protocol.browser?.(connection, context);\n\n yield* Effect.addFinalizer(() => Effect.sync(() => releasePort?.()));\n const now = () => BrowserClock.monotonicMillis(clock);\n const { settings, eventHistory, maxPages } = yield* settingsOf(options);\n // Measured on first need: the first capture of any page measures it, and input never waits.\n const mapping = BrowserClock.mapping(now);\n\n const timeline = Timeline.make(eventHistory);\n\n yield* Effect.addFinalizer(() => timeline.close);\n const publish = timeline.publish;\n\n if (expiresAt !== undefined)\n publish(new Events.SessionEnding({ at: now(), expiresAt: expiresAt }));\n\n const { lostBy, lost, lose, untilLost, native } = yield* watchLoss(\n context,\n expiresAt,\n clock,\n (cause) => publish(new Events.Disconnected({ at: now(), cause })),\n );\n\n if (options.requests !== undefined)\n yield* Requests.install(\n context,\n options.requests,\n clock,\n publish,\n now,\n () => lose(\"connection\"),\n () => lostBy() !== undefined,\n );\n\n const inputGate = Gate.make({\n now,\n sequence: timeline.sequence,\n closedBy: lostBy,\n lost,\n clock,\n drain: settings.navigationTimeout,\n });\n\n return {\n clock,\n connection,\n protocol,\n now,\n settings,\n maxPages,\n mapping,\n timeline,\n publish,\n lostBy,\n lost,\n lose,\n untilLost,\n native,\n inputGate,\n };\n});\n\n/**\n * Build the service over a context the provider owns. The provider closes the context; this only\n * tracks its pages and events, for as long as the surrounding scope is open. Each page's protocol\n * session, capture and listeners end when that page closes or when the scope does, so a closed\n * tab retains nothing and the context keeps none of them afterwards.\n */\nexport const make = Effect.fn(\"Browser.make\")(function* (\n context: BrowserContext,\n info: {\n readonly id?: string | undefined;\n readonly provider: string;\n readonly expiresAt?: DateTime.Utc | undefined;\n /** Where pages' screencasts run, if not on each page's own session. */\n readonly capture?: CaptureSource | undefined;\n },\n options: Options = {},\n) {\n const {\n clock,\n connection,\n protocol,\n now,\n settings,\n maxPages,\n mapping,\n timeline,\n publish,\n lostBy,\n lost,\n lose,\n untilLost,\n native,\n inputGate,\n } = yield* runtime(context, info.expiresAt, options);\n\n const session = info.id ?? connection;\n\n const registry = new Map<PlaywrightPage, Page.Page>();\n const registrations: Openings.Registrations = new WeakMap();\n // The pages' scopes close after the browser is marked released, so what fails as they close\n // says why.\n const pagesScope = yield* Scope.fork(yield* Scope.Scope);\n\n const release = releaseNative(clock);\n const budget = pageBudget(maxPages, () => registry.size, settings.actionTimeout, clock);\n\n // Each tab's scope closes with the tab or the browser. A dropped connection closes every page,\n // then the context, and `Disconnected` stands for all of them: the queue hands a close to its\n // fiber in a later turn, once Playwright has reported the context's.\n const closing = yield* closures(lostBy, publish, now);\n\n const registerPage = (playwright: PlaywrightPage) =>\n Effect.gen(function* () {\n if (playwright.isClosed())\n return yield* failWith(\"newPage\", new Failed({ detail: \"the page closed as it opened\" }));\n const viewport = options.viewport;\n\n if (viewport !== undefined)\n yield* native(\"viewport\", () => playwright.setViewportSize(viewport));\n const scope = yield* Scope.fork(pagesScope);\n\n return yield* Effect.gen(function* () {\n let crashed = false;\n const closedBy = () => lostBy() ?? (crashed ? \"crashed\" : \"page\");\n\n const cdp = yield* Port.openSession(\n () => context.newCDPSession(playwright),\n playwright,\n ).pipe(Effect.provideService(Port.Current, protocol));\n\n yield* Effect.addFinalizer(() => release(() => cdp.detach()));\n // The page's name, its target id, costs one round trip, which the calls that keep it\n // painting behind other tabs and report its documents share. A renderer busy with its\n // first script answers those two late, so what needs them waits, and registering does not.\n const send: typeof cdp.send = (method, params) => untilLost(cdp.send(method, params));\n const focusing = sentNow(send(\"Emulation.setFocusEmulationEnabled\", { enabled: true }));\n const paging = sentNow(send(\"Page.enable\"));\n const { targetInfo } = yield* native(\"newPage\", () => send(\"Target.getTargetInfo\"));\n const id = targetInfo.targetId;\n\n const page = yield* PageImpl.make({\n id,\n session,\n connection,\n url: targetInfo.url,\n playwright,\n cdp,\n nativePort: protocol.native,\n untilLost,\n settings,\n inputGate,\n clock,\n mapping,\n publish,\n recentEvents: eventsOf(timeline.recent, id),\n openings: yield* Openings.make(playwright, cdp, registrations, closedBy),\n focused: call(\"focus\", () => focusing, closedBy).pipe(Effect.asVoid),\n paging: (operation) => call(operation, () => paging, closedBy).pipe(Effect.asVoid),\n closedBy,\n capture: info.capture,\n }).pipe(Effect.provideService(Port.Current, protocol));\n\n const close = () => {\n if (registry.get(playwright) !== page) return;\n registry.delete(playwright);\n registrations.delete(playwright);\n budget.makeRoom();\n Queue.offerUnsafe(closing, { scope, page: id, cause: crashed ? \"crashed\" : \"page\" });\n };\n\n // Playwright drives a crashed page no more and its calls never return, so it is closed:\n // they fail at once, `Closed` because it crashed.\n const crash = () => {\n crashed = true;\n void playwright.close().catch(() => undefined);\n };\n\n registry.set(playwright, page);\n publish(\n new Events.PageOpened({\n at: now(),\n page: id,\n url: Url.redact(targetInfo.url),\n opener: targetInfo.openerId,\n }),\n );\n yield* listen(\n playwright,\n id,\n publish,\n now,\n (accept) =>\n native(\"dialog\", () => send(\"Page.handleJavaScriptDialog\", { accept })).pipe(\n Effect.asVoid,\n Effect.timeoutOrElse({\n duration: settings.actionTimeout,\n orElse: () => failWith(\"dialog\", new Failed({ detail: \"dialog answer timed out\" })),\n }),\n Effect.provideService(Clock.Clock, clock),\n ),\n {\n close,\n crash,\n failed: () => {\n // An unanswered dialog invalidates this page, not sibling pages or the connection.\n void playwright.close().catch(() => undefined);\n },\n },\n );\n if (playwright.isClosed()) close();\n\n return page;\n }).pipe(\n Scope.provide(scope),\n Effect.onError(() => Scope.close(scope, Exit.void)),\n );\n });\n\n // Playwright registers its init scripts as it sets up each page, before a popup's first document\n // runs, and they cost no call per document.\n for (const content of documentScripts(settings.pageTime, options.initScripts ?? []))\n yield* native(\"initScripts\", () => context.addInitScript({ content }));\n const register = yield* followOpened(context, registrations, registerPage, publish, now);\n\n for (const existing of context.pages()) yield* register(existing);\n\n // Added last, so it runs first as the owner's scope closes.\n yield* Effect.addFinalizer(() => Effect.sync(() => lose(\"released\")));\n\n const service: Service = {\n id: session,\n connection,\n provider: info.provider,\n expiresAt: info.expiresAt,\n now: Effect.sync(now),\n suspend: (options = {}) =>\n Effect.map(inputGate.suspend(options.drain), (held) => new Suspension(held)),\n ...tabs(context, registry, budget, native, register, release, Semaphore.makeUnsafe(1)),\n hasCookie: cookieQuery(context, native, settings.actionTimeout, clock),\n disconnected: lost,\n events: (eventOptions = {}) => timeline.stream(eventOptions.after),\n recentEvents: timeline.recent.pipe(\n Effect.map((records) => records.map((record) => record.event)),\n ),\n };\n\n return Browser.of(service);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,WAAW,KAA0B,OACzC,IAAI,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,SAAS,SAAS,EAAE,CAAC;AAEhD,MAAMA,UAAQ,OAAc,OAAc,YAA4B;CACpE,QAAQ,MAAM,MAAd;EACE,KAAK,SACH,OAAO,MAAM,SAAS,SAClB;GAAE,GAAG;GAAO,wBAAQ,IAAI,IAAI,CAAC,GAAG,MAAM,QAAQ,MAAM,EAAE,CAAC;EAAE,IACzD;EACN,KAAK,OAAO;GACV,IAAI,MAAM,SAAS,QAAQ,OAAO;GAClC,MAAM,SAAS,QAAQ,MAAM,QAAQ,MAAM,EAAE;GAE7C,OAAO,MAAM,SAAS,cAAc,OAAO,SAAS,IAChD;IAAE,MAAM;IAAQ,QAAQ,MAAM;IAAQ;GAAQ,IAC9C;IAAE,GAAG;IAAO;GAAO;EACzB;EACA,KAAK;GACH,IAAI,MAAM,SAAS,QAAQ,OAAO;IAAE,GAAG;IAAO,wBAAQ,IAAI,IAAI,CAAC,GAAG,MAAM,QAAQ,MAAM,EAAE,CAAC;GAAE;GAE3F,OAAO,MAAM,OAAO,SAAS,IACzB;IAAE,MAAM;IAAQ,wBAAQ,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;IAAG;GAAQ,IACrD;IACE,MAAM;IACN,QAAQ,MAAM;IACd,wBAAQ,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;IAC1B,WAAW,QAAQ;IACnB,UAAU,QAAQ,KAAK,MAAM;GA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