@capybara-hq/plugin-browser 0.0.0-stage → 0.1.0-rc.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.
- package/.capybara-plugin/plugin.json +100 -0
- package/LICENSE +202 -0
- package/NOTICE +2 -0
- package/README.md +77 -2
- package/dist/index.mjs +920 -0
- package/icon.svg +1 -0
- package/package.json +19 -4
- package/ui/panel.js +704 -0
- package/ui/service/daemon.mjs +2077 -0
- package/ui/service/vendor/playwright-core/LICENSE +202 -0
- package/ui/service/vendor/playwright-core/NOTICE +5 -0
- package/ui/service/vendor/playwright-core/README.md +3 -0
- package/ui/service/vendor/playwright-core/ThirdPartyNotices.txt +13 -0
- package/ui/service/vendor/playwright-core/browsers.json +52 -0
- package/ui/service/vendor/playwright-core/cli.js +22 -0
- package/ui/service/vendor/playwright-core/index.js +17 -0
- package/ui/service/vendor/playwright-core/index.mjs +28 -0
- package/ui/service/vendor/playwright-core/lib/bootstrap.js +149 -0
- package/ui/service/vendor/playwright-core/lib/coreBundle.js +78764 -0
- package/ui/service/vendor/playwright-core/lib/entry/cliDaemon.js +5 -0
- package/ui/service/vendor/playwright-core/lib/entry/dashboardApp.js +3 -0
- package/ui/service/vendor/playwright-core/lib/entry/mcp.js +10 -0
- package/ui/service/vendor/playwright-core/lib/entry/oopBrowserDownload.js +3 -0
- package/ui/service/vendor/playwright-core/lib/package.js +50 -0
- package/ui/service/vendor/playwright-core/lib/server/chromium/appIcon.png +0 -0
- package/ui/service/vendor/playwright-core/lib/server/electron/loader.js +130 -0
- package/ui/service/vendor/playwright-core/lib/serverRegistry.js +1939 -0
- package/ui/service/vendor/playwright-core/lib/serverRegistry.js.LICENSE +65 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/channelSessions.js +143 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/cli.js +7 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/help.json +813 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/minimist.js +128 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/output.js +352 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/program.js +422 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/registry.js +180 -0
- package/ui/service/vendor/playwright-core/lib/tools/cli-client/session.js +261 -0
- package/ui/service/vendor/playwright-core/lib/tools/dashboard/appIcon.png +0 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/SKILL.md +493 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/pr-attachments.md +60 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/running-code.md +247 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/session-management.md +227 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/storage-state.md +278 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/tracing.md +146 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-cli/references/video-recording.md +216 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/SKILL.md +136 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/migration.md +89 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/react.md +69 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/typing.md +173 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-component-testing/references/vue.md +77 -0
- package/ui/service/vendor/playwright-core/lib/tools/skills/playwright-trace/SKILL.md +174 -0
- package/ui/service/vendor/playwright-core/lib/tools/utils/extension.js +112 -0
- package/ui/service/vendor/playwright-core/lib/tools/utils/socketConnection.js +108 -0
- package/ui/service/vendor/playwright-core/lib/utilsBundle.js +92408 -0
- package/ui/service/vendor/playwright-core/lib/utilsBundle.js.LICENSE +1917 -0
- package/ui/service/vendor/playwright-core/lib/webp_codec.LICENSE +173 -0
- package/ui/service/vendor/playwright-core/lib/webp_codec.wasm +0 -0
- package/ui/service/vendor/playwright-core/lib/xdg-open +1267 -0
- package/ui/service/vendor/playwright-core/package.json +34 -0
|
@@ -0,0 +1,2077 @@
|
|
|
1
|
+
// @capybara-hq/plugin-browser daemon (generated by daemon/build.ts)
|
|
2
|
+
|
|
3
|
+
// ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.70/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
|
|
4
|
+
var DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
|
|
5
|
+
var DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
|
|
6
|
+
var DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
|
|
7
|
+
var HEADER = 4;
|
|
8
|
+
function encodeServiceMessage(body) {
|
|
9
|
+
if (body.byteLength > DEVICE_SERVICE_MAX_MESSAGE)
|
|
10
|
+
throw new RangeError(`service message of ${body.byteLength} bytes exceeds ${DEVICE_SERVICE_MAX_MESSAGE} bytes`);
|
|
11
|
+
const out = new Uint8Array(HEADER + body.byteLength);
|
|
12
|
+
new DataView(out.buffer).setUint32(0, body.byteLength);
|
|
13
|
+
out.set(body, HEADER);
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
var ServiceMessageDecoder = class {
|
|
17
|
+
// unread bytes, oldest first from index `first`; `pending` is their total length
|
|
18
|
+
chunks = [];
|
|
19
|
+
first = 0;
|
|
20
|
+
pending = 0;
|
|
21
|
+
// the declared length of the message being read, once its header is complete
|
|
22
|
+
need = null;
|
|
23
|
+
push(chunk) {
|
|
24
|
+
if (chunk.byteLength > 0) {
|
|
25
|
+
this.chunks.push(chunk.slice());
|
|
26
|
+
this.pending += chunk.byteLength;
|
|
27
|
+
}
|
|
28
|
+
const out = [];
|
|
29
|
+
for (; ; ) {
|
|
30
|
+
if (this.need === null) {
|
|
31
|
+
if (this.pending < HEADER)
|
|
32
|
+
break;
|
|
33
|
+
const header = this.take(HEADER);
|
|
34
|
+
const len = new DataView(header.buffer, header.byteOffset, HEADER).getUint32(0);
|
|
35
|
+
if (len > DEVICE_SERVICE_MAX_MESSAGE)
|
|
36
|
+
throw new RangeError(`service message of ${len} bytes exceeds ${DEVICE_SERVICE_MAX_MESSAGE} bytes`);
|
|
37
|
+
this.need = len;
|
|
38
|
+
}
|
|
39
|
+
if (this.pending < this.need)
|
|
40
|
+
break;
|
|
41
|
+
out.push(this.take(this.need));
|
|
42
|
+
this.need = null;
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
/** Removes the first `n` (at most `pending`) bytes into one new array, copying each byte once. */
|
|
47
|
+
take(n) {
|
|
48
|
+
const out = new Uint8Array(n);
|
|
49
|
+
let at = 0;
|
|
50
|
+
while (at < n) {
|
|
51
|
+
const head = this.chunks[this.first];
|
|
52
|
+
if (head === void 0)
|
|
53
|
+
break;
|
|
54
|
+
const k = Math.min(head.byteLength, n - at);
|
|
55
|
+
out.set(head.subarray(0, k), at);
|
|
56
|
+
at += k;
|
|
57
|
+
if (k === head.byteLength)
|
|
58
|
+
this.first++;
|
|
59
|
+
else
|
|
60
|
+
this.chunks[this.first] = head.subarray(k);
|
|
61
|
+
}
|
|
62
|
+
if (this.first > 64 || this.first === this.chunks.length) {
|
|
63
|
+
this.chunks = this.chunks.slice(this.first);
|
|
64
|
+
this.first = 0;
|
|
65
|
+
}
|
|
66
|
+
this.pending -= n;
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// daemon/main.ts
|
|
72
|
+
import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync } from "node:fs";
|
|
73
|
+
import { createServer } from "node:net";
|
|
74
|
+
|
|
75
|
+
// daemon/actions.ts
|
|
76
|
+
import { lstatSync, mkdirSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
77
|
+
import { request as httpRequest } from "node:http";
|
|
78
|
+
import { basename, extname, join, sep } from "node:path";
|
|
79
|
+
|
|
80
|
+
// daemon/protocol.ts
|
|
81
|
+
var VIEWPORT = { width: 1280, height: 800 };
|
|
82
|
+
var SNAPSHOT_MAX_CHARS = 4e4;
|
|
83
|
+
var IDLE_STOP_MS = 15 * 6e4;
|
|
84
|
+
var TAKEOVER_GRACE_MS = 6e4;
|
|
85
|
+
var VIEWER_MAX_FPS = 5;
|
|
86
|
+
var VIEWER_UNACKED_FRAMES = 2;
|
|
87
|
+
var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
|
|
88
|
+
var HANDOFF_MAX_CHARS = 4096;
|
|
89
|
+
var MAX_TABS = 10;
|
|
90
|
+
var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
|
|
91
|
+
var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
|
|
92
|
+
var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
|
|
93
|
+
|
|
94
|
+
// daemon/snapshot.ts
|
|
95
|
+
var isNode = (line) => line.trimStart().startsWith("- ");
|
|
96
|
+
function capSnapshot(text, max = SNAPSHOT_MAX_CHARS) {
|
|
97
|
+
if (text.length <= max) return text;
|
|
98
|
+
const lines = text.split("\n");
|
|
99
|
+
const marker = (n) => `[truncated: ${n} more nodes]`;
|
|
100
|
+
const room = max - marker(lines.length).length - 1;
|
|
101
|
+
let used = 0;
|
|
102
|
+
let kept = 0;
|
|
103
|
+
while (kept < lines.length) {
|
|
104
|
+
const len = (lines[kept] ?? "").length + 1;
|
|
105
|
+
if (used + len > room) break;
|
|
106
|
+
used += len;
|
|
107
|
+
kept++;
|
|
108
|
+
}
|
|
109
|
+
const rest = lines.slice(kept).filter(isNode).length;
|
|
110
|
+
return `${lines.slice(0, kept).join("\n")}
|
|
111
|
+
${marker(rest)}`;
|
|
112
|
+
}
|
|
113
|
+
async function takeSnapshot(page) {
|
|
114
|
+
return capSnapshot(await page.ariaSnapshot({ mode: "ai" }));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// daemon/state.ts
|
|
118
|
+
var systemClock = {
|
|
119
|
+
now: () => Date.now(),
|
|
120
|
+
schedule: (fn, ms) => setTimeout(fn, ms).unref(),
|
|
121
|
+
cancel: (h) => clearTimeout(h)
|
|
122
|
+
};
|
|
123
|
+
var DaemonState = class {
|
|
124
|
+
clock;
|
|
125
|
+
idleMs;
|
|
126
|
+
graceMs;
|
|
127
|
+
onIdle;
|
|
128
|
+
listeners = /* @__PURE__ */ new Set();
|
|
129
|
+
viewers = 0;
|
|
130
|
+
inflight = 0;
|
|
131
|
+
since;
|
|
132
|
+
note;
|
|
133
|
+
idleTimer;
|
|
134
|
+
graceTimer;
|
|
135
|
+
disposed = false;
|
|
136
|
+
pendingHandoff;
|
|
137
|
+
/** When the first notice of the pending handoff arrived (the keepalive counts from it). */
|
|
138
|
+
handoffSince;
|
|
139
|
+
constructor(opts) {
|
|
140
|
+
this.clock = opts.clock ?? systemClock;
|
|
141
|
+
this.idleMs = opts.idleMs ?? IDLE_STOP_MS;
|
|
142
|
+
this.graceMs = opts.graceMs ?? TAKEOVER_GRACE_MS;
|
|
143
|
+
this.onIdle = opts.onIdle;
|
|
144
|
+
this.armIdle();
|
|
145
|
+
}
|
|
146
|
+
get control() {
|
|
147
|
+
return this.since === void 0 ? "agent" : "user";
|
|
148
|
+
}
|
|
149
|
+
/** When the person took control (ISO), while they hold it. */
|
|
150
|
+
get userControlledSince() {
|
|
151
|
+
return this.since === void 0 ? void 0 : new Date(this.since).toISOString();
|
|
152
|
+
}
|
|
153
|
+
get viewerCount() {
|
|
154
|
+
return this.viewers;
|
|
155
|
+
}
|
|
156
|
+
get requestsInFlight() {
|
|
157
|
+
return this.inflight;
|
|
158
|
+
}
|
|
159
|
+
/** Subscribes to control changes; returns the unsubscribe function. */
|
|
160
|
+
onChange(fn) {
|
|
161
|
+
this.listeners.add(fn);
|
|
162
|
+
return () => this.listeners.delete(fn);
|
|
163
|
+
}
|
|
164
|
+
/** The pending handoff question (the latest notice), if any. */
|
|
165
|
+
get handoff() {
|
|
166
|
+
return this.pendingHandoff;
|
|
167
|
+
}
|
|
168
|
+
/** Records a handoff question; it replaces any earlier one. */
|
|
169
|
+
noticeHandoff(callId, message) {
|
|
170
|
+
const m = message.length <= HANDOFF_MAX_CHARS ? message : `${message.slice(0, HANDOFF_MAX_CHARS - 1)}\u2026`;
|
|
171
|
+
this.pendingHandoff = { callId, message: m };
|
|
172
|
+
this.handoffSince ??= this.clock.now();
|
|
173
|
+
this.emit();
|
|
174
|
+
this.armIdle();
|
|
175
|
+
}
|
|
176
|
+
/** Clears the pending handoff when it is `callId`'s; a stale clear changes nothing. */
|
|
177
|
+
clearHandoff(callId) {
|
|
178
|
+
if (this.pendingHandoff?.callId !== callId) return;
|
|
179
|
+
this.endHandoff();
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Drops the pending handoff whatever its callId: the next agent tool request means its run has
|
|
183
|
+
* moved on (an aborted run never sends handoff_clear). This is device-wide on purpose: a tool
|
|
184
|
+
* call from any conversation of the device drops it, since they are all the owner's
|
|
185
|
+
* conversations and the browser is one.
|
|
186
|
+
*/
|
|
187
|
+
dropHandoff() {
|
|
188
|
+
if (this.pendingHandoff === void 0) return;
|
|
189
|
+
this.endHandoff();
|
|
190
|
+
}
|
|
191
|
+
endHandoff() {
|
|
192
|
+
this.pendingHandoff = void 0;
|
|
193
|
+
this.handoffSince = void 0;
|
|
194
|
+
this.emit();
|
|
195
|
+
this.armIdle();
|
|
196
|
+
}
|
|
197
|
+
takeover() {
|
|
198
|
+
if (this.since !== void 0) return;
|
|
199
|
+
this.since = this.clock.now();
|
|
200
|
+
this.note = void 0;
|
|
201
|
+
this.emit();
|
|
202
|
+
}
|
|
203
|
+
handback() {
|
|
204
|
+
if (this.since === void 0) return;
|
|
205
|
+
this.note = this.since;
|
|
206
|
+
this.since = void 0;
|
|
207
|
+
this.clearGrace();
|
|
208
|
+
this.emit();
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* When the last takeover began (ISO), once: the first tool reply after a hand back carries it so
|
|
212
|
+
* the agent learns the person drove the browser.
|
|
213
|
+
*/
|
|
214
|
+
takeHandbackNote() {
|
|
215
|
+
const n = this.note;
|
|
216
|
+
this.note = void 0;
|
|
217
|
+
return n === void 0 ? void 0 : new Date(n).toISOString();
|
|
218
|
+
}
|
|
219
|
+
viewerOpened() {
|
|
220
|
+
this.viewers++;
|
|
221
|
+
this.clearGrace();
|
|
222
|
+
this.armIdle();
|
|
223
|
+
}
|
|
224
|
+
viewerClosed() {
|
|
225
|
+
this.viewers = Math.max(0, this.viewers - 1);
|
|
226
|
+
if (this.viewers === 0 && this.since !== void 0) {
|
|
227
|
+
this.clearGrace();
|
|
228
|
+
this.graceTimer = this.clock.schedule(() => {
|
|
229
|
+
this.graceTimer = void 0;
|
|
230
|
+
this.handback();
|
|
231
|
+
}, this.graceMs);
|
|
232
|
+
}
|
|
233
|
+
this.armIdle();
|
|
234
|
+
}
|
|
235
|
+
requestStarted() {
|
|
236
|
+
this.inflight++;
|
|
237
|
+
this.armIdle();
|
|
238
|
+
}
|
|
239
|
+
requestEnded() {
|
|
240
|
+
this.inflight = Math.max(0, this.inflight - 1);
|
|
241
|
+
this.armIdle();
|
|
242
|
+
}
|
|
243
|
+
dispose() {
|
|
244
|
+
this.disposed = true;
|
|
245
|
+
this.clearGrace();
|
|
246
|
+
if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
|
|
247
|
+
this.idleTimer = void 0;
|
|
248
|
+
this.listeners.clear();
|
|
249
|
+
}
|
|
250
|
+
emit() {
|
|
251
|
+
for (const fn of [...this.listeners]) fn();
|
|
252
|
+
}
|
|
253
|
+
clearGrace() {
|
|
254
|
+
if (this.graceTimer !== void 0) this.clock.cancel(this.graceTimer);
|
|
255
|
+
this.graceTimer = void 0;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* (Re)starts the idle countdown when nothing is in use; stops it otherwise. A pending handoff
|
|
259
|
+
* keeps the daemon running until {@link HANDOFF_KEEPALIVE_MS} after its notice (the person is
|
|
260
|
+
* still to answer it); the device's idle suspension may still stop the device sooner.
|
|
261
|
+
*/
|
|
262
|
+
armIdle() {
|
|
263
|
+
if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
|
|
264
|
+
this.idleTimer = void 0;
|
|
265
|
+
if (this.disposed || this.viewers > 0 || this.inflight > 0) return;
|
|
266
|
+
const keepalive = this.handoffSince === void 0 ? 0 : this.handoffSince + HANDOFF_KEEPALIVE_MS - this.clock.now();
|
|
267
|
+
this.idleTimer = this.clock.schedule(
|
|
268
|
+
() => {
|
|
269
|
+
this.idleTimer = void 0;
|
|
270
|
+
this.onIdle();
|
|
271
|
+
},
|
|
272
|
+
Math.max(this.idleMs, keepalive)
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
// daemon/actions.ts
|
|
278
|
+
var ActionError = class extends Error {
|
|
279
|
+
constructor(code, message) {
|
|
280
|
+
super(message);
|
|
281
|
+
this.code = code;
|
|
282
|
+
}
|
|
283
|
+
code;
|
|
284
|
+
};
|
|
285
|
+
var DOWNLOAD_WAIT_MS = 1e4;
|
|
286
|
+
var DEFAULT_DOWNLOAD_MAX_BYTES = 200 * 1024 * 1024;
|
|
287
|
+
var DOWNLOAD_POLL_MS = 250;
|
|
288
|
+
var MAX_NAME_BYTES = 200;
|
|
289
|
+
var ACTION_TIMEOUT_MS = 1e4;
|
|
290
|
+
var NAVIGATION_TIMEOUT_MS = 3e4;
|
|
291
|
+
var LOAD_GRACE_MS = 5e3;
|
|
292
|
+
var MAX_WAIT_MS = 6e4;
|
|
293
|
+
var MAX_SCREENSHOT_BYTES = Math.floor((8 * 1024 * 1024 - 64 * 1024) * 3 / 4);
|
|
294
|
+
var MAX_TITLE_CHARS = 2048;
|
|
295
|
+
var MAX_URL_CHARS = 2048;
|
|
296
|
+
var MAX_DIALOG_CHARS = 4096;
|
|
297
|
+
var DEFAULT_WAIT_MS = 1e4;
|
|
298
|
+
var MAX_UNREPORTED = 20;
|
|
299
|
+
var TAKEN_OVER_MESSAGE = "The user is controlling the browser; call wait or handoff.";
|
|
300
|
+
function clip(s, max) {
|
|
301
|
+
return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}\u2026`;
|
|
302
|
+
}
|
|
303
|
+
function utf8Prefix(s, max) {
|
|
304
|
+
let out = "";
|
|
305
|
+
let bytes = 0;
|
|
306
|
+
for (const ch of s) {
|
|
307
|
+
const n = Buffer.byteLength(ch);
|
|
308
|
+
if (bytes + n > max) break;
|
|
309
|
+
out += ch;
|
|
310
|
+
bytes += n;
|
|
311
|
+
}
|
|
312
|
+
return out;
|
|
313
|
+
}
|
|
314
|
+
function safeFileName(raw) {
|
|
315
|
+
const visible = [...raw].map((ch) => {
|
|
316
|
+
const code = ch.charCodeAt(0);
|
|
317
|
+
return code < 32 || code === 127 ? "_" : ch;
|
|
318
|
+
}).join("");
|
|
319
|
+
const name = basename(visible.replace(/\\/g, "/")).replace(/[/:*?"<>|]/g, "_").replace(/^\.+/, "").trim();
|
|
320
|
+
if (name === "") return "download";
|
|
321
|
+
if (Buffer.byteLength(name) <= MAX_NAME_BYTES) return name;
|
|
322
|
+
let ext = extname(name);
|
|
323
|
+
if (Buffer.byteLength(ext) > 32) ext = "";
|
|
324
|
+
return utf8Prefix(name.slice(0, name.length - ext.length), MAX_NAME_BYTES - Buffer.byteLength(ext)) + ext;
|
|
325
|
+
}
|
|
326
|
+
function absent(path) {
|
|
327
|
+
try {
|
|
328
|
+
lstatSync(path);
|
|
329
|
+
return false;
|
|
330
|
+
} catch {
|
|
331
|
+
return true;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
var PROXY_PROBE_TIMEOUT_MS = 5e3;
|
|
335
|
+
var REF_RE = /^(f\d+)?e\d+$/;
|
|
336
|
+
var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
|
|
337
|
+
function jpegSize(jpeg) {
|
|
338
|
+
let i = 2;
|
|
339
|
+
while (i + 9 < jpeg.length) {
|
|
340
|
+
if (jpeg[i] !== 255) break;
|
|
341
|
+
const marker = jpeg[i + 1] ?? 0;
|
|
342
|
+
const len = jpeg.readUInt16BE(i + 2);
|
|
343
|
+
if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
|
|
344
|
+
return { height: jpeg.readUInt16BE(i + 5), width: jpeg.readUInt16BE(i + 7) };
|
|
345
|
+
}
|
|
346
|
+
i += 2 + len;
|
|
347
|
+
}
|
|
348
|
+
return { width: 0, height: 0 };
|
|
349
|
+
}
|
|
350
|
+
var QUALITIES = [80, 60, 40, 25];
|
|
351
|
+
var SCALES = [1, 0.75, 0.5, 0.35, 0.25, 0.15];
|
|
352
|
+
async function captureFitting(cdp, opts) {
|
|
353
|
+
const metrics = await cdp.send("Page.getLayoutMetrics");
|
|
354
|
+
const vv = metrics.cssVisualViewport;
|
|
355
|
+
const content = metrics.cssContentSize;
|
|
356
|
+
const area = opts.fullPage ? { x: 0, y: 0, width: content.width, height: Math.min(content.height, 16384) } : { x: vv.pageX, y: vv.pageY, width: vv.clientWidth, height: vv.clientHeight };
|
|
357
|
+
const maxScale = Math.min(1, opts.maxScale ?? 1);
|
|
358
|
+
for (const s of SCALES) {
|
|
359
|
+
const scale = s * maxScale;
|
|
360
|
+
if (scale * area.width < 16) break;
|
|
361
|
+
for (const quality of QUALITIES) {
|
|
362
|
+
const shot = await cdp.send("Page.captureScreenshot", {
|
|
363
|
+
format: "jpeg",
|
|
364
|
+
quality,
|
|
365
|
+
clip: { ...area, scale },
|
|
366
|
+
captureBeyondViewport: opts.fullPage === true
|
|
367
|
+
});
|
|
368
|
+
const bytes = Buffer.from(shot.data, "base64");
|
|
369
|
+
if (bytes.length <= opts.maxBytes) return { data: shot.data, ...jpegSize(bytes) };
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return null;
|
|
373
|
+
}
|
|
374
|
+
function proxyRefuses(proxy, host, port) {
|
|
375
|
+
return new Promise((resolve) => {
|
|
376
|
+
let url;
|
|
377
|
+
try {
|
|
378
|
+
url = new URL(proxy.includes("://") ? proxy : `http://${proxy}`);
|
|
379
|
+
} catch {
|
|
380
|
+
resolve(false);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const headers = { host: `${host}:${port}` };
|
|
384
|
+
if (url.username !== "") {
|
|
385
|
+
const cred = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
|
|
386
|
+
headers["proxy-authorization"] = `Basic ${Buffer.from(cred).toString("base64")}`;
|
|
387
|
+
}
|
|
388
|
+
const req = httpRequest({
|
|
389
|
+
host: url.hostname,
|
|
390
|
+
port: Number(url.port || 80),
|
|
391
|
+
method: "CONNECT",
|
|
392
|
+
path: `${host}:${port}`,
|
|
393
|
+
headers,
|
|
394
|
+
timeout: PROXY_PROBE_TIMEOUT_MS
|
|
395
|
+
});
|
|
396
|
+
req.on("connect", (res, socket) => {
|
|
397
|
+
socket.destroy();
|
|
398
|
+
resolve(res.statusCode === 403);
|
|
399
|
+
});
|
|
400
|
+
req.on("response", (res) => {
|
|
401
|
+
res.resume();
|
|
402
|
+
resolve(res.statusCode === 403);
|
|
403
|
+
});
|
|
404
|
+
req.on("timeout", () => req.destroy());
|
|
405
|
+
req.on("error", () => resolve(false));
|
|
406
|
+
req.end();
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function normalizeUrl(raw) {
|
|
410
|
+
const s = raw.trim();
|
|
411
|
+
if (s === "about:blank") return s;
|
|
412
|
+
const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(s) && !/^[^/]+:\d+(\/|$)/.test(s) ? s : `https://${s}`;
|
|
413
|
+
let url;
|
|
414
|
+
try {
|
|
415
|
+
url = new URL(withScheme);
|
|
416
|
+
} catch {
|
|
417
|
+
throw new ActionError("failed", `${JSON.stringify(raw)} is not a valid URL.`);
|
|
418
|
+
}
|
|
419
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
420
|
+
throw new ActionError("failed", `Only http and https URLs can be opened, not ${url.protocol}`);
|
|
421
|
+
}
|
|
422
|
+
return url.href;
|
|
423
|
+
}
|
|
424
|
+
var firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0]?.replace(/^[a-zA-Z.]+: /, "") ?? "";
|
|
425
|
+
var BrowserSession = class {
|
|
426
|
+
ctx;
|
|
427
|
+
proxy;
|
|
428
|
+
clock;
|
|
429
|
+
/** The device's workspace root (CAPYBARA_SERVICE_WORKSPACE): uploads and downloads stay in it. */
|
|
430
|
+
workspace;
|
|
431
|
+
downloadsTmp;
|
|
432
|
+
downloadMaxBytes;
|
|
433
|
+
downloadWaitMs;
|
|
434
|
+
/** Downloads in progress, cancelled together when their bytes pass the cap. */
|
|
435
|
+
activeDownloads = /* @__PURE__ */ new Set();
|
|
436
|
+
downloadPoll;
|
|
437
|
+
/**
|
|
438
|
+
* Files of downloads cancelled at the cap: Playwright removes them later, and until then they
|
|
439
|
+
* do not count toward the cap of the downloads that follow.
|
|
440
|
+
*/
|
|
441
|
+
cancelledTmp = /* @__PURE__ */ new Set();
|
|
442
|
+
pages = /* @__PURE__ */ new Map();
|
|
443
|
+
ids = /* @__PURE__ */ new WeakMap();
|
|
444
|
+
titles = /* @__PURE__ */ new Map();
|
|
445
|
+
loadingTabs = /* @__PURE__ */ new Set();
|
|
446
|
+
listeners = /* @__PURE__ */ new Set();
|
|
447
|
+
collectors = /* @__PURE__ */ new Set();
|
|
448
|
+
probes = /* @__PURE__ */ new Map();
|
|
449
|
+
reservedDownloads = /* @__PURE__ */ new Set();
|
|
450
|
+
unreported = [];
|
|
451
|
+
nextId = 1;
|
|
452
|
+
active;
|
|
453
|
+
queue = Promise.resolve();
|
|
454
|
+
/** The agent's latest click; `seq` grows with every click (viewers flash only new ones). */
|
|
455
|
+
lastClick;
|
|
456
|
+
clickSeq = 0;
|
|
457
|
+
constructor(ctx, opts) {
|
|
458
|
+
this.ctx = ctx;
|
|
459
|
+
this.proxy = opts.proxy;
|
|
460
|
+
this.workspace = opts.workspace;
|
|
461
|
+
this.downloadsTmp = opts.downloadsTmp;
|
|
462
|
+
this.downloadMaxBytes = opts.downloadMaxBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES;
|
|
463
|
+
this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
|
|
464
|
+
this.clock = opts.clock ?? systemClock;
|
|
465
|
+
ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
|
|
466
|
+
ctx.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);
|
|
467
|
+
ctx.on("page", (p) => {
|
|
468
|
+
if (!this.ids.has(p) && this.pages.size >= MAX_TABS) {
|
|
469
|
+
p.close().catch(() => void 0);
|
|
470
|
+
this.note(
|
|
471
|
+
`The page opened a popup, but the browser keeps at most ${MAX_TABS} tabs, so the popup was closed; close a tab and retry if it was needed.`
|
|
472
|
+
);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
this.track(p);
|
|
476
|
+
this.active = this.ids.get(p);
|
|
477
|
+
this.emit({ type: "active" });
|
|
478
|
+
this.emit({ type: "state" });
|
|
479
|
+
});
|
|
480
|
+
for (const p of ctx.pages()) this.track(p);
|
|
481
|
+
}
|
|
482
|
+
get context() {
|
|
483
|
+
return this.ctx;
|
|
484
|
+
}
|
|
485
|
+
on(fn) {
|
|
486
|
+
this.listeners.add(fn);
|
|
487
|
+
return () => this.listeners.delete(fn);
|
|
488
|
+
}
|
|
489
|
+
/** The active tab, opening a blank one when none is left. */
|
|
490
|
+
async activePage() {
|
|
491
|
+
const cur = this.active === void 0 ? void 0 : this.pages.get(this.active);
|
|
492
|
+
if (cur !== void 0 && !cur.isClosed()) return cur;
|
|
493
|
+
const first = [...this.pages.values()].find((p2) => !p2.isClosed());
|
|
494
|
+
if (first !== void 0) {
|
|
495
|
+
this.active = this.ids.get(first);
|
|
496
|
+
return first;
|
|
497
|
+
}
|
|
498
|
+
const p = await this.ctx.newPage();
|
|
499
|
+
this.track(p);
|
|
500
|
+
this.active = this.ids.get(p);
|
|
501
|
+
return p;
|
|
502
|
+
}
|
|
503
|
+
tabIdOf(page) {
|
|
504
|
+
return this.ids.get(page) ?? "";
|
|
505
|
+
}
|
|
506
|
+
tabs() {
|
|
507
|
+
return [...this.pages.entries()].map(([id, p]) => ({
|
|
508
|
+
id,
|
|
509
|
+
title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
|
|
510
|
+
url: clip(p.url(), MAX_URL_CHARS),
|
|
511
|
+
active: id === this.active
|
|
512
|
+
}));
|
|
513
|
+
}
|
|
514
|
+
/** Whether the active tab is loading a document. */
|
|
515
|
+
get loading() {
|
|
516
|
+
return this.active !== void 0 && this.loadingTabs.has(this.active);
|
|
517
|
+
}
|
|
518
|
+
emit(e) {
|
|
519
|
+
for (const fn of [...this.listeners]) {
|
|
520
|
+
try {
|
|
521
|
+
fn(e);
|
|
522
|
+
} catch {
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
track(page) {
|
|
527
|
+
if (this.ids.has(page)) return;
|
|
528
|
+
const id = `t${this.nextId++}`;
|
|
529
|
+
this.ids.set(page, id);
|
|
530
|
+
this.pages.set(id, page);
|
|
531
|
+
const refresh = () => {
|
|
532
|
+
page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).finally(() => this.emit({ type: "state" }));
|
|
533
|
+
};
|
|
534
|
+
page.on("request", (r) => {
|
|
535
|
+
if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
536
|
+
this.loadingTabs.add(id);
|
|
537
|
+
this.emit({ type: "state" });
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
page.on("framenavigated", (f) => {
|
|
541
|
+
if (f === page.mainFrame()) refresh();
|
|
542
|
+
});
|
|
543
|
+
page.on("domcontentloaded", refresh);
|
|
544
|
+
page.on("load", () => {
|
|
545
|
+
this.loadingTabs.delete(id);
|
|
546
|
+
refresh();
|
|
547
|
+
});
|
|
548
|
+
page.on("requestfailed", (r) => {
|
|
549
|
+
const err = r.failure()?.errorText ?? "";
|
|
550
|
+
if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
551
|
+
this.loadingTabs.delete(id);
|
|
552
|
+
this.emit({ type: "state" });
|
|
553
|
+
}
|
|
554
|
+
if (this.proxy !== void 0 && PROXY_FAILURE_RE.test(err))
|
|
555
|
+
this.checkBlocked(r.url(), this.pageToOpen(page, r));
|
|
556
|
+
});
|
|
557
|
+
page.on("response", (r) => {
|
|
558
|
+
if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
|
|
559
|
+
this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
page.on("dialog", (d) => this.onDialog(d));
|
|
563
|
+
page.on("download", (d) => this.onDownload(d));
|
|
564
|
+
page.on("filechooser", () => {
|
|
565
|
+
this.note("The page opened a file chooser; use the upload tool with the file input's ref.");
|
|
566
|
+
this.emit({ type: "dialog", kind: "file", message: "" });
|
|
567
|
+
});
|
|
568
|
+
page.on("close", () => {
|
|
569
|
+
this.pages.delete(id);
|
|
570
|
+
this.titles.delete(id);
|
|
571
|
+
this.loadingTabs.delete(id);
|
|
572
|
+
if (this.active === id) {
|
|
573
|
+
const next = [...this.pages.keys()].at(-1);
|
|
574
|
+
this.active = next;
|
|
575
|
+
this.emit({ type: "active" });
|
|
576
|
+
}
|
|
577
|
+
this.emit({ type: "state" });
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
onDialog(d) {
|
|
581
|
+
const type = d.type();
|
|
582
|
+
if (type === "beforeunload") {
|
|
583
|
+
d.accept().catch(() => void 0);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
const kind = type === "confirm" || type === "prompt" ? type : "alert";
|
|
587
|
+
const message = clip(d.message(), MAX_DIALOG_CHARS);
|
|
588
|
+
const settle = kind === "alert" ? d.accept() : d.dismiss();
|
|
589
|
+
settle.catch(() => void 0);
|
|
590
|
+
this.note(
|
|
591
|
+
`The page showed ${kind === "alert" ? "an alert" : `a ${kind}`} dialog: ${JSON.stringify(message)} (${kind === "alert" ? "closed" : "dismissed"}).`
|
|
592
|
+
);
|
|
593
|
+
this.emit({ type: "dialog", kind, message });
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Adds a note to the replies of the requests in flight; with none in flight (a download that
|
|
597
|
+
* finished after its click replied, a dialog the person caused) the next reply carries it.
|
|
598
|
+
*/
|
|
599
|
+
note(text) {
|
|
600
|
+
const n = clip(text, MAX_DIALOG_CHARS + 200);
|
|
601
|
+
if (this.collectors.size === 0) {
|
|
602
|
+
this.unreported.push(n);
|
|
603
|
+
if (this.unreported.length > MAX_UNREPORTED) this.unreported.shift();
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
for (const c of this.collectors) c.notes.push(n);
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Saves a download into `<workspace>/downloads` under its suggested name (sanitized, numbered
|
|
610
|
+
* when taken). A request in flight waits for it at most `downloadWaitMs`, then says it is still
|
|
611
|
+
* in progress; the result note then comes with a later reply. Downloads in progress are
|
|
612
|
+
* cancelled when together they pass `downloadMaxBytes`, so a page cannot fill the disk.
|
|
613
|
+
* Without a workspace the download is cancelled.
|
|
614
|
+
*/
|
|
615
|
+
onDownload(d) {
|
|
616
|
+
const shown = JSON.stringify(clip(d.suggestedFilename(), 300));
|
|
617
|
+
const workspace = this.workspace;
|
|
618
|
+
if (workspace === void 0) {
|
|
619
|
+
d.cancel().catch(() => void 0);
|
|
620
|
+
this.note(
|
|
621
|
+
`The page started a download (${shown}), which was cancelled: the device has no workspace.`
|
|
622
|
+
);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
this.activeDownloads.add(d);
|
|
626
|
+
this.pollDownloads();
|
|
627
|
+
const entry = { name: shown, done: Promise.resolve(), finished: false };
|
|
628
|
+
entry.done = (async () => {
|
|
629
|
+
let target;
|
|
630
|
+
try {
|
|
631
|
+
const failure = await d.failure();
|
|
632
|
+
if (failure !== null) {
|
|
633
|
+
if (failure !== "canceled") this.note(`The download of ${shown} failed: ${failure}.`);
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const tmp = await d.path();
|
|
637
|
+
if (statSync(tmp).size > this.downloadMaxBytes) {
|
|
638
|
+
this.note(
|
|
639
|
+
`The download of ${shown} was not saved: it is larger than ${this.downloadMaxBytes} bytes.`
|
|
640
|
+
);
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
target = this.downloadTarget(workspace, safeFileName(d.suggestedFilename()));
|
|
644
|
+
await d.saveAs(target);
|
|
645
|
+
this.note(`Downloaded ${shown} to ${target}.`);
|
|
646
|
+
} catch (e) {
|
|
647
|
+
this.note(
|
|
648
|
+
`The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
|
|
649
|
+
);
|
|
650
|
+
} finally {
|
|
651
|
+
if (target !== void 0) this.reservedDownloads.delete(target);
|
|
652
|
+
await d.delete().catch(() => void 0);
|
|
653
|
+
this.activeDownloads.delete(d);
|
|
654
|
+
entry.finished = true;
|
|
655
|
+
}
|
|
656
|
+
})();
|
|
657
|
+
for (const c of this.collectors) c.downloads.push(entry);
|
|
658
|
+
}
|
|
659
|
+
/** A free path in `<workspace>/downloads`, refusing a downloads directory that is a link. */
|
|
660
|
+
downloadTarget(workspace, name) {
|
|
661
|
+
const root = realpathSync(workspace);
|
|
662
|
+
const dir = join(root, "downloads");
|
|
663
|
+
mkdirSync(dir, { recursive: true });
|
|
664
|
+
const st = lstatSync(dir);
|
|
665
|
+
if (!st.isDirectory() || st.isSymbolicLink() || realpathSync(dir) !== dir) {
|
|
666
|
+
throw new ActionError(
|
|
667
|
+
"failed",
|
|
668
|
+
`${dir} is not a plain directory in the workspace; remove it so downloads can be saved.`
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
const ext = extname(name);
|
|
672
|
+
const stem = name.slice(0, name.length - ext.length);
|
|
673
|
+
let target = join(dir, name);
|
|
674
|
+
for (let i = 1; !absent(target) || this.reservedDownloads.has(target); i++) {
|
|
675
|
+
target = join(dir, `${stem} (${i})${ext}`);
|
|
676
|
+
}
|
|
677
|
+
this.reservedDownloads.add(target);
|
|
678
|
+
return target;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* While downloads run, sums the bytes of Playwright's in-progress files and cancels every
|
|
682
|
+
* running download once the sum passes the cap.
|
|
683
|
+
*/
|
|
684
|
+
pollDownloads() {
|
|
685
|
+
if (this.downloadPoll !== void 0 || this.activeDownloads.size === 0) return;
|
|
686
|
+
this.downloadPoll = this.clock.schedule(() => {
|
|
687
|
+
this.downloadPoll = void 0;
|
|
688
|
+
if (this.activeDownloads.size === 0) return;
|
|
689
|
+
let bytes = 0;
|
|
690
|
+
let names = [];
|
|
691
|
+
const dir = this.downloadsTmp;
|
|
692
|
+
if (dir !== void 0) {
|
|
693
|
+
try {
|
|
694
|
+
names = readdirSync(dir);
|
|
695
|
+
} catch {
|
|
696
|
+
}
|
|
697
|
+
for (const f of this.cancelledTmp) if (!names.includes(f)) this.cancelledTmp.delete(f);
|
|
698
|
+
for (const f of names) {
|
|
699
|
+
if (this.cancelledTmp.has(f)) continue;
|
|
700
|
+
try {
|
|
701
|
+
bytes += statSync(join(dir, f)).size;
|
|
702
|
+
} catch {
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (bytes > this.downloadMaxBytes) {
|
|
707
|
+
for (const f of names) this.cancelledTmp.add(f);
|
|
708
|
+
for (const d of this.activeDownloads) {
|
|
709
|
+
this.note(
|
|
710
|
+
`The download of ${JSON.stringify(clip(d.suggestedFilename(), 300))} was cancelled: downloads in progress passed ${this.downloadMaxBytes} bytes.`
|
|
711
|
+
);
|
|
712
|
+
d.cancel().catch(() => void 0);
|
|
713
|
+
}
|
|
714
|
+
this.activeDownloads.clear();
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
this.pollDownloads();
|
|
718
|
+
}, DOWNLOAD_POLL_MS);
|
|
719
|
+
}
|
|
720
|
+
/** The real path of an upload, refused unless it is inside the workspace. */
|
|
721
|
+
uploadPath(path) {
|
|
722
|
+
const workspace = this.workspace;
|
|
723
|
+
if (workspace === void 0) {
|
|
724
|
+
throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
|
|
725
|
+
}
|
|
726
|
+
const root = realpathSync(workspace);
|
|
727
|
+
let real;
|
|
728
|
+
try {
|
|
729
|
+
real = realpathSync(path);
|
|
730
|
+
} catch {
|
|
731
|
+
throw new ActionError(
|
|
732
|
+
"failed",
|
|
733
|
+
`No file at ${path}; give the absolute path of a file in the workspace (${root}).`
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
if (real !== root && !real.startsWith(root.endsWith(sep) ? root : root + sep)) {
|
|
737
|
+
throw new ActionError(
|
|
738
|
+
"failed",
|
|
739
|
+
`Upload paths must be inside the workspace (${root}); copy the file there first.`
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
return real;
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* The page a viewer opens once the refused host is allowed: the navigation's target for a
|
|
746
|
+
* main-frame navigation, else the page that loaded the refused resource.
|
|
747
|
+
*/
|
|
748
|
+
pageToOpen(page, r) {
|
|
749
|
+
return r.isNavigationRequest() && r.frame() === page.mainFrame() ? r.url() : page.url();
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Probes the proxy for the URL's host and reports it when refused; the viewers' `blocked`
|
|
753
|
+
* message carries `pageUrl` (default: the URL itself), the page to open once allowed.
|
|
754
|
+
*/
|
|
755
|
+
checkBlocked(rawUrl, pageUrl) {
|
|
756
|
+
const proxy = this.proxy;
|
|
757
|
+
if (proxy === void 0) return Promise.resolve(false);
|
|
758
|
+
let url;
|
|
759
|
+
try {
|
|
760
|
+
url = new URL(rawUrl);
|
|
761
|
+
} catch {
|
|
762
|
+
return Promise.resolve(false);
|
|
763
|
+
}
|
|
764
|
+
const host = url.hostname;
|
|
765
|
+
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
766
|
+
let probe = this.probes.get(host);
|
|
767
|
+
if (probe === void 0) {
|
|
768
|
+
probe = proxyRefuses(proxy, host, port).then((refused) => {
|
|
769
|
+
this.probes.delete(host);
|
|
770
|
+
if (refused) {
|
|
771
|
+
for (const c of this.collectors) c.blocked.add(host);
|
|
772
|
+
this.emit({ type: "blocked", host, url: pageUrl ?? url.href });
|
|
773
|
+
}
|
|
774
|
+
return refused;
|
|
775
|
+
});
|
|
776
|
+
this.probes.set(host, probe);
|
|
777
|
+
}
|
|
778
|
+
for (const c of this.collectors) c.pending.push(probe);
|
|
779
|
+
return probe;
|
|
780
|
+
}
|
|
781
|
+
/** Runs `fn` one at a time with the other actions (`wait` runs beside them). */
|
|
782
|
+
serial(fn) {
|
|
783
|
+
const run = this.queue.then(fn, fn);
|
|
784
|
+
this.queue = run.catch(() => void 0);
|
|
785
|
+
return run;
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Runs a tool request; never throws. `takenOver` is checked when a queued request leaves the
|
|
789
|
+
* queue: a takeover that began while it waited refuses it. An action already running is left to
|
|
790
|
+
* finish (stopping it halfway would leave the page in an unknown state).
|
|
791
|
+
*/
|
|
792
|
+
async run(req, opts = {}) {
|
|
793
|
+
const late = this.unreported.splice(0);
|
|
794
|
+
const c = { blocked: /* @__PURE__ */ new Set(), notes: [...late], pending: [], downloads: [] };
|
|
795
|
+
this.collectors.add(c);
|
|
796
|
+
let reply;
|
|
797
|
+
try {
|
|
798
|
+
const out = await (req.op === "wait" ? this.exec(req) : this.serial(() => {
|
|
799
|
+
if (opts.takenOver?.() === true)
|
|
800
|
+
throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
|
|
801
|
+
return this.exec(req);
|
|
802
|
+
}));
|
|
803
|
+
await this.settleProbes(c);
|
|
804
|
+
await this.settleDownloads(c);
|
|
805
|
+
this.collectors.delete(c);
|
|
806
|
+
const page = await this.activePage();
|
|
807
|
+
const text = [...c.notes, ...out.text === void 0 ? [] : [out.text]].join("\n");
|
|
808
|
+
reply = {
|
|
809
|
+
ok: true,
|
|
810
|
+
page: await this.pageInfo(page),
|
|
811
|
+
blockedHosts: [...c.blocked],
|
|
812
|
+
...text === "" ? {} : { text },
|
|
813
|
+
...out.image === void 0 ? {} : { image: out.image }
|
|
814
|
+
};
|
|
815
|
+
} catch (e) {
|
|
816
|
+
await this.settleProbes(c);
|
|
817
|
+
let code = e instanceof ActionError ? e.code : "failed";
|
|
818
|
+
let message = e instanceof ActionError ? e.message : firstLine(e);
|
|
819
|
+
if (!(e instanceof ActionError) && e instanceof Error && e.name === "TimeoutError") {
|
|
820
|
+
code = "timeout";
|
|
821
|
+
}
|
|
822
|
+
if (c.blocked.size > 0 && code !== "no_such_ref" && code !== "taken_over") {
|
|
823
|
+
code = "blocked";
|
|
824
|
+
message = `The device's network settings block ${[...c.blocked].join(", ")}.`;
|
|
825
|
+
}
|
|
826
|
+
reply = { ok: false, error: code, message, blockedHosts: [...c.blocked] };
|
|
827
|
+
this.unreported.unshift(...late);
|
|
828
|
+
} finally {
|
|
829
|
+
this.collectors.delete(c);
|
|
830
|
+
}
|
|
831
|
+
this.emit({ type: "state" });
|
|
832
|
+
return reply;
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* Waits for the request's downloads at most `downloadWaitMs`; those still running are noted as
|
|
836
|
+
* in progress (their result note comes later).
|
|
837
|
+
*/
|
|
838
|
+
async settleDownloads(c) {
|
|
839
|
+
if (c.downloads.length === 0) return;
|
|
840
|
+
let timer;
|
|
841
|
+
await Promise.race([
|
|
842
|
+
Promise.allSettled(c.downloads.map((x) => x.done)),
|
|
843
|
+
new Promise((r) => {
|
|
844
|
+
timer = this.clock.schedule(r, this.downloadWaitMs);
|
|
845
|
+
})
|
|
846
|
+
]);
|
|
847
|
+
this.clock.cancel(timer);
|
|
848
|
+
for (const x of c.downloads) {
|
|
849
|
+
if (!x.finished)
|
|
850
|
+
c.notes.push(
|
|
851
|
+
`Download still in progress: ${x.name}; a later reply says where it was saved.`
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
async settleProbes(c) {
|
|
856
|
+
while (c.pending.length > 0) {
|
|
857
|
+
const all = c.pending.splice(0);
|
|
858
|
+
await Promise.allSettled(all);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
async pageInfo(page) {
|
|
862
|
+
let title = "";
|
|
863
|
+
try {
|
|
864
|
+
title = await page.title();
|
|
865
|
+
} catch {
|
|
866
|
+
title = this.titles.get(this.tabIdOf(page)) ?? "";
|
|
867
|
+
}
|
|
868
|
+
return {
|
|
869
|
+
url: clip(page.url(), MAX_URL_CHARS),
|
|
870
|
+
title: clip(title, MAX_TITLE_CHARS),
|
|
871
|
+
tabId: this.tabIdOf(page)
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
async locate(page, ref) {
|
|
875
|
+
if (!REF_RE.test(ref)) {
|
|
876
|
+
throw new ActionError(
|
|
877
|
+
"no_such_ref",
|
|
878
|
+
`${JSON.stringify(ref)} is not an element ref; refs look like e12. Take a snapshot first.`
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
const loc = page.getByRef(ref);
|
|
882
|
+
let n = 0;
|
|
883
|
+
try {
|
|
884
|
+
n = await loc.count();
|
|
885
|
+
} catch {
|
|
886
|
+
n = 0;
|
|
887
|
+
}
|
|
888
|
+
if (n === 0) {
|
|
889
|
+
throw new ActionError(
|
|
890
|
+
"no_such_ref",
|
|
891
|
+
`No element has ref ${ref} on this page; take a new snapshot and use a ref from it.`
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
return loc.first();
|
|
895
|
+
}
|
|
896
|
+
/** Runs `fn`; when it started a main-frame navigation, waits until that document has loaded. */
|
|
897
|
+
async settled(page, fn) {
|
|
898
|
+
let navigating = false;
|
|
899
|
+
let loaded2 = false;
|
|
900
|
+
const onReq = (r) => {
|
|
901
|
+
if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
|
|
902
|
+
navigating = true;
|
|
903
|
+
loaded2 = false;
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
const onLoad = () => {
|
|
907
|
+
loaded2 = true;
|
|
908
|
+
};
|
|
909
|
+
page.on("request", onReq);
|
|
910
|
+
page.on("domcontentloaded", onLoad);
|
|
911
|
+
try {
|
|
912
|
+
const out = await fn();
|
|
913
|
+
if (navigating && !loaded2) {
|
|
914
|
+
await page.waitForEvent("domcontentloaded", { timeout: NAVIGATION_TIMEOUT_MS }).catch(() => void 0);
|
|
915
|
+
}
|
|
916
|
+
return out;
|
|
917
|
+
} finally {
|
|
918
|
+
page.off("request", onReq);
|
|
919
|
+
page.off("domcontentloaded", onLoad);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
async centerOf(loc) {
|
|
923
|
+
const box = await loc.boundingBox().catch(() => null);
|
|
924
|
+
if (box === null) return void 0;
|
|
925
|
+
return { x: Math.round(box.x + box.width / 2), y: Math.round(box.y + box.height / 2) };
|
|
926
|
+
}
|
|
927
|
+
checkPoint(x, y) {
|
|
928
|
+
if (!(x >= 0 && y >= 0 && x < VIEWPORT.width && y < VIEWPORT.height)) {
|
|
929
|
+
throw new ActionError(
|
|
930
|
+
"failed",
|
|
931
|
+
`(${x}, ${y}) is outside the ${VIEWPORT.width}x${VIEWPORT.height} viewport; use viewport pixel coordinates from a screenshot.`
|
|
932
|
+
);
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
markClick(x, y) {
|
|
936
|
+
this.lastClick = { x, y, seq: ++this.clickSeq };
|
|
937
|
+
}
|
|
938
|
+
async goto(page, url) {
|
|
939
|
+
let res;
|
|
940
|
+
const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
|
|
941
|
+
download.catch(() => void 0);
|
|
942
|
+
try {
|
|
943
|
+
res = await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
944
|
+
} catch (e) {
|
|
945
|
+
const msg = firstLine(e);
|
|
946
|
+
if (msg.includes("Download is starting")) {
|
|
947
|
+
await download.catch(() => void 0);
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
if (PROXY_FAILURE_RE.test(msg)) await this.checkBlocked(url);
|
|
951
|
+
throw e;
|
|
952
|
+
}
|
|
953
|
+
if (res?.status() === 403 && await this.checkBlocked(res.url())) {
|
|
954
|
+
throw new ActionError(
|
|
955
|
+
"blocked",
|
|
956
|
+
`The device's network settings block ${new URL(res.url()).hostname}.`
|
|
957
|
+
);
|
|
958
|
+
}
|
|
959
|
+
await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
|
|
960
|
+
}
|
|
961
|
+
async exec(req) {
|
|
962
|
+
switch (req.op) {
|
|
963
|
+
case "navigate": {
|
|
964
|
+
const page = await this.activePage();
|
|
965
|
+
if (req.url !== void 0) {
|
|
966
|
+
await this.goto(page, normalizeUrl(req.url));
|
|
967
|
+
} else if (req.action === "back" || req.action === "forward") {
|
|
968
|
+
const r = await (req.action === "back" ? page.goBack() : page.goForward());
|
|
969
|
+
if (r === null && page.url() === "about:blank") {
|
|
970
|
+
return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
|
|
971
|
+
}
|
|
972
|
+
} else if (req.action === "reload") {
|
|
973
|
+
await page.reload({ waitUntil: "domcontentloaded" });
|
|
974
|
+
} else {
|
|
975
|
+
throw new ActionError(
|
|
976
|
+
"failed",
|
|
977
|
+
"navigate needs a url or an action (back, forward, reload)."
|
|
978
|
+
);
|
|
979
|
+
}
|
|
980
|
+
return {};
|
|
981
|
+
}
|
|
982
|
+
case "tabs":
|
|
983
|
+
return this.tabsOp(req);
|
|
984
|
+
case "snapshot":
|
|
985
|
+
return { text: await takeSnapshot(await this.activePage()) };
|
|
986
|
+
case "click":
|
|
987
|
+
case "hover": {
|
|
988
|
+
const page = await this.activePage();
|
|
989
|
+
const loc = await this.locate(page, req.ref);
|
|
990
|
+
if (req.op === "hover") {
|
|
991
|
+
await loc.hover();
|
|
992
|
+
return {};
|
|
993
|
+
}
|
|
994
|
+
const at = await this.centerOf(loc);
|
|
995
|
+
if (at !== void 0) this.markClick(at.x, at.y);
|
|
996
|
+
await this.settled(page, () => loc.click());
|
|
997
|
+
return {};
|
|
998
|
+
}
|
|
999
|
+
case "type": {
|
|
1000
|
+
const page = await this.activePage();
|
|
1001
|
+
const loc = await this.locate(page, req.ref);
|
|
1002
|
+
await loc.fill(req.text);
|
|
1003
|
+
if (req.submit === true) await this.settled(page, () => loc.press("Enter"));
|
|
1004
|
+
return {};
|
|
1005
|
+
}
|
|
1006
|
+
case "select": {
|
|
1007
|
+
const page = await this.activePage();
|
|
1008
|
+
const loc = await this.locate(page, req.ref);
|
|
1009
|
+
const chosen = await this.settled(page, () => loc.selectOption(req.values));
|
|
1010
|
+
return { text: `Selected ${JSON.stringify(chosen)}.` };
|
|
1011
|
+
}
|
|
1012
|
+
case "press": {
|
|
1013
|
+
const page = await this.activePage();
|
|
1014
|
+
await this.settled(page, () => page.keyboard.press(req.key));
|
|
1015
|
+
return {};
|
|
1016
|
+
}
|
|
1017
|
+
case "scroll": {
|
|
1018
|
+
const page = await this.activePage();
|
|
1019
|
+
if (req.ref !== void 0) {
|
|
1020
|
+
const loc = await this.locate(page, req.ref);
|
|
1021
|
+
await loc.scrollIntoViewIfNeeded();
|
|
1022
|
+
if (req.dy !== 0) {
|
|
1023
|
+
await loc.hover();
|
|
1024
|
+
await page.mouse.wheel(0, req.dy);
|
|
1025
|
+
}
|
|
1026
|
+
} else {
|
|
1027
|
+
await page.evaluate(`window.scrollBy(0, ${Number(req.dy) || 0})`);
|
|
1028
|
+
}
|
|
1029
|
+
return {};
|
|
1030
|
+
}
|
|
1031
|
+
case "upload": {
|
|
1032
|
+
const page = await this.activePage();
|
|
1033
|
+
const path = this.uploadPath(req.path);
|
|
1034
|
+
const loc = await this.locate(page, req.ref);
|
|
1035
|
+
await loc.setInputFiles(path);
|
|
1036
|
+
return {};
|
|
1037
|
+
}
|
|
1038
|
+
case "click_at":
|
|
1039
|
+
case "type_at": {
|
|
1040
|
+
const page = await this.activePage();
|
|
1041
|
+
this.checkPoint(req.x, req.y);
|
|
1042
|
+
this.markClick(Math.round(req.x), Math.round(req.y));
|
|
1043
|
+
await this.settled(page, () => page.mouse.click(req.x, req.y));
|
|
1044
|
+
if (req.op === "type_at") await page.keyboard.type(req.text);
|
|
1045
|
+
return {};
|
|
1046
|
+
}
|
|
1047
|
+
case "wait":
|
|
1048
|
+
return this.waitOp(req);
|
|
1049
|
+
case "screenshot": {
|
|
1050
|
+
const page = await this.activePage();
|
|
1051
|
+
const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
|
|
1052
|
+
if (!(maxBytes > 0))
|
|
1053
|
+
throw new ActionError("failed", "screenshot needs a positive maxBytes.");
|
|
1054
|
+
const cdp = await this.ctx.newCDPSession(page);
|
|
1055
|
+
try {
|
|
1056
|
+
const shot = await captureFitting(cdp, {
|
|
1057
|
+
maxBytes,
|
|
1058
|
+
...req.fullPage === true ? { fullPage: true } : {}
|
|
1059
|
+
});
|
|
1060
|
+
if (shot === null) {
|
|
1061
|
+
throw new ActionError(
|
|
1062
|
+
"failed",
|
|
1063
|
+
`The page does not fit in a ${maxBytes}-byte screenshot even at the smallest size; use snapshot instead.`
|
|
1064
|
+
);
|
|
1065
|
+
}
|
|
1066
|
+
return {
|
|
1067
|
+
image: shot.data,
|
|
1068
|
+
text: `Screenshot ${shot.width}x${shot.height} (viewport ${VIEWPORT.width}x${VIEWPORT.height}).`
|
|
1069
|
+
};
|
|
1070
|
+
} finally {
|
|
1071
|
+
await cdp.detach().catch(() => void 0);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
throw new ActionError(
|
|
1076
|
+
"failed",
|
|
1077
|
+
`Unknown browser operation ${JSON.stringify(req.op)}.`
|
|
1078
|
+
);
|
|
1079
|
+
}
|
|
1080
|
+
async tabsOp(req) {
|
|
1081
|
+
switch (req.action) {
|
|
1082
|
+
case "list": {
|
|
1083
|
+
await this.activePage();
|
|
1084
|
+
const lines = await Promise.all(
|
|
1085
|
+
[...this.pages.entries()].map(async ([id, p]) => {
|
|
1086
|
+
const info = await this.pageInfo(p);
|
|
1087
|
+
return `${id}${id === this.active ? " (active)" : ""}: ${info.title || "(no title)"} ${info.url}`;
|
|
1088
|
+
})
|
|
1089
|
+
);
|
|
1090
|
+
return { text: lines.join("\n") };
|
|
1091
|
+
}
|
|
1092
|
+
case "open": {
|
|
1093
|
+
const page = await this.openTab();
|
|
1094
|
+
if (req.url !== void 0) await this.goto(page, normalizeUrl(req.url));
|
|
1095
|
+
return {};
|
|
1096
|
+
}
|
|
1097
|
+
case "switch": {
|
|
1098
|
+
const page = this.tabById(req.tabId);
|
|
1099
|
+
this.active = req.tabId;
|
|
1100
|
+
await page.bringToFront().catch(() => void 0);
|
|
1101
|
+
this.emit({ type: "active" });
|
|
1102
|
+
return {};
|
|
1103
|
+
}
|
|
1104
|
+
case "close": {
|
|
1105
|
+
const page = this.tabById(req.tabId);
|
|
1106
|
+
await page.close();
|
|
1107
|
+
await this.activePage();
|
|
1108
|
+
return {};
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
throw new ActionError("failed", "tabs needs an action: list, open, switch or close.");
|
|
1112
|
+
}
|
|
1113
|
+
/** Opens a blank tab and makes it active. */
|
|
1114
|
+
async openTab() {
|
|
1115
|
+
if (this.pages.size >= MAX_TABS) {
|
|
1116
|
+
throw new ActionError(
|
|
1117
|
+
"failed",
|
|
1118
|
+
`The browser has ${MAX_TABS} tabs open, the most it keeps; close one first.`
|
|
1119
|
+
);
|
|
1120
|
+
}
|
|
1121
|
+
const page = await this.ctx.newPage();
|
|
1122
|
+
this.track(page);
|
|
1123
|
+
this.active = this.ids.get(page);
|
|
1124
|
+
this.emit({ type: "active" });
|
|
1125
|
+
this.emit({ type: "state" });
|
|
1126
|
+
return page;
|
|
1127
|
+
}
|
|
1128
|
+
tabById(tabId) {
|
|
1129
|
+
const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
|
|
1130
|
+
if (page === void 0 || page.isClosed()) {
|
|
1131
|
+
throw new ActionError(
|
|
1132
|
+
"failed",
|
|
1133
|
+
`No tab ${JSON.stringify(tabId ?? "")}; list the tabs to see their ids.`
|
|
1134
|
+
);
|
|
1135
|
+
}
|
|
1136
|
+
return page;
|
|
1137
|
+
}
|
|
1138
|
+
/** Makes a tab active (a viewer's tab switch). */
|
|
1139
|
+
async switchTo(tabId) {
|
|
1140
|
+
const page = this.tabById(tabId);
|
|
1141
|
+
this.active = tabId;
|
|
1142
|
+
await page.bringToFront().catch(() => void 0);
|
|
1143
|
+
this.emit({ type: "active" });
|
|
1144
|
+
this.emit({ type: "state" });
|
|
1145
|
+
}
|
|
1146
|
+
/** Navigates the active tab for a viewer (address bar, back, forward, reload); never throws. */
|
|
1147
|
+
async viewerNav(nav) {
|
|
1148
|
+
try {
|
|
1149
|
+
const page = await this.activePage();
|
|
1150
|
+
if (nav.url !== void 0) await this.goto(page, normalizeUrl(nav.url));
|
|
1151
|
+
else if (nav.action === "back") await page.goBack();
|
|
1152
|
+
else if (nav.action === "forward") await page.goForward();
|
|
1153
|
+
else if (nav.action === "reload") await page.reload();
|
|
1154
|
+
} catch {
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
async waitOp(req) {
|
|
1158
|
+
const asked = Number(req.timeoutMs);
|
|
1159
|
+
const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
|
|
1160
|
+
const page = await this.activePage();
|
|
1161
|
+
if (req.text !== void 0) {
|
|
1162
|
+
await page.getByText(req.text).first().waitFor({ state: "visible", timeout }).catch((e) => {
|
|
1163
|
+
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
|
|
1164
|
+
"timeout",
|
|
1165
|
+
`${JSON.stringify(req.text)} did not appear within ${timeout} ms.`
|
|
1166
|
+
) : e;
|
|
1167
|
+
});
|
|
1168
|
+
await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
|
|
1169
|
+
return {};
|
|
1170
|
+
}
|
|
1171
|
+
if (req.ref !== void 0) {
|
|
1172
|
+
if (!REF_RE.test(req.ref))
|
|
1173
|
+
throw new ActionError(
|
|
1174
|
+
"no_such_ref",
|
|
1175
|
+
`${JSON.stringify(req.ref)} is not an element ref; refs look like e12.`
|
|
1176
|
+
);
|
|
1177
|
+
await page.getByRef(req.ref).first().waitFor({ state: "visible", timeout }).catch((e) => {
|
|
1178
|
+
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError("timeout", `Element ${req.ref} did not appear within ${timeout} ms.`) : e;
|
|
1179
|
+
});
|
|
1180
|
+
return {};
|
|
1181
|
+
}
|
|
1182
|
+
if (req.navigation === true) {
|
|
1183
|
+
await page.waitForEvent("framenavigated", { predicate: (f) => f === page.mainFrame(), timeout }).catch((e) => {
|
|
1184
|
+
throw e instanceof Error && e.name === "TimeoutError" ? new ActionError("timeout", `No navigation within ${timeout} ms.`) : e;
|
|
1185
|
+
});
|
|
1186
|
+
await page.waitForLoadState("domcontentloaded").catch(() => void 0);
|
|
1187
|
+
return {};
|
|
1188
|
+
}
|
|
1189
|
+
await new Promise((r) => this.clock.schedule(r, timeout));
|
|
1190
|
+
return {};
|
|
1191
|
+
}
|
|
1192
|
+
/** Closes the browser (flushes the profile). */
|
|
1193
|
+
async close() {
|
|
1194
|
+
this.listeners.clear();
|
|
1195
|
+
if (this.downloadPoll !== void 0) this.clock.cancel(this.downloadPoll);
|
|
1196
|
+
await this.ctx.close().catch(() => void 0);
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
|
|
1200
|
+
// daemon/chromium.ts
|
|
1201
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
1202
|
+
import { createRequire } from "node:module";
|
|
1203
|
+
import { dirname, join as join2 } from "node:path";
|
|
1204
|
+
import { fileURLToPath } from "node:url";
|
|
1205
|
+
function envValue(env, name) {
|
|
1206
|
+
const v = env[name] ?? env[name.toLowerCase()];
|
|
1207
|
+
return v === void 0 || v === "" ? void 0 : v;
|
|
1208
|
+
}
|
|
1209
|
+
function headlessShellRevision() {
|
|
1210
|
+
const candidates = [new URL("./vendor/playwright-core/browsers.json", import.meta.url)];
|
|
1211
|
+
try {
|
|
1212
|
+
const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
|
|
1213
|
+
candidates.push(new URL(`file://${join2(dirname(pkg), "browsers.json")}`));
|
|
1214
|
+
} catch {
|
|
1215
|
+
}
|
|
1216
|
+
for (const file of candidates) {
|
|
1217
|
+
try {
|
|
1218
|
+
const json = JSON.parse(readFileSync(fileURLToPath(file), "utf8"));
|
|
1219
|
+
const rev = json.browsers?.find((b) => b.name === "chromium-headless-shell")?.revision;
|
|
1220
|
+
if (typeof rev === "string" && rev !== "") return rev;
|
|
1221
|
+
} catch {
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
return void 0;
|
|
1225
|
+
}
|
|
1226
|
+
function playwrightDownloadHosts(env) {
|
|
1227
|
+
const custom = envValue(env, "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST") ?? envValue(env, "PLAYWRIGHT_DOWNLOAD_HOST");
|
|
1228
|
+
if (custom !== void 0) {
|
|
1229
|
+
try {
|
|
1230
|
+
return [new URL(custom.includes("://") ? custom : `https://${custom}`).hostname];
|
|
1231
|
+
} catch {
|
|
1232
|
+
return [];
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com"];
|
|
1236
|
+
}
|
|
1237
|
+
function browsersPathFor(stateDir, env, revision) {
|
|
1238
|
+
const cache = envValue(env, "PLAYWRIGHT_BROWSERS_PATH");
|
|
1239
|
+
if (cache !== void 0 && revision !== void 0 && existsSync(join2(cache, `chromium_headless_shell-${revision}`)))
|
|
1240
|
+
return cache;
|
|
1241
|
+
return join2(stateDir, "browsers");
|
|
1242
|
+
}
|
|
1243
|
+
function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
|
|
1244
|
+
const args = ["--headless", "--use-mock-keychain"];
|
|
1245
|
+
if (opts.platform === "darwin") args.push("--single-process");
|
|
1246
|
+
const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
|
|
1247
|
+
let proxyAuth;
|
|
1248
|
+
if (proxy !== void 0) {
|
|
1249
|
+
const noProxy = envValue(opts.env, "NO_PROXY");
|
|
1250
|
+
const bypass = (noProxy ?? "").split(",").map((s) => s.trim()).filter((s) => s !== "");
|
|
1251
|
+
let url;
|
|
1252
|
+
try {
|
|
1253
|
+
url = new URL(proxy.includes("://") ? proxy : `http://${proxy}`);
|
|
1254
|
+
} catch {
|
|
1255
|
+
url = void 0;
|
|
1256
|
+
}
|
|
1257
|
+
if (url !== void 0 && (url.username !== "" || url.password !== "")) {
|
|
1258
|
+
proxyAuth = {
|
|
1259
|
+
server: `${url.protocol}//${url.host}`,
|
|
1260
|
+
username: decodeURIComponent(url.username),
|
|
1261
|
+
password: decodeURIComponent(url.password),
|
|
1262
|
+
...bypass.length > 0 ? { bypass: bypass.join(",") } : {}
|
|
1263
|
+
};
|
|
1264
|
+
} else {
|
|
1265
|
+
args.push(`--proxy-server=${proxy}`);
|
|
1266
|
+
if (bypass.length > 0) args.push(`--proxy-bypass-list=${bypass.join(";")}`);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
return {
|
|
1270
|
+
browsersPath: opts.browsersPath ?? browsersPathFor(opts.stateDir, opts.env, revision),
|
|
1271
|
+
profileDir: join2(opts.stateDir, "profile"),
|
|
1272
|
+
downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
|
|
1273
|
+
args,
|
|
1274
|
+
proxy,
|
|
1275
|
+
...proxyAuth === void 0 ? {} : { proxyAuth }
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
var loaded;
|
|
1279
|
+
async function loadPlaywright(browsersPath) {
|
|
1280
|
+
if (loaded !== void 0) {
|
|
1281
|
+
if (loaded.browsersPath !== browsersPath) {
|
|
1282
|
+
throw new Error(
|
|
1283
|
+
`playwright-core is already loaded with browsers in ${loaded.browsersPath}, not ${browsersPath}`
|
|
1284
|
+
);
|
|
1285
|
+
}
|
|
1286
|
+
return loaded.pw;
|
|
1287
|
+
}
|
|
1288
|
+
process.env.PLAYWRIGHT_BROWSERS_PATH = browsersPath;
|
|
1289
|
+
const pw = await import("./vendor/playwright-core/index.mjs");
|
|
1290
|
+
loaded = { browsersPath, pw: pw.default ?? pw };
|
|
1291
|
+
return loaded.pw;
|
|
1292
|
+
}
|
|
1293
|
+
async function ensureChromium(browsersPath) {
|
|
1294
|
+
await loadPlaywright(browsersPath);
|
|
1295
|
+
const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
|
|
1296
|
+
const registry = (mod.registry ?? mod.default?.registry)?.registry;
|
|
1297
|
+
if (registry === void 0) throw new Error("playwright-core has no browser registry");
|
|
1298
|
+
const exe = registry.findExecutable("chromium-headless-shell");
|
|
1299
|
+
if (exe === void 0) throw new Error("playwright-core does not know chromium-headless-shell");
|
|
1300
|
+
const path = exe.executablePath();
|
|
1301
|
+
if (path !== void 0 && existsSync(path)) return path;
|
|
1302
|
+
await registry.install([exe], { gc: false });
|
|
1303
|
+
const installed = exe.executablePath();
|
|
1304
|
+
if (installed === void 0 || !existsSync(installed)) {
|
|
1305
|
+
throw new Error("the Chromium download finished without an executable");
|
|
1306
|
+
}
|
|
1307
|
+
return installed;
|
|
1308
|
+
}
|
|
1309
|
+
async function launchChromium(plan) {
|
|
1310
|
+
const executablePath = await ensureChromium(plan.browsersPath);
|
|
1311
|
+
const pw = await loadPlaywright(plan.browsersPath);
|
|
1312
|
+
return pw.chromium.launchPersistentContext(plan.profileDir, {
|
|
1313
|
+
headless: true,
|
|
1314
|
+
executablePath,
|
|
1315
|
+
args: plan.args,
|
|
1316
|
+
viewport: { ...VIEWPORT },
|
|
1317
|
+
// downloads are saved into the workspace by the session (actions.ts)
|
|
1318
|
+
acceptDownloads: true,
|
|
1319
|
+
downloadsPath: plan.downloadsTmp,
|
|
1320
|
+
...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// daemon/session-file.ts
|
|
1325
|
+
import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
1326
|
+
import { join as join3 } from "node:path";
|
|
1327
|
+
var RESTORE_MAX_AGE_MS = 10 * 6e4;
|
|
1328
|
+
var SessionFile = class {
|
|
1329
|
+
file;
|
|
1330
|
+
clock;
|
|
1331
|
+
queued = false;
|
|
1332
|
+
forgotten = false;
|
|
1333
|
+
constructor(stateDir, clock) {
|
|
1334
|
+
this.file = join3(stateDir, "session.json");
|
|
1335
|
+
this.clock = clock;
|
|
1336
|
+
}
|
|
1337
|
+
/** The saved session when it is recent and well formed; undefined otherwise. */
|
|
1338
|
+
read() {
|
|
1339
|
+
let raw;
|
|
1340
|
+
try {
|
|
1341
|
+
raw = JSON.parse(readFileSync2(this.file, "utf8"));
|
|
1342
|
+
} catch {
|
|
1343
|
+
return void 0;
|
|
1344
|
+
}
|
|
1345
|
+
const s = raw;
|
|
1346
|
+
if (typeof s !== "object" || s === null || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs))
|
|
1347
|
+
return void 0;
|
|
1348
|
+
const tabs = s.tabs.filter(
|
|
1349
|
+
(u) => typeof u === "string" && /^https?:\/\//i.test(u)
|
|
1350
|
+
);
|
|
1351
|
+
const h = s.handoff;
|
|
1352
|
+
const handoff = typeof h === "object" && h !== null && typeof h.callId === "string" && h.callId !== "" && typeof h.message === "string" ? { callId: h.callId, message: h.message.slice(0, HANDOFF_MAX_CHARS) } : void 0;
|
|
1353
|
+
return {
|
|
1354
|
+
savedAt: s.savedAt,
|
|
1355
|
+
tabs: tabs.slice(0, MAX_TABS),
|
|
1356
|
+
active: typeof s.active === "number" ? s.active : 0,
|
|
1357
|
+
...handoff === void 0 ? {} : { handoff }
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Writes the session soon (coalesced): the tabs' URLs and the pending handoff, both read when
|
|
1362
|
+
* the write runs.
|
|
1363
|
+
*/
|
|
1364
|
+
save(session, handoffNow) {
|
|
1365
|
+
if (this.queued || this.forgotten) return;
|
|
1366
|
+
this.queued = true;
|
|
1367
|
+
queueMicrotask(() => {
|
|
1368
|
+
this.queued = false;
|
|
1369
|
+
if (this.forgotten) return;
|
|
1370
|
+
const handoff = handoffNow();
|
|
1371
|
+
const all = session.tabs();
|
|
1372
|
+
const kept = all.filter((t) => /^https?:\/\//i.test(t.url));
|
|
1373
|
+
const active = Math.max(
|
|
1374
|
+
0,
|
|
1375
|
+
kept.findIndex((t) => t.active)
|
|
1376
|
+
);
|
|
1377
|
+
const body = {
|
|
1378
|
+
savedAt: this.clock.now(),
|
|
1379
|
+
tabs: kept.map((t) => t.url),
|
|
1380
|
+
active,
|
|
1381
|
+
...handoff === void 0 ? {} : { handoff }
|
|
1382
|
+
};
|
|
1383
|
+
try {
|
|
1384
|
+
writeFileSync(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
|
|
1385
|
+
renameSync(`${this.file}.tmp`, this.file);
|
|
1386
|
+
} catch {
|
|
1387
|
+
}
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
/** Removes the file and stops saving (an idle stop). */
|
|
1391
|
+
forget() {
|
|
1392
|
+
this.forgotten = true;
|
|
1393
|
+
rmSync(this.file, { force: true });
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* Opens the saved tabs in a browser that has only its first blank tab. The navigations are
|
|
1397
|
+
* started, not awaited: the first request after a restart does not wait for every page to load.
|
|
1398
|
+
*/
|
|
1399
|
+
async restoreTabs(session, saved) {
|
|
1400
|
+
if (saved.tabs.length === 0) return;
|
|
1401
|
+
const ids = [];
|
|
1402
|
+
for (const [i, url] of saved.tabs.entries()) {
|
|
1403
|
+
try {
|
|
1404
|
+
const page = i === 0 ? await session.activePage() : await session.openTab();
|
|
1405
|
+
ids.push(session.tabIdOf(page));
|
|
1406
|
+
void session.viewerNav({ url: normalizeUrl(url) });
|
|
1407
|
+
} catch {
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
const active = ids[saved.active];
|
|
1411
|
+
if (active !== void 0) await session.switchTo(active).catch(() => void 0);
|
|
1412
|
+
}
|
|
1413
|
+
};
|
|
1414
|
+
|
|
1415
|
+
// daemon/viewer.ts
|
|
1416
|
+
var FRAME_JSON_OVERHEAD = 128;
|
|
1417
|
+
var START_QUALITY = 60;
|
|
1418
|
+
var MIN_QUALITY = 20;
|
|
1419
|
+
var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.max(16, Math.min(max, Math.floor(n))) : max;
|
|
1420
|
+
var ViewerSession = class {
|
|
1421
|
+
browser;
|
|
1422
|
+
state;
|
|
1423
|
+
out;
|
|
1424
|
+
clock;
|
|
1425
|
+
frameMaxBytes;
|
|
1426
|
+
unsubscribe = [];
|
|
1427
|
+
maxWidth = VIEWPORT.width;
|
|
1428
|
+
maxHeight = VIEWPORT.height;
|
|
1429
|
+
/** Lowered when a frame does not fit the message cap. */
|
|
1430
|
+
quality = START_QUALITY;
|
|
1431
|
+
shrink = 1;
|
|
1432
|
+
started = false;
|
|
1433
|
+
closed = false;
|
|
1434
|
+
page;
|
|
1435
|
+
cdp;
|
|
1436
|
+
/** Serializes attach / detach / restart. */
|
|
1437
|
+
chain = Promise.resolve();
|
|
1438
|
+
inputChain = Promise.resolve();
|
|
1439
|
+
/** Bumped on close and hand back: input queued before it is dropped, not replayed. */
|
|
1440
|
+
inputGen = 0;
|
|
1441
|
+
seq = 0;
|
|
1442
|
+
acked = 0;
|
|
1443
|
+
lastSentAt = 0;
|
|
1444
|
+
/** A screencast frame waiting for room (viewer acks, transport, rate cap); acked once sent. */
|
|
1445
|
+
pending;
|
|
1446
|
+
pumpTimer;
|
|
1447
|
+
draining = false;
|
|
1448
|
+
stateQueued = false;
|
|
1449
|
+
constructor(opts) {
|
|
1450
|
+
this.browser = opts.browser;
|
|
1451
|
+
this.state = opts.state;
|
|
1452
|
+
this.out = opts.transport;
|
|
1453
|
+
this.clock = opts.clock;
|
|
1454
|
+
this.frameMaxBytes = opts.frameMaxBytes;
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Handles one viewer message; the first must be `hello`. It returns at once: screencast work runs
|
|
1458
|
+
* on its own chain and input (mouse, keys, address bar, tabs) on another, in order, so a slow
|
|
1459
|
+
* navigation or screenshot never holds back a takeover, hand back or frame ack.
|
|
1460
|
+
*/
|
|
1461
|
+
handle(m) {
|
|
1462
|
+
if (this.closed) return;
|
|
1463
|
+
if (!this.started) {
|
|
1464
|
+
if (m.t !== "hello") return;
|
|
1465
|
+
this.started = true;
|
|
1466
|
+
this.setSize(m.maxWidth, m.maxHeight);
|
|
1467
|
+
this.unsubscribe.push(
|
|
1468
|
+
this.browser.on((e) => this.onSession(e)),
|
|
1469
|
+
this.state.onChange(() => this.queueState())
|
|
1470
|
+
);
|
|
1471
|
+
this.sendState();
|
|
1472
|
+
void this.serial(() => this.attach());
|
|
1473
|
+
return;
|
|
1474
|
+
}
|
|
1475
|
+
switch (m.t) {
|
|
1476
|
+
case "hello":
|
|
1477
|
+
case "resize":
|
|
1478
|
+
this.setSize(m.maxWidth, m.maxHeight);
|
|
1479
|
+
void this.serial(async () => {
|
|
1480
|
+
await this.detach();
|
|
1481
|
+
await this.attach();
|
|
1482
|
+
});
|
|
1483
|
+
return;
|
|
1484
|
+
case "frame-ack":
|
|
1485
|
+
if (typeof m.seq === "number" && m.seq > this.acked) this.acked = Math.min(m.seq, this.seq);
|
|
1486
|
+
this.pump();
|
|
1487
|
+
return;
|
|
1488
|
+
case "takeover":
|
|
1489
|
+
this.state.takeover();
|
|
1490
|
+
return;
|
|
1491
|
+
case "handback":
|
|
1492
|
+
this.inputGen++;
|
|
1493
|
+
this.state.handback();
|
|
1494
|
+
return;
|
|
1495
|
+
case "mouse":
|
|
1496
|
+
this.input(() => this.mouse(m));
|
|
1497
|
+
return;
|
|
1498
|
+
case "key":
|
|
1499
|
+
this.input(() => this.key(m));
|
|
1500
|
+
return;
|
|
1501
|
+
case "nav":
|
|
1502
|
+
this.input(
|
|
1503
|
+
() => this.browser.viewerNav({
|
|
1504
|
+
...typeof m.url === "string" ? { url: m.url } : {},
|
|
1505
|
+
...m.action === void 0 ? {} : { action: m.action }
|
|
1506
|
+
})
|
|
1507
|
+
);
|
|
1508
|
+
return;
|
|
1509
|
+
case "tab":
|
|
1510
|
+
this.input(async () => {
|
|
1511
|
+
try {
|
|
1512
|
+
if (m.action === "open") await this.browser.openTab();
|
|
1513
|
+
else if (m.action === "switch" && m.tabId !== void 0)
|
|
1514
|
+
await this.browser.switchTo(m.tabId);
|
|
1515
|
+
else if (m.action === "close" && m.tabId !== void 0) {
|
|
1516
|
+
await this.browser.tabById(m.tabId).close();
|
|
1517
|
+
await this.browser.activePage();
|
|
1518
|
+
}
|
|
1519
|
+
} catch {
|
|
1520
|
+
}
|
|
1521
|
+
});
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
/** Runs viewer input in arrival order, apart from the screencast chain. */
|
|
1526
|
+
input(fn) {
|
|
1527
|
+
const gen = this.inputGen;
|
|
1528
|
+
const guarded = () => gen === this.inputGen && !this.closed ? fn() : Promise.resolve();
|
|
1529
|
+
const run = this.inputChain.then(guarded, guarded);
|
|
1530
|
+
this.inputChain = run.catch(() => void 0);
|
|
1531
|
+
}
|
|
1532
|
+
/** Ends the viewer: stops its screencast and its subscriptions. */
|
|
1533
|
+
async close() {
|
|
1534
|
+
if (this.closed) return;
|
|
1535
|
+
this.closed = true;
|
|
1536
|
+
this.inputGen++;
|
|
1537
|
+
for (const u of this.unsubscribe.splice(0)) u();
|
|
1538
|
+
if (this.pumpTimer !== void 0) this.clock.cancel(this.pumpTimer);
|
|
1539
|
+
await this.serial(() => this.detach());
|
|
1540
|
+
}
|
|
1541
|
+
setSize(w, h) {
|
|
1542
|
+
this.maxWidth = clampDim(w, VIEWPORT.width);
|
|
1543
|
+
this.maxHeight = clampDim(h, VIEWPORT.height);
|
|
1544
|
+
this.shrink = 1;
|
|
1545
|
+
}
|
|
1546
|
+
serial(fn) {
|
|
1547
|
+
const run = this.chain.then(fn, fn);
|
|
1548
|
+
this.chain = run.catch(() => void 0);
|
|
1549
|
+
return run.catch(() => void 0);
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* A non-frame message cut to the per-message cap (BROWSER_FRAME_MAX_BYTES): long page text is
|
|
1553
|
+
* shortened, and a message that still does not fit is dropped (null). Frames are sized when
|
|
1554
|
+
* captured.
|
|
1555
|
+
*/
|
|
1556
|
+
fitted(m) {
|
|
1557
|
+
const fits = (x) => Buffer.byteLength(JSON.stringify(x)) <= this.frameMaxBytes;
|
|
1558
|
+
if (m.t === "frame" || fits(m)) return m;
|
|
1559
|
+
let small;
|
|
1560
|
+
if (m.t === "state") {
|
|
1561
|
+
const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
|
|
1562
|
+
small = {
|
|
1563
|
+
...m,
|
|
1564
|
+
tabs: m.tabs.map((t) => ({ ...t, title: clip(t.title, 200), url: clip(t.url, 200) })),
|
|
1565
|
+
...handoff
|
|
1566
|
+
};
|
|
1567
|
+
} else if (m.t === "dialog") {
|
|
1568
|
+
small = { ...m, message: clip(m.message, 200) };
|
|
1569
|
+
} else {
|
|
1570
|
+
small = { ...m, url: clip(m.url, 200) };
|
|
1571
|
+
}
|
|
1572
|
+
return fits(small) ? small : null;
|
|
1573
|
+
}
|
|
1574
|
+
send(raw) {
|
|
1575
|
+
if (this.closed) return;
|
|
1576
|
+
const m = this.fitted(raw);
|
|
1577
|
+
if (m === null) return;
|
|
1578
|
+
if (!this.out.send(m) && !this.draining) {
|
|
1579
|
+
this.draining = true;
|
|
1580
|
+
this.out.whenDrained().then(() => {
|
|
1581
|
+
this.draining = false;
|
|
1582
|
+
this.pump();
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
onSession(e) {
|
|
1587
|
+
if (e.type === "state") this.queueState();
|
|
1588
|
+
else if (e.type === "active") {
|
|
1589
|
+
this.queueState();
|
|
1590
|
+
void this.serial(async () => {
|
|
1591
|
+
const page = await this.browser.activePage();
|
|
1592
|
+
if (page === this.page) return;
|
|
1593
|
+
await this.detach();
|
|
1594
|
+
await this.attach();
|
|
1595
|
+
});
|
|
1596
|
+
} else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
|
|
1597
|
+
else this.send({ t: "dialog", kind: e.kind, message: e.message });
|
|
1598
|
+
}
|
|
1599
|
+
/** Coalesces bursts of changes into one state message. */
|
|
1600
|
+
queueState() {
|
|
1601
|
+
if (this.stateQueued) return;
|
|
1602
|
+
this.stateQueued = true;
|
|
1603
|
+
queueMicrotask(() => {
|
|
1604
|
+
this.stateQueued = false;
|
|
1605
|
+
this.sendState();
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
sendState() {
|
|
1609
|
+
const tabs = this.browser.tabs();
|
|
1610
|
+
const active = tabs.find((t) => t.active);
|
|
1611
|
+
const last = this.browser.lastClick;
|
|
1612
|
+
this.send({
|
|
1613
|
+
t: "state",
|
|
1614
|
+
tabs,
|
|
1615
|
+
loading: this.browser.loading,
|
|
1616
|
+
secure: active?.url.startsWith("https:") ?? false,
|
|
1617
|
+
control: this.state.control,
|
|
1618
|
+
...last === void 0 ? {} : { lastClick: last },
|
|
1619
|
+
...this.state.handoff === void 0 ? {} : { handoff: this.state.handoff }
|
|
1620
|
+
});
|
|
1621
|
+
}
|
|
1622
|
+
get scale() {
|
|
1623
|
+
return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.shrink;
|
|
1624
|
+
}
|
|
1625
|
+
/** Room for the JPEG's decoded bytes in one frame message. */
|
|
1626
|
+
get jpegBudget() {
|
|
1627
|
+
return Math.floor((this.frameMaxBytes - FRAME_JSON_OVERHEAD) * 3 / 4);
|
|
1628
|
+
}
|
|
1629
|
+
async attach() {
|
|
1630
|
+
if (this.closed) return;
|
|
1631
|
+
const page = await this.browser.activePage();
|
|
1632
|
+
const cdp = await this.browser.context.newCDPSession(page);
|
|
1633
|
+
this.page = page;
|
|
1634
|
+
this.cdp = cdp;
|
|
1635
|
+
cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
|
|
1636
|
+
const first = await captureFitting(cdp, {
|
|
1637
|
+
maxBytes: this.jpegBudget,
|
|
1638
|
+
maxScale: this.scale
|
|
1639
|
+
}).catch(() => null);
|
|
1640
|
+
if (first !== null && this.cdp === cdp) {
|
|
1641
|
+
this.sendFrame(first.data, first.width, first.height);
|
|
1642
|
+
}
|
|
1643
|
+
await this.startScreencast(cdp);
|
|
1644
|
+
}
|
|
1645
|
+
async startScreencast(cdp) {
|
|
1646
|
+
if (this.closed || this.cdp !== cdp) return;
|
|
1647
|
+
await cdp.send("Page.startScreencast", {
|
|
1648
|
+
format: "jpeg",
|
|
1649
|
+
quality: this.quality,
|
|
1650
|
+
maxWidth: Math.max(16, Math.floor(VIEWPORT.width * this.scale)),
|
|
1651
|
+
maxHeight: Math.max(16, Math.floor(VIEWPORT.height * this.scale)),
|
|
1652
|
+
everyNthFrame: 1
|
|
1653
|
+
});
|
|
1654
|
+
}
|
|
1655
|
+
async detach() {
|
|
1656
|
+
const cdp = this.cdp;
|
|
1657
|
+
this.cdp = void 0;
|
|
1658
|
+
this.page = void 0;
|
|
1659
|
+
this.pending = void 0;
|
|
1660
|
+
if (cdp === void 0) return;
|
|
1661
|
+
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
1662
|
+
await cdp.detach().catch(() => void 0);
|
|
1663
|
+
}
|
|
1664
|
+
sendFrame(jpeg, width, height) {
|
|
1665
|
+
this.seq++;
|
|
1666
|
+
this.lastSentAt = this.clock.now();
|
|
1667
|
+
this.send({ t: "frame", seq: this.seq, jpeg, width, height });
|
|
1668
|
+
}
|
|
1669
|
+
onFrame(cdp, f) {
|
|
1670
|
+
if (this.closed || this.cdp !== cdp) return;
|
|
1671
|
+
const bytes = Buffer.from(f.data, "base64");
|
|
1672
|
+
if (bytes.length > this.jpegBudget) {
|
|
1673
|
+
cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => void 0);
|
|
1674
|
+
if (this.quality > MIN_QUALITY) this.quality = Math.max(MIN_QUALITY, this.quality - 15);
|
|
1675
|
+
else this.shrink *= 0.75;
|
|
1676
|
+
void this.serial(async () => {
|
|
1677
|
+
if (this.cdp !== cdp) return;
|
|
1678
|
+
await cdp.send("Page.stopScreencast").catch(() => void 0);
|
|
1679
|
+
await this.startScreencast(cdp);
|
|
1680
|
+
});
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
const { width, height } = jpegSize(bytes);
|
|
1684
|
+
this.pending = { cdp, sessionId: f.sessionId, data: f.data, width, height };
|
|
1685
|
+
this.pump();
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Sends the held screencast frame and acks it (letting Chromium send the next) once the viewer
|
|
1689
|
+
* has room for it, the transport is not backed up and the rate cap allows: a frame never follows
|
|
1690
|
+
* the previous one sooner than 1000 / VIEWER_MAX_FPS ms, the first after an attach included.
|
|
1691
|
+
*/
|
|
1692
|
+
pump() {
|
|
1693
|
+
const pending = this.pending;
|
|
1694
|
+
if (pending === void 0 || this.closed || this.draining) return;
|
|
1695
|
+
if (this.seq - this.acked >= VIEWER_UNACKED_FRAMES) return;
|
|
1696
|
+
const wait = this.lastSentAt + 1e3 / VIEWER_MAX_FPS - this.clock.now();
|
|
1697
|
+
if (wait > 0) {
|
|
1698
|
+
if (this.pumpTimer === void 0) {
|
|
1699
|
+
this.pumpTimer = this.clock.schedule(() => {
|
|
1700
|
+
this.pumpTimer = void 0;
|
|
1701
|
+
this.pump();
|
|
1702
|
+
}, wait);
|
|
1703
|
+
}
|
|
1704
|
+
return;
|
|
1705
|
+
}
|
|
1706
|
+
this.pending = void 0;
|
|
1707
|
+
if (this.cdp !== pending.cdp) return;
|
|
1708
|
+
this.sendFrame(pending.data, pending.width, pending.height);
|
|
1709
|
+
pending.cdp.send("Page.screencastFrameAck", { sessionId: pending.sessionId }).catch(() => void 0);
|
|
1710
|
+
}
|
|
1711
|
+
async mouse(m) {
|
|
1712
|
+
const page = await this.browser.activePage();
|
|
1713
|
+
if (!Number.isFinite(Number(m.x)) || !Number.isFinite(Number(m.y))) return;
|
|
1714
|
+
const x = Math.max(0, Math.min(VIEWPORT.width - 1, Number(m.x)));
|
|
1715
|
+
const y = Math.max(0, Math.min(VIEWPORT.height - 1, Number(m.y)));
|
|
1716
|
+
const button = m.button === "right" ? "right" : "left";
|
|
1717
|
+
try {
|
|
1718
|
+
if (m.kind === "move") await page.mouse.move(x, y);
|
|
1719
|
+
else if (m.kind === "down") {
|
|
1720
|
+
await page.mouse.move(x, y);
|
|
1721
|
+
await page.mouse.down({ button });
|
|
1722
|
+
} else if (m.kind === "up") {
|
|
1723
|
+
await page.mouse.move(x, y);
|
|
1724
|
+
await page.mouse.up({ button });
|
|
1725
|
+
} else if (m.kind === "wheel") {
|
|
1726
|
+
await page.mouse.move(x, y);
|
|
1727
|
+
await page.mouse.wheel(Number(m.dx) || 0, Number(m.dy) || 0);
|
|
1728
|
+
}
|
|
1729
|
+
} catch {
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
async key(m) {
|
|
1733
|
+
const page = await this.browser.activePage();
|
|
1734
|
+
try {
|
|
1735
|
+
if (m.kind === "char") {
|
|
1736
|
+
const text = m.text ?? m.key;
|
|
1737
|
+
if (typeof text === "string" && text !== "") await page.keyboard.insertText(text);
|
|
1738
|
+
} else if (m.kind === "down") await page.keyboard.down(m.key);
|
|
1739
|
+
else if (m.kind === "up") await page.keyboard.up(m.key);
|
|
1740
|
+
} catch {
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
};
|
|
1744
|
+
|
|
1745
|
+
// daemon/main.ts
|
|
1746
|
+
var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
|
|
1747
|
+
var enc = new TextEncoder();
|
|
1748
|
+
var dec = new TextDecoder();
|
|
1749
|
+
var REQUEST_OPS = /* @__PURE__ */ new Set([
|
|
1750
|
+
"handoff_notice",
|
|
1751
|
+
"handoff_clear",
|
|
1752
|
+
"navigate",
|
|
1753
|
+
"tabs",
|
|
1754
|
+
"snapshot",
|
|
1755
|
+
"click",
|
|
1756
|
+
"hover",
|
|
1757
|
+
"type",
|
|
1758
|
+
"select",
|
|
1759
|
+
"press",
|
|
1760
|
+
"scroll",
|
|
1761
|
+
"upload",
|
|
1762
|
+
"click_at",
|
|
1763
|
+
"type_at",
|
|
1764
|
+
"wait",
|
|
1765
|
+
"screenshot"
|
|
1766
|
+
]);
|
|
1767
|
+
function downloadMaxBytes(env) {
|
|
1768
|
+
const raw = env.BROWSER_DOWNLOAD_MAX_BYTES;
|
|
1769
|
+
const n = raw === void 0 ? Number.NaN : Number(raw);
|
|
1770
|
+
return Number.isInteger(n) && n > 0 ? n : DEFAULT_DOWNLOAD_MAX_BYTES;
|
|
1771
|
+
}
|
|
1772
|
+
function frameMaxBytes(env) {
|
|
1773
|
+
const raw = env.BROWSER_FRAME_MAX_BYTES;
|
|
1774
|
+
const n = raw === void 0 ? Number.NaN : Number(raw);
|
|
1775
|
+
return Number.isInteger(n) && n >= 4096 ? Math.min(n, 4 * 1024 * 1024) : DEFAULT_FRAME_MAX_BYTES;
|
|
1776
|
+
}
|
|
1777
|
+
function parse(raw) {
|
|
1778
|
+
try {
|
|
1779
|
+
return JSON.parse(dec.decode(raw));
|
|
1780
|
+
} catch {
|
|
1781
|
+
return void 0;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
function write(sock, value, tooLarge) {
|
|
1785
|
+
if (sock.destroyed) return false;
|
|
1786
|
+
let framed;
|
|
1787
|
+
try {
|
|
1788
|
+
framed = encodeServiceMessage(enc.encode(JSON.stringify(value)));
|
|
1789
|
+
} catch (e) {
|
|
1790
|
+
if (!(e instanceof RangeError)) throw e;
|
|
1791
|
+
tooLarge?.();
|
|
1792
|
+
return false;
|
|
1793
|
+
}
|
|
1794
|
+
return sock.write(framed);
|
|
1795
|
+
}
|
|
1796
|
+
var fail = (message) => ({
|
|
1797
|
+
ok: false,
|
|
1798
|
+
error: "failed",
|
|
1799
|
+
message,
|
|
1800
|
+
blockedHosts: []
|
|
1801
|
+
});
|
|
1802
|
+
async function startDaemon(opts) {
|
|
1803
|
+
const clock = opts.clock ?? systemClock;
|
|
1804
|
+
const frameCap = frameMaxBytes(opts.env);
|
|
1805
|
+
const plan = chromiumLaunchPlan({
|
|
1806
|
+
stateDir: opts.stateDir,
|
|
1807
|
+
env: opts.env,
|
|
1808
|
+
platform: opts.platform ?? process.platform,
|
|
1809
|
+
...opts.browsersPath === void 0 ? {} : { browsersPath: opts.browsersPath }
|
|
1810
|
+
});
|
|
1811
|
+
mkdirSync2(opts.stateDir, { recursive: true });
|
|
1812
|
+
let closing = false;
|
|
1813
|
+
const sessionFile = new SessionFile(opts.stateDir, clock);
|
|
1814
|
+
const saved = sessionFile.read();
|
|
1815
|
+
const state = new DaemonState({
|
|
1816
|
+
clock,
|
|
1817
|
+
...opts.idleMs === void 0 ? {} : { idleMs: opts.idleMs },
|
|
1818
|
+
onIdle: () => {
|
|
1819
|
+
sessionFile.forget();
|
|
1820
|
+
opts.onIdle?.();
|
|
1821
|
+
}
|
|
1822
|
+
});
|
|
1823
|
+
if (saved?.handoff !== void 0)
|
|
1824
|
+
state.noticeHandoff(saved.handoff.callId, saved.handoff.message);
|
|
1825
|
+
const launch = opts.launch ?? launchChromium;
|
|
1826
|
+
let current;
|
|
1827
|
+
let restored = false;
|
|
1828
|
+
function browser() {
|
|
1829
|
+
if (current !== void 0) return current;
|
|
1830
|
+
const starting = launch(plan).then(async (ctx) => {
|
|
1831
|
+
ctx.on("close", () => {
|
|
1832
|
+
if (!closing) opts.onBrowserGone?.();
|
|
1833
|
+
});
|
|
1834
|
+
const workspace = opts.env[SERVICE_WORKSPACE_ENV];
|
|
1835
|
+
const session = new BrowserSession(ctx, {
|
|
1836
|
+
proxy: plan.proxy,
|
|
1837
|
+
clock,
|
|
1838
|
+
workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
|
|
1839
|
+
downloadsTmp: plan.downloadsTmp,
|
|
1840
|
+
downloadMaxBytes: downloadMaxBytes(opts.env),
|
|
1841
|
+
...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
|
|
1842
|
+
});
|
|
1843
|
+
if (!restored) {
|
|
1844
|
+
restored = true;
|
|
1845
|
+
if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
|
|
1846
|
+
}
|
|
1847
|
+
const save = () => sessionFile.save(session, () => state.handoff);
|
|
1848
|
+
session.on(save);
|
|
1849
|
+
state.onChange(save);
|
|
1850
|
+
return session;
|
|
1851
|
+
});
|
|
1852
|
+
current = starting;
|
|
1853
|
+
starting.catch(() => {
|
|
1854
|
+
if (current === starting) current = void 0;
|
|
1855
|
+
});
|
|
1856
|
+
return starting;
|
|
1857
|
+
}
|
|
1858
|
+
async function launchFailure(e) {
|
|
1859
|
+
const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
|
|
1860
|
+
const proxy = plan.proxy;
|
|
1861
|
+
const refused = proxy === void 0 ? [] : (await Promise.all(
|
|
1862
|
+
playwrightDownloadHosts(opts.env).map(
|
|
1863
|
+
async (h) => await proxyRefuses(proxy, h, 443) ? h : void 0
|
|
1864
|
+
)
|
|
1865
|
+
)).filter((h) => h !== void 0);
|
|
1866
|
+
if (refused.length > 0)
|
|
1867
|
+
return {
|
|
1868
|
+
ok: false,
|
|
1869
|
+
error: "blocked",
|
|
1870
|
+
message: `${DOWNLOAD_BLOCKED_PREFIX}${refused.join(", ")}.`,
|
|
1871
|
+
blockedHosts: refused
|
|
1872
|
+
};
|
|
1873
|
+
return fail(
|
|
1874
|
+
`The browser could not start in the device: ${cause}. The next browser call tries again.`
|
|
1875
|
+
);
|
|
1876
|
+
}
|
|
1877
|
+
const ready = browser().then(() => void 0);
|
|
1878
|
+
ready.catch(() => void 0);
|
|
1879
|
+
async function handoffOp(req) {
|
|
1880
|
+
if (typeof req.callId !== "string" || req.callId === "")
|
|
1881
|
+
return fail("The handoff needs a callId.");
|
|
1882
|
+
if (req.op === "handoff_notice") {
|
|
1883
|
+
if (typeof req.message !== "string") return fail("The handoff notice needs a message.");
|
|
1884
|
+
state.noticeHandoff(req.callId, req.message);
|
|
1885
|
+
} else {
|
|
1886
|
+
state.clearHandoff(req.callId);
|
|
1887
|
+
if (req.handback === true) state.handback();
|
|
1888
|
+
}
|
|
1889
|
+
let session;
|
|
1890
|
+
try {
|
|
1891
|
+
session = await browser();
|
|
1892
|
+
} catch (e) {
|
|
1893
|
+
return launchFailure(e);
|
|
1894
|
+
}
|
|
1895
|
+
return { ok: true, page: await session.pageInfo(await session.activePage()), blockedHosts: [] };
|
|
1896
|
+
}
|
|
1897
|
+
async function handleRequest(raw) {
|
|
1898
|
+
if (typeof raw !== "object" || raw === null || !REQUEST_OPS.has(String(raw.op))) {
|
|
1899
|
+
return fail("Unknown browser request.");
|
|
1900
|
+
}
|
|
1901
|
+
const req = raw;
|
|
1902
|
+
if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
|
|
1903
|
+
state.dropHandoff();
|
|
1904
|
+
if (state.control === "user" && req.op !== "wait") {
|
|
1905
|
+
return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
|
|
1906
|
+
}
|
|
1907
|
+
let session;
|
|
1908
|
+
try {
|
|
1909
|
+
session = await browser();
|
|
1910
|
+
} catch (e) {
|
|
1911
|
+
return launchFailure(e);
|
|
1912
|
+
}
|
|
1913
|
+
const reply = await session.run(req, { takenOver: () => state.control === "user" });
|
|
1914
|
+
if (reply.ok) {
|
|
1915
|
+
const since = state.takeHandbackNote();
|
|
1916
|
+
if (since !== void 0) reply.userControlledSince = since;
|
|
1917
|
+
}
|
|
1918
|
+
return reply;
|
|
1919
|
+
}
|
|
1920
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
1921
|
+
function onConnection(sock) {
|
|
1922
|
+
sockets.add(sock);
|
|
1923
|
+
const decoder = new ServiceMessageDecoder();
|
|
1924
|
+
let kind;
|
|
1925
|
+
let handled = false;
|
|
1926
|
+
let viewer;
|
|
1927
|
+
let opened = false;
|
|
1928
|
+
let viewerChain = Promise.resolve();
|
|
1929
|
+
const end = () => {
|
|
1930
|
+
sockets.delete(sock);
|
|
1931
|
+
if (viewer !== void 0) {
|
|
1932
|
+
const v = viewer;
|
|
1933
|
+
viewer = void 0;
|
|
1934
|
+
void v.close();
|
|
1935
|
+
}
|
|
1936
|
+
if (opened) {
|
|
1937
|
+
opened = false;
|
|
1938
|
+
state.viewerClosed();
|
|
1939
|
+
}
|
|
1940
|
+
};
|
|
1941
|
+
sock.on("close", end);
|
|
1942
|
+
sock.on("error", () => sock.destroy());
|
|
1943
|
+
const onMessage = (raw) => {
|
|
1944
|
+
if (kind === void 0) {
|
|
1945
|
+
const first = parse(raw);
|
|
1946
|
+
if (first?.kind === "request") kind = "request";
|
|
1947
|
+
else if (first?.kind === "stream") {
|
|
1948
|
+
kind = "stream";
|
|
1949
|
+
opened = true;
|
|
1950
|
+
state.viewerOpened();
|
|
1951
|
+
browser().then(
|
|
1952
|
+
(session) => {
|
|
1953
|
+
if (sock.destroyed) return;
|
|
1954
|
+
viewer = new ViewerSession({
|
|
1955
|
+
browser: session,
|
|
1956
|
+
state,
|
|
1957
|
+
clock,
|
|
1958
|
+
frameMaxBytes: frameCap,
|
|
1959
|
+
transport: {
|
|
1960
|
+
send: (m) => {
|
|
1961
|
+
let dropped = false;
|
|
1962
|
+
const ok = write(sock, m, () => {
|
|
1963
|
+
dropped = true;
|
|
1964
|
+
});
|
|
1965
|
+
return ok || dropped || sock.destroyed;
|
|
1966
|
+
},
|
|
1967
|
+
whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
|
|
1968
|
+
}
|
|
1969
|
+
});
|
|
1970
|
+
},
|
|
1971
|
+
() => sock.destroy()
|
|
1972
|
+
);
|
|
1973
|
+
} else sock.destroy();
|
|
1974
|
+
return;
|
|
1975
|
+
}
|
|
1976
|
+
if (kind === "request") {
|
|
1977
|
+
if (handled) return;
|
|
1978
|
+
handled = true;
|
|
1979
|
+
state.requestStarted();
|
|
1980
|
+
handleRequest(parse(raw)).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
|
|
1981
|
+
write(sock, reply, () => write(sock, fail(REPLY_TOO_LARGE_MESSAGE), () => void 0));
|
|
1982
|
+
sock.end();
|
|
1983
|
+
}).catch(() => sock.destroy()).finally(() => state.requestEnded());
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
const msg = parse(raw);
|
|
1987
|
+
if (msg === void 0 || typeof msg !== "object" || typeof msg.t !== "string") return;
|
|
1988
|
+
viewerChain = viewerChain.then(() => current).then(() => viewer?.handle(msg)).catch(() => void 0);
|
|
1989
|
+
};
|
|
1990
|
+
sock.on("data", (chunk) => {
|
|
1991
|
+
let msgs;
|
|
1992
|
+
try {
|
|
1993
|
+
msgs = decoder.push(chunk);
|
|
1994
|
+
} catch {
|
|
1995
|
+
sock.destroy();
|
|
1996
|
+
return;
|
|
1997
|
+
}
|
|
1998
|
+
for (const m of msgs) onMessage(m);
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
if (existsSync2(opts.socketPath)) unlinkSync(opts.socketPath);
|
|
2002
|
+
const server = createServer(onConnection);
|
|
2003
|
+
await new Promise((resolve, reject) => {
|
|
2004
|
+
server.once("error", reject);
|
|
2005
|
+
server.listen(opts.socketPath, () => {
|
|
2006
|
+
server.off("error", reject);
|
|
2007
|
+
resolve();
|
|
2008
|
+
});
|
|
2009
|
+
});
|
|
2010
|
+
chmodSync(opts.socketPath, 384);
|
|
2011
|
+
return {
|
|
2012
|
+
ready,
|
|
2013
|
+
state,
|
|
2014
|
+
async close() {
|
|
2015
|
+
if (closing) return;
|
|
2016
|
+
closing = true;
|
|
2017
|
+
state.dispose();
|
|
2018
|
+
await new Promise((r) => {
|
|
2019
|
+
server.close(() => r());
|
|
2020
|
+
for (const s of sockets) s.destroy();
|
|
2021
|
+
});
|
|
2022
|
+
const session = await current?.catch(() => void 0);
|
|
2023
|
+
await session?.close();
|
|
2024
|
+
if (existsSync2(opts.socketPath)) {
|
|
2025
|
+
try {
|
|
2026
|
+
unlinkSync(opts.socketPath);
|
|
2027
|
+
} catch {
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
// daemon/cli.ts
|
|
2035
|
+
async function main() {
|
|
2036
|
+
const socketPath = process.env[DEVICE_SERVICE_SOCKET_ENV];
|
|
2037
|
+
const stateDir = process.env[DEVICE_SERVICE_STATE_ENV];
|
|
2038
|
+
if (!socketPath || !stateDir) {
|
|
2039
|
+
process.stderr.write(
|
|
2040
|
+
`browser daemon: ${DEVICE_SERVICE_SOCKET_ENV} and ${DEVICE_SERVICE_STATE_ENV} must be set
|
|
2041
|
+
`
|
|
2042
|
+
);
|
|
2043
|
+
process.exit(2);
|
|
2044
|
+
}
|
|
2045
|
+
let daemon;
|
|
2046
|
+
let stopping = false;
|
|
2047
|
+
const stop = (code, why) => {
|
|
2048
|
+
if (stopping) return;
|
|
2049
|
+
stopping = true;
|
|
2050
|
+
process.stderr.write(`browser daemon: stopping (${why})
|
|
2051
|
+
`);
|
|
2052
|
+
const done = daemon?.close() ?? Promise.resolve();
|
|
2053
|
+
done.finally(() => process.exit(code));
|
|
2054
|
+
};
|
|
2055
|
+
process.on("SIGTERM", () => stop(0, "SIGTERM"));
|
|
2056
|
+
process.on("SIGINT", () => stop(0, "SIGINT"));
|
|
2057
|
+
daemon = await startDaemon({
|
|
2058
|
+
socketPath,
|
|
2059
|
+
stateDir,
|
|
2060
|
+
env: process.env,
|
|
2061
|
+
onIdle: () => stop(0, "idle"),
|
|
2062
|
+
onBrowserGone: () => stop(1, "Chromium exited")
|
|
2063
|
+
});
|
|
2064
|
+
process.stderr.write(`browser daemon: listening on ${socketPath}
|
|
2065
|
+
`);
|
|
2066
|
+
daemon.ready.then(
|
|
2067
|
+
() => process.stderr.write("browser daemon: Chromium is running\n"),
|
|
2068
|
+
// the daemon stays up: every request answers the cause and launches Chromium again
|
|
2069
|
+
(e) => {
|
|
2070
|
+
process.stderr.write(
|
|
2071
|
+
`browser daemon: Chromium could not start (retried on use): ${String(e)}
|
|
2072
|
+
`
|
|
2073
|
+
);
|
|
2074
|
+
}
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
await main();
|