Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: enforce dispatcher API convention for server types (4) (#40037)
Pavel Feldmanff6d41b3cb7b
diff --git a/eslint.config.mjs b/eslint.config.mjsindex 23dc500594..09c05422a9 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -21,6 +21,7 @@ import path from "path";import { fileURLToPath } from "url";import stylistic from "@stylistic/eslint-plugin";import importRules from "eslint-plugin-import";+import progressPlugin from "./utils/eslint-plugin-progress/index.js";import { fixupConfigRules } from "@eslint/compat";import { FlatCompat } from "@eslint/eslintrc";import js from "@eslint/js";@@ -420,6 +421,18 @@ export default [...noBooleanCompareRules,},},+ {+ files: [+ "packages/playwright-core/src/server/**/*.ts",+ ],+ plugins: {+ "progress": progressPlugin,+ },+ languageOptions: languageOptionsWithTsConfig,+ rules: {+ "progress/await-must-use-progress": "warn",+ },+ },{files: ["tests/**/*.spec.js", "tests/**/*.ts"],languageOptions: {diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.tsindex 7c7314e9f0..39d7382f9f 100644--- a/packages/playwright-core/src/server/browserContext.ts+++ b/packages/playwright-core/src/server/browserContext.ts@@ -34,6 +34,7 @@ import { RecorderApp } from './recorder/recorderApp';import { Selectors } from './selectors';import { Tracing } from './trace/recorder/tracing';import * as rawStorageSource from '../generated/storageScriptSource';+import { nullProgress } from './progress';import type { Artifact } from './artifact';import type { Browser, BrowserOptions } from './browser';@@ -164,10 +165,10 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk}if (debugMode() === 'console')- await this.exposeConsoleApi();+ await this._exposeConsoleApi();if (this._options.serviceWorkers === 'block')- await this.addInitScript(`\nif (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };\n`);+ await this.addInitScript(nullProgress, `\nif (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };\n`);if (this._options.permissions)await this.grantPermissions(this._options.permissions);@@ -177,7 +178,11 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkreturn this._debugger;}- async exposeConsoleApi() {+ async exposeConsoleApi(progress: Progress) {+ await progress.race(this._exposeConsoleApi());+ }++ private async _exposeConsoleApi() {if (this._consoleApiExposed)return;this._consoleApiExposed = true;@@ -224,9 +229,9 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdklet page: Page | undefined = this.pages()[0];const otherPages = this.possiblyUninitializedPages().filter(p => p !== page);for (const p of otherPages)- await p.close();+ await p.close(progress);if (page && page.hasCrashed()) {- await page.close();+ await page.close(progress);page = undefined;}@@ -292,14 +297,18 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkprotected abstract doClose(reason: string | undefined): Promise<void | 'close-browser'>;protected abstract onClosePersistent(): void;- async cookies(urls: string | string[] | undefined = []): Promise<channels.NetworkCookie[]> {+ async cookies(progress: Progress, urls: string | string[] | undefined = []): Promise<channels.NetworkCookie[]> {+ return await progress.race(this._cookies(urls));+ }++ private async _cookies(urls: string | string[] | undefined = []): Promise<channels.NetworkCookie[]> {if (urls && !Array.isArray(urls))urls = [urls];return await this.doGetCookies(urls as string[]);}async clearCookies(options: {name?: string | RegExp, domain?: string | RegExp, path?: string | RegExp}): Promise<void> {- const currentCookies = await this.cookies();+ const currentCookies = await this._cookies();await this.doClearCookies();const matches = (cookie: channels.NetworkCookie, prop: 'name' | 'domain' | 'path', value: string | RegExp | undefined) => {@@ -321,7 +330,11 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkawait this.addCookies(cookiesToReadd);}- setHTTPCredentials(httpCredentials?: types.Credentials): Promise<void> {+ setHTTPCredentials(progress: Progress, httpCredentials?: types.Credentials): Promise<void> {+ return progress.race(this.innerSetHTTPCredentials(httpCredentials));+ }++ innerSetHTTPCredentials(httpCredentials?: types.Credentials): Promise<void> {return this.doSetHTTPCredentials(httpCredentials);}@@ -445,7 +458,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk// - chromium fails to change isMobile for existing page;// - webkit fails to change locale for existing page.await this.newPage(progress);- await defaultPage.close();+ await defaultPage.close(progress);}}@@ -471,7 +484,11 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkthis._options.httpCredentials = { username, password: password || '' };}- async addInitScript(source: string) {+ async addInitScript(progress: Progress, source: string): Promise<InitScript> {+ return await progress.race(this._internalAddInitScript(source));+ }++ private async _internalAddInitScript(source: string) {const initScript = new InitScript(this, source);this.initScripts.push(initScript);try {@@ -568,7 +585,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk}throw pageOrError;} catch (error) {- await page?.close({ reason: 'Failed to create page' }).catch(() => {});+ await page?.close(progress, { reason: 'Failed to create page' }).catch(() => {});throw error;} finally {this._creatingStorageStatePage = false;@@ -581,7 +598,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkasync storageState(progress: Progress, indexedDB = false): Promise<channels.BrowserContextStorageStateResult> {const result: channels.BrowserContextStorageStateResult = {- cookies: await this.cookies(),+ cookies: await this.cookies(progress),origins: []};const originsToSave = new Set(this._origins);@@ -623,7 +640,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkresult.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });}} finally {- await page.close();+ await page.close(progress);}}return result;@@ -676,7 +693,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkthrow error;} finally {if (mode !== 'resetForReuse')- await page?.close();+ await page?.close(progress);else if (interceptor)await page?.removeRequestInterceptor(interceptor);}@@ -702,9 +719,9 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdkreturn harId;}- async harExport(harId: string | undefined): Promise<Artifact> {+ async harExport(progress: Progress, harId: string | undefined): Promise<Artifact> {const recorder = this._harRecorders.get(harId || '')!;- return recorder.export();+ return progress.race(recorder.export());}addRouteInFlight(route: network.Route) {diff --git a/packages/playwright-core/src/server/clock.ts b/packages/playwright-core/src/server/clock.tsindex 4c15f9ec13..130864fdda 100644--- a/packages/playwright-core/src/server/clock.ts+++ b/packages/playwright-core/src/server/clock.ts@@ -15,6 +15,7 @@*/import * as rawClockSource from '../generated/clockSource';+import { nullProgress } from './progress';import type { BrowserContext } from './browserContext';import type { InitScript } from './page';@@ -36,21 +37,21 @@ export class Clock {async fastForward(ticks: number | string) {await this._installIfNeeded();const ticksMillis = parseTicks(ticks);- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('fastForward', ${Date.now()}, ${ticksMillis})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('fastForward', ${Date.now()}, ${ticksMillis})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.fastForward(${ticksMillis})`);}async install(time: number | string | undefined) {await this._installIfNeeded();const timeMillis = time !== undefined ? parseTime(time) : Date.now();- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('install', ${Date.now()}, ${timeMillis})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('install', ${Date.now()}, ${timeMillis})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.install(${timeMillis})`);}async pauseAt(ticks: number | string) {await this._installIfNeeded();const timeMillis = parseTime(ticks);- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('pauseAt', ${Date.now()}, ${timeMillis})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('pauseAt', ${Date.now()}, ${timeMillis})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.pauseAt(${timeMillis})`);}@@ -58,7 +59,7 @@ export class Clock {if (!this._initScripts.length)return;const doResume = async () => {- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('resume', ${Date.now()})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`);};doResume().catch(() => {});@@ -66,28 +67,28 @@ export class Clock {async resume(progress: Progress) {await this._installIfNeeded();- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('resume', ${Date.now()})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`);}async setFixedTime(time: string | number) {await this._installIfNeeded();const timeMillis = parseTime(time);- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('setFixedTime', ${Date.now()}, ${timeMillis})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setFixedTime', ${Date.now()}, ${timeMillis})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.setFixedTime(${timeMillis})`);}async setSystemTime(time: string | number) {await this._installIfNeeded();const timeMillis = parseTime(time);- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('setSystemTime', ${Date.now()}, ${timeMillis})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setSystemTime', ${Date.now()}, ${timeMillis})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.setSystemTime(${timeMillis})`);}async runFor(ticks: number | string) {await this._installIfNeeded();const ticksMillis = parseTicks(ticks);- this._initScripts.push(await this._browserContext.addInitScript(`globalThis.__pwClock.controller.log('runFor', ${Date.now()}, ${ticksMillis})`));+ this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('runFor', ${Date.now()}, ${ticksMillis})`));await this._evaluateInFrames(`globalThis.__pwClock.controller.runFor(${ticksMillis})`);}@@ -100,7 +101,7 @@ export class Clock {if (!globalThis.__pwClock)globalThis.__pwClock = (module.exports.inject())(globalThis, ${JSON.stringify(this._browserContext._browser.options.name)});})();`;- const initScript = await this._browserContext.addInitScript(script);+ const initScript = await this._browserContext.addInitScript(nullProgress, script);await this._evaluateInFrames(script);this._initScripts.push(initScript);}diff --git a/packages/playwright-core/src/server/debugController.ts b/packages/playwright-core/src/server/debugController.tsindex fcece35f9d..5e004ff602 100644--- a/packages/playwright-core/src/server/debugController.ts+++ b/packages/playwright-core/src/server/debugController.ts@@ -169,7 +169,7 @@ export class DebugController extends SdkObject {for (const browser of this._playwright.allBrowsers()) {for (const context of browser.contexts()) {if (!context.pages().length)- await progress.race(context.close(progress, { reason: 'Browser collected' }));+ await context.close(progress, { reason: 'Browser collected' });}if (!browser.contexts())await browser.close(progress, { reason: 'Browser collected' });diff --git a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.tsindex bc91f6da42..fa5d4e094c 100644--- a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts@@ -252,7 +252,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel}async cookies(params: channels.BrowserContextCookiesParams, progress: Progress): Promise<channels.BrowserContextCookiesResult> {- return { cookies: await progress.race(this._context.cookies(params.urls)) };+ return { cookies: await this._context.cookies(progress, params.urls) };}async addCookies(params: channels.BrowserContextAddCookiesParams, progress: Progress): Promise<void> {@@ -297,11 +297,11 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channelasync setHTTPCredentials(params: channels.BrowserContextSetHTTPCredentialsParams, progress: Progress): Promise<void> {// Note: this operation is deprecated, so we do not properly cleanup.- await progress.race(this._context.setHTTPCredentials(params.httpCredentials));+ await this._context.setHTTPCredentials(progress, params.httpCredentials);}async addInitScript(params: channels.BrowserContextAddInitScriptParams, progress: Progress): Promise<channels.BrowserContextAddInitScriptResult> {- const initScript = await this._context.addInitScript(params.source);+ const initScript = await this._context.addInitScript(progress, params.source);this._disposables.push(initScript);return { disposable: new DisposableDispatcher(this, initScript) };}@@ -328,7 +328,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel}async storageState(params: channels.BrowserContextStorageStateParams, progress: Progress): Promise<channels.BrowserContextStorageStateResult> {- return await progress.race(this._context.storageState(progress, params.indexedDB));+ return await this._context.storageState(progress, params.indexedDB);}async setStorageState(params: channels.BrowserContextSetStorageStateParams, progress: Progress): Promise<void> {@@ -350,7 +350,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel}async exposeConsoleApi(params: channels.BrowserContextExposeConsoleApiParams, progress: Progress): Promise<void> {- await this._context.exposeConsoleApi();+ await this._context.exposeConsoleApi(progress);}async pause(params: channels.BrowserContextPauseParams, progress: Progress) {@@ -372,7 +372,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel}async harExport(params: channels.BrowserContextHarExportParams, progress: Progress): Promise<channels.BrowserContextHarExportResult> {- const artifact = await progress.race(this._context.harExport(params.harId));+ const artifact = await this._context.harExport(progress, params.harId);if (!artifact)throw new Error('No HAR artifact. Ensure record.harPath is set.');return { artifact: ArtifactDispatcher.from(this, artifact) };diff --git a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts b/packages/playwright-core/src/server/dispatchers/pageDispatcher.tsindex b6e02c7362..130bd89805 100644--- a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts@@ -31,6 +31,7 @@ import { deserializeURLMatch, urlMatches } from '../../utils/isomorphic/urlMatchimport { Recorder } from '../recorder';import { disposeAll } from '../disposable';import { VideoRecorder } from '../videoRecorder';+import { nullProgress } from '../progress';import type { Artifact } from '../artifact';import type { BrowserContext } from '../browserContext';@@ -163,7 +164,7 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows}async requestGC(params: channels.PageRequestGCParams, progress: Progress): Promise<channels.PageRequestGCResult> {- await progress.race(this._page.requestGC());+ await this._page.requestGC(progress);}async registerLocatorHandler(params: channels.PageRegisterLocatorHandlerParams, progress: Progress): Promise<channels.PageRegisterLocatorHandlerResult> {@@ -196,7 +197,7 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows}async addInitScript(params: channels.PageAddInitScriptParams, progress: Progress): Promise<channels.PageAddInitScriptResult> {- const initScript = await this._page.addInitScript(params.source);+ const initScript = await this._page.addInitScript(progress, params.source);this._disposables.push(initScript);return { disposable: new DisposableDispatcher(this, initScript) };}@@ -249,13 +250,13 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Browsasync close(params: channels.PageCloseParams, progress: Progress): Promise<void> {if (!params.runBeforeUnload)progress.metadata.potentiallyClosesScope = true;- await this._page.close(params);+ await this._page.close(progress, params);}async updateSubscription(params: channels.PageUpdateSubscriptionParams, progress: Progress): Promise<void> {// Note: progress is ignored because this operation is not cancellable and should not block in the browser anyway.if (params.event === 'fileChooser')- await this._page.setFileChooserInterceptedBy(params.enabled, this);+ await this._page.setFileChooserInterceptedBy(progress, params.enabled, this);if (params.enabled)this._subscriptions.add(params.event);else@@ -343,7 +344,7 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows}async bringToFront(params: channels.PageBringToFrontParams, progress: Progress): Promise<void> {- await progress.race(this._page.bringToFront());+ await this._page.bringToFront(progress);}async pickLocator(params: channels.PagePickLocatorParams, progress: Progress): Promise<channels.PagePickLocatorResult> {@@ -465,7 +466,7 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Browsfor (const uid of this._locatorHandlers)this._page.unregisterLocatorHandler(uid);this._locatorHandlers.clear();- this._page.setFileChooserInterceptedBy(false, this).catch(() => {});+ this._page.setFileChooserInterceptedBy(nullProgress, false, this).catch(() => {});if (this._jsCoverageActive)(this._page.coverage as CRCoverage).stopJSCoverage().catch(() => {});this._jsCoverageActive = false;@@ -502,11 +503,11 @@ export class WorkerDispatcher extends Dispatcher<Worker, channels.WorkerChannel,}async evaluateExpression(params: channels.WorkerEvaluateExpressionParams, progress: Progress): Promise<channels.WorkerEvaluateExpressionResult> {- return { value: serializeResult(await progress.race(this._object.evaluateExpression(params.expression, params.isFunction, parseArgument(params.arg)))) };+ return { value: serializeResult(await this._object.evaluateExpression(progress, params.expression, params.isFunction, parseArgument(params.arg))) };}async evaluateExpressionHandle(params: channels.WorkerEvaluateExpressionHandleParams, progress: Progress): Promise<channels.WorkerEvaluateExpressionHandleResult> {- return { handle: JSHandleDispatcher.fromJSHandle(this, await progress.race(this._object.evaluateExpressionHandle(params.expression, params.isFunction, parseArgument(params.arg)))) };+ return { handle: JSHandleDispatcher.fromJSHandle(this, await this._object.evaluateExpressionHandle(progress, params.expression, params.isFunction, parseArgument(params.arg))) };}async updateSubscription(params: channels.WorkerUpdateSubscriptionParams, progress: Progress): Promise<void> {diff --git a/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts b/packages/playwright-core/src/server/dispatchers/tracingDispatcher.tsindex 68c201d9cb..e632509720 100644--- a/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/tracingDispatcher.ts@@ -61,7 +61,6 @@ export class TracingDispatcher extends Dispatcher<Tracing, channels.TracingChann}async tracingStop(params: channels.TracingTracingStopParams, progress: Progress): Promise<channels.TracingTracingStopResult> {- this._started = false;await this._object.stop(progress);}diff --git a/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts b/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.tsindex 1abf02c57c..93eb677c20 100644--- a/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/webSocketRouteDispatcher.ts@@ -97,7 +97,7 @@ export class WebSocketRouteDispatcher extends Dispatcher<SdkObject, channels.Web}++data.counter;- return await target.addInitScript(`+ return await target.addInitScript(progress, `(() => {const module = {};${rawWebSocketMockSource.source}diff --git a/packages/playwright-core/src/server/dom.ts b/packages/playwright-core/src/server/dom.tsindex 6c16bb724e..8a709367b6 100644--- a/packages/playwright-core/src/server/dom.ts+++ b/packages/playwright-core/src/server/dom.ts@@ -456,7 +456,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {if ((options as any).__testHookBeforeHitTarget)await progress.race((options as any).__testHookBeforeHitTarget());- const frameCheckResult = await progress.race(this._checkFrameIsHitTarget(progress, point));+ const frameCheckResult = await this._checkFrameIsHitTarget(progress, point);if (frameCheckResult === 'error:notconnected' || ('hitTargetDescription' in frameCheckResult))return frameCheckResult;const hitPoint = frameCheckResult.framePoint;@@ -864,7 +864,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {while (frame.parentFrame()) {const frameElement = await frame.frameElement(progress) as ElementHandle<Element>;const box = await frameElement.boundingBox(progress);- const style = await frameElement.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe), {}).catch(e => 'error:notconnected' as const);+ const style = await progress.race(frameElement.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe), {}).catch(e => 'error:notconnected' as const));if (!box || style === 'error:notconnected')return 'error:notconnected';if (style === 'transformed') {@@ -885,9 +885,9 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {const element = data[i - 1].frameElement!;const point = data[i].pointInFrame;// Hit target in the parent frame should hit the child frame element.- const hitTargetResult = await element.evaluateInUtility(([injected, element, hitPoint]) => {+ const hitTargetResult = await progress.race(element.evaluateInUtility(([injected, element, hitPoint]) => {return injected.expectHitTarget(hitPoint, element);- }, point);+ }, point));if (hitTargetResult !== 'done')return hitTargetResult;}diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.tsindex 76118b0387..c3987a2e92 100644--- a/packages/playwright-core/src/server/fetch.ts+++ b/packages/playwright-core/src/server/fetch.ts@@ -135,8 +135,8 @@ export abstract class APIRequestContext extends SdkObject {abstract dispose(options: { reason?: string }): Promise<void>;abstract _defaultOptions(): FetchRequestOptions;- abstract _addCookies(cookies: channels.NetworkCookie[]): Promise<void>;- abstract _cookies(url: URL): Promise<channels.NetworkCookie[]>;+ abstract addCookies(cookies: channels.NetworkCookie[]): Promise<void>;+ abstract cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]>;protected _disposeImpl() {APIRequestContext.allInstances.delete(this);@@ -259,7 +259,7 @@ export abstract class APIRequestContext extends SdkObject {private async _updateRequestCookieHeader(progress: Progress, url: URL, headers: HeadersObject) {if (getHeader(headers, 'cookie') !== undefined)return;- const contextCookies = await progress.race(this._cookies(url));+ const contextCookies = await this.cookies(progress, url);// Browser context returns cookies with domain matching both .example.com and// example.com. Those without leading dot are only sent when domain is strictly// matching example.com, but not for sub.example.com.@@ -372,11 +372,11 @@ export abstract class APIRequestContext extends SdkObject {const cookies = this._parseSetCookieHeader(response.url || url.toString(), response.headers['set-cookie']) ;if (cookies.length) {try {- await this._addCookies(cookies);+ await this.addCookies(cookies);} catch (e) {// Cookie value is limited by 4096 characters in the browsers. If setCookies failed,// we try setting each cookie individually just in case only some of them are bad.- await Promise.all(cookies.map(c => this._addCookies([c]).catch(() => {})));+ await Promise.all(cookies.map(c => this.addCookies([c]).catch(() => {})));}}@@ -618,12 +618,12 @@ export class BrowserContextAPIRequestContext extends APIRequestContext {};}- async _addCookies(cookies: channels.NetworkCookie[]): Promise<void> {+ async addCookies(cookies: channels.NetworkCookie[]): Promise<void> {await this._context.addCookies(cookies);}- async _cookies(url: URL): Promise<channels.NetworkCookie[]> {- return await this._context.cookies(url.toString());+ async cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]> {+ return await this._context.cookies(progress, url.toString());}override async storageState(progress: Progress, indexedDB?: boolean): Promise<channels.APIRequestContextStorageStateResult> {@@ -675,11 +675,11 @@ export class GlobalAPIRequestContext extends APIRequestContext {return this._options;}- async _addCookies(cookies: channels.NetworkCookie[]): Promise<void> {+ async addCookies(cookies: channels.NetworkCookie[]): Promise<void> {this._cookieStore.addCookies(cookies);}- async _cookies(url: URL): Promise<channels.NetworkCookie[]> {+ async cookies(progress: Progress, url: URL): Promise<channels.NetworkCookie[]> {return this._cookieStore.cookies(url);}diff --git a/packages/playwright-core/src/server/firefox/ffBrowser.ts b/packages/playwright-core/src/server/firefox/ffBrowser.tsindex 8280ac4d78..e06467925f 100644--- a/packages/playwright-core/src/server/firefox/ffBrowser.ts+++ b/packages/playwright-core/src/server/firefox/ffBrowser.ts@@ -204,7 +204,7 @@ export class FFBrowserContext extends BrowserContext {if (this._options.extraHTTPHeaders || this._options.locale)promises.push(this.doUpdateExtraHTTPHeaders());if (this._options.httpCredentials)- promises.push(this.setHTTPCredentials(this._options.httpCredentials));+ promises.push(this.innerSetHTTPCredentials(this._options.httpCredentials));if (this._options.geolocation)promises.push(this.setGeolocation(this._options.geolocation));if (this._options.offline)diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.tsindex 67f100fc03..f3905b6307 100644--- a/packages/playwright-core/src/server/frames.ts+++ b/packages/playwright-core/src/server/frames.ts@@ -1260,7 +1260,7 @@ export class Frame extends SdkObject<FrameEventMap> {let frame: Frame | null = element._frame;const result = [generated];while (frame?.parentFrame()) {- const frameElement = await progress.race(frame.frameElement(progress));+ const frameElement = await frame.frameElement(progress);if (frameElement) {const generated = await progress.race(frameElement.evaluateInUtility(async ([injected, node]) => {return injected.generateSelectorSimple(node as unknown as Element);diff --git a/packages/playwright-core/src/server/launchApp.ts b/packages/playwright-core/src/server/launchApp.tsindex d92b83b7af..eade44ef12 100644--- a/packages/playwright-core/src/server/launchApp.ts+++ b/packages/playwright-core/src/server/launchApp.ts@@ -20,7 +20,7 @@ import path from 'path';import { isUnderTest, rewriteErrorMessage, wrapInASCIIBox } from '../utils';import { buildPlaywrightCLICommand, findChromiumChannelBestEffort } from './registry';import { registryDirectory } from './registry';-import { ProgressController } from './progress';+import { nullProgress, ProgressController } from './progress';import type { BrowserType } from './browserType';import type { CRPage } from './chromium/crPage';@@ -77,8 +77,8 @@ export async function launchApp(browserType: BrowserType, options: {if (browserType.name() === 'chromium' && process.platform === 'darwin') {context.on('page', async (newPage: Page) => {if (newPage.mainFrame().url() === 'chrome://new-tab-page/') {- await page.bringToFront();- await newPage.close();+ await page.bringToFront(nullProgress);+ await newPage.close(nullProgress);}});}@@ -108,7 +108,7 @@ export async function syncLocalStorageWithSettings(page: Page, appName: string)});const settings = await fs.promises.readFile(settingsFile, 'utf-8').catch(() => ('{}'));- await page.addInitScript(+ await page.addInitScript(nullProgress,`(${String((settings: any) => {// iframes w/ snapshots, etc.if (location && location.protocol === 'data:')diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.tsindex ba9fffb5ab..c6ea477fd0 100644--- a/packages/playwright-core/src/server/page.ts+++ b/packages/playwright-core/src/server/page.ts@@ -496,8 +496,8 @@ export class Page extends SdkObject<PageEventMap> {});}- requestGC(): Promise<void> {- return this.delegate.requestGC();+ requestGC(progress: Progress): Promise<void> {+ return progress.race(this.delegate.requestGC());}registerLocatorHandler(selector: string, noWaitAfter: boolean | undefined) {@@ -637,11 +637,15 @@ export class Page extends SdkObject<PageEventMap> {return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : undefined;}- async bringToFront(): Promise<void> {- await this.delegate.bringToFront();+ async bringToFront(progress: Progress): Promise<void> {+ await progress.race(this.delegate.bringToFront());}- async addInitScript(source: string) {+ async addInitScript(progress: Progress, source: string) {+ return await progress.race(this._addInitScript(source));+ }++ private async _addInitScript(source: string) {const initScript = new InitScript(this, source);this.initScripts.push(initScript);try {@@ -787,7 +791,11 @@ export class Page extends SdkObject<PageEventMap> {return await this.screenshotter.screenshotPage(progress, options);}- async close(options: { runBeforeUnload?: boolean, reason?: string } = {}) {+ async close(progress: Progress, options: { runBeforeUnload?: boolean, reason?: string } = {}) {+ await progress.race(this._close(options));+ }++ private async _close(options: { runBeforeUnload?: boolean, reason?: string } = {}) {if (this._closedState === 'closed')return;@@ -842,7 +850,11 @@ export class Page extends SdkObject<PageEventMap> {}}- async setFileChooserInterceptedBy(enabled: boolean, by: any): Promise<void> {+ async setFileChooserInterceptedBy(progress: Progress, enabled: boolean, by: any): Promise<void> {+ await progress.race(this._setFileChooserInterceptedBy(enabled, by));+ }++ private async _setFileChooserInterceptedBy(enabled: boolean, by: any): Promise<void> {const wasIntercepted = this.fileChooserIntercepted();if (enabled)this._fileChooserInterceptedBy.add(by);@@ -953,12 +965,12 @@ export class Worker extends SdkObject<WorkerEventMap> {this.openScope.close(new Error('Worker closed'));}- async evaluateExpression(expression: string, isFunction: boolean | undefined, arg: any): Promise<any> {- return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: true, isFunction }, arg);+ async evaluateExpression(progress: Progress, expression: string, isFunction: boolean | undefined, arg: any): Promise<any> {+ return progress.race(js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: true, isFunction }, arg));}- async evaluateExpressionHandle(expression: string, isFunction: boolean | undefined, arg: any): Promise<any> {- return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: false, isFunction }, arg);+ async evaluateExpressionHandle(progress: Progress, expression: string, isFunction: boolean | undefined, arg: any): Promise<any> {+ return progress.race(js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: false, isFunction }, arg));}}diff --git a/packages/playwright-core/src/server/recorder.ts b/packages/playwright-core/src/server/recorder.tsindex 54c6f42b6f..8427d98246 100644--- a/packages/playwright-core/src/server/recorder.ts+++ b/packages/playwright-core/src/server/recorder.ts@@ -23,7 +23,7 @@ import { Debugger } from './debugger';import { buildFullSelector, generateFrameSelector, metadataToCallLog } from './recorder/recorderUtils';import { locatorOrSelectorAsSelector } from '../utils/isomorphic/locatorParser';import { stringifySelector } from '../utils/isomorphic/selectorParser';-import { ProgressController } from './progress';+import { nullProgress, ProgressController } from './progress';import { ManualPromise } from '../utils/isomorphic/manualPromise';import { RecorderSignalProcessor } from './recorder/recorderSignalProcessor';@@ -267,7 +267,7 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrumelet pageToFocus = this._pickLocatorPage;if (!pageToFocus && this._context.pages().length === 1)pageToFocus = this._context.pages()[0];- pageToFocus?.bringToFront().catch(() => {});+ pageToFocus?.bringToFront(nullProgress).catch(() => {});}await this._refreshOverlay();}diff --git a/packages/playwright-core/src/server/recorder/recorderApp.ts b/packages/playwright-core/src/server/recorder/recorderApp.tsindex 5a05b59ccf..a121178c04 100644--- a/packages/playwright-core/src/server/recorder/recorderApp.ts+++ b/packages/playwright-core/src/server/recorder/recorderApp.ts@@ -188,7 +188,7 @@ export class RecorderApp {}async close() {- await this._page.close();+ await this._page.close(nullProgress);}static showInspectorNoReply(context: BrowserContext) {@@ -271,7 +271,7 @@ export class RecorderApp {recorder.on(RecorderEvent.ElementPicked, (elementInfo: ElementInfo, userGesture?: boolean) => {if (userGesture)- this._page.bringToFront();+ this._page.bringToFront(nullProgress).catch(() => {});this._frontend.elementPicked({ elementInfo, userGesture });});diff --git a/packages/playwright-core/src/server/recorder/recorderRunner.ts b/packages/playwright-core/src/server/recorder/recorderRunner.tsindex 1ebdf6d381..3daf608c80 100644--- a/packages/playwright-core/src/server/recorder/recorderRunner.ts+++ b/packages/playwright-core/src/server/recorder/recorderRunner.ts@@ -41,7 +41,7 @@ async function performActionImpl(progress: Progress, mainFrame: Frame, actionInCthrow Error('Not reached');if (action.name === 'closePage') {- await mainFrame._page.close();+ await mainFrame._page.close(progress);return;}diff --git a/packages/playwright-core/src/server/trace/recorder/snapshotter.ts b/packages/playwright-core/src/server/trace/recorder/snapshotter.tsindex 1cf3505c72..d7331e7a18 100644--- a/packages/playwright-core/src/server/trace/recorder/snapshotter.ts+++ b/packages/playwright-core/src/server/trace/recorder/snapshotter.ts@@ -29,6 +29,7 @@ import type { RegisteredListener } from '../../utils/eventsHelper';import type { Frame } from '../../frames';import type { InitScript } from '../../page';import type { FrameSnapshot } from '@trace/snapshot';+import type { Progress } from '../../progress';export type SnapshotterBlob = {buffer: Buffer,@@ -59,10 +60,10 @@ export class Snapshotter {return this._started;}- async start() {+ async start(progress: Progress) {this._started = true;if (!this._initScript)- await this._initialize();+ await this._initialize(progress);await this.reset();}@@ -84,7 +85,7 @@ export class Snapshotter {}}- async _initialize() {+ async _initialize(progress: Progress) {for (const page of this._context.pages())this._onPage(page);this._eventListeners = [@@ -93,7 +94,7 @@ export class Snapshotter {const { javaScriptEnabled } = this._context._options;const initScriptSource = `(${frameSnapshotStreamer})("${this._snapshotStreamer}", ${javaScriptEnabled || javaScriptEnabled === undefined})`;- this._initScript = await this._context.addInitScript(initScriptSource);+ this._initScript = await this._context.addInitScript(progress, initScriptSource);await this._context.safeNonStallingEvaluateInAllFrames(initScriptSource, 'main');}diff --git a/packages/playwright-core/src/server/trace/recorder/tracing.ts b/packages/playwright-core/src/server/trace/recorder/tracing.tsindex 38e5aa1556..de3d590505 100644--- a/packages/playwright-core/src/server/trace/recorder/tracing.ts+++ b/packages/playwright-core/src/server/trace/recorder/tracing.ts@@ -34,7 +34,7 @@ import { SerializedFS, removeFolders } from '../../utils/fileUtils';import { HarTracer } from '../../har/harTracer';import { SdkObject } from '../../instrumentation';import { Page } from '../../page';-import { isAbortError } from '../../progress';+import { isAbortError, nullProgress } from '../../progress';import type { SnapshotterBlob, SnapshotterDelegate } from './snapshotter';import type { NameValue } from '../../../utils/isomorphic/types';@@ -93,6 +93,7 @@ export class Tracing extends SdkObject implements InstrumentationListener, Snapsprivate _allResources = new Set<string>();private _contextCreatedEvent: trace.ContextCreatedTraceEvent;private _pendingHarEntries = new Set<har.Entry>();+ private _started = false;constructor(context: BrowserContext | APIRequestContext, tracesDir: string | undefined) {super(context, 'tracing');@@ -175,6 +176,7 @@ export class Tracing extends SdkObject implements InstrumentationListener, Snaps// Tracing is 10x bigger if we include scripts in every trace.if (options.snapshots)this._harTracer.start({ omitScripts: !options.live });+ this._started = true;}async startChunk(progress: Progress, options: { name?: string, title?: string } = {}): Promise<{ traceName: string }> {@@ -217,7 +219,7 @@ export class Tracing extends SdkObject implements InstrumentationListener, Snapsif (this._state.options.screenshots)this._startScreencast();if (this._state.options.snapshots)- await this._snapshotter?.start();+ await this._snapshotter?.start(progress);return { traceName: this._state.traceName };}@@ -599,6 +601,13 @@ export class Tracing extends SdkObject implements InstrumentationListener, Snapsthis._appendTraceEvent(event);}+ dispose(params: TracingTracingStopChunkParams) {+ // Avoid protocol calls for the closed context.+ if (this._started)+ this.stopChunk(nullProgress, params).then(() => this._stop()).catch(() => {});+ this._started = false;+ }+private _onPageError(error: Error, page: Page) {const event: trace.EventTraceEvent = {type: 'event',diff --git a/packages/playwright-core/src/server/webkit/wkBrowser.ts b/packages/playwright-core/src/server/webkit/wkBrowser.tsindex 1482a51356..39f7a1cebc 100644--- a/packages/playwright-core/src/server/webkit/wkBrowser.ts+++ b/packages/playwright-core/src/server/webkit/wkBrowser.ts@@ -231,7 +231,7 @@ export class WKBrowserContext extends BrowserContext {if (this._options.offline)promises.push(this.doUpdateOffline());if (this._options.httpCredentials)- promises.push(this.setHTTPCredentials(this._options.httpCredentials));+ promises.push(this.innerSetHTTPCredentials(this._options.httpCredentials));await Promise.all(promises);}diff --git a/packages/playwright-core/src/server/webkit/wkInput.ts b/packages/playwright-core/src/server/webkit/wkInput.tsindex d62b1f681d..5a762a82dd 100644--- a/packages/playwright-core/src/server/webkit/wkInput.ts+++ b/packages/playwright-core/src/server/webkit/wkInput.ts@@ -157,7 +157,7 @@ export class RawMouseImpl implements input.RawMouse {throw new Error('Mouse wheel is not supported in mobile WebKit');await this._session!.send('Page.updateScrollingState');// Wheel events hit the compositor first, so wait one frame for it to be synced.- await progress.race(this._page!.mainFrame().evaluateExpression(progress, `new Promise(requestAnimationFrame)`, { world: 'utility' }));+ await this._page!.mainFrame().evaluateExpression(progress, `new Promise(requestAnimationFrame)`, { world: 'utility' });await progress.race(this._pageProxySession.send('Input.dispatchWheelEvent', {x,y,diff --git a/packages/protocol/src/progress.d.ts b/packages/protocol/src/progress.d.tsindex f7abd096ac..097b9d37e8 100644--- a/packages/protocol/src/progress.d.ts+++ b/packages/protocol/src/progress.d.ts@@ -30,10 +30,6 @@ import type { CallMetadata } from './callMetadata';// - Using `progress.race()` when awaiting other methods that do not take a Progress argument.// In this case, it is important that awaited method has no side effects, for example// it is a read-only browser protocol call.-// - In rare cases, when the awaited method does not take a Progress argument,-// but it does have side effects such as creating a page - a proper try/catch/finally-// should be used to cleanup. Whether the cleanup is awaited or not depends on the method details.-// For the trickiest cases, look at `raceUncancellableOperationWithCleanup()` helper method.export interface Progress {timeout: number;deadline: number;diff --git a/tests/page/page-leaks.spec.ts b/tests/page/page-leaks.spec.tsindex e45eefd26c..42ff3d1c41 100644--- a/tests/page/page-leaks.spec.ts+++ b/tests/page/page-leaks.spec.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import { nullProgress } from '../../packages/playwright-core/lib/server/progress';import { MultiMap } from '../../packages/playwright-core/lib/utils/isomorphic/multimap';import { test, expect } from './pageTest';@@ -56,7 +57,7 @@ async function weakRefObjects(pageImpl: any, selector: string) {async function weakRefCount(pageImpl): Promise<{ main: number, utility: number }> {const result = { main: 0, utility: 0 };for (const world of ['main', 'utility']) {- await pageImpl.requestGC();+ await pageImpl.requestGC(nullProgress);const context = await pageImpl.mainFrame().context(world);result[world] = await context.evaluate(() => globalThis.weakRefs.filter(r => !!r.deref()).length);}diff --git a/utils/eslint-plugin-progress/index.js b/utils/eslint-plugin-progress/index.jsnew file mode 100644index 0000000000..d976b137eb--- /dev/null+++ b/utils/eslint-plugin-progress/index.js@@ -0,0 +1,168 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++// @ts-check++const { ESLintUtils } = require('@typescript-eslint/utils');++const createRule = ESLintUtils.RuleCreator(name => name);++/**+ * Checks whether a function parameter named "progress" has type "Progress".+ */+function hasProgressParam(node, services) {+ const checker = services.program.getTypeChecker();+ for (const param of node.params) {+ if (param.type === 'Identifier' && param.name === 'progress') {+ const tsNode = services.esTreeNodeToTSNodeMap.get(param);+ const type = checker.getTypeAtLocation(tsNode);+ if (type.symbol?.name === 'Progress' || type.aliasSymbol?.name === 'Progress')+ return true;+ // Also check the declared type annotation.+ const typeStr = checker.typeToString(type);+ if (typeStr === 'Progress')+ return true;+ }+ }+ return false;+}++/**+ * Checks whether an expression is `progress.race(...)`.+ */+function isProgressRace(node) {+ return (+ node.type === 'CallExpression' &&+ node.callee.type === 'MemberExpression' &&+ node.callee.object.type === 'Identifier' &&+ node.callee.object.name === 'progress' &&+ node.callee.property.type === 'Identifier' &&+ node.callee.property.name === 'race'+ );+}++/**+ * Checks whether `progress` is passed as first argument to a call.+ */+function passesProgressAsFirstArg(node) {+ if (node.type !== 'CallExpression')+ return false;+ const firstArg = node.arguments[0];+ return firstArg?.type === 'Identifier' && firstArg.name === 'progress';+}++/**+ * Checks whether the return type of a call expression is a Promise.+ */+function isAsyncCall(node, services) {+ const checker = services.program.getTypeChecker();+ const tsNode = services.esTreeNodeToTSNodeMap.get(node);+ const type = checker.getTypeAtLocation(tsNode);+ // Check if the type is a Promise (has a "then" method).+ const thenProp = type.getProperty('then');+ return !!thenProp;+}++/**+ * Walks up to find if this expression is inside a progress.race() call.+ */+function isInsideProgressRace(node) {+ let current = node.parent;+ while (current) {+ if (isProgressRace(current))+ return true;+ // Stop at function boundaries.+ if (current.type === 'ArrowFunctionExpression' || current.type === 'FunctionExpression' || current.type === 'FunctionDeclaration' || current.type === 'MethodDefinition')+ return false;+ current = current.parent;+ }+ return false;+}++const rule = createRule({+ name: 'await-must-use-progress',+ meta: {+ type: 'problem',+ docs: {+ description: 'In methods accepting Progress, awaited async calls must pass progress or be wrapped in progress.race()',+ },+ messages: {+ missingProgress: 'Awaited async call must either pass `progress` as first argument or be wrapped in `progress.race()`. See packages/protocol/src/progress.d.ts.',+ },+ schema: [],+ },+ defaultOptions: [],+ create(context) {+ const services = ESLintUtils.getParserServices(context);+ // Stack of functions that have a progress parameter.+ const progressFunctionStack = [];++ function enterFunction(node) {+ progressFunctionStack.push(hasProgressParam(node, services));+ }++ function exitFunction() {+ progressFunctionStack.pop();+ }++ function isInProgressFunction() {+ return progressFunctionStack.length > 0 && progressFunctionStack[progressFunctionStack.length - 1];+ }++ return {+ 'FunctionDeclaration': enterFunction,+ 'FunctionDeclaration:exit': exitFunction,+ 'FunctionExpression': enterFunction,+ 'FunctionExpression:exit': exitFunction,+ 'ArrowFunctionExpression': enterFunction,+ 'ArrowFunctionExpression:exit': exitFunction,++ // Check await expressions in progress functions.+ 'AwaitExpression'(node) {+ if (!isInProgressFunction())+ return;++ const awaited = node.argument;++ // await progress.race(...) is always fine.+ if (isProgressRace(awaited))+ return;++ // await someCall(progress, ...) is fine.+ if (passesProgressAsFirstArg(awaited))+ return;++ // Check if this await is inside a progress.race() call higher up.+ if (isInsideProgressRace(node))+ return;++ // Only flag async calls (calls that return Promise).+ if (awaited.type === 'CallExpression' && isAsyncCall(awaited, services)) {+ context.report({+ node: awaited,+ messageId: 'missingProgress',+ });+ }+ },+ };+ },+});++module.exports = {+ rules: {+ 'await-must-use-progress': rule,+ },+};