@namzu/browser 0.1.0

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 (74) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE.md +110 -0
  3. package/README.md +149 -0
  4. package/dist/classifier.d.ts +70 -0
  5. package/dist/classifier.d.ts.map +1 -0
  6. package/dist/classifier.js +147 -0
  7. package/dist/classifier.js.map +1 -0
  8. package/dist/detect.d.ts +126 -0
  9. package/dist/detect.d.ts.map +1 -0
  10. package/dist/detect.js +282 -0
  11. package/dist/detect.js.map +1 -0
  12. package/dist/errors.d.ts +64 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +99 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/host.d.ts +167 -0
  17. package/dist/host.d.ts.map +1 -0
  18. package/dist/host.js +1024 -0
  19. package/dist/host.js.map +1 -0
  20. package/dist/index.d.ts +17 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +10 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/page-scripts.d.ts +51 -0
  25. package/dist/page-scripts.d.ts.map +1 -0
  26. package/dist/page-scripts.js +123 -0
  27. package/dist/page-scripts.js.map +1 -0
  28. package/dist/policy.d.ts +61 -0
  29. package/dist/policy.d.ts.map +1 -0
  30. package/dist/policy.js +150 -0
  31. package/dist/policy.js.map +1 -0
  32. package/dist/profiles.d.ts +107 -0
  33. package/dist/profiles.d.ts.map +1 -0
  34. package/dist/profiles.js +312 -0
  35. package/dist/profiles.js.map +1 -0
  36. package/dist/relay.d.ts +27 -0
  37. package/dist/relay.d.ts.map +1 -0
  38. package/dist/relay.js +69 -0
  39. package/dist/relay.js.map +1 -0
  40. package/dist/snapshot.d.ts +101 -0
  41. package/dist/snapshot.d.ts.map +1 -0
  42. package/dist/snapshot.js +265 -0
  43. package/dist/snapshot.js.map +1 -0
  44. package/dist/windows-bridge-script.d.ts +29 -0
  45. package/dist/windows-bridge-script.d.ts.map +1 -0
  46. package/dist/windows-bridge-script.js +161 -0
  47. package/dist/windows-bridge-script.js.map +1 -0
  48. package/dist/windows-bridge.d.ts +120 -0
  49. package/dist/windows-bridge.d.ts.map +1 -0
  50. package/dist/windows-bridge.js +267 -0
  51. package/dist/windows-bridge.js.map +1 -0
  52. package/dist/windows-engine.d.ts +55 -0
  53. package/dist/windows-engine.d.ts.map +1 -0
  54. package/dist/windows-engine.js +154 -0
  55. package/dist/windows-engine.js.map +1 -0
  56. package/dist/wsl.d.ts +52 -0
  57. package/dist/wsl.d.ts.map +1 -0
  58. package/dist/wsl.js +134 -0
  59. package/dist/wsl.js.map +1 -0
  60. package/package.json +74 -0
  61. package/src/classifier.ts +191 -0
  62. package/src/detect.ts +432 -0
  63. package/src/errors.ts +121 -0
  64. package/src/host.ts +1217 -0
  65. package/src/index.ts +79 -0
  66. package/src/page-scripts.ts +154 -0
  67. package/src/policy.ts +190 -0
  68. package/src/profiles.ts +373 -0
  69. package/src/relay.ts +101 -0
  70. package/src/snapshot.ts +317 -0
  71. package/src/windows-bridge-script.ts +160 -0
  72. package/src/windows-bridge.ts +358 -0
  73. package/src/windows-engine.ts +208 -0
  74. package/src/wsl.ts +155 -0
@@ -0,0 +1,358 @@
1
+ import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'
2
+ import { WINDOWS_BRIDGE_SCRIPT } from './windows-bridge-script.js'
3
+
4
+ /**
5
+ * The WSL half of the PowerShell bridge: builds the command line, starts
6
+ * `powershell.exe` through interop, reads its `ready` line, and moves
7
+ * newline-framed CDP messages in and out of its standard streams.
8
+ */
9
+
10
+ /** What the bridge script is told, as base64 JSON inside the script. */
11
+ export interface WindowsBridgeParams {
12
+ /** The browser, as Windows sees it. */
13
+ readonly executable: string
14
+ /** The profile name; the user data directory defaults to `%LOCALAPPDATA%\namzu\browser\profiles\<profile>`. */
15
+ readonly profile: string
16
+ /** A user data directory (Windows path) to use instead of the default. */
17
+ readonly userDataDir?: string
18
+ readonly headless: boolean
19
+ /** Close a browser this bridge started when its stdin closes. */
20
+ readonly closeOnExit: boolean
21
+ /** How long to wait for `DevToolsActivePort` after starting the browser. */
22
+ readonly launchTimeoutMs: number
23
+ /** Only attach to a running browser; never start one. */
24
+ readonly attachOnly?: boolean
25
+ }
26
+
27
+ /** The bridge's `ready` line. */
28
+ export interface WindowsBridgeReady {
29
+ readonly type: 'ready'
30
+ /** The profile's user data directory, as Windows sees it. */
31
+ readonly userDataDir: string
32
+ /** The browser's debugging port on Windows' `127.0.0.1`. */
33
+ readonly port: number
34
+ /** `/devtools/browser/<id>`. */
35
+ readonly path: string
36
+ /** Whether this bridge started the browser (else it attached to a running one). */
37
+ readonly launched: boolean
38
+ /** The started browser's Windows process id; 0 when attached. */
39
+ readonly pid: number
40
+ readonly localAppData: string
41
+ }
42
+
43
+ /** A refusal from the bridge script, before `ready`. */
44
+ export class WindowsBridgeError extends Error {
45
+ override readonly name = 'WindowsBridgeError'
46
+
47
+ constructor(
48
+ readonly code: string,
49
+ message: string,
50
+ ) {
51
+ super(message)
52
+ }
53
+ }
54
+
55
+ const PARAMS_PLACEHOLDER = '__NAMZU_BRIDGE_PARAMS__'
56
+
57
+ /** PowerShell's `-EncodedCommand` form: the script as UTF-16LE, base64. */
58
+ export function encodePowerShellCommand(script: string): string {
59
+ return Buffer.from(script, 'utf16le').toString('base64')
60
+ }
61
+
62
+ /** The bridge script with `params` embedded. */
63
+ export function bridgeScript(params: WindowsBridgeParams): string {
64
+ const encoded = Buffer.from(JSON.stringify(params), 'utf8').toString('base64')
65
+ return WINDOWS_BRIDGE_SCRIPT.replace(PARAMS_PLACEHOLDER, encoded)
66
+ }
67
+
68
+ /** `powershell.exe`'s arguments for the bridge. */
69
+ export function bridgeArguments(params: WindowsBridgeParams): string[] {
70
+ return [
71
+ '-NoLogo',
72
+ '-NoProfile',
73
+ '-NonInteractive',
74
+ '-ExecutionPolicy',
75
+ 'Bypass',
76
+ '-EncodedCommand',
77
+ encodePowerShellCommand(bridgeScript(params)),
78
+ ]
79
+ }
80
+
81
+ /**
82
+ * Chrome's `DevToolsActivePort` file: the port on the first line, the browser
83
+ * target's path on the second. `undefined` for anything else.
84
+ */
85
+ export function parseDevToolsActivePort(
86
+ text: string | undefined,
87
+ ): { port: number; path: string } | undefined {
88
+ if (text === undefined) return undefined
89
+ const [first, second] = text.split(/\r?\n/)
90
+ const port = Number((first ?? '').trim())
91
+ const path = (second ?? '').trim()
92
+ if (!Number.isInteger(port) || port <= 0 || port > 65_535) return undefined
93
+ if (!/^\/devtools\/browser\/[A-Za-z0-9-]+$/.test(path)) return undefined
94
+ return { port, path }
95
+ }
96
+
97
+ const NEWLINE = 0x0a
98
+ const CARRIAGE_RETURN = 0x0d
99
+
100
+ /**
101
+ * Cuts a byte stream into lines at `\n` (a trailing `\r` is dropped).
102
+ * Chunks are kept as they arrive and joined once per line, and only the new
103
+ * chunk is scanned, so a multi-megabyte line costs one copy.
104
+ */
105
+ export class LineSplitter {
106
+ private pending: Buffer[] = []
107
+ private pendingBytes = 0
108
+
109
+ constructor(private readonly onLine: (line: Buffer) => void) {}
110
+
111
+ push(chunk: Buffer): void {
112
+ let start = 0
113
+ for (;;) {
114
+ const at = chunk.indexOf(NEWLINE, start)
115
+ if (at === -1) break
116
+ let line: Buffer
117
+ const part = chunk.subarray(start, at)
118
+ if (this.pendingBytes > 0) {
119
+ this.pending.push(part)
120
+ line = Buffer.concat(this.pending, this.pendingBytes + part.length)
121
+ this.pending = []
122
+ this.pendingBytes = 0
123
+ } else {
124
+ line = part
125
+ }
126
+ if (line.length > 0 && line[line.length - 1] === CARRIAGE_RETURN) {
127
+ line = line.subarray(0, line.length - 1)
128
+ }
129
+ this.onLine(line)
130
+ start = at + 1
131
+ }
132
+ if (start < chunk.length) {
133
+ const rest = chunk.subarray(start)
134
+ this.pending.push(rest)
135
+ this.pendingBytes += rest.length
136
+ }
137
+ }
138
+
139
+ /** Bytes held for a line not yet ended. */
140
+ get buffered(): number {
141
+ return this.pendingBytes
142
+ }
143
+ }
144
+
145
+ const CONTROL_PREFIX = Buffer.from('@namzu ')
146
+ const OPEN_BRACE = 0x7b
147
+
148
+ export interface StartWindowsBridgeOptions {
149
+ /** `powershell.exe`, as WSL sees it. */
150
+ readonly powershell: string
151
+ readonly params: WindowsBridgeParams
152
+ /** The environment for `powershell.exe`; must carry a working `WSL_INTEROP`. */
153
+ readonly env: NodeJS.ProcessEnv
154
+ /** How long to wait for `ready`. Default: the launch timeout plus 15 s. */
155
+ readonly readyTimeoutMs?: number
156
+ /** For tests: start something other than `powershell.exe`. */
157
+ readonly spawnProcess?: (
158
+ command: string,
159
+ args: readonly string[],
160
+ env: NodeJS.ProcessEnv,
161
+ ) => ChildProcessWithoutNullStreams
162
+ }
163
+
164
+ /** A running bridge: one `powershell.exe`, one browser connection. */
165
+ export class WindowsCdpBridge {
166
+ private messageListener: ((message: Buffer) => void) | undefined
167
+ private readonly early: Buffer[] = []
168
+ private exitedFlag = false
169
+ /** Resolves when the bridge process has exited. */
170
+ readonly exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>
171
+
172
+ private constructor(
173
+ private readonly child: ChildProcessWithoutNullStreams,
174
+ readonly ready: WindowsBridgeReady,
175
+ exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>,
176
+ early: Buffer[],
177
+ private readonly stderrTail: string[],
178
+ ) {
179
+ this.exited = exited
180
+ this.early.push(...early)
181
+ void exited.then(() => {
182
+ this.exitedFlag = true
183
+ })
184
+ }
185
+
186
+ /** The bridge's process id on the Linux side. */
187
+ get pid(): number | undefined {
188
+ return this.child.pid
189
+ }
190
+
191
+ get alive(): boolean {
192
+ return !this.exitedFlag
193
+ }
194
+
195
+ static async start(options: StartWindowsBridgeOptions): Promise<WindowsCdpBridge> {
196
+ const args = bridgeArguments(options.params)
197
+ const child = options.spawnProcess
198
+ ? options.spawnProcess(options.powershell, args, options.env)
199
+ : spawn(options.powershell, args, {
200
+ env: options.env,
201
+ stdio: ['pipe', 'pipe', 'pipe'],
202
+ windowsHide: true,
203
+ })
204
+ const stderrTail: string[] = []
205
+ child.stderr.setEncoding('utf8')
206
+ child.stderr.on('data', (text: string) => {
207
+ stderrTail.push(text)
208
+ while (stderrTail.join('').length > 4_000) stderrTail.shift()
209
+ })
210
+ // A write to a bridge that has gone is reported by `exited`, not thrown.
211
+ child.stdin.on('error', () => undefined)
212
+ const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
213
+ (resolve) => {
214
+ child.once('close', (code, signal) => resolve({ code, signal }))
215
+ child.once('error', () => resolve({ code: null, signal: null }))
216
+ },
217
+ )
218
+
219
+ const holder: { bridge?: WindowsCdpBridge } = {}
220
+ const early: Buffer[] = []
221
+ const readyTimeout = options.readyTimeoutMs ?? options.params.launchTimeoutMs + 15_000
222
+ const ready = await new Promise<WindowsBridgeReady>((resolve, reject) => {
223
+ let settled = false
224
+ const settle = (fn: () => void) => {
225
+ if (settled) return
226
+ settled = true
227
+ clearTimeout(timer)
228
+ fn()
229
+ }
230
+ const timer = setTimeout(() => {
231
+ settle(() =>
232
+ reject(
233
+ new WindowsBridgeError(
234
+ 'bridge-timeout',
235
+ `powershell.exe did not report within ${readyTimeout} ms.${tail(stderrTail)}`,
236
+ ),
237
+ ),
238
+ )
239
+ }, readyTimeout)
240
+ const splitter = new LineSplitter((line) => {
241
+ if (line[0] === OPEN_BRACE) {
242
+ if (holder.bridge) holder.bridge.deliver(line)
243
+ else early.push(line)
244
+ return
245
+ }
246
+ if (!startsWith(line, CONTROL_PREFIX)) return
247
+ let control: Record<string, unknown>
248
+ try {
249
+ control = JSON.parse(line.subarray(CONTROL_PREFIX.length).toString('utf8'))
250
+ } catch {
251
+ return
252
+ }
253
+ if (control.type === 'ready')
254
+ settle(() => resolve(control as unknown as WindowsBridgeReady))
255
+ else if (control.type === 'error') {
256
+ settle(() =>
257
+ reject(
258
+ new WindowsBridgeError(
259
+ String(control.code ?? 'bridge-error'),
260
+ String(control.message ?? 'The bridge failed.'),
261
+ ),
262
+ ),
263
+ )
264
+ }
265
+ })
266
+ child.stdout.on('data', (chunk: Buffer) => splitter.push(chunk))
267
+ child.once('error', (error) => {
268
+ settle(() =>
269
+ reject(
270
+ new WindowsBridgeError(
271
+ 'spawn-failed',
272
+ `Could not start ${options.powershell}: ${error.message}`,
273
+ ),
274
+ ),
275
+ )
276
+ })
277
+ void exited.then(({ code }) => {
278
+ settle(() =>
279
+ reject(
280
+ new WindowsBridgeError(
281
+ 'bridge-exited',
282
+ `powershell.exe exited (code ${code}) before the browser was ready.${tail(stderrTail)}`,
283
+ ),
284
+ ),
285
+ )
286
+ })
287
+ }).catch((error: unknown) => {
288
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
289
+ throw error
290
+ })
291
+ holder.bridge = new WindowsCdpBridge(child, ready, exited, early, stderrTail)
292
+ return holder.bridge
293
+ }
294
+
295
+ private deliver(line: Buffer): void {
296
+ if (this.messageListener) this.messageListener(line)
297
+ else this.early.push(line)
298
+ }
299
+
300
+ /** Receive every CDP message from the browser, one per call, as UTF-8 JSON. */
301
+ onMessage(listener: (message: Buffer) => void): void {
302
+ this.messageListener = listener
303
+ const held = this.early.splice(0)
304
+ for (const line of held) listener(line)
305
+ }
306
+
307
+ /**
308
+ * Send one CDP message. A message with a raw newline (legal JSON
309
+ * whitespace, never produced by Playwright) is re-serialised so it stays
310
+ * one line.
311
+ */
312
+ send(message: string | Buffer): boolean {
313
+ if (!this.alive || this.child.stdin.destroyed) return false
314
+ let text = typeof message === 'string' ? message : message.toString('utf8')
315
+ if (text.includes('\n') || text.includes('\r')) text = JSON.stringify(JSON.parse(text))
316
+ this.child.stdin.write(`${text}\n`)
317
+ return true
318
+ }
319
+
320
+ /** Leave a browser this bridge started running when it exits. */
321
+ keepBrowser(): void {
322
+ if (this.alive && !this.child.stdin.destroyed) this.child.stdin.write('@namzu keep\n')
323
+ }
324
+
325
+ /**
326
+ * Close stdin and wait for the bridge to exit (it closes a browser it
327
+ * started unless told to keep it). Killed after `timeoutMs`.
328
+ */
329
+ async stop(timeoutMs = 15_000): Promise<void> {
330
+ if (!this.alive) return
331
+ this.child.stdin.end()
332
+ let timer: NodeJS.Timeout | undefined
333
+ const timedOut = new Promise<'timeout'>((resolve) => {
334
+ timer = setTimeout(() => resolve('timeout'), timeoutMs)
335
+ })
336
+ const outcome = await Promise.race([this.exited, timedOut])
337
+ clearTimeout(timer)
338
+ if (outcome === 'timeout') {
339
+ this.child.kill('SIGKILL')
340
+ await this.exited
341
+ }
342
+ }
343
+
344
+ /** The end of what `powershell.exe` wrote to stderr. */
345
+ get stderr(): string {
346
+ return this.stderrTail.join('')
347
+ }
348
+ }
349
+
350
+ function startsWith(line: Buffer, prefix: Buffer): boolean {
351
+ return line.length >= prefix.length && line.subarray(0, prefix.length).equals(prefix)
352
+ }
353
+
354
+ function tail(parts: readonly string[]): string {
355
+ const text = parts.join('').trim()
356
+ if (text.length === 0) return ''
357
+ return ` PowerShell said: ${text.length > 600 ? `…${text.slice(-600)}` : text}`
358
+ }
@@ -0,0 +1,208 @@
1
+ import { type Browser, type BrowserContext, type CDPSession, chromium } from 'playwright-core'
2
+ import type { WindowsCdpBrowserPlan } from './detect.js'
3
+ import { type CdpRelay, startCdpRelay } from './relay.js'
4
+ import { type StartWindowsBridgeOptions, WindowsCdpBridge } from './windows-bridge.js'
5
+
6
+ /**
7
+ * The `windows-cdp` engine: the Windows browser, started (or found) by the
8
+ * PowerShell bridge, driven by Playwright over CDP.
9
+ *
10
+ * Under NAT networking, WSL cannot reach Windows' `127.0.0.1`, so Playwright
11
+ * connects to a relay on WSL's `127.0.0.1` and every message crosses the
12
+ * bridge's standard streams. Under mirrored networking it first tries the
13
+ * browser's own port, and falls back to the relay when that does not answer.
14
+ * Either way the bridge process stays up: it is what closes a browser it
15
+ * started if this process dies.
16
+ */
17
+
18
+ export interface WindowsBrowserConnection {
19
+ readonly browser: Browser
20
+ readonly context: BrowserContext
21
+ readonly bridge: WindowsCdpBridge
22
+ /** `relay` through the bridge, or `direct` to the browser's port (mirrored networking). */
23
+ readonly transport: 'relay' | 'direct'
24
+ /** The profile's user data directory, as Windows sees it. */
25
+ readonly userDataDir: string
26
+ /** Whether the bridge started the browser (else it attached to one already running). */
27
+ readonly launched: boolean
28
+ /** Close the browser, then the connection. */
29
+ close(): Promise<void>
30
+ /** Disconnect and leave the browser running. */
31
+ detach(): Promise<void>
32
+ }
33
+
34
+ export interface ConnectWindowsBrowserOptions {
35
+ readonly plan: WindowsCdpBrowserPlan
36
+ readonly profile: string
37
+ /** The profile's user data directory (Windows path) when it is already known. */
38
+ readonly userDataDir?: string
39
+ /** Close a browser the bridge started if this process goes away. */
40
+ readonly closeOnExit: boolean
41
+ /** The environment `powershell.exe` is started with. */
42
+ readonly env: NodeJS.ProcessEnv
43
+ /** Default 60 000. */
44
+ readonly timeoutMs?: number
45
+ /** Called for each download the browser refuses, with its suggested file name. */
46
+ readonly onDownloadRefused?: (name: string) => void
47
+ /** For tests. */
48
+ readonly spawnProcess?: StartWindowsBridgeOptions['spawnProcess']
49
+ }
50
+
51
+ const DIRECT_CONNECT_TIMEOUT_MS = 3_000
52
+
53
+ /** The environment for `powershell.exe`: the caller's, plus the interop socket the plan found. */
54
+ export function windowsBridgeEnv(
55
+ plan: WindowsCdpBrowserPlan,
56
+ env: NodeJS.ProcessEnv,
57
+ ): NodeJS.ProcessEnv {
58
+ return plan.interopSocket ? { ...env, WSL_INTEROP: plan.interopSocket } : { ...env }
59
+ }
60
+
61
+ export async function connectWindowsBrowser(
62
+ options: ConnectWindowsBrowserOptions,
63
+ ): Promise<WindowsBrowserConnection> {
64
+ const { plan } = options
65
+ const timeoutMs = options.timeoutMs ?? 60_000
66
+ const bridge = await WindowsCdpBridge.start({
67
+ powershell: plan.powershell,
68
+ env: windowsBridgeEnv(plan, options.env),
69
+ params: {
70
+ executable: plan.windowsExecutable,
71
+ profile: options.profile,
72
+ ...(options.userDataDir ? { userDataDir: options.userDataDir } : {}),
73
+ headless: plan.headless,
74
+ closeOnExit: options.closeOnExit,
75
+ launchTimeoutMs: Math.max(5_000, timeoutMs - 15_000),
76
+ },
77
+ ...(options.spawnProcess ? { spawnProcess: options.spawnProcess } : {}),
78
+ })
79
+
80
+ let relay: CdpRelay | undefined
81
+ let browser: Browser | undefined
82
+ let transport: 'relay' | 'direct' = 'relay'
83
+ try {
84
+ if (plan.networkingMode === 'mirrored') {
85
+ browser = await chromium
86
+ .connectOverCDP(`ws://127.0.0.1:${bridge.ready.port}${bridge.ready.path}`, {
87
+ timeout: DIRECT_CONNECT_TIMEOUT_MS,
88
+ })
89
+ .catch(() => undefined)
90
+ if (browser) transport = 'direct'
91
+ }
92
+ if (!browser) {
93
+ relay = await startCdpRelay(bridge)
94
+ browser = await chromium.connectOverCDP(relay.url, { timeout: timeoutMs })
95
+ }
96
+ } catch (error) {
97
+ await relay?.close().catch(() => undefined)
98
+ // A browser the bridge started for a connection that never came up is
99
+ // not wanted: stopping the bridge closes it (when closeOnExit).
100
+ await bridge.stop().catch(() => undefined)
101
+ throw error
102
+ }
103
+
104
+ const context = browser.contexts()[0]
105
+ if (!context) {
106
+ await browser.close().catch(() => undefined)
107
+ await relay?.close().catch(() => undefined)
108
+ await bridge.stop().catch(() => undefined)
109
+ throw new Error('The Windows browser has no default context.')
110
+ }
111
+
112
+ // Playwright points the browser's downloads at a temporary directory on
113
+ // this side, which on Windows names a path that does not exist (or worse,
114
+ // one that does). Refuse downloads in the browser itself instead, and
115
+ // report each one.
116
+ let session: CDPSession | undefined
117
+ try {
118
+ session = await browser.newBrowserCDPSession()
119
+ await session.send('Browser.setDownloadBehavior', { behavior: 'deny', eventsEnabled: true })
120
+ session.on('Browser.downloadWillBegin', (event: { suggestedFilename?: string }) => {
121
+ options.onDownloadRefused?.(event.suggestedFilename ?? 'a file')
122
+ })
123
+ } catch (error) {
124
+ await browser.close().catch(() => undefined)
125
+ await relay?.close().catch(() => undefined)
126
+ await bridge.stop().catch(() => undefined)
127
+ throw error
128
+ }
129
+
130
+ let finished = false
131
+ const finish = async (closeBrowser: boolean): Promise<void> => {
132
+ if (finished) return
133
+ finished = true
134
+ if (closeBrowser) {
135
+ await session
136
+ ?.send('Browser.close')
137
+ .then(() => undefined)
138
+ .catch(() => undefined)
139
+ } else {
140
+ bridge.keepBrowser()
141
+ }
142
+ await browser?.close().catch(() => undefined)
143
+ await relay?.close().catch(() => undefined)
144
+ await bridge.stop().catch(() => undefined)
145
+ }
146
+ browser.on('disconnected', () => {
147
+ void relay?.close().catch(() => undefined)
148
+ })
149
+ void bridge.exited.then(() => {
150
+ if (finished) return
151
+ // The bridge went away on its own: killed, or its interop session
152
+ // ended. A Windows process whose WSL side is killed is not told, so
153
+ // the browser it started would stay up with nobody driving it. Under
154
+ // NAT the bridge was the only way to the browser, so the connection is
155
+ // gone too.
156
+ finished = true
157
+ if (transport === 'relay') void browser?.close().catch(() => undefined)
158
+ void relay?.close().catch(() => undefined)
159
+ if (bridge.ready.launched && options.closeOnExit) {
160
+ void closeWindowsBrowser(options, bridge.ready.userDataDir).catch(() => undefined)
161
+ }
162
+ })
163
+
164
+ return {
165
+ browser,
166
+ context,
167
+ bridge,
168
+ transport,
169
+ userDataDir: bridge.ready.userDataDir,
170
+ launched: bridge.ready.launched,
171
+ close: () => finish(true),
172
+ detach: () => finish(false),
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Close the browser running on `userDataDir` through a fresh bridge that
178
+ * only attaches (it never starts one): `Browser.close` over CDP, which lets
179
+ * the browser save the profile.
180
+ */
181
+ export async function closeWindowsBrowser(
182
+ options: Pick<ConnectWindowsBrowserOptions, 'plan' | 'profile' | 'env' | 'spawnProcess'>,
183
+ userDataDir: string,
184
+ ): Promise<boolean> {
185
+ let bridge: WindowsCdpBridge
186
+ try {
187
+ bridge = await WindowsCdpBridge.start({
188
+ powershell: options.plan.powershell,
189
+ env: windowsBridgeEnv(options.plan, options.env),
190
+ params: {
191
+ executable: options.plan.windowsExecutable,
192
+ profile: options.profile,
193
+ userDataDir,
194
+ headless: true,
195
+ closeOnExit: false,
196
+ launchTimeoutMs: 5_000,
197
+ attachOnly: true,
198
+ },
199
+ ...(options.spawnProcess ? { spawnProcess: options.spawnProcess } : {}),
200
+ })
201
+ } catch {
202
+ return false
203
+ }
204
+ bridge.send(JSON.stringify({ id: 1, method: 'Browser.close' }))
205
+ // The bridge exits by itself when the browser drops the connection.
206
+ await bridge.stop(10_000)
207
+ return true
208
+ }