Skip to content

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

26.0 KB
Raw Blame
/**
 * Copyright 2017 Google Inc. All rights reserved.
 * Modifications 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.
 */

import fs from 'fs';
import path from 'path';

import { headersObjectToArray } from '@isomorphic/headers';
import { urlMatchesEqual } from '@isomorphic/urlMatch';
import { rewriteErrorMessage } from '@utils/stackTrace';
import { Browser } from './browser';
import { CDPSession } from './cdpSession';
import { ChannelOwner, apiCall, internal } from './channelOwner';
import { evaluationScript } from './clientHelper';
import { Clock } from './clock';
import { ConsoleMessage } from './consoleMessage';
import { Credentials } from './credentials';
import { Debugger } from './debugger';
import { Dialog } from './dialog';
import { DisposableObject, DisposableStub } from './disposable';
import { TargetClosedError, parseError } from './errors';
import { Events } from './events';
import { APIRequestContext } from './fetch';
import { Frame } from './frame';
import { HarRouter } from './harRouter';
import { assertEvaluateOptions } from './jsHandle';
import * as network from './network';
import { BindingCall, Page, addInitScriptWithExposedFunctions } from './page';
import { Tracing } from './tracing';
import { Waiter } from './waiter';
import { WebError } from './webError';
import { Worker } from './worker';
import { TimeoutSettings, kNoTimeout } from './timeoutSettings';
import { mkdirIfNeeded } from './fileUtils';

import type { ExposeFunctionsOptions } from './jsHandle';
import type { BrowserContextOptions, Headers, SetStorageState, StorageState, WaitForEventOptions } from './types';
import type { HttpCredentials } from '@protocol/structs';
import type * as structs from '../../types/structs';
import type * as api from '../../types/types';
import type { URLMatch } from '@isomorphic/urlMatch';
import type * as channels from './channels';
import type * as actions from '@isomorphic/codegen/actions';

interface RecorderEventSink {
  actionAdded?(page: Page, action: actions.Action, code: string): void;
  actionUpdated?(page: Page, action: actions.Action, code: string): void;
  signalAdded?(page: Page, signal: actions.Signal, code: string): void;
}

export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel> implements api.BrowserContext {
  _pages = new Set<Page>();
  _routes: network.RouteHandler[] = [];
  _webSocketRoutes: network.WebSocketRouteHandler[] = [];
  // Browser is null for browser contexts created outside of normal browser, e.g. android or electron.
  _browser: Browser | null = null;
  readonly _bindings = new Map<string, (source: structs.BindingSource, ...args: any[]) => any>();
  _timeoutSettings: TimeoutSettings;
  _ownerPage: Page | undefined;
  _forReuse = false;
  private _closedPromise: Promise<void>;
  readonly _options: channels.BrowserNewContextParams;

  readonly debugger: Debugger;
  readonly request: APIRequestContext;
  readonly tracing: Tracing;
  readonly clock: Clock;
  readonly credentials: Credentials;

  readonly _serviceWorkers = new Set<Worker>();
  private _closingStatus: 'none' | 'closing' | 'closed' = 'none';
  private _closeReason: string | undefined;
  private _harRouters: HarRouter[] = [];
  private _onRecorderEventSink: RecorderEventSink | undefined;


  static from(context: channels.BrowserContextChannel): BrowserContext {
    return (context as any)._object;
  }

  static fromNullable(context: channels.BrowserContextChannel | null): BrowserContext | null {
    return context ? BrowserContext.from(context) : null;
  }

  constructor(parent: ChannelOwner, type: string, guid: string, initializer: channels.BrowserContextInitializer) {
    super(parent, type, guid, initializer);
    this._options = initializer.options;
    this._timeoutSettings = new TimeoutSettings();
    this.debugger = Debugger.from(initializer.debugger);
    this.tracing = Tracing.from(initializer.tracing);
    this.request = APIRequestContext.from(initializer.requestContext);
    this.request._timeoutSettings = this._timeoutSettings;
    this.clock = new Clock(this);
    this.credentials = new Credentials(this);

    this._channel.on('bindingCall', ({ binding }) => this._onBinding(BindingCall.from(binding)));
    this._channel.on('close', () => this._onClose());
    this._channel.on('page', ({ page }) => this._onPage(Page.from(page)));
    this._channel.on('route', ({ route }) => this._onRoute(network.Route.from(route)));
    this._channel.on('webSocketRoute', ({ webSocketRoute }) => this._onWebSocketRoute(network.WebSocketRoute.from(webSocketRoute)));
    this._channel.on('serviceWorker', ({ worker }) => {
      const serviceWorker = Worker.from(worker);
      serviceWorker._context = this;
      this._serviceWorkers.add(serviceWorker);
      this.emit(Events.BrowserContext.ServiceWorker, serviceWorker);
    });
    this._channel.on('console', event => {
      const worker = Worker.fromNullable(event.worker);
      const page = Page.fromNullable(event.page);
      const consoleMessage = new ConsoleMessage(event, page, worker);
      worker?.emit(Events.Worker.Console, consoleMessage);
      page?.emit(Events.Page.Console, consoleMessage);
      if (worker && this._serviceWorkers.has(worker)) {
        const scope = this._serviceWorkerScope(worker);
        for (const page of this._pages) {
          if (scope && page.url().startsWith(scope))
            page.emit(Events.Page.Console, consoleMessage);
        }
      }
      this.emit(Events.BrowserContext.Console, consoleMessage);
    });
    this._channel.on('pageError', ({ error, page, location }) => {
      const pageObject = Page.from(page);
      const parsedError = parseError(error);
      this.emit(Events.BrowserContext.WebError, new WebError(pageObject, parsedError, location));
      if (pageObject)
        pageObject.emit(Events.Page.PageError, parsedError);
    });
    this._channel.on('dialog', ({ dialog }) => {
      const dialogObject = Dialog.from(dialog);
      let hasListeners = this.emit(Events.BrowserContext.Dialog, dialogObject);
      const page = dialogObject.page();
      if (page)
        hasListeners = page.emit(Events.Page.Dialog, dialogObject) || hasListeners;
      if (!hasListeners) {
        // Although we do similar handling on the server side, we still need this logic
        // on the client side due to a possible race condition between two async calls:
        // a) removing "dialog" listener subscription (client->server)
        // b) actual "dialog" event (server->client)
        if (dialogObject.type() === 'beforeunload')
          dialog.accept({}, kNoTimeout).catch(() => {});
        else
          dialog.dismiss({}, kNoTimeout).catch(() => {});
      }
    });
    this._channel.on('dialogClosed', ({ dialog }) => {
      const dialogObject = Dialog.from(dialog);
      this.emit(Events.BrowserContext.DialogClosed, dialogObject);
      const page = dialogObject.page();
      if (page)
        page.emit(Events.Page.DialogClosed, dialogObject);
    });
    this._channel.on('request', ({ request, page }) => this._onRequest(network.Request.from(request), Page.fromNullable(page)));
    this._channel.on('requestFailed', ({ request, failureText, responseEndTiming, page }) => this._onRequestFailed(network.Request.from(request), responseEndTiming, failureText, Page.fromNullable(page)));
    this._channel.on('requestFinished', params => this._onRequestFinished(params));
    this._channel.on('response', ({ response, page }) => this._onResponse(network.Response.from(response), Page.fromNullable(page)));
    this._channel.on('recorderEvent', ({ event, data, page, code }) => {
      if (event === 'actionAdded')
        this._onRecorderEventSink?.actionAdded?.(Page.from(page), data as actions.Action, code);
      else if (event === 'actionUpdated')
        this._onRecorderEventSink?.actionUpdated?.(Page.from(page), data as actions.Action, code);
      else if (event === 'signalAdded')
        this._onRecorderEventSink?.signalAdded?.(Page.from(page), data as actions.Signal, code);
    });
    this._closedPromise = new Promise(f => this.once(Events.BrowserContext.Close, f));

    this._setEventToSubscriptionMapping(new Map<string, channels.BrowserContextUpdateSubscriptionParams['event']>([
      [Events.BrowserContext.Console, 'console'],
      [Events.BrowserContext.Dialog, 'dialog'],
      [Events.BrowserContext.DialogClosed, 'dialogClosed'],
      [Events.BrowserContext.Request, 'request'],
      [Events.BrowserContext.Response, 'response'],
      [Events.BrowserContext.RequestFinished, 'requestFinished'],
      [Events.BrowserContext.RequestFailed, 'requestFailed'],
    ]));
  }

  async _initializeHarFromOptions(recordHar: BrowserContextOptions['recordHar']) {
    if (!recordHar)
      return;
    const defaultContent = /\.zip$/i.test(recordHar.path) ? 'attach' : 'embed';
    await this.tracing._recordIntoHAR(recordHar.path, null, {
      url: recordHar.urlFilter,
      updateContent: recordHar.content ?? (recordHar.omitContent ? 'omit' : defaultContent),
      updateMode: recordHar.mode ?? 'full',
    });
  }

  private _onPage(page: Page): void {
    this._pages.add(page);
    this.emit(Events.BrowserContext.Page, page);
    if (page._opener && !page._opener.isClosed())
      page._opener.emit(Events.Page.Popup, page);
  }

  private _onRequest(request: network.Request, page: Page | null) {
    this.emit(Events.BrowserContext.Request, request);
    if (page)
      page.emit(Events.Page.Request, request);
  }

  private _onResponse(response: network.Response, page: Page | null) {
    this.emit(Events.BrowserContext.Response, response);
    if (page)
      page.emit(Events.Page.Response, response);
  }

  private _onRequestFailed(request: network.Request, responseEndTiming: number, failureText: string | undefined, page: Page | null) {
    request._failureText = failureText || null;
    request._setResponseEndTiming(responseEndTiming);
    this.emit(Events.BrowserContext.RequestFailed, request);
    if (page)
      page.emit(Events.Page.RequestFailed, request);
  }

  private _onRequestFinished(params: channels.BrowserContextRequestFinishedEvent) {
    const { responseEndTiming } = params;
    const request = network.Request.from(params.request);
    const response = network.Response.fromNullable(params.response);
    const page = Page.fromNullable(params.page);
    request._setResponseEndTiming(responseEndTiming);
    this.emit(Events.BrowserContext.RequestFinished, request);
    if (page)
      page.emit(Events.Page.RequestFinished, request);
    if (response)
      response._finishedPromise.resolve(null);
  }

  async _onRoute(route: network.Route) {
    route._context = this;
    const page = route.request()._safePage();
    const routeHandlers = this._routes.slice();
    for (const routeHandler of routeHandlers) {
      // If the page or the context was closed we stall all requests right away.
      if (page?._closeWasCalled || this.isClosed())
        return;
      if (!routeHandler.matches(route.request().url()))
        continue;
      const index = this._routes.indexOf(routeHandler);
      if (index === -1)
        continue;
      if (routeHandler.willExpire())
        this._routes.splice(index, 1);
      const handled = await routeHandler.handle(route);
      if (!this._routes.length)
        this._disableInterception().catch(() => {});
      if (handled)
        return;
    }
    // If the page is closed or unrouteAll() was called without waiting and interception disabled,
    // the method will throw an error - silence it.
    await route._innerContinue(true /* isFallback */).catch(() => {});
  }

  async _onWebSocketRoute(webSocketRoute: network.WebSocketRoute) {
    const routeHandler = this._webSocketRoutes.find(route => route.matches(webSocketRoute.url()));
    if (routeHandler)
      await routeHandler.handle(webSocketRoute);
    else
      webSocketRoute.connectToServer();
  }

  async _onBinding(bindingCall: BindingCall) {
    const func = this._bindings.get(bindingCall._initializer.name);
    if (!func)
      return;
    await bindingCall.call(func);
  }

  private _serviceWorkerScope(serviceWorker: Worker) {
    try {
      let url = new URL('.', serviceWorker.url()).href;
      if (!url.endsWith('/'))
        url += '/';
      return url;
    } catch {
      return null;
    }
  }

  setDefaultNavigationTimeout(timeout: number | undefined) {
    this._timeoutSettings.setDefaultNavigationTimeout(timeout);
  }

  setDefaultTimeout(timeout: number | undefined) {
    this._timeoutSettings.setDefaultTimeout(timeout);
  }

  browser(): Browser | null {
    return this._browser;
  }

  pages(): Page[] {
    return [...this._pages];
  }

  isClosed(): boolean {
    return this._closingStatus !== 'none';
  }

  async newPage(): Promise<Page> {
    if (this._ownerPage)
      throw new Error('Please use browser.newContext()');
    return Page.from((await this._channel.newPage({}, kNoTimeout)).page);
  }

  async cookies(urls?: string | string[]): Promise<network.NetworkCookie[]> {
    if (!urls)
      urls = [];
    if (urls && typeof urls === 'string')
      urls = [urls];
    return (await this._channel.cookies({ urls: urls as string[] }, kNoTimeout)).cookies;
  }

  async addCookies(cookies: network.SetNetworkCookieParam[]): Promise<void> {
    await this._channel.addCookies({ cookies }, kNoTimeout);
  }

  async clearCookies(options: network.ClearNetworkCookieOptions = {}): Promise<void> {
    await this._channel.clearCookies(network.toClearCookiesParams(options), kNoTimeout);
  }

  async grantPermissions(permissions: string[], options?: { origin?: string }): Promise<void> {
    await this._channel.grantPermissions({ permissions, ...options }, kNoTimeout);
  }

  async clearPermissions(): Promise<void> {
    await this._channel.clearPermissions({}, kNoTimeout);
  }

  async setGeolocation(geolocation: { longitude: number, latitude: number, accuracy?: number } | null): Promise<void> {
    await this._channel.setGeolocation({ geolocation: geolocation || undefined }, kNoTimeout);
  }

  async setExtraHTTPHeaders(headers: Headers): Promise<void> {
    network.validateHeaders(headers);
    await this._channel.setExtraHTTPHeaders({ headers: headersObjectToArray(headers) }, kNoTimeout);
  }

  async setOffline(offline: boolean): Promise<void> {
    await this._channel.setOffline({ offline }, kNoTimeout);
  }

  async setHTTPCredentials(httpCredentials: HttpCredentials | HttpCredentials[] | null): Promise<void> {
    await this._channel.setHTTPCredentials({ httpCredentials: toHttpCredentialsProtocol(httpCredentials || undefined) }, kNoTimeout);
  }

  async addInitScript(script: Function | string | { path?: string, content?: string }, arg?: any, options?: ExposeFunctionsOptions) {
    assertEvaluateOptions(options);
    if (options?.exposeFunctions)
      return await addInitScriptWithExposedFunctions(this, script, arg);
    const source = await evaluationScript(script, arg);
    return DisposableObject.from((await this._channel.addInitScript({ source }, kNoTimeout)).disposable);
  }

  async exposeBinding(name: string, callback: (source: structs.BindingSource, ...args: any[]) => any): Promise<DisposableObject> {
    const result = await this._channel.exposeBinding({ name }, kNoTimeout);
    this._bindings.set(name, callback);
    return DisposableObject.from(result.disposable);
  }

  async _exposeCallbackBinding(name: string, callback: Function): Promise<DisposableObject> {
    this._bindings.set(name, (source, ...args) => callback(...args));
    const result = await this._channel.exposeBinding({ name, noGlobal: true }, kNoTimeout);
    return DisposableObject.from(result.disposable);
  }

  async exposeFunction(name: string, callback: Function): Promise<DisposableObject> {
    const result = await this._channel.exposeBinding({ name }, kNoTimeout);
    const binding = (source: structs.BindingSource, ...args: any[]) => callback(...args);
    this._bindings.set(name, binding);
    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();
    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();
  }

  async routeFromHAR(har: string, options: { url?: string | RegExp, notFound?: 'abort' | 'fallback', update?: boolean, updateContent?: 'attach' | 'embed', updateMode?: 'minimal' | 'full' } = {}): Promise<void> {
    const localUtils = this._connection.localUtils();
    if (!localUtils)
      throw new Error('Route from har is not supported in thin clients');
    if (options.update) {
      await this.tracing._recordIntoHAR(har, null, options);
      return;
    }
    const harRouter = await HarRouter.create(localUtils, har, options.notFound || 'abort', { urlMatch: options.url });
    this._harRouters.push(harRouter);
    await harRouter.addContextRoute(this);
  }

  private _disposeHarRouters() {
    this._harRouters.forEach(router => router.dispose());
    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 = [];
    for (const route of this._routes) {
      if (urlMatchesEqual(route.url, url) && (!handler || route.handler === handler))
        removed.push(route);
      else
        remaining.push(route);
    }
    await this._unrouteInternal(removed, remaining, 'default');
  }

  private async _unrouteInternal(removed: network.RouteHandler[], remaining: network.RouteHandler[], behavior?: 'wait'|'ignoreErrors'|'default'): Promise<void> {
    this._routes = remaining;
    if (behavior && behavior !== 'default') {
      const promises = removed.map(routeHandler => routeHandler.stop(behavior));
      await Promise.all(promises);
    }
    await this._updateInterceptionPatterns();
  }

  @internal
  private async _disableInterception() {
    await this._updateInterceptionPatterns();
  }

  private async _updateInterceptionPatterns() {
    const patterns = network.RouteHandler.prepareInterceptionPatterns(this._routes);
    await this._channel.setNetworkInterceptionPatterns({ patterns }, kNoTimeout);
  }

  private async _updateWebSocketInterceptionPatterns() {
    const patterns = network.WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes);
    await this._channel.setWebSocketInterceptionPatterns({ patterns }, kNoTimeout);
  }

  _effectiveCloseReason(): string | undefined {
    return this._closeReason || this._browser?._closeReason;
  }

  @apiCall()
  async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {
    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> {
    const state = await this._channel.storageState({ indexedDB: options.indexedDB, opfs: options.opfs, credentials: options.credentials }, kNoTimeout);
    if (options.path) {
      await mkdirIfNeeded(options.path);
      await fs.promises.writeFile(options.path, JSON.stringify(state, undefined, 2), 'utf8');
    }
    return state;
  }

  async setStorageState(storageState: string | SetStorageState): Promise<void> {
    const state = await prepareStorageState(storageState);
    await this._channel.setStorageState({ storageState: state }, kNoTimeout);
  }

  backgroundPages(): Page[] {
    return [];
  }

  serviceWorkers(): Worker[] {
    return [...this._serviceWorkers];
  }

  async newCDPSession(page: Page | Frame): Promise<api.CDPSession> {
    // channelOwner.ts's validation messages don't handle the pseudo-union type, so we're explicit here
    if (!(page instanceof Page) && !(page instanceof Frame))
      throw new Error('page: expected Page or Frame');
    const result = await this._channel.newCDPSession(page instanceof Page ? { page: page._channel } : { frame: page._channel }, kNoTimeout);
    return CDPSession.from(result.session);
  }

  _onClose() {
    this._closingStatus = 'closed';
    this._browser?._contexts.delete(this);
    this._browser?._browserType._contexts.delete(this);
    this._browser?._browserType._playwright.selectors._contextsForSelectors.delete(this);
    this._disposeHarRouters();
    this.tracing._resetStackCounter();
    this.request.tracing._resetStackCounter();
    this.emit(Events.BrowserContext.Close, this);
  }

  async [Symbol.asyncDispose]() {
    await this.close();
  }

  async close(options: { reason?: string } = {}): Promise<void> {
    if (this.isClosed())
      return;
    this._closeReason = options.reason;
    this._closingStatus = 'closing';
    await this.request.dispose(options);
    await this._instrumentation.runBeforeCloseBrowserContext(this);
    const harError = await this.tracing._exportAllHars().catch(e => e);
    await this._channel.close(options, kNoTimeout);
    await this._closedPromise;
    if (harError)
      throw harError;
  }

  async _showRecorder(params: channels.BrowserContextShowRecorderParams) {
    await this._channel.showRecorder(params, kNoTimeout);
  }

  async _startRecording(params: channels.BrowserContextStartRecordingParams, eventSink: RecorderEventSink) {
    this._onRecorderEventSink = eventSink;
    await this._channel.startRecording(params, kNoTimeout);
  }

  async _stopRecording() {
    try {
      await this._channel.stopRecording({}, kNoTimeout);
    } finally {
      this._onRecorderEventSink = undefined;
    }
  }

  async _exposeConsoleApi() {
    await this._channel.exposeConsoleApi({}, kNoTimeout);
  }

}

async function prepareStorageState(storageState: string | SetStorageState): Promise<NonNullable<channels.BrowserNewContextParams['storageState']>> {
  if (typeof storageState !== 'string')
    return storageState as any;
  try {
    return JSON.parse(await fs.promises.readFile(storageState, 'utf8'));
  } catch (e) {
    rewriteErrorMessage(e, `Error reading storage state from ${storageState}:\n` + e.message);
    throw e;
  }
}

export async function prepareBrowserContextParams(options: BrowserContextOptions): Promise<channels.BrowserNewContextParams> {
  if (options.extraHTTPHeaders)
    network.validateHeaders(options.extraHTTPHeaders);
  const contextParams: channels.BrowserNewContextParams = {
    ...options,
    viewport: options.viewport === null ? undefined : options.viewport,
    noDefaultViewport: options.viewport === null,
    extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
    storageState: options.storageState ? await prepareStorageState(options.storageState) : undefined,
    serviceWorkers: options.serviceWorkers,
    colorScheme: options.colorScheme === null ? 'no-override' : options.colorScheme,
    reducedMotion: options.reducedMotion === null ? 'no-override' : options.reducedMotion,
    forcedColors: options.forcedColors === null ? 'no-override' : options.forcedColors,
    contrast: options.contrast === null ? 'no-override' : options.contrast,
    acceptDownloads: toAcceptDownloadsProtocol(options.acceptDownloads),
    clientCertificates: await toClientCertificatesProtocol(options.clientCertificates),
    httpCredentials: toHttpCredentialsProtocol(options.httpCredentials),
  };
  if (contextParams.recordVideo && contextParams.recordVideo.dir)
    contextParams.recordVideo.dir = path.resolve(contextParams.recordVideo.dir);
  return contextParams;
}

export function toHttpCredentialsProtocol(credentials?: HttpCredentials | HttpCredentials[]): HttpCredentials[] | undefined {
  if (!credentials)
    return undefined;
  const list = Array.isArray(credentials) ? credentials : [credentials];
  return list.length ? list : undefined;
}

function toAcceptDownloadsProtocol(acceptDownloads?: boolean) {
  if (acceptDownloads === undefined)
    return undefined;
  if (acceptDownloads)
    return 'accept';
  return 'deny';
}

export async function toClientCertificatesProtocol(certs?: BrowserContextOptions['clientCertificates']): Promise<channels.PlaywrightNewRequestParams['clientCertificates']> {
  if (!certs)
    return undefined;

  const bufferizeContent = async (value?: Buffer, filePath?: string): Promise<Buffer | undefined> => {
    if (value)
      return value;
    if (filePath)
      return await fs.promises.readFile(filePath);
  };

  return await Promise.all(certs.map(async cert => ({
    origin: cert.origin,
    cert: await bufferizeContent(cert.cert, cert.certPath),
    key: await bufferizeContent(cert.key, cert.keyPath),
    pfx: await bufferizeContent(cert.pfx, cert.pfxPath),
    passphrase: cert.passphrase,
  })));
}