@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
@@ -0,0 +1,116 @@
1
+ // Split out of browser.ts (file-size sweep). Pure move: no behaviour change.
2
+
3
+ import { execSync } from 'node:child_process';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { connect } from 'node:net';
6
+ import { fetchTargets } from './cdp.js';
7
+ import { CHROME_EXECUTABLES } from './types.js';
8
+
9
+ export function findChrome(executablePath?: string): string {
10
+ if (executablePath) {
11
+ if (existsSync(executablePath)) return executablePath;
12
+ throw new Error(`Chrome executable not found: ${executablePath}`);
13
+ }
14
+ for (const candidate of CHROME_EXECUTABLES) {
15
+ if (existsSync(candidate)) return candidate;
16
+ }
17
+ // Try PATH
18
+ try {
19
+ const result = execSync(
20
+ 'which google-chrome chromium-browser chromium microsoft-edge microsoft-edge-stable 2>/dev/null',
21
+ { encoding: 'utf8' },
22
+ ).trim();
23
+ const first = result.split('\n')[0];
24
+ if (first) return first;
25
+ } catch {
26
+ // ignore
27
+ }
28
+ throw new Error(
29
+ 'No supported browser found. Install Google Chrome, Microsoft Edge, or Chromium — or pass executablePath in BrowserConfig.',
30
+ );
31
+ }
32
+
33
+ export async function isPortOpen(port: number): Promise<boolean> {
34
+ try {
35
+ await fetchTargets(port);
36
+ return true;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Confirm the CDP endpoint on `port` actually identifies as Chrome/Chromium
44
+ * via `/json/version`'s `Browser` field, rather than assuming any CDP-speaking
45
+ * responder is "ours". Reduces (does not eliminate) the risk of silently
46
+ * attaching to an unrelated real browser that happens to be listening there.
47
+ */
48
+ export async function isChromeIdentity(port: number): Promise<boolean> {
49
+ return (await chromeIdentity(port)) === 'chrome';
50
+ }
51
+
52
+ /** isChromeIdentity, telling "answered as something else" apart from "did
53
+ * not answer in time" ('unknown': a timeout, a refused or reset connection,
54
+ * a non-OK status or an unparseable body). */
55
+ export async function chromeIdentity(port: number): Promise<'chrome' | 'other' | 'unknown'> {
56
+ try {
57
+ const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
58
+ signal: AbortSignal.timeout(1000),
59
+ });
60
+ if (!res.ok) return 'unknown';
61
+ const info = (await res.json()) as { Browser?: string };
62
+ // Edge's Browser field is "Edg/<version>" with no "chrome"/"chromium"
63
+ // substring, even though it's Chromium-based and CDP-compatible —
64
+ // accept it alongside Chrome/Chromium rather than rejecting a valid target.
65
+ return typeof info.Browser === 'string' && /chrom(e|ium)|edg/i.test(info.Browser)
66
+ ? 'chrome'
67
+ : 'other';
68
+ } catch {
69
+ return 'unknown';
70
+ }
71
+ }
72
+
73
+ /** Raw TCP connect probe — distinguishes "nothing listening" from "something listening that isn't CDP". */
74
+ export function isTcpPortOpen(port: number, timeoutMs = 1000): Promise<boolean> {
75
+ return new Promise((resolve) => {
76
+ const socket = connect({ host: '127.0.0.1', port, timeout: timeoutMs });
77
+ const done = (result: boolean) => {
78
+ socket.removeAllListeners();
79
+ socket.destroy();
80
+ resolve(result);
81
+ };
82
+ socket.once('connect', () => done(true));
83
+ socket.once('timeout', () => done(false));
84
+ socket.once('error', () => done(false));
85
+ });
86
+ }
87
+
88
+ /** The port Chrome wrote to `<userDataDir>/DevToolsActivePort` once its
89
+ * DevTools server was listening, or null if it has not (yet). */
90
+ export function readDevToolsActivePort(file: string): number | null {
91
+ try {
92
+ const port = Number.parseInt(readFileSync(file, 'utf8').split('\n')[0], 10);
93
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /** The per-process id in a browser-level CDP websocket URL
100
+ * (`ws://host:port/devtools/browser/<id>`), or null. */
101
+ export function browserIdOf(wsUrl: string | undefined): string | null {
102
+ return wsUrl?.match(/\/devtools\/browser\/([^/?#\s]+)/)?.[1] ?? null;
103
+ }
104
+
105
+ /** Chrome's browser-level debugger endpoint, from /json/version — the
106
+ * connection `Browser.close` belongs on. Null if the port isn't answering as
107
+ * a Chrome/Chromium CDP endpoint (same identity check as isChromeIdentity). */
108
+ export async function fetchBrowserWebSocketUrl(port: number): Promise<string | null> {
109
+ const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
110
+ signal: AbortSignal.timeout(1000),
111
+ });
112
+ if (!res.ok) return null;
113
+ const info = (await res.json()) as { Browser?: string; webSocketDebuggerUrl?: string };
114
+ if (typeof info.Browser !== 'string' || !/chrom(e|ium)|edg/i.test(info.Browser)) return null;
115
+ return typeof info.webSocketDebuggerUrl === 'string' ? info.webSocketDebuggerUrl : null;
116
+ }
@@ -0,0 +1,375 @@
1
+ // Split out of browser.ts (file-size sweep). Pure move: no behaviour change.
2
+
3
+ import { spawn } from 'node:child_process';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { rmSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import {
8
+ browserIdOf,
9
+ chromeIdentity,
10
+ fetchBrowserWebSocketUrl,
11
+ findChrome,
12
+ isChromeIdentity,
13
+ isPortOpen,
14
+ isTcpPortOpen,
15
+ readDevToolsActivePort,
16
+ } from './browser-discovery.js';
17
+ import { reapIdleLaunchedBrowser } from './browser-lifecycle.js';
18
+ import { launchedPids, launchedUserDataDirs, ownedUserDataDirPorts } from './browser-state.js';
19
+ import {
20
+ launchProfileDirPath,
21
+ removeOwnedProfileDir,
22
+ sweepStaleProfileDirs,
23
+ } from './profile-dir.js';
24
+ import type { BrowserConfig } from './types.js';
25
+
26
+ const DEFAULT_PORT = 9222;
27
+ const LAUNCH_TIMEOUT = 10_000;
28
+ const POLL_INTERVAL = 200;
29
+
30
+ /** Ports scanned when the requested one is occupied by a non-Chrome process
31
+ * (e.g. another local tool that happens to reuse Chrome's conventional CDP
32
+ * default, 9222 — mirrors the auto-increment convention this monorepo's own
33
+ * dashboard server uses in bindServer/server.mjs). Only occupied-by-a-
34
+ * DIFFERENT-process is worked around; an already-attachable Chrome on the
35
+ * requested port is still returned as-is (existing "attach, don't relaunch"
36
+ * behavior). */
37
+ const LAUNCH_PORT_SCAN_TRIES = 10;
38
+
39
+ export async function launchBrowser(config: BrowserConfig = {}): Promise<number> {
40
+ const rawPort = config.port ?? DEFAULT_PORT;
41
+ // Port 0 means "let Chrome bind a free port and tell us which" — see
42
+ // launchOnFreePort. Otherwise validate port is in a safe range for
43
+ // localhost CDP debugging.
44
+ if (rawPort === 0) {
45
+ if (!config.userDataDir) {
46
+ throw new Error(
47
+ 'port 0 requires a dedicated userDataDir (Chrome reports the port it bound inside it).',
48
+ );
49
+ }
50
+ } else if (!Number.isInteger(rawPort) || rawPort < 1024 || rawPort > 65535) {
51
+ throw new Error(`Invalid port: ${rawPort}. Must be 0 or an integer between 1024 and 65535.`);
52
+ }
53
+
54
+ // Every launch/attach is this tool's only chance to notice that a previous
55
+ // session abandoned a browser on a CDP port and never gave it back — there
56
+ // is no daemon to do it on a timer. Bounded and non-throwing; a stale
57
+ // instance on the port we are about to use is freed before we probe it.
58
+ await reapIdleLaunchedBrowser();
59
+ // Same reasoning for temp profile dirs (#395): a process that crashed or
60
+ // was killed never deleted the one its browser used. Only dead, idle,
61
+ // unused dirs of our own naming go — see sweepStaleProfileDirs.
62
+ await sweepStaleProfileDirs();
63
+
64
+ if (rawPort === 0) return launchOnFreePort(config, 0);
65
+
66
+ // strictPort: fail fast on the exact requested port, matching the old
67
+ // behavior (Vite has the same escape hatch for the same reason) — for
68
+ // callers that treat the error as a signal ("this port is taken by
69
+ // something else, bail") rather than consuming the returned port.
70
+ if (config.strictPort) {
71
+ if (await isTcpPortOpen(rawPort)) {
72
+ if (await isChromeIdentity(rawPort)) return rawPort;
73
+ throw new Error(
74
+ `Port ${rawPort} is occupied by a process that does not identify as Chrome/Chromium. ` +
75
+ `Refusing to attach — pass a different port or free port ${rawPort}.`,
76
+ );
77
+ }
78
+ return launchOnFreePort(config, rawPort);
79
+ }
80
+
81
+ const candidates: number[] = [];
82
+ for (let i = 0; i < LAUNCH_PORT_SCAN_TRIES && rawPort + i <= 65535; i++)
83
+ candidates.push(rawPort + i);
84
+
85
+ for (const candidate of candidates) {
86
+ // TCP-level check for "is anything at all listening" — isPortOpen()
87
+ // does a full CDP /json fetch, which returns false BOTH for a genuinely
88
+ // free port and for one occupied by a non-CDP process (that ambiguity is
89
+ // exactly what the post-spawn isTcpPortOpen fallback below exists to
90
+ // resolve, the hard way, after a 10s launch timeout). Checking the raw
91
+ // socket first tells free and occupied apart up front, so the scan can
92
+ // skip an occupied candidate instead of trying to spawn Chrome on top of
93
+ // it and only discovering the conflict after a timeout.
94
+ if (await isTcpPortOpen(candidate)) {
95
+ // Attach-if-already-Chrome only applies to the EXACT requested port —
96
+ // the original, deliberate, single-port risk ("don't silently take
97
+ // over an unrelated real browser that happens to be on this port").
98
+ // Scanning past an occupied default must not let that same shortcut
99
+ // attach to a DIFFERENT Chrome instance the caller never named;
100
+ // forward candidates are launch-only (skip if anything is there,
101
+ // Chrome or not).
102
+ if (candidate === rawPort && (await isChromeIdentity(candidate))) return candidate;
103
+ // Occupied (by anything — not just non-Chrome, per the note above) —
104
+ // try the next candidate instead of failing outright, same as a
105
+ // normal EADDRINUSE retry would.
106
+ continue;
107
+ }
108
+ try {
109
+ return await launchOnFreePort(config, candidate);
110
+ } catch (err) {
111
+ const isLastCandidate = candidate === candidates[candidates.length - 1];
112
+ // isTcpPortOpen() above is a connect() probe, not an atomic claim: two
113
+ // concurrent launchBrowser() calls with no explicit --port can both
114
+ // observe the same candidate as free and both spawn Chrome on it
115
+ // before either binds. One wins; the other's Chrome exits before its
116
+ // CDP endpoint opens ("Chrome exited before the CDP endpoint opened
117
+ // ... code=21"). Something is listening on the candidate NOW that
118
+ // was not a moment ago — a losing race, not a broken Chrome install —
119
+ // so try the next candidate exactly like an already-occupied one,
120
+ // instead of failing the whole launch outright. A candidate that
121
+ // fails with nothing now listening (a real launch failure — bad
122
+ // executable, sandbox refusal, etc.) is not a race: retrying the
123
+ // next candidate would only fail the same way, so surface it as-is.
124
+ if (!isLastCandidate && (await isTcpPortOpen(candidate))) continue;
125
+ throw err;
126
+ }
127
+ }
128
+ throw new Error(
129
+ `Ports ${candidates[0]}-${candidates[candidates.length - 1]} are all occupied and port ${candidates[0]} ` +
130
+ `isn't a Chrome/Chromium instance to attach to. Pass a different --port.`,
131
+ );
132
+ }
133
+
134
+ /**
135
+ * Spawn Chrome and wait for its CDP endpoint.
136
+ *
137
+ * With a fixed `port`, "our Chrome is up" is inferred from *some* Chrome
138
+ * answering on 127.0.0.1:<port> — which is not necessarily ours. When the port
139
+ * is already bound on 127.0.0.1 (a concurrent launch picked the same "free"
140
+ * port between its probe and Chrome's bind), Chrome does not fail: it logs
141
+ * `bind() failed: Address already in use` and listens on [::1]:<port>
142
+ * instead. The poll then accepts the OTHER launcher's browser, both callers
143
+ * drive one Chrome, and whichever closes first kills the other's connections
144
+ * ("CDP connection closed") while this launch's own Chrome is orphaned.
145
+ *
146
+ * `port: 0` removes the race instead of narrowing it: Chrome asks the kernel
147
+ * for a free port at bind time — atomic, nothing to collide on — and writes
148
+ * the port it got to DevToolsActivePort in its own (caller-dedicated) profile
149
+ * directory, which is proof the endpoint is the process we spawned.
150
+ *
151
+ * A fixed port needs its own proof, since Chrome writes DevToolsActivePort
152
+ * only for port 0. Once listening, Chrome prints `DevTools listening on
153
+ * ws://…/devtools/browser/<id>` to stderr, and `<id>` is unique to that
154
+ * browser process, the same one `/json/version` reports. An endpoint is
155
+ * adopted only when it reports the id our own child printed. Without that
156
+ * check, a launch whose Chrome was still booting found a concurrent
157
+ * launch's Chrome on the shared port and returned it, recording its own
158
+ * doomed pid there. It also covers Chrome's [::1] fallback described above.
159
+ */
160
+ async function launchOnFreePort(config: BrowserConfig, port: number): Promise<number> {
161
+ const chromePath = findChrome(config.executablePath);
162
+ // Unique per launch, not just per port and pid: two concurrent launches
163
+ // that both probe the same candidate port as free (the race this function
164
+ // exists to survive — see the retry-on-collision caller above) would
165
+ // otherwise share one profile directory (lock files, preferences, the
166
+ // DevToolsActivePort file itself) — including two launches from the same
167
+ // process, where a pid suffix alone is identical.
168
+ const userDataDir = config.userDataDir ?? launchProfileDirPath(port, randomUUID().slice(0, 8));
169
+ // A dir we created is deleted once its browser is gone (#395); a
170
+ // caller-supplied one only when the caller says it made it for us.
171
+ const ownsUserDataDir = config.userDataDir === undefined || config.ownsUserDataDir === true;
172
+ const activePortFile = join(userDataDir, 'DevToolsActivePort');
173
+ // A reused profile dir may hold a previous run's file naming a port some
174
+ // other process now owns.
175
+ if (port === 0) rmSync(activePortFile, { force: true });
176
+
177
+ const defaultArgs = [
178
+ `--remote-debugging-port=${port}`,
179
+ `--user-data-dir=${userDataDir}`,
180
+ '--no-first-run',
181
+ '--no-default-browser-check',
182
+ '--disable-background-networking',
183
+ '--disable-client-side-phishing-detection',
184
+ '--disable-default-apps',
185
+ '--disable-extensions',
186
+ '--disable-hang-monitor',
187
+ '--disable-popup-blocking',
188
+ '--disable-prompt-on-repost',
189
+ '--disable-sync',
190
+ '--disable-translate',
191
+ '--metrics-recording-only',
192
+ '--safebrowsing-disable-auto-update',
193
+ '--password-store=basic',
194
+ '--use-mock-keychain',
195
+ ];
196
+
197
+ if (config.headless !== false) {
198
+ defaultArgs.push('--headless=new');
199
+ }
200
+
201
+ // Chrome's setuid sandbox cannot initialise on most CI runners and
202
+ // containers, so the process dies during startup and the CDP endpoint never
203
+ // opens. The launch below then burns its whole timeout before reporting a
204
+ // generic failure, which reads as a hang rather than "Chrome could not
205
+ // start". Disabling the sandbox is the standard remedy and is scoped to CI
206
+ // so a real user's browser keeps it. --disable-dev-shm-usage goes with it:
207
+ // a container's default /dev/shm is 64MB, which Chrome exhausts and then
208
+ // crashes the same way.
209
+ if (process.env.CI) {
210
+ defaultArgs.push('--no-sandbox', '--disable-dev-shm-usage');
211
+ }
212
+
213
+ // Cap caller-supplied args to prevent memory exhaustion via huge argument arrays
214
+ const callerArgs = (config.args ?? []).slice(0, 50);
215
+ const args = [...defaultArgs, ...callerArgs];
216
+ const child = spawn(chromePath, args, {
217
+ detached: true,
218
+ // stderr carries the fixed-port ownership proof (see above). The pipe is
219
+ // closed as soon as this launch settles, so a Chrome that outlives us
220
+ // never blocks writing to it.
221
+ stdio: port === 0 ? 'ignore' : ['ignore', 'ignore', 'pipe'],
222
+ });
223
+ let announcedBrowserId: string | null = null;
224
+ if (child.stderr) {
225
+ let stderrTail = '';
226
+ child.stderr.setEncoding('utf8');
227
+ child.stderr.on('data', (chunk: string) => {
228
+ if (announcedBrowserId) return;
229
+ stderrTail = (stderrTail + chunk).slice(-4096);
230
+ announcedBrowserId = browserIdOf(
231
+ /DevTools listening on (ws:\/\/\S+)\r?\n/.exec(stderrTail)?.[1],
232
+ );
233
+ });
234
+ child.stderr.on('error', () => {
235
+ /* closed under us — nothing to read */
236
+ });
237
+ }
238
+
239
+ // Without this, a spawn failure (e.g. EACCES/ENOENT — chromePath exists per
240
+ // findChrome()'s existsSync check but isn't actually executable, or is
241
+ // removed between the check and exec) fires Node's 'error' event on the
242
+ // next tick. With no listener, Node throws it as an uncaught exception and
243
+ // the whole process goes down — which strands this function's promise
244
+ // forever pending rather than rejecting it (issue #314: node:test reports
245
+ // that as "cancelledByParent" / "still pending" because nothing here ever
246
+ // got the chance to settle it). Recording the failure and having the poll
247
+ // loop below notice it turns that crash into a normal rejection. 'exit'
248
+ // covers the twin case: Chrome execs fine but the process itself dies
249
+ // immediately (missing shared libraries, a container's sandbox refusing
250
+ // it, etc.) — that fires 'exit', not 'error', and without this the poll
251
+ // loop would just burn its whole timeout probing a port nothing will ever
252
+ // open on.
253
+ let earlyFailure: Error | null = null;
254
+ child.on('error', (err) => {
255
+ earlyFailure ??= new Error(`Chrome failed to start on port ${port}: ${err.message}`);
256
+ });
257
+ child.on('exit', (code, signal) => {
258
+ earlyFailure ??= new Error(
259
+ `Chrome exited before the CDP endpoint opened on port ${port} ` +
260
+ `(code=${code ?? 'null'}, signal=${signal ?? 'null'})`,
261
+ );
262
+ });
263
+
264
+ child.unref();
265
+ const track = (boundPort: number) => {
266
+ if (!child.pid) return;
267
+ launchedPids.set(boundPort, child.pid);
268
+ launchedUserDataDirs.set(boundPort, userDataDir);
269
+ if (ownsUserDataDir) ownedUserDataDirPorts.add(boundPort);
270
+ else ownedUserDataDirPorts.delete(boundPort);
271
+ };
272
+ // Tracked only once Chrome is CONFIRMED up on `boundPort`, not right after
273
+ // spawn(). For port !== 0 this used to track(port) unconditionally the
274
+ // moment the child was spawned, before knowing whether it would actually
275
+ // win the port — when a racing launchBrowser() call retries a candidate
276
+ // that a concurrent process also spawned Chrome on (see the retry loop in
277
+ // launchBrowser), BOTH child processes called track() for the SAME
278
+ // candidate, and whichever call's spawn happened to run last clobbered the
279
+ // map entry with its own pid — including the LOSING, about-to-exit
280
+ // process's pid overwriting the real winner's, corrupting the very map
281
+ // closeBrowser()'s kill fallback depends on.
282
+
283
+ // A refused or timed-out launch is not tracked under any port, so no
284
+ // closeBrowser() could ever reach it — stop it rather than leave it
285
+ // running.
286
+ const killUntracked = () => {
287
+ try {
288
+ if (child.pid) process.kill(child.pid, 'SIGKILL');
289
+ } catch {
290
+ /* already gone */
291
+ }
292
+ };
293
+
294
+ // Our own Chrome, not just some Chrome, is serving `boundPort`. For port 0
295
+ // the port came from our own profile's DevToolsActivePort, so it is.
296
+ const isOwnEndpoint = async (boundPort: number): Promise<boolean> => {
297
+ if (port === 0) return true;
298
+ if (!announcedBrowserId) return false;
299
+ const wsUrl = await fetchBrowserWebSocketUrl(boundPort).catch(() => null);
300
+ return browserIdOf(wsUrl ?? undefined) === announcedBrowserId;
301
+ };
302
+
303
+ const launchTimeout = config.launchTimeoutMs ?? LAUNCH_TIMEOUT;
304
+ const deadline = Date.now() + launchTimeout;
305
+ let launched = false;
306
+ try {
307
+ while (Date.now() < deadline) {
308
+ if (earlyFailure) throw earlyFailure;
309
+ await sleep(POLL_INTERVAL);
310
+ if (earlyFailure) throw earlyFailure;
311
+ const boundPort = port === 0 ? readDevToolsActivePort(activePortFile) : port;
312
+ if (boundPort !== null && (await isPortOpen(boundPort))) {
313
+ const identity = await chromeIdentity(boundPort);
314
+ if (identity === 'chrome') {
315
+ if (await isOwnEndpoint(boundPort)) {
316
+ track(boundPort);
317
+ launched = true;
318
+ return boundPort;
319
+ }
320
+ // Some Chrome answers on the port, but not the one we started: a
321
+ // concurrent launch's, or ours before its stderr line arrived. Our
322
+ // child exiting (it lost the bind) or the deadline decides.
323
+ continue;
324
+ }
325
+ // A Chrome that has only just opened its endpoint, on a loaded
326
+ // machine, can answer /json/list (no timeout) yet miss the identity
327
+ // check's 1 s timeout on /json/version. That says nothing about who is
328
+ // listening — keep polling rather than refuse our own Chrome.
329
+ if (identity === 'unknown') continue;
330
+ killUntracked();
331
+ throw new Error(
332
+ `Port ${boundPort} is occupied by a CDP-speaking process that does not identify as Chrome/Chromium. ` +
333
+ `Refusing to attach — pass a different port or free port ${boundPort}.`,
334
+ );
335
+ }
336
+ }
337
+
338
+ if (earlyFailure) throw earlyFailure;
339
+ killUntracked();
340
+
341
+ if (port === 0) {
342
+ throw new Error(
343
+ `Chrome did not report a CDP port in ${activePortFile} within ${launchTimeout}ms`,
344
+ );
345
+ }
346
+
347
+ // Timed out waiting for our Chrome to come up on the port. Distinguish
348
+ // "another Chrome holds it", "nothing is listening" (real launch failure)
349
+ // and "something non-CDP is squatting the port" (confusing generic
350
+ // timeout otherwise).
351
+ if (await isChromeIdentity(port)) {
352
+ throw new Error(
353
+ `Port ${port} is held by a Chrome/Chromium this launch did not start (a concurrent launch took it).`,
354
+ );
355
+ }
356
+ if (await isTcpPortOpen(port)) {
357
+ throw new Error(
358
+ `Port ${port} is occupied by a non-Chrome process (TCP connection succeeds but no CDP response within ${launchTimeout}ms). ` +
359
+ `Free the port or pass a different one.`,
360
+ );
361
+ }
362
+
363
+ throw new Error(`Chrome failed to start on port ${port} within ${launchTimeout}ms`);
364
+ } finally {
365
+ child.stderr?.destroy();
366
+ // A failed launch (lost port race, refusal, timeout) is never tracked,
367
+ // so no close will ever clean its profile — and the port-scan retry in
368
+ // launchBrowser can make several of these per call.
369
+ if (!launched && ownsUserDataDir) await removeOwnedProfileDir(userDataDir, { pid: child.pid });
370
+ }
371
+ }
372
+
373
+ function sleep(ms: number): Promise<void> {
374
+ return new Promise((r) => setTimeout(r, ms));
375
+ }