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
@@ -1,264 +0,0 @@
1
- import { BrowserError, Busy } from "./BrowserError.mjs";
2
- import { Context, Deferred, Duration, Effect, Exit } from "effect";
3
- //#region src/internal/page/lane.ts
4
- /**
5
- * A page's admission: the one lane every operation on the page takes its turn in, so a page waits
6
- * only for itself. A write, an action that sends input or navigates, holds the lane alone, in the
7
- * order writes asked; reads share it, after the write in flight and every write asked before them,
8
- * so a read describes the page an action left, never one an action is still changing. Each write
9
- * starts a new epoch as it asks. A turn not given in time fails `Busy`, never `Timeout`, and a
10
- * caller under `FailFast` gets it at once.
11
- *
12
- * Reads keep their work. An identical read asked in the same epoch and document joins the one in
13
- * flight, which runs in the page's scope under the action timeout whoever gives up; one that ends
14
- * after all its callers gave up serves the next to ask the same, within an action timeout. A write
15
- * stops the reads nobody awaits, since no caller after it could use them.
16
- *
17
- * Effect's `Semaphore` is not fair to a writer that needs every permit, so the rule is this
18
- * module's own: one state, changed by `step` alone, which the model test drives.
19
- */
20
- const initial = {
21
- turn: { _tag: "Free" },
22
- queue: [],
23
- epoch: 0
24
- };
25
- const holders = (turn) => turn._tag === "Reading" ? turn.count : turn._tag === "Writing" ? 1 : 0;
26
- /** Whether a ticket of `kind` asking now would hold the lane at once. */
27
- const admitsNow = ({ turn, queue }, kind) => queue.length === 0 && (kind === "read" ? turn._tag !== "Writing" : turn._tag === "Free");
28
- /**
29
- * The operations ahead of a waiting ticket: those holding the lane and those asked before it, or
30
- * all that are queued for a ticket not in the queue.
31
- */
32
- const ahead = ({ turn, queue }, id) => {
33
- const at = queue.findIndex((ticket) => ticket.id === id);
34
- return holders(turn) + (at === -1 ? queue.length : at);
35
- };
36
- /**
37
- * The lane after `input`, and the tickets it lets in. Tickets go in from the head of the queue
38
- * only: a write once the lane is free, reads while no write holds it, so reads asked before a
39
- * write go before it, and reads asked after it wait for it.
40
- */
41
- const step = (state, input) => {
42
- let { turn, queue, epoch } = state;
43
- if (input._tag === "Ask") {
44
- queue = [...queue, input.ticket];
45
- if (input.ticket.kind === "write") epoch += 1;
46
- } else {
47
- const at = queue.findIndex((ticket) => ticket.id === input.ticket.id);
48
- if (at !== -1) queue = queue.toSpliced(at, 1);
49
- else turn = turn._tag === "Reading" && turn.count > 1 ? {
50
- _tag: "Reading",
51
- count: turn.count - 1
52
- } : { _tag: "Free" };
53
- }
54
- const admitted = [];
55
- for (const ticket of queue) {
56
- if (ticket.kind === "write" ? turn._tag !== "Free" : turn._tag === "Writing") break;
57
- admitted.push(ticket);
58
- turn = ticket.kind === "write" ? { _tag: "Writing" } : {
59
- _tag: "Reading",
60
- count: holders(turn) + 1
61
- };
62
- }
63
- return {
64
- state: {
65
- turn,
66
- queue: queue.slice(admitted.length),
67
- epoch
68
- },
69
- admitted
70
- };
71
- };
72
- /** Whether operations on a busy page fail `Busy` at once rather than wait their turn. */
73
- const FailFast = Context.Reference("effect-browser/internal/page/FailFast", { defaultValue: () => false });
74
- /** The id a caller gives the actions it asks for, which each records as its `correlation`. */
75
- const Correlation = Context.Reference("effect-browser/internal/page/Correlation", { defaultValue: () => void 0 });
76
- const make = (options) => {
77
- const { now, actionTimeout } = options;
78
- let state = initial;
79
- let tickets = 0;
80
- const admissions = /* @__PURE__ */ new Map();
81
- const sweeps = [];
82
- const apply = (input) => {
83
- const next = step(state, input);
84
- state = next.state;
85
- if (input._tag === "Leave") admissions.delete(input.ticket.id);
86
- for (const ticket of next.admitted) {
87
- const admitted = admissions.get(ticket.id);
88
- admissions.delete(ticket.id);
89
- if (admitted !== void 0) Deferred.doneUnsafe(admitted, Exit.void);
90
- }
91
- if (input._tag === "Ask" && input.ticket.kind === "write") for (const sweep of sweeps) sweep();
92
- };
93
- const busy = (operation, askedAt, id) => new BrowserError({
94
- operation,
95
- reason: new Busy({
96
- waitedMillis: Math.round(now() - askedAt),
97
- ahead: ahead(state, id)
98
- }),
99
- dispatched: false
100
- });
101
- /**
102
- * Run `effect` in a turn of `kind`, waiting at most `wait` for it, or failing `Busy`. The turn
103
- * ends with `effect`, however it ends.
104
- */
105
- const turn = (kind, operation, wait) => (effect) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
106
- const ticket = {
107
- id: ++tickets,
108
- kind
109
- };
110
- const askedAt = now();
111
- if (kind === "write" && options.inputGate !== void 0) yield* options.inputGate.check(operation);
112
- if ((yield* FailFast) && !admitsNow(state, kind)) return yield* busy(operation, askedAt);
113
- const admitted = Deferred.makeUnsafe();
114
- admissions.set(ticket.id, admitted);
115
- apply({
116
- _tag: "Ask",
117
- ticket
118
- });
119
- const waiting = Deferred.await(admitted).pipe(Effect.timeoutOrElse({
120
- duration: wait,
121
- orElse: () => Deferred.isDoneUnsafe(admitted) ? Effect.void : Effect.fail(busy(operation, askedAt, ticket.id))
122
- }));
123
- const given = yield* Effect.exit(restore(kind === "write" && options.inputGate !== void 0 ? Effect.raceFirst(waiting, options.inputGate.refused(operation)) : waiting));
124
- if (Exit.isFailure(given)) {
125
- apply({
126
- _tag: "Leave",
127
- ticket
128
- });
129
- return yield* Effect.failCause(given.cause);
130
- }
131
- return yield* restore(effect).pipe(Effect.ensuring(Effect.sync(() => apply({
132
- _tag: "Leave",
133
- ticket
134
- }))));
135
- }));
136
- /**
137
- * A read whose identical calls share their work: `work` runs once per epoch and document while
138
- * calls await it, and with `keep` its result serves the next call after all of them gave up,
139
- * within an action timeout of its end. Pictures, whose callers say how old they may be, only
140
- * join.
141
- */
142
- const shared = (operation, keep) => {
143
- const flights = /* @__PURE__ */ new Map();
144
- const kept = /* @__PURE__ */ new Map();
145
- sweeps.push(() => {
146
- kept.clear();
147
- for (const flight of flights.values()) if (flight.waiting === 0) flight.fiber?.interruptUnsafe();
148
- });
149
- const start = (id, work) => Effect.gen(function* () {
150
- const flight = {
151
- epoch: state.epoch,
152
- result: Deferred.makeUnsafe(),
153
- waiting: 1,
154
- fiber: void 0
155
- };
156
- flights.set(id, flight);
157
- flight.fiber = yield* turn("read", operation, actionTimeout)(work).pipe(Effect.provideService(FailFast, false), Effect.forkIn(options.scope));
158
- flight.fiber.addObserver((exit) => {
159
- flights.delete(id);
160
- if (keep && Exit.isSuccess(exit) && flight.waiting === 0 && flight.epoch === state.epoch) kept.set(id, {
161
- value: exit.value,
162
- until: now() + Duration.toMillis(actionTimeout)
163
- });
164
- Deferred.doneUnsafe(flight.result, Exit.hasInterrupts(exit) ? Effect.fail(options.gone(operation)) : exit);
165
- });
166
- return flight;
167
- });
168
- const join = (id, work) => Effect.acquireUseRelease(Effect.suspend(() => {
169
- const flying = flights.get(id);
170
- if (flying === void 0) return start(id, work);
171
- flying.waiting += 1;
172
- return Effect.as(Effect.annotateCurrentSpan("shared", "joined"), flying);
173
- }), (flight) => Deferred.await(flight.result), (flight) => Effect.sync(() => {
174
- flight.waiting -= 1;
175
- if (flight.waiting === 0 && flight.epoch < state.epoch) flight.fiber?.interruptUnsafe();
176
- }));
177
- return (key, work) => Effect.gen(function* () {
178
- const id = `${state.epoch} ${options.documentAt()} ${key}`;
179
- const at = now();
180
- for (const [old, { until }] of kept) if (until < at) kept.delete(old);
181
- const hit = kept.get(id);
182
- if (hit !== void 0) {
183
- kept.delete(id);
184
- yield* Effect.annotateCurrentSpan("shared", "kept");
185
- return hit.value;
186
- }
187
- if ((yield* FailFast) && !admitsNow(state, "read")) return yield* busy(operation, at);
188
- return yield* join(id, work);
189
- });
190
- };
191
- return {
192
- /** A turn alone, for an action: `wait` bounds the wait for it. */
193
- write: (operation, wait) => turn("write", operation, wait),
194
- /** A turn beside other reads, waited for within the action timeout. */
195
- read: (operation, wait = actionTimeout) => turn("read", operation, wait),
196
- shared
197
- };
198
- };
199
- //#endregion
200
- //#region src/internal/page/url.ts
201
- /**
202
- * Addresses: reading one the way a person types it, for `Page.goto` and the browser tools alike,
203
- * and reporting one without the values that are credentials, by one rule that the page script runs
204
- * too, for the outline's links.
205
- */
206
- const scheme = /^[a-z][a-z0-9+.-]*:/i;
207
- const hostAndPort = /^[^\s/?#@:]+:\d+(?:[/?#]|$)/;
208
- const loopback = /^(?:localhost|127(?:\.\d+){3}|\[::1\])(?:[:/?#]|$)/i;
209
- /** The URL `input` names. Without a scheme it is a web address: HTTPS, or HTTP on loopback. */
210
- const parse = (input) => {
211
- const text = input.trim();
212
- if (scheme.test(text) && !hostAndPort.test(text)) return URL.parse(text);
213
- return URL.parse(`${loopback.test(text) ? "http" : "https"}://${text}`);
214
- };
215
- /**
216
- * The rule that reports an address without its credentials. The page script runs it too, so it
217
- * stays self-contained, as `names.inpage.ts` says a page-side part must.
218
- */
219
- const addresses = () => {
220
- const withheld = "••••••••";
221
- const credential = /token|secret|passw|passcode|passphrase|signature|credential|assertion|verifier|bearer|jwt|hmac|apikey|accesskey|privatekey|sess(?:ion)?id|saml(?:response|art)|(?:sig|otp)$|(?:auth|api|access|private|secret|signing|client|encryption|licen[cs]e|session|master|app|device|verification|verify|confirmation|confirm|activation|activate|reset|recovery|login|security|magic|onetime|mfa|2fa|sms|email|otp|oob)(?:code|key)$|^(?:auth|authorization|pwd|pass)$/;
222
- const ambiguous = /^(?:code|key|session|sid|ticket)$/;
223
- const secret = (name, value) => {
224
- const bare = name.toLowerCase().replace(/[^a-z0-9]/g, "");
225
- return value !== "" && (credential.test(bare) || ambiguous.test(bare) && value.length >= 16 && /\d/.test(value) && /[a-z]/i.test(value));
226
- };
227
- const masked = (parameters, separator) => parameters.split(separator).map((parameter) => {
228
- const [name = "", value = ""] = [...new URLSearchParams(parameter)][0] ?? [];
229
- return secret(name, value) ? `${parameter.slice(0, parameter.indexOf("=") + 1)}${withheld}` : parameter;
230
- }).join(separator);
231
- /**
232
- * `url` as the library reports it: without userinfo, and with each credential's value withheld,
233
- * so the rest keeps its identity, such as a chart's `?ticker=ETH`. An address without a host,
234
- * such as `data:` or `about:blank`, is content or a fixed name, and stays as it is.
235
- */
236
- const redact = (url) => {
237
- const parsed = URL.parse(url);
238
- if (parsed === null || parsed.host === "") return url;
239
- parsed.username = "";
240
- parsed.password = "";
241
- parsed.pathname = masked(parsed.pathname, ";");
242
- parsed.search = masked(parsed.search.slice(1), "&");
243
- if (parsed.hash.includes("=")) {
244
- const fragment = parsed.hash.slice(1);
245
- const question = fragment.indexOf("?");
246
- const start = question >= 0 && question < fragment.indexOf("=") ? question + 1 : 0;
247
- parsed.hash = fragment.slice(0, start) + masked(fragment.slice(start), "&");
248
- }
249
- return parsed.href.replaceAll(encodeURIComponent(withheld), withheld);
250
- };
251
- return {
252
- withheld,
253
- redact
254
- };
255
- };
256
- const { withheld, redact } = addresses();
257
- /** An address inside text, as a failure's message quotes one. */
258
- const quoted = /[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/gi;
259
- /** `text` with each address in it redacted. */
260
- const redactWithin = (text) => text.replace(quoted, (url) => redact(url));
261
- //#endregion
262
- export { redactWithin as a, FailFast as c, redact as i, make as l, parse as n, withheld as o, quoted as r, Correlation as s, addresses as t };
263
-
264
- //# sourceMappingURL=url-Cd04Okid.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"url-Cd04Okid.mjs","names":[],"sources":["../src/internal/page/lane.ts","../src/internal/page/url.ts"],"sourcesContent":["/**\n * A page's admission: the one lane every operation on the page takes its turn in, so a page waits\n * only for itself. A write, an action that sends input or navigates, holds the lane alone, in the\n * order writes asked; reads share it, after the write in flight and every write asked before them,\n * so a read describes the page an action left, never one an action is still changing. Each write\n * starts a new epoch as it asks. A turn not given in time fails `Busy`, never `Timeout`, and a\n * caller under `FailFast` gets it at once.\n *\n * Reads keep their work. An identical read asked in the same epoch and document joins the one in\n * flight, which runs in the page's scope under the action timeout whoever gives up; one that ends\n * after all its callers gave up serves the next to ask the same, within an action timeout. A write\n * stops the reads nobody awaits, since no caller after it could use them.\n *\n * Effect's `Semaphore` is not fair to a writer that needs every permit, so the rule is this\n * module's own: one state, changed by `step` alone, which the model test drives.\n */\nimport { Context, Deferred, Duration, Effect, Exit, type Fiber, type Scope } from \"effect\";\n\nimport { BrowserError, Busy } from \"../../BrowserError.ts\";\nimport type { Gate } from \"../input/gate.ts\";\n\nexport type Kind = \"read\" | \"write\";\n\nexport interface Ticket {\n readonly id: number;\n readonly kind: Kind;\n}\n\n/** Who holds the lane: no one, reads together, or one write. */\nexport type Turn =\n | { readonly _tag: \"Free\" }\n | { readonly _tag: \"Reading\"; readonly count: number }\n | { readonly _tag: \"Writing\" };\n\nexport interface State {\n readonly turn: Turn;\n /** The tickets waiting, in the order they asked. */\n readonly queue: ReadonlyArray<Ticket>;\n /** The writes asked so far: two reads in one epoch follow the same writes. */\n readonly epoch: number;\n}\n\nexport type Input =\n | { readonly _tag: \"Ask\"; readonly ticket: Ticket }\n /** The ticket gave up waiting, or ended its turn. */\n | { readonly _tag: \"Leave\"; readonly ticket: Ticket };\n\nexport const initial: State = { turn: { _tag: \"Free\" }, queue: [], epoch: 0 };\n\nconst holders = (turn: Turn) =>\n turn._tag === \"Reading\" ? turn.count : turn._tag === \"Writing\" ? 1 : 0;\n\n/** Whether a ticket of `kind` asking now would hold the lane at once. */\nexport const admitsNow = ({ turn, queue }: State, kind: Kind) =>\n queue.length === 0 && (kind === \"read\" ? turn._tag !== \"Writing\" : turn._tag === \"Free\");\n\n/**\n * The operations ahead of a waiting ticket: those holding the lane and those asked before it, or\n * all that are queued for a ticket not in the queue.\n */\nexport const ahead = ({ turn, queue }: State, id?: number) => {\n const at = queue.findIndex((ticket) => ticket.id === id);\n\n return holders(turn) + (at === -1 ? queue.length : at);\n};\n\n/**\n * The lane after `input`, and the tickets it lets in. Tickets go in from the head of the queue\n * only: a write once the lane is free, reads while no write holds it, so reads asked before a\n * write go before it, and reads asked after it wait for it.\n */\nexport const step = (\n state: State,\n input: Input,\n): { readonly state: State; readonly admitted: ReadonlyArray<Ticket> } => {\n let { turn, queue, epoch } = state;\n\n if (input._tag === \"Ask\") {\n queue = [...queue, input.ticket];\n if (input.ticket.kind === \"write\") epoch += 1;\n } else {\n const at = queue.findIndex((ticket) => ticket.id === input.ticket.id);\n\n if (at !== -1) queue = queue.toSpliced(at, 1);\n else\n turn =\n turn._tag === \"Reading\" && turn.count > 1\n ? { _tag: \"Reading\", count: turn.count - 1 }\n : { _tag: \"Free\" };\n }\n\n const admitted: Array<Ticket> = [];\n\n for (const ticket of queue) {\n if (ticket.kind === \"write\" ? turn._tag !== \"Free\" : turn._tag === \"Writing\") break;\n admitted.push(ticket);\n turn =\n ticket.kind === \"write\" ? { _tag: \"Writing\" } : { _tag: \"Reading\", count: holders(turn) + 1 };\n }\n\n return { state: { turn, queue: queue.slice(admitted.length), epoch }, admitted };\n};\n\n/** Whether operations on a busy page fail `Busy` at once rather than wait their turn. */\nexport const FailFast = Context.Reference<boolean>(\"effect-browser/internal/page/FailFast\", {\n defaultValue: () => false,\n});\n\n/** The id a caller gives the actions it asks for, which each records as its `correlation`. */\nexport const Correlation = Context.Reference<string | undefined>(\n \"effect-browser/internal/page/Correlation\",\n { defaultValue: () => undefined },\n);\n\n/** A shared read in flight: its epoch, its result once it ends, and how many callers await it. */\ninterface Flight<A> {\n readonly epoch: number;\n readonly result: Deferred.Deferred<A, BrowserError>;\n waiting: number;\n fiber: Fiber.Fiber<A, BrowserError> | undefined;\n}\n\nexport const make = (options: {\n readonly now: () => number;\n readonly actionTimeout: Duration.Duration;\n /** When the page's current document began: a read is shared only within one. */\n readonly documentAt: () => number;\n /** The failure of a read still awaited as the page closes. */\n readonly gone: (operation: string) => BrowserError;\n /** The page's scope, which shared reads run in. */\n readonly scope: Scope.Scope;\n readonly inputGate?: Gate | undefined;\n}) => {\n const { now, actionTimeout } = options;\n let state = initial;\n let tickets = 0;\n const admissions = new Map<number, Deferred.Deferred<void>>();\n // Each shared read's sweep, which a write runs as it asks.\n const sweeps: Array<() => void> = [];\n\n const apply = (input: Input) => {\n const next = step(state, input);\n\n state = next.state;\n if (input._tag === \"Leave\") admissions.delete(input.ticket.id);\n for (const ticket of next.admitted) {\n const admitted = admissions.get(ticket.id);\n\n admissions.delete(ticket.id);\n if (admitted !== undefined) Deferred.doneUnsafe(admitted, Exit.void);\n }\n if (input._tag === \"Ask\" && input.ticket.kind === \"write\") for (const sweep of sweeps) sweep();\n };\n\n const busy = (operation: string, askedAt: number, id?: number) =>\n new BrowserError({\n operation,\n reason: new Busy({ waitedMillis: Math.round(now() - askedAt), ahead: ahead(state, id) }),\n dispatched: false,\n });\n\n /**\n * Run `effect` in a turn of `kind`, waiting at most `wait` for it, or failing `Busy`. The turn\n * ends with `effect`, however it ends.\n */\n const turn =\n (kind: Kind, operation: string, wait: Duration.Duration) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | BrowserError, R> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const ticket: Ticket = { id: ++tickets, kind };\n const askedAt = now();\n\n if (kind === \"write\" && options.inputGate !== undefined)\n yield* options.inputGate.check(operation);\n\n if ((yield* FailFast) && !admitsNow(state, kind)) return yield* busy(operation, askedAt);\n const admitted = Deferred.makeUnsafe<void>();\n\n admissions.set(ticket.id, admitted);\n apply({ _tag: \"Ask\", ticket });\n\n const waiting = Deferred.await(admitted).pipe(\n Effect.timeoutOrElse({\n duration: wait,\n orElse: () =>\n Deferred.isDoneUnsafe(admitted)\n ? Effect.void\n : Effect.fail(busy(operation, askedAt, ticket.id)),\n }),\n );\n\n const given = yield* Effect.exit(\n restore(\n kind === \"write\" && options.inputGate !== undefined\n ? Effect.raceFirst(waiting, options.inputGate.refused(operation))\n : waiting,\n ),\n );\n\n if (Exit.isFailure(given)) {\n apply({ _tag: \"Leave\", ticket });\n\n return yield* Effect.failCause(given.cause);\n }\n\n return yield* restore(effect).pipe(\n Effect.ensuring(Effect.sync(() => apply({ _tag: \"Leave\", ticket }))),\n );\n }),\n );\n\n /**\n * A read whose identical calls share their work: `work` runs once per epoch and document while\n * calls await it, and with `keep` its result serves the next call after all of them gave up,\n * within an action timeout of its end. Pictures, whose callers say how old they may be, only\n * join.\n */\n const shared = <A>(operation: string, keep: boolean) => {\n const flights = new Map<string, Flight<A>>();\n const kept = new Map<string, { readonly value: A; readonly until: number }>();\n\n sweeps.push(() => {\n kept.clear();\n for (const flight of flights.values())\n if (flight.waiting === 0) flight.fiber?.interruptUnsafe();\n });\n\n // A read in flight, its first caller waiting. However its fiber ends, even before it began,\n // as when the page closes, its callers hear.\n const start = (id: string, work: Effect.Effect<A, BrowserError>) =>\n Effect.gen(function* () {\n const flight: Flight<A> = {\n epoch: state.epoch,\n result: Deferred.makeUnsafe(),\n waiting: 1,\n fiber: undefined,\n };\n\n flights.set(id, flight);\n flight.fiber = yield* turn(\n \"read\",\n operation,\n actionTimeout,\n )(work).pipe(\n // The caller chose whether to wait; the work it started serves others too.\n Effect.provideService(FailFast, false),\n Effect.forkIn(options.scope),\n );\n flight.fiber.addObserver((exit) => {\n flights.delete(id);\n if (keep && Exit.isSuccess(exit) && flight.waiting === 0 && flight.epoch === state.epoch)\n kept.set(id, { value: exit.value, until: now() + Duration.toMillis(actionTimeout) });\n Deferred.doneUnsafe(\n flight.result,\n Exit.hasInterrupts(exit) ? Effect.fail(options.gone(operation)) : exit,\n );\n });\n\n return flight;\n });\n\n const join = (id: string, work: Effect.Effect<A, BrowserError>) =>\n Effect.acquireUseRelease(\n Effect.suspend(() => {\n const flying = flights.get(id);\n\n if (flying === undefined) return start(id, work);\n flying.waiting += 1;\n\n return Effect.as(Effect.annotateCurrentSpan(\"shared\", \"joined\"), flying);\n }),\n (flight) => Deferred.await(flight.result),\n (flight) =>\n Effect.sync(() => {\n flight.waiting -= 1;\n if (flight.waiting === 0 && flight.epoch < state.epoch) flight.fiber?.interruptUnsafe();\n }),\n );\n\n return (key: string, work: Effect.Effect<A, BrowserError>): Effect.Effect<A, BrowserError> =>\n Effect.gen(function* () {\n const id = `${state.epoch} ${options.documentAt()} ${key}`;\n const at = now();\n\n for (const [old, { until }] of kept) if (until < at) kept.delete(old);\n const hit = kept.get(id);\n\n if (hit !== undefined) {\n kept.delete(id);\n yield* Effect.annotateCurrentSpan(\"shared\", \"kept\");\n\n return hit.value;\n }\n if ((yield* FailFast) && !admitsNow(state, \"read\")) return yield* busy(operation, at);\n\n return yield* join(id, work);\n });\n };\n\n return {\n /** A turn alone, for an action: `wait` bounds the wait for it. */\n write: (operation: string, wait: Duration.Duration) => turn(\"write\", operation, wait),\n /** A turn beside other reads, waited for within the action timeout. */\n read: (operation: string, wait: Duration.Duration = actionTimeout) =>\n turn(\"read\", operation, wait),\n shared,\n };\n};\n\nexport type Lane = ReturnType<typeof make>;\n","/**\n * Addresses: reading one the way a person types it, for `Page.goto` and the browser tools alike,\n * and reporting one without the values that are credentials, by one rule that the page script runs\n * too, for the outline's links.\n */\n\nconst scheme = /^[a-z][a-z0-9+.-]*:/i;\n\n// `localhost:3000` and `example.com:8080/a` look like a scheme to the URL parser; a port decides.\nconst hostAndPort = /^[^\\s/?#@:]+:\\d+(?:[/?#]|$)/;\n\nconst loopback = /^(?:localhost|127(?:\\.\\d+){3}|\\[::1\\])(?:[:/?#]|$)/i;\n\n/** The URL `input` names. Without a scheme it is a web address: HTTPS, or HTTP on loopback. */\nexport const parse = (input: string): URL | null => {\n const text = input.trim();\n\n if (scheme.test(text) && !hostAndPort.test(text)) return URL.parse(text);\n\n return URL.parse(`${loopback.test(text) ? \"http\" : \"https\"}://${text}`);\n};\n\n/**\n * The rule that reports an address without its credentials. The page script runs it too, so it\n * stays self-contained, as `names.inpage.ts` says a page-side part must.\n */\nexport const addresses = () => {\n // What a credential's value reads as, as a secret field's text does (`Page.redacted`).\n const withheld = \"••••••••\" as const;\n\n // A parameter's name, compared in lowercase without separators, says it is a credential: a token,\n // secret, password, signature, assertion, session id or one-time code, or a code or key of a kind\n // that signs someone in or signs a request, such as `verification_code` or `api_key`.\n const credential =\n /token|secret|passw|passcode|passphrase|signature|credential|assertion|verifier|bearer|jwt|hmac|apikey|accesskey|privatekey|sess(?:ion)?id|saml(?:response|art)|(?:sig|otp)$|(?:auth|api|access|private|secret|signing|client|encryption|licen[cs]e|session|master|app|device|verification|verify|confirmation|confirm|activation|activate|reset|recovery|login|security|magic|onetime|mfa|2fa|sms|email|otp|oob)(?:code|key)$|^(?:auth|authorization|pwd|pass)$/;\n\n // These names as often say what an address is about, such as a stock code, a support ticket or a\n // conference session. Under them a value is a credential when it looks generated, at least 16\n // characters with letters and digits, as tokens, session ids and authorization codes do.\n const ambiguous = /^(?:code|key|session|sid|ticket)$/;\n\n const secret = (name: string, value: string) => {\n const bare = name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\n return (\n value !== \"\" &&\n (credential.test(bare) ||\n (ambiguous.test(bare) && value.length >= 16 && /\\d/.test(value) && /[a-z]/i.test(value)))\n );\n };\n\n // Parameters as written, each credential's value withheld: a query's, a fragment's written as a\n // query, or a path's segments', as a Java session id is.\n const masked = (parameters: string, separator: string) =>\n parameters\n .split(separator)\n .map((parameter) => {\n const [name = \"\", value = \"\"] = [...new URLSearchParams(parameter)][0] ?? [];\n\n return secret(name, value)\n ? `${parameter.slice(0, parameter.indexOf(\"=\") + 1)}${withheld}`\n : parameter;\n })\n .join(separator);\n\n /**\n * `url` as the library reports it: without userinfo, and with each credential's value withheld,\n * so the rest keeps its identity, such as a chart's `?ticker=ETH`. An address without a host,\n * such as `data:` or `about:blank`, is content or a fixed name, and stays as it is.\n */\n const redact = (url: string): string => {\n const parsed = URL.parse(url);\n\n if (parsed === null || parsed.host === \"\") return url;\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.pathname = masked(parsed.pathname, \";\");\n parsed.search = masked(parsed.search.slice(1), \"&\");\n if (parsed.hash.includes(\"=\")) {\n const fragment = parsed.hash.slice(1);\n const question = fragment.indexOf(\"?\");\n // A route before the parameters, as in `#/inbox?token=…`, stays.\n const start = question >= 0 && question < fragment.indexOf(\"=\") ? question + 1 : 0;\n\n parsed.hash = fragment.slice(0, start) + masked(fragment.slice(start), \"&\");\n }\n\n return parsed.href.replaceAll(encodeURIComponent(withheld), withheld);\n };\n\n return { withheld, redact };\n};\n\nexport const { withheld, redact } = addresses();\n\n/** An address inside text, as a failure's message quotes one. */\nexport const quoted = /[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi;\n\n/** `text` with each address in it redacted. */\nexport const redactWithin = (text: string) => text.replace(quoted, (url) => redact(url));\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+CA,MAAa,UAAiB;CAAE,MAAM,EAAE,MAAM,OAAO;CAAG,OAAO,CAAC;CAAG,OAAO;AAAE;AAE5E,MAAM,WAAW,SACf,KAAK,SAAS,YAAY,KAAK,QAAQ,KAAK,SAAS,YAAY,IAAI;;AAGvE,MAAa,aAAa,EAAE,MAAM,SAAgB,SAChD,MAAM,WAAW,MAAM,SAAS,SAAS,KAAK,SAAS,YAAY,KAAK,SAAS;;;;;AAMnF,MAAa,SAAS,EAAE,MAAM,SAAgB,OAAgB;CAC5D,MAAM,KAAK,MAAM,WAAW,WAAW,OAAO,OAAO,EAAE;CAEvD,OAAO,QAAQ,IAAI,KAAK,OAAO,KAAK,MAAM,SAAS;AACrD;;;;;;AAOA,MAAa,QACX,OACA,UACwE;CACxE,IAAI,EAAE,MAAM,OAAO,UAAU;CAE7B,IAAI,MAAM,SAAS,OAAO;EACxB,QAAQ,CAAC,GAAG,OAAO,MAAM,MAAM;EAC/B,IAAI,MAAM,OAAO,SAAS,SAAS,SAAS;CAC9C,OAAO;EACL,MAAM,KAAK,MAAM,WAAW,WAAW,OAAO,OAAO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KAAK,QAAQ,SAAS,QAAQ,OAAO,GAAG,CAAC"}
package/src/Cdp.ts DELETED
@@ -1,101 +0,0 @@
1
- /**
2
- * A browser reached over the Chrome DevTools Protocol: a Chrome started with
3
- * `--remote-debugging-port`, or any provider that hands out a CDP WebSocket URL.
4
- *
5
- * Closing the scope disconnects. It does not close the remote browser; its owner does that.
6
- *
7
- * @since 0.3.0
8
- */
9
- import { type DateTime, Effect, Layer, Redacted } from "effect";
10
- import { chromium } from "playwright-core";
11
-
12
- import * as Browser from "./Browser.ts";
13
- import { type BrowserError, Failed, type Reason } from "./BrowserError.ts";
14
- import { reasonOf, undispatched } from "./internal/page/context.ts";
15
- import * as Url from "./internal/page/url.ts";
16
-
17
- export interface Options extends Browser.Options {
18
- /**
19
- * `ws://`, `wss://` or `http://` DevTools endpoint. Often a credential, so it may be redacted;
20
- * connect failures never include its userinfo, path or query.
21
- */
22
- readonly endpoint: string | Redacted.Redacted<string>;
23
- readonly headers?: Readonly<Record<string, string>> | undefined;
24
- /** Identifies the session in `Browser.id`. Defaults to `"cdp"`. */
25
- readonly id?: string | undefined;
26
- readonly provider?: string | undefined;
27
- /** Bound on connecting. Defaults to 30 seconds. */
28
- readonly connectTimeoutMillis?: number | undefined;
29
- /** When the provider ends the session on its own, as a hosted session's timeout does. */
30
- readonly expiresAt?: DateTime.Utc | undefined;
31
- /**
32
- * A connection apart from this one for the pages' screencasts, as a hosted provider supplies.
33
- * Without one, each page's capture runs on its own session.
34
- */
35
- readonly capture?: Browser.CaptureSource | undefined;
36
- }
37
-
38
- /**
39
- * Playwright can echo the endpoint, or a URL derived from it with its query, userinfo or path, in
40
- * a connect failure. Those parts are often the credential, so a URL keeps its scheme, host and
41
- * port, and any other echo of the endpoint is replaced.
42
- */
43
- const withoutEndpoint = (endpoint: string, reason: Reason): Reason => {
44
- if (reason._tag !== "Failed") return reason;
45
-
46
- const origins = reason.detail.replace(Url.quoted, (url) => {
47
- const parsed = URL.parse(url);
48
-
49
- return parsed === null || parsed.host === "" ? "<url>" : `${parsed.protocol}//${parsed.host}`;
50
- });
51
-
52
- return new Failed({
53
- detail: endpoint === "" ? origins : origins.replaceAll(endpoint, "<endpoint>"),
54
- });
55
- };
56
-
57
- /** Connect and open a `Browser` over the endpoint's first context. */
58
- export const open = Effect.fn("Cdp.open")(function* (options: Options) {
59
- const endpoint = Redacted.isRedacted(options.endpoint)
60
- ? Redacted.value(options.endpoint)
61
- : options.endpoint;
62
-
63
- const timeout = options.connectTimeoutMillis ?? 30_000;
64
-
65
- const failed = (cause: unknown, timeoutMillis?: number) =>
66
- undispatched("connect", withoutEndpoint(endpoint, reasonOf(cause, timeoutMillis)));
67
-
68
- // The endpoint is often a credential, so the connect span names no part of it.
69
- const connected = yield* Effect.acquireRelease(
70
- Effect.tryPromise({
71
- try: () =>
72
- chromium.connectOverCDP(endpoint, {
73
- timeout,
74
- ...(options.headers === undefined ? {} : { headers: { ...options.headers } }),
75
- }),
76
- catch: (cause) => failed(cause, timeout),
77
- }).pipe(Effect.withSpan("Cdp.connect", {}, { captureStackTrace: false })),
78
- (browser) => Effect.tryPromise(() => browser.close()).pipe(Effect.ignore),
79
- );
80
-
81
- const context =
82
- connected.contexts()[0] ??
83
- (yield* Effect.tryPromise({
84
- try: () => connected.newContext(),
85
- catch: (cause) => failed(cause),
86
- }));
87
-
88
- return yield* Browser.make(
89
- context,
90
- {
91
- id: options.id ?? "cdp",
92
- provider: options.provider ?? "cdp",
93
- expiresAt: options.expiresAt,
94
- capture: options.capture,
95
- },
96
- options,
97
- );
98
- });
99
-
100
- export const layer = (options: Options): Layer.Layer<Browser.Browser, BrowserError> =>
101
- Layer.effect(Browser.Browser, open(options));
package/src/Expect.ts DELETED
@@ -1,180 +0,0 @@
1
- /**
2
- * Expectations: what an action is for, checked on the page, so that an action whose outcome is
3
- * uncertain is sent again only where it did not take effect. An action that failed after its input
4
- * went, a `Timeout` or a `Closed` with `dispatched`, may have done what it was for; repeating it
5
- * blindly may do it twice, such as placing an order twice.
6
- *
7
- * An attempt takes its expectation's baseline from the page once, as it begins. Each `run` then
8
- * checks first: where the expectation holds already, it sends nothing and is `AlreadyDone`.
9
- * Otherwise it acts, and waits for the expectation: `Done`, or `NotDone` when it did not come in
10
- * time. An action that fails after its input went is checked too, `Done` if its effect came, and
11
- * otherwise fails as it did, so a later `run` of the same attempt checks before it acts again,
12
- * on the same page or on the one a reconnect finds by its id.
13
- *
14
- * ```ts
15
- * const placing = yield* Expect.attempt(page, Expect.appeared({ text: "Order placed" }))
16
- * const outcome = yield* placing.run(page, (page) => page.click("e12"))
17
- * // After a Timeout that left `dispatched`, the same call clicks again only if no order shows.
18
- * ```
19
- *
20
- * A query is `Page.find`'s, over the whole document unless it says otherwise, and each check is one
21
- * call to the page, a wait included; `navigated` reads the page's address and document, at no
22
- * call. What `changed` compares stays in the page: text, field values and states, focus aside.
23
- *
24
- * @since 0.3.0
25
- */
26
- import { Cause, Duration, Effect, Exit, Option, Schedule } from "effect";
27
-
28
- import { type BrowserError, InvalidRequest } from "./BrowserError.ts";
29
- import { undispatched } from "./internal/page/context.ts";
30
- import { type Internals, internalsOf } from "./internal/page/page.ts";
31
- import type { FindQuery, Page } from "./Page.ts";
32
-
33
- /** What an action is for, as the page can tell it. */
34
- export type Expectation =
35
- | { readonly _tag: "Appeared"; readonly query: FindQuery }
36
- | { readonly _tag: "Gone"; readonly query: FindQuery }
37
- | { readonly _tag: "Changed"; readonly query: FindQuery }
38
- | { readonly _tag: "Navigated"; readonly url: string | RegExp | undefined };
39
-
40
- /** Something the query finds. */
41
- export const appeared = (query: FindQuery): Expectation => ({ _tag: "Appeared", query });
42
-
43
- /** Nothing the query finds. */
44
- export const gone = (query: FindQuery): Expectation => ({ _tag: "Gone", query });
45
-
46
- /**
47
- * What the query finds shows something other than it did as the attempt began: other elements, or
48
- * their text, values or states.
49
- */
50
- export const changed = (query: FindQuery): Expectation => ({ _tag: "Changed", query });
51
-
52
- /**
53
- * The page is at `url`, the whole address or a pattern; without one, at an address or in a
54
- * document other than the attempt's first.
55
- */
56
- export const navigated = (url?: string | RegExp): Expectation => ({ _tag: "Navigated", url });
57
-
58
- /**
59
- * `Done`: the action ran, and what it was for came. `AlreadyDone`: it held before the action was
60
- * sent, so it was not. `NotDone`: the action ran, and it did not come within the attempt's wait.
61
- */
62
- export type Outcome = "Done" | "AlreadyDone" | "NotDone";
63
-
64
- export interface Options {
65
- /** How long an action's effect may take to show. Defaults to 5 seconds. */
66
- readonly wait?: Duration.Input | undefined;
67
- }
68
-
69
- export interface Attempt {
70
- readonly expectation: Expectation;
71
- /** Whether the expectation holds on `page` now. */
72
- readonly holds: (page: Page) => Effect.Effect<boolean, BrowserError>;
73
- /**
74
- * `act` on `page`, unless the expectation holds there already: see the module's comment. A
75
- * failure before its input went is the action's own, and nothing is checked.
76
- */
77
- readonly run: (
78
- page: Page,
79
- act: (page: Page) => Effect.Effect<unknown, BrowserError>,
80
- ) => Effect.Effect<Outcome, BrowserError>;
81
- }
82
-
83
- const refused = (detail: string) => undispatched("expect", new InvalidRequest({ detail }));
84
-
85
- const internalsFor = (page: Page): Effect.Effect<Internals, BrowserError> => {
86
- const internals = internalsOf(page);
87
-
88
- return internals === undefined
89
- ? Effect.fail(
90
- refused("only a page a Browser opened, or a presenter's view of one, can be checked"),
91
- )
92
- : Effect.succeed(internals);
93
- };
94
-
95
- const atUrl = (url: string, wanted: string | RegExp) =>
96
- typeof wanted === "string" ? url === wanted : new RegExp(wanted.source, wanted.flags).test(url);
97
-
98
- /** Begin an attempt at `expectation` on `page`, which takes its baseline from the page now. */
99
- export const attempt = Effect.fn("Expect.attempt")(function* (
100
- page: Page,
101
- expectation: Expectation,
102
- options: Options = {},
103
- ) {
104
- const wait = Duration.fromInput(options.wait ?? Duration.seconds(5));
105
-
106
- if (Option.isNone(wait) || Duration.isNegative(wait.value))
107
- return yield* refused("wait must be a duration, not negative");
108
- const waitMillis = Duration.toMillis(wait.value);
109
- const first = yield* page.state;
110
- const internals = yield* internalsFor(page);
111
-
112
- // What `changed` compares with: the mark of what the query found as the attempt began.
113
- const from =
114
- expectation._tag === "Changed"
115
- ? (yield* internals.until(expectation.query, "some", 0)).mark
116
- : undefined;
117
-
118
- // Navigated: at the address asked, or, without one, somewhere other than the attempt's first,
119
- // where a document counts only on the page that counted it, not on one a reconnect found.
120
- const navigatedOn = (target: Page, url: string | RegExp | undefined) =>
121
- Effect.map(target.state, (now) =>
122
- url !== undefined
123
- ? atUrl(now.url, url)
124
- : now.url !== first.url ||
125
- (internalsOf(target) === internals && now.document !== first.document),
126
- );
127
-
128
- const holdsWithin = (target: Page, millis: number): Effect.Effect<boolean, BrowserError> => {
129
- if (expectation._tag === "Navigated") {
130
- const look = navigatedOn(target, expectation.url);
131
-
132
- return look.pipe(
133
- Effect.repeat({
134
- until: (held) => held,
135
- schedule: Schedule.spaced(Duration.millis(50)),
136
- }),
137
- Effect.timeoutOrElse({ duration: Duration.millis(millis), orElse: () => look }),
138
- );
139
- }
140
-
141
- const want =
142
- expectation._tag === "Appeared"
143
- ? "some"
144
- : expectation._tag === "Gone"
145
- ? "none"
146
- : { other: from ?? "" };
147
-
148
- return internalsFor(target).pipe(
149
- Effect.flatMap((own) => own.until(expectation.query, want, millis)),
150
- Effect.map(({ met }) => met),
151
- );
152
- };
153
-
154
- const run = Effect.fn("Expect.run")(
155
- function* (target: Page, act: (page: Page) => Effect.Effect<unknown, BrowserError>) {
156
- if (yield* holdsWithin(target, 0)) return "AlreadyDone" as const;
157
- const acted = yield* Effect.exit(act(target));
158
-
159
- if (Exit.isSuccess(acted))
160
- return (yield* holdsWithin(target, waitMillis)) ? ("Done" as const) : ("NotDone" as const);
161
- const error = Cause.findErrorOption(acted.cause);
162
-
163
- // A failure before the input went did nothing; one after it may have done what it was for.
164
- if (Option.isNone(error) || !error.value.dispatched)
165
- return yield* Effect.failCause(acted.cause);
166
- const held = yield* Effect.exit(holdsWithin(target, waitMillis));
167
-
168
- return Exit.isSuccess(held) && held.value
169
- ? ("Done" as const)
170
- : yield* Effect.failCause(acted.cause);
171
- },
172
- Effect.tap((outcome) => Effect.annotateCurrentSpan({ expectation: expectation._tag, outcome })),
173
- );
174
-
175
- return {
176
- expectation,
177
- holds: (target) => holdsWithin(target, 0),
178
- run,
179
- } satisfies Attempt;
180
- });