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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +130 -159
  2. package/dist/Action-24sLOubi.d.mts +110 -0
  3. package/dist/Action.d.mts +2 -0
  4. package/dist/Action.mjs +141 -0
  5. package/dist/Action.mjs.map +1 -0
  6. package/dist/ActionPort.d.mts +15 -0
  7. package/dist/ActionPort.mjs +101 -0
  8. package/dist/ActionPort.mjs.map +1 -0
  9. package/dist/Browser-Cq2K1FEA.mjs +4075 -0
  10. package/dist/Browser-Cq2K1FEA.mjs.map +1 -0
  11. package/dist/{Browser-CiXHT1yO.d.mts → Browser-wZhwZSlG.d.mts} +51 -13
  12. package/dist/Browser.d.mts +2 -2
  13. package/dist/Browser.mjs +1 -1
  14. package/dist/{BrowserError-Coy7EW1N.d.mts → BrowserError-BlcmLVzn.d.mts} +22 -7
  15. package/dist/BrowserError.d.mts +2 -2
  16. package/dist/BrowserError.mjs +46 -9
  17. package/dist/BrowserError.mjs.map +1 -1
  18. package/dist/{BrowserEvent-dq6FRT8w.d.mts → BrowserEvent-lLqJ3GJS.d.mts} +93 -37
  19. package/dist/BrowserEvent.d.mts +2 -2
  20. package/dist/BrowserEvent.mjs +29 -24
  21. package/dist/BrowserEvent.mjs.map +1 -1
  22. package/dist/{Change-DqING3tr.d.mts → Change-Ba7INmay.d.mts} +4 -6
  23. package/dist/Change.d.mts +2 -2
  24. package/dist/Change.mjs +97 -2
  25. package/dist/Change.mjs.map +1 -0
  26. package/dist/Clock.d.mts +57 -0
  27. package/dist/Clock.mjs +80 -0
  28. package/dist/Clock.mjs.map +1 -0
  29. package/dist/{Frame-DkNdjjjr.d.mts → Frame-UEH2hO5T.d.mts} +10 -3
  30. package/dist/Frame.d.mts +2 -2
  31. package/dist/Frame.mjs +10 -2
  32. package/dist/Frame.mjs.map +1 -1
  33. package/dist/{Motion-DND6I-64.d.mts → Geometry-DJx9qrYy.d.mts} +7 -10
  34. package/dist/Geometry.d.mts +2 -0
  35. package/dist/Geometry.mjs +32 -0
  36. package/dist/Geometry.mjs.map +1 -0
  37. package/dist/Matching.d.mts +37 -0
  38. package/dist/Matching.mjs +72 -0
  39. package/dist/Matching.mjs.map +1 -0
  40. package/dist/Page-BF5izr8R.mjs +795 -0
  41. package/dist/Page-BF5izr8R.mjs.map +1 -0
  42. package/dist/{Page-ku6j5t-v.d.mts → Page-CvsOEorc.d.mts} +158 -185
  43. package/dist/Page.d.mts +2 -2
  44. package/dist/Page.mjs +1 -1
  45. package/dist/Released-tURbFmal.d.mts +15 -0
  46. package/dist/{Snapshot-B34hZ4Jl.d.mts → Snapshot-CtBVOtuu.d.mts} +6 -1
  47. package/dist/Snapshot.d.mts +1 -1
  48. package/dist/Snapshot.mjs.map +1 -1
  49. package/dist/Stillness-CNlvayIo.mjs +136 -0
  50. package/dist/Stillness-CNlvayIo.mjs.map +1 -0
  51. package/dist/Style-AO4V7Czt.mjs +357 -0
  52. package/dist/Style-AO4V7Czt.mjs.map +1 -0
  53. package/dist/Style.d.mts +72 -0
  54. package/dist/Style.mjs +2 -0
  55. package/dist/Url.d.mts +26 -0
  56. package/dist/Url.mjs +74 -0
  57. package/dist/Url.mjs.map +1 -0
  58. package/dist/Window-CMddGMt1.d.mts +34 -0
  59. package/dist/Window.d.mts +2 -0
  60. package/dist/Window.mjs +35 -0
  61. package/dist/Window.mjs.map +1 -0
  62. package/dist/{cdp-DL7XfEj5.d.mts → connection-2KHI4_KN.d.mts} +4 -4
  63. package/dist/{cdp-BMpYMWYe.mjs → connection-BTeO0Hiz.mjs} +5 -6
  64. package/dist/connection-BTeO0Hiz.mjs.map +1 -0
  65. package/dist/index.d.mts +15 -18
  66. package/dist/index.mjs +11 -15
  67. package/dist/moment/Moment.d.mts +86 -0
  68. package/dist/{Moment.mjs → moment/Moment.mjs} +44 -38
  69. package/dist/moment/Moment.mjs.map +1 -0
  70. package/dist/{Plan-DJ4hEEna.d.mts → plan/index.d.mts} +169 -64
  71. package/dist/{Plan-BG1WifW2.mjs → plan/index.mjs} +122 -199
  72. package/dist/plan/index.mjs.map +1 -0
  73. package/dist/{Policy-BGWjbqCl.d.mts → policy/Policy.d.mts} +16 -20
  74. package/dist/{Policy.mjs → policy/Policy.mjs} +11 -21
  75. package/dist/policy/Policy.mjs.map +1 -0
  76. package/dist/presentation/Motion.d.mts +12 -0
  77. package/dist/{Motion.mjs → presentation/Motion.mjs} +4 -27
  78. package/dist/presentation/Motion.mjs.map +1 -0
  79. package/dist/presentation/Presentation.d.mts +30 -0
  80. package/dist/presentation/Presentation.mjs +105 -0
  81. package/dist/presentation/Presentation.mjs.map +1 -0
  82. package/dist/{Stage-NHp8N81k.d.mts → presentation/Stage.d.mts} +12 -15
  83. package/dist/{Stage.mjs → presentation/Stage.mjs} +68 -76
  84. package/dist/presentation/Stage.mjs.map +1 -0
  85. package/dist/presentation/feed.d.mts +20 -0
  86. package/dist/presentation/feed.mjs +18 -0
  87. package/dist/presentation/feed.mjs.map +1 -0
  88. package/dist/providers/Cdp.d.mts +9 -0
  89. package/dist/{Cdp.mjs → providers/Cdp.mjs} +3 -8
  90. package/dist/providers/Cdp.mjs.map +1 -0
  91. package/dist/{Chromium.d.mts → providers/Chromium.d.mts} +6 -7
  92. package/dist/{Chromium.mjs → providers/Chromium.mjs} +6 -15
  93. package/dist/providers/Chromium.mjs.map +1 -0
  94. package/dist/providers/Released.d.mts +2 -0
  95. package/dist/providers/Released.mjs +12 -0
  96. package/dist/providers/Released.mjs.map +1 -0
  97. package/dist/stillness/Stillness.d.mts +12 -0
  98. package/dist/stillness/Stillness.mjs +2 -0
  99. package/dist/supervisor/Supervisor.d.mts +104 -0
  100. package/dist/supervisor/Supervisor.mjs +513 -0
  101. package/dist/supervisor/Supervisor.mjs.map +1 -0
  102. package/dist/testing/index.d.mts +337 -0
  103. package/dist/testing/index.mjs +515 -0
  104. package/dist/testing/index.mjs.map +1 -0
  105. package/dist/workerd/Cdp.d.mts +8 -3
  106. package/dist/workerd/Cdp.mjs +2 -7
  107. package/dist/workerd/Cdp.mjs.map +1 -1
  108. package/package.json +86 -36
  109. package/src/Action.ts +127 -0
  110. package/src/ActionPort.ts +128 -0
  111. package/src/Browser.ts +352 -201
  112. package/src/BrowserError.ts +63 -6
  113. package/src/BrowserEvent.ts +26 -25
  114. package/src/Change.ts +0 -2
  115. package/src/{internal/pictures/clock.ts → Clock.ts} +17 -6
  116. package/src/Frame.ts +14 -0
  117. package/src/Geometry.ts +48 -0
  118. package/src/{internal/reading/match.inpage.ts → Matching.ts} +34 -4
  119. package/src/Page.ts +111 -92
  120. package/src/Snapshot.ts +5 -0
  121. package/src/{internal/input/style.ts → Style.ts} +121 -14
  122. package/src/Window.ts +30 -0
  123. package/src/index.ts +15 -6
  124. package/src/internal/input/actions.ts +61 -119
  125. package/src/internal/input/dispatch.ts +3 -3
  126. package/src/internal/input/gate.ts +21 -18
  127. package/src/internal/input/guard.inpage.ts +25 -58
  128. package/src/internal/input/guard.ts +11 -20
  129. package/src/internal/input/keyboard.ts +12 -3
  130. package/src/internal/input/perform.ts +78 -60
  131. package/src/internal/input/pointer.ts +4 -2
  132. package/src/internal/input/settle.ts +7 -5
  133. package/src/internal/input/targets.inpage.ts +1 -1
  134. package/src/internal/input/targets.ts +4 -9
  135. package/src/internal/page/bridge.ts +209 -113
  136. package/src/internal/page/context.ts +12 -59
  137. package/src/internal/page/dialogs.ts +58 -0
  138. package/src/internal/page/lane.ts +14 -15
  139. package/src/internal/page/navigation.ts +50 -42
  140. package/src/internal/page/openings.ts +11 -5
  141. package/src/internal/page/page.ts +44 -81
  142. package/src/internal/page/port.ts +125 -0
  143. package/src/internal/{input → page}/replies.ts +1 -1
  144. package/src/internal/page/request-owner.ts +269 -0
  145. package/src/internal/page/requests.ts +357 -0
  146. package/src/internal/page/scripts.ts +124 -0
  147. package/src/internal/pictures/capture.ts +255 -332
  148. package/src/internal/pictures/dimensions.ts +162 -0
  149. package/src/internal/pictures/frame.ts +68 -0
  150. package/src/internal/pictures/pictures.ts +57 -23
  151. package/src/internal/pictures/quiescence.ts +1 -1
  152. package/src/internal/pictures/state.ts +26 -0
  153. package/src/internal/pictures/transport.ts +21 -4
  154. package/src/internal/reading/controls.inpage.ts +5 -70
  155. package/src/internal/reading/expect.inpage.ts +13 -17
  156. package/src/internal/reading/names.inpage.ts +89 -45
  157. package/src/internal/reading/outline.inpage.ts +6 -7
  158. package/src/internal/reading/reading.ts +144 -176
  159. package/src/internal/reading/ready.inpage.ts +6 -17
  160. package/src/internal/reading/ready.ts +13 -135
  161. package/src/internal/reading/subjects.inpage.ts +83 -43
  162. package/src/internal/reading/walk.inpage.ts +33 -13
  163. package/src/internal/timeline/changes.ts +55 -6
  164. package/src/internal/timeline/events.ts +15 -5
  165. package/src/internal/timeline/history.inpage.ts +1 -1
  166. package/src/internal/timeline/record.inpage.ts +4 -1
  167. package/src/internal/timeline/window.ts +2 -1
  168. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  169. package/src/{internal/timeline → moment}/words.ts +2 -2
  170. package/src/{internal/reading → plan}/choose.ts +3 -3
  171. package/src/plan/data.ts +117 -0
  172. package/src/plan/execute.ts +411 -0
  173. package/src/plan/index.ts +36 -0
  174. package/src/plan/record.ts +71 -0
  175. package/src/plan/targets.ts +71 -0
  176. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  177. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  178. package/src/presentation/Presentation.ts +176 -0
  179. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  180. package/src/presentation/feed.ts +21 -0
  181. package/src/{Cdp.ts → providers/Cdp.ts} +2 -2
  182. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  183. package/src/providers/Released.ts +13 -0
  184. package/src/{internal/cdp.ts → providers/connection.ts} +2 -2
  185. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +1 -1
  186. package/src/stillness/Stillness.ts +166 -0
  187. package/src/supervisor/Supervisor.ts +170 -0
  188. package/src/supervisor/contract.ts +105 -0
  189. package/src/supervisor/lifecycle.ts +272 -0
  190. package/src/supervisor/runtime.ts +234 -0
  191. package/src/testing/TestBrowser.ts +115 -0
  192. package/src/testing/TestPage.ts +10 -0
  193. package/src/testing/evidence.ts +154 -0
  194. package/src/testing/index.ts +3 -0
  195. package/src/testing/model.ts +222 -0
  196. package/src/testing/page.ts +360 -0
  197. package/src/workerd/Cdp.ts +2 -2
  198. package/dist/Browser-CxXUjxOp.mjs +0 -619
  199. package/dist/Browser-CxXUjxOp.mjs.map +0 -1
  200. package/dist/Cdp-CzCRnMlM.d.mts +0 -10
  201. package/dist/Cdp.d.mts +0 -11
  202. package/dist/Cdp.mjs.map +0 -1
  203. package/dist/Change-DNvztNLu.mjs +0 -138
  204. package/dist/Change-DNvztNLu.mjs.map +0 -1
  205. package/dist/Chromium.mjs.map +0 -1
  206. package/dist/Expect-u3P_ENLX.d.mts +0 -62
  207. package/dist/Expect.d.mts +0 -2
  208. package/dist/Expect.mjs +0 -114
  209. package/dist/Expect.mjs.map +0 -1
  210. package/dist/Moment.d.mts +0 -2
  211. package/dist/Moment.mjs.map +0 -1
  212. package/dist/Motion.d.mts +0 -2
  213. package/dist/Motion.mjs.map +0 -1
  214. package/dist/Page-BP02bmNv.mjs +0 -264
  215. package/dist/Page-BP02bmNv.mjs.map +0 -1
  216. package/dist/Plan-BG1WifW2.mjs.map +0 -1
  217. package/dist/Plan.d.mts +0 -2
  218. package/dist/Plan.mjs +0 -2
  219. package/dist/Policy.d.mts +0 -2
  220. package/dist/Policy.mjs.map +0 -1
  221. package/dist/Presentation-DxVikn9_.d.mts +0 -48
  222. package/dist/Presentation.d.mts +0 -2
  223. package/dist/Presentation.mjs +0 -118
  224. package/dist/Presentation.mjs.map +0 -1
  225. package/dist/Stage.d.mts +0 -2
  226. package/dist/Stage.mjs.map +0 -1
  227. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  228. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  229. package/dist/Supervisor-CfRxbaso.d.mts +0 -317
  230. package/dist/Supervisor.d.mts +0 -2
  231. package/dist/Supervisor.mjs +0 -2
  232. package/dist/cdp-BMpYMWYe.mjs.map +0 -1
  233. package/dist/context-EGhOqjNN.mjs +0 -335
  234. package/dist/context-EGhOqjNN.mjs.map +0 -1
  235. package/dist/page-PTM8m5wC.mjs +0 -4057
  236. package/dist/page-PTM8m5wC.mjs.map +0 -1
  237. package/dist/url-Bsp2y55M.mjs +0 -264
  238. package/dist/url-Bsp2y55M.mjs.map +0 -1
  239. package/dist/workerd/index.d.mts +0 -16
  240. package/dist/workerd/index.mjs +0 -17
  241. package/src/Expect.ts +0 -180
  242. package/src/Plan.ts +0 -674
  243. package/src/Presentation.ts +0 -196
  244. package/src/Supervisor.ts +0 -632
  245. package/src/internal/supervisor/lifecycle.ts +0 -484
  246. package/src/workerd/index.ts +0 -17
  247. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  248. /package/src/{internal/pictures → stillness}/utilsBundle.d.ts +0 -0
@@ -6,9 +6,9 @@
6
6
  */
7
7
  import { chromium } from "playwright-core";
8
8
 
9
- import { make } from "./internal/cdp.ts";
9
+ import { make } from "./connection.ts";
10
10
 
11
- export type { Connector, ConnectOptions, Options } from "./internal/cdp.ts";
11
+ export type { Connector, ConnectOptions, Options } from "./connection.ts";
12
12
 
13
13
  /** Connect and open a `Browser` over the endpoint's first context. */
14
14
  export const { open, layer } = make((endpoint, options) =>
@@ -12,9 +12,8 @@
12
12
  import { Effect, Layer } from "effect";
13
13
  import { chromium } from "playwright-core";
14
14
 
15
- import * as Browser from "./Browser.ts";
16
- import { type BrowserError, Failed } from "./BrowserError.ts";
17
- import { reasonOf, undispatched } from "./internal/page/context.ts";
15
+ import * as Browser from "../Browser.ts";
16
+ import { type BrowserError, Failed, reasonOf, undispatched } from "../BrowserError.ts";
18
17
 
19
18
  export interface Options extends Browser.Options {
20
19
  /** Defaults to true. */
@@ -26,8 +25,10 @@ export interface Options extends Browser.Options {
26
25
  * fails and says so.
27
26
  */
28
27
  readonly sandbox?: boolean | undefined;
29
- /** Defaults to 1280x720 CSS pixels at a device scale factor of 1. */
28
+ /** Defaults to 1280x720 CSS pixels. */
30
29
  readonly viewport?: { readonly width: number; readonly height: number } | undefined;
30
+ /** Device pixels per CSS pixel, as a high-density screen has two. Defaults to 1. */
31
+ readonly deviceScaleFactor?: number | undefined;
31
32
  readonly executablePath?: string | undefined;
32
33
  readonly args?: ReadonlyArray<string> | undefined;
33
34
  readonly userAgent?: string | undefined;
@@ -83,18 +84,14 @@ export const open = Effect.fn("Chromium.open")(function* (options: Options = {})
83
84
  try: () =>
84
85
  launched.newContext({
85
86
  viewport: options.viewport ?? { width: 1280, height: 720 },
86
- deviceScaleFactor: 1,
87
+ deviceScaleFactor: options.deviceScaleFactor ?? 1,
87
88
  ...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
88
89
  ...(options.locale === undefined ? {} : { locale: options.locale }),
89
90
  }),
90
91
  catch: failed("launch"),
91
92
  });
92
93
 
93
- return yield* Browser.make(
94
- context,
95
- { id: `chromium-${launched.version()}`, provider: "chromium" },
96
- options,
97
- );
94
+ return yield* Browser.make(context, { provider: "chromium" }, options);
98
95
  });
99
96
 
100
97
  /** A `Browser` Layer that launches Chromium when built and closes it when released. */
@@ -0,0 +1,13 @@
1
+ /** Provider release evidence, independent of supervision or browser implementation. */
2
+ import { Schema } from "effect";
3
+
4
+ /** The provider confirmed the resource ended. */
5
+ export class Settled extends Schema.TaggedClass<Settled>()("Settled", {}) {}
6
+
7
+ /** The resource may still run, and bill, because its end could not be confirmed. */
8
+ export class Unconfirmed extends Schema.TaggedClass<Unconfirmed>()("Unconfirmed", {
9
+ detail: Schema.String,
10
+ }) {}
11
+
12
+ export const Released = Schema.Union([Settled, Unconfirmed]);
13
+ export type Released = typeof Released.Type;
@@ -11,8 +11,8 @@ import type { Browser as PlaywrightBrowser } from "playwright-core";
11
11
 
12
12
  import * as Browser from "../Browser.ts";
13
13
  import * as Errors from "../BrowserError.ts";
14
- import { reasonOf, undispatched } from "./page/context.ts";
15
- import * as Url from "./page/url.ts";
14
+ import { reasonOf, undispatched } from "../BrowserError.ts";
15
+ import * as Url from "../Url.ts";
16
16
 
17
17
  /** The runtime connector receives the bound and cancellation signal owned by the opening scope. */
18
18
  export interface ConnectOptions {
@@ -13,7 +13,7 @@
13
13
  /// <reference path="./utilsBundle.d.ts" />
14
14
  import { jpegjs } from "playwright-core/lib/utilsBundle";
15
15
 
16
- import type { Frame } from "../../Frame.ts";
16
+ import type { Frame } from "../Frame.ts";
17
17
 
18
18
  /** A decoded frame: RGBA, `width` pixels a row. */
19
19
  export type Picture = ReturnType<typeof jpegjs.decode>;
@@ -0,0 +1,166 @@
1
+ /** Screen and foreground stillness over the public page capture and owning clock. */
2
+ import { Clock, Duration, Effect, Option, Schedule, Stream } from "effect";
3
+
4
+ import { Failed, refuse, Timeout, undispatched } from "../BrowserError.ts";
5
+ import { monotonicMillis } from "../Clock.ts";
6
+ import type { Frame } from "../Frame.ts";
7
+ import type { Page } from "../Page.ts";
8
+ import * as Motion from "./Pixels.ts";
9
+
10
+ export interface Options {
11
+ readonly still?: "screen" | "content" | "foreground" | undefined;
12
+ readonly quietMillis: number;
13
+ readonly timeout?: Duration.Input | undefined;
14
+ }
15
+
16
+ const observe = (page: Page, options: Options, timeout: Duration.Duration) =>
17
+ Effect.gen(function* () {
18
+ const now = () => monotonicMillis(page.clock);
19
+ const deadline = now() + Duration.toMillis(timeout);
20
+
21
+ const settled = () =>
22
+ page.ready({
23
+ quietMillis: options.quietMillis,
24
+ timeout: Duration.millis(Math.max(0, deadline - now())),
25
+ });
26
+
27
+ // A capture the wait starts sends its first frame late, over half a second from a hosted
28
+ // browser, so the spell counts from that frame (#202); Chrome sends one as a capture starts,
29
+ // even of a still page.
30
+ const quiet = (millis: number) =>
31
+ Effect.gen(function* () {
32
+ const capture = yield* page.capture();
33
+
34
+ const foreground = options.still === "foreground";
35
+ let counts = yield* capture.stats();
36
+ let stirred = now();
37
+ let reference: Motion.Picture | undefined;
38
+
39
+ const decoded = (frame: Frame) =>
40
+ Effect.try({
41
+ try: () => Motion.picture(frame),
42
+ catch: (error) =>
43
+ undispatched("ready", new Failed({ detail: `no picture: ${String(error)}` })),
44
+ });
45
+
46
+ // The background: what moved in up to eight frames of the document's 1.5 s before its
47
+ // latest input, as far back as the capture keeps them.
48
+ const inputAt =
49
+ (yield* page.recentEvents).findLast((event) => event._tag === "Action")?.startedAt ??
50
+ Number.NEGATIVE_INFINITY;
51
+
52
+ const document = (yield* page.state).document;
53
+
54
+ const before = (foreground ? yield* page.recentFrames : []).filter(
55
+ (frame) =>
56
+ frame.hostTime < inputAt &&
57
+ frame.hostTime >= inputAt - 1500 &&
58
+ frame.document === document,
59
+ );
60
+
61
+ const sampled = before.filter((_, index) => index % Math.ceil(before.length / 8) === 0);
62
+ const mask = Motion.background(yield* Effect.forEach(sampled, decoded));
63
+
64
+ // How long the screen has been still: since a frame, or an unanswered acknowledgement. In
65
+ // the foreground, since a frame moved outside the background, or acknowledgements went
66
+ // unanswered with no frame coming.
67
+ const look = Effect.gen(function* () {
68
+ const stats = yield* capture.stats();
69
+ const latest = (yield* page.state).frame;
70
+ const arrived = stats.received !== counts.received;
71
+ const unseen = stats.accepted - counts.accepted;
72
+
73
+ counts = stats;
74
+ if (latest === undefined || !capture.isCurrent(latest)) stirred = now();
75
+ else if (!foreground ? arrived || stats.ackBacklog > 0 : !arrived && stats.ackBacklog > 0)
76
+ stirred = now();
77
+ else if (foreground && (unseen > 0 || reference === undefined)) {
78
+ // A move and its return between looks both count. Bound decoding; any frames lost
79
+ // from history, or beyond this batch, deny a quiet spell rather than hiding motion.
80
+ const frames = (yield* page.recentFrames).slice(-Math.max(1, Math.min(8, unseen)));
81
+
82
+ if (unseen > frames.length) stirred = now();
83
+ for (const frame of frames) {
84
+ const seen = yield* decoded(frame);
85
+
86
+ if (reference === undefined || Motion.stirs(reference, seen, mask)) {
87
+ reference = seen;
88
+ stirred = now();
89
+ }
90
+ }
91
+ }
92
+
93
+ return now() - stirred;
94
+ });
95
+
96
+ // Decode at a fixed cadence: adding a delay after a full batch lets its backlog grow.
97
+ const spell = Effect.repeat(look, {
98
+ schedule: Schedule.fixed(Duration.millis(foreground ? 100 : 25)),
99
+ until: (still) => still >= millis,
100
+ });
101
+
102
+ const still = Effect.gen(function* () {
103
+ for (;;) {
104
+ yield* spell;
105
+ const before = counts.received;
106
+
107
+ yield* Effect.all([settled(), capture.sync], { concurrency: 2, discard: true });
108
+ if ((yield* look) >= millis && (foreground || counts.received === before)) return;
109
+ }
110
+ });
111
+
112
+ return yield* Effect.raceFirst(
113
+ capture.stream.pipe(Stream.runDrain, Effect.andThen(Effect.never)),
114
+ still,
115
+ );
116
+ });
117
+
118
+ yield* page.afterInput(Effect.void);
119
+ if (options.still === "content") {
120
+ yield* page.changes();
121
+ yield* Effect.sleep(Duration.millis(options.quietMillis));
122
+
123
+ return yield* settled();
124
+ }
125
+ yield* settled();
126
+ yield* quiet(options.quietMillis);
127
+ });
128
+
129
+ export const wait = (page: Page, options: Options) =>
130
+ Effect.gen(function* () {
131
+ if (!Number.isFinite(options.quietMillis) || options.quietMillis < 0)
132
+ return yield* refuse("stillness", "quietMillis must be finite and nonnegative");
133
+ const input = options.timeout ?? Duration.seconds(15);
134
+
135
+ const components =
136
+ typeof input === "number"
137
+ ? [input]
138
+ : typeof input === "object" && !Duration.isDuration(input)
139
+ ? Object.values(input)
140
+ : [];
141
+
142
+ const timeout = Duration.fromInput(input);
143
+
144
+ if (
145
+ components.some((value) => typeof value === "number" && !Number.isFinite(value)) ||
146
+ Option.isNone(timeout) ||
147
+ !Duration.isFinite(timeout.value) ||
148
+ Duration.isNegative(timeout.value)
149
+ )
150
+ return yield* refuse("stillness", "timeout must be a finite nonnegative duration");
151
+ const duration = timeout.value;
152
+
153
+ return yield* observe(page, options, duration).pipe(
154
+ Effect.timeoutOrElse({
155
+ duration,
156
+ orElse: () =>
157
+ Effect.fail(
158
+ undispatched("stillness", new Timeout({ millis: Duration.toMillis(duration) })),
159
+ ),
160
+ }),
161
+ );
162
+ }).pipe(
163
+ Effect.scoped,
164
+ Effect.provideService(Clock.Clock, page.clock),
165
+ Effect.withSpan("Stillness.wait"),
166
+ );
@@ -0,0 +1,170 @@
1
+ /**
2
+ * A resource kept serving through typed acquisition failures, loss and rotation.
3
+ * `make` adds its finalizer directly to its caller's scope. Each generation has its own scope;
4
+ * its loss signal remains watched until that scope closes, after release. Optional policies
5
+ * compose by wrapping `open`, `release` and the public generation stream.
6
+ */
7
+ import {
8
+ Clock,
9
+ Context,
10
+ Deferred,
11
+ Effect,
12
+ Exit,
13
+ FiberSet,
14
+ Option,
15
+ PubSub,
16
+ Scope,
17
+ Semaphore,
18
+ Stream,
19
+ SubscriptionRef,
20
+ type Take,
21
+ Tracer,
22
+ } from "effect";
23
+
24
+ import { type Generation, type Options, type Supervisor, Unavailable } from "./contract.ts";
25
+ import * as Lifecycle from "./lifecycle.ts";
26
+ import { type Apply, type Hold, type Runtime, leasing, opening, releasing } from "./runtime.ts";
27
+
28
+ export {
29
+ type Generation,
30
+ InvalidWait,
31
+ type Lease,
32
+ type Opened,
33
+ type Options,
34
+ type State,
35
+ type Supervisor,
36
+ Superseded,
37
+ Unavailable,
38
+ type UseOptions,
39
+ Why,
40
+ } from "./contract.ts";
41
+
42
+ export const make = Effect.fn("Supervisor.make")(function* <A, E, R>(
43
+ options: Options<A, E, R>,
44
+ ): Effect.fn.Return<Supervisor<A, E>, never, Scope.Scope | Exclude<R, Scope.Scope>> {
45
+ const clock = yield* Clock.Clock;
46
+ // The caller span survives as a link, never as the parent of a later generation.
47
+ const context = Context.omit(Tracer.ParentSpan)(yield* Effect.context<Exclude<R, Scope.Scope>>());
48
+ const parent = yield* Effect.serviceOption(Tracer.ParentSpan);
49
+ const links = Option.isSome(parent) ? [{ span: parent.value, attributes: {} }] : [];
50
+ // A parallel caller scope must not close workers alongside retirement.
51
+ const own = yield* Scope.make();
52
+ const started = Lifecycle.start<Runtime<A>, Hold, E>();
53
+ const state = yield* SubscriptionRef.make(started.state);
54
+ const permit = yield* Semaphore.make(1);
55
+ const events = yield* PubSub.unbounded<Take.Take<Generation<E>>>({ replay: 64 });
56
+ const fibers = yield* FiberSet.make().pipe(Scope.provide(own));
57
+
58
+ const run = yield* FiberSet.runtime(fibers)<never>().pipe(
59
+ Effect.updateContext<never, never>(() => context),
60
+ );
61
+
62
+ const retiring = Deferred.makeUnsafe<void>();
63
+ const stopped = Deferred.makeUnsafe<void>();
64
+
65
+ const apply: Apply<A, E> = (input) =>
66
+ permit.withPermit(
67
+ Effect.uninterruptible(
68
+ Effect.gen(function* () {
69
+ const step = Lifecycle.transition(state.value, input, options.exclusive ?? false);
70
+
71
+ // SubscriptionRef.set wakes retirement's waiter immediately; publish its last outcome first.
72
+ for (const [number, change] of step.events)
73
+ PubSub.publishUnsafe(events, [
74
+ {
75
+ number,
76
+ state: change,
77
+ at: clock.currentTimeMillisUnsafe(),
78
+ hostTime: Number(clock.monotonicTimeNanosUnsafe()) / 1e6,
79
+ },
80
+ ]);
81
+ if (step.state !== state.value) yield* SubscriptionRef.set(state, step.state);
82
+ for (const command of step.commands) yield* perform(command);
83
+
84
+ return step;
85
+ }),
86
+ ),
87
+ );
88
+
89
+ const openGeneration = opening<A, E, R>(options, context, own, retiring, apply, links);
90
+ const releaseGeneration = releasing(apply, links);
91
+
92
+ const perform = (command: Lifecycle.Command<Runtime<A>, Hold>): Effect.Effect<void> => {
93
+ switch (command._tag) {
94
+ case "Open":
95
+ return Effect.sync(() => void run(openGeneration(command.number)));
96
+ case "Watch": {
97
+ const { number, value } = command.live;
98
+ const { lost } = value.opened;
99
+
100
+ return lost === undefined
101
+ ? Effect.void
102
+ : Effect.asVoid(
103
+ Effect.forkIn(
104
+ Effect.flatMap(lost, (detail) => apply({ _tag: "Lost", number, detail })),
105
+ value.scope,
106
+ ),
107
+ );
108
+ }
109
+ case "End":
110
+ return Effect.asVoid(Deferred.succeed(command.live.value.ending, command.why));
111
+ case "Release":
112
+ return Effect.sync(() => void run(releaseGeneration(command.live, command.why)));
113
+ case "Stop":
114
+ return Deferred.succeed(retiring, undefined).pipe(
115
+ Effect.andThen(Effect.sync(() => void run(stop))),
116
+ );
117
+ }
118
+ };
119
+
120
+ const rotate = Effect.fnUntraced(function* (from?: number) {
121
+ const step = yield* apply({ _tag: "Rotate", from });
122
+ const target = step.reply;
123
+
124
+ if (target === undefined)
125
+ return step.state._tag === "Retired"
126
+ ? yield* new Unavailable<E>({ reason: "retired", detail: "retired" })
127
+ : undefined;
128
+
129
+ const reached = (s: typeof step.state) =>
130
+ s._tag === "Retired"
131
+ ? new Unavailable<E>({ reason: "retired", detail: "retired" })
132
+ : s._tag === "Down" && s.number >= target
133
+ ? new Unavailable<E>({ reason: "down", error: s.error, detail: s.detail })
134
+ : s._tag === "Open" && s.serving.number >= target
135
+ ? ("served" as const)
136
+ : undefined;
137
+
138
+ const outcome = yield* Stream.runHead(
139
+ Stream.filter(Stream.map(SubscriptionRef.changes(state), reached), (r) => r !== undefined),
140
+ );
141
+
142
+ if (Option.isSome(outcome) && outcome.value !== "served") return yield* outcome.value;
143
+ });
144
+
145
+ const stop = Effect.gen(function* () {
146
+ yield* Stream.runHead(
147
+ Stream.filter(
148
+ SubscriptionRef.changes(state),
149
+ (s) => s._tag === "Retired" && s.opening === undefined && s.ended.size === 0,
150
+ ),
151
+ );
152
+ yield* PubSub.publish(events, Exit.void);
153
+ }).pipe(Effect.ensuring(Deferred.succeed(stopped, undefined)));
154
+
155
+ // Commit the transition even if its caller is interrupted while waiting for the state lock.
156
+ const retire = apply({ _tag: "Retire" }).pipe(
157
+ Effect.uninterruptible,
158
+ Effect.andThen(Deferred.await(stopped)),
159
+ );
160
+
161
+ yield* Effect.addFinalizer((exit) => retire.pipe(Effect.ensuring(Scope.close(own, exit))));
162
+ yield* Effect.forEach(started.commands, perform, { discard: true });
163
+
164
+ return {
165
+ use: leasing(state, apply, clock),
166
+ states: Stream.fromPubSubTake(events),
167
+ rotate,
168
+ retire,
169
+ };
170
+ });
@@ -0,0 +1,105 @@
1
+ /** Resource generations, typed acquisition failures and the public supervision contract. */
2
+ import {
3
+ type Cause,
4
+ Data,
5
+ type Duration,
6
+ type Effect,
7
+ Schema,
8
+ type Schedule,
9
+ type Scope,
10
+ type Stream,
11
+ } from "effect";
12
+
13
+ import type { Released } from "../providers/Released.ts";
14
+
15
+ /** Why a generation stopped serving. */
16
+ export const Why = Schema.Literals(["lost", "rotated", "retired"]);
17
+ export type Why = typeof Why.Type;
18
+
19
+ /** A resource acquired in the generation's scope. The core never inspects its value. */
20
+ export interface Opened<A> {
21
+ readonly value: A;
22
+ /** Watched until the generation's scope closes, after its release. */
23
+ readonly lost?: Effect.Effect<string> | undefined;
24
+ /** Without a release hook, closing the generation's scope ends the resource. */
25
+ readonly release?: ((why: Why) => Effect.Effect<Released>) | undefined;
26
+ }
27
+
28
+ export interface Options<A, E, R> {
29
+ /** Each try receives its generation number and owns resources in the supplied Scope. */
30
+ readonly open: (number: number) => Effect.Effect<Opened<A>, E, R>;
31
+ /** Defaults to exponential from one second, for five minutes. */
32
+ readonly reopen?: Schedule.Schedule<unknown, E> | undefined;
33
+ readonly definite?: ((error: E) => boolean) | undefined;
34
+ /** Each generation waits until every earlier release has completed. */
35
+ readonly exclusive?: boolean | undefined;
36
+ }
37
+
38
+ /** Every failed try retains its own typed error, including any provider cleanup evidence. */
39
+ export type State<E> =
40
+ | { readonly _tag: "Opening"; readonly attempt: number }
41
+ | { readonly _tag: "Failed"; readonly attempt: number; readonly error: E }
42
+ | { readonly _tag: "Down"; readonly error: E | undefined; readonly detail: string }
43
+ | { readonly _tag: "Open" }
44
+ | { readonly _tag: "Ending"; readonly why: Why; readonly detail?: string | undefined }
45
+ | { readonly _tag: "Closed"; readonly released?: Released | undefined };
46
+
47
+ export interface Generation<E = unknown> {
48
+ readonly number: number;
49
+ /** Epoch milliseconds on the owning Effect clock. */
50
+ readonly at: number;
51
+ /** Monotonic milliseconds on the same clock. */
52
+ readonly hostTime: number;
53
+ readonly state: State<E>;
54
+ }
55
+
56
+ /** No generation serves because opening failed permanently or the supervisor retired. */
57
+ export class Unavailable<E = unknown> extends Data.TaggedError("Unavailable")<{
58
+ readonly reason: "down" | "retired";
59
+ readonly error?: E | undefined;
60
+ readonly detail: string;
61
+ }> {
62
+ override get message() {
63
+ return `no resource: ${this.detail}`;
64
+ }
65
+ }
66
+
67
+ /** Revoked work still uses its input receipt to determine whether input reached the site. */
68
+ export class Superseded extends Schema.TaggedError<Superseded>()("Superseded", {
69
+ generation: Schema.Int,
70
+ reason: Why,
71
+ }) {}
72
+
73
+ export interface Lease<A> {
74
+ readonly generation: number;
75
+ readonly value: A;
76
+ readonly ending: Effect.Effect<Why>;
77
+ /** Stale declarations do nothing. */
78
+ readonly lose: (detail: string) => Effect.Effect<void>;
79
+ }
80
+
81
+ /** A public admission budget must be finite and nonnegative. */
82
+ export class InvalidWait extends Data.TaggedError("InvalidWait")<{ readonly detail: string }> {}
83
+
84
+ export interface UseOptions {
85
+ /** Finite nonnegative admission budget on the owner's clock. Zero peeks; absent waits. */
86
+ readonly wait?: Duration.Input | undefined;
87
+ }
88
+
89
+ export interface Supervisor<A, E = unknown> {
90
+ /** Ending interrupts the work and awaits its scoped cleanup before releasing the resource. */
91
+ readonly use: <B, E2, R>(
92
+ work: (lease: Lease<A>) => Effect.Effect<B, E2, R>,
93
+ options?: UseOptions,
94
+ ) => Effect.Effect<
95
+ B,
96
+ E2 | Unavailable<E> | Superseded | Cause.TimeoutError | InvalidWait,
97
+ Exclude<R, Scope.Scope>
98
+ >;
99
+ /** Replays the latest 64 changes; ends only after every try and release has finished. */
100
+ readonly states: Stream.Stream<Generation<E>>;
101
+ /** Replace the current generation. A stale `from` does nothing. */
102
+ readonly rotate: (from?: number) => Effect.Effect<void, Unavailable<E>>;
103
+ /** The stop runs on its own fiber; abandoning this wait never abandons retirement. */
104
+ readonly retire: Effect.Effect<void>;
105
+ }