@rushstack/playwright-browser-tunnel 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 (55) hide show
  1. package/.rush/temp/chunked-rush-logs/playwright-browser-tunnel._phase_build.chunks.jsonl +8 -0
  2. package/.rush/temp/operation/_phase_build/all.log +8 -0
  3. package/.rush/temp/operation/_phase_build/log-chunks.jsonl +8 -0
  4. package/.rush/temp/operation/_phase_build/state.json +3 -0
  5. package/.rush/temp/rushstack+playwright-browser-tunnel-_phase_build-83a085f61cdc0a4bb81c20aa939830fc5b5cff2f.tar.log +42 -0
  6. package/.rush/temp/shrinkwrap-deps.json +104 -0
  7. package/CHANGELOG.json +17 -0
  8. package/CHANGELOG.md +11 -0
  9. package/README.md +128 -0
  10. package/config/api-extractor.json +19 -0
  11. package/config/rig.json +7 -0
  12. package/dist/playwright-browser-tunnel.d.ts +276 -0
  13. package/eslint.config.js +18 -0
  14. package/lib/HttpServer.d.ts +20 -0
  15. package/lib/HttpServer.d.ts.map +1 -0
  16. package/lib/HttpServer.js +77 -0
  17. package/lib/HttpServer.js.map +1 -0
  18. package/lib/LaunchOptionsValidator.d.ts +93 -0
  19. package/lib/LaunchOptionsValidator.d.ts.map +1 -0
  20. package/lib/LaunchOptionsValidator.js +163 -0
  21. package/lib/LaunchOptionsValidator.js.map +1 -0
  22. package/lib/PlaywrightBrowserTunnel.d.ts +92 -0
  23. package/lib/PlaywrightBrowserTunnel.d.ts.map +1 -0
  24. package/lib/PlaywrightBrowserTunnel.js +468 -0
  25. package/lib/PlaywrightBrowserTunnel.js.map +1 -0
  26. package/lib/index.d.ts +23 -0
  27. package/lib/index.d.ts.map +1 -0
  28. package/lib/index.js +33 -0
  29. package/lib/index.js.map +1 -0
  30. package/lib/tsdoc-metadata.json +11 -0
  31. package/lib/tunneledBrowserConnection.d.ts +48 -0
  32. package/lib/tunneledBrowserConnection.d.ts.map +1 -0
  33. package/lib/tunneledBrowserConnection.js +216 -0
  34. package/lib/tunneledBrowserConnection.js.map +1 -0
  35. package/lib/utilities.d.ts +17 -0
  36. package/lib/utilities.d.ts.map +1 -0
  37. package/lib/utilities.js +41 -0
  38. package/lib/utilities.js.map +1 -0
  39. package/package.json +44 -0
  40. package/playwright.config.ts +45 -0
  41. package/rush-logs/playwright-browser-tunnel._phase_build.cache.log +3 -0
  42. package/rush-logs/playwright-browser-tunnel._phase_build.log +8 -0
  43. package/src/HttpServer.ts +87 -0
  44. package/src/LaunchOptionsValidator.ts +234 -0
  45. package/src/PlaywrightBrowserTunnel.ts +590 -0
  46. package/src/index.ts +38 -0
  47. package/src/tunneledBrowserConnection.ts +284 -0
  48. package/src/utilities.ts +42 -0
  49. package/temp/build/lint/_eslint-5eVG3S6w.json +30 -0
  50. package/temp/build/lint/lint.sarif +233 -0
  51. package/temp/build/typescript/ts_l9Fw4VUO.json +1 -0
  52. package/temp/playwright-browser-tunnel.api.md +120 -0
  53. package/tests/demo.spec.ts +10 -0
  54. package/tests/testFixture.ts +22 -0
  55. package/tsconfig.json +6 -0
@@ -0,0 +1,590 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+
4
+ import type { ChildProcess } from 'node:child_process';
5
+ import { once } from 'node:events';
6
+
7
+ import type { BrowserServer, BrowserType, LaunchOptions } from 'playwright-core';
8
+ import { type RawData, WebSocket, type WebSocketServer } from 'ws';
9
+ import semver from 'semver';
10
+
11
+ import { TerminalProviderSeverity, TerminalStreamWritable, type ITerminal } from '@rushstack/terminal';
12
+ import { Executable, FileSystem, Async } from '@rushstack/node-core-library';
13
+
14
+ import { getNormalizedErrorString } from './utilities';
15
+ import { LaunchOptionsValidator, type ILaunchOptionsValidationResult } from './LaunchOptionsValidator';
16
+
17
+ /**
18
+ * Allowed Playwright browser names.
19
+ * @beta
20
+ */
21
+ export type BrowserName = 'chromium' | 'firefox' | 'webkit';
22
+ const validBrowserNames: Set<string> = new Set(['chromium', 'firefox', 'webkit'] satisfies BrowserName[]);
23
+ function isValidBrowserName(browserName: string): browserName is BrowserName {
24
+ return validBrowserNames.has(browserName);
25
+ }
26
+
27
+ /**
28
+ * Status values reported by {@link PlaywrightTunnel}.
29
+ * @beta
30
+ */
31
+ export type TunnelStatus =
32
+ | 'waiting-for-connection'
33
+ | 'browser-server-running'
34
+ | 'stopped'
35
+ | 'setting-up-browser-server'
36
+ | 'error';
37
+
38
+ /**
39
+ * Handshake data exchanged during the initial WebSocket connection.
40
+ * @beta
41
+ */
42
+ export interface IHandshake {
43
+ action: 'handshake';
44
+ browserName: BrowserName;
45
+ launchOptions: LaunchOptions;
46
+ playwrightVersion: semver.SemVer;
47
+ }
48
+
49
+ type TunnelMode = 'poll-connection' | 'wait-for-incoming-connection';
50
+
51
+ /**
52
+ * Options for configuring a {@link PlaywrightTunnel} instance.
53
+ * @beta
54
+ */
55
+ export type IPlaywrightTunnelOptions = {
56
+ terminal: ITerminal;
57
+ onStatusChange: (status: TunnelStatus) => void;
58
+ playwrightInstallPath: string;
59
+ /**
60
+ * Optional callback invoked before launching the browser server.
61
+ * Receives the handshake data including launch options.
62
+ * If the callback returns false, the browser server launch will be aborted.
63
+ * This allows the client to prompt the user for approval before starting.
64
+ */
65
+ onBeforeLaunch?: (handshake: IHandshake) => Promise<boolean> | boolean;
66
+ } & (
67
+ | {
68
+ mode: 'poll-connection';
69
+ wsEndpoint: string;
70
+ }
71
+ | {
72
+ mode: 'wait-for-incoming-connection';
73
+ listenPort: number;
74
+ }
75
+ );
76
+
77
+ interface IBrowserServerProxy {
78
+ browserServer: BrowserServer;
79
+ client: WebSocket;
80
+ }
81
+
82
+ /**
83
+ * Hosts a Playwright browser server and forwards traffic over a WebSocket tunnel.
84
+ * @beta
85
+ */
86
+ export class PlaywrightTunnel {
87
+ private readonly _terminal: ITerminal;
88
+ private readonly _onStatusChange: (status: TunnelStatus) => void;
89
+ private readonly _onBeforeLaunch?: (handshake: IHandshake) => Promise<boolean> | boolean;
90
+ private readonly _playwrightBrowsersInstalled: Set<string> = new Set();
91
+ private readonly _wsEndpoint: string | undefined;
92
+ private readonly _listenPort: number | undefined;
93
+ private readonly _playwrightInstallPath: string;
94
+ private _status: TunnelStatus = 'stopped';
95
+ private _initWsPromise?: Promise<WebSocket>;
96
+ private _keepRunning: boolean = false;
97
+ private _ws?: WebSocket;
98
+ private _mode: TunnelMode;
99
+ private _pendingConnectionAttempt?: Promise<WebSocket>;
100
+ private _pollInterval?: NodeJS.Timeout;
101
+
102
+ public constructor(options: IPlaywrightTunnelOptions) {
103
+ const { mode, terminal, onStatusChange, playwrightInstallPath, onBeforeLaunch } = options;
104
+
105
+ switch (mode) {
106
+ case 'poll-connection':
107
+ if (!options.wsEndpoint) {
108
+ throw new Error('wsEndpoint is required for poll-connection mode');
109
+ }
110
+ this._wsEndpoint = options.wsEndpoint;
111
+ this._listenPort = undefined;
112
+ break;
113
+ case 'wait-for-incoming-connection':
114
+ if (options.listenPort === undefined) {
115
+ throw new Error('listenPort is required for wait-for-incoming-connection mode');
116
+ }
117
+ this._wsEndpoint = undefined;
118
+ this._listenPort = options.listenPort;
119
+ break;
120
+ default:
121
+ throw new Error(`Invalid mode: ${mode}`);
122
+ }
123
+
124
+ this._mode = mode;
125
+ this._terminal = terminal;
126
+ this._onStatusChange = onStatusChange;
127
+ this._onBeforeLaunch = onBeforeLaunch;
128
+ this._playwrightInstallPath = playwrightInstallPath;
129
+ }
130
+
131
+ public get status(): TunnelStatus {
132
+ return this._status;
133
+ }
134
+
135
+ // eslint-disable-next-line @typescript-eslint/naming-convention
136
+ private set status(newStatus: TunnelStatus) {
137
+ this._status = newStatus;
138
+ this._onStatusChange(newStatus);
139
+ }
140
+
141
+ public async waitForCloseAsync(): Promise<void> {
142
+ const terminal: ITerminal = this._terminal;
143
+ const initWsPromise: Promise<WebSocket> | undefined = this._initWsPromise;
144
+ if (initWsPromise) {
145
+ const ws: WebSocket = await initWsPromise;
146
+ await once(ws, 'close');
147
+ terminal.writeDebugLine('WebSocket connection closed. resolving init promise.');
148
+ this._initWsPromise = undefined;
149
+ }
150
+ }
151
+
152
+ public async startAsync(options: { keepRunning?: boolean } = {}): Promise<void> {
153
+ this._keepRunning = options.keepRunning ?? true;
154
+ const terminal: ITerminal = this._terminal;
155
+ terminal.writeLine(`keepRunning: ${this._keepRunning}`);
156
+ while (this._keepRunning) {
157
+ if (!this._initWsPromise) {
158
+ this._initWsPromise = this._initPlaywrightBrowserTunnelAsync();
159
+ } else {
160
+ terminal.writeLine(`Tunnel is already running with status: ${this.status}`);
161
+ }
162
+ await this.waitForCloseAsync();
163
+ }
164
+ }
165
+
166
+ public async stopAsync(): Promise<void> {
167
+ this._keepRunning = false;
168
+ if (this._pollInterval) {
169
+ clearInterval(this._pollInterval);
170
+ this._pollInterval = undefined;
171
+ }
172
+ await this._initWsPromise?.finally(() => {
173
+ this._ws?.close();
174
+ });
175
+ }
176
+
177
+ public async [Symbol.asyncDispose](): Promise<void> {
178
+ this._terminal.writeLine('Disposing WebSocket connection.');
179
+ await this.stopAsync();
180
+ }
181
+
182
+ public async cleanTempFilesAsync(): Promise<void> {
183
+ const tmpPath: string = this._playwrightInstallPath;
184
+ this._terminal.writeLine(`Cleaning up temporary files in ${tmpPath}`);
185
+ try {
186
+ await FileSystem.ensureEmptyFolderAsync(tmpPath);
187
+ this._terminal.writeLine(`Temporary files cleaned up.`);
188
+ } catch (error) {
189
+ this._terminal.writeLine(`Failed to clean up temporary files: ${getNormalizedErrorString(error)}`);
190
+ }
191
+ }
192
+
193
+ // TODO: We should implement an uninstall command to remove installed Playwright browsers
194
+ // public async uninstallPlaywrightBrowsersAsync(): Promise<void> {}
195
+
196
+ private async _runCommandAsync(command: string, args: string[]): Promise<void> {
197
+ const tmpPath: string = this._playwrightInstallPath;
198
+ await FileSystem.ensureFolderAsync(tmpPath);
199
+ this._terminal.writeLine(`Running command: ${command} ${args.join(' ')} in ${tmpPath}`);
200
+
201
+ const cp: ChildProcess = Executable.spawn(command, args, {
202
+ stdio: [
203
+ 'ignore', // stdin
204
+ 'pipe', // stdout
205
+ 'pipe' // stderr
206
+ ],
207
+ currentWorkingDirectory: tmpPath
208
+ });
209
+
210
+ cp.stdout?.pipe(
211
+ new TerminalStreamWritable({
212
+ terminal: this._terminal,
213
+ severity: TerminalProviderSeverity.log
214
+ })
215
+ );
216
+ cp.stderr?.pipe(
217
+ new TerminalStreamWritable({
218
+ terminal: this._terminal,
219
+ severity: TerminalProviderSeverity.error
220
+ })
221
+ );
222
+
223
+ await Executable.waitForExitAsync(cp, { throwOnNonZeroExitCode: true, throwOnSignal: true });
224
+ }
225
+
226
+ private async _installPlaywrightCoreAsync({
227
+ playwrightVersion
228
+ }: Pick<IHandshake, 'playwrightVersion'>): Promise<void> {
229
+ this._terminal.writeLine(`Installing playwright-core version ${playwrightVersion}`);
230
+ await this._runCommandAsync('npm', [
231
+ 'install',
232
+ `playwright-core-${playwrightVersion}@npm:playwright-core@${playwrightVersion}`
233
+ ]);
234
+ }
235
+
236
+ private async _installPlaywrightBrowsersAsync({
237
+ playwrightVersion,
238
+ browserName
239
+ }: Pick<IHandshake, 'playwrightVersion' | 'browserName'>): Promise<void> {
240
+ await this._installPlaywrightCoreAsync({ playwrightVersion });
241
+ this._terminal.writeLine(`Executing playwright-core version ${playwrightVersion}`);
242
+ await this._runCommandAsync('node', [
243
+ `node_modules/playwright-core-${playwrightVersion}/cli.js`,
244
+ 'install',
245
+ browserName
246
+ ]);
247
+ }
248
+
249
+ private async _tryConnectAsync(): Promise<WebSocket> {
250
+ const wsEndpoint: string | undefined = this._wsEndpoint;
251
+ if (!wsEndpoint) {
252
+ throw new Error('WebSocket endpoint is not defined');
253
+ }
254
+ return await new Promise<WebSocket>((resolve, reject) => {
255
+ const ws: WebSocket = new WebSocket(wsEndpoint);
256
+ ws.on('open', () => {
257
+ this._terminal.writeLine(`WebSocket connection opened`);
258
+ resolve(ws);
259
+ });
260
+ ws.once('error', (error) => {
261
+ reject(error);
262
+ });
263
+ });
264
+ }
265
+
266
+ // TODO: Only supporting one test at a time.
267
+ // Need to support multiple simultaneous connections for parallel tests.
268
+ private async _pollConnectionAsync(): Promise<WebSocket> {
269
+ this._terminal.writeLine(`Waiting for WebSocket connection`);
270
+ return await new Promise((resolve, reject) => {
271
+ this._pollInterval = setInterval(() => {
272
+ if (this._pendingConnectionAttempt) {
273
+ return; // Skip if a connection attempt is already in progress
274
+ }
275
+ const connectionPromise: Promise<WebSocket> = this._tryConnectAsync();
276
+ this._pendingConnectionAttempt = connectionPromise;
277
+ connectionPromise
278
+ .then((ws: WebSocket) => {
279
+ clearInterval(this._pollInterval);
280
+ this._pollInterval = undefined;
281
+ ws.removeAllListeners();
282
+ this._pendingConnectionAttempt = undefined;
283
+ resolve(ws);
284
+ })
285
+ .catch(() => {
286
+ // no-op - will retry on next interval
287
+ this._pendingConnectionAttempt = undefined;
288
+ });
289
+ }, 500);
290
+ });
291
+ }
292
+
293
+ private async _waitForIncomingConnectionAsync(): Promise<WebSocket> {
294
+ this._terminal.writeLine('Waiting for incoming WebSocket connection');
295
+
296
+ return await new Promise<WebSocket>((resolve, reject) => {
297
+ const server: WebSocketServer = new WebSocket.Server({ port: this._listenPort });
298
+
299
+ const cleanup = (): void => {
300
+ server.removeAllListeners();
301
+ };
302
+
303
+ server.once('connection', (ws) => {
304
+ this._terminal.writeLine('Incoming WebSocket connection established');
305
+
306
+ // Stop listening immediately so the port is released
307
+ cleanup();
308
+ server.close((closeError?: Error) => {
309
+ if (closeError) {
310
+ this._terminal.writeLine(
311
+ `Failed to close WebSocket server: ${
312
+ closeError instanceof Error ? closeError.message : closeError
313
+ }`
314
+ );
315
+ }
316
+ resolve(ws);
317
+ });
318
+ });
319
+
320
+ server.once('error', (error) => {
321
+ this._terminal.writeLine(`WebSocket server error: ${getNormalizedErrorString(error)}`);
322
+
323
+ cleanup();
324
+ // Try to close (best-effort), then reject
325
+ server.close(() => reject(error));
326
+ });
327
+ });
328
+ }
329
+
330
+ // TODO: If a user runs this for the first time, `this._playwrightBrowsersInstalled` will be empty
331
+ // and it will try to install the browsers every time. We should persist this information. Maybe a cache file with text per
332
+ // machine instance?
333
+ private async _setupPlaywrightAsync({
334
+ playwrightVersion,
335
+ browserName
336
+ }: Pick<IHandshake, 'playwrightVersion' | 'browserName'>): Promise<typeof import('playwright-core')> {
337
+ const browserKey: string = `${playwrightVersion}-${browserName}`;
338
+ this._terminal.writeLine(`Checking for installed playwright browsers. Installed browsers: ${browserKey}`);
339
+ if (!this._playwrightBrowsersInstalled.has(browserKey)) {
340
+ this._terminal.writeLine(
341
+ `Playwright browser not found. Installing playwright-core version ${playwrightVersion}`
342
+ );
343
+ await this._installPlaywrightBrowsersAsync({ playwrightVersion, browserName });
344
+ this._playwrightBrowsersInstalled.add(browserKey);
345
+ }
346
+
347
+ this._terminal.writeLine(`Using playwright-core version ${playwrightVersion} for browser server`);
348
+ return await import(`${this._playwrightInstallPath}/node_modules/playwright-core-${playwrightVersion}`);
349
+ }
350
+
351
+ private async _getPlaywrightBrowserServerProxyAsync({
352
+ browserName,
353
+ playwrightVersion,
354
+ launchOptions
355
+ }: Pick<IHandshake, 'playwrightVersion' | 'browserName' | 'launchOptions'>): Promise<IBrowserServerProxy> {
356
+ const terminal: ITerminal = this._terminal;
357
+
358
+ // Validate launch options against security allowlist
359
+ terminal.writeLine('Validating launch options against security allowlist...');
360
+ const validationResult: ILaunchOptionsValidationResult =
361
+ await LaunchOptionsValidator.validateLaunchOptionsAsync(launchOptions, terminal);
362
+
363
+ if (!validationResult.isValid) {
364
+ terminal.writeWarningLine(
365
+ `Some launch options were denied: ${validationResult.deniedOptions.join(', ')}`
366
+ );
367
+ terminal.writeWarningLine(`Using filtered launch options. Denied options have been removed.`);
368
+ }
369
+
370
+ // Use filtered options and ensure headless: false for headed tests in codespaces
371
+ // This is critical for the extension's purpose - enabling headed Playwright tests remotely
372
+ const safeOptions: LaunchOptions = {
373
+ ...validationResult.filteredOptions,
374
+ headless: false
375
+ };
376
+
377
+ // Log the validated options, excluding 'headless' since it's always false for this extension
378
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
379
+ const { headless, ...logOptions } = safeOptions;
380
+ terminal.writeLine(
381
+ `Launch options after validation: ${JSON.stringify(logOptions)} (headless: false enforced)`
382
+ );
383
+
384
+ const playwright: typeof import('playwright-core') = await this._setupPlaywrightAsync({
385
+ playwrightVersion,
386
+ browserName
387
+ });
388
+
389
+ const { chromium, firefox, webkit } = playwright;
390
+ const browsers: Record<BrowserName, BrowserType> = { chromium, firefox, webkit };
391
+
392
+ const browserServer: BrowserServer = await browsers[browserName].launchServer(safeOptions);
393
+
394
+ if (!browserServer) {
395
+ throw new Error(
396
+ `Failed to launch browser server for ${browserName} with options: ${JSON.stringify(safeOptions)}`
397
+ );
398
+ }
399
+
400
+ terminal.writeLine(`Launched ${browserName} browser server`);
401
+ const client: WebSocket = new WebSocket(browserServer.wsEndpoint());
402
+
403
+ return {
404
+ browserServer,
405
+ client
406
+ };
407
+ }
408
+
409
+ private _validateHandshake(rawHandshake: unknown): IHandshake {
410
+ if (
411
+ typeof rawHandshake !== 'object' ||
412
+ rawHandshake === null ||
413
+ 'action' in rawHandshake === false ||
414
+ 'browserName' in rawHandshake === false ||
415
+ 'playwrightVersion' in rawHandshake === false ||
416
+ 'launchOptions' in rawHandshake === false ||
417
+ typeof rawHandshake.action !== 'string' ||
418
+ typeof rawHandshake.browserName !== 'string' ||
419
+ typeof rawHandshake.playwrightVersion !== 'string' ||
420
+ typeof rawHandshake.launchOptions !== 'object'
421
+ ) {
422
+ throw new Error(`Invalid handshake: ${JSON.stringify(rawHandshake)}. Must be an object.`);
423
+ }
424
+
425
+ const { action, browserName, playwrightVersion, launchOptions } = rawHandshake;
426
+
427
+ if (action !== 'handshake') {
428
+ throw new Error(`Invalid action: ${action}. Expected 'handshake'.`);
429
+ }
430
+ const playwrightVersionSemver: semver.SemVer | null = semver.coerce(playwrightVersion);
431
+ if (!playwrightVersionSemver) {
432
+ throw new Error(`Invalid Playwright version: ${playwrightVersion}. Must be a valid semver version.`);
433
+ }
434
+ if (!isValidBrowserName(browserName)) {
435
+ throw new Error(
436
+ `Invalid browser name: ${browserName}. Must be one of ${Array.from(validBrowserNames).join(', ')}.`
437
+ );
438
+ }
439
+
440
+ return {
441
+ action,
442
+ launchOptions: launchOptions as LaunchOptions,
443
+ playwrightVersion: playwrightVersionSemver,
444
+ browserName
445
+ };
446
+ }
447
+
448
+ // ws1 is the tunnel websocket, ws2 is the browser server websocket
449
+ private async _setupForwardingAsync(ws1: WebSocket, ws2: WebSocket): Promise<void> {
450
+ this._terminal.writeLine('Setting up message forwarding between ws1 and ws2');
451
+ ws1.on('message', (data) => {
452
+ if (ws2.readyState === WebSocket.OPEN) {
453
+ ws2.send(data);
454
+ } else {
455
+ this._terminal.writeLine('ws2 is not open. Dropping message.');
456
+ }
457
+ });
458
+ ws2.on('message', (data) => {
459
+ if (ws1.readyState === WebSocket.OPEN) {
460
+ ws1.send(data);
461
+ } else {
462
+ this._terminal.writeLine('ws1 is not open. Dropping message.');
463
+ }
464
+ });
465
+
466
+ ws1.once('close', () => {
467
+ if (ws2.readyState === WebSocket.OPEN) {
468
+ ws2.close();
469
+ }
470
+ });
471
+ ws2.once('close', () => {
472
+ if (ws1.readyState === WebSocket.OPEN) {
473
+ ws1.close();
474
+ }
475
+ });
476
+
477
+ ws1.once('error', (error) => {
478
+ this._terminal.writeLine(`WebSocket error: ${getNormalizedErrorString(error)}`);
479
+ });
480
+ ws2.once('error', (error) => {
481
+ this._terminal.writeLine(`WebSocket error: ${getNormalizedErrorString(error)}`);
482
+ });
483
+ }
484
+
485
+ /**
486
+ * Initializes the Playwright browser tunnel by establishing a WebSocket connection
487
+ * and setting up the browser server.
488
+ * Returns when the handshake is complete and the browser server is running.
489
+ */
490
+ private async _initPlaywrightBrowserTunnelAsync(): Promise<WebSocket> {
491
+ let handshake: IHandshake | undefined = undefined;
492
+ let client: WebSocket | undefined = undefined;
493
+ let browserServer: BrowserServer | undefined = undefined;
494
+
495
+ this.status = 'waiting-for-connection';
496
+ const ws: WebSocket =
497
+ this._mode === 'poll-connection'
498
+ ? await this._pollConnectionAsync()
499
+ : await this._waitForIncomingConnectionAsync();
500
+
501
+ ws.on('open', () => {
502
+ this._terminal.writeLine(`WebSocket connection established`);
503
+ handshake = undefined;
504
+ });
505
+
506
+ ws.on('error', (error) => {
507
+ this._terminal.writeLine(`WebSocket error occurred: ${getNormalizedErrorString(error)}`);
508
+ });
509
+
510
+ ws.on('close', async () => {
511
+ this._initWsPromise = undefined;
512
+ this.status = 'stopped';
513
+ this._terminal.writeLine('WebSocket connection closed');
514
+ await browserServer?.close();
515
+ });
516
+
517
+ return await new Promise<WebSocket>((resolve, reject) => {
518
+ const onMessageHandler = async (data: RawData): Promise<void> => {
519
+ const terminal: ITerminal = this._terminal;
520
+ if (!handshake) {
521
+ try {
522
+ const rawHandshakeString: string = data.toString();
523
+ const rawHandshake: unknown = JSON.parse(rawHandshakeString);
524
+ terminal.writeLine(`Received handshake: ${rawHandshakeString}`);
525
+ handshake = this._validateHandshake(rawHandshake);
526
+
527
+ // Call the onBeforeLaunch callback if provided
528
+ if (this._onBeforeLaunch) {
529
+ terminal.writeLine('Requesting user approval before launching browser server...');
530
+ const shouldProceed: boolean = await this._onBeforeLaunch(handshake);
531
+ if (!shouldProceed) {
532
+ terminal.writeLine('Browser server launch cancelled by user.');
533
+ ws.off('message', onMessageHandler);
534
+ ws.close();
535
+ reject(new Error('Browser server launch cancelled by user'));
536
+ return;
537
+ }
538
+ terminal.writeLine('User approved browser server launch.');
539
+ }
540
+
541
+ this.status = 'setting-up-browser-server';
542
+ const browserServerProxy: IBrowserServerProxy =
543
+ await this._getPlaywrightBrowserServerProxyAsync(handshake);
544
+ client = browserServerProxy.client;
545
+ browserServer = browserServerProxy.browserServer;
546
+
547
+ this.status = 'browser-server-running';
548
+
549
+ // Send ack so that the counterpart also knows to start forwarding messages.
550
+ // NOTE: The 1-second delay is an intentional workaround. In the current
551
+ // protocol, the remote tunnel endpoint does not expose an explicit "ready"
552
+ // signal for when it has finished initializing its own forwarding logic
553
+ // after receiving the initial handshake. This
554
+ // delay avoids races where early messages could be dropped or mishandled
555
+ // if they arrive before the remote side is fully ready.
556
+ //
557
+ // TODO: A future improvement would be to replace this delay with a deterministic
558
+ // synchronization mechanism (e.g. an explicit "ready" message or event)
559
+ // instead of relying on a fixed timeout.
560
+ await Async.sleepAsync(2000);
561
+
562
+ ws.send(JSON.stringify({ action: 'handshakeAck' }));
563
+ await this._setupForwardingAsync(ws, client);
564
+
565
+ // Clean up message handler after successful handshake
566
+ ws.off('message', onMessageHandler);
567
+ resolve(ws);
568
+ } catch (error) {
569
+ terminal.writeLine(`Error processing handshake: ${error}`);
570
+ this.status = 'error';
571
+
572
+ // Cleanup and close connection on error
573
+ ws.off('message', onMessageHandler);
574
+ ws.close();
575
+ reject(error);
576
+ return;
577
+ }
578
+ } else {
579
+ if (!client) {
580
+ terminal.writeLine('Browser WebSocket client is not initialized.');
581
+ ws.off('message', onMessageHandler);
582
+ ws.close();
583
+ return;
584
+ }
585
+ }
586
+ };
587
+ ws.on('message', onMessageHandler);
588
+ });
589
+ }
590
+ }
package/src/index.ts ADDED
@@ -0,0 +1,38 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+
4
+ /**
5
+ * Run a Playwright browser server in one environment and drive it from another environment by
6
+ * forwarding Playwright's WebSocket traffic through a tunnel.
7
+ *
8
+ * @remarks
9
+ * This package is intended for remote development and CI scenarios (for example: Codespaces,
10
+ * devcontainers, or a separate "browser host" machine) where you want tests to run in one
11
+ * environment but the actual browser process to run in another.
12
+ *
13
+ * The package provides two main APIs:
14
+ * - {@link PlaywrightTunnel} - Run on the browser host to launch the real browser server and forward messages
15
+ * - {@link tunneledBrowserConnection} - Run on the test runner to create a local endpoint that your Playwright client can connect to
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+
20
+ export { PlaywrightTunnel } from './PlaywrightBrowserTunnel';
21
+ export type {
22
+ BrowserName,
23
+ TunnelStatus,
24
+ IPlaywrightTunnelOptions,
25
+ IHandshake
26
+ } from './PlaywrightBrowserTunnel';
27
+ export { createTunneledBrowserAsync, tunneledBrowserConnection } from './tunneledBrowserConnection';
28
+ export type {
29
+ IDisposableTunneledBrowserConnection,
30
+ IDisposableTunneledBrowser
31
+ } from './tunneledBrowserConnection';
32
+ export {
33
+ isExtensionInstalledAsync,
34
+ EXTENSION_INSTALLED_FILENAME,
35
+ getNormalizedErrorString
36
+ } from './utilities';
37
+ export { LaunchOptionsValidator, LAUNCH_OPTIONS_ALLOWLIST_FILENAME } from './LaunchOptionsValidator';
38
+ export type { ILaunchOptionsAllowlist, ILaunchOptionsValidationResult } from './LaunchOptionsValidator';