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(client): add @apiCall and @internal decorators (#43437)
Pavel Feldmane7edafd2d37b
diff --git a/packages/playwright-core/src/client/android.ts b/packages/playwright-core/src/client/android.tsindex 400547e7a1..8600856ea8 100644--- a/packages/playwright-core/src/client/android.ts+++ b/packages/playwright-core/src/client/android.ts@@ -21,7 +21,7 @@ import { monotonicTime } from '@isomorphic/time';import { raceAgainstDeadline } from '@isomorphic/timeoutRunner';import { EventEmitter } from './eventEmitter';import { BrowserContext, prepareBrowserContextParams } from './browserContext';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall } from './channelOwner';import { TargetClosedError, isTargetClosedError } from './errors';import { Events } from './events';import { Waiter } from './waiter';@@ -67,36 +67,35 @@ export class Android extends ChannelOwner<channels.AndroidChannel> implements apreturn await this._serverLauncher.launchServer(options);}+ @apiCall()async connect(endpoint: string, options: Parameters<api.Android['connect']>[1] = {}): Promise<api.AndroidDevice> {- return await this._wrapApiCall(async () => {- const deadline = options.timeout ? monotonicTime() + options.timeout : 0;- const headers = { 'x-playwright-browser': 'android', ...options.headers };- const connectParams: channels.LocalUtilsConnectParams = { endpoint, headers, slowMo: options.slowMo };- const connection = await connectToEndpoint(this._connection, connectParams, { signal: undefined, timeout: options.timeout || 0 });-- let device: AndroidDevice;- connection.on('close', () => {- device?._didClose();- });-- const result = await raceAgainstDeadline(async () => {- const playwright = await connection!.initializePlaywright();- if (!playwright._initializer.preConnectedAndroidDevice) {- connection.close();- throw new Error('Malformed endpoint. Did you use Android.launchServer method?');- }- device = AndroidDevice.from(playwright._initializer.preConnectedAndroidDevice!);- device._shouldCloseConnectionOnClose = true;- device.on(Events.AndroidDevice.Close, () => connection.close());- return device;- }, deadline);- if (!result.timedOut) {- return result.result;- } else {+ const deadline = options.timeout ? monotonicTime() + options.timeout : 0;+ const headers = { 'x-playwright-browser': 'android', ...options.headers };+ const connectParams: channels.LocalUtilsConnectParams = { endpoint, headers, slowMo: options.slowMo };+ const connection = await connectToEndpoint(this._connection, connectParams, { signal: undefined, timeout: options.timeout || 0 });++ let device: AndroidDevice;+ connection.on('close', () => {+ device?._didClose();+ });++ const result = await raceAgainstDeadline(async () => {+ const playwright = await connection!.initializePlaywright();+ if (!playwright._initializer.preConnectedAndroidDevice) {connection.close();- throw new Error(`Timeout ${options.timeout}ms exceeded`);+ throw new Error('Malformed endpoint. Did you use Android.launchServer method?');}- });+ device = AndroidDevice.from(playwright._initializer.preConnectedAndroidDevice!);+ device._shouldCloseConnectionOnClose = true;+ device.on(Events.AndroidDevice.Close, () => connection.close());+ return device;+ }, deadline);+ if (!result.timedOut) {+ return result.result;+ } else {+ connection.close();+ throw new Error(`Timeout ${options.timeout}ms exceeded`);+ }}}@@ -270,18 +269,17 @@ export class AndroidDevice extends ChannelOwner<channels.AndroidDeviceChannel> ireturn context;}+ @apiCall()async waitForEvent(event: string, optionsOrPredicate: types.WaitForEventOptions = {}): Promise<any> {- return await this._wrapApiCall(async () => {- const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- const waiter = Waiter.createForEvent(this, event);- waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);- if (event !== Events.AndroidDevice.Close)- waiter.rejectOnEvent(this, Events.AndroidDevice.Close, () => new TargetClosedError());- const result = await waiter.waitForEvent(this, event, predicate as any);- waiter.dispose();- return result;- });+ const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);+ const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;+ const waiter = Waiter.createForEvent(this, event);+ waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);+ if (event !== Events.AndroidDevice.Close)+ waiter.rejectOnEvent(this, Events.AndroidDevice.Close, () => new TargetClosedError());+ const result = await waiter.waitForEvent(this, event, predicate as any);+ waiter.dispose();+ return result;}}diff --git a/packages/playwright-core/src/client/browser.ts b/packages/playwright-core/src/client/browser.tsindex 4a9736ebde..23d9d38bf4 100644--- a/packages/playwright-core/src/client/browser.ts+++ b/packages/playwright-core/src/client/browser.ts@@ -19,7 +19,7 @@ import fs from 'fs';import { Artifact } from './artifact';import { BrowserContext, prepareBrowserContextParams } from './browserContext';import { CDPSession } from './cdpSession';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall } from './channelOwner';import { isTargetClosedError } from './errors';import { Events } from './events';import { mkdirIfNeeded } from './fileUtils';@@ -142,14 +142,13 @@ export class Browser extends ChannelOwner<channels.BrowserChannel> implements apawait this._channel.stopServer({}, kNoTimeout);}+ @apiCall({ title: 'Create page' })async newPage(options: BrowserContextOptions = {}): Promise<Page> {- return await this._wrapApiCall(async () => {- const context = await this.newContext(options);- const page = await context.newPage();- page._ownedContext = context;- context._ownerPage = page;- return page;- }, { title: 'Create page' });+ const context = await this.newContext(options);+ const page = await context.newPage();+ page._ownedContext = context;+ context._ownerPage = page;+ return page;}isConnected(): boolean {diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.tsindex fbe49ff548..983a96fa11 100644--- a/packages/playwright-core/src/client/browserContext.ts+++ b/packages/playwright-core/src/client/browserContext.ts@@ -23,7 +23,7 @@ import { urlMatchesEqual } from '@isomorphic/urlMatch';import { rewriteErrorMessage } from '@utils/stackTrace';import { Browser } from './browser';import { CDPSession } from './cdpSession';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall, internal } from './channelOwner';import { evaluationScript } from './clientHelper';import { Clock } from './clock';import { ConsoleMessage } from './consoleMessage';@@ -256,7 +256,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>this._routes.splice(index, 1);const handled = await routeHandler.handle(route);if (!this._routes.length)- this._updateInterceptionPatterns({ internal: true }).catch(() => {});+ this._disableInterception().catch(() => {});if (handled)return;}@@ -385,15 +385,17 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>return DisposableObject.from(result.disposable);}+ @apiCall({ title: 'Route requests' })async route(url: URLMatch, handler: network.RouteHandlerCallback, options: { times?: number } = {}): Promise<DisposableStub> {this._routes.unshift(new network.RouteHandler(this._options.baseURL, url, handler, options.times));- await this._updateInterceptionPatterns({ title: 'Route requests' });+ await this._updateInterceptionPatterns();return new DisposableStub(() => this.unroute(url, handler));}+ @apiCall({ title: 'Route WebSockets' })async routeWebSocket(url: URLMatch, handler: network.WebSocketRouteHandlerCallback): Promise<void> {this._webSocketRoutes.unshift(new network.WebSocketRouteHandler(this._options.baseURL, url, handler));- await this._updateWebSocketInterceptionPatterns({ title: 'Route WebSockets' });+ await this._updateWebSocketInterceptionPatterns();}async routeFromHAR(har: string, options: { url?: string | RegExp, notFound?: 'abort' | 'fallback', update?: boolean, updateContent?: 'attach' | 'embed', updateMode?: 'minimal' | 'full' } = {}): Promise<void> {@@ -414,11 +416,13 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>this._harRouters = [];}+ @apiCall({ title: 'Unroute requests' })async unrouteAll(options?: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void> {await this._unrouteInternal(this._routes, [], options?.behavior);this._disposeHarRouters();}+ @apiCall({ title: 'Unroute requests' })async unroute(url: URLMatch, handler?: network.RouteHandlerCallback): Promise<void> {const removed = [];const remaining = [];@@ -437,35 +441,39 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>const promises = removed.map(routeHandler => routeHandler.stop(behavior));await Promise.all(promises);}- await this._updateInterceptionPatterns({ title: 'Unroute requests' });+ await this._updateInterceptionPatterns();}- private async _updateInterceptionPatterns(options: { internal: true } | { title: string }) {+ @internal+ private async _disableInterception() {+ await this._updateInterceptionPatterns();+ }++ private async _updateInterceptionPatterns() {const patterns = network.RouteHandler.prepareInterceptionPatterns(this._routes);- await this._wrapApiCall(() => this._channel.setNetworkInterceptionPatterns({ patterns }, kNoTimeout), options);+ await this._channel.setNetworkInterceptionPatterns({ patterns }, kNoTimeout);}- private async _updateWebSocketInterceptionPatterns(options: { internal: true } | { title: string }) {+ private async _updateWebSocketInterceptionPatterns() {const patterns = network.WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes);- await this._wrapApiCall(() => this._channel.setWebSocketInterceptionPatterns({ patterns }, kNoTimeout), options);+ await this._channel.setWebSocketInterceptionPatterns({ patterns }, kNoTimeout);}_effectiveCloseReason(): string | undefined {return this._closeReason || this._browser?._closeReason;}+ @apiCall()async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {- return await this._wrapApiCall(async () => {- const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- const waiter = Waiter.createForEvent(this, event);- waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);- if (event !== Events.BrowserContext.Close)- waiter.rejectOnEvent(this, Events.BrowserContext.Close, () => new TargetClosedError(this._effectiveCloseReason()));- const result = await waiter.waitForEvent(this, event, predicate as any);- waiter.dispose();- return result;- });+ const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);+ const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;+ const waiter = Waiter.createForEvent(this, event);+ waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);+ if (event !== Events.BrowserContext.Close)+ waiter.rejectOnEvent(this, Events.BrowserContext.Close, () => new TargetClosedError(this._effectiveCloseReason()));+ const result = await waiter.waitForEvent(this, event, predicate as any);+ waiter.dispose();+ return result;}async storageState(options: { path?: string, indexedDB?: boolean, opfs?: boolean, credentials?: boolean } = {}): Promise<StorageState> {diff --git a/packages/playwright-core/src/client/browserType.ts b/packages/playwright-core/src/client/browserType.tsindex 37c691c78c..ca33489c6d 100644--- a/packages/playwright-core/src/client/browserType.ts+++ b/packages/playwright-core/src/client/browserType.ts@@ -20,7 +20,7 @@ import { assert } from '@isomorphic/assert';import { headersObjectToArray } from '@isomorphic/headers';import { Browser } from './browser';import { BrowserContext, prepareBrowserContextParams } from './browserContext';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall } from './channelOwner';import { envObjectToArray } from './clientHelper';import { connectToBrowser } from './connect';import { TimeoutSettings } from './timeoutSettings';@@ -63,6 +63,7 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> implereturn this._initializer.name;}+ @apiCall()async launch(options: LaunchOptions = {}): Promise<Browser> {assert(!(options as any).userDataDir, 'userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead');assert(!(options as any).port, 'Cannot specify a port without launching as a server.');@@ -75,11 +76,9 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> impleignoreAllDefaultArgs: !!options.ignoreDefaultArgs && !Array.isArray(options.ignoreDefaultArgs),env: options.env ? envObjectToArray(options.env) : undefined,};- return await this._wrapApiCall(async () => {- const browser = Browser.from((await this._channel.launch(launchOptions, new TimeoutSettings().launchTimeout(options))).browser);- browser._connectToBrowserType(this, options, logger);- return browser;- });+ const browser = Browser.from((await this._channel.launch(launchOptions, new TimeoutSettings().launchTimeout(options))).browser);+ browser._connectToBrowserType(this, options, logger);+ return browser;}async launchServer(options: LaunchServerOptions = {}): Promise<api.BrowserServer> {@@ -89,6 +88,7 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> implereturn await this._serverLauncher.launchServer(options);}+ @apiCall()async launchPersistentContext(userDataDir: string, options: LaunchPersistentContextOptions = {}): Promise<BrowserContext> {assert(!(options as any).port, 'Cannot specify a port without launching as a server.');options = this._playwright.selectors._withSelectorOptions({@@ -107,20 +107,18 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> implechannel: options.channel,userDataDir: (path.isAbsolute(userDataDir) || !userDataDir) ? userDataDir : path.resolve(userDataDir),};- const context = await this._wrapApiCall(async () => {- const result = await this._channel.launchPersistentContext(persistentParams, new TimeoutSettings().launchTimeout(options));- const browser = Browser.from(result.browser);- browser._connectToBrowserType(this, options, logger);- const context = BrowserContext.from(result.context);- await context._initializeHarFromOptions(options.recordHar);- return context;- });+ const result = await this._channel.launchPersistentContext(persistentParams, new TimeoutSettings().launchTimeout(options));+ const browser = Browser.from(result.browser);+ browser._connectToBrowserType(this, options, logger);+ const context = BrowserContext.from(result.context);+ await context._initializeHarFromOptions(options.recordHar);await this._instrumentation.runAfterCreateBrowserContext(context);return context;}connect(options: api.ConnectOptions & { wsEndpoint: string }): Promise<Browser>;connect(endpoint: string, options?: api.ConnectOptions): Promise<Browser>;+ @apiCall()async connect(optionsOrEndpoint: string | (api.ConnectOptions & { wsEndpoint?: string }), options?: api.ConnectOptions): Promise<Browser>{if (typeof optionsOrEndpoint === 'string')return await this._connect({ ...options, endpoint: optionsOrEndpoint });@@ -129,11 +127,9 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple}async _connect(params: ConnectOptions): Promise<Browser> {- return await this._wrapApiCall(async () => {- const browser = await connectToBrowser(this._playwright, { browserName: this.name(), ...params });- browser._connectToBrowserType(this, {}, undefined);- return browser;- });+ const browser = await connectToBrowser(this._playwright, { browserName: this.name(), ...params });+ browser._connectToBrowserType(this, {}, undefined);+ return browser;}async connectOverCDP(options: api.ConnectOverCDPOptions & { wsEndpoint?: string }): Promise<api.Browser>;diff --git a/packages/playwright-core/src/client/channelOwner.ts b/packages/playwright-core/src/client/channelOwner.tsindex 079c4e36c4..ee9099b61e 100644--- a/packages/playwright-core/src/client/channelOwner.ts+++ b/packages/playwright-core/src/client/channelOwner.ts@@ -186,7 +186,7 @@ export abstract class ChannelOwner<T extends channels.Channel = channels.Channelreturn channel;}- async _wrapApiCall<R>(func: (apiZone: ApiZone) => Promise<R>, options?: { internal?: boolean, title?: string }): Promise<R> {+ async _wrapApiCall<R>(func: (apiZone: ApiZone) => Promise<R>, options?: ApiCallOptions): Promise<R> {const logger = this._logger;const existingApiZone = currentZone().data<ApiZone>('apiZone');if (existingApiZone)@@ -235,6 +235,27 @@ export abstract class ChannelOwner<T extends channels.Channel = channels.Channel}}+export type ApiCallOptions = { title?: string, internal?: boolean };+type ApiCallScope = { _wrapApiCall<R>(func: () => Promise<R>, options?: ApiCallOptions): Promise<R> };+type ApiCallMethod<This> = (this: This, ...args: any[]) => Promise<any>;++export function apiCall(options?: { title?: string }) {+ return wrapApiCallDecorator(options);+}++export const internal = wrapApiCallDecorator({ internal: true });++function wrapApiCallDecorator(options: ApiCallOptions | undefined) {+ return function<This extends ApiCallScope, T extends ApiCallMethod<This>>(method: T, context: ClassMethodDecoratorContext<This, T>): T {+ const wrapper = function(this: This, ...args: any[]) {+ return this._wrapApiCall(() => method.apply(this, args), options);+ };+ // Stack traces name the wrapper after the method, api name is derived from the stack.+ Object.defineProperty(wrapper, 'name', { value: context.name });+ return wrapper as T;+ };+}+function logApiCall(logger: Logger | undefined, message: string) {if (logger && logger.isEnabled('api', 'info'))logger.log('api', 'info', message, [], { color: 'cyan' });diff --git a/packages/playwright-core/src/client/electron.ts b/packages/playwright-core/src/client/electron.tsindex ffbba3bb25..7f47117714 100644--- a/packages/playwright-core/src/client/electron.ts+++ b/packages/playwright-core/src/client/electron.ts@@ -15,7 +15,7 @@*/import { BrowserContext, prepareBrowserContextParams } from './browserContext';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall } from './channelOwner';import { envObjectToArray } from './clientHelper';import { ConsoleMessage } from './consoleMessage';import { TargetClosedError, isTargetClosedError } from './errors';@@ -139,18 +139,17 @@ export class ElectronApplication extends ChannelOwner<channels.ElectronApplicati}}+ @apiCall()async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {- return await this._wrapApiCall(async () => {- const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- const waiter = Waiter.createForEvent(this, event);- waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);- if (event !== Events.ElectronApplication.Close)- waiter.rejectOnEvent(this, Events.ElectronApplication.Close, () => new TargetClosedError());- const result = await waiter.waitForEvent(this, event, predicate as any);- waiter.dispose();- return result;- });+ const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);+ const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;+ const waiter = Waiter.createForEvent(this, event);+ waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);+ if (event !== Events.ElectronApplication.Close)+ waiter.rejectOnEvent(this, Events.ElectronApplication.Close, () => new TargetClosedError());+ const result = await waiter.waitForEvent(this, event, predicate as any);+ waiter.dispose();+ return result;}async browserWindow(page: Page): Promise<JSHandle<BrowserWindow>> {diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.tsindex c69f60a2e3..68d71d81ab 100644--- a/packages/playwright-core/src/client/fetch.ts+++ b/packages/playwright-core/src/client/fetch.ts@@ -22,13 +22,14 @@ import { assert } from '@isomorphic/assert';import { headersObjectToArray } from '@isomorphic/headers';import { isString } from '@isomorphic/rtti';import { toClientCertificatesProtocol, toHttpCredentialsProtocol } from './browserContext';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall, internal } from './channelOwner';import { TargetClosedError, isTargetClosedError } from './errors';import { RawHeaders, toClearCookiesParams } from './network';import { Tracing } from './tracing';import { mkdirIfNeeded } from './fileUtils';import { TimeoutSettings, kNoTimeout } from './timeoutSettings';+import type { ApiCallOptions } from './channelOwner';import type { Playwright } from './playwright';import type { ClearNetworkCookieOptions, NetworkCookie, ResourceTiming, SetNetworkCookieParam } from './network';import type { ClientCertificate, FilePayload, Headers, RemoteAddr, SecurityDetails, SetStorageState, StorageState, TimeoutOptions } from './types';@@ -186,6 +187,7 @@ export class APIRequestContext extends ChannelOwner<channels.APIRequestContextCh});}+ @apiCall()async fetch(urlOrRequest: string | api.Request, options: FetchOptions = {}): Promise<APIResponse> {const url = isString(urlOrRequest) ? urlOrRequest : undefined;const request = isString(urlOrRequest) ? undefined : urlOrRequest;@@ -193,96 +195,94 @@ export class APIRequestContext extends ChannelOwner<channels.APIRequestContextCh}async _innerFetch(options: FetchOptions & { url?: string, request?: api.Request } = {}): Promise<APIResponse> {- return await this._wrapApiCall(async () => {- if (this._closeReason)- throw new TargetClosedError(this._closeReason);- assert(options.request || typeof options.url === 'string', 'First argument must be either URL string or Request');- assert((options.data === undefined ? 0 : 1) + (options.form === undefined ? 0 : 1) + (options.multipart === undefined ? 0 : 1) <= 1, `Only one of 'data', 'form' or 'multipart' can be specified`);- assert(options.maxRedirects === undefined || options.maxRedirects >= 0, `'maxRedirects' must be greater than or equal to '0'`);- assert(options.maxRetries === undefined || options.maxRetries >= 0, `'maxRetries' must be greater than or equal to '0'`);- const url = options.url !== undefined ? options.url : options.request!.url();- const method = options.method || options.request?.method();- let encodedParams = undefined;- if (typeof options.params === 'string')- encodedParams = options.params;- else if (options.params instanceof URLSearchParams)- encodedParams = options.params.toString();- // Cannot call allHeaders() here as the request may be paused inside route handler.- const headersObj = options.headers || options.request?.headers();- const headers = headersObj ? headersObjectToArray(headersObj) : undefined;- let jsonData: any;- let formData: channels.NameValue[] | undefined;- let multipartData: channels.FormField[] | undefined;- let postDataBuffer: Buffer | undefined;- if (options.data !== undefined) {- if (isString(options.data)) {- if (isJsonContentType(headers))- jsonData = isJsonParsable(options.data) ? options.data : JSON.stringify(options.data);- else- postDataBuffer = Buffer.from(options.data, 'utf8');- } else if (Buffer.isBuffer(options.data)) {- postDataBuffer = options.data;- } else if (typeof options.data === 'object' || typeof options.data === 'number' || typeof options.data === 'boolean') {- jsonData = JSON.stringify(options.data);- } else {- throw new Error(`Unexpected 'data' type`);- }- } else if (options.form) {- if (globalThis.FormData && options.form instanceof FormData) {- formData = [];- for (const [name, value] of options.form.entries()) {- if (typeof value !== 'string')- throw new Error(`Expected string for options.form["${name}"], found File. Please use options.multipart instead.`);- formData.push({ name, value });- }- } else {- formData = objectToArray(options.form);+ if (this._closeReason)+ throw new TargetClosedError(this._closeReason);+ assert(options.request || typeof options.url === 'string', 'First argument must be either URL string or Request');+ assert((options.data === undefined ? 0 : 1) + (options.form === undefined ? 0 : 1) + (options.multipart === undefined ? 0 : 1) <= 1, `Only one of 'data', 'form' or 'multipart' can be specified`);+ assert(options.maxRedirects === undefined || options.maxRedirects >= 0, `'maxRedirects' must be greater than or equal to '0'`);+ assert(options.maxRetries === undefined || options.maxRetries >= 0, `'maxRetries' must be greater than or equal to '0'`);+ const url = options.url !== undefined ? options.url : options.request!.url();+ const method = options.method || options.request?.method();+ let encodedParams = undefined;+ if (typeof options.params === 'string')+ encodedParams = options.params;+ else if (options.params instanceof URLSearchParams)+ encodedParams = options.params.toString();+ // Cannot call allHeaders() here as the request may be paused inside route handler.+ const headersObj = options.headers || options.request?.headers();+ const headers = headersObj ? headersObjectToArray(headersObj) : undefined;+ let jsonData: any;+ let formData: channels.NameValue[] | undefined;+ let multipartData: channels.FormField[] | undefined;+ let postDataBuffer: Buffer | undefined;+ if (options.data !== undefined) {+ if (isString(options.data)) {+ if (isJsonContentType(headers))+ jsonData = isJsonParsable(options.data) ? options.data : JSON.stringify(options.data);+ else+ postDataBuffer = Buffer.from(options.data, 'utf8');+ } else if (Buffer.isBuffer(options.data)) {+ postDataBuffer = options.data;+ } else if (typeof options.data === 'object' || typeof options.data === 'number' || typeof options.data === 'boolean') {+ jsonData = JSON.stringify(options.data);+ } else {+ throw new Error(`Unexpected 'data' type`);+ }+ } else if (options.form) {+ if (globalThis.FormData && options.form instanceof FormData) {+ formData = [];+ for (const [name, value] of options.form.entries()) {+ if (typeof value !== 'string')+ throw new Error(`Expected string for options.form["${name}"], found File. Please use options.multipart instead.`);+ formData.push({ name, value });}- } else if (options.multipart) {- multipartData = [];- if (globalThis.FormData && options.multipart instanceof FormData) {- const form = options.multipart;- for (const [name, value] of form.entries()) {- if (isString(value)) {- multipartData.push({ name, value });- } else {- const file: ServerFilePayload = {- name: value.name,- mimeType: value.type,- buffer: Buffer.from(await value.arrayBuffer()),- };- multipartData.push({ name, file });- }+ } else {+ formData = objectToArray(options.form);+ }+ } else if (options.multipart) {+ multipartData = [];+ if (globalThis.FormData && options.multipart instanceof FormData) {+ const form = options.multipart;+ for (const [name, value] of form.entries()) {+ if (isString(value)) {+ multipartData.push({ name, value });+ } else {+ const file: ServerFilePayload = {+ name: value.name,+ mimeType: value.type,+ buffer: Buffer.from(await value.arrayBuffer()),+ };+ multipartData.push({ name, file });}- } else {- // Convert file-like values to ServerFilePayload structs.- for (const [name, value] of Object.entries(options.multipart))- multipartData.push(await toFormField(name, value));}+ } else {+ // Convert file-like values to ServerFilePayload structs.+ for (const [name, value] of Object.entries(options.multipart))+ multipartData.push(await toFormField(name, value));}- if (postDataBuffer === undefined && jsonData === undefined && formData === undefined && multipartData === undefined)- postDataBuffer = options.request?.postDataBuffer() || undefined;- const fixtures = {- __testHookLookup: (options as any).__testHookLookup- };- const result = await this._channel.fetch({- url,- params: typeof options.params === 'object' ? objectToArray(options.params) : undefined,- encodedParams,- method,- headers,- postData: postDataBuffer,- jsonData,- formData,- multipartData,- failOnStatusCode: options.failOnStatusCode,- ignoreHTTPSErrors: options.ignoreHTTPSErrors,- maxRedirects: options.maxRedirects,- maxRetries: options.maxRetries,- ...fixtures- }, this._timeoutSettings.timeout(options));- return new APIResponse(this, result.response);- });+ }+ if (postDataBuffer === undefined && jsonData === undefined && formData === undefined && multipartData === undefined)+ postDataBuffer = options.request?.postDataBuffer() || undefined;+ const fixtures = {+ __testHookLookup: (options as any).__testHookLookup+ };+ const result = await this._channel.fetch({+ url,+ params: typeof options.params === 'object' ? objectToArray(options.params) : undefined,+ encodedParams,+ method,+ headers,+ postData: postDataBuffer,+ jsonData,+ formData,+ multipartData,+ failOnStatusCode: options.failOnStatusCode,+ ignoreHTTPSErrors: options.ignoreHTTPSErrors,+ maxRedirects: options.maxRedirects,+ maxRetries: options.maxRetries,+ ...fixtures+ }, this._timeoutSettings.timeout(options));+ return new APIResponse(this, result.response);}async storageState(options: { path?: string, indexedDB?: boolean, opfs?: boolean } = {}): Promise<StorageState> {@@ -338,6 +338,10 @@ export class APIResponse implements api.APIResponse {(this as any)[inspect.custom] = () => this._inspect();}+ async _wrapApiCall<R>(func: () => Promise<R>, options?: ApiCallOptions): Promise<R> {+ return await this._request._wrapApiCall(func, options);+ }+ok(): boolean {return this._initializer.status >= 200 && this._initializer.status <= 299;}@@ -385,19 +389,18 @@ export class APIResponse implements api.APIResponse {};}+ @internalasync body(): Promise<Buffer> {- return await this._request._wrapApiCall(async () => {- try {- const result = await this._request._channel.fetchResponseBody({ fetchUid: this._fetchUid() }, kNoTimeout);- if (result.binary === undefined)- throw new Error('Response has been disposed');- return result.binary;- } catch (e) {- if (isTargetClosedError(e))- throw new Error('Response has been disposed');- throw e;- }- }, { internal: true });+ try {+ const result = await this._request._channel.fetchResponseBody({ fetchUid: this._fetchUid() }, kNoTimeout);+ if (result.binary === undefined)+ throw new Error('Response has been disposed');+ return result.binary;+ } catch (e) {+ if (isTargetClosedError(e))+ throw new Error('Response has been disposed');+ throw e;+ }}async text(): Promise<string> {diff --git a/packages/playwright-core/src/client/frame.ts b/packages/playwright-core/src/client/frame.tsindex 80250a6118..e6a17a7707 100644--- a/packages/playwright-core/src/client/frame.ts+++ b/packages/playwright-core/src/client/frame.ts@@ -23,7 +23,7 @@ import { getByAltTextSelector, getByLabelSelector, getByPlaceholderSelector, getimport { kAnyFrameSelector } from '@isomorphic/selectorParser';import { urlMatches } from '@isomorphic/urlMatch';import { EventEmitter } from './eventEmitter';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall } from './channelOwner';import { addSourceUrlToScript } from './clientHelper';import { ElementHandle, convertInputFiles, convertSelectOptionValues } from './elementHandle';import { AbortError, PlaywrightError } from './errors';@@ -143,59 +143,57 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Frreturn waiter;}+ @apiCall({ title: 'Wait for navigation' })async waitForNavigation(options: WaitForNavigationOptions = {}): Promise<network.Response | null> {- return await this._page!._wrapApiCall(async () => {- const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);- const waiter = this._setupNavigationWaiter(options);-- const toUrl = typeof options.url === 'string' ? ` to "${options.url}"` : '';- waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`);-- const navigatedEvent = await waiter.waitForEvent<channels.FrameNavigatedEvent>(this._eventEmitter, 'navigated', event => {- // Any failed navigation results in a rejection.- if (event.error)- return true;- waiter.log(` navigated to "${event.url}"`);- return urlMatches(this._page?.context()._options.baseURL, event.url, options.url);- });- if (navigatedEvent.error) {- const e = new Error(navigatedEvent.error);- e.stack = '';- await waiter.waitForPromise(Promise.reject(e));- }+ const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);+ const waiter = this._setupNavigationWaiter(options);- if (!this._loadStates.has(waitUntil)) {- await waiter.waitForEvent<LifecycleEvent>(this._eventEmitter, 'loadstate', s => {- waiter.log(` "${s}" event fired`);- return s === waitUntil;- });- }+ const toUrl = typeof options.url === 'string' ? ` to "${options.url}"` : '';+ waiter.log(`waiting for navigation${toUrl} until "${waitUntil}"`);- const request = navigatedEvent.newDocument ? network.Request.fromNullable(navigatedEvent.newDocument.request) : null;- const response = request ? await waiter.waitForPromise(request._finalRequest()._internalResponse()) : null;- waiter.dispose();- return response;- }, { title: 'Wait for navigation' });+ const navigatedEvent = await waiter.waitForEvent<channels.FrameNavigatedEvent>(this._eventEmitter, 'navigated', event => {+ // Any failed navigation results in a rejection.+ if (event.error)+ return true;+ waiter.log(` navigated to "${event.url}"`);+ return urlMatches(this._page?.context()._options.baseURL, event.url, options.url);+ });+ if (navigatedEvent.error) {+ const e = new Error(navigatedEvent.error);+ e.stack = '';+ await waiter.waitForPromise(Promise.reject(e));+ }++ if (!this._loadStates.has(waitUntil)) {+ await waiter.waitForEvent<LifecycleEvent>(this._eventEmitter, 'loadstate', s => {+ waiter.log(` "${s}" event fired`);+ return s === waitUntil;+ });+ }++ const request = navigatedEvent.newDocument ? network.Request.fromNullable(navigatedEvent.newDocument.request) : null;+ const response = request ? await waiter.waitForPromise(request._finalRequest()._internalResponse()) : null;+ waiter.dispose();+ return response;}+ @apiCall({ title: 'Wait for load state' })async waitForLoadState(state: LifecycleEvent = 'load', options?: TimeoutOptions): Promise<void> {state = verifyLoadState('state', state);- return await this._page!._wrapApiCall(async () => {- const waiter = this._setupNavigationWaiter(options ?? {});- try {- if (this._loadStates.has(state)) {- waiter.log(` not waiting, "${state}" event already fired`);- waiter.throwIfImmediatelyRejected();- } else {- await waiter.waitForEvent<LifecycleEvent>(this._eventEmitter, 'loadstate', s => {- waiter.log(` "${s}" event fired`);- return s === state;- });- }- } finally {- waiter.dispose();+ const waiter = this._setupNavigationWaiter(options ?? {});+ try {+ if (this._loadStates.has(state)) {+ waiter.log(` not waiting, "${state}" event already fired`);+ waiter.throwIfImmediatelyRejected();+ } else {+ await waiter.waitForEvent<LifecycleEvent>(this._eventEmitter, 'loadstate', s => {+ waiter.log(` "${s}" event fired`);+ return s === state;+ });}- }, { title: `Wait for load state "${state}"` });+ } finally {+ waiter.dispose();+ }}async waitForURL(url: URLMatch, options?: { waitUntil?: LifecycleEvent } & TimeoutOptions): Promise<void> {diff --git a/packages/playwright-core/src/client/input.ts b/packages/playwright-core/src/client/input.tsindex 8ff99de6be..117d665bbd 100644--- a/packages/playwright-core/src/client/input.ts+++ b/packages/playwright-core/src/client/input.ts@@ -15,7 +15,9 @@* limitations under the License.*/+import { apiCall } from './channelOwner';import { kNoTimeout } from './timeoutSettings';+import type { ApiCallOptions } from './channelOwner';import type { Page } from './page';import type * as api from '../../types/types';import type * as channels from './channels';@@ -55,6 +57,10 @@ export class Mouse implements api.Mouse {this._page = page;}+ async _wrapApiCall<R>(func: () => Promise<R>, options?: ApiCallOptions): Promise<R> {+ return await this._page._wrapApiCall(func, options);+ }+async move(x: number, y: number, options: { steps?: number } = {}) {await this._page._channel.mouseMove({ x, y, ...options }, kNoTimeout);}@@ -71,10 +77,9 @@ export class Mouse implements api.Mouse {await this._page._channel.mouseClick({ x, y, ...options }, kNoTimeout);}+ @apiCall({ title: 'Double click' })async dblclick(x: number, y: number, options: Omit<channels.PageMouseClickOptions, 'clickCount'> = {}) {- await this._page._wrapApiCall(async () => {- await this.click(x, y, { ...options, clickCount: 2 });- }, { title: 'Double click' });+ await this.click(x, y, { ...options, clickCount: 2 });}async wheel(deltaX: number, deltaY: number) {diff --git a/packages/playwright-core/src/client/locator.ts b/packages/playwright-core/src/client/locator.tsindex da55f7ba4f..0fee8fa2ff 100644--- a/packages/playwright-core/src/client/locator.ts+++ b/packages/playwright-core/src/client/locator.ts@@ -26,7 +26,9 @@ import { ElementHandle } from './elementHandle';import { serializeArgument } from './jsHandle';import { DisposableStub } from './disposable';import { kNoTimeout } from './timeoutSettings';+import { apiCall } from './channelOwner';+import type { ApiCallOptions } from './channelOwner';import type { ExpectResult, Frame } from './frame';import type { EvaluateOptions } from './jsHandle';import type { DropPayload, FilePayload, FrameExpectParams, Rect, SelectOption, SelectOptionOptions, TimeoutOptions } from './types';@@ -81,21 +83,23 @@ export class Locator implements api.Locator {(this as any)[inspect.custom] = () => this._inspect();}- private async _withElement<R>(task: (handle: ElementHandle<SVGElement | HTMLElement>, timeout?: number) => Promise<R>, options: { title: string, internal?: boolean, timeout?: number, signal?: AbortSignal }): Promise<R> {+ async _wrapApiCall<R>(func: () => Promise<R>, options?: ApiCallOptions): Promise<R> {+ return await this._frame._wrapApiCall(func, options);+ }++ private async _withElement<R>(task: (handle: ElementHandle<SVGElement | HTMLElement>, timeout?: number) => Promise<R>, options: { timeout?: number, signal?: AbortSignal }): Promise<R> {const timeout = this._frame._timeout({ timeout: options.timeout }).timeout;const deadline = timeout ? monotonicTime() + timeout : 0;- return await this._frame._wrapApiCall<R>(async () => {- const result = await this._frame._channel.waitForSelector({ selector: this._selector, strict: true, state: 'attached' }, { signal: options.signal, timeout });- const handle = ElementHandle.fromNullable(result.element) as ElementHandle<SVGElement | HTMLElement> | null;- if (!handle)- throw new Error(`Could not resolve ${this._selector} to DOM Element`);- try {- return await task(handle, deadline ? deadline - monotonicTime() : 0);- } finally {- await handle.dispose();- }- }, { title: options.title, internal: options.internal });+ const result = await this._frame._channel.waitForSelector({ selector: this._selector, strict: true, state: 'attached' }, { signal: options.signal, timeout });+ const handle = ElementHandle.fromNullable(result.element) as ElementHandle<SVGElement | HTMLElement> | null;+ if (!handle)+ throw new Error(`Could not resolve ${this._selector} to DOM Element`);+ try {+ return await task(handle, deadline ? deadline - monotonicTime() : 0);+ } finally {+ await handle.dispose();+ }}_equals(locator: Locator) {@@ -106,8 +110,9 @@ export class Locator implements api.Locator {return this._frame.page();}+ @apiCall({ title: 'Bounding box' })async boundingBox(options?: TimeoutOptions): Promise<Rect | null> {- return await this._withElement(h => h.boundingBox(), { title: 'Bounding box', timeout: options?.timeout, signal: options?.signal });+ return await this._withElement(h => h.boundingBox(), { timeout: options?.timeout, signal: options?.signal });}async check(options: channels.ElementHandleCheckOptions & TimeoutOptions = {}) {@@ -137,24 +142,27 @@ export class Locator implements api.Locator {await this._frame._drop(this._selector, payload, { strict: true, ...options });}+ @apiCall({ title: 'Evaluate' })async evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<SVGElement | HTMLElement, Arg, R>, arg?: Arg, options?: TimeoutOptions & EvaluateOptions): Promise<R> {- return await this._withElement(h => h.evaluate(pageFunction, arg, options), { title: 'Evaluate', timeout: options?.timeout, signal: options?.signal });+ return await this._withElement(h => h.evaluate(pageFunction, arg, options), { timeout: options?.timeout, signal: options?.signal });}async evaluateAll<R, Arg>(pageFunction: structs.PageFunctionOn<Element[], Arg, R>, arg?: Arg): Promise<R> {return await this._frame.$$eval(this._selector, pageFunction, arg);}+ @apiCall({ title: 'Evaluate' })async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<any, Arg, R>, arg?: Arg, options?: TimeoutOptions & EvaluateOptions): Promise<structs.SmartHandle<R>> {- return await this._withElement(h => h.evaluateHandle(pageFunction, arg, options), { title: 'Evaluate', timeout: options?.timeout, signal: options?.signal });+ return await this._withElement(h => h.evaluateHandle(pageFunction, arg, options), { timeout: options?.timeout, signal: options?.signal });}async fill(value: string, options: channels.ElementHandleFillOptions & TimeoutOptions = {}): Promise<void> {return await this._frame.fill(this._selector, value, { strict: true, ...options });}+ @apiCall({ title: 'Clear' })async clear(options: channels.ElementHandleFillOptions = {}): Promise<void> {- await this._frame._wrapApiCall(() => this.fill('', options), { title: 'Clear' });+ await this.fill('', options);}async _highlight() {@@ -333,9 +341,10 @@ export class Locator implements api.Locator {return await this._frame.press(this._selector, key, { strict: true, ...options });}+ @apiCall({ title: 'Screenshot' })async screenshot(options: Omit<channels.ElementHandleScreenshotOptions, 'mask'> & TimeoutOptions & { path?: string, mask?: api.Locator[] } = {}): Promise<Buffer> {const mask = options.mask as Locator[] | undefined;- return await this._withElement((h, timeout) => h.screenshot({ ...options, mask, timeout }), { title: 'Screenshot', timeout: options.timeout, signal: options.signal });+ return await this._withElement((h, timeout) => h.screenshot({ ...options, mask, timeout }), { timeout: options.timeout, signal: options.signal });}async ariaSnapshot(options: TimeoutOptions & { mode?: 'ai' | 'default', depth?: number, boxes?: boolean } = {}): Promise<string> {@@ -348,16 +357,18 @@ export class Locator implements api.Locator {return result.snapshot;}+ @apiCall({ title: 'Scroll into view' })async scrollIntoViewIfNeeded(options: channels.ElementHandleScrollIntoViewIfNeededOptions & TimeoutOptions = {}) {- return await this._withElement((h, timeout) => h.scrollIntoViewIfNeeded({ ...options, timeout }), { title: 'Scroll into view', timeout: options.timeout, signal: options.signal });+ return await this._withElement((h, timeout) => h.scrollIntoViewIfNeeded({ ...options, timeout }), { timeout: options.timeout, signal: options.signal });}async selectOption(values: string | api.ElementHandle | SelectOption | string[] | api.ElementHandle[] | SelectOption[] | null, options: SelectOptionOptions = {}): Promise<string[]> {return await this._frame.selectOption(this._selector, values, { strict: true, ...options });}+ @apiCall({ title: 'Select text' })async selectText(options: channels.ElementHandleSelectTextOptions & TimeoutOptions = {}): Promise<void> {- return await this._withElement((h, timeout) => h.selectText({ ...options, timeout }), { title: 'Select text', timeout: options.timeout, signal: options.signal });+ return await this._withElement((h, timeout) => h.selectText({ ...options, timeout }), { timeout: options.timeout, signal: options.signal });}async setChecked(checked: boolean, options?: channels.ElementHandleCheckOptions & TimeoutOptions) {diff --git a/packages/playwright-core/src/client/network.ts b/packages/playwright-core/src/client/network.tsindex 52cad6aeeb..817c58585d 100644--- a/packages/playwright-core/src/client/network.ts+++ b/packages/playwright-core/src/client/network.ts@@ -31,7 +31,7 @@ import { Frame } from './frame';import { APIResponse } from './fetch';import { Events } from './events';import { isTargetClosedError } from './errors';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall, internal } from './channelOwner';import { kNoTimeout } from './timeoutSettings';import type { BrowserContext } from './browserContext';@@ -192,22 +192,22 @@ export class Request extends ChannelOwner<channels.RequestChannel> implements apif (this._fallbackOverrides.headers)return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers);- if (!this._actualHeadersPromise) {- this._actualHeadersPromise = this._wrapApiCall(async () => {- return new RawHeaders((await this._channel.rawRequestHeaders({}, kNoTimeout)).headers);- }, { internal: true });- }+ if (!this._actualHeadersPromise)+ this._actualHeadersPromise = this._channel.rawRequestHeaders({}, kNoTimeout).then(result => new RawHeaders(result.headers));return await this._actualHeadersPromise;}+ @internalasync allHeaders(): Promise<Headers> {return (await this._actualHeaders()).headers();}+ @internalasync headersArray(): Promise<HeadersArray> {return (await this._actualHeaders()).headersArray();}+ @internalasync headerValue(name: string): Promise<string | null> {return (await this._actualHeaders()).get(name);}@@ -361,10 +361,9 @@ export class Route extends ChannelOwner<channels.RouteChannel> implements api.Ro});}+ @apiCall()async fetch(options: FallbackOverrides & { maxRedirects?: number, maxRetries?: number, timeout?: number, signal?: AbortSignal } = {}): Promise<APIResponse> {- return await this._wrapApiCall(async () => {- return await this._context.request._innerFetch({ request: this.request(), data: options.postData, ...options });- });+ return await this._context.request._innerFetch({ request: this.request(), data: options.postData, ...options });}async fulfill(options: { response?: api.APIResponse, status?: number, headers?: Headers, contentType?: string, body?: string | Buffer, json?: any, path?: string } = {}) {@@ -816,21 +815,20 @@ export class WebSocket extends ChannelOwner<channels.WebSocketChannel> implementreturn this._isClosed;}+ @apiCall()async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {- return await this._wrapApiCall(async () => {- const timeoutOptions = this._page._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- const waiter = Waiter.createForEvent(this, event);- waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);- if (event !== Events.WebSocket.Error)- waiter.rejectOnEvent(this, Events.WebSocket.Error, new Error('Socket error'));- if (event !== Events.WebSocket.Close)- waiter.rejectOnEvent(this, Events.WebSocket.Close, new Error('Socket closed'));- waiter.rejectOnEvent(this._page, Events.Page.Close, () => this._page._closeErrorWithReason());- const result = await waiter.waitForEvent(this, event, predicate as any);- waiter.dispose();- return result;- });+ const timeoutOptions = this._page._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);+ const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;+ const waiter = Waiter.createForEvent(this, event);+ waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);+ if (event !== Events.WebSocket.Error)+ waiter.rejectOnEvent(this, Events.WebSocket.Error, new Error('Socket error'));+ if (event !== Events.WebSocket.Close)+ waiter.rejectOnEvent(this, Events.WebSocket.Close, new Error('Socket closed'));+ waiter.rejectOnEvent(this._page, Events.Page.Close, () => this._page._closeErrorWithReason());+ const result = await waiter.waitForEvent(this, event, predicate as any);+ waiter.dispose();+ return result;}}diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.tsindex 063a6176b0..935ee24919 100644--- a/packages/playwright-core/src/client/page.ts+++ b/packages/playwright-core/src/client/page.ts@@ -27,7 +27,7 @@ import { urlMatches, urlMatchesEqual } from '@isomorphic/urlMatch';import { LongStandingScope } from '@isomorphic/manualPromise';import { isObject, isRegExp, isString } from '@isomorphic/rtti';import { Artifact } from './artifact';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall, internal } from './channelOwner';import { evaluationScript, initScriptSourceWithExposedFunctions } from './clientHelper';import { Coverage } from './coverage';import { DisposableObject, DisposableStub } from './disposable';@@ -225,7 +225,7 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagethis._routes.splice(index, 1);const handled = await routeHandler.handle(route);if (!this._routes.length)- this._updateInterceptionPatterns({ internal: true }).catch(() => {});+ this._disableInterception().catch(() => {});if (handled)return;}@@ -473,6 +473,7 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagereturn await this._mainFrame.waitForURL(url, options);}+ @apiCall()async waitForRequest(urlOrPredicate: string | RegExp | ((r: Request) => boolean | Promise<boolean>), options: TimeoutOptions = {}): Promise<Request> {const predicate = async (request: Request) => {if (isString(urlOrPredicate) || isRegExp(urlOrPredicate))@@ -484,6 +485,7 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagereturn await this._waitForEvent(Events.Page.Request, { predicate, timeout: options.timeout, signal: options.signal }, logLine);}+ @apiCall()async waitForResponse(urlOrPredicate: string | RegExp | ((r: Response) => boolean | Promise<boolean>), options: TimeoutOptions = {}): Promise<Response> {const predicate = async (response: Response) => {if (isString(urlOrPredicate) || isRegExp(urlOrPredicate))@@ -495,6 +497,7 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagereturn await this._waitForEvent(Events.Page.Response, { predicate, timeout: options.timeout, signal: options.signal }, logLine);}+ @apiCall()async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {return await this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);}@@ -504,21 +507,19 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Page}private async _waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions, logLine?: string): Promise<any> {- return await this._wrapApiCall(async () => {- const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- const waiter = Waiter.createForEvent(this, event);- if (logLine)- waiter.log(logLine);- waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);- if (event !== Events.Page.Crash)- waiter.rejectOnEvent(this, Events.Page.Crash, new Error('Page crashed'));- if (event !== Events.Page.Close)- waiter.rejectOnEvent(this, Events.Page.Close, () => this._closeErrorWithReason());- const result = await waiter.waitForEvent(this, event, predicate as any);- waiter.dispose();- return result;- });+ const timeoutOptions = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);+ const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;+ const waiter = Waiter.createForEvent(this, event);+ if (logLine)+ waiter.log(logLine);+ waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);+ if (event !== Events.Page.Crash)+ waiter.rejectOnEvent(this, Events.Page.Crash, new Error('Page crashed'));+ if (event !== Events.Page.Close)+ waiter.rejectOnEvent(this, Events.Page.Close, () => this._closeErrorWithReason());+ const result = await waiter.waitForEvent(this, event, predicate as any);+ waiter.dispose();+ return result;}async goBack(options: channels.PageGoBackOptions & TimeoutOptions = {}): Promise<Response | null> {@@ -567,9 +568,10 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagereturn DisposableObject.from((await this._channel.addInitScript({ source }, kNoTimeout)).disposable);}+ @apiCall({ title: 'Route requests' })async route(url: URLMatch, handler: RouteHandlerCallback, options: { times?: number } = {}): Promise<DisposableStub> {this._routes.unshift(new RouteHandler(this._browserContext._options.baseURL, url, handler, options.times));- await this._updateInterceptionPatterns({ title: 'Route requests' });+ await this._updateInterceptionPatterns();return new DisposableStub(() => this.unroute(url, handler));}@@ -586,9 +588,10 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pageawait harRouter.addPageRoute(this);}+ @apiCall({ title: 'Route WebSockets' })async routeWebSocket(url: URLMatch, handler: WebSocketRouteHandlerCallback): Promise<void> {this._webSocketRoutes.unshift(new WebSocketRouteHandler(this._browserContext._options.baseURL, url, handler));- await this._updateWebSocketInterceptionPatterns({ title: 'Route WebSockets' });+ await this._updateWebSocketInterceptionPatterns();}private _disposeHarRouters() {@@ -596,11 +599,13 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pagethis._harRouters = [];}+ @apiCall({ title: 'Unroute requests' })async unrouteAll(options?: { behavior?: 'wait'|'ignoreErrors'|'default' }): Promise<void> {await this._unrouteInternal(this._routes, [], options?.behavior);this._disposeHarRouters();}+ @apiCall({ title: 'Unroute requests' })async unroute(url: URLMatch, handler?: RouteHandlerCallback): Promise<void> {const removed = [];const remaining = [];@@ -619,17 +624,22 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Pageconst promises = removed.map(routeHandler => routeHandler.stop(behavior));await Promise.all(promises);}- await this._updateInterceptionPatterns({ title: 'Unroute requests' });+ await this._updateInterceptionPatterns();+ }++ @internal+ private async _disableInterception() {+ await this._updateInterceptionPatterns();}- private async _updateInterceptionPatterns(options: { internal: true } | { title: string }) {+ private async _updateInterceptionPatterns() {const patterns = RouteHandler.prepareInterceptionPatterns(this._routes);- await this._wrapApiCall(() => this._channel.setNetworkInterceptionPatterns({ patterns }, kNoTimeout), options);+ await this._channel.setNetworkInterceptionPatterns({ patterns }, kNoTimeout);}- private async _updateWebSocketInterceptionPatterns(options: { internal: true } | { title: string }) {+ private async _updateWebSocketInterceptionPatterns() {const patterns = WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes);- await this._wrapApiCall(() => this._channel.setWebSocketInterceptionPatterns({ patterns }, kNoTimeout), options);+ await this._channel.setWebSocketInterceptionPatterns({ patterns }, kNoTimeout);}async screenshot(options: Omit<channels.PageScreenshotOptions, 'mask'> & TimeoutOptions & { path?: string, mask?: api.Locator[] } = {}): Promise<Buffer> {diff --git a/packages/playwright-core/src/client/screencast.ts b/packages/playwright-core/src/client/screencast.tsindex 8ceeeef52b..87664fbe76 100644--- a/packages/playwright-core/src/client/screencast.ts+++ b/packages/playwright-core/src/client/screencast.ts@@ -15,10 +15,12 @@*/import { Artifact } from './artifact';+import { apiCall } from './channelOwner';import { DisposableStub } from './disposable';import { kNoTimeout } from './timeoutSettings';import type * as api from '../../types/types';+import type { ApiCallOptions } from './channelOwner';import type { Page } from './page';export class Screencast implements api.Screencast {@@ -39,6 +41,10 @@ export class Screencast implements api.Screencast {});}+ async _wrapApiCall<R>(func: () => Promise<R>, options?: ApiCallOptions): Promise<R> {+ return await this._page._wrapApiCall(func, options);+ }+async start(options: { onFrame?: (frame: { data: Buffer, timestamp: number, viewportWidth: number, viewportHeight: number }) => Promise<any>|any, path?: string, size?: { width: number, height: number }, quality?: number, fps?: number } = {}): Promise<DisposableStub> {if (this._started)throw new Error('Screencast is already started');@@ -59,16 +65,15 @@ export class Screencast implements api.Screencast {return new DisposableStub(() => this.stop());}+ @apiCall()async stop(): Promise<void> {- await this._page._wrapApiCall(async () => {- this._started = false;- this._onFrame = null;- await this._page._channel.screencastStop({}, kNoTimeout);- if (this._savePath)- await this._artifact?.saveAs(this._savePath);- this._artifact = undefined;- this._savePath = undefined;- });+ this._started = false;+ this._onFrame = null;+ await this._page._channel.screencastStop({}, kNoTimeout);+ if (this._savePath)+ await this._artifact?.saveAs(this._savePath);+ this._artifact = undefined;+ this._savePath = undefined;}async showActions(options?: { duration?: number, position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right', fontSize?: number, cursor?: 'none' | 'pointer', style?: { point?: string, highlight?: string, title?: string } }): Promise<DisposableStub> {diff --git a/packages/playwright-core/src/client/tracing.ts b/packages/playwright-core/src/client/tracing.tsindex 705a6c3369..db9477a41e 100644--- a/packages/playwright-core/src/client/tracing.ts+++ b/packages/playwright-core/src/client/tracing.ts@@ -16,7 +16,7 @@import { isRegExp, isString } from '@isomorphic/rtti';import { Artifact } from './artifact';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall, internal } from './channelOwner';import { DisposableStub } from './disposable';import { kNoTimeout } from './timeoutSettings';@@ -42,31 +42,29 @@ export class Tracing extends ChannelOwner<channels.TracingChannel> implements apsuper(parent, type, guid, initializer);}+ @apiCall()async start(options: { name?: string, title?: string, snapshots?: boolean | { dom?: boolean, aria?: boolean, screen?: boolean }, screenshots?: boolean, _coverage?: boolean, sources?: boolean, live?: boolean } = {}) {- await this._wrapApiCall(async () => {- this._includeSources = !!options.sources;- this._isLive = !!options.live;- const snapshots = typeof options.snapshots === 'object' ? options.snapshots : { dom: options.snapshots };- await this._channel.tracingStart({- name: options.name,- snapshotDom: snapshots.dom,- snapshotAria: snapshots.aria,- snapshotScreen: snapshots.screen,- screencast: options.screenshots,- coverage: options._coverage,- live: options.live,- }, kNoTimeout);- const { traceName } = await this._channel.tracingStartChunk({ name: options.name, title: options.title }, kNoTimeout);- await this._startCollectingStacks(traceName, this._isLive);- });+ this._includeSources = !!options.sources;+ this._isLive = !!options.live;+ const snapshots = typeof options.snapshots === 'object' ? options.snapshots : { dom: options.snapshots };+ await this._channel.tracingStart({+ name: options.name,+ snapshotDom: snapshots.dom,+ snapshotAria: snapshots.aria,+ snapshotScreen: snapshots.screen,+ screencast: options.screenshots,+ coverage: options._coverage,+ live: options.live,+ }, kNoTimeout);+ const { traceName } = await this._channel.tracingStartChunk({ name: options.name, title: options.title }, kNoTimeout);+ await this._startCollectingStacks(traceName, this._isLive);return new DisposableStub(() => this.stop());}+ @apiCall()async startChunk(options: { name?: string, title?: string } = {}) {- await this._wrapApiCall(async () => {- const { traceName } = await this._channel.tracingStartChunk(options, kNoTimeout);- await this._startCollectingStacks(traceName, this._isLive);- });+ const { traceName } = await this._channel.tracingStartChunk(options, kNoTimeout);+ await this._startCollectingStacks(traceName, this._isLive);return new DisposableStub(() => this.stopChunk());}@@ -90,46 +88,42 @@ export class Tracing extends ChannelOwner<channels.TracingChannel> implements apthis._stacksId = result?.stacksId;}+ @apiCall()async stopChunk(options: { path?: string } = {}) {- await this._wrapApiCall(async () => {- await this._doStopChunk(options.path);- });+ await this._doStopChunk(options.path);}+ @apiCall()async stop(options: { path?: string } = {}) {- await this._wrapApiCall(async () => {- const error = await this._doStopChunk(options.path).catch(e => e);- await this._channel.tracingStop({}, kNoTimeout);- if (error)- throw error;- });+ const error = await this._doStopChunk(options.path).catch(e => e);+ await this._channel.tracingStop({}, kNoTimeout);+ if (error)+ throw error;}+ @apiCall()async startHar(path: string, options: { content?: 'embed' | 'attach' | 'omit', mode?: 'full' | 'minimal', urlFilter?: string | RegExp, resourcesDir?: string } = {}) {- await this._wrapApiCall(async () => {- if (this._harId)- throw new Error('HAR recording has already been started');- if (options.resourcesDir && path.endsWith('.zip'))- throw new Error('resourcesDir option is not compatible with a .zip har file');- const defaultContent = path.endsWith('.zip') ? 'attach' : 'embed';- this._harId = await this._recordIntoHAR(path, null, {- url: options.urlFilter,- updateContent: options.content ?? defaultContent,- updateMode: options.mode ?? 'full',- resourcesDir: options.resourcesDir,- });+ if (this._harId)+ throw new Error('HAR recording has already been started');+ if (options.resourcesDir && path.endsWith('.zip'))+ throw new Error('resourcesDir option is not compatible with a .zip har file');+ const defaultContent = path.endsWith('.zip') ? 'attach' : 'embed';+ this._harId = await this._recordIntoHAR(path, null, {+ url: options.urlFilter,+ updateContent: options.content ?? defaultContent,+ updateMode: options.mode ?? 'full',+ resourcesDir: options.resourcesDir,});return new DisposableStub(() => this.stopHar());}+ @apiCall()async stopHar() {- await this._wrapApiCall(async () => {- const harId = this._harId;- if (!harId)- throw new Error('HAR recording has not been started');- this._harId = undefined;- await this._exportHAR(harId);- });+ const harId = this._harId;+ if (!harId)+ throw new Error('HAR recording has not been started');+ this._harId = undefined;+ await this._exportHAR(harId);}async _recordIntoHAR(har: string, page: Page | null, options: { url?: string | RegExp, updateContent?: 'attach' | 'embed' | 'omit', updateMode?: 'minimal' | 'full', resourcesDir?: string } = {}): Promise<string> {@@ -186,10 +180,9 @@ export class Tracing extends ChannelOwner<channels.TracingChannel> implements apawait artifact.delete();}+ @internalasync _exportAllHars(): Promise<void> {- await this._wrapApiCall(async () => {- await Promise.all([...this._harRecorders.keys()].map(harId => this._exportHAR(harId)));- }, { internal: true });+ await Promise.all([...this._harRecorders.keys()].map(harId => this._exportHAR(harId)));}private async _doStopChunk(filePath: string | undefined) {diff --git a/packages/playwright-core/src/client/worker.ts b/packages/playwright-core/src/client/worker.tsindex 90987e03a8..1b11583697 100644--- a/packages/playwright-core/src/client/worker.ts+++ b/packages/playwright-core/src/client/worker.ts@@ -15,7 +15,7 @@*/import { LongStandingScope } from '@isomorphic/manualPromise';-import { ChannelOwner } from './channelOwner';+import { ChannelOwner, apiCall } from './channelOwner';import { ConsoleMessage } from './consoleMessage';import { isTargetClosedError, TargetClosedError } from './errors';import { Events } from './events';@@ -86,19 +86,18 @@ export class Worker extends ChannelOwner<channels.WorkerChannel> implements api.return JSHandle.from(result.handle) as any as structs.SmartHandle<R>;}+ @apiCall()async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {- return await this._wrapApiCall(async () => {- const timeoutSettings = this._page?._timeoutSettings ?? this._context?._timeoutSettings ?? new TimeoutSettings();- const timeoutOptions = timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- const waiter = Waiter.createForEvent(this, event);- waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);- if (event !== Events.Worker.Close)- waiter.rejectOnEvent(this, Events.Worker.Close, () => this._closeErrorWithReason());- const result = await waiter.waitForEvent(this, event, predicate as any);- waiter.dispose();- return result;- });+ const timeoutSettings = this._page?._timeoutSettings ?? this._context?._timeoutSettings ?? new TimeoutSettings();+ const timeoutOptions = timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);+ const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;+ const waiter = Waiter.createForEvent(this, event);+ waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);+ if (event !== Events.Worker.Close)+ waiter.rejectOnEvent(this, Events.Worker.Close, () => this._closeErrorWithReason());+ const result = await waiter.waitForEvent(this, event, predicate as any);+ waiter.dispose();+ return result;}async _disconnect(options: { reason?: string } = {}): Promise<void> {diff --git a/tests/library/trace-viewer.spec.ts b/tests/library/trace-viewer.spec.tsindex adc0f07e99..47a1fc3462 100644--- a/tests/library/trace-viewer.spec.ts+++ b/tests/library/trace-viewer.spec.ts@@ -1492,8 +1492,8 @@ test('should display waitForLoadState even if did not wait for it', async ({ run});await expect(traceViewer.actionTitles).toHaveText([/Navigate/,- /Wait for load state "load"/,- /Wait for load state "load"/,+ /Wait for load state/,+ /Wait for load state/,]);});