Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore: remove HMR support from trace viewer (#37785)

Pavel Feldman47fbd3a51a89
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a945d57263..67468d397d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -31,16 +31,6 @@ npm run watch
npx playwright install
```
-**Experimental dev mode with Hot Module Replacement for recorder/trace-viewer/UI Mode**
-
-```
-PW_HMR=1 npm run watch
-PW_HMR=1 npx playwright show-trace
-PW_HMR=1 npm run ctest -- --ui
-PW_HMR=1 npx playwright codegen
-PW_HMR=1 npx playwright show-report
-```
-
Playwright is a multi-package repository that uses npm workspaces. For browser APIs, look at [`packages/playwright-core`](https://github.com/microsoft/playwright/blob/main/packages/playwright-core). For test runner, see [`packages/playwright`](https://github.com/microsoft/playwright/blob/main/packages/playwright).
Note that some files are generated by the build, so the watch process might override your changes if done in the wrong file. For example, TypeScript types for the API are generated from the [`docs/src`](https://github.com/microsoft/playwright/blob/main/docs/src).
diff --git a/packages/playwright-core/src/server/recorder/recorderApp.ts b/packages/playwright-core/src/server/recorder/recorderApp.ts
index 5d1ffb81bd..a216dc7006 100644
--- a/packages/playwright-core/src/server/recorder/recorderApp.ts
+++ b/packages/playwright-core/src/server/recorder/recorderApp.ts
@@ -107,7 +107,7 @@ export class RecorderApp {
delete (inspectedContext as any)[recorderAppSymbol];
});
- await this._page.mainFrame().goto(progress, process.env.PW_HMR ? 'http://localhost:44225' : 'https://playwright/index.html');
+ await this._page.mainFrame().goto(progress, 'https://playwright/index.html');
});
const url = this._recorder.url();
diff --git a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
index 48a504209a..53438cf7c0 100644
--- a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
+++ b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts
@@ -69,10 +69,6 @@ export async function startTraceViewerServer(options?: TraceViewerServerOptions)
server.routePrefix('/trace', (request, response) => {
const url = new URL('http://localhost' + request.url!);
const relativePath = url.pathname.slice('/trace'.length);
- if (process.env.PW_HMR) {
- // When running in Vite HMR mode, port is hardcoded in build.js
- response.appendHeader('Access-Control-Allow-Origin', 'http://localhost:44223');
- }
if (relativePath.endsWith('/stall.js'))
return true;
if (relativePath.startsWith('/file')) {
@@ -131,13 +127,7 @@ export async function installRootRedirect(server: HttpServer, traceUrl: string |
for (const reporter of options.reporter || [])
params.append('reporter', reporter);
- let baseUrl = '.';
- if (process.env.PW_HMR) {
- baseUrl = 'http://localhost:44223'; // port is hardcoded in build.js
- params.set('server', server.urlPrefix('precise'));
- }
-
- const urlPath = `${baseUrl}/trace/${options.webApp || 'index.html'}?${params.toString()}`;
+ const urlPath = `./trace/${options.webApp || 'index.html'}?${params.toString()}`;
server.routePath('/', (_, response) => {
response.statusCode = 302;
response.setHeader('Location', urlPath);
diff --git a/packages/playwright/src/reporters/html.ts b/packages/playwright/src/reporters/html.ts
index 22d2a144de..898034c2e6 100644
--- a/packages/playwright/src/reporters/html.ts
+++ b/packages/playwright/src/reporters/html.ts
@@ -315,31 +315,6 @@ class HtmlBuilder {
singleTestId = testFile.tests[0].testId;
}
- if (process.env.PW_HMR === '1') {
- const redirectFile = path.join(this._reportFolder, 'index.html');
-
- await this._writeReportData(redirectFile);
-
- async function redirect() {
- const hmrURL = new URL('http://localhost:44224'); // dev server, port is harcoded in build.js
- const popup = window.open(hmrURL);
- const listener = (evt: MessageEvent) => {
- if (evt.source === popup && evt.data === 'ready') {
- const element = document.getElementById('playwrightReportBase64');
- popup!.postMessage(element?.textContent ?? '', hmrURL.origin);
- window.removeEventListener('message', listener);
- // This is generally not allowed
- window.close();
- }
- };
- window.addEventListener('message', listener);
- }
-
- fs.appendFileSync(redirectFile, `<script>(${redirect.toString()})()</script>`);
-
- return { ok, singleTestId };
- }
-
// Copy app.
const appFolder = path.join(require.resolve('playwright-core'), '..', 'lib', 'vite', 'htmlReport');
await copyFileAndMakeWritable(path.join(appFolder, 'index.html'), path.join(this._reportFolder, 'index.html'));
diff --git a/packages/trace-viewer/src/sw/main.ts b/packages/trace-viewer/src/sw/main.ts
index 64d22a4263..731cb8e552 100644
--- a/packages/trace-viewer/src/sw/main.ts
+++ b/packages/trace-viewer/src/sw/main.ts
@@ -18,7 +18,7 @@ import { splitProgress } from './progress';
import { unwrapPopoutUrl } from './snapshotRenderer';
import { SnapshotServer } from './snapshotServer';
import { TraceModel } from './traceModel';
-import { FetchTraceModelBackend, TraceViewerServer, ZipTraceModelBackend } from './traceModelBackends';
+import { FetchTraceModelBackend, traceFileURL, ZipTraceModelBackend } from './traceModelBackends';
import { TraceVersionError } from './traceModernizer';
// @ts-ignore
@@ -33,28 +33,19 @@ self.addEventListener('activate', function(event: any) {
});
const scopePath = new URL(self.registration.scope).pathname;
-
const loadedTraces = new Map<string, { traceModel: TraceModel, snapshotServer: SnapshotServer }>();
-
-type ClientData = {
- traceUrl: string;
- traceViewerServer: TraceViewerServer
-};
-const clientIdToTraceUrls = new Map<string, ClientData>();
+const clientIdToTraceUrls = new Map<string, string>();
async function loadTrace(traceUrl: string, traceFileName: string | null, client: any | undefined, progress: (done: number, total: number) => undefined): Promise<TraceModel> {
const clientId = client?.id ?? '';
- const clientURL = new URL(client?.url ?? self.registration.scope);
- const traceViewerServerBaseUrl = new URL(clientURL.searchParams.get('server') ?? '../', clientURL);
- const data: ClientData = { traceUrl, traceViewerServer: new TraceViewerServer(traceViewerServerBaseUrl) };
- clientIdToTraceUrls.set(clientId, data);
+ clientIdToTraceUrls.set(clientId, traceUrl);
await gc();
const traceModel = new TraceModel();
try {
// Allow 10% to hop from sw to page.
const [fetchProgress, unzipProgress] = splitProgress(progress, [0.5, 0.4, 0.1]);
- const backend = traceUrl.endsWith('json') ? new FetchTraceModelBackend(traceUrl, data.traceViewerServer) : new ZipTraceModelBackend(traceUrl, data.traceViewerServer, fetchProgress);
+ const backend = traceUrl.endsWith('json') ? new FetchTraceModelBackend(traceUrl) : new ZipTraceModelBackend(traceUrl, fetchProgress);
await traceModel.load(backend, unzipProgress);
} catch (error: any) {
// eslint-disable-next-line no-console
@@ -161,11 +152,9 @@ async function doFetch(event: FetchEvent): Promise<Response> {
if (relativePath.startsWith('/file/')) {
const path = url.searchParams.get('path')!;
- const traceViewerServer = clientIdToTraceUrls.get(event.clientId ?? '')?.traceViewerServer;
- if (!traceViewerServer)
- throw new Error('client is not initialized');
- const response = await traceViewerServer.readFile(path);
- if (!response)
+ const fileURL = traceFileURL(path);
+ const response = await fetch(fileURL);
+ if (response.status === 404)
return new Response(null, { status: 404 });
return response;
}
@@ -202,13 +191,13 @@ async function gc() {
const clients = await self.clients.matchAll();
const usedTraces = new Set<string>();
- for (const [clientId, data] of clientIdToTraceUrls) {
+ for (const [clientId, traceUrl] of clientIdToTraceUrls) {
// @ts-ignore
if (!clients.find(c => c.id === clientId)) {
clientIdToTraceUrls.delete(clientId);
continue;
}
- usedTraces.add(data.traceUrl);
+ usedTraces.add(traceUrl);
}
for (const traceUrl of loadedTraces.keys()) {
diff --git a/packages/trace-viewer/src/sw/traceModelBackends.ts b/packages/trace-viewer/src/sw/traceModelBackends.ts
index 91aad60c9a..da60e9c1e9 100644
--- a/packages/trace-viewer/src/sw/traceModelBackends.ts
+++ b/packages/trace-viewer/src/sw/traceModelBackends.ts
@@ -28,11 +28,12 @@ export class ZipTraceModelBackend implements TraceModelBackend {
private _entriesPromise: Promise<Map<string, zip.Entry>>;
private _traceURL: string;
- constructor(traceURL: string, server: TraceViewerServer, progress: Progress) {
+ constructor(traceURL: string, progress: Progress) {
this._traceURL = traceURL;
zipjs.configure({ baseURL: self.location.href } as any);
+
this._zipReader = new zipjs.ZipReader(
- new zipjs.HttpReader(formatUrl(traceURL, server), { mode: 'cors', preventHeadRequest: true } as any),
+ new zipjs.HttpReader(this._resolveTraceURL(traceURL), { mode: 'cors', preventHeadRequest: true } as any),
{ useWebWorkers: false });
this._entriesPromise = this._zipReader.getEntries({ onprogress: progress }).then(entries => {
const map = new Map<string, zip.Entry>();
@@ -42,6 +43,18 @@ export class ZipTraceModelBackend implements TraceModelBackend {
});
}
+ private _resolveTraceURL(traceURL: string): string {
+ let url: string;
+ if (traceURL.startsWith('http') || traceURL.startsWith('blob')) {
+ url = traceURL;
+ if (url.startsWith('https://www.dropbox.com/'))
+ url = 'https://dl.dropboxusercontent.com/' + url.substring('https://www.dropbox.com/'.length);
+ } else {
+ url = traceFileURL(traceURL);
+ }
+ return url;
+ }
+
isLive() {
return false;
}
@@ -84,12 +97,10 @@ export class ZipTraceModelBackend implements TraceModelBackend {
export class FetchTraceModelBackend implements TraceModelBackend {
private _entriesPromise: Promise<Map<string, string>>;
private _path: string;
- private _server: TraceViewerServer;
- constructor(path: string, server: TraceViewerServer) {
+ constructor(path: string) {
this._path = path;
- this._server = server;
- this._entriesPromise = server.readFile(path).then(async response => {
+ this._entriesPromise = this._readFile(path).then(async response => {
if (!response)
throw new Error('File not found');
const json = await response.json();
@@ -133,31 +144,17 @@ export class FetchTraceModelBackend implements TraceModelBackend {
const fileName = entries.get(entryName);
if (!fileName)
return;
- return this._server.readFile(fileName);
+ return this._readFile(fileName);
}
-}
-
-function formatUrl(trace: string, server: TraceViewerServer) {
- let url = trace.startsWith('http') || trace.startsWith('blob') ? trace : server.getFileURL(trace).toString();
- // Dropbox does not support cors.
- if (url.startsWith('https://www.dropbox.com/'))
- url = 'https://dl.dropboxusercontent.com/' + url.substring('https://www.dropbox.com/'.length);
- return url;
-}
-export class TraceViewerServer {
- constructor(private readonly baseUrl: URL) {}
-
- getFileURL(path: string): URL {
- const url = new URL('trace/file', this.baseUrl);
- url.searchParams.set('path', path);
- return url;
- }
-
- async readFile(path: string): Promise<Response | undefined> {
- const response = await fetch(this.getFileURL(path));
+ private async _readFile(path: string): Promise<Response | undefined> {
+ const response = await fetch(traceFileURL(path));
if (response.status === 404)
return;
return response;
}
}
+
+export function traceFileURL(path: string): string {
+ return `file?path=${encodeURIComponent(path)}`;
+}
diff --git a/packages/trace-viewer/src/ui/snapshotTab.tsx b/packages/trace-viewer/src/ui/snapshotTab.tsx
index 041a4e988f..ce0f1d6890 100644
--- a/packages/trace-viewer/src/ui/snapshotTab.tsx
+++ b/packages/trace-viewer/src/ui/snapshotTab.tsx
@@ -412,7 +412,6 @@ export function collectSnapshots(action: ActionTraceEvent | undefined): Snapshot
}
const isUnderTest = new URLSearchParams(window.location.search).has('isUnderTest');
-const serverParam = new URLSearchParams(window.location.search).get('server');
export function extendSnapshot(traceUrl: string, snapshot: Snapshot, shouldPopulateCanvasFromScreenshot: boolean): SnapshotUrls {
const params = new URLSearchParams();
@@ -434,8 +433,6 @@ export function extendSnapshot(traceUrl: string, snapshot: Snapshot, shouldPopul
const popoutParams = new URLSearchParams();
popoutParams.set('r', snapshotUrl);
- if (serverParam)
- popoutParams.set('server', serverParam);
popoutParams.set('trace', traceUrl);
if (snapshot.point) {
popoutParams.set('pointX', String(snapshot.point.x));