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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/README.md +221 -158
  2. package/dist/Action-24sLOubi.d.mts +110 -0
  3. package/dist/Action.d.mts +2 -0
  4. package/dist/Action.mjs +141 -0
  5. package/dist/Action.mjs.map +1 -0
  6. package/dist/ActionPort.d.mts +15 -0
  7. package/dist/ActionPort.mjs +101 -0
  8. package/dist/ActionPort.mjs.map +1 -0
  9. package/dist/Browser-Cq2K1FEA.mjs +4075 -0
  10. package/dist/Browser-Cq2K1FEA.mjs.map +1 -0
  11. package/dist/Browser-wZhwZSlG.d.mts +167 -0
  12. package/dist/Browser.d.mts +2 -129
  13. package/dist/Browser.mjs +1 -1
  14. package/dist/{BrowserError-Coy7EW1N.d.mts → BrowserError-BlcmLVzn.d.mts} +22 -7
  15. package/dist/BrowserError.d.mts +2 -2
  16. package/dist/BrowserError.mjs +46 -9
  17. package/dist/BrowserError.mjs.map +1 -1
  18. package/dist/{BrowserEvent-dq6FRT8w.d.mts → BrowserEvent-lLqJ3GJS.d.mts} +93 -37
  19. package/dist/BrowserEvent.d.mts +2 -2
  20. package/dist/BrowserEvent.mjs +29 -24
  21. package/dist/BrowserEvent.mjs.map +1 -1
  22. package/dist/{Change-DqING3tr.d.mts → Change-Ba7INmay.d.mts} +4 -6
  23. package/dist/Change.d.mts +2 -2
  24. package/dist/Change.mjs +97 -2
  25. package/dist/Change.mjs.map +1 -0
  26. package/dist/Clock.d.mts +57 -0
  27. package/dist/Clock.mjs +80 -0
  28. package/dist/Clock.mjs.map +1 -0
  29. package/dist/{Frame-DkNdjjjr.d.mts → Frame-UEH2hO5T.d.mts} +10 -3
  30. package/dist/Frame.d.mts +2 -2
  31. package/dist/Frame.mjs +10 -2
  32. package/dist/Frame.mjs.map +1 -1
  33. package/dist/{Motion-DND6I-64.d.mts → Geometry-DJx9qrYy.d.mts} +7 -10
  34. package/dist/Geometry.d.mts +2 -0
  35. package/dist/Geometry.mjs +32 -0
  36. package/dist/Geometry.mjs.map +1 -0
  37. package/dist/LICENSE-jpeg-js +28 -0
  38. package/dist/Matching.d.mts +37 -0
  39. package/dist/{match.inpage-xOe9LNO0.mjs → Matching.mjs} +28 -4
  40. package/dist/Matching.mjs.map +1 -0
  41. package/dist/{Page-CfB6Zn1p.mjs → Page-BF5izr8R.mjs} +216 -31
  42. package/dist/Page-BF5izr8R.mjs.map +1 -0
  43. package/dist/{Page-ku6j5t-v.d.mts → Page-CvsOEorc.d.mts} +158 -185
  44. package/dist/Page.d.mts +2 -2
  45. package/dist/Page.mjs +1 -1
  46. package/dist/Released-tURbFmal.d.mts +15 -0
  47. package/dist/{Snapshot-B34hZ4Jl.d.mts → Snapshot-CtBVOtuu.d.mts} +6 -1
  48. package/dist/Snapshot.d.mts +1 -1
  49. package/dist/Snapshot.mjs.map +1 -1
  50. package/dist/Stillness-CNlvayIo.mjs +136 -0
  51. package/dist/Stillness-CNlvayIo.mjs.map +1 -0
  52. package/dist/Style-AO4V7Czt.mjs +357 -0
  53. package/dist/Style-AO4V7Czt.mjs.map +1 -0
  54. package/dist/Style.d.mts +72 -0
  55. package/dist/Style.mjs +2 -0
  56. package/dist/Url.d.mts +26 -0
  57. package/dist/Url.mjs +74 -0
  58. package/dist/Url.mjs.map +1 -0
  59. package/dist/Window-CMddGMt1.d.mts +34 -0
  60. package/dist/Window.d.mts +2 -0
  61. package/dist/Window.mjs +35 -0
  62. package/dist/Window.mjs.map +1 -0
  63. package/dist/connection-2KHI4_KN.d.mts +41 -0
  64. package/dist/connection-BTeO0Hiz.mjs +68 -0
  65. package/dist/connection-BTeO0Hiz.mjs.map +1 -0
  66. package/dist/index.d.mts +15 -17
  67. package/dist/index.mjs +11 -14
  68. package/dist/moment/Moment.d.mts +86 -0
  69. package/dist/{Moment.mjs → moment/Moment.mjs} +44 -38
  70. package/dist/moment/Moment.mjs.map +1 -0
  71. package/dist/{Plan-DJ4hEEna.d.mts → plan/index.d.mts} +169 -64
  72. package/dist/{Plan-C-d5QYS8.mjs → plan/index.mjs} +122 -155
  73. package/dist/plan/index.mjs.map +1 -0
  74. package/dist/{Policy.d.mts → policy/Policy.d.mts} +5 -9
  75. package/dist/{Policy.mjs → policy/Policy.mjs} +11 -21
  76. package/dist/policy/Policy.mjs.map +1 -0
  77. package/dist/presentation/Motion.d.mts +12 -0
  78. package/dist/{Motion.mjs → presentation/Motion.mjs} +4 -27
  79. package/dist/presentation/Motion.mjs.map +1 -0
  80. package/dist/presentation/Presentation.d.mts +30 -0
  81. package/dist/presentation/Presentation.mjs +105 -0
  82. package/dist/presentation/Presentation.mjs.map +1 -0
  83. package/dist/{Stage.d.mts → presentation/Stage.d.mts} +5 -8
  84. package/dist/{Stage.mjs → presentation/Stage.mjs} +68 -76
  85. package/dist/presentation/Stage.mjs.map +1 -0
  86. package/dist/presentation/feed.d.mts +20 -0
  87. package/dist/presentation/feed.mjs +18 -0
  88. package/dist/presentation/feed.mjs.map +1 -0
  89. package/dist/providers/Cdp.d.mts +9 -0
  90. package/dist/providers/Cdp.mjs +15 -0
  91. package/dist/providers/Cdp.mjs.map +1 -0
  92. package/dist/{Chromium.d.mts → providers/Chromium.d.mts} +6 -7
  93. package/dist/{Chromium.mjs → providers/Chromium.mjs} +7 -16
  94. package/dist/providers/Chromium.mjs.map +1 -0
  95. package/dist/providers/Released.d.mts +2 -0
  96. package/dist/providers/Released.mjs +12 -0
  97. package/dist/providers/Released.mjs.map +1 -0
  98. package/dist/stillness/Stillness.d.mts +12 -0
  99. package/dist/stillness/Stillness.mjs +2 -0
  100. package/dist/supervisor/Supervisor.d.mts +104 -0
  101. package/dist/supervisor/Supervisor.mjs +513 -0
  102. package/dist/supervisor/Supervisor.mjs.map +1 -0
  103. package/dist/testing/index.d.mts +337 -0
  104. package/dist/testing/index.mjs +515 -0
  105. package/dist/testing/index.mjs.map +1 -0
  106. package/dist/workerd/Cdp.d.mts +8 -0
  107. package/dist/workerd/Cdp.mjs +13 -0
  108. package/dist/workerd/Cdp.mjs.map +1 -0
  109. package/package.json +94 -33
  110. package/src/Action.ts +127 -0
  111. package/src/ActionPort.ts +128 -0
  112. package/src/Browser.ts +366 -225
  113. package/src/BrowserError.ts +63 -6
  114. package/src/BrowserEvent.ts +26 -25
  115. package/src/Change.ts +0 -2
  116. package/src/{internal/pictures/clock.ts → Clock.ts} +17 -6
  117. package/src/Frame.ts +14 -0
  118. package/src/Geometry.ts +48 -0
  119. package/src/{internal/reading/match.inpage.ts → Matching.ts} +34 -4
  120. package/src/Page.ts +111 -92
  121. package/src/Snapshot.ts +5 -0
  122. package/src/{internal/input/style.ts → Style.ts} +121 -14
  123. package/src/Window.ts +30 -0
  124. package/src/index.ts +8 -13
  125. package/src/internal/input/actions.ts +61 -119
  126. package/src/internal/input/dispatch.ts +3 -3
  127. package/src/internal/input/gate.ts +21 -18
  128. package/src/internal/input/guard.inpage.ts +25 -58
  129. package/src/internal/input/guard.ts +11 -20
  130. package/src/internal/input/keyboard.ts +12 -3
  131. package/src/internal/input/perform.ts +78 -60
  132. package/src/internal/input/pointer.ts +4 -2
  133. package/src/internal/input/settle.ts +7 -5
  134. package/src/internal/input/targets.inpage.ts +1 -1
  135. package/src/internal/input/targets.ts +4 -9
  136. package/src/internal/page/bridge.ts +210 -114
  137. package/src/internal/page/context.ts +23 -73
  138. package/src/internal/page/dialogs.ts +58 -0
  139. package/src/internal/page/identity.ts +6 -23
  140. package/src/internal/page/lane.ts +14 -15
  141. package/src/internal/page/navigation.ts +50 -42
  142. package/src/internal/page/openings.ts +11 -5
  143. package/src/internal/page/page.ts +44 -81
  144. package/src/internal/page/port.ts +125 -0
  145. package/src/internal/{input → page}/replies.ts +1 -1
  146. package/src/internal/page/request-owner.ts +269 -0
  147. package/src/internal/page/requests.ts +357 -0
  148. package/src/internal/page/scripts.ts +124 -0
  149. package/src/internal/pictures/capture.ts +255 -332
  150. package/src/internal/pictures/dimensions.ts +162 -0
  151. package/src/internal/pictures/frame.ts +68 -0
  152. package/src/internal/pictures/pictures.ts +57 -23
  153. package/src/internal/pictures/quiescence.ts +1 -1
  154. package/src/internal/pictures/state.ts +26 -0
  155. package/src/internal/pictures/transport.ts +21 -4
  156. package/src/internal/reading/controls.inpage.ts +5 -70
  157. package/src/internal/reading/expect.inpage.ts +13 -17
  158. package/src/internal/reading/names.inpage.ts +89 -45
  159. package/src/internal/reading/outline.inpage.ts +6 -7
  160. package/src/internal/reading/reading.ts +144 -176
  161. package/src/internal/reading/ready.inpage.ts +6 -17
  162. package/src/internal/reading/ready.ts +13 -135
  163. package/src/internal/reading/subjects.inpage.ts +83 -43
  164. package/src/internal/reading/walk.inpage.ts +33 -13
  165. package/src/internal/timeline/changes.ts +55 -6
  166. package/src/internal/timeline/events.ts +15 -5
  167. package/src/internal/timeline/history.inpage.ts +1 -1
  168. package/src/internal/timeline/record.inpage.ts +4 -1
  169. package/src/internal/timeline/window.ts +2 -1
  170. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  171. package/src/{internal/timeline → moment}/words.ts +2 -2
  172. package/src/{internal/reading → plan}/choose.ts +3 -3
  173. package/src/plan/data.ts +117 -0
  174. package/src/plan/execute.ts +411 -0
  175. package/src/plan/index.ts +36 -0
  176. package/src/plan/record.ts +71 -0
  177. package/src/plan/targets.ts +71 -0
  178. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  179. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  180. package/src/presentation/Presentation.ts +176 -0
  181. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  182. package/src/presentation/feed.ts +21 -0
  183. package/src/providers/Cdp.ts +16 -0
  184. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  185. package/src/providers/Released.ts +13 -0
  186. package/src/providers/connection.ts +134 -0
  187. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +4 -4
  188. package/src/stillness/Stillness.ts +166 -0
  189. package/src/supervisor/Supervisor.ts +170 -0
  190. package/src/supervisor/contract.ts +105 -0
  191. package/src/supervisor/lifecycle.ts +272 -0
  192. package/src/supervisor/runtime.ts +234 -0
  193. package/src/testing/TestBrowser.ts +115 -0
  194. package/src/testing/TestPage.ts +10 -0
  195. package/src/testing/evidence.ts +154 -0
  196. package/src/testing/index.ts +3 -0
  197. package/src/testing/model.ts +222 -0
  198. package/src/testing/page.ts +360 -0
  199. package/src/workerd/Cdp.ts +11 -0
  200. package/dist/Browser-BwCldIff.mjs +0 -629
  201. package/dist/Browser-BwCldIff.mjs.map +0 -1
  202. package/dist/Cdp.d.mts +0 -32
  203. package/dist/Cdp.mjs +0 -61
  204. package/dist/Cdp.mjs.map +0 -1
  205. package/dist/Change-DNvztNLu.mjs +0 -138
  206. package/dist/Change-DNvztNLu.mjs.map +0 -1
  207. package/dist/Chromium.mjs.map +0 -1
  208. package/dist/Expect.d.mts +0 -62
  209. package/dist/Expect.mjs +0 -114
  210. package/dist/Expect.mjs.map +0 -1
  211. package/dist/Moment.d.mts +0 -2
  212. package/dist/Moment.mjs.map +0 -1
  213. package/dist/Motion.d.mts +0 -2
  214. package/dist/Motion.mjs.map +0 -1
  215. package/dist/Page-CfB6Zn1p.mjs.map +0 -1
  216. package/dist/Plan-C-d5QYS8.mjs.map +0 -1
  217. package/dist/Plan.d.mts +0 -2
  218. package/dist/Plan.mjs +0 -2
  219. package/dist/Policy.mjs.map +0 -1
  220. package/dist/Presentation.d.mts +0 -48
  221. package/dist/Presentation.mjs +0 -118
  222. package/dist/Presentation.mjs.map +0 -1
  223. package/dist/Stage.mjs.map +0 -1
  224. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  225. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  226. package/dist/Supervisor-mVPeEUp8.d.mts +0 -317
  227. package/dist/Supervisor.d.mts +0 -2
  228. package/dist/Supervisor.mjs +0 -2
  229. package/dist/context-w3NJPRLo.mjs +0 -335
  230. package/dist/context-w3NJPRLo.mjs.map +0 -1
  231. package/dist/match.inpage-xOe9LNO0.mjs.map +0 -1
  232. package/dist/page-BKwfF6z-.mjs +0 -5099
  233. package/dist/page-BKwfF6z-.mjs.map +0 -1
  234. package/dist/url-Cd04Okid.mjs +0 -264
  235. package/dist/url-Cd04Okid.mjs.map +0 -1
  236. package/src/Cdp.ts +0 -101
  237. package/src/Expect.ts +0 -180
  238. package/src/Plan.ts +0 -674
  239. package/src/Presentation.ts +0 -196
  240. package/src/Supervisor.ts +0 -632
  241. package/src/internal/supervisor/lifecycle.ts +0 -484
  242. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  243. /package/src/{internal/pictures → stillness}/utilsBundle.d.ts +0 -0
@@ -0,0 +1,162 @@
1
+ /** Viewport evidence and bounded foreign-picture filtering for one capture. */
2
+ import { Clock, Duration, Effect, Queue } from "effect";
3
+
4
+ import type { BrowserError } from "../../BrowserError.ts";
5
+ import { monotonicMillis } from "../../Clock.ts";
6
+ import type { Frame } from "../../Frame.ts";
7
+
8
+ export interface Size {
9
+ readonly width: number;
10
+ readonly height: number;
11
+ }
12
+
13
+ interface Options {
14
+ readonly clock: Clock.Clock;
15
+ readonly viewport: Effect.Effect<Size, BrowserError>;
16
+ }
17
+ const deadline = Duration.seconds(2);
18
+
19
+ interface Held {
20
+ readonly frame: Frame;
21
+ readonly timestamp: number;
22
+ }
23
+
24
+ /** Consecutive frames of one device size other than the expected one, oldest first. */
25
+ interface Run {
26
+ readonly device: Size;
27
+ /** When its first frame arrived, on the owner's monotonic clock. */
28
+ readonly since: number;
29
+ readonly frames: Array<Held>;
30
+ }
31
+
32
+ // Device sizes can be fractional at some scale factors; the page reports whole pixels.
33
+ const sameSize = (left: Size, right: Size) =>
34
+ Math.abs(left.width - right.width) < 1 && Math.abs(left.height - right.height) < 1;
35
+
36
+ // A frame is its device scaled to fit, so it keeps the device's shape to within a pixel a side.
37
+ const sameShape = (image: Size, device: Size) =>
38
+ Math.abs(image.width * device.height - image.height * device.width) <
39
+ device.width + device.height;
40
+
41
+ // Another capture's frames last only as long as it does; a run of frames that lasts longer is
42
+ // the page's own.
43
+ const outlasting = Duration.seconds(1);
44
+
45
+ // A page too busy to report its viewport in time reads as null.
46
+ export const readViewport = (options: Options) =>
47
+ options.viewport.pipe(
48
+ Effect.interruptible,
49
+ Effect.timeoutOrElse({ duration: deadline, orElse: () => Effect.succeed(null) }),
50
+ Effect.orElseSucceed(() => null),
51
+ Effect.provideService(Clock.Clock, options.clock),
52
+ );
53
+
54
+ /**
55
+ * Keeps other captures' frames from readers. A clipped or scaled screenshot of the page, taken
56
+ * from any session, draws frames into its running screencast without resizing the page, until
57
+ * Chromium returns to the page's size. Either their picture has another shape than their device,
58
+ * and they are dropped, or their device has another size than the page's frames.
59
+ *
60
+ * A frame of the expected device size goes to readers at once and drops any run of frames of
61
+ * another size before it, as another capture's. A run waits, in order, until the page reports a
62
+ * viewport of its size or until it outlasts any capture: then it was a real resize, so it goes to
63
+ * readers and its size is expected. The page's report only shortens the wait, so a page too busy
64
+ * to answer, or one measuring in other units as under browser zoom, never stalls the stream.
65
+ */
66
+ export const sizeFilter = (
67
+ options: Options,
68
+ deliver: (frame: Frame, timestamp: number) => void,
69
+ drop: (frames: number) => void,
70
+ resized: (size: Size) => void,
71
+ ) =>
72
+ Effect.gen(function* () {
73
+ // Until a capture reads its viewport or delivers a frame, its first frame stands in.
74
+ let expected: Size | null = null;
75
+ let run: Run | undefined;
76
+ // Wakes the decider for a new run or an ended one; wakes while it is busy coalesce.
77
+ const wake = yield* Queue.sliding<void>(1);
78
+
79
+ const end = () => {
80
+ if (run === undefined) return;
81
+ drop(run.frames.length);
82
+ run = undefined;
83
+ Queue.offerUnsafe(wake, undefined);
84
+ };
85
+
86
+ const now = () => monotonicMillis(options.clock);
87
+
88
+ const adopt = (adopted: Run) => {
89
+ run = undefined;
90
+ expected = adopted.device;
91
+ resized(adopted.device);
92
+ for (const held of adopted.frames) deliver(held.frame, held.timestamp);
93
+ };
94
+
95
+ const decide: Effect.Effect<void> = Effect.suspend(() => {
96
+ const deciding = run;
97
+
98
+ if (deciding === undefined) return Effect.void;
99
+
100
+ return readViewport(options).pipe(
101
+ Effect.flatMap((viewport) => {
102
+ if (run !== deciding) return decide;
103
+ if (viewport !== null && sameSize(viewport, deciding.device))
104
+ return Effect.sync(() => adopt(deciding));
105
+
106
+ return outlast(deciding);
107
+ }),
108
+ );
109
+ });
110
+
111
+ // Waits until the run outlasts any capture, unless a newer frame decides it first.
112
+ const outlast = (waiting: Run): Effect.Effect<void> =>
113
+ Effect.suspend(() => {
114
+ if (run !== waiting) return decide;
115
+ const remaining = waiting.since + Duration.toMillis(outlasting) - now();
116
+
117
+ if (remaining <= 0) return Effect.sync(() => adopt(waiting));
118
+
119
+ return Effect.sleep(Duration.millis(remaining)).pipe(
120
+ Effect.provideService(Clock.Clock, options.clock),
121
+ Effect.race(Queue.take(wake)),
122
+ Effect.andThen(outlast(waiting)),
123
+ );
124
+ });
125
+
126
+ yield* Queue.take(wake).pipe(Effect.andThen(decide), Effect.forever, Effect.forkScoped);
127
+
128
+ return {
129
+ /** Drops the frames still waiting; their capture has stopped. */
130
+ end,
131
+ /** A new capture expects the viewport it read, if any. */
132
+ restart: (viewport: Size | null) => {
133
+ end();
134
+ expected = viewport;
135
+ },
136
+ /** Whether a frame of this device size shows the page, as far as the capture knows. */
137
+ offer: (frame: Frame, timestamp: number, image: Size | undefined, device: Size) => {
138
+ if (image !== undefined && !sameShape(image, device)) {
139
+ drop(1);
140
+
141
+ return;
142
+ }
143
+ expected ??= device;
144
+ if (sameSize(device, expected)) {
145
+ end();
146
+ deliver(frame, timestamp);
147
+
148
+ return;
149
+ }
150
+ if (run !== undefined && !sameSize(run.device, device)) end();
151
+ if (run === undefined) {
152
+ run = { device, since: now(), frames: [] };
153
+ Queue.offerUnsafe(wake, undefined);
154
+ }
155
+ run.frames.push({ frame, timestamp });
156
+ if (run.frames.length > 16) {
157
+ run.frames.shift();
158
+ drop(1);
159
+ }
160
+ },
161
+ };
162
+ });
@@ -0,0 +1,68 @@
1
+ /** Native frame timing and monotonic evidence across clock recalibration. */
2
+ import type { Clock } from "effect";
3
+
4
+ import { type Estimate, monotonicMillis, toHostTime, uncertaintyAt } from "../../Clock.ts";
5
+ import { BrowserPaint, Frame } from "../../Frame.ts";
6
+ import type { NativeFrame, Transport } from "./transport.ts";
7
+
8
+ /**
9
+ * A native frame as readers get it: its picture's size, else the capture's or its device's, and
10
+ * its paint mapped by the browser's newest estimate, which may be older than the frame and says
11
+ * less about later paint.
12
+ */
13
+ export const timed = (
14
+ options: {
15
+ readonly id: string;
16
+ readonly clock: Clock.Clock;
17
+ readonly imageSize: (
18
+ data: Uint8Array,
19
+ ) => { readonly width: number; readonly height: number } | undefined;
20
+ readonly latest: () => Estimate | undefined;
21
+ },
22
+ native: NativeFrame,
23
+ timestamp: number,
24
+ generation: {
25
+ readonly id: number;
26
+ readonly sequence: number;
27
+ readonly calibration: Estimate;
28
+ readonly size: { readonly width: number; readonly height: number } | null;
29
+ readonly transport: Pick<Transport, "frameTag">;
30
+ },
31
+ data: Uint8Array,
32
+ ) => {
33
+ const image = options.imageSize(data);
34
+ const device = { width: native.metadata.deviceWidth, height: native.metadata.deviceHeight };
35
+ const size = image ?? generation.size ?? device;
36
+ const estimate = options.latest() ?? generation.calibration;
37
+ const hostTime = toHostTime(estimate, timestamp);
38
+
39
+ const frame = new Frame({
40
+ page: options.id,
41
+ capture: { generation: generation.id, sequence: generation.sequence },
42
+ data,
43
+ timing: new BrowserPaint({
44
+ timestamp,
45
+ hostTime,
46
+ uncertaintyMillis: uncertaintyAt(estimate, hostTime),
47
+ }),
48
+ receivedAt: monotonicMillis(options.clock),
49
+ width: size.width,
50
+ height: size.height,
51
+ ...generation.transport.frameTag(),
52
+ });
53
+
54
+ return { frame, image, device };
55
+ };
56
+
57
+ /** Clamp only the estimate's centre, widening its interval by the correction. */
58
+ export const orderedFrame = (frame: Frame, previous: number): Frame =>
59
+ frame.hostTime < previous && frame.timing._tag === "BrowserPaint"
60
+ ? new Frame({
61
+ ...frame,
62
+ timing: new BrowserPaint({
63
+ ...frame.timing,
64
+ hostTime: previous,
65
+ uncertaintyMillis: frame.timing.uncertaintyMillis + previous - frame.hostTime,
66
+ }),
67
+ })
68
+ : frame;
@@ -4,11 +4,13 @@
4
4
  * one call where a device pixel is a CSS pixel and nothing is cropped, and two otherwise, unless
5
5
  * Playwright emulates the viewport. The page's first clipped picture also holds the screen it reads.
6
6
  */
7
- import { Duration, Effect, Option, Schedule, Schema } from "effect";
7
+ import { Duration, Effect, Option, Result, Schedule, Schema } from "effect";
8
+ import { Base64 } from "effect/encoding";
8
9
 
9
10
  import { BrowserError, Failed, InvalidRequest } from "../../BrowserError.ts";
11
+ import * as BrowserClock from "../../Clock.ts";
10
12
  import { Frame, Image, Screenshot } from "../../Frame.ts";
11
- import type { Point } from "../../Motion.ts";
13
+ import type { Point } from "../../Geometry.ts";
12
14
  import { type FrameOptions, Region, type ScreenshotOptions, Zoom } from "../../Page.ts";
13
15
  import { type Bridge, scriptCall } from "../page/bridge.ts";
14
16
  import {
@@ -19,13 +21,15 @@ import {
19
21
  refuse,
20
22
  undispatched,
21
23
  } from "../page/context.ts";
24
+ import * as Port from "../page/port.ts";
22
25
  import type { Viewport } from "../page/viewport.ts";
23
26
  import * as Capture from "./capture.ts";
24
- import * as BrowserClock from "./clock.ts";
27
+ import { countsKept } from "./counts.ts";
28
+ import type { Size } from "./dimensions.ts";
25
29
  import * as Transport from "./transport.ts";
26
30
 
27
31
  /** Read a JPEG's dimensions from its start-of-frame marker. */
28
- export const jpegSize = (bytes: Uint8Array): Capture.Size | undefined => {
32
+ export const jpegSize = (bytes: Uint8Array): Size | undefined => {
29
33
  let offset = 2;
30
34
 
31
35
  while (offset + 9 < bytes.length) {
@@ -45,7 +49,7 @@ export const jpegSize = (bytes: Uint8Array): Capture.Size | undefined => {
45
49
  };
46
50
 
47
51
  /** Read a PNG's dimensions from its header chunk. */
48
- export const pngSize = (bytes: Uint8Array): Capture.Size | undefined => {
52
+ export const pngSize = (bytes: Uint8Array): Size | undefined => {
49
53
  if (bytes.length < 24 || bytes[1] !== 0x50 || bytes[2] !== 0x4e || bytes[3] !== 0x47)
50
54
  return undefined;
51
55
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -56,6 +60,9 @@ export const pngSize = (bytes: Uint8Array): Capture.Size | undefined => {
56
60
  /** The format a new picture is taken in. */
57
61
  export type Format = "jpeg" | "png";
58
62
 
63
+ // A picture's pixels: CSS pixels, or the screen's own.
64
+ type Scale = NonNullable<ScreenshotOptions["scale"]>;
65
+
59
66
  // The part of `Page.getLayoutMetrics` a clip needs: the visual viewport's place in the document and
60
67
  // its pinch scale, and the content's size in device and CSS pixels, whose ratio is the device's.
61
68
  const LayoutMetrics = Schema.Struct({
@@ -225,34 +232,54 @@ const camera = (
225
232
  operation: string,
226
233
  format: Format,
227
234
  quality: number,
228
- clip?: Capture.Size & Point & { readonly scale: number },
235
+ clip?: Size & Point & { readonly scale: number },
229
236
  ) =>
230
237
  take(operation, format, () =>
231
238
  send("Page.captureScreenshot", {
232
239
  format,
233
240
  ...(format === "jpeg" ? { quality } : {}),
234
241
  ...(clip === undefined ? {} : { clip }),
235
- }).then(({ data }) => Buffer.from(data, "base64")),
242
+ }).then(({ data }) => {
243
+ const decoded = Base64.decode(data);
244
+
245
+ return Result.isSuccess(decoded)
246
+ ? decoded.success
247
+ : Promise.reject(new Error("the browser sent invalid base64 picture data"));
248
+ }),
236
249
  );
237
250
 
238
251
  // Playwright's promise owns native restoration; the outer Effect alone bounds callers.
239
- const emulatedShot = (operation: string, format: Format, quality: number, crop?: Region) =>
252
+ const emulatedShot = (
253
+ operation: string,
254
+ format: Format,
255
+ quality: number,
256
+ scale: Scale,
257
+ crop?: Region,
258
+ ) =>
240
259
  take(operation, format, () =>
241
260
  playwright.screenshot({
242
261
  type: format,
243
262
  ...(format === "jpeg" ? { quality } : {}),
244
- scale: "css",
263
+ scale,
245
264
  timeout: 0,
246
265
  ...(crop === undefined ? {} : { clip: crop }),
247
266
  }),
248
267
  );
249
268
 
250
- return (operation: string, quality: number, crop?: Region, format: Format = "jpeg") =>
269
+ return (
270
+ operation: string,
271
+ quality: number,
272
+ crop?: Region,
273
+ format: Format = "jpeg",
274
+ pixels: Scale = "css",
275
+ ) =>
251
276
  Effect.gen(function* () {
252
277
  const known = viewport.knownViewport();
253
278
  let whole: Image | undefined;
254
279
 
255
- if (crop === undefined && ratio === 1) {
280
+ // A copy without a clip can come at the viewport's CSS size whatever the device scale
281
+ // factor, so a picture in device pixels always takes a clip.
282
+ if (crop === undefined && ratio === 1 && pixels === "css") {
256
283
  whole = yield* shot(operation, format, quality);
257
284
  if (whole.width === known?.width && whole.height === known.height) return whole;
258
285
  }
@@ -262,7 +289,7 @@ const camera = (
262
289
  if (emulated !== null) {
263
290
  if (whole !== undefined) ratio = whole.width / emulated.width;
264
291
 
265
- return yield* emulatedShot(operation, format, quality, crop);
292
+ return yield* emulatedShot(operation, format, quality, pixels, crop);
266
293
  }
267
294
 
268
295
  const [metrics] = yield* native(operation, () => send("Page.getLayoutMetrics")).pipe(
@@ -290,7 +317,7 @@ const camera = (
290
317
  y: pageY + rect.y,
291
318
  width: Math.floor(rect.width / scale + 1e-3),
292
319
  height: Math.floor(rect.height / scale + 1e-3),
293
- scale: scale / ratio,
320
+ scale: pixels === "device" ? scale : scale / ratio,
294
321
  });
295
322
  }).pipe(capture.excluding, within(operation));
296
323
  };
@@ -355,10 +382,10 @@ export const make = Effect.fnUntraced(function* (
355
382
  // only a browser with no estimate yet needs this page's renderer to answer.
356
383
  const capture = yield* Capture.make({
357
384
  id,
358
- transport:
359
- page.capture === undefined
360
- ? Effect.succeed(Transport.own(page, bridge))
361
- : Transport.apart(page, bridge, page.capture, error, yield* Effect.scope),
385
+ transport: (page.capture === undefined
386
+ ? Effect.succeed(Transport.own(page, bridge))
387
+ : Transport.apart(page, bridge, page.capture, error, yield* Effect.scope)
388
+ ).pipe(Effect.provideService(Port.Current, yield* Port.Current)),
362
389
  clock,
363
390
  // A capture starts once the page's own session keeps it painting behind other tabs, which a
364
391
  // renderer stuck in a script never confirms, and with the browser's clock mapped. Only a
@@ -400,17 +427,24 @@ export const make = Effect.fnUntraced(function* (
400
427
  options.clip,
401
428
  options.quality,
402
429
  options.format,
430
+ options.scale,
403
431
  ]),
404
432
  Effect.gen(function* () {
405
- // Screencast frames are JPEGs, so a PNG is always new.
433
+ // A reused frame is a JPEG of the viewport's CSS size, so a PNG or a device picture is new.
406
434
  const reused =
407
- options.clip === undefined && options.format !== "png"
435
+ options.clip === undefined && options.format !== "png" && options.scale !== "device"
408
436
  ? yield* reusable("screenshot", { maxAge: options.maxAge, after: "input" })
409
437
  : Option.none<Frame>();
410
438
 
411
439
  const image = Option.isSome(reused)
412
440
  ? reused.value.image
413
- : yield* picture("screenshot", options.quality ?? 80, options.clip, options.format);
441
+ : yield* picture(
442
+ "screenshot",
443
+ options.quality ?? 80,
444
+ options.clip,
445
+ options.format,
446
+ options.scale,
447
+ );
414
448
 
415
449
  yield* Effect.annotateCurrentSpan({ source: sourceOf(reused), bytes: image.data.length });
416
450
 
@@ -464,7 +498,7 @@ export const make = Effect.fnUntraced(function* (
464
498
  owned,
465
499
  );
466
500
 
467
- const zoom = (requested: Region) =>
501
+ const zoom = (requested: Region, options: Pick<ScreenshotOptions, "scale"> = {}) =>
468
502
  lane
469
503
  .read("zoom")(
470
504
  Effect.gen(function* () {
@@ -479,7 +513,7 @@ export const make = Effect.fnUntraced(function* (
479
513
 
480
514
  if (region.x + region.width > size.width || region.y + region.height > size.height)
481
515
  return yield* refuse("zoom", "the crop must fit entirely within the viewport");
482
- const image = yield* picture("zoom", 80, region);
516
+ const image = yield* picture("zoom", 80, region, "jpeg", options.scale);
483
517
 
484
518
  return new Zoom({ page: id, region, image });
485
519
  }).pipe(within("zoom")),
@@ -490,7 +524,7 @@ export const make = Effect.fnUntraced(function* (
490
524
  if (options.window === undefined) return capture.stats();
491
525
  const millis = millisOf(options.window);
492
526
 
493
- return millis > 0 && millis <= Duration.toMillis(Capture.countsKept)
527
+ return millis > 0 && millis <= Duration.toMillis(countsKept)
494
528
  ? capture.stats(millis)
495
529
  : refuse("captureStats", "window must be over zero and at most a minute");
496
530
  };
@@ -2,7 +2,7 @@
2
2
  import { Cause, Clock, Duration, Effect, Exit, Fiber } from "effect";
3
3
 
4
4
  import type { BrowserError } from "../../BrowserError.ts";
5
- import * as Replies from "../input/replies.ts";
5
+ import * as Replies from "../page/replies.ts";
6
6
 
7
7
  const deadline = Duration.seconds(2);
8
8
 
@@ -0,0 +1,26 @@
1
+ /** The capture's one lifecycle: retirement is absorbing and retains its first failure. */
2
+ import type { BrowserError } from "../../BrowserError.ts";
3
+
4
+ export type State =
5
+ | { readonly _tag: "Capturing" }
6
+ | { readonly _tag: "Paused" }
7
+ | { readonly _tag: "Stopped"; readonly failure: BrowserError | undefined };
8
+
9
+ export type Input =
10
+ | { readonly _tag: "Pause" | "Resume" }
11
+ | { readonly _tag: "Stop"; readonly failure?: BrowserError | undefined };
12
+
13
+ export const initial: State = { _tag: "Capturing" };
14
+
15
+ export const step = (state: State, input: Input): State => {
16
+ if (input._tag === "Stop")
17
+ return {
18
+ _tag: "Stopped",
19
+ failure: state._tag === "Stopped" ? (state.failure ?? input.failure) : input.failure,
20
+ };
21
+ if (state._tag === "Stopped") return state;
22
+
23
+ return { _tag: input._tag === "Pause" ? "Paused" : "Capturing" };
24
+ };
25
+
26
+ export const failureOf = (state: State) => (state._tag === "Stopped" ? state.failure : undefined);
@@ -10,12 +10,13 @@
10
10
  * session. They are numbered as the page's own session counts documents: a commit it has counted
11
11
  * keeps its number, and one the capture connection sees first takes the next, until it is counted.
12
12
  */
13
- import { Effect, Exit, Option, Schema, Scope } from "effect";
13
+ import { Effect, Exit, Option, Schema, Scope, Semaphore } from "effect";
14
14
 
15
15
  import type { CaptureSource } from "../../Browser.ts";
16
16
  import { type BrowserError, Failed } from "../../BrowserError.ts";
17
17
  import { type Bridge, Commit, commitOf, mainFrame, MainFrameEvent } from "../page/bridge.ts";
18
18
  import { type PageContext, undispatched } from "../page/context.ts";
19
+ import * as Port from "../page/port.ts";
19
20
 
20
21
  /** Where a capture's screencast runs. Its calls never throw: a failure rejects. */
21
22
  export interface Transport {
@@ -58,7 +59,19 @@ export const own = (page: PageContext, bridge: Bridge): Transport => {
58
59
  acknowledge: (frame) => send("Page.screencastFrameAck", { sessionId: frame }),
59
60
  stop: () => send("Page.stopScreencast"),
60
61
  sync: () => Promise.resolve(),
61
- listen: ({ frame }) => {
62
+ listen: (on) => {
63
+ const frame = (value: unknown) =>
64
+ Option.match(Schema.decodeUnknownOption(ScreencastFrame)(value), {
65
+ onNone: () =>
66
+ on.lost(
67
+ undispatched(
68
+ "screencast",
69
+ new Failed({ detail: "the page connection sent an unreadable screencast frame" }),
70
+ ),
71
+ ),
72
+ onSome: on.frame,
73
+ });
74
+
62
75
  page.cdp.on("Page.screencastFrame", frame);
63
76
 
64
77
  return () => {
@@ -135,6 +148,7 @@ export const apart = (
135
148
  error: (cause: unknown) => BrowserError,
136
149
  pageScope: Scope.Scope,
137
150
  ): Effect.Effect<Transport, BrowserError> => {
151
+ const lock = Semaphore.makeUnsafe(1);
138
152
  let state: State = { _tag: "Detached" };
139
153
  let listening: Parameters<Transport["listen"]>[0] | undefined;
140
154
  const latest = (): State => state;
@@ -172,7 +186,10 @@ export const apart = (
172
186
  end(scope, error(new Error("Target page has been closed")));
173
187
  };
174
188
 
175
- const send = yield* source.attach(page.id, { event, lost: (lost) => end(scope, lost) });
189
+ const send = yield* Port.openCapture(page.id, source, {
190
+ event,
191
+ lost: (lost) => end(scope, lost),
192
+ });
176
193
 
177
194
  // Tracked from the frame tree's answer on, set as it arrives so that no commit after it is
178
195
  // missed.
@@ -239,5 +256,5 @@ export const apart = (
239
256
  }
240
257
  });
241
258
 
242
- return current;
259
+ return lock.withPermits(1)(current);
243
260
  };
@@ -1,29 +1,15 @@
1
1
  /**
2
2
  * In the page: a control's states and value as the outline shows them, and as a value; the elements a CSS selector scopes a
3
- * read to; and a condition `Page.waitFor` waits for. See `names.inpage.ts` for what a page-side part
3
+ * read to. See `names.inpage.ts` for what a page-side part
4
4
  * may use.
5
5
  */
6
- import { Schema } from "effect";
7
-
8
6
  import type { Control } from "../../Snapshot.ts";
9
7
  import type { Names } from "./names.inpage.ts";
10
8
  import type { Subjects } from "./subjects.inpage.ts";
11
9
  import type { Texts } from "./text.inpage.ts";
12
- import type { Walk } from "./walk.inpage.ts";
13
-
14
- /** What `waitUntil` waits for, as `Page.waitFor` asks it. */
15
- export interface ConditionRequest {
16
- readonly selector: string | null;
17
- readonly text: string | null;
18
- readonly state: "visible" | "hidden" | "enabled";
19
- }
20
-
21
- /** Whether the condition held by the deadline, or why the selector is not CSS. */
22
- export type ConditionResult = typeof ConditionResultSchema.Encoded;
23
10
 
24
- export const controls = (names: Names, walked: Walk, subjects: Subjects, texts: Texts) => {
25
- const { clean, isDisabled, isHtml, isInput, isSelect, isTextArea, refFor, textOf } = names;
26
- const { visible } = walked;
11
+ export const controls = (names: Names, subjects: Subjects, texts: Texts) => {
12
+ const { clean, isInput, isSelect, isTextArea, refFor, textEntry } = names;
27
13
  const { stateOf } = subjects;
28
14
  const { shown } = texts;
29
15
 
@@ -55,9 +41,6 @@ export const controls = (names: Names, walked: Walk, subjects: Subjects, texts:
55
41
  return value === undefined || value === "" ? "" : ` value=${JSON.stringify(clean(value, 80))}`;
56
42
  };
57
43
 
58
- // Inputs that take no typed text.
59
- const untyped = ["button", "reset", "submit", "image", "checkbox", "radio", "file", "range"];
60
-
61
44
  /** A control as a value, as its outline line shows it. */
62
45
  const controlOf = (element: Element, role: string | null, kind: string, name: string) => {
63
46
  const { disabled, checked } = stateOf(element, role);
@@ -70,10 +53,7 @@ export const controls = (names: Names, walked: Walk, subjects: Subjects, texts:
70
53
  ? clean(shown(element, true), 200)
71
54
  : "";
72
55
 
73
- const editable =
74
- isTextArea(element) ||
75
- (isInput(element) && !untyped.includes(element.type)) ||
76
- (isHtml(element) && element.isContentEditable);
56
+ const editable = textEntry(element);
77
57
 
78
58
  const control: typeof Control.Encoded = {
79
59
  ref: refFor(element),
@@ -114,52 +94,7 @@ export const controls = (names: Names, walked: Walk, subjects: Subjects, texts:
114
94
  );
115
95
  };
116
96
 
117
- // Whether the condition holds now: what the selector matches, or the body, and shows, with the
118
- // text when one is asked, case and all. A document has no body until its parser reaches one.
119
- const holds = (request: ConditionRequest): ConditionResult => {
120
- const roots =
121
- request.selector === null ? [document.body].filter(Boolean) : rootsOf(request.selector);
122
-
123
- if ("invalid" in roots) return roots;
124
- const text = request.text === null ? null : clean(request.text, Infinity);
125
-
126
- const showing = roots.filter(
127
- (element) =>
128
- visible(element) && (text === null || clean(textOf(element), Infinity).includes(text)),
129
- );
130
-
131
- return {
132
- met:
133
- request.state === "hidden"
134
- ? showing.length === 0
135
- : request.state === "enabled"
136
- ? showing.some((element) => !isDisabled(element))
137
- : showing.length > 0,
138
- };
139
- };
140
-
141
- // Looks every 100 ms until the condition holds or the deadline passes.
142
- const waitUntil = async (request: ConditionRequest, millis: number) => {
143
- const until = performance.now() + millis;
144
-
145
- for (;;) {
146
- const result = holds(request);
147
- const left = until - performance.now();
148
-
149
- if ("invalid" in result || result.met || left <= 0) return result;
150
- const { promise, resolve } = Promise.withResolvers<void>();
151
-
152
- setTimeout(resolve, Math.min(100, left));
153
- await promise;
154
- }
155
- };
156
-
157
- return { controlOf, rootsOf, states, valueOf, waitUntil };
97
+ return { controlOf, rootsOf, states, valueOf };
158
98
  };
159
99
 
160
100
  export type Controls = ReturnType<typeof controls>;
161
-
162
- export const ConditionResultSchema = Schema.Union([
163
- Schema.Struct({ met: Schema.Boolean }),
164
- Schema.Struct({ invalid: Schema.String }),
165
- ]);