@monoes/monobrowse 1.0.26 → 1.0.28

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