@monoes/monobrowse 1.0.26 → 1.0.27
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/dist/src/browser/actions-eval.d.ts +8 -0
- package/dist/src/browser/actions-eval.d.ts.map +1 -0
- package/dist/src/browser/actions-eval.js +72 -0
- package/dist/src/browser/actions-eval.js.map +1 -0
- package/dist/src/browser/actions-form.d.ts +10 -0
- package/dist/src/browser/actions-form.d.ts.map +1 -0
- package/dist/src/browser/actions-form.js +133 -0
- package/dist/src/browser/actions-form.js.map +1 -0
- package/dist/src/browser/actions-keyboard.d.ts +7 -0
- package/dist/src/browser/actions-keyboard.d.ts.map +1 -0
- package/dist/src/browser/actions-keyboard.js +131 -0
- package/dist/src/browser/actions-keyboard.js.map +1 -0
- package/dist/src/browser/actions-mouse.d.ts +11 -0
- package/dist/src/browser/actions-mouse.d.ts.map +1 -0
- package/dist/src/browser/actions-mouse.js +105 -0
- package/dist/src/browser/actions-mouse.js.map +1 -0
- package/dist/src/browser/actions.d.ts +12 -28
- package/dist/src/browser/actions.d.ts.map +1 -1
- package/dist/src/browser/actions.js +12 -434
- package/dist/src/browser/actions.js.map +1 -1
- package/dist/src/browser/browser-discovery.d.ts +26 -0
- package/dist/src/browser/browser-discovery.d.ts.map +1 -0
- package/dist/src/browser/browser-discovery.js +113 -0
- package/dist/src/browser/browser-discovery.js.map +1 -0
- package/dist/src/browser/browser-launch.d.ts +3 -0
- package/dist/src/browser/browser-launch.d.ts.map +1 -0
- package/dist/src/browser/browser-launch.js +324 -0
- package/dist/src/browser/browser-launch.js.map +1 -0
- package/dist/src/browser/browser-lifecycle.d.ts +52 -0
- package/dist/src/browser/browser-lifecycle.d.ts.map +1 -0
- package/dist/src/browser/browser-lifecycle.js +233 -0
- package/dist/src/browser/browser-lifecycle.js.map +1 -0
- package/dist/src/browser/browser-page.d.ts +13 -0
- package/dist/src/browser/browser-page.d.ts.map +1 -0
- package/dist/src/browser/browser-page.js +179 -0
- package/dist/src/browser/browser-page.js.map +1 -0
- package/dist/src/browser/browser-state.d.ts +7 -0
- package/dist/src/browser/browser-state.d.ts.map +1 -0
- package/dist/src/browser/browser-state.js +19 -0
- package/dist/src/browser/browser-state.js.map +1 -0
- package/dist/src/browser/browser.d.ts +5 -68
- package/dist/src/browser/browser.d.ts.map +1 -1
- package/dist/src/browser/browser.js +9 -849
- package/dist/src/browser/browser.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/browser/actions-eval.ts +118 -0
- package/src/browser/actions-form.ts +218 -0
- package/src/browser/actions-keyboard.ts +171 -0
- package/src/browser/actions-mouse.ts +212 -0
- package/src/browser/actions.ts +37 -712
- package/src/browser/browser-discovery.ts +116 -0
- package/src/browser/browser-launch.ts +358 -0
- package/src/browser/browser-lifecycle.ts +238 -0
- package/src/browser/browser-page.ts +213 -0
- package/src/browser/browser-state.ts +21 -0
- package/src/browser/browser.ts +17 -917
package/src/browser/browser.ts
CHANGED
|
@@ -1,917 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const DEFAULT_PORT = 9222;
|
|
20
|
-
const LAUNCH_TIMEOUT = 10_000;
|
|
21
|
-
const POLL_INTERVAL = 200;
|
|
22
|
-
const BROWSER_CLOSE_TIMEOUT_MS = 3000;
|
|
23
|
-
// How long closeBrowser() waits for the process to actually disappear before
|
|
24
|
-
// forcing it, and again after forcing. Bounded so a wedged Chrome cannot hang
|
|
25
|
-
// a caller indefinitely.
|
|
26
|
-
const PROCESS_EXIT_TIMEOUT_MS = 5000;
|
|
27
|
-
const PROCESS_EXIT_POLL_MS = 50;
|
|
28
|
-
// A cross-process persisted PID older than this is not trusted for the
|
|
29
|
-
// SIGKILL fallback in closeBrowser() — see the call site for why.
|
|
30
|
-
const PERSISTED_PID_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
31
|
-
// A browser WE launched that has had no targets for longer than this is
|
|
32
|
-
// reaped at the next launch/attach — see reapIdleLaunchedBrowser().
|
|
33
|
-
const IDLE_REAP_AFTER_MS = 30 * 60 * 1000;
|
|
34
|
-
const REAP_CONNECT_TIMEOUT_MS = 3000;
|
|
35
|
-
|
|
36
|
-
// Tracks the PID of Chrome instances *we* spawned, keyed by CDP port, so
|
|
37
|
-
// closeBrowser() has a kill fallback when the graceful `Browser.close` CDP
|
|
38
|
-
// command fails or times out (e.g. a hung renderer). Ports we merely attached
|
|
39
|
-
// to (already-running browser) are never recorded here — we only ever kill
|
|
40
|
-
// processes we launched ourselves.
|
|
41
|
-
const launchedPids = new Map<number, number>();
|
|
42
|
-
// userDataDir per launched port — informational, persisted alongside the pid
|
|
43
|
-
// so a later process could clean up the temp profile dir too if ever needed.
|
|
44
|
-
const launchedUserDataDirs = new Map<number, string>();
|
|
45
|
-
|
|
46
|
-
/** PID of the Chrome instance *this process* launched on `port`, if any. */
|
|
47
|
-
export function getLaunchedPid(port: number): number | undefined {
|
|
48
|
-
return launchedPids.get(port);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** userDataDir of the Chrome instance *this process* launched on `port`, if any. */
|
|
52
|
-
export function getLaunchedUserDataDir(port: number): string | undefined {
|
|
53
|
-
return launchedUserDataDirs.get(port);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function findChrome(executablePath?: string): string {
|
|
57
|
-
if (executablePath) {
|
|
58
|
-
if (existsSync(executablePath)) return executablePath;
|
|
59
|
-
throw new Error(`Chrome executable not found: ${executablePath}`);
|
|
60
|
-
}
|
|
61
|
-
for (const candidate of CHROME_EXECUTABLES) {
|
|
62
|
-
if (existsSync(candidate)) return candidate;
|
|
63
|
-
}
|
|
64
|
-
// Try PATH
|
|
65
|
-
try {
|
|
66
|
-
const result = execSync(
|
|
67
|
-
'which google-chrome chromium-browser chromium microsoft-edge microsoft-edge-stable 2>/dev/null',
|
|
68
|
-
{ encoding: 'utf8' },
|
|
69
|
-
).trim();
|
|
70
|
-
const first = result.split('\n')[0];
|
|
71
|
-
if (first) return first;
|
|
72
|
-
} catch {
|
|
73
|
-
// ignore
|
|
74
|
-
}
|
|
75
|
-
throw new Error(
|
|
76
|
-
'No supported browser found. Install Google Chrome, Microsoft Edge, or Chromium — or pass executablePath in BrowserConfig.',
|
|
77
|
-
);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export async function isPortOpen(port: number): Promise<boolean> {
|
|
81
|
-
try {
|
|
82
|
-
await fetchTargets(port);
|
|
83
|
-
return true;
|
|
84
|
-
} catch {
|
|
85
|
-
return false;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Confirm the CDP endpoint on `port` actually identifies as Chrome/Chromium
|
|
91
|
-
* via `/json/version`'s `Browser` field, rather than assuming any CDP-speaking
|
|
92
|
-
* responder is "ours". Reduces (does not eliminate) the risk of silently
|
|
93
|
-
* attaching to an unrelated real browser that happens to be listening there.
|
|
94
|
-
*/
|
|
95
|
-
async function isChromeIdentity(port: number): Promise<boolean> {
|
|
96
|
-
return (await chromeIdentity(port)) === 'chrome';
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** isChromeIdentity, telling "answered as something else" apart from "did
|
|
100
|
-
* not answer in time" ('unknown': a timeout, a refused or reset connection,
|
|
101
|
-
* a non-OK status or an unparseable body). */
|
|
102
|
-
async function chromeIdentity(port: number): Promise<'chrome' | 'other' | 'unknown'> {
|
|
103
|
-
try {
|
|
104
|
-
const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
|
|
105
|
-
signal: AbortSignal.timeout(1000),
|
|
106
|
-
});
|
|
107
|
-
if (!res.ok) return 'unknown';
|
|
108
|
-
const info = (await res.json()) as { Browser?: string };
|
|
109
|
-
// Edge's Browser field is "Edg/<version>" with no "chrome"/"chromium"
|
|
110
|
-
// substring, even though it's Chromium-based and CDP-compatible —
|
|
111
|
-
// accept it alongside Chrome/Chromium rather than rejecting a valid target.
|
|
112
|
-
return typeof info.Browser === 'string' && /chrom(e|ium)|edg/i.test(info.Browser)
|
|
113
|
-
? 'chrome'
|
|
114
|
-
: 'other';
|
|
115
|
-
} catch {
|
|
116
|
-
return 'unknown';
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/** Raw TCP connect probe — distinguishes "nothing listening" from "something listening that isn't CDP". */
|
|
121
|
-
function isTcpPortOpen(port: number, timeoutMs = 1000): Promise<boolean> {
|
|
122
|
-
return new Promise((resolve) => {
|
|
123
|
-
const socket = connect({ host: '127.0.0.1', port, timeout: timeoutMs });
|
|
124
|
-
const done = (result: boolean) => {
|
|
125
|
-
socket.removeAllListeners();
|
|
126
|
-
socket.destroy();
|
|
127
|
-
resolve(result);
|
|
128
|
-
};
|
|
129
|
-
socket.once('connect', () => done(true));
|
|
130
|
-
socket.once('timeout', () => done(false));
|
|
131
|
-
socket.once('error', () => done(false));
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** Ports scanned when the requested one is occupied by a non-Chrome process
|
|
136
|
-
* (e.g. another local tool that happens to reuse Chrome's conventional CDP
|
|
137
|
-
* default, 9222 — mirrors the auto-increment convention this monorepo's own
|
|
138
|
-
* dashboard server uses in bindServer/server.mjs). Only occupied-by-a-
|
|
139
|
-
* DIFFERENT-process is worked around; an already-attachable Chrome on the
|
|
140
|
-
* requested port is still returned as-is (existing "attach, don't relaunch"
|
|
141
|
-
* behavior). */
|
|
142
|
-
const LAUNCH_PORT_SCAN_TRIES = 10;
|
|
143
|
-
|
|
144
|
-
export async function launchBrowser(config: BrowserConfig = {}): Promise<number> {
|
|
145
|
-
const rawPort = config.port ?? DEFAULT_PORT;
|
|
146
|
-
// Port 0 means "let Chrome bind a free port and tell us which" — see
|
|
147
|
-
// launchOnFreePort. Otherwise validate port is in a safe range for
|
|
148
|
-
// localhost CDP debugging.
|
|
149
|
-
if (rawPort === 0) {
|
|
150
|
-
if (!config.userDataDir) {
|
|
151
|
-
throw new Error(
|
|
152
|
-
'port 0 requires a dedicated userDataDir (Chrome reports the port it bound inside it).',
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
} else if (!Number.isInteger(rawPort) || rawPort < 1024 || rawPort > 65535) {
|
|
156
|
-
throw new Error(`Invalid port: ${rawPort}. Must be 0 or an integer between 1024 and 65535.`);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// Every launch/attach is this tool's only chance to notice that a previous
|
|
160
|
-
// session abandoned a browser on a CDP port and never gave it back — there
|
|
161
|
-
// is no daemon to do it on a timer. Bounded and non-throwing; a stale
|
|
162
|
-
// instance on the port we are about to use is freed before we probe it.
|
|
163
|
-
await reapIdleLaunchedBrowser();
|
|
164
|
-
|
|
165
|
-
if (rawPort === 0) return launchOnFreePort(config, 0);
|
|
166
|
-
|
|
167
|
-
// strictPort: fail fast on the exact requested port, matching the old
|
|
168
|
-
// behavior (Vite has the same escape hatch for the same reason) — for
|
|
169
|
-
// callers that treat the error as a signal ("this port is taken by
|
|
170
|
-
// something else, bail") rather than consuming the returned port.
|
|
171
|
-
if (config.strictPort) {
|
|
172
|
-
if (await isTcpPortOpen(rawPort)) {
|
|
173
|
-
if (await isChromeIdentity(rawPort)) return rawPort;
|
|
174
|
-
throw new Error(
|
|
175
|
-
`Port ${rawPort} is occupied by a process that does not identify as Chrome/Chromium. ` +
|
|
176
|
-
`Refusing to attach — pass a different port or free port ${rawPort}.`,
|
|
177
|
-
);
|
|
178
|
-
}
|
|
179
|
-
return launchOnFreePort(config, rawPort);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
const candidates: number[] = [];
|
|
183
|
-
for (let i = 0; i < LAUNCH_PORT_SCAN_TRIES && rawPort + i <= 65535; i++)
|
|
184
|
-
candidates.push(rawPort + i);
|
|
185
|
-
|
|
186
|
-
for (const candidate of candidates) {
|
|
187
|
-
// TCP-level check for "is anything at all listening" — isPortOpen()
|
|
188
|
-
// does a full CDP /json fetch, which returns false BOTH for a genuinely
|
|
189
|
-
// free port and for one occupied by a non-CDP process (that ambiguity is
|
|
190
|
-
// exactly what the post-spawn isTcpPortOpen fallback below exists to
|
|
191
|
-
// resolve, the hard way, after a 10s launch timeout). Checking the raw
|
|
192
|
-
// socket first tells free and occupied apart up front, so the scan can
|
|
193
|
-
// skip an occupied candidate instead of trying to spawn Chrome on top of
|
|
194
|
-
// it and only discovering the conflict after a timeout.
|
|
195
|
-
if (await isTcpPortOpen(candidate)) {
|
|
196
|
-
// Attach-if-already-Chrome only applies to the EXACT requested port —
|
|
197
|
-
// the original, deliberate, single-port risk ("don't silently take
|
|
198
|
-
// over an unrelated real browser that happens to be on this port").
|
|
199
|
-
// Scanning past an occupied default must not let that same shortcut
|
|
200
|
-
// attach to a DIFFERENT Chrome instance the caller never named;
|
|
201
|
-
// forward candidates are launch-only (skip if anything is there,
|
|
202
|
-
// Chrome or not).
|
|
203
|
-
if (candidate === rawPort && (await isChromeIdentity(candidate))) return candidate;
|
|
204
|
-
// Occupied (by anything — not just non-Chrome, per the note above) —
|
|
205
|
-
// try the next candidate instead of failing outright, same as a
|
|
206
|
-
// normal EADDRINUSE retry would.
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
try {
|
|
210
|
-
return await launchOnFreePort(config, candidate);
|
|
211
|
-
} catch (err) {
|
|
212
|
-
const isLastCandidate = candidate === candidates[candidates.length - 1];
|
|
213
|
-
// isTcpPortOpen() above is a connect() probe, not an atomic claim: two
|
|
214
|
-
// concurrent launchBrowser() calls with no explicit --port can both
|
|
215
|
-
// observe the same candidate as free and both spawn Chrome on it
|
|
216
|
-
// before either binds. One wins; the other's Chrome exits before its
|
|
217
|
-
// CDP endpoint opens ("Chrome exited before the CDP endpoint opened
|
|
218
|
-
// ... code=21"). Something is listening on the candidate NOW that
|
|
219
|
-
// was not a moment ago — a losing race, not a broken Chrome install —
|
|
220
|
-
// so try the next candidate exactly like an already-occupied one,
|
|
221
|
-
// instead of failing the whole launch outright. A candidate that
|
|
222
|
-
// fails with nothing now listening (a real launch failure — bad
|
|
223
|
-
// executable, sandbox refusal, etc.) is not a race: retrying the
|
|
224
|
-
// next candidate would only fail the same way, so surface it as-is.
|
|
225
|
-
if (!isLastCandidate && (await isTcpPortOpen(candidate))) continue;
|
|
226
|
-
throw err;
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
throw new Error(
|
|
230
|
-
`Ports ${candidates[0]}-${candidates[candidates.length - 1]} are all occupied and port ${candidates[0]} ` +
|
|
231
|
-
`isn't a Chrome/Chromium instance to attach to. Pass a different --port.`,
|
|
232
|
-
);
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/** The port Chrome wrote to `<userDataDir>/DevToolsActivePort` once its
|
|
236
|
-
* DevTools server was listening, or null if it has not (yet). */
|
|
237
|
-
function readDevToolsActivePort(file: string): number | null {
|
|
238
|
-
try {
|
|
239
|
-
const port = Number.parseInt(readFileSync(file, 'utf8').split('\n')[0], 10);
|
|
240
|
-
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
|
|
241
|
-
} catch {
|
|
242
|
-
return null;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
/**
|
|
247
|
-
* Spawn Chrome and wait for its CDP endpoint.
|
|
248
|
-
*
|
|
249
|
-
* With a fixed `port`, "our Chrome is up" is inferred from *some* Chrome
|
|
250
|
-
* answering on 127.0.0.1:<port> — which is not necessarily ours. When the port
|
|
251
|
-
* is already bound on 127.0.0.1 (a concurrent launch picked the same "free"
|
|
252
|
-
* port between its probe and Chrome's bind), Chrome does not fail: it logs
|
|
253
|
-
* `bind() failed: Address already in use` and listens on [::1]:<port>
|
|
254
|
-
* instead. The poll then accepts the OTHER launcher's browser, both callers
|
|
255
|
-
* drive one Chrome, and whichever closes first kills the other's connections
|
|
256
|
-
* ("CDP connection closed") while this launch's own Chrome is orphaned.
|
|
257
|
-
*
|
|
258
|
-
* `port: 0` removes the race instead of narrowing it: Chrome asks the kernel
|
|
259
|
-
* for a free port at bind time — atomic, nothing to collide on — and writes
|
|
260
|
-
* the port it got to DevToolsActivePort in its own (caller-dedicated) profile
|
|
261
|
-
* directory, which is proof the endpoint is the process we spawned.
|
|
262
|
-
*
|
|
263
|
-
* A fixed port needs its own proof, since Chrome writes DevToolsActivePort
|
|
264
|
-
* only for port 0. Once listening, Chrome prints `DevTools listening on
|
|
265
|
-
* ws://…/devtools/browser/<id>` to stderr, and `<id>` is unique to that
|
|
266
|
-
* browser process, the same one `/json/version` reports. An endpoint is
|
|
267
|
-
* adopted only when it reports the id our own child printed. Without that
|
|
268
|
-
* check, a launch whose Chrome was still booting found a concurrent
|
|
269
|
-
* launch's Chrome on the shared port and returned it, recording its own
|
|
270
|
-
* doomed pid there. It also covers Chrome's [::1] fallback described above.
|
|
271
|
-
*/
|
|
272
|
-
async function launchOnFreePort(config: BrowserConfig, port: number): Promise<number> {
|
|
273
|
-
const chromePath = findChrome(config.executablePath);
|
|
274
|
-
// Unique per launch, not just per port and pid: two concurrent launches
|
|
275
|
-
// that both probe the same candidate port as free (the race this function
|
|
276
|
-
// exists to survive — see the retry-on-collision caller above) would
|
|
277
|
-
// otherwise share one profile directory (lock files, preferences, the
|
|
278
|
-
// DevToolsActivePort file itself) — including two launches from the same
|
|
279
|
-
// process, where a pid suffix alone is identical.
|
|
280
|
-
const userDataDir =
|
|
281
|
-
config.userDataDir ??
|
|
282
|
-
join(tmpdir(), `monomind-browser-${port}-${process.pid}-${randomUUID().slice(0, 8)}`);
|
|
283
|
-
const activePortFile = join(userDataDir, 'DevToolsActivePort');
|
|
284
|
-
// A reused profile dir may hold a previous run's file naming a port some
|
|
285
|
-
// other process now owns.
|
|
286
|
-
if (port === 0) rmSync(activePortFile, { force: true });
|
|
287
|
-
|
|
288
|
-
const defaultArgs = [
|
|
289
|
-
`--remote-debugging-port=${port}`,
|
|
290
|
-
`--user-data-dir=${userDataDir}`,
|
|
291
|
-
'--no-first-run',
|
|
292
|
-
'--no-default-browser-check',
|
|
293
|
-
'--disable-background-networking',
|
|
294
|
-
'--disable-client-side-phishing-detection',
|
|
295
|
-
'--disable-default-apps',
|
|
296
|
-
'--disable-extensions',
|
|
297
|
-
'--disable-hang-monitor',
|
|
298
|
-
'--disable-popup-blocking',
|
|
299
|
-
'--disable-prompt-on-repost',
|
|
300
|
-
'--disable-sync',
|
|
301
|
-
'--disable-translate',
|
|
302
|
-
'--metrics-recording-only',
|
|
303
|
-
'--safebrowsing-disable-auto-update',
|
|
304
|
-
'--password-store=basic',
|
|
305
|
-
'--use-mock-keychain',
|
|
306
|
-
];
|
|
307
|
-
|
|
308
|
-
if (config.headless !== false) {
|
|
309
|
-
defaultArgs.push('--headless=new');
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// Chrome's setuid sandbox cannot initialise on most CI runners and
|
|
313
|
-
// containers, so the process dies during startup and the CDP endpoint never
|
|
314
|
-
// opens. The launch below then burns its whole timeout before reporting a
|
|
315
|
-
// generic failure, which reads as a hang rather than "Chrome could not
|
|
316
|
-
// start". Disabling the sandbox is the standard remedy and is scoped to CI
|
|
317
|
-
// so a real user's browser keeps it. --disable-dev-shm-usage goes with it:
|
|
318
|
-
// a container's default /dev/shm is 64MB, which Chrome exhausts and then
|
|
319
|
-
// crashes the same way.
|
|
320
|
-
if (process.env.CI) {
|
|
321
|
-
defaultArgs.push('--no-sandbox', '--disable-dev-shm-usage');
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// Cap caller-supplied args to prevent memory exhaustion via huge argument arrays
|
|
325
|
-
const callerArgs = (config.args ?? []).slice(0, 50);
|
|
326
|
-
const args = [...defaultArgs, ...callerArgs];
|
|
327
|
-
const child = spawn(chromePath, args, {
|
|
328
|
-
detached: true,
|
|
329
|
-
// stderr carries the fixed-port ownership proof (see above). The pipe is
|
|
330
|
-
// closed as soon as this launch settles, so a Chrome that outlives us
|
|
331
|
-
// never blocks writing to it.
|
|
332
|
-
stdio: port === 0 ? 'ignore' : ['ignore', 'ignore', 'pipe'],
|
|
333
|
-
});
|
|
334
|
-
let announcedBrowserId: string | null = null;
|
|
335
|
-
if (child.stderr) {
|
|
336
|
-
let stderrTail = '';
|
|
337
|
-
child.stderr.setEncoding('utf8');
|
|
338
|
-
child.stderr.on('data', (chunk: string) => {
|
|
339
|
-
if (announcedBrowserId) return;
|
|
340
|
-
stderrTail = (stderrTail + chunk).slice(-4096);
|
|
341
|
-
announcedBrowserId = browserIdOf(
|
|
342
|
-
/DevTools listening on (ws:\/\/\S+)\r?\n/.exec(stderrTail)?.[1],
|
|
343
|
-
);
|
|
344
|
-
});
|
|
345
|
-
child.stderr.on('error', () => {
|
|
346
|
-
/* closed under us — nothing to read */
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
// Without this, a spawn failure (e.g. EACCES/ENOENT — chromePath exists per
|
|
351
|
-
// findChrome()'s existsSync check but isn't actually executable, or is
|
|
352
|
-
// removed between the check and exec) fires Node's 'error' event on the
|
|
353
|
-
// next tick. With no listener, Node throws it as an uncaught exception and
|
|
354
|
-
// the whole process goes down — which strands this function's promise
|
|
355
|
-
// forever pending rather than rejecting it (issue #314: node:test reports
|
|
356
|
-
// that as "cancelledByParent" / "still pending" because nothing here ever
|
|
357
|
-
// got the chance to settle it). Recording the failure and having the poll
|
|
358
|
-
// loop below notice it turns that crash into a normal rejection. 'exit'
|
|
359
|
-
// covers the twin case: Chrome execs fine but the process itself dies
|
|
360
|
-
// immediately (missing shared libraries, a container's sandbox refusing
|
|
361
|
-
// it, etc.) — that fires 'exit', not 'error', and without this the poll
|
|
362
|
-
// loop would just burn its whole timeout probing a port nothing will ever
|
|
363
|
-
// open on.
|
|
364
|
-
let earlyFailure: Error | null = null;
|
|
365
|
-
child.on('error', (err) => {
|
|
366
|
-
earlyFailure ??= new Error(`Chrome failed to start on port ${port}: ${err.message}`);
|
|
367
|
-
});
|
|
368
|
-
child.on('exit', (code, signal) => {
|
|
369
|
-
earlyFailure ??= new Error(
|
|
370
|
-
`Chrome exited before the CDP endpoint opened on port ${port} ` +
|
|
371
|
-
`(code=${code ?? 'null'}, signal=${signal ?? 'null'})`,
|
|
372
|
-
);
|
|
373
|
-
});
|
|
374
|
-
|
|
375
|
-
child.unref();
|
|
376
|
-
const track = (boundPort: number) => {
|
|
377
|
-
if (!child.pid) return;
|
|
378
|
-
launchedPids.set(boundPort, child.pid);
|
|
379
|
-
launchedUserDataDirs.set(boundPort, userDataDir);
|
|
380
|
-
};
|
|
381
|
-
// Tracked only once Chrome is CONFIRMED up on `boundPort`, not right after
|
|
382
|
-
// spawn(). For port !== 0 this used to track(port) unconditionally the
|
|
383
|
-
// moment the child was spawned, before knowing whether it would actually
|
|
384
|
-
// win the port — when a racing launchBrowser() call retries a candidate
|
|
385
|
-
// that a concurrent process also spawned Chrome on (see the retry loop in
|
|
386
|
-
// launchBrowser), BOTH child processes called track() for the SAME
|
|
387
|
-
// candidate, and whichever call's spawn happened to run last clobbered the
|
|
388
|
-
// map entry with its own pid — including the LOSING, about-to-exit
|
|
389
|
-
// process's pid overwriting the real winner's, corrupting the very map
|
|
390
|
-
// closeBrowser()'s kill fallback depends on.
|
|
391
|
-
|
|
392
|
-
// A refused or timed-out launch is not tracked under any port, so no
|
|
393
|
-
// closeBrowser() could ever reach it — stop it rather than leave it
|
|
394
|
-
// running.
|
|
395
|
-
const killUntracked = () => {
|
|
396
|
-
try {
|
|
397
|
-
if (child.pid) process.kill(child.pid, 'SIGKILL');
|
|
398
|
-
} catch {
|
|
399
|
-
/* already gone */
|
|
400
|
-
}
|
|
401
|
-
};
|
|
402
|
-
|
|
403
|
-
// Our own Chrome, not just some Chrome, is serving `boundPort`. For port 0
|
|
404
|
-
// the port came from our own profile's DevToolsActivePort, so it is.
|
|
405
|
-
const isOwnEndpoint = async (boundPort: number): Promise<boolean> => {
|
|
406
|
-
if (port === 0) return true;
|
|
407
|
-
if (!announcedBrowserId) return false;
|
|
408
|
-
const wsUrl = await fetchBrowserWebSocketUrl(boundPort).catch(() => null);
|
|
409
|
-
return browserIdOf(wsUrl ?? undefined) === announcedBrowserId;
|
|
410
|
-
};
|
|
411
|
-
|
|
412
|
-
const launchTimeout = config.launchTimeoutMs ?? LAUNCH_TIMEOUT;
|
|
413
|
-
const deadline = Date.now() + launchTimeout;
|
|
414
|
-
try {
|
|
415
|
-
while (Date.now() < deadline) {
|
|
416
|
-
if (earlyFailure) throw earlyFailure;
|
|
417
|
-
await sleep(POLL_INTERVAL);
|
|
418
|
-
if (earlyFailure) throw earlyFailure;
|
|
419
|
-
const boundPort = port === 0 ? readDevToolsActivePort(activePortFile) : port;
|
|
420
|
-
if (boundPort !== null && (await isPortOpen(boundPort))) {
|
|
421
|
-
const identity = await chromeIdentity(boundPort);
|
|
422
|
-
if (identity === 'chrome') {
|
|
423
|
-
if (await isOwnEndpoint(boundPort)) {
|
|
424
|
-
track(boundPort);
|
|
425
|
-
return boundPort;
|
|
426
|
-
}
|
|
427
|
-
// Some Chrome answers on the port, but not the one we started: a
|
|
428
|
-
// concurrent launch's, or ours before its stderr line arrived. Our
|
|
429
|
-
// child exiting (it lost the bind) or the deadline decides.
|
|
430
|
-
continue;
|
|
431
|
-
}
|
|
432
|
-
// A Chrome that has only just opened its endpoint, on a loaded
|
|
433
|
-
// machine, can answer /json/list (no timeout) yet miss the identity
|
|
434
|
-
// check's 1 s timeout on /json/version. That says nothing about who is
|
|
435
|
-
// listening — keep polling rather than refuse our own Chrome.
|
|
436
|
-
if (identity === 'unknown') continue;
|
|
437
|
-
killUntracked();
|
|
438
|
-
throw new Error(
|
|
439
|
-
`Port ${boundPort} is occupied by a CDP-speaking process that does not identify as Chrome/Chromium. ` +
|
|
440
|
-
`Refusing to attach — pass a different port or free port ${boundPort}.`,
|
|
441
|
-
);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
if (earlyFailure) throw earlyFailure;
|
|
446
|
-
killUntracked();
|
|
447
|
-
|
|
448
|
-
if (port === 0) {
|
|
449
|
-
throw new Error(
|
|
450
|
-
`Chrome did not report a CDP port in ${activePortFile} within ${launchTimeout}ms`,
|
|
451
|
-
);
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// Timed out waiting for our Chrome to come up on the port. Distinguish
|
|
455
|
-
// "another Chrome holds it", "nothing is listening" (real launch failure)
|
|
456
|
-
// and "something non-CDP is squatting the port" (confusing generic
|
|
457
|
-
// timeout otherwise).
|
|
458
|
-
if (await isChromeIdentity(port)) {
|
|
459
|
-
throw new Error(
|
|
460
|
-
`Port ${port} is held by a Chrome/Chromium this launch did not start (a concurrent launch took it).`,
|
|
461
|
-
);
|
|
462
|
-
}
|
|
463
|
-
if (await isTcpPortOpen(port)) {
|
|
464
|
-
throw new Error(
|
|
465
|
-
`Port ${port} is occupied by a non-Chrome process (TCP connection succeeds but no CDP response within ${launchTimeout}ms). ` +
|
|
466
|
-
`Free the port or pass a different one.`,
|
|
467
|
-
);
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
throw new Error(`Chrome failed to start on port ${port} within ${launchTimeout}ms`);
|
|
471
|
-
} finally {
|
|
472
|
-
child.stderr?.destroy();
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
/** The per-process id in a browser-level CDP websocket URL
|
|
477
|
-
* (`ws://host:port/devtools/browser/<id>`), or null. */
|
|
478
|
-
function browserIdOf(wsUrl: string | undefined): string | null {
|
|
479
|
-
return wsUrl?.match(/\/devtools\/browser\/([^/?#\s]+)/)?.[1] ?? null;
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
export async function enableSessionDomains(client: CdpClient, sessionId: string): Promise<void> {
|
|
483
|
-
await Promise.all([
|
|
484
|
-
client.send('Page.enable', {}, sessionId),
|
|
485
|
-
client.send('Runtime.enable', {}, sessionId),
|
|
486
|
-
client.send('Network.enable', {}, sessionId),
|
|
487
|
-
client.send('DOM.enable', {}, sessionId),
|
|
488
|
-
client.send('Accessibility.enable', {}, sessionId),
|
|
489
|
-
]);
|
|
490
|
-
setupConsoleCapture(client, sessionId);
|
|
491
|
-
await enableConsoleCapture(client, sessionId);
|
|
492
|
-
setupDialogAutoHandling(client, sessionId);
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
export async function connectToTarget(
|
|
496
|
-
port: number,
|
|
497
|
-
targetId?: string,
|
|
498
|
-
): Promise<{ client: CdpClient; target: CdpTarget; sessionId: string }> {
|
|
499
|
-
const targets = await fetchTargets(port);
|
|
500
|
-
const pageTargets = targets.filter((t) => t.type === 'page');
|
|
501
|
-
|
|
502
|
-
let target: CdpTarget;
|
|
503
|
-
if (targetId) {
|
|
504
|
-
const found = pageTargets.find((t) => t.id === targetId);
|
|
505
|
-
if (!found) throw new Error(`Target ${targetId} not found`);
|
|
506
|
-
target = found;
|
|
507
|
-
} else if (pageTargets.length > 0) {
|
|
508
|
-
target = pageTargets[0];
|
|
509
|
-
} else {
|
|
510
|
-
target = await fetchNewTarget(port, 'about:blank');
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
const wsUrl = target.webSocketDebuggerUrl ?? `ws://127.0.0.1:${port}/devtools/page/${target.id}`;
|
|
514
|
-
const client = new CdpClient();
|
|
515
|
-
await client.connect(wsUrl);
|
|
516
|
-
|
|
517
|
-
const { sessionId } = await client.send<{ sessionId: string }>('Target.attachToTarget', {
|
|
518
|
-
targetId: target.id,
|
|
519
|
-
flatten: true,
|
|
520
|
-
});
|
|
521
|
-
|
|
522
|
-
await enableSessionDomains(client, sessionId);
|
|
523
|
-
return { client, target, sessionId };
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
/**
|
|
527
|
-
* Cleanly terminate a Chrome/Chromium instance we launched on `port`.
|
|
528
|
-
* Sends the `Browser.close` CDP command (the correct graceful shutdown —
|
|
529
|
-
* closes all tabs and exits the process cleanly) over `client`'s connection.
|
|
530
|
-
* If that command fails, times out, or the connection is already gone,
|
|
531
|
-
* falls back to killing the tracked PID directly so a headed/interactive
|
|
532
|
-
* browser window (e.g. one spawned for a login/CAPTCHA flow) never lingers
|
|
533
|
-
* as a visible, authenticated, still-debuggable orphan process.
|
|
534
|
-
*
|
|
535
|
-
* On the graceful path this resolves only once the process is actually gone,
|
|
536
|
-
* or after force-killing it when it outlasts PROCESS_EXIT_TIMEOUT_MS. Chrome
|
|
537
|
-
* acknowledges `Browser.close` well before it exits, and this used to return
|
|
538
|
-
* on the ack with an unref'd 1s timer as the only force-kill — so it resolved
|
|
539
|
-
* while Chrome was still running and holding its port and its profile's
|
|
540
|
-
* singleton lock, and if the caller's process exited first the kill never
|
|
541
|
-
* happened at all. Callers reasonably read a resolved close() as "that
|
|
542
|
-
* browser is gone"; on the graceful path it now means that.
|
|
543
|
-
*/
|
|
544
|
-
export async function closeBrowser(client: CdpClient, port: number): Promise<void> {
|
|
545
|
-
let gracefullyClosed = false;
|
|
546
|
-
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
547
|
-
try {
|
|
548
|
-
await Promise.race([
|
|
549
|
-
client.send('Browser.close', {}),
|
|
550
|
-
// Deliberately NOT unref'd, for the same reason waitForProcessExit()'s
|
|
551
|
-
// poll below is not. This timer is the only thing that settles the race
|
|
552
|
-
// when Chrome's socket dies without ever acknowledging the close, and
|
|
553
|
-
// closeBrowser() is actively awaited by callers. An unref'd timer does
|
|
554
|
-
// not hold the event loop open, so Node would consider the loop drained
|
|
555
|
-
// and exit — status 0, before the caller's verdict was ever printed.
|
|
556
|
-
// Cleared in the finally so a close that IS acknowledged does not pin
|
|
557
|
-
// the loop for the rest of BROWSER_CLOSE_TIMEOUT_MS.
|
|
558
|
-
new Promise<never>((_, reject) => {
|
|
559
|
-
closeTimer = setTimeout(
|
|
560
|
-
() => reject(new Error('Browser.close timed out')),
|
|
561
|
-
BROWSER_CLOSE_TIMEOUT_MS,
|
|
562
|
-
);
|
|
563
|
-
}),
|
|
564
|
-
]);
|
|
565
|
-
gracefullyClosed = true;
|
|
566
|
-
} catch {
|
|
567
|
-
// fall through to PID-kill fallback below
|
|
568
|
-
} finally {
|
|
569
|
-
clearTimeout(closeTimer);
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
let pid = launchedPids.get(port);
|
|
573
|
-
if (pid === undefined) {
|
|
574
|
-
// Fresh process (each CLI invocation is its own node process — see
|
|
575
|
-
// module header) — launchedPids is per-process and empty here even
|
|
576
|
-
// though a prior `open` in a DIFFERENT process launched this Chrome.
|
|
577
|
-
// Fall back to the PID that process persisted via saveSessionRecord().
|
|
578
|
-
try {
|
|
579
|
-
const persisted = await loadSessionRecord(port);
|
|
580
|
-
if (persisted?.launched && persisted.pid) {
|
|
581
|
-
// Bound how far we trust a cross-process PID: if the Chrome we
|
|
582
|
-
// launched died outside this flow (OOM-killed, host slept, etc.)
|
|
583
|
-
// without its session record ever being cleared, the OS can recycle
|
|
584
|
-
// that PID for an unrelated process. There is no cmdline/start-time
|
|
585
|
-
// check available portably, so a coarse age bound is the practical
|
|
586
|
-
// guard — a PID persisted more than a day ago is far more likely to
|
|
587
|
-
// be stale/reused than to still be the same live Chrome.
|
|
588
|
-
const age = persisted.savedAt !== undefined ? Date.now() - persisted.savedAt : undefined;
|
|
589
|
-
if (age === undefined || age <= PERSISTED_PID_MAX_AGE_MS) {
|
|
590
|
-
pid = persisted.pid;
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
} catch {
|
|
594
|
-
// best-effort — fall through to "nothing to kill" below
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
if (pid === undefined) return; // not a process we launched, or too stale to trust — nothing to kill
|
|
598
|
-
launchedPids.delete(port);
|
|
599
|
-
|
|
600
|
-
// Liveness-check before every SIGKILL (not just the safety-net path below)
|
|
601
|
-
// — process.kill(pid, 0) throws ESRCH if the PID is no longer running,
|
|
602
|
-
// which also catches the case where the PID has already been recycled by
|
|
603
|
-
// an unrelated process that happens to have exited too.
|
|
604
|
-
if (!gracefullyClosed) {
|
|
605
|
-
try {
|
|
606
|
-
process.kill(pid, 0);
|
|
607
|
-
process.kill(pid, 'SIGKILL');
|
|
608
|
-
} catch {
|
|
609
|
-
/* already exited, or never was — nothing to do */
|
|
610
|
-
}
|
|
611
|
-
return;
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
// Browser.close was acknowledged — wait for the process to actually go away,
|
|
615
|
-
// then force-kill as a safety net in case it hung.
|
|
616
|
-
if (await waitForProcessExit(pid)) return;
|
|
617
|
-
try {
|
|
618
|
-
process.kill(pid, 'SIGKILL');
|
|
619
|
-
} catch {
|
|
620
|
-
/* raced us to exit — expected */
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
/** Poll until `pid` is gone or PROCESS_EXIT_TIMEOUT_MS elapses. Returns
|
|
625
|
-
* whether it exited. `process.kill(pid, 0)` throws once the process is no
|
|
626
|
-
* longer there, on Windows as well as POSIX.
|
|
627
|
-
*
|
|
628
|
-
* This timer is deliberately NOT unref'd. closeBrowser() awaits this poll
|
|
629
|
-
* as part of its own return value — a caller that awaits closeBrowser() is
|
|
630
|
-
* actively blocked on it, not doing other work in the background. Once
|
|
631
|
-
* Chrome's CDP websocket closes (which happens right around here, as part
|
|
632
|
-
* of it shutting down), nothing else may be left holding the event loop
|
|
633
|
-
* open; an unref'd timer at that point never fires because Node considers
|
|
634
|
-
* the loop drained and exits without running it, leaving this promise (and
|
|
635
|
-
* closeBrowser()'s) pending forever — reproduced locally by closing a real
|
|
636
|
-
* launched browser with nothing else scheduled. Bounded by
|
|
637
|
-
* PROCESS_EXIT_TIMEOUT_MS (5s) either way, so keeping it ref'd only ever
|
|
638
|
-
* costs a caller a few seconds, never a hang. */
|
|
639
|
-
async function waitForProcessExit(pid: number): Promise<boolean> {
|
|
640
|
-
const deadline = Date.now() + PROCESS_EXIT_TIMEOUT_MS;
|
|
641
|
-
for (;;) {
|
|
642
|
-
try {
|
|
643
|
-
process.kill(pid, 0);
|
|
644
|
-
} catch {
|
|
645
|
-
return true;
|
|
646
|
-
}
|
|
647
|
-
if (Date.now() >= deadline) return false;
|
|
648
|
-
await new Promise((resolve) => {
|
|
649
|
-
setTimeout(resolve, PROCESS_EXIT_POLL_MS);
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
/**
|
|
655
|
-
* Give back the CDP port of a browser we launched that nothing is using any
|
|
656
|
-
* more. A launched Chrome is deliberately detached and unref'd so it outlives
|
|
657
|
-
* the command that spawned it and later commands can reattach — but nothing
|
|
658
|
-
* reaped it afterwards, so an abandoned session kept listening on its port
|
|
659
|
-
* (9222 by convention, which other local tools want) indefinitely. A foreign
|
|
660
|
-
* CDP server *answers* there rather than refusing the connection, so those
|
|
661
|
-
* tools retry the wrong port and report misleading errors instead of moving on.
|
|
662
|
-
*
|
|
663
|
-
* Nothing long-lived exists to run this on a timer — every CLI command is its
|
|
664
|
-
* own short-lived process — so it runs at the next launch/attach instead
|
|
665
|
-
* (see launchBrowser). A browser is reaped only when ALL of these hold:
|
|
666
|
-
* - the persisted session says WE launched it — `connect` records
|
|
667
|
-
* launched:false for a browser that belongs to the user, never touched;
|
|
668
|
-
* - that session is older than IDLE_REAP_AFTER_MS;
|
|
669
|
-
* - the CDP endpoint still answers and reports ZERO targets. An open tab,
|
|
670
|
-
* or a client attached to one (Chrome drops webSocketDebuggerUrl from an
|
|
671
|
-
* attached target but still lists it), means the session is live and
|
|
672
|
-
* reattach-across-commands must keep working.
|
|
673
|
-
*
|
|
674
|
-
* Shutdown goes through closeBrowser() on the browser-level websocket — the
|
|
675
|
-
* only connection left once every target is gone — so a recycled PID can
|
|
676
|
-
* never be signaled by mistake: graceful `Browser.close` reaches whatever is
|
|
677
|
-
* actually listening on that port, at any age, and the persisted PID is only
|
|
678
|
-
* ever used for closeBrowser's own age-bounded force-kill.
|
|
679
|
-
*
|
|
680
|
-
* Never throws: a failed reap must not stop a launch. Returns the reaped
|
|
681
|
-
* port, or null when there was nothing to reap. Sessions are per-port
|
|
682
|
-
* (#318), so every recorded one is considered, not just the newest.
|
|
683
|
-
*/
|
|
684
|
-
export async function reapIdleLaunchedBrowser(): Promise<number | null> {
|
|
685
|
-
let reaped: number | null = null;
|
|
686
|
-
for (const session of await listSessionRecords().catch(() => [])) {
|
|
687
|
-
const port = await reapSession(session);
|
|
688
|
-
reaped ??= port;
|
|
689
|
-
}
|
|
690
|
-
return reaped;
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
async function reapSession(session: SessionRecord): Promise<number | null> {
|
|
694
|
-
try {
|
|
695
|
-
if (!session.launched || session.savedAt === undefined) return null;
|
|
696
|
-
if (Date.now() - session.savedAt < IDLE_REAP_AFTER_MS) return null;
|
|
697
|
-
|
|
698
|
-
const wsUrl = await fetchBrowserWebSocketUrl(session.port);
|
|
699
|
-
if (!wsUrl) return null;
|
|
700
|
-
if ((await fetchTargets(session.port)).length > 0) return null;
|
|
701
|
-
|
|
702
|
-
const client = new CdpClient();
|
|
703
|
-
let reapTimer: ReturnType<typeof setTimeout> | undefined;
|
|
704
|
-
try {
|
|
705
|
-
// CdpClient.connect() has no timeout of its own — a socket that never
|
|
706
|
-
// opens (and never errors) would hang the launch this reap is running
|
|
707
|
-
// inside of, which is strictly worse than leaving the port squatted.
|
|
708
|
-
// Not unref'd (see closeBrowser): a socket that never opens and never
|
|
709
|
-
// errors leaves this timer as the only thing that can settle the race,
|
|
710
|
-
// and the reap is awaited inside launch/attach. Cleared in the finally
|
|
711
|
-
// below so a connect that succeeds does not pin the event loop.
|
|
712
|
-
await Promise.race([
|
|
713
|
-
client.connect(wsUrl),
|
|
714
|
-
new Promise<never>((_, reject) => {
|
|
715
|
-
reapTimer = setTimeout(
|
|
716
|
-
() => reject(new Error('Reap: CDP connect timed out')),
|
|
717
|
-
REAP_CONNECT_TIMEOUT_MS,
|
|
718
|
-
);
|
|
719
|
-
}),
|
|
720
|
-
]);
|
|
721
|
-
await closeBrowser(client, session.port);
|
|
722
|
-
} finally {
|
|
723
|
-
clearTimeout(reapTimer);
|
|
724
|
-
try {
|
|
725
|
-
client.close();
|
|
726
|
-
} catch {
|
|
727
|
-
/* already gone */
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
launchedPids.delete(session.port);
|
|
731
|
-
launchedUserDataDirs.delete(session.port);
|
|
732
|
-
await removeSessionRecord(session.port);
|
|
733
|
-
return session.port;
|
|
734
|
-
} catch {
|
|
735
|
-
return null;
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
/** Chrome's browser-level debugger endpoint, from /json/version — the
|
|
740
|
-
* connection `Browser.close` belongs on. Null if the port isn't answering as
|
|
741
|
-
* a Chrome/Chromium CDP endpoint (same identity check as isChromeIdentity). */
|
|
742
|
-
async function fetchBrowserWebSocketUrl(port: number): Promise<string | null> {
|
|
743
|
-
const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
|
|
744
|
-
signal: AbortSignal.timeout(1000),
|
|
745
|
-
});
|
|
746
|
-
if (!res.ok) return null;
|
|
747
|
-
const info = (await res.json()) as { Browser?: string; webSocketDebuggerUrl?: string };
|
|
748
|
-
if (typeof info.Browser !== 'string' || !/chrom(e|ium)|edg/i.test(info.Browser)) return null;
|
|
749
|
-
return typeof info.webSocketDebuggerUrl === 'string' ? info.webSocketDebuggerUrl : null;
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
export async function openUrl(client: CdpClient, sessionId: string, url: string): Promise<void> {
|
|
753
|
-
// Cap to 2 MB to prevent OOM in CDP message serializer (e.g. data: URI attacks)
|
|
754
|
-
if (url.length > 2_097_152) throw new Error('URL exceeds 2 MB limit');
|
|
755
|
-
// Page.navigate reports a protocol-level failure (e.g. a refused connection)
|
|
756
|
-
// via errorText in its own response, before Chrome ever settles on the
|
|
757
|
-
// chrome-error://chromewebdata/ page — without this check a refused
|
|
758
|
-
// connection previously reported success against that error page.
|
|
759
|
-
const nav = await client.send<{ errorText?: string }>('Page.navigate', { url }, sessionId);
|
|
760
|
-
if (nav.errorText) throw new Error(`Navigation to ${url} failed: ${nav.errorText}`);
|
|
761
|
-
await waitForNetworkIdle(client, sessionId, 500, 30_000);
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
export async function waitForLoad(
|
|
765
|
-
client: CdpClient,
|
|
766
|
-
sessionId: string,
|
|
767
|
-
condition: 'load' | 'networkidle' | 'domcontentloaded' = 'load',
|
|
768
|
-
timeout = 30_000,
|
|
769
|
-
): Promise<void> {
|
|
770
|
-
if (condition === 'load' || condition === 'domcontentloaded') {
|
|
771
|
-
// Guard against race where the page loads before the listener is registered
|
|
772
|
-
const readyExpr =
|
|
773
|
-
condition === 'load'
|
|
774
|
-
? 'document.readyState === "complete"'
|
|
775
|
-
: 'document.readyState !== "loading"';
|
|
776
|
-
const readyCheck = await client
|
|
777
|
-
.send<{ result: { value?: boolean } }>(
|
|
778
|
-
'Runtime.evaluate',
|
|
779
|
-
{
|
|
780
|
-
expression: readyExpr,
|
|
781
|
-
returnByValue: true,
|
|
782
|
-
},
|
|
783
|
-
sessionId,
|
|
784
|
-
)
|
|
785
|
-
.catch(() => ({ result: { value: false } }));
|
|
786
|
-
if (readyCheck.result?.value) return;
|
|
787
|
-
|
|
788
|
-
const event = condition === 'load' ? 'Page.loadEventFired' : 'Page.domContentEventFired';
|
|
789
|
-
const [eventPromise, cancelOnce] = client.onceWithOff(event, sessionId);
|
|
790
|
-
let timedOut = false;
|
|
791
|
-
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
|
|
792
|
-
const timeoutPromise = new Promise<void>((resolve) => {
|
|
793
|
-
timeoutHandle = setTimeout(() => {
|
|
794
|
-
timedOut = true;
|
|
795
|
-
resolve();
|
|
796
|
-
}, timeout);
|
|
797
|
-
});
|
|
798
|
-
try {
|
|
799
|
-
await Promise.race([eventPromise, timeoutPromise]);
|
|
800
|
-
if (timedOut) throw new Error(`Timeout waiting for ${condition}`);
|
|
801
|
-
} finally {
|
|
802
|
-
cancelOnce();
|
|
803
|
-
clearTimeout(timeoutHandle);
|
|
804
|
-
}
|
|
805
|
-
return;
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
// networkidle: no network requests for 500ms
|
|
809
|
-
await waitForNetworkIdle(client, sessionId, 500, timeout);
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
async function waitForNetworkIdle(
|
|
813
|
-
client: CdpClient,
|
|
814
|
-
sessionId: string,
|
|
815
|
-
idleMs: number,
|
|
816
|
-
timeout: number,
|
|
817
|
-
): Promise<void> {
|
|
818
|
-
return new Promise((resolve, reject) => {
|
|
819
|
-
let pending = 0;
|
|
820
|
-
const inflight = new Set<string>();
|
|
821
|
-
let idleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
822
|
-
const killTimer = setTimeout(() => {
|
|
823
|
-
cleanup();
|
|
824
|
-
reject(new Error('Timeout waiting for networkidle'));
|
|
825
|
-
}, timeout);
|
|
826
|
-
|
|
827
|
-
const cleanup = () => {
|
|
828
|
-
if (idleTimer) {
|
|
829
|
-
clearTimeout(idleTimer);
|
|
830
|
-
idleTimer = null;
|
|
831
|
-
}
|
|
832
|
-
clearTimeout(killTimer);
|
|
833
|
-
offReq();
|
|
834
|
-
offResp();
|
|
835
|
-
offFail();
|
|
836
|
-
offCache();
|
|
837
|
-
offResp2();
|
|
838
|
-
};
|
|
839
|
-
|
|
840
|
-
const settle = () => {
|
|
841
|
-
cleanup();
|
|
842
|
-
resolve();
|
|
843
|
-
};
|
|
844
|
-
|
|
845
|
-
const check = () => {
|
|
846
|
-
if (pending === 0) {
|
|
847
|
-
if (idleTimer) clearTimeout(idleTimer);
|
|
848
|
-
idleTimer = setTimeout(settle, idleMs);
|
|
849
|
-
} else {
|
|
850
|
-
if (idleTimer) {
|
|
851
|
-
clearTimeout(idleTimer);
|
|
852
|
-
idleTimer = null;
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
};
|
|
856
|
-
|
|
857
|
-
const offReq = client.on('Network.requestWillBeSent', (params, sid) => {
|
|
858
|
-
if (sid !== sessionId) return;
|
|
859
|
-
const id = params.requestId as string;
|
|
860
|
-
if (!inflight.has(id)) {
|
|
861
|
-
inflight.add(id);
|
|
862
|
-
pending++;
|
|
863
|
-
check();
|
|
864
|
-
}
|
|
865
|
-
});
|
|
866
|
-
|
|
867
|
-
const decrement = (params: Record<string, unknown>, sid?: string) => {
|
|
868
|
-
if (sid !== sessionId) return;
|
|
869
|
-
const id = params.requestId as string;
|
|
870
|
-
if (inflight.delete(id)) {
|
|
871
|
-
pending = Math.max(0, pending - 1);
|
|
872
|
-
check();
|
|
873
|
-
}
|
|
874
|
-
};
|
|
875
|
-
|
|
876
|
-
const offResp = client.on('Network.loadingFinished', decrement);
|
|
877
|
-
const offFail = client.on('Network.loadingFailed', decrement);
|
|
878
|
-
const offCache = client.on('Network.requestServedFromCache', decrement);
|
|
879
|
-
// Guard against requests that never fire loadingFinished/loadingFailed (e.g. data: URLs)
|
|
880
|
-
// Skip 3xx redirect responses — the request continues under the same requestId
|
|
881
|
-
const offResp2 = client.on('Network.responseReceived', (params, sid) => {
|
|
882
|
-
const p = params as { requestId: string; response: { status: number } };
|
|
883
|
-
if (p.response.status >= 300 && p.response.status < 400) return;
|
|
884
|
-
decrement(params, sid);
|
|
885
|
-
});
|
|
886
|
-
|
|
887
|
-
check();
|
|
888
|
-
});
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
export async function getCurrentUrl(client: CdpClient, sessionId: string): Promise<string> {
|
|
892
|
-
const result = await client.send<{ result: { value: string } }>(
|
|
893
|
-
'Runtime.evaluate',
|
|
894
|
-
{
|
|
895
|
-
expression: 'location.href',
|
|
896
|
-
returnByValue: true,
|
|
897
|
-
},
|
|
898
|
-
sessionId,
|
|
899
|
-
);
|
|
900
|
-
return result.result?.value ?? '';
|
|
901
|
-
}
|
|
902
|
-
|
|
903
|
-
export async function getCurrentTitle(client: CdpClient, sessionId: string): Promise<string> {
|
|
904
|
-
const result = await client.send<{ result: { value: string } }>(
|
|
905
|
-
'Runtime.evaluate',
|
|
906
|
-
{
|
|
907
|
-
expression: 'document.title',
|
|
908
|
-
returnByValue: true,
|
|
909
|
-
},
|
|
910
|
-
sessionId,
|
|
911
|
-
);
|
|
912
|
-
return result.result?.value ?? '';
|
|
913
|
-
}
|
|
914
|
-
|
|
915
|
-
function sleep(ms: number): Promise<void> {
|
|
916
|
-
return new Promise((r) => setTimeout(r, ms));
|
|
917
|
-
}
|
|
1
|
+
// File-size sweep: split into sibling modules (browser-state, browser-discovery,
|
|
2
|
+
// browser-launch, browser-lifecycle, browser-page). Pure move — this file now
|
|
3
|
+
// re-exports everything it used to define, so every existing import path
|
|
4
|
+
// keeps working.
|
|
5
|
+
|
|
6
|
+
export { isPortOpen } from './browser-discovery.js';
|
|
7
|
+
export { launchBrowser } from './browser-launch.js';
|
|
8
|
+
export { closeBrowser, reapIdleLaunchedBrowser } from './browser-lifecycle.js';
|
|
9
|
+
export {
|
|
10
|
+
connectToTarget,
|
|
11
|
+
enableSessionDomains,
|
|
12
|
+
getCurrentTitle,
|
|
13
|
+
getCurrentUrl,
|
|
14
|
+
openUrl,
|
|
15
|
+
waitForLoad,
|
|
16
|
+
} from './browser-page.js';
|
|
17
|
+
export { getLaunchedPid, getLaunchedUserDataDir } from './browser-state.js';
|