effect-browser 0.2.0-beta.0 → 0.2.0-beta.1

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 (40) hide show
  1. package/README.md +150 -10
  2. package/dist/{Association-zlgInoaj.mjs → Association-BsSfBYVx.mjs} +14 -10
  3. package/dist/Association-BsSfBYVx.mjs.map +1 -0
  4. package/dist/{Bootstrap-Be-2Ddmh.mjs → Bootstrap-CeQOWBy6.mjs} +6 -4
  5. package/dist/Bootstrap-CeQOWBy6.mjs.map +1 -0
  6. package/dist/Bootstrap.mjs +1 -1
  7. package/dist/Browser.d.mts +13 -1
  8. package/dist/Browser.mjs.map +1 -1
  9. package/dist/{BrowserData-DJAnUHoZ.d.mts → BrowserData-CRuxEZcn.d.mts} +90 -10
  10. package/dist/BrowserData.d.mts +2 -2
  11. package/dist/BrowserData.mjs +85 -7
  12. package/dist/BrowserData.mjs.map +1 -1
  13. package/dist/BrowserRuntime-Coz-5DYb.d.mts +143 -0
  14. package/dist/{BrowserRuntime-fZz1b0VI.mjs → BrowserRuntime-DViKNUdD.mjs} +2819 -2206
  15. package/dist/BrowserRuntime-DViKNUdD.mjs.map +1 -0
  16. package/dist/BrowserRuntime.d.mts +3 -139
  17. package/dist/BrowserRuntime.mjs +1 -1
  18. package/dist/Capture.d.mts +15 -1
  19. package/dist/Capture.mjs +58 -22
  20. package/dist/Capture.mjs.map +1 -1
  21. package/dist/{CaptureData-AmqVP_Ba.mjs → CaptureData-B5-mXlyq.mjs} +24 -6
  22. package/dist/CaptureData-B5-mXlyq.mjs.map +1 -0
  23. package/dist/CaptureData.d.mts +11 -2
  24. package/dist/CaptureData.mjs +1 -1
  25. package/dist/Chromium.d.mts +4 -3
  26. package/dist/Chromium.mjs +22 -16
  27. package/dist/Chromium.mjs.map +1 -1
  28. package/dist/Errors.d.mts +2 -2
  29. package/dist/Errors.mjs +1 -0
  30. package/dist/Errors.mjs.map +1 -1
  31. package/dist/PageControl.d.mts +1 -1
  32. package/dist/PageControl.mjs +1 -1
  33. package/dist/Testing.d.mts +437 -0
  34. package/dist/Testing.mjs +1561 -0
  35. package/dist/Testing.mjs.map +1 -0
  36. package/package.json +5 -1
  37. package/dist/Association-zlgInoaj.mjs.map +0 -1
  38. package/dist/Bootstrap-Be-2Ddmh.mjs.map +0 -1
  39. package/dist/BrowserRuntime-fZz1b0VI.mjs.map +0 -1
  40. package/dist/CaptureData-AmqVP_Ba.mjs.map +0 -1
@@ -0,0 +1,1561 @@
1
+ import { BrowserError, InitializationError, Reasons } from "./Errors.mjs";
2
+ import { BrowserPolicy, ControlFacts, FrameInfo, Identifier, ObservedControl, PageExecutionState, PageInfo, PageSuspension, SafeFilename, TargetUrl, ViewportEvidence, ViewportRect } from "./BrowserData.mjs";
3
+ import { a as cleanupStep, c as checked, l as fromNativeAttempt, n as make, s as reported, u as issueBinding } from "./BrowserRuntime-DViKNUdD.mjs";
4
+ import { Crypto, Effect, Layer, Option, PlatformError, Redacted, Schema } from "effect";
5
+ //#region src/internal/testing/Crypto.ts
6
+ /**
7
+ * A `Crypto` whose bytes count up from one, so every id and handoff token a scripted browser draws
8
+ * is predictable. It is not random and computes no digest.
9
+ */
10
+ const makeSequentialCrypto = () => {
11
+ let draws = 0;
12
+ return Crypto.make({
13
+ randomBytes: (size) => {
14
+ const bytes = new Uint8Array(size);
15
+ let rest = ++draws;
16
+ for (let index = size - 1; index >= 0 && rest > 0; index--) {
17
+ bytes[index] = rest % 256;
18
+ rest = Math.floor(rest / 256);
19
+ }
20
+ return bytes;
21
+ },
22
+ digest: () => Effect.fail(PlatformError.badArgument({
23
+ module: "Crypto",
24
+ method: "digest",
25
+ description: "A scripted browser's Crypto computes no digest"
26
+ }))
27
+ });
28
+ };
29
+ //#endregion
30
+ //#region src/internal/testing/Frame.ts
31
+ /** A valid 64×48 baseline JPEG, the bytes a scripted capture frame carries by default. */
32
+ const jpegFrame = () => Uint8Array.from(atob("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCAAwAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDyVLf2qdLf2q6lv7VOlv7UoyMadcpJb+1Tpb+1XUt/ap0t/atoyPSp1yklv7VYS39qupb+1Tpb+1bxkejTrlJLf2qdLf2q6lv7VOlv7VtGR6NOuYKW/tU6W/tV1Lf2qwlv7V4kZH5fTrlFLf2qwlv7VdS39qnS39q2jI9GnXKSW/tU6W/tV1Lf2qdLf2raMj0adcpJb+1Tpb+1Xkt/ap0t/at4yPRp1zBS39qnS39qupb+1Tpb+1eHGR+X065SS39qnS39qupb+1Tpb+1bxkejTrlJLf2qwlv7VdS39qnS39q2jI9GnXKSW/tU6W/tV1Lf2qdLf2raMj0adc//2Q=="), (character) => character.charCodeAt(0));
33
+ //#endregion
34
+ //#region src/internal/testing/Script.ts
35
+ const uniqueBy = (key, title) => Schema.makeFilter((items) => new Set(items.map(key)).size === items.length, { title });
36
+ /** Host-only facts a scripted control reports beyond what its observed fields imply. */
37
+ const ControlFactsScript = Schema.Struct({
38
+ editable: Schema.optionalKey(Schema.Boolean),
39
+ formMethod: Schema.optionalKey(Schema.Literals([
40
+ "get",
41
+ "post",
42
+ "dialog"
43
+ ])),
44
+ hitTest: Schema.optionalKey(Schema.Literals([
45
+ "self",
46
+ "covered",
47
+ "uncertain",
48
+ "unsampled"
49
+ ])),
50
+ placement: Schema.optionalKey(Schema.Literals([
51
+ "inside",
52
+ "partial",
53
+ "outside"
54
+ ])),
55
+ autocomplete: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(128))),
56
+ box: Schema.optionalKey(Schema.Struct({
57
+ x: Schema.Finite,
58
+ y: Schema.Finite,
59
+ width: Schema.Finite,
60
+ height: Schema.Finite
61
+ }))
62
+ });
63
+ /**
64
+ * One control a scripted document offers. `id` becomes the issued `elementId`, so a scripted
65
+ * model turn can name it statically. Nothing here is a live capability.
66
+ */
67
+ const ControlScript = Schema.Struct({
68
+ id: Identifier,
69
+ kind: ObservedControl.fields.kind,
70
+ label: ObservedControl.fields.label,
71
+ disabled: Schema.optionalKey(Schema.Boolean),
72
+ /** A checkbox or radio `input` without it starts unchecked, as a real one does. */
73
+ checked: Schema.optionalKey(Schema.Boolean),
74
+ selected: Schema.optionalKey(Schema.Boolean),
75
+ inputType: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(32))),
76
+ required: Schema.optionalKey(Schema.Boolean),
77
+ multiple: Schema.optionalKey(Schema.Boolean),
78
+ /** The scripted select this option belongs to; it must be in the same document. */
79
+ selectElementId: Schema.optionalKey(Identifier),
80
+ /**
81
+ * The link target, or the form action a submit control sends to: reported as the control's
82
+ * destination fact, and where activating it leads. Only a `link`, or a `button`/`input` whose
83
+ * `inputType` is `submit` or `image`, has one, because that is all a real document reports.
84
+ */
85
+ destination: Schema.optionalKey(TargetUrl),
86
+ /** Where activation leads with no destination fact: what an `onclick` handler does. */
87
+ activates: Schema.optionalKey(TargetUrl),
88
+ /** Outside the viewport: absent from viewport readings and refused by hover. */
89
+ offscreen: Schema.optionalKey(Schema.Boolean),
90
+ /** What `readText({ selector: "#id" })` returns; defaults to the label. */
91
+ text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(65536))),
92
+ /** Clicking for a download completes one with this name. */
93
+ download: Schema.optionalKey(SafeFilename),
94
+ facts: Schema.optionalKey(ControlFactsScript)
95
+ }).check(Schema.makeFilter((control) => control.destination === void 0 || control.kind === "link" || (control.kind === "button" || control.kind === "input") && (control.inputType === "submit" || control.inputType === "image"), { title: "a destination only on a link or a submit control" }));
96
+ const DocumentScript = Schema.Struct({
97
+ url: TargetUrl,
98
+ title: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(512))),
99
+ text: Schema.String.check(Schema.isMaxLength(131072)),
100
+ controls: Schema.optionalKey(Schema.Array(ControlScript).check(Schema.isMaxLength(64), uniqueBy((control) => control.id, "unique control ids")))
101
+ });
102
+ /**
103
+ * The documents a scripted browser can show. A navigation to a listed address reaches that
104
+ * document; an unlisted address reaches an empty document with that address.
105
+ */
106
+ const Script = Schema.Struct({
107
+ documents: Schema.Array(DocumentScript).check(Schema.isMinLength(1), Schema.isMaxLength(64), uniqueBy((document) => document.url, "unique document addresses")),
108
+ /** The first page's document at connect; defaults to the first listed document. */
109
+ start: Schema.optionalKey(TargetUrl),
110
+ /**
111
+ * What successive connection attempts to one browser do: `refuse` fails the attempt as an
112
+ * unreachable endpoint would, and `accept` connects. Attempts past the list connect.
113
+ */
114
+ connections: Schema.optionalKey(Schema.Array(Schema.Literals(["accept", "refuse"])).check(Schema.isMaxLength(16)))
115
+ });
116
+ var ScriptedReference = class extends Schema.Class("ScriptedBrowserReference")({
117
+ provider: Schema.Literal("scripted"),
118
+ id: Identifier
119
+ }) {};
120
+ var ScriptedCleanupIssue = class extends Schema.Class("ScriptedCleanupIssue")({
121
+ step: Schema.Literals([
122
+ "fence",
123
+ "capture",
124
+ "initialization",
125
+ "disconnect"
126
+ ]),
127
+ reason: Schema.Literals([
128
+ "timeout",
129
+ "failed",
130
+ "interrupted"
131
+ ])
132
+ }) {};
133
+ /** Connection teardown facts for a scripted browser; there is no process or provider status. */
134
+ var ScriptedCleanupResult = class extends Schema.Class("ScriptedCleanupResult")({
135
+ reference: ScriptedReference,
136
+ connection: Schema.Literals([
137
+ "closed",
138
+ "failed",
139
+ "not-connected",
140
+ "pending"
141
+ ]),
142
+ issues: Schema.Array(ScriptedCleanupIssue).check(Schema.isMaxLength(16))
143
+ }) {};
144
+ /**
145
+ * The operations whose next call a test may script. `disconnect` is the owner's native teardown
146
+ * of a connection: a `Fail` makes it fail and a `Hold` parks it, however long cleanup waits.
147
+ */
148
+ const ScriptableOperation = Schema.Literals([
149
+ "navigate",
150
+ "navigate-stop",
151
+ "observe",
152
+ "checkpoint",
153
+ "control-facts",
154
+ "revalidate",
155
+ "read-text",
156
+ "screenshot",
157
+ "wait",
158
+ "click",
159
+ "fill",
160
+ "fill-form",
161
+ "select-option",
162
+ "scroll",
163
+ "click-and-wait",
164
+ "download-action",
165
+ "select-files",
166
+ "file-chooser",
167
+ "pointer-move",
168
+ "hover",
169
+ "wheel",
170
+ "press",
171
+ "type",
172
+ "list-pages",
173
+ "list-frames",
174
+ "select-page",
175
+ "select-frame",
176
+ "new-page",
177
+ "close-page",
178
+ "resize",
179
+ "page-suspend",
180
+ "page-resume",
181
+ "capture-stop",
182
+ "disconnect"
183
+ ]);
184
+ //#endregion
185
+ //#region src/internal/testing/Engine.ts
186
+ const gates = /* @__PURE__ */ new WeakMap();
187
+ /** A gate that holds a scripted call until the test opens it. */
188
+ const makeGate = Effect.sync(() => {
189
+ let reach = () => {};
190
+ let open = () => {};
191
+ const reached = new Promise((resolve) => {
192
+ reach = resolve;
193
+ });
194
+ const opened = new Promise((resolve) => {
195
+ open = resolve;
196
+ });
197
+ const gate = {
198
+ reached: Effect.promise(() => reached),
199
+ open: Effect.sync(() => {
200
+ open();
201
+ })
202
+ };
203
+ gates.set(gate, {
204
+ reach,
205
+ opened
206
+ });
207
+ return gate;
208
+ });
209
+ /** A 1×1 PNG: what a scripted screenshot or checkpoint picture contains. */
210
+ const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), (character) => character.charCodeAt(0));
211
+ const fail = (operation, reason, outcome = "undispatched") => BrowserError.make({
212
+ operation,
213
+ reason,
214
+ outcome
215
+ });
216
+ const encoder = new TextEncoder();
217
+ /** Cut at a character boundary so the bounded text is still valid UTF-16. */
218
+ const bounded = (text, maximumBytes) => {
219
+ if (encoder.encode(text).length <= maximumBytes) return {
220
+ text,
221
+ truncated: false
222
+ };
223
+ let kept = "";
224
+ let bytes = 0;
225
+ for (const character of text) {
226
+ const size = encoder.encode(character).length;
227
+ if (bytes + size > maximumBytes) break;
228
+ kept += character;
229
+ bytes += size;
230
+ }
231
+ return {
232
+ text: kept,
233
+ truncated: true
234
+ };
235
+ };
236
+ const originOf = (url) => {
237
+ try {
238
+ return new URL(url).origin;
239
+ } catch {
240
+ return "null";
241
+ }
242
+ };
243
+ const isSelectable = (kind) => kind === "select";
244
+ const isEditable = (control) => (control.kind === "input" || control.kind === "textarea") && control.disabled !== true;
245
+ const isToggle = (control) => control.kind === "input" && (control.inputType === "checkbox" || control.inputType === "radio");
246
+ /** Input types native fill types or assigns text into; every other input takes none. */
247
+ const textInputs = /* @__PURE__ */ new Set([
248
+ "",
249
+ "email",
250
+ "number",
251
+ "password",
252
+ "search",
253
+ "tel",
254
+ "text",
255
+ "url",
256
+ "color",
257
+ "date",
258
+ "time",
259
+ "datetime-local",
260
+ "month",
261
+ "range",
262
+ "week"
263
+ ]);
264
+ /**
265
+ * What the real driver refuses before dispatching text into a control: a disabled one, one that
266
+ * takes no text, and a number field given something that is not a number.
267
+ */
268
+ const textRefusal = (control, text) => {
269
+ const editable = control.facts?.editable;
270
+ if (control.disabled === true) return Reasons.Disabled.make({});
271
+ if (editable === false) return Reasons.Unsupported.make({});
272
+ if (control.kind === "textarea") return void 0;
273
+ if (control.kind !== "input") return editable === true ? void 0 : Reasons.Unsupported.make({});
274
+ const type = (control.inputType ?? "").toLowerCase();
275
+ if (!textInputs.has(type)) return Reasons.Unsupported.make({});
276
+ return type === "number" && Number.isNaN(Number(text.trim())) ? Reasons.Unsupported.make({}) : void 0;
277
+ };
278
+ const controlState = (script) => ({
279
+ script,
280
+ checked: script.checked ?? (isToggle(script) ? false : void 0),
281
+ selected: script.selected
282
+ });
283
+ const makeScriptedBrowser = (script, timers) => {
284
+ const pages = /* @__PURE__ */ new Map();
285
+ const calls = [];
286
+ const armed = /* @__PURE__ */ new Map();
287
+ const connections = [];
288
+ const live = /* @__PURE__ */ new Set();
289
+ let latest;
290
+ /** The page last selected by any connection: where the control's document operations act. */
291
+ let lastSelected;
292
+ let attempts = 0;
293
+ let sequence = 0;
294
+ let pageSerial = 0;
295
+ let observationSerial = 0;
296
+ let suspensionSerial = 0;
297
+ let downloadSerial = 0;
298
+ let lastTimestamp = 17e11;
299
+ const state = (document) => ({
300
+ url: document.url,
301
+ title: document.title ?? "",
302
+ text: document.text,
303
+ controls: (document.controls ?? []).map(controlState)
304
+ });
305
+ const documentFor = (url) => {
306
+ const listed = script.documents.find((document) => document.url === url);
307
+ return state(listed ?? {
308
+ url,
309
+ text: ""
310
+ });
311
+ };
312
+ const createPage = (document, registered) => {
313
+ const serial = ++pageSerial;
314
+ const page = {
315
+ pageId: `page-${serial}`,
316
+ targetId: `target-${serial}`,
317
+ frameId: `frame-${serial}`,
318
+ document,
319
+ epoch: 0,
320
+ registeredEpoch: registered ? 0 : -1,
321
+ values: /* @__PURE__ */ new Map(),
322
+ files: /* @__PURE__ */ new Map(),
323
+ focused: void 0,
324
+ closed: false,
325
+ held: void 0,
326
+ navigation: void 0,
327
+ watchers: /* @__PURE__ */ new Set(),
328
+ capture: void 0
329
+ };
330
+ pages.set(page.pageId, page);
331
+ return page;
332
+ };
333
+ const openPages = () => [...pages.values()].filter((page) => !page.closed);
334
+ const notify = (page) => {
335
+ const watchers = Array.from(page.watchers);
336
+ for (const watcher of watchers) watcher();
337
+ };
338
+ /** The page shows a new document: nodes go stale, values reset, captures learn of it. */
339
+ const commit = (page, document) => {
340
+ page.document = document;
341
+ page.epoch++;
342
+ page.values.clear();
343
+ page.files.clear();
344
+ page.focused = void 0;
345
+ page.navigation = void 0;
346
+ for (const connection of live) connection.retire(page.pageId);
347
+ if (page.capture !== void 0) {
348
+ const { start } = page.capture;
349
+ if (start.document === void 0) start.invalidate("target-changed");
350
+ else start.document(document.url);
351
+ }
352
+ notify(page);
353
+ for (const connection of live) connection.announce(page.pageId);
354
+ };
355
+ /** In-document change: identity survives by control id, so retained nodes and waits carry on. */
356
+ const update = (page, document) => {
357
+ const previous = new Map(page.document.controls.map((control) => [control.script.id, control]));
358
+ const controls = (document.controls ?? []).map((script) => {
359
+ const existing = previous.get(script.id);
360
+ if (existing === void 0) return controlState(script);
361
+ existing.script = script;
362
+ if (script.checked !== void 0) existing.checked = script.checked;
363
+ if (script.selected !== void 0) existing.selected = script.selected;
364
+ return existing;
365
+ });
366
+ page.document = {
367
+ url: document.url,
368
+ title: document.title ?? "",
369
+ text: document.text,
370
+ controls
371
+ };
372
+ if (page.focused !== void 0 && !previous.has(page.focused)) page.focused = void 0;
373
+ notify(page);
374
+ };
375
+ const take = (operation) => {
376
+ const queue = armed.get(operation);
377
+ const next = queue?.shift();
378
+ if (queue !== void 0 && queue.length === 0) armed.delete(operation);
379
+ return next;
380
+ };
381
+ const internalGate = (gate) => {
382
+ const internal = gates.get(gate);
383
+ if (internal === void 0) throw new Error("A scripted gate must come from the browser it holds");
384
+ return internal;
385
+ };
386
+ /** Only a mutation's Ticket carries dispatch evidence; a read's ticket has none to give. */
387
+ const isTicket = (ticket) => "dispatch" in ticket;
388
+ const connect = (options, events) => {
389
+ const ordinal = attempts++;
390
+ if (script.connections?.[ordinal] === "refuse") {
391
+ connections.push("refused");
392
+ throw new Error("The scripted browser refused this connection");
393
+ }
394
+ const bindings = options.bindings ?? [];
395
+ let viewport = { ...options.viewport };
396
+ const positions = /* @__PURE__ */ new Map();
397
+ let pointer = null;
398
+ let selectedId;
399
+ let snapshot;
400
+ let disconnected = false;
401
+ let index = -1;
402
+ const place = (pageId, point) => {
403
+ positions.set(pageId, point);
404
+ pointer = point;
405
+ };
406
+ const receipt = (pageId) => ({ position: positions.get(pageId) ?? null });
407
+ const select = (pageId) => {
408
+ selectedId = pageId;
409
+ lastSelected = pageId;
410
+ };
411
+ const selectedPage = (operation = "target") => {
412
+ const page = selectedId === void 0 ? void 0 : pages.get(selectedId);
413
+ if (disconnected || page === void 0 || page.closed) throw fail(operation, Reasons.Closed.make({}));
414
+ return page;
415
+ };
416
+ const current = (target, operation) => {
417
+ if (target === void 0) return selectedPage(operation);
418
+ if (disconnected) throw fail(operation, Reasons.Closed.make({}));
419
+ const page = pages.get(target.pageId);
420
+ if (page === void 0 || page.closed || page.frameId !== target.frameId) throw fail(operation, Reasons.Stale.make({}));
421
+ return page;
422
+ };
423
+ const pageOf = (info, operation) => {
424
+ const page = pages.get(info.pageId);
425
+ if (page === void 0) throw fail(operation, Reasons.NotFound.make({}));
426
+ if (page.closed || page.targetId !== info.targetId) throw fail(operation, Reasons.Stale.make({}));
427
+ return page;
428
+ };
429
+ const info = (page) => PageInfo.make({
430
+ pageId: page.pageId,
431
+ targetId: page.targetId,
432
+ url: page.document.url,
433
+ title: page.document.title,
434
+ selected: page.pageId === selectedId
435
+ });
436
+ const frameInfo = (page) => FrameInfo.make({
437
+ frameId: page.frameId,
438
+ parentFrameId: null,
439
+ url: page.document.url,
440
+ name: ""
441
+ });
442
+ const invalidateSnapshot = (scope = "all") => {
443
+ if (snapshot !== void 0 && scope !== "none" && (scope === "all" || scope.pageId === snapshot.pageId)) snapshot.validity = "invalid";
444
+ };
445
+ /** This connection ends: what it held on the browser's pages ends with it. */
446
+ const dropConnection = (announce, ended = "dropped") => {
447
+ if (disconnected) return;
448
+ disconnected = true;
449
+ connections[index] = ended;
450
+ live.delete(connection);
451
+ for (const page of pages.values()) {
452
+ if (page.navigation?.by === connection) page.navigation.drop();
453
+ if (page.held?.by === connection) page.held = void 0;
454
+ if (page.capture?.by === connection) page.capture = void 0;
455
+ notify(page);
456
+ }
457
+ if (announce) events.disconnected();
458
+ };
459
+ const dispatch = (ticket, record) => {
460
+ if (isTicket(ticket)) ticket.dispatch();
461
+ record.dispatched = true;
462
+ };
463
+ /** Once the owner aborts the admitted call, its own check names the reason. */
464
+ const aborted = (ticket, operation) => {
465
+ try {
466
+ ticket.check();
467
+ } catch (error) {
468
+ if (Schema.is(BrowserError)(error)) return error;
469
+ }
470
+ return fail(operation, Reasons.Interrupted.make({}), "unknown");
471
+ };
472
+ const hold = (gate, ticket, operation, record) => {
473
+ const internal = internalGate(gate);
474
+ internal.reach();
475
+ return new Promise((resolve, reject) => {
476
+ const onAbort = () => {
477
+ cleanup();
478
+ record.settled = "failed";
479
+ reject(aborted(ticket, operation));
480
+ };
481
+ const cleanup = () => ticket.signal.removeEventListener("abort", onAbort);
482
+ if (ticket.signal.aborted) {
483
+ onAbort();
484
+ return;
485
+ }
486
+ ticket.signal.addEventListener("abort", onAbort, { once: true });
487
+ internal.opened.then(() => {
488
+ cleanup();
489
+ resolve();
490
+ });
491
+ });
492
+ };
493
+ const applyArmed = async (operation, ticket, record) => {
494
+ const outcome = take(operation);
495
+ if (outcome === void 0) return;
496
+ switch (outcome._tag) {
497
+ case "Fail":
498
+ if (outcome.outcome === "unknown") dispatch(ticket, record);
499
+ throw fail(operation, outcome.reason, outcome.outcome);
500
+ case "Hold":
501
+ if (outcome.dispatched) dispatch(ticket, record);
502
+ await hold(outcome.gate, ticket, operation, record);
503
+ ticket.check();
504
+ return;
505
+ case "Disconnect":
506
+ if (outcome.dispatched === true) dispatch(ticket, record);
507
+ dropConnection(true);
508
+ throw fail(operation, Reasons.Disconnected.make({}), record.dispatched ? "unknown" : "undispatched");
509
+ }
510
+ };
511
+ const attempt = async (operation, ticket, meta, body) => {
512
+ const record = {
513
+ sequence: ++sequence,
514
+ operation,
515
+ pageId: meta.pageId ?? selectedId ?? "",
516
+ ...meta.elementId === void 0 ? {} : { elementId: meta.elementId },
517
+ ...meta.selector === void 0 ? {} : { selector: meta.selector },
518
+ dispatched: false,
519
+ settled: "pending"
520
+ };
521
+ calls.push(record);
522
+ try {
523
+ ticket?.check();
524
+ if (ticket !== void 0) await applyArmed(operation, ticket, record);
525
+ const value = await body(record);
526
+ record.settled = "completed";
527
+ return value;
528
+ } catch (error) {
529
+ record.settled = "failed";
530
+ throw error;
531
+ }
532
+ };
533
+ const meta = (target) => target === void 0 ? {} : typeof target === "string" ? { selector: target } : { elementId: target.elementId };
534
+ const facts = (control) => {
535
+ const { script: value } = control;
536
+ const extra = value.facts ?? {};
537
+ return ControlFacts.make({
538
+ kind: value.kind,
539
+ label: value.label,
540
+ disabled: value.disabled ?? false,
541
+ ...control.checked === void 0 ? {} : { checked: control.checked },
542
+ ...control.selected === void 0 ? {} : { selected: control.selected },
543
+ ...value.required === void 0 ? {} : { required: value.required },
544
+ ...value.multiple === void 0 ? {} : { multiple: value.multiple },
545
+ editable: extra.editable ?? isEditable(value),
546
+ ...value.inputType === void 0 ? {} : { inputType: value.inputType },
547
+ ...extra.autocomplete === void 0 ? {} : { autocomplete: extra.autocomplete },
548
+ ...value.destination === void 0 ? {} : { destination: value.destination },
549
+ ...extra.formMethod === void 0 ? {} : { formMethod: extra.formMethod },
550
+ box: ViewportRect.make(extra.box ?? {
551
+ x: 0,
552
+ y: 0,
553
+ width: 120,
554
+ height: 24
555
+ }),
556
+ placement: extra.placement ?? (value.offscreen === true ? "outside" : "inside"),
557
+ hitTest: extra.hitTest ?? (value.offscreen === true ? "unsampled" : "self"),
558
+ mainFrame: true
559
+ });
560
+ };
561
+ const observed = (control) => {
562
+ const { script: value } = control;
563
+ return ObservedControl.make({
564
+ elementId: value.id,
565
+ kind: value.kind,
566
+ label: value.label,
567
+ disabled: value.disabled ?? false,
568
+ ...control.checked === void 0 ? {} : { checked: control.checked },
569
+ ...control.selected === void 0 ? {} : { selected: control.selected },
570
+ ...value.inputType === void 0 ? {} : { inputType: value.inputType },
571
+ ...value.required === void 0 ? {} : { required: value.required },
572
+ ...value.multiple === void 0 ? {} : { multiple: value.multiple },
573
+ ...value.selectElementId === void 0 ? {} : { selectElementId: value.selectElementId }
574
+ });
575
+ };
576
+ const bySelector = (page, selector, operation) => {
577
+ const id = selector.startsWith("#") ? selector.slice(1) : void 0;
578
+ const control = id === void 0 ? void 0 : page.document.controls.find((c) => c.script.id === id);
579
+ if (control === void 0) throw fail(operation, Reasons.NotFound.make({}));
580
+ return control;
581
+ };
582
+ /** A retained node is only as current as the observation that produced it. */
583
+ const retained = (target, ticket, operation, allowSuspended = false, attached = true) => {
584
+ ticket.check();
585
+ const stale = () => fail(operation, Reasons.Stale.make({}));
586
+ const current = snapshot;
587
+ if (current === void 0 || current.id !== target.observationId) throw stale();
588
+ const node = current.nodes.get(target.elementId);
589
+ if (node === void 0) throw stale();
590
+ if (current.validity === "invalid" || current.generation !== ticket.generation) throw stale();
591
+ const page = pages.get(current.pageId);
592
+ if (page === void 0 || page.closed || page.epoch !== current.epoch) throw stale();
593
+ if (selectedId !== current.pageId) throw stale();
594
+ if (current.validity === "suspended" && !allowSuspended && !current.revalidated.has(target.elementId)) throw stale();
595
+ if (attached && !page.document.controls.includes(node)) throw stale();
596
+ return {
597
+ node,
598
+ page,
599
+ snapshot: current
600
+ };
601
+ };
602
+ const resolve = (target, ticket, operation, policy, browserTarget, allowSuspended = false, enablement = false) => {
603
+ let node;
604
+ let page;
605
+ if (typeof target === "string") {
606
+ page = current(browserTarget, operation);
607
+ node = bySelector(page, target, operation);
608
+ } else ({node, page} = retained(target, ticket, operation, allowSuspended));
609
+ const fresh = facts(node);
610
+ if (enablement && node.script.disabled === true) throw fail(operation, Reasons.Disabled.make({}));
611
+ if (policy !== void 0) {
612
+ let admitted = false;
613
+ try {
614
+ admitted = policy(fresh) === true;
615
+ } catch {
616
+ admitted = false;
617
+ }
618
+ if (!admitted) throw fail(operation, Reasons.Denied.make({}));
619
+ }
620
+ ticket.check();
621
+ return {
622
+ node,
623
+ page,
624
+ facts: fresh
625
+ };
626
+ };
627
+ const requireRunning = (page, operation) => {
628
+ if (page.held !== void 0) throw fail(operation, Reasons.Busy.make({}));
629
+ };
630
+ const heldObservation = (pageId) => {
631
+ if (snapshot?.pageId === pageId && snapshot.validity === "valid") {
632
+ snapshot.validity = "suspended";
633
+ snapshot.revalidated.clear();
634
+ }
635
+ };
636
+ const activate = (page, node) => {
637
+ const { script: value } = node;
638
+ page.focused = value.id;
639
+ if (value.kind === "input" && value.inputType === "checkbox") node.checked = !node.checked;
640
+ if (value.kind === "input" && value.inputType === "radio") node.checked = true;
641
+ const target = value.destination ?? value.activates;
642
+ if (target !== void 0) commit(page, documentFor(target));
643
+ return page.document.url;
644
+ };
645
+ const focusedOrRefuse = (into, ticket, operation, policy, browserTarget) => {
646
+ if (into === void 0) return current(browserTarget, operation);
647
+ const { node, page } = resolve(into, ticket, operation, policy, browserTarget);
648
+ if (page.focused !== node.script.id) throw fail(operation, Reasons.NotFocused.make({}));
649
+ return page;
650
+ };
651
+ const typed = (page, text) => {
652
+ const focused = page.focused === void 0 ? void 0 : page.document.controls.find((control) => control.script.id === page.focused);
653
+ if (focused !== void 0 && isEditable(focused.script)) page.values.set(focused.script.id, (page.values.get(focused.script.id) ?? "") + text);
654
+ };
655
+ /** Issued options of one select, refused exactly where native selection refuses them. */
656
+ const chosen = (node, ids, operation) => {
657
+ const current = snapshot;
658
+ if (current === void 0) throw fail(operation, Reasons.Stale.make({}));
659
+ if (!isSelectable(node.script.kind)) throw fail(operation, Reasons.Unsupported.make({}));
660
+ const options = ids.map((id) => {
661
+ const option = current.nodes.get(id);
662
+ if (option === void 0 || option.script.selectElementId !== node.script.id) throw fail(operation, Reasons.Stale.make({}));
663
+ return option;
664
+ });
665
+ if (node.script.disabled === true || options.some((option) => option.script.disabled === true)) throw fail(operation, Reasons.Disabled.make({}));
666
+ if (node.script.multiple !== true && options.length > 1) throw fail(operation, Reasons.Unsupported.make({}));
667
+ return options;
668
+ };
669
+ const choose = (page, node, options) => {
670
+ if (node.script.multiple !== true) {
671
+ for (const candidate of page.document.controls) if (candidate.script.selectElementId === node.script.id) candidate.selected = false;
672
+ }
673
+ for (const option of options) option.selected = true;
674
+ page.focused = node.script.id;
675
+ };
676
+ /** A control's private state after a form step. It is compared here and never returned. */
677
+ const fieldState = (page, node) => {
678
+ const { script: value } = node;
679
+ if (node.checked !== void 0) return JSON.stringify(["checked", node.checked]);
680
+ if (value.kind === "select") return JSON.stringify(["options", page.document.controls.filter((option) => option.script.selectElementId === value.id && option.selected).map((option) => option.script.id)]);
681
+ if (value.kind === "input" || value.kind === "textarea" || value.facts?.editable === true) return JSON.stringify(["value", page.values.get(value.id) ?? ""]);
682
+ return JSON.stringify(["other"]);
683
+ };
684
+ /** One form step, as the real driver takes it; see `Driver["formStep"]`. */
685
+ const formStep = (page, node, field, ticket, record) => {
686
+ const epoch = page.epoch;
687
+ let act;
688
+ if (field.options !== void 0) {
689
+ const options = chosen(node, field.options, "fill-form");
690
+ act = () => choose(page, node, options);
691
+ } else if (field.checked !== void 0) {
692
+ if (node.checked === void 0) throw fail("fill-form", Reasons.Unsupported.make({}));
693
+ if (node.checked !== field.checked) {
694
+ if (!field.checked && node.script.inputType === "radio") throw fail("fill-form", Reasons.Unsupported.make({}));
695
+ act = () => {
696
+ activate(page, node);
697
+ };
698
+ }
699
+ } else {
700
+ const text = field.value ?? "";
701
+ const refusal = textRefusal(node.script, text);
702
+ if (refusal !== void 0) throw fail("fill-form", refusal);
703
+ act = () => {
704
+ page.values.set(node.script.id, text);
705
+ page.focused = void 0;
706
+ };
707
+ }
708
+ if (act !== void 0) {
709
+ dispatch(ticket, record);
710
+ act();
711
+ }
712
+ const state = page.epoch === epoch && !page.closed && page.document.controls.includes(node) ? fieldState(page, node) : void 0;
713
+ return {
714
+ status: act === void 0 ? "unchanged" : "set",
715
+ reached: field.checked === void 0 || state === void 0 || state === JSON.stringify(["checked", field.checked]),
716
+ state,
717
+ url: page.document.url
718
+ };
719
+ };
720
+ const inFlight = (page, url, outcome, timeoutMillis, record) => new Promise((resolve, reject) => {
721
+ let done = false;
722
+ const timer = timers.sleep(timeoutMillis);
723
+ const finish = (settle) => {
724
+ if (done) return;
725
+ done = true;
726
+ timer.cancel();
727
+ if (page.navigation === flight) page.navigation = void 0;
728
+ settle();
729
+ };
730
+ const failed = (reason) => finish(() => {
731
+ record.settled = "failed";
732
+ reject(fail("navigate", reason, "unknown"));
733
+ });
734
+ const flight = {
735
+ stop: () => failed(Reasons.Interrupted.make({})),
736
+ drop: () => failed(Reasons.Disconnected.make({})),
737
+ by: connection
738
+ };
739
+ page.navigation = flight;
740
+ timer.done.then(() => failed(Reasons.Timeout.make({})), () => {});
741
+ switch (outcome._tag) {
742
+ case "Fail":
743
+ failed(outcome.reason);
744
+ return;
745
+ case "Disconnect":
746
+ dropConnection(true);
747
+ return;
748
+ case "Hold": {
749
+ const gate = internalGate(outcome.gate);
750
+ gate.reach();
751
+ gate.opened.then(() => finish(() => {
752
+ commit(page, documentFor(url));
753
+ resolve(url);
754
+ }));
755
+ }
756
+ }
757
+ });
758
+ const waitUntil = (ticket, page, operation, record, satisfied, detached) => new Promise((resolve, reject) => {
759
+ const cleanup = () => {
760
+ page.watchers.delete(check);
761
+ ticket.signal.removeEventListener("abort", onAbort);
762
+ ticket.retire();
763
+ };
764
+ const onAbort = () => {
765
+ cleanup();
766
+ record.settled = "failed";
767
+ reject(aborted(ticket, operation));
768
+ };
769
+ const check = () => {
770
+ try {
771
+ ticket.check();
772
+ if (disconnected) throw fail(operation, Reasons.Disconnected.make({}));
773
+ if (detached()) throw fail(operation, Reasons.Stale.make({}));
774
+ if (!satisfied()) return;
775
+ cleanup();
776
+ resolve();
777
+ } catch (error) {
778
+ cleanup();
779
+ record.settled = "failed";
780
+ reject(error);
781
+ }
782
+ };
783
+ if (ticket.signal.aborted) {
784
+ onAbort();
785
+ return;
786
+ }
787
+ ticket.signal.addEventListener("abort", onAbort, { once: true });
788
+ page.watchers.add(check);
789
+ check();
790
+ });
791
+ const invokeBinding = async (name, input, origin) => {
792
+ const binding = bindings.find((candidate) => candidate.name === name);
793
+ if (binding === void 0) return { ok: false };
794
+ const page = selectedId === void 0 ? void 0 : pages.get(selectedId);
795
+ const epoch = page?.epoch;
796
+ const documentOrigin = origin ?? (page === void 0 ? "null" : originOf(page.document.url));
797
+ const text = JSON.stringify(input) ?? "null";
798
+ const error = (reason) => InitializationError.make({
799
+ operation: "callback",
800
+ step: name,
801
+ reason
802
+ });
803
+ const check = async (signal) => {
804
+ if (disconnected || signal.aborted) throw error("closed");
805
+ if (page === void 0 || page.closed || page.epoch !== epoch) throw error("stale");
806
+ if (!binding.origins.includes(documentOrigin)) throw error("origin");
807
+ };
808
+ try {
809
+ const reply = await binding.invoke({
810
+ read: async (signal) => {
811
+ await check(signal);
812
+ return text;
813
+ },
814
+ check,
815
+ dispose: async () => {}
816
+ });
817
+ return {
818
+ ok: true,
819
+ output: JSON.parse(reply)
820
+ };
821
+ } catch {
822
+ return { ok: false };
823
+ }
824
+ };
825
+ if (pages.size === 0) {
826
+ const startUrl = script.start ?? script.documents[0]?.url ?? "https://scripted.invalid/";
827
+ const first = createPage(documentFor(startUrl), true);
828
+ select(first.pageId);
829
+ if (options.initialTargetId !== void 0 && options.initialTargetId !== first.targetId) throw fail("connect", Reasons.NotFound.make({}));
830
+ if (options.newPage === true) select(createPage(state({
831
+ url: startUrl,
832
+ text: ""
833
+ }), false).pageId);
834
+ } else if (options.initialTargetId !== void 0) {
835
+ const target = openPages().find((page) => page.targetId === options.initialTargetId);
836
+ if (target === void 0) throw fail("connect", Reasons.NotFound.make({}));
837
+ select(target.pageId);
838
+ } else if (options.newPage === true) select(createPage(state({
839
+ url: "https://scripted.invalid/blank",
840
+ text: ""
841
+ }), false).pageId);
842
+ else {
843
+ const previous = lastSelected === void 0 ? void 0 : pages.get(lastSelected);
844
+ select(previous !== void 0 && !previous.closed ? previous.pageId : openPages()[0]?.pageId);
845
+ }
846
+ const driver = {
847
+ ...options.pageControl === true ? { pageControl: {
848
+ state: async (page, ticket) => {
849
+ ticket.check();
850
+ const target = pageOf(page, "page-control");
851
+ return PageExecutionState.make({
852
+ pageId: target.pageId,
853
+ targetId: target.targetId,
854
+ state: target.held === void 0 ? "running" : "suspended",
855
+ ...target.held === void 0 ? {} : { suspensionId: target.held.suspensionId }
856
+ });
857
+ },
858
+ suspend: (page, ticket) => attempt("page-suspend", ticket, { pageId: page.pageId }, async (record) => {
859
+ const target = pageOf(page, "page-suspend");
860
+ requireRunning(target, "page-suspend");
861
+ dispatch(ticket, record);
862
+ target.held = {
863
+ suspensionId: `suspension-${++suspensionSerial}`,
864
+ by: connection
865
+ };
866
+ heldObservation(target.pageId);
867
+ return PageSuspension.make({
868
+ pageId: target.pageId,
869
+ targetId: target.targetId,
870
+ suspensionId: target.held.suspensionId
871
+ });
872
+ }),
873
+ resume: (receipt, ticket) => attempt("page-resume", ticket, { pageId: receipt.pageId }, async (record) => {
874
+ const target = pages.get(receipt.pageId);
875
+ if (target === void 0 || target.closed || target.held === void 0 || target.targetId !== receipt.targetId || target.held.suspensionId !== receipt.suspensionId) throw fail("page-resume", Reasons.Stale.make({}));
876
+ dispatch(ticket, record);
877
+ target.held = void 0;
878
+ heldObservation(target.pageId);
879
+ }),
880
+ checkTarget: async (target, ticket) => {
881
+ ticket.check();
882
+ requireRunning(current(target, "page-control"), "page-control");
883
+ }
884
+ } } : {},
885
+ selected: () => {
886
+ const page = selectedPage();
887
+ return {
888
+ pageId: page.pageId,
889
+ frameId: page.frameId
890
+ };
891
+ },
892
+ selectedTargetId: async () => selectedPage().targetId,
893
+ listPages: (ticket) => attempt("list-pages", ticket, {}, async () => openPages().map(info)),
894
+ resolvePage: async (page, ticket) => {
895
+ ticket.check();
896
+ const target = pageOf(page, "target");
897
+ return {
898
+ pageId: target.pageId,
899
+ frameId: target.frameId
900
+ };
901
+ },
902
+ selectPage: (page, ticket) => attempt("select-page", ticket, { pageId: page.pageId }, async () => {
903
+ const target = pageOf(page, "select-page");
904
+ select(target.pageId);
905
+ events.invalidate("target-changed", "none");
906
+ }),
907
+ newPage: (ticket) => attempt("new-page", ticket, {}, async (record) => {
908
+ if (openPages().length >= options.maxPages) throw fail("new-page", Reasons.Limit.make({
909
+ dimension: "pages",
910
+ maximum: options.maxPages,
911
+ observed: openPages().length
912
+ }));
913
+ dispatch(ticket, record);
914
+ return info(createPage(state({
915
+ url: "https://scripted.invalid/blank",
916
+ text: ""
917
+ }), false));
918
+ }),
919
+ closePage: (page, ticket) => attempt("close-page", ticket, { pageId: page.pageId }, async (record) => {
920
+ const target = pageOf(page, "close-page");
921
+ dispatch(ticket, record);
922
+ target.closed = true;
923
+ target.navigation?.drop();
924
+ target.capture?.start.invalidate("target-changed");
925
+ target.capture = void 0;
926
+ notify(target);
927
+ if (selectedId === target.pageId) select(void 0);
928
+ invalidateSnapshot({ pageId: target.pageId });
929
+ events.invalidate("target-changed", { pageId: target.pageId });
930
+ for (const other of live) {
931
+ if (other === connection) continue;
932
+ other.retire(target.pageId);
933
+ other.announce(target.pageId);
934
+ }
935
+ }),
936
+ listFrames: (ticket, page) => attempt("list-frames", ticket, {}, async () => [frameInfo(page === void 0 ? selectedPage("list-frames") : pageOf(page, "list-frames"))]),
937
+ resolveFrame: async (page, frame, ticket) => {
938
+ ticket.check();
939
+ const target = pageOf(page, "target");
940
+ if (frame.frameId !== target.frameId) throw fail("target", Reasons.NotFound.make({}));
941
+ return {
942
+ pageId: target.pageId,
943
+ frameId: target.frameId
944
+ };
945
+ },
946
+ selectFrame: (id, ticket) => attempt("select-frame", ticket, {}, async () => {
947
+ if (id !== selectedPage("select-frame").frameId) throw fail("select-frame", Reasons.NotFound.make({}));
948
+ events.invalidate("target-changed", "none");
949
+ }),
950
+ beginNavigation: (url, timeoutMillis, ticket, target) => attempt("navigate", void 0, { pageId: target?.pageId }, async (record) => {
951
+ ticket.check();
952
+ const page = current(target, "navigate");
953
+ requireRunning(page, "navigate");
954
+ const outcome = take("navigate");
955
+ if (outcome?._tag === "Fail" && outcome.outcome !== "unknown") throw fail("navigate", outcome.reason, outcome.outcome);
956
+ if (outcome?._tag === "Hold" && !outcome.dispatched) {
957
+ await hold(outcome.gate, ticket, "navigate", record);
958
+ ticket.check();
959
+ }
960
+ if (outcome?._tag === "Disconnect" && outcome.dispatched !== true) {
961
+ dropConnection(true);
962
+ throw fail("navigate", Reasons.Disconnected.make({}));
963
+ }
964
+ dispatch(ticket, record);
965
+ page.navigation?.stop();
966
+ const inFlightOutcome = outcome === void 0 || outcome._tag === "Hold" && !outcome.dispatched ? void 0 : outcome;
967
+ let settled;
968
+ if (inFlightOutcome === void 0) {
969
+ commit(page, documentFor(url));
970
+ settled = Promise.resolve(url);
971
+ } else {
972
+ settled = inFlight(page, url, inFlightOutcome, timeoutMillis, record);
973
+ settled.catch(() => {});
974
+ }
975
+ return {
976
+ pageId: page.pageId,
977
+ mainFrame: true,
978
+ settled,
979
+ stop: (stopTicket, pending, onDispatch) => attempt("navigate-stop", void 0, { pageId: page.pageId }, async (stopRecord) => {
980
+ stopTicket.check();
981
+ const armedStop = take("navigate-stop");
982
+ if (armedStop?._tag === "Hold" && !armedStop.dispatched) {
983
+ await hold(armedStop.gate, stopTicket, "navigate-stop", stopRecord);
984
+ stopTicket.check();
985
+ }
986
+ if (!pending()) return "settled";
987
+ if (armedStop?._tag === "Fail" && armedStop.outcome !== "unknown") throw fail("navigate-stop", armedStop.reason, armedStop.outcome);
988
+ if (armedStop?._tag === "Disconnect" && armedStop.dispatched !== true) {
989
+ dropConnection(true);
990
+ throw fail("navigate-stop", Reasons.Disconnected.make({}));
991
+ }
992
+ dispatch(stopTicket, stopRecord);
993
+ onDispatch();
994
+ switch (armedStop?._tag) {
995
+ case "Fail": throw fail("navigate-stop", armedStop.reason, "unknown");
996
+ case "Disconnect":
997
+ dropConnection(true);
998
+ throw fail("navigate-stop", Reasons.Disconnected.make({}), "unknown");
999
+ case "Hold":
1000
+ if (armedStop.dispatched) {
1001
+ await hold(armedStop.gate, stopTicket, "navigate-stop", stopRecord);
1002
+ stopTicket.check();
1003
+ }
1004
+ break;
1005
+ case void 0:
1006
+ }
1007
+ page.navigation?.stop();
1008
+ return "dispatched";
1009
+ })
1010
+ };
1011
+ }),
1012
+ readText: (selector, maximumBytes, ticket, target) => attempt("read-text", ticket, {
1013
+ pageId: target?.pageId,
1014
+ ...meta(selector)
1015
+ }, async () => {
1016
+ const page = current(target, "read-text");
1017
+ if (selector === void 0) return bounded(page.document.text, maximumBytes).text;
1018
+ const control = bySelector(page, selector, "read-text");
1019
+ return bounded(control.script.text ?? control.script.label, maximumBytes).text;
1020
+ }),
1021
+ observe: (scope, maximumBytes, controls, ticket, match) => attempt("observe", ticket, {}, async () => {
1022
+ const page = selectedPage("observe");
1023
+ const needle = match?.toLowerCase();
1024
+ const matches = (value) => needle === void 0 || value.toLowerCase().includes(needle);
1025
+ snapshot = void 0;
1026
+ const selects = new Set(page.document.controls.filter((control) => isSelectable(control.script.kind) && (matches(control.script.label) || page.document.controls.some((option) => option.script.selectElementId === control.script.id && matches(option.script.label)))).map((control) => control.script.id));
1027
+ const matching = page.document.controls.filter((control) => control.script.selectElementId !== void 0 ? selects.has(control.script.selectElementId) : isSelectable(control.script.kind) ? selects.has(control.script.id) : matches(control.script.label));
1028
+ const reachable = matching.filter((control) => scope === "document" || control.script.offscreen !== true);
1029
+ const kept = reachable.slice(0, controls);
1030
+ const text = bounded(needle === void 0 ? page.document.text : page.document.text.split("\n").map((line) => line.trim()).filter((line) => line !== "" && matches(line)).join("\n"), maximumBytes);
1031
+ const next = {
1032
+ id: `observation-${++observationSerial}`,
1033
+ pageId: page.pageId,
1034
+ epoch: page.epoch,
1035
+ generation: ticket.generation,
1036
+ validity: "valid",
1037
+ nodes: new Map(kept.map((control) => [control.script.id, control])),
1038
+ revalidated: /* @__PURE__ */ new Set()
1039
+ };
1040
+ snapshot = next;
1041
+ return {
1042
+ observationId: next.id,
1043
+ scope,
1044
+ ...match === void 0 ? {} : { match },
1045
+ url: page.document.url,
1046
+ text: text.text,
1047
+ textTruncated: text.truncated,
1048
+ controls: kept.map(observed),
1049
+ controlsTruncated: kept.length < reachable.length,
1050
+ viewport: ViewportEvidence.make({
1051
+ width: viewport.width,
1052
+ height: viewport.height,
1053
+ clippedText: 0,
1054
+ coveredText: 0,
1055
+ uncertainText: 0,
1056
+ unreachableControls: matching.length - reachable.length,
1057
+ exhausted: false
1058
+ })
1059
+ };
1060
+ }),
1061
+ checkpoint: (maximumBytes, controls, pictureBytes, ticket) => attempt("checkpoint", ticket, {}, async () => {
1062
+ const page = selectedPage("checkpoint");
1063
+ const text = bounded(page.document.text, maximumBytes);
1064
+ const reachable = page.document.controls.filter((control) => control.script.offscreen !== true);
1065
+ return {
1066
+ url: page.document.url,
1067
+ text: text.text,
1068
+ textTruncated: text.truncated,
1069
+ controls: reachable.slice(0, controls).map(facts),
1070
+ controlsTruncated: reachable.length > controls,
1071
+ viewport: ViewportEvidence.make({
1072
+ width: viewport.width,
1073
+ height: viewport.height,
1074
+ clippedText: 0,
1075
+ coveredText: 0,
1076
+ uncertainText: 0,
1077
+ unreachableControls: page.document.controls.length - reachable.length,
1078
+ exhausted: false
1079
+ }),
1080
+ documentChanged: false,
1081
+ ...pictureBytes === void 0 ? {} : { picture: new Uint8Array(PNG) }
1082
+ };
1083
+ }),
1084
+ controlFacts: (target, ticket) => attempt("control-facts", ticket, meta(target), async () => {
1085
+ selectedPage("control-facts");
1086
+ return resolve(target, ticket, "control-facts").facts;
1087
+ }),
1088
+ revalidate: (target, ticket) => attempt("revalidate", ticket, meta(target), async () => {
1089
+ const { snapshot: current } = retained(target, ticket, "revalidate", true);
1090
+ current.revalidated.add(target.elementId);
1091
+ }),
1092
+ click: (target, ticket, policy, browserTarget) => attempt("click", ticket, {
1093
+ pageId: browserTarget?.pageId,
1094
+ ...meta(target)
1095
+ }, async (record) => {
1096
+ const { node, page } = resolve(target, ticket, "click", policy, browserTarget);
1097
+ requireRunning(page, "click");
1098
+ dispatch(ticket, record);
1099
+ return activate(page, node);
1100
+ }),
1101
+ fill: (target, value, ticket, policy, browserTarget) => attempt("fill", ticket, {
1102
+ pageId: browserTarget?.pageId,
1103
+ ...meta(target)
1104
+ }, async (record) => {
1105
+ const { node, page } = resolve(target, ticket, "fill", policy, browserTarget);
1106
+ requireRunning(page, "fill");
1107
+ const refusal = textRefusal(node.script, value);
1108
+ if (refusal !== void 0) throw fail("fill", refusal);
1109
+ dispatch(ticket, record);
1110
+ page.focused = node.script.id;
1111
+ page.values.set(node.script.id, value);
1112
+ return page.document.url;
1113
+ }),
1114
+ selectOption: (target, ids, ticket, policy) => attempt("select-option", ticket, meta(target), async (record) => {
1115
+ const { node, page } = resolve(target, ticket, "select-option", policy);
1116
+ requireRunning(page, "select-option");
1117
+ const options = chosen(node, ids, "select-option");
1118
+ dispatch(ticket, record);
1119
+ choose(page, node, options);
1120
+ return page.document.url;
1121
+ }),
1122
+ formStep: (target, field, ticket, policy) => attempt("fill-form", ticket, meta(target), async (record) => {
1123
+ const { node, page } = resolve(target, ticket, "fill-form", policy, void 0, false, true);
1124
+ requireRunning(page, "fill-form");
1125
+ return formStep(page, node, field, ticket, record);
1126
+ }),
1127
+ formState: (targets, ticket) => attempt("fill-form", ticket, {}, async () => targets.map((target) => {
1128
+ const { node, page } = retained(target, ticket, "fill-form", false, false);
1129
+ return page.document.controls.includes(node) ? fieldState(page, node) : void 0;
1130
+ })),
1131
+ formSubmit: (target, ticket, policy) => attempt("fill-form", ticket, meta(target), async (record) => {
1132
+ const { node, page } = resolve(target, ticket, "fill-form", policy, void 0, false, true);
1133
+ requireRunning(page, "fill-form");
1134
+ dispatch(ticket, record);
1135
+ return activate(page, node);
1136
+ }),
1137
+ scroll: (_deltaX, _deltaY, ticket, target) => attempt("scroll", ticket, { pageId: target?.pageId }, async (record) => {
1138
+ const page = current(target, "scroll");
1139
+ requireRunning(page, "scroll");
1140
+ dispatch(ticket, record);
1141
+ return page.document.url;
1142
+ }),
1143
+ pointerMove: (to, ticket, target) => attempt("pointer-move", ticket, { pageId: target?.pageId }, async (record) => {
1144
+ const page = current(target, "pointer-move");
1145
+ requireRunning(page, "pointer-move");
1146
+ dispatch(ticket, record);
1147
+ place(page.pageId, {
1148
+ x: to.x,
1149
+ y: to.y
1150
+ });
1151
+ return receipt(page.pageId);
1152
+ }),
1153
+ hover: (target, ticket, policy, browserTarget) => attempt("hover", ticket, {
1154
+ pageId: browserTarget?.pageId,
1155
+ ...meta(target)
1156
+ }, async (record) => {
1157
+ const { node, page, facts: fresh } = resolve(target, ticket, "hover", policy, browserTarget);
1158
+ requireRunning(page, "hover");
1159
+ if (node.script.offscreen === true) throw fail("hover", Reasons.NotVisible.make({}));
1160
+ dispatch(ticket, record);
1161
+ place(page.pageId, {
1162
+ x: fresh.box.x + fresh.box.width / 2,
1163
+ y: fresh.box.y + fresh.box.height / 2
1164
+ });
1165
+ return receipt(page.pageId);
1166
+ }),
1167
+ wheel: (_deltaX, _deltaY, at, ticket, target) => attempt("wheel", ticket, { pageId: target?.pageId }, async (record) => {
1168
+ const page = current(target, "wheel");
1169
+ requireRunning(page, "wheel");
1170
+ dispatch(ticket, record);
1171
+ if (at !== void 0) place(page.pageId, {
1172
+ x: at.x,
1173
+ y: at.y
1174
+ });
1175
+ return receipt(page.pageId);
1176
+ }),
1177
+ press: (key, _modifiers, into, ticket, policy, browserTarget) => attempt("press", ticket, {
1178
+ pageId: browserTarget?.pageId,
1179
+ ...meta(into)
1180
+ }, async (record) => {
1181
+ const page = focusedOrRefuse(into, ticket, "press", policy, browserTarget);
1182
+ requireRunning(page, "press");
1183
+ dispatch(ticket, record);
1184
+ if (key.length === 1) typed(page, key);
1185
+ return receipt(page.pageId);
1186
+ }),
1187
+ type: (text, into, ticket, policy, browserTarget) => attempt("type", ticket, {
1188
+ pageId: browserTarget?.pageId,
1189
+ ...meta(into)
1190
+ }, async (record) => {
1191
+ const page = focusedOrRefuse(into, ticket, "type", policy, browserTarget);
1192
+ requireRunning(page, "type");
1193
+ dispatch(ticket, record);
1194
+ typed(page, text);
1195
+ return receipt(page.pageId);
1196
+ }),
1197
+ screenshot: (_fullPage, _maximumBytes, ticket, target) => attempt("screenshot", ticket, { pageId: target?.pageId }, async () => {
1198
+ current(target, "screenshot");
1199
+ return new Uint8Array(PNG);
1200
+ }),
1201
+ resize: (next, ticket) => attempt("resize", ticket, {}, async (record) => {
1202
+ const page = selectedPage("resize");
1203
+ dispatch(ticket, record);
1204
+ viewport = {
1205
+ width: next.width,
1206
+ height: next.height
1207
+ };
1208
+ page.capture?.start.invalidate("resized");
1209
+ events.invalidate("resized");
1210
+ }),
1211
+ waitFor: (selector, state, ticket, target) => attempt("wait", ticket, {
1212
+ pageId: target.pageId,
1213
+ selector
1214
+ }, async (record) => {
1215
+ const page = current(target, "wait");
1216
+ const epoch = page.epoch;
1217
+ const find = () => {
1218
+ const id = selector.startsWith("#") ? selector.slice(1) : void 0;
1219
+ return id === void 0 ? void 0 : page.document.controls.find((control) => control.script.id === id);
1220
+ };
1221
+ await waitUntil(ticket, page, "wait", record, () => {
1222
+ const control = find();
1223
+ const present = control !== void 0;
1224
+ const visible = present && control.script.offscreen !== true;
1225
+ switch (state) {
1226
+ case "visible": return visible;
1227
+ case "hidden": return !visible;
1228
+ case "attached": return present;
1229
+ case "detached": return !present;
1230
+ }
1231
+ }, () => page.closed || page.epoch !== epoch);
1232
+ }).finally(() => ticket.retire()),
1233
+ waitForElement: (reference, state, ticket, target) => attempt("wait", ticket, {
1234
+ pageId: target.pageId,
1235
+ elementId: reference.elementId
1236
+ }, async (record) => {
1237
+ const page = current(target, "wait");
1238
+ const { node } = retained(reference, ticket, "wait", true);
1239
+ const epoch = page.epoch;
1240
+ await waitUntil(ticket, page, "wait", record, () => {
1241
+ const present = page.document.controls.includes(node);
1242
+ const visible = present && node.script.offscreen !== true;
1243
+ switch (state) {
1244
+ case "visible": return visible;
1245
+ case "hidden": return !visible;
1246
+ case "enabled": return present && node.script.disabled !== true;
1247
+ case "disabled": return present && node.script.disabled === true;
1248
+ }
1249
+ }, () => page.closed || page.epoch !== epoch);
1250
+ }).finally(() => ticket.retire()),
1251
+ clickAndWait: (target, ticket) => attempt("click-and-wait", ticket, meta(target), async (record) => {
1252
+ const { node, page } = resolve(target, ticket, "click-and-wait");
1253
+ requireRunning(page, "click-and-wait");
1254
+ dispatch(ticket, record);
1255
+ return activate(page, node);
1256
+ }),
1257
+ clickForDownload: (target, ticket) => attempt("download-action", ticket, meta(target), async (record) => {
1258
+ const { node, page } = resolve(target, ticket, "download-action");
1259
+ requireRunning(page, "download-action");
1260
+ if (node.script.download === void 0) throw fail("download-action", Reasons.Unsupported.make({}));
1261
+ dispatch(ticket, record);
1262
+ page.focused = node.script.id;
1263
+ return {
1264
+ downloadId: `download-${++downloadSerial}`,
1265
+ filename: node.script.download,
1266
+ state: "completed"
1267
+ };
1268
+ }),
1269
+ selectFiles: (target, files, ticket) => attempt("select-files", ticket, meta(target), async (record) => selectFilesOn(target, files, ticket, record, "select-files")),
1270
+ clickForFileSelection: (target, files, ticket) => attempt("file-chooser", ticket, meta(target), async (record) => selectFilesOn(target, files, ticket, record, "file-chooser")),
1271
+ documentReadiness: async (ticket, target) => {
1272
+ ticket.check();
1273
+ const page = current(target, "ready");
1274
+ const bootstrap = options.bootstrap;
1275
+ if (bootstrap === void 0 || bootstrap.readiness.length === 0) return { _tag: "Ready" };
1276
+ if (page.epoch <= page.registeredEpoch && bootstrap.existingDocuments === "RequireFreshNavigation") return { _tag: "RequiresNavigation" };
1277
+ const origin = originOf(page.document.url);
1278
+ return bootstrap.readiness.some((requirement) => requirement.origins === void 0 || requirement.origins.includes(origin)) ? { _tag: "Ready" } : { _tag: "NotApplicable" };
1279
+ },
1280
+ dismissDialogs: async () => {},
1281
+ capture: async (target) => {
1282
+ const page = target === void 0 ? selectedPage("capture") : pageOf(PageInfo.make({
1283
+ pageId: target.pageId,
1284
+ targetId: target.targetId,
1285
+ url: "",
1286
+ title: "",
1287
+ selected: false
1288
+ }), "capture");
1289
+ return {
1290
+ pageId: page.pageId,
1291
+ targetId: page.targetId,
1292
+ frameId: page.frameId,
1293
+ source: {
1294
+ start: async (start) => {
1295
+ if (disconnected || page.closed) throw fail("capture-start", Reasons.Closed.make({}));
1296
+ page.capture = {
1297
+ start,
1298
+ by: connection
1299
+ };
1300
+ start.opened?.(page.document.url);
1301
+ },
1302
+ stop: async () => {
1303
+ page.capture = void 0;
1304
+ const outcome = take("capture-stop");
1305
+ if (outcome?._tag === "Fail") throw fail("capture-stop", outcome.reason, outcome.outcome);
1306
+ }
1307
+ }
1308
+ };
1309
+ },
1310
+ invalidateObservation: (scope) => {
1311
+ invalidateSnapshot(scope);
1312
+ },
1313
+ disconnect: async () => {
1314
+ if (disconnected) return;
1315
+ const outcome = take("disconnect");
1316
+ if (outcome?._tag === "Hold") {
1317
+ const gate = internalGate(outcome.gate);
1318
+ gate.reach();
1319
+ await gate.opened;
1320
+ }
1321
+ if (outcome?._tag === "Fail") {
1322
+ dropConnection(false, "close-failed");
1323
+ throw fail("disconnect", outcome.reason, outcome.outcome);
1324
+ }
1325
+ dropConnection(false, "closed");
1326
+ }
1327
+ };
1328
+ const selectFilesOn = (target, files, ticket, record, operation) => {
1329
+ const { node, page } = resolve(target, ticket, operation);
1330
+ requireRunning(page, operation);
1331
+ if (node.script.kind !== "input" || node.script.inputType !== "file") throw fail(operation, Reasons.Unsupported.make({}));
1332
+ dispatch(ticket, record);
1333
+ page.files.set(node.script.id, files.map((file) => file._tag === "Inline" ? file.name : file.path));
1334
+ return page.document.url;
1335
+ };
1336
+ const connection = {
1337
+ retire: (pageId) => invalidateSnapshot({ pageId }),
1338
+ announce: (pageId) => events.invalidate("target-changed", { pageId }),
1339
+ drop: () => dropConnection(true),
1340
+ invoke: invokeBinding,
1341
+ pointer: () => pointer,
1342
+ viewport: () => viewport
1343
+ };
1344
+ index = connections.push("open") - 1;
1345
+ live.add(connection);
1346
+ latest = connection;
1347
+ return driver;
1348
+ };
1349
+ const toScript = (document) => ({
1350
+ url: document.url,
1351
+ title: document.title,
1352
+ text: document.text,
1353
+ controls: document.controls.map((control) => ({
1354
+ ...control.script,
1355
+ ...control.checked === void 0 ? {} : { checked: control.checked },
1356
+ ...control.selected === void 0 ? {} : { selected: control.selected }
1357
+ }))
1358
+ });
1359
+ /** The page last selected by any connection; it stays reachable while no connection is open. */
1360
+ const selectedOrClosed = Effect.suspend(() => {
1361
+ const page = lastSelected === void 0 ? void 0 : pages.get(lastSelected);
1362
+ return page === void 0 || page.closed ? Effect.fail(fail("target", Reasons.Closed.make({}))) : Effect.succeed(page);
1363
+ });
1364
+ return {
1365
+ connect,
1366
+ control: {
1367
+ calls: Effect.sync(() => calls.map((call) => Object.freeze({ ...call }))),
1368
+ next: (operation, outcome) => Effect.sync(() => {
1369
+ const queue = armed.get(operation) ?? [];
1370
+ queue.push(outcome);
1371
+ armed.set(operation, queue);
1372
+ }),
1373
+ gate: makeGate,
1374
+ document: {
1375
+ current: selectedOrClosed.pipe(Effect.map((page) => toScript(page.document))),
1376
+ replace: (next) => checked(DocumentScript, next, "configure").pipe(Effect.flatMap((document) => selectedOrClosed.pipe(Effect.map((page) => {
1377
+ page.navigation?.stop();
1378
+ commit(page, state(document));
1379
+ })))),
1380
+ update: (next) => checked(DocumentScript, next, "configure").pipe(Effect.flatMap((document) => selectedOrClosed.pipe(Effect.map((page) => {
1381
+ update(page, document);
1382
+ })))),
1383
+ values: Effect.sync(() => lastSelected === void 0 ? /* @__PURE__ */ new Map() : new Map(pages.get(lastSelected)?.values ?? [])),
1384
+ files: Effect.sync(() => lastSelected === void 0 ? /* @__PURE__ */ new Map() : new Map(pages.get(lastSelected)?.files ?? []))
1385
+ },
1386
+ pointer: Effect.sync(() => latest?.pointer() ?? null),
1387
+ capture: { emit: (frame = {}) => selectedOrClosed.pipe(Effect.flatMap((page) => {
1388
+ const running = page.capture?.start;
1389
+ if (running === void 0) return Effect.fail(fail("capture-consume", Reasons.NotFound.make({})));
1390
+ const timestamp = frame.timestamp ?? lastTimestamp + 40;
1391
+ const viewport = page.capture?.by.viewport() ?? {
1392
+ width: 0,
1393
+ height: 0
1394
+ };
1395
+ lastTimestamp = Math.max(lastTimestamp, timestamp);
1396
+ return Effect.sync(() => {
1397
+ running.receive({
1398
+ data: frame.bytes ?? jpegFrame(),
1399
+ timestamp,
1400
+ viewportWidth: frame.viewportWidth ?? viewport.width,
1401
+ viewportHeight: frame.viewportHeight ?? viewport.height
1402
+ });
1403
+ });
1404
+ })) },
1405
+ invoke: (name, input, invokeOptions) => Effect.promise(() => {
1406
+ const open = [...live].at(-1);
1407
+ return open === void 0 ? Promise.resolve({ ok: false }) : open.invoke(name, input, invokeOptions?.origin);
1408
+ }),
1409
+ disconnect: Effect.sync(() => {
1410
+ for (const connection of [...live]) connection.drop();
1411
+ }),
1412
+ connections: Effect.sync(() => [...connections])
1413
+ }
1414
+ };
1415
+ };
1416
+ //#endregion
1417
+ //#region src/internal/testing/Lifetime.ts
1418
+ /**
1419
+ * A lifetime with nothing outside the connection: no process to terminate and no provider to
1420
+ * release. Cleanup runs the same local steps an owned Chromium runs, each settling on its own,
1421
+ * and reports the same kind of receipt.
1422
+ */
1423
+ const scriptedSource = (reference, onCleanup) => (local) => Effect.gen(function* () {
1424
+ let latest;
1425
+ let closing = false;
1426
+ const close = yield* Effect.cached(Effect.uninterruptible(Effect.gen(function* () {
1427
+ const issues = [];
1428
+ const step = (name, action) => cleanupStep(action, 3e3).pipe(Effect.tap((result) => Effect.sync(() => {
1429
+ if (result._tag === "Failure") issues.push(ScriptedCleanupIssue.make({
1430
+ step: name,
1431
+ reason: result.reason
1432
+ }));
1433
+ })));
1434
+ yield* step("fence", local.fence);
1435
+ yield* step("capture", local.capture);
1436
+ yield* step("initialization", local.initialization);
1437
+ const disconnected = yield* step("disconnect", local.disconnect);
1438
+ const result = ScriptedCleanupResult.make({
1439
+ reference,
1440
+ connection: disconnected._tag === "Success" ? disconnected.value : "failed",
1441
+ issues
1442
+ });
1443
+ Object.freeze(result.issues);
1444
+ latest = Object.freeze(result);
1445
+ return latest;
1446
+ })));
1447
+ const release = yield* Effect.cached(Effect.gen(function* () {
1448
+ closing = true;
1449
+ const result = yield* close;
1450
+ if (onCleanup !== void 0) yield* reported(Effect.suspend(() => onCleanup(result)));
1451
+ return result;
1452
+ }).pipe(Effect.uninterruptible));
1453
+ yield* Effect.addFinalizer(() => release.pipe(Effect.asVoid));
1454
+ return {
1455
+ reference,
1456
+ connection: () => Effect.suspend(() => closing ? Effect.fail(BrowserError.make({
1457
+ operation: "connect",
1458
+ reason: Reasons.Closed.make({}),
1459
+ outcome: "undispatched"
1460
+ })) : Effect.succeed(Redacted.make(`scripted://${reference.id}`))),
1461
+ release,
1462
+ closeChecked: release.pipe(Effect.filterOrFail((result) => result.connection === "closed" && result.issues.length === 0, () => BrowserError.make({
1463
+ operation: "close",
1464
+ reason: Reasons.Failed.make({}),
1465
+ outcome: "unknown"
1466
+ }))),
1467
+ cleanupResult: Effect.sync(() => Option.fromNullishOr(latest)),
1468
+ controlRetired: Effect.sync(() => latest !== void 0 && latest.connection === "closed")
1469
+ };
1470
+ });
1471
+ //#endregion
1472
+ //#region src/Testing.ts
1473
+ let references = 0;
1474
+ const makeEngine = Effect.fnUntraced(function* (script) {
1475
+ const context = yield* Effect.context();
1476
+ const browsers = /* @__PURE__ */ new Map();
1477
+ const timers = { sleep: (millis) => {
1478
+ const controller = new AbortController();
1479
+ const done = Effect.runPromiseWith(context)(Effect.sleep(millis), { signal: controller.signal });
1480
+ done.catch(() => {});
1481
+ return {
1482
+ done,
1483
+ cancel: () => controller.abort()
1484
+ };
1485
+ } };
1486
+ const attempt = async (request) => {
1487
+ const address = Redacted.isRedacted(request.connection) ? String(Redacted.value(request.connection)) : String(request.connection);
1488
+ let browser = browsers.get(address);
1489
+ if (browser === void 0) {
1490
+ browser = makeScriptedBrowser(script, timers);
1491
+ browsers.set(address, browser);
1492
+ }
1493
+ return browser.connect(request.options, request.events);
1494
+ };
1495
+ return {
1496
+ binding: issueBinding({ _tag: "BrowserBinding" }, fromNativeAttempt(attempt)),
1497
+ controls: () => [...browsers.values()].map((browser) => browser.control)
1498
+ };
1499
+ });
1500
+ /**
1501
+ * Open one scripted browser in the caller's Scope. The session is the real owner over a
1502
+ * scripted native engine: admission, budgets, staleness, dispatch evidence, capture, page holds
1503
+ * and typed callbacks are the production code paths. Only the page and its outcomes are scripted,
1504
+ * and the owner's ids and handoff tokens come from `sequentialCrypto`.
1505
+ */
1506
+ const open = Effect.fnUntraced(function* (script, options = {}) {
1507
+ const fixed = yield* checked(Script, script, "configure");
1508
+ const policy = yield* checked(BrowserPolicy, options.policy ?? BrowserPolicy.unrestricted(), "configure");
1509
+ const engine = yield* makeEngine(fixed);
1510
+ const runtime = yield* make({
1511
+ implementation: "scripted",
1512
+ binding: engine.binding,
1513
+ ...options.automation === void 0 ? {} : { automation: options.automation },
1514
+ ...options.viewport === void 0 ? {} : { viewport: options.viewport }
1515
+ }).pipe(Effect.provide(sequentialCrypto));
1516
+ const reference = Object.freeze(ScriptedReference.make({
1517
+ provider: "scripted",
1518
+ id: `scripted-${++references}`
1519
+ }));
1520
+ const acquired = yield* runtime.acquire(policy, scriptedSource(reference, options.onCleanup), options.bootstrap === void 0 ? {} : { bootstrap: options.bootstrap });
1521
+ const connection = yield* acquired.connect;
1522
+ const control = engine.controls().at(-1);
1523
+ if (control === void 0) return yield* BrowserError.make({
1524
+ operation: "connect",
1525
+ reason: Reasons.Provider.make({}),
1526
+ outcome: "unknown"
1527
+ });
1528
+ return Object.assign(connection.session, {
1529
+ reference,
1530
+ control,
1531
+ closeChecked: connection.session.closeChecked.pipe(Effect.andThen(acquired.lifetime.closeChecked)),
1532
+ close: acquired.close,
1533
+ cleanupResult: acquired.lifetime.cleanupResult
1534
+ });
1535
+ });
1536
+ /**
1537
+ * The `Crypto` scripted browsers draw their ids and handoff tokens from. Its bytes count up from
1538
+ * one on each build, so every value is predictable; it is not random and computes no digest.
1539
+ * `open` uses it already. A provider Layer built over `binding` still requires a `Crypto`, and
1540
+ * this one keeps such a test free of a platform package.
1541
+ */
1542
+ const sequentialCrypto = Layer.sync(Crypto.Crypto, makeSequentialCrypto);
1543
+ /**
1544
+ * The same engine for a provider Layer built on `browser-runtime`, such as
1545
+ * `BrowserbaseBrowser.layer` with `BrowserBinding.layer(binding)`. Each address the Layer
1546
+ * connects to is one browser with one control handle; reconnecting to it finds its pages.
1547
+ */
1548
+ const binding = Effect.fnUntraced(function* (script) {
1549
+ const fixed = yield* checked(Script, script, "configure");
1550
+ const engine = yield* makeEngine(fixed);
1551
+ return {
1552
+ binding: engine.binding,
1553
+ browsers: Effect.sync(engine.controls)
1554
+ };
1555
+ });
1556
+ /** A valid 64×48 JPEG: the default bytes of a scripted capture frame, for a caller's own frames. */
1557
+ const jpeg = jpegFrame;
1558
+ //#endregion
1559
+ export { ControlFactsScript, ControlScript, DocumentScript, Script, ScriptableOperation, ScriptedCleanupIssue, ScriptedCleanupResult, ScriptedReference, binding, jpeg, open, sequentialCrypto };
1560
+
1561
+ //# sourceMappingURL=Testing.mjs.map