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

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 (249) 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-BKPAbyys.mjs +4076 -0
  10. package/dist/Browser-BKPAbyys.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-CK83pvqP.mjs} +5 -6
  64. package/dist/connection-CK83pvqP.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 +515 -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 +89 -39
  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/identity.ts +6 -5
  139. package/src/internal/page/lane.ts +14 -15
  140. package/src/internal/page/navigation.ts +50 -42
  141. package/src/internal/page/openings.ts +11 -5
  142. package/src/internal/page/page.ts +44 -81
  143. package/src/internal/page/port.ts +125 -0
  144. package/src/internal/{input → page}/replies.ts +1 -1
  145. package/src/internal/page/request-owner.ts +269 -0
  146. package/src/internal/page/requests.ts +357 -0
  147. package/src/internal/page/scripts.ts +124 -0
  148. package/src/internal/pictures/capture.ts +255 -332
  149. package/src/internal/pictures/dimensions.ts +162 -0
  150. package/src/internal/pictures/frame.ts +68 -0
  151. package/src/internal/pictures/pictures.ts +57 -23
  152. package/src/internal/pictures/quiescence.ts +1 -1
  153. package/src/internal/pictures/state.ts +26 -0
  154. package/src/internal/pictures/transport.ts +21 -4
  155. package/src/internal/reading/controls.inpage.ts +5 -70
  156. package/src/internal/reading/expect.inpage.ts +13 -17
  157. package/src/internal/reading/names.inpage.ts +89 -45
  158. package/src/internal/reading/outline.inpage.ts +6 -7
  159. package/src/internal/reading/reading.ts +144 -176
  160. package/src/internal/reading/ready.inpage.ts +6 -17
  161. package/src/internal/reading/ready.ts +13 -135
  162. package/src/internal/reading/subjects.inpage.ts +83 -43
  163. package/src/internal/reading/walk.inpage.ts +33 -13
  164. package/src/internal/timeline/changes.ts +55 -6
  165. package/src/internal/timeline/events.ts +15 -5
  166. package/src/internal/timeline/history.inpage.ts +1 -1
  167. package/src/internal/timeline/record.inpage.ts +4 -1
  168. package/src/internal/timeline/window.ts +2 -1
  169. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  170. package/src/{internal/timeline → moment}/words.ts +2 -2
  171. package/src/{internal/reading → plan}/choose.ts +3 -3
  172. package/src/plan/data.ts +117 -0
  173. package/src/plan/execute.ts +411 -0
  174. package/src/plan/index.ts +36 -0
  175. package/src/plan/record.ts +71 -0
  176. package/src/plan/targets.ts +71 -0
  177. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  178. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  179. package/src/presentation/Presentation.ts +176 -0
  180. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  181. package/src/presentation/feed.ts +21 -0
  182. package/src/{Cdp.ts → providers/Cdp.ts} +2 -2
  183. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  184. package/src/providers/Released.ts +13 -0
  185. package/src/{internal/cdp.ts → providers/connection.ts} +2 -2
  186. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +1 -1
  187. package/src/stillness/Stillness.ts +166 -0
  188. package/src/supervisor/Supervisor.ts +170 -0
  189. package/src/supervisor/contract.ts +105 -0
  190. package/src/supervisor/lifecycle.ts +272 -0
  191. package/src/supervisor/runtime.ts +238 -0
  192. package/src/testing/TestBrowser.ts +115 -0
  193. package/src/testing/TestPage.ts +10 -0
  194. package/src/testing/evidence.ts +154 -0
  195. package/src/testing/index.ts +3 -0
  196. package/src/testing/model.ts +222 -0
  197. package/src/testing/page.ts +360 -0
  198. package/src/workerd/Cdp.ts +2 -2
  199. package/dist/Browser-CxXUjxOp.mjs +0 -619
  200. package/dist/Browser-CxXUjxOp.mjs.map +0 -1
  201. package/dist/Cdp-CzCRnMlM.d.mts +0 -10
  202. package/dist/Cdp.d.mts +0 -11
  203. package/dist/Cdp.mjs.map +0 -1
  204. package/dist/Change-DNvztNLu.mjs +0 -138
  205. package/dist/Change-DNvztNLu.mjs.map +0 -1
  206. package/dist/Chromium.mjs.map +0 -1
  207. package/dist/Expect-u3P_ENLX.d.mts +0 -62
  208. package/dist/Expect.d.mts +0 -2
  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-BP02bmNv.mjs +0 -264
  216. package/dist/Page-BP02bmNv.mjs.map +0 -1
  217. package/dist/Plan-BG1WifW2.mjs.map +0 -1
  218. package/dist/Plan.d.mts +0 -2
  219. package/dist/Plan.mjs +0 -2
  220. package/dist/Policy.d.mts +0 -2
  221. package/dist/Policy.mjs.map +0 -1
  222. package/dist/Presentation-DxVikn9_.d.mts +0 -48
  223. package/dist/Presentation.d.mts +0 -2
  224. package/dist/Presentation.mjs +0 -118
  225. package/dist/Presentation.mjs.map +0 -1
  226. package/dist/Stage.d.mts +0 -2
  227. package/dist/Stage.mjs.map +0 -1
  228. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  229. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  230. package/dist/Supervisor-CfRxbaso.d.mts +0 -317
  231. package/dist/Supervisor.d.mts +0 -2
  232. package/dist/Supervisor.mjs +0 -2
  233. package/dist/cdp-BMpYMWYe.mjs.map +0 -1
  234. package/dist/context-EGhOqjNN.mjs +0 -335
  235. package/dist/context-EGhOqjNN.mjs.map +0 -1
  236. package/dist/page-PTM8m5wC.mjs +0 -4057
  237. package/dist/page-PTM8m5wC.mjs.map +0 -1
  238. package/dist/url-Bsp2y55M.mjs +0 -264
  239. package/dist/url-Bsp2y55M.mjs.map +0 -1
  240. package/dist/workerd/index.d.mts +0 -16
  241. package/dist/workerd/index.mjs +0 -17
  242. package/src/Expect.ts +0 -180
  243. package/src/Plan.ts +0 -674
  244. package/src/Presentation.ts +0 -196
  245. package/src/Supervisor.ts +0 -632
  246. package/src/internal/supervisor/lifecycle.ts +0 -484
  247. package/src/workerd/index.ts +0 -17
  248. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  249. /package/src/{internal/pictures → stillness}/utilsBundle.d.ts +0 -0
package/src/Supervisor.ts DELETED
@@ -1,632 +0,0 @@
1
- /**
2
- * A browser kept open across losses and session ends, as a series of generations, each a new
3
- * browser from the same provider. Pages don't carry over from one generation to the next.
4
- *
5
- * `make` opens the first generation at once with the provider's `open`, in a scope of its own, so
6
- * a caller that stops waiting never interrupts a half-open browser. `browser` gives the current
7
- * generation; callers wait, bounded, and share one open. A loss is published at once and the next
8
- * generation opens on the `reopen` schedule, which also retries a failed open, unless the provider
9
- * deems its failure `definite`: that goes `Down` at once, with its cause. `rotate` opens the
10
- * next generation now, and so does the time `rotateBefore` ahead of a generation's `expiresAt`. A
11
- * rotation makes the next generation before it breaks the current one, unless generations are
12
- * `exclusive`, as sessions saving to one stored context must be: then the current one is released
13
- * first. `retire` stops reopening at once and releases what is open; the scope's close retires
14
- * too, unless the supervisor `keep`s: then it leaves the serving generation running, `Kept`. `states`
15
- * publishes each generation's changes, with the provider's release outcome last.
16
- *
17
- * Providers supply the specifics: `Browserbase.supervise` opens hosted sessions this way.
18
- *
19
- * @since 0.3.0
20
- */
21
- import {
22
- Cause,
23
- Clock,
24
- Context,
25
- DateTime,
26
- Deferred,
27
- Duration,
28
- Effect,
29
- Exit,
30
- FiberHandle,
31
- FiberMap,
32
- Option,
33
- Predicate,
34
- PubSub,
35
- Schedule,
36
- Schema,
37
- Scope,
38
- Semaphore,
39
- Stream,
40
- SubscriptionRef,
41
- type Take,
42
- } from "effect";
43
-
44
- import type * as Browser from "./Browser.ts";
45
- import * as Lifecycle from "./internal/supervisor/lifecycle.ts";
46
-
47
- export {
48
- Closed,
49
- Down,
50
- Draining,
51
- GenerationState,
52
- Kept,
53
- Lost,
54
- Open,
55
- Opening,
56
- Released,
57
- Reopening,
58
- Settled,
59
- Unconfirmed,
60
- } from "./internal/supervisor/lifecycle.ts";
61
-
62
- /** One change in a generation's life. `at` is wall-clock epoch milliseconds from the Effect `Clock`. */
63
- export class Generation extends Schema.Class<Generation>("effect-browser/Generation")({
64
- number: Schema.Int.check(Schema.isGreaterThan(0)),
65
- at: Schema.Finite,
66
- hostTime: Schema.Finite,
67
- state: Lifecycle.GenerationState,
68
- }) {}
69
-
70
- /**
71
- * No browser to give: none opened within `waitTimeout` (`opening`), the latest generation failed
72
- * to open (`down`, with what it failed with as `cause`), or the supervisor was retired.
73
- */
74
- export class Unavailable extends Schema.TaggedError<Unavailable>()("Unavailable", {
75
- reason: Schema.Literals(["opening", "down", "retired"]),
76
- detail: Schema.String,
77
- cause: Schema.optional(Schema.Defect()),
78
- }) {
79
- override get message() {
80
- return `no browser: ${this.detail}`;
81
- }
82
- }
83
-
84
- /** One generation, as a provider opened it in the scope the supervisor gave it. */
85
- export interface Opened<A = void> {
86
- readonly value: A;
87
- readonly browser: Browser.Service;
88
- /**
89
- * End the generation, and say whether the provider confirmed its end. The supervisor asks it
90
- * before it closes the generation's scope; without it, closing the scope ends the generation,
91
- * which counts as `Settled`.
92
- */
93
- readonly release?: Effect.Effect<Lifecycle.Released> | undefined;
94
- }
95
-
96
- /** Facts available before an acquisition attempt; awaiting `after` never changes release order. */
97
- export interface Admission {
98
- readonly number: number;
99
- /**
100
- * Every earlier session that stopped serving, including failed attempts and older drains.
101
- * Waits for all pending releases; an Unconfirmed end remains visible to later attempts.
102
- * Undefined before any release. A still-serving nonexclusive predecessor is excluded.
103
- */
104
- readonly after: Effect.Effect<Lifecycle.Released> | undefined;
105
- }
106
-
107
- /**
108
- * Optional service supplied during `open`. Providers report failed-attempt cleanup here before
109
- * their scope closes; successful generations instead return `Opened.release`. Reporting does
110
- * not release resources or replace the original acquisition failure. Terminal `Down` and opening
111
- * `Closed` states publish the reported outcomes of their own generation's tries.
112
- */
113
- export class Releasing extends Context.Service<
114
- Releasing,
115
- { readonly released: (outcome: Lifecycle.Released) => Effect.Effect<void> }
116
- >()("effect-browser/Supervisor/Releasing") {}
117
-
118
- export interface Options<E, R, A = void> {
119
- /** Opens one generation in the scope it is given. */
120
- readonly open: Effect.Effect<Opened<A>, E, R>;
121
- /** Runs before every open attempt, including the first; failures follow `reopen` and `definite`. */
122
- readonly admit?: ((opening: Admission) => Effect.Effect<void, E, R>) | undefined;
123
- /** When to try a failed open again. Defaults to exponential from 1 second, for 5 minutes. */
124
- readonly reopen?: Schedule.Schedule<unknown, E> | undefined;
125
- /**
126
- * Failures no new try mends, such as a refused key: an open that fails so is `Down` at once.
127
- * Defaults to none.
128
- */
129
- readonly definite?: ((error: E) => boolean) | undefined;
130
- /**
131
- * Rotate this long ahead of a generation's `expiresAt`, but no sooner than halfway through its
132
- * life. Without it, a generation's end is a loss.
133
- */
134
- readonly rotateBefore?: Duration.Input | undefined;
135
- /** Generations must not overlap: a rotation releases the current one before it opens the next. */
136
- readonly exclusive?: boolean | undefined;
137
- /** Finite, nonnegative time outgoing holds may finish; defaults to 30 seconds. */
138
- readonly handover?: Duration.Input | undefined;
139
- /**
140
- * Closing the scope leaves the serving generation running, `Kept`: it closes the generation's
141
- * scope but never asks `release`. For providers whose scope only disconnects, such as
142
- * `Browserbase.supervise` with `keep`. `retire` still releases it.
143
- */
144
- readonly keep?: boolean | undefined;
145
- /** How long `browser` and `rotate` wait for a generation to open. Defaults to 2 minutes. */
146
- readonly waitTimeout?: Duration.Input | undefined;
147
- }
148
-
149
- /** Work whose generation was revoked; input receipts still determine whether input reached a site. */
150
- export class Superseded extends Schema.TaggedError<Superseded>()("Superseded", {
151
- generation: Schema.Int,
152
- reason: Schema.Literals(["rotated", "lost", "retired"]),
153
- revokeAt: Schema.Finite,
154
- }) {}
155
-
156
- export interface Lease<A> {
157
- readonly generation: number;
158
- readonly browser: Browser.Service;
159
- readonly value: A;
160
- /** Declare this serving generation unusable and revoke it now; stale declarations do nothing. */
161
- readonly lose: (detail: string) => Effect.Effect<void>;
162
- /** First notice that serving ended; loss or retirement may revoke before its deadline. */
163
- readonly ending: Effect.Effect<Superseded>;
164
- /** An independent scope; its resources close before provider release. Fails once revoked. */
165
- readonly retain: Effect.Effect<Scope.Closeable, Superseded>;
166
- }
167
-
168
- export interface UseOptions {
169
- /** Finite, nonnegative wait for a serving generation. Zero makes an immediate attempt. */
170
- readonly wait?: Duration.Input | undefined;
171
- }
172
-
173
- export interface Supervisor<A = void> {
174
- /** Scoped work on the current generation. Revocation interrupts it and waits for its cleanup. */
175
- readonly use: <B, E, R>(
176
- work: (lease: Lease<A>) => Effect.Effect<B, E, R>,
177
- options?: UseOptions,
178
- ) => Effect.Effect<B, E | Unavailable | Superseded, Exclude<R, Scope.Scope>>;
179
- /** The current generation's browser, waiting up to `waitTimeout` while none is open. */
180
- readonly browser: Effect.Effect<Browser.Service, Unavailable>;
181
- /** Each generation's changes, in order. A new reader first gets the latest 64; ends on retiring. */
182
- readonly states: Stream.Stream<Generation>;
183
- /** Open the next generation now, or join the one opening, and wait for it. */
184
- readonly rotate: Effect.Effect<Browser.Service, Unavailable>;
185
- /** Stop opening at once, release every generation, and wait until each release has finished. */
186
- readonly retire: Effect.Effect<void>;
187
- }
188
-
189
- type Hold =
190
- | { readonly _tag: "Use" }
191
- | { readonly _tag: "Retained"; readonly scope: Scope.Closeable };
192
-
193
- interface Held<A> {
194
- readonly opened: Opened<A>;
195
- readonly ending: Deferred.Deferred<Superseded>;
196
- readonly revoked: Deferred.Deferred<Superseded>;
197
- readonly released: Deferred.Deferred<Lifecycle.Released>;
198
- readonly scope: Scope.Closeable;
199
- }
200
-
201
- type State<A> = Lifecycle.State<Held<A>, Hold>;
202
- type Input<A> = Lifecycle.Input<Held<A>, Hold>;
203
- type Step<A> = Lifecycle.Step<Held<A>, Hold>;
204
- type Apply<A> = (input: Input<A>) => Effect.Effect<Step<A>>;
205
-
206
- const superseded = (generation: number, { reason, revokeAt }: Lifecycle.Draining) =>
207
- new Superseded({ generation, reason, revokeAt });
208
-
209
- const retired = () => new Unavailable({ reason: "retired", detail: "the supervisor was retired" });
210
-
211
- const describe = (cause: Cause.Cause<unknown>) => {
212
- const error = Cause.squash(cause);
213
-
214
- return Predicate.isError(error) ? error.message : String(error);
215
- };
216
-
217
- const timedOut = () =>
218
- new Unavailable({ reason: "opening", detail: "no generation opened within the wait" });
219
-
220
- const bounded = (input: Duration.Input, name: string) =>
221
- Effect.suspend(() => {
222
- const duration = Duration.fromInput(input);
223
-
224
- return Option.isSome(duration) &&
225
- Duration.isFinite(duration.value) &&
226
- !Duration.isNegative(duration.value)
227
- ? Effect.succeed(duration.value)
228
- : Effect.die(new RangeError(`${name} must be a finite nonnegative duration`));
229
- });
230
-
231
- /** Resolve immediately before starting a bounded wait, including when its duration is zero. */
232
- const waitFor = <A, H>(
233
- state: SubscriptionRef.SubscriptionRef<Lifecycle.State<A, H>>,
234
- wait: Duration.Duration,
235
- clock: Clock.Clock,
236
- target?: number,
237
- ) => {
238
- const result = (resolution: Lifecycle.Resolution<A>) =>
239
- resolution._tag === "Serve"
240
- ? Effect.succeed(resolution.live)
241
- : Effect.fail(new Unavailable(resolution));
242
-
243
- return Effect.suspend(() => {
244
- const current = Lifecycle.resolve(state.value, target);
245
-
246
- return current === undefined
247
- ? SubscriptionRef.changes(state).pipe(
248
- Stream.map((state) => Lifecycle.resolve(state, target)),
249
- Stream.filter(Predicate.isNotUndefined),
250
- Stream.runHead,
251
- Effect.flatMap(Option.match({ onNone: () => Effect.fail(retired()), onSome: result })),
252
- Effect.timeoutOrElse({ duration: wait, orElse: () => Effect.fail(timedOut()) }),
253
- )
254
- : result(current);
255
- }).pipe(Effect.provideService(Clock.Clock, clock));
256
- };
257
-
258
- /** Sleep until `before` ahead of `expiresAt`, but no sooner than halfway there from now. */
259
- const untilRotation = (expiresAt: DateTime.Utc, before: Duration.Duration) =>
260
- Clock.currentTimeMillis.pipe(
261
- Effect.flatMap((now) => {
262
- const left = DateTime.toEpochMillis(expiresAt) - now;
263
-
264
- return Effect.sleep(Duration.millis(Math.max(left - Duration.toMillis(before), left / 2, 0)));
265
- }),
266
- );
267
-
268
- /** Native timers may wake a fraction early; a revocation must reach its monotonic deadline. */
269
- const until = (at: number, now: () => number): Effect.Effect<void> =>
270
- Effect.suspend(() =>
271
- now() >= at
272
- ? Effect.void
273
- : Effect.sleep(Duration.millis(Math.ceil(at - now()))).pipe(Effect.andThen(until(at, now))),
274
- );
275
-
276
- /** Borrowed work and transferred scopes hold a generation until cleanup lets it go. */
277
- const leasing = <A>(
278
- state: SubscriptionRef.SubscriptionRef<State<A>>,
279
- apply: Apply<A>,
280
- waitTimeout: Duration.Duration,
281
- now: () => number,
282
- clock: Clock.Clock,
283
- ) => {
284
- const borrow = Effect.fnUntraced(function* (hold: Hold, wait: Duration.Duration) {
285
- const until = now() + Duration.toMillis(wait);
286
-
287
- for (;;) {
288
- const step = yield* apply({ _tag: "Hold", hold });
289
-
290
- if (step.borrowed !== undefined) return step.borrowed;
291
- yield* waitFor(state, Duration.millis(Math.max(0, until - now())), clock).pipe(
292
- Effect.interruptible,
293
- );
294
- if (now() >= until) return yield* timedOut();
295
- }
296
- });
297
-
298
- const leaseOf = (live: Lifecycle.Live<Held<A>>): Lease<A> => ({
299
- generation: live.number,
300
- browser: live.value.opened.browser,
301
- value: live.value.opened.value,
302
- lose: (detail) =>
303
- apply({ _tag: "Lost", number: live.number, cause: "declared", detail }).pipe(Effect.asVoid),
304
- ending: Deferred.await(live.value.ending),
305
- retain: Effect.uninterruptible(
306
- Effect.gen(function* () {
307
- const scope = yield* Scope.make();
308
- const hold: Hold = { _tag: "Retained", scope };
309
- const step = yield* apply({ _tag: "Hold", number: live.number, hold });
310
-
311
- if (step.borrowed === undefined) {
312
- yield* Scope.close(scope, Exit.void);
313
-
314
- return yield* yield* Deferred.await(live.value.ending);
315
- }
316
- yield* Scope.addFinalizer(
317
- scope,
318
- apply({ _tag: "Let", number: live.number, hold }).pipe(Effect.asVoid),
319
- );
320
-
321
- return scope;
322
- }),
323
- ),
324
- });
325
-
326
- const use: Supervisor<A>["use"] = (work, options = {}) =>
327
- Effect.scoped(
328
- Effect.gen(function* () {
329
- const hold: Hold = { _tag: "Use" };
330
- const wait = yield* bounded(options.wait ?? waitTimeout, "wait");
331
-
332
- const live = yield* Effect.acquireRelease(borrow(hold, wait), (live) =>
333
- apply({ _tag: "Let", number: live.number, hold }).pipe(Effect.asVoid),
334
- );
335
-
336
- const revoked = Deferred.await(live.value.revoked).pipe(Effect.flatMap(Effect.fail));
337
-
338
- return yield* Effect.raceFirst(
339
- work(leaseOf(live)).pipe(
340
- // Declaring loss and returning can finish before the race's other fiber runs.
341
- Effect.tap(() =>
342
- Deferred.isDone(live.value.revoked).pipe(
343
- Effect.flatMap((done) => (done ? revoked : Effect.void)),
344
- ),
345
- ),
346
- ),
347
- revoked,
348
- );
349
- }),
350
- );
351
-
352
- return use;
353
- };
354
-
355
- type Provider = Omit<Opened, "value">;
356
- type MakeOptions<E, R, A> = Omit<Options<E, R, A>, "open"> & {
357
- readonly open: Effect.Effect<Opened<A> | Provider, E, R>;
358
- };
359
-
360
- const acquireGeneration = <A, E, R>(
361
- open: Effect.Effect<Opened<A> | Provider, E, R>,
362
- own: Scope.Scope,
363
- ) =>
364
- Effect.uninterruptibleMask((restore) =>
365
- Effect.flatMap(Scope.fork(own), (scope) =>
366
- restore(open.pipe(Scope.provide(scope))).pipe(
367
- Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))),
368
- Effect.map((opened): Held<A | void> => ({
369
- opened: { ...opened, value: "value" in opened ? opened.value : undefined },
370
- scope,
371
- ending: Deferred.makeUnsafe<Superseded>(),
372
- revoked: Deferred.makeUnsafe<Superseded>(),
373
- released: Deferred.makeUnsafe<Lifecycle.Released>(),
374
- })),
375
- ),
376
- ),
377
- );
378
-
379
- const watchGeneration = <A>(
380
- live: Lifecycle.Live<Held<A>>,
381
- rotateBefore: Duration.Duration | undefined,
382
- apply: Apply<A>,
383
- ) => {
384
- const { browser } = live.value.opened;
385
-
386
- const loss = browser.disconnected.pipe(
387
- Effect.flatMap((cause) => apply({ _tag: "Lost", number: live.number, cause })),
388
- );
389
-
390
- const rotation =
391
- browser.expiresAt === undefined || rotateBefore === undefined
392
- ? Effect.void
393
- : untilRotation(browser.expiresAt, rotateBefore).pipe(
394
- Effect.andThen(apply({ _tag: "Rotate", due: live.number })),
395
- );
396
-
397
- return Effect.all([loss, rotation], { concurrency: 2, discard: true });
398
- };
399
-
400
- // After revocation, retained resources and use finalizers let go before the provider.
401
- const releaseGeneration = Effect.fnUntraced(function* <A>(
402
- command: Extract<Lifecycle.Command<Held<A>>, { readonly _tag: "Release" | "Leave" }>,
403
- state: SubscriptionRef.SubscriptionRef<State<A>>,
404
- apply: Apply<A>,
405
- ) {
406
- const { live } = command;
407
-
408
- const cleaned = yield* Effect.forEach(
409
- Lifecycle.lookup(state.value, live.number)?.holds ?? [],
410
- (hold) =>
411
- Effect.exit(hold._tag === "Retained" ? Scope.close(hold.scope, Exit.void) : Effect.void),
412
- { concurrency: 8 },
413
- );
414
-
415
- yield* SubscriptionRef.changes(state).pipe(
416
- Stream.filter((current) => (Lifecycle.lookup(current, live.number)?.holds.size ?? 0) === 0),
417
- Stream.runHead,
418
- );
419
-
420
- const released =
421
- command._tag === "Leave"
422
- ? undefined
423
- : yield* (live.value.opened.release ?? Effect.succeed(new Lifecycle.Settled())).pipe(
424
- Effect.catchCause((cause) =>
425
- Effect.succeed(
426
- new Lifecycle.Unconfirmed({ detail: `the release failed: ${describe(cause)}` }),
427
- ),
428
- ),
429
- );
430
-
431
- const closed = yield* Effect.exit(Scope.close(live.value.scope, Exit.void));
432
-
433
- yield* apply({ _tag: "Released", number: live.number, released });
434
- if (released !== undefined) yield* Deferred.succeed(live.value.released, released);
435
- yield* Exit.asVoidAll([...cleaned, closed]);
436
- });
437
-
438
- const admissionAfter = <A>(state: State<A>) => {
439
- const released = state.released;
440
-
441
- const pending = [...state.draining.values()]
442
- .filter((drain) => drain._tag !== "Leaving")
443
- .map(({ live }) => live.value.released);
444
-
445
- return pending.length === 0 && released === undefined
446
- ? undefined
447
- : Effect.gen(function* () {
448
- let outcome = released;
449
-
450
- for (const release of pending)
451
- outcome = Lifecycle.combine(outcome, yield* Deferred.await(release));
452
-
453
- return outcome ?? new Lifecycle.Settled();
454
- });
455
- };
456
-
457
- const makeScoped = Effect.fn("Supervisor.make")(function* <E, R, A>(
458
- options: MakeOptions<E, R, A>,
459
- ): Effect.fn.Return<Supervisor<A | void>, never, Scope.Scope | Exclude<R, Scope.Scope>> {
460
- const clock = yield* Clock.Clock;
461
- const now = () => Number(clock.monotonicTimeNanosUnsafe()) / 1e6;
462
- const context = yield* Effect.context<Exclude<R, Scope.Scope>>();
463
- const own = yield* Scope.fork(yield* Effect.scope);
464
- const exclusive = options.exclusive ?? false;
465
-
466
- const reopen: Schedule.Schedule<unknown, E> =
467
- options.reopen ??
468
- Schedule.exponential("1 second").pipe(Schedule.upTo({ duration: Duration.minutes(5) }));
469
-
470
- const rotateBefore =
471
- options.rotateBefore === undefined ? undefined : Duration.fromInputUnsafe(options.rotateBefore);
472
-
473
- const waitTimeout = yield* bounded(options.waitTimeout ?? Duration.minutes(2), "waitTimeout");
474
-
475
- const handover = Duration.toMillis(
476
- yield* bounded(options.handover ?? Duration.seconds(30), "handover"),
477
- );
478
-
479
- const started = Lifecycle.start<Held<A | void>, Hold>();
480
- const state = yield* SubscriptionRef.make(started.state);
481
- const applying = yield* Semaphore.make(1);
482
- const events = yield* PubSub.unbounded<Take.Take<Generation>>({ replay: 64 });
483
- const opening = yield* FiberHandle.make<unknown, never>();
484
- const releases = yield* FiberMap.make<number, unknown, never>();
485
- const runOpen = yield* FiberHandle.runtime(opening)();
486
- const runRelease = yield* FiberMap.runtime(releases)();
487
-
488
- const apply: Apply<A | void> = Effect.fnUntraced(
489
- function* (input: Input<A | void>) {
490
- const current = state.value;
491
- const step = Lifecycle.transition(current, input, exclusive, now(), handover);
492
-
493
- if (step.state !== current) yield* SubscriptionRef.set(state, step.state);
494
- yield* perform(step);
495
-
496
- return step;
497
- },
498
- (effect) => applying.withPermit(effect),
499
- Effect.uninterruptible,
500
- Effect.provideService(Clock.Clock, clock),
501
- );
502
-
503
- const perform = Effect.fnUntraced(function* (step: Step<A | void>): Effect.fn.Return<void> {
504
- for (const [number, generation] of step.events)
505
- PubSub.publishUnsafe(events, [
506
- new Generation({
507
- number,
508
- at: clock.currentTimeMillisUnsafe(),
509
- hostTime: now(),
510
- state: generation,
511
- }),
512
- ]);
513
- for (const command of step.commands)
514
- switch (command._tag) {
515
- case "Open":
516
- runOpen(openGeneration(command.number));
517
- break;
518
- case "Watch":
519
- yield* Effect.forkIn(
520
- Effect.provideContext(watchGeneration(command.live, rotateBefore, apply), context),
521
- command.live.value.scope,
522
- );
523
- break;
524
- case "Drain": {
525
- const ending = superseded(command.live.number, command.ending);
526
-
527
- yield* Deferred.succeed(command.live.value.ending, ending);
528
- yield* Effect.forkIn(
529
- until(ending.revokeAt, now).pipe(
530
- Effect.andThen(
531
- Effect.suspend(() => apply({ _tag: "Revoke", number: command.live.number })),
532
- ),
533
- ),
534
- command.live.value.scope,
535
- );
536
- break;
537
- }
538
- case "Release":
539
- case "Leave":
540
- yield* Deferred.succeed(
541
- command.live.value.revoked,
542
- superseded(command.live.number, command.ending),
543
- );
544
- runRelease(command.live.number, releaseGeneration(command, state, apply));
545
- break;
546
- }
547
- });
548
-
549
- const openGeneration = (number: number) => {
550
- const openOnce = acquireGeneration(
551
- Effect.gen(function* () {
552
- const after = admissionAfter(state.value);
553
-
554
- if (exclusive && after !== undefined) yield* after;
555
- yield* options.admit?.({ number, after }) ?? Effect.void;
556
-
557
- return yield* options.open.pipe(
558
- Effect.provideService(Releasing, {
559
- released: (released) =>
560
- apply({ _tag: "AttemptReleased", number, released }).pipe(Effect.asVoid),
561
- }),
562
- );
563
- }),
564
- own,
565
- ).pipe(Effect.provideContext(context));
566
-
567
- return Effect.uninterruptibleMask((restore) =>
568
- restore(
569
- Effect.retry(openOnce, {
570
- schedule: reopen,
571
- while: (error) => !options.definite?.(error),
572
- }),
573
- ).pipe(
574
- Effect.exit,
575
- Effect.flatMap((exit) => {
576
- if (Exit.isSuccess(exit))
577
- return apply({ _tag: "Opened", live: { number, value: exit.value } });
578
- const cause = exit.cause;
579
-
580
- return apply(
581
- Cause.hasInterruptsOnly(cause)
582
- ? { _tag: "Abandoned", number }
583
- : { _tag: "Failed", number, detail: describe(cause), cause: Cause.squash(cause) },
584
- );
585
- }),
586
- ),
587
- );
588
- };
589
-
590
- const end = yield* Effect.cached(PubSub.publish(events, Exit.void));
591
-
592
- const stop = Effect.fnUntraced(function* (input: Input<A | void>) {
593
- yield* apply(input);
594
- yield* FiberHandle.clear(opening);
595
- yield* FiberMap.awaitEmpty(releases);
596
- if (yield* Deferred.isDone(releases.deferred)) yield* FiberMap.join(releases);
597
- }, Effect.ensuring(end));
598
-
599
- const retire = yield* Effect.cached(stop({ _tag: "Retire" }));
600
-
601
- // The browser of the generation serving, or of the one `target` names once it serves.
602
- const browserOf = (target?: number) =>
603
- Effect.map(waitFor(state, waitTimeout, clock, target), (live) => live.value.opened.browser);
604
-
605
- yield* Effect.addFinalizer(() => (options.keep === true ? stop({ _tag: "Keep" }) : retire));
606
- yield* perform(started);
607
-
608
- return {
609
- browser: browserOf(),
610
- use: leasing(state, apply, waitTimeout, now, clock),
611
- states: Stream.fromPubSubTake(events),
612
- rotate: apply({ _tag: "Rotate" }).pipe(
613
- Effect.flatMap(({ reply }) =>
614
- reply === undefined ? Effect.fail(retired()) : browserOf(reply),
615
- ),
616
- ),
617
- retire,
618
- };
619
- });
620
-
621
- /** Supervise scoped generation values. Browser-only providers retain their existing void value. */
622
- export function make<E, R, A = void>(
623
- options: Options<E, R, A>,
624
- ): Effect.Effect<Supervisor<A>, never, Scope.Scope | Exclude<R, Scope.Scope>>;
625
-
626
- export function make<E, R>(
627
- options: MakeOptions<E, R, never>,
628
- ): Effect.Effect<Supervisor<void>, never, Scope.Scope | Exclude<R, Scope.Scope>>;
629
-
630
- export function make<E, R, A>(options: MakeOptions<E, R, A>) {
631
- return makeScoped(options);
632
- }