🎥 Make videos programmatically with React
remove more unnecessary functions
Jonny Burger9cfcb78bdca6
diff --git a/packages/renderer/src/browser/Browser.ts b/packages/renderer/src/browser/Browser.tsindex 5e72038ea0..b69ea8c92a 100644--- a/packages/renderer/src/browser/Browser.ts+++ b/packages/renderer/src/browser/Browser.ts@@ -30,7 +30,7 @@ import {waitWithTimeout} from './util';** @public*/-export interface BrowserContextOptions {+interface BrowserContextOptions {/*** Proxy server with optional port to use for all requests.* Username and password can be set in `Page.authenticate`.@@ -45,7 +45,7 @@ export interface BrowserContextOptions {/*** @internal*/-export type BrowserCloseCallback = () => Promise<void> | void;+type BrowserCloseCallback = () => Promise<void> | void;/*** @public@@ -90,7 +90,7 @@ const WEB_PERMISSION_TO_PROTOCOL_PERMISSION = new Map</*** @public*/-export type Permission =+type Permission =| 'geolocation'| 'midi'| 'notifications'@@ -112,7 +112,7 @@ export type Permission =/*** @public*/-export interface WaitForTargetOptions {+interface WaitForTargetOptions {/*** Maximum wait time in milliseconds. Pass `0` to disable the timeout.* @defaultValue 30 seconds.@@ -125,7 +125,7 @@ export interface WaitForTargetOptions {** @public*/-export const enum BrowserEmittedEvents {+const enum BrowserEmittedEvents {/*** Emitted when Puppeteer gets disconnected from the Chromium instance. This* might happen because of one of the following:@@ -704,7 +704,7 @@ export class Browser extends EventEmitter {/*** @public*/-export const enum BrowserContextEmittedEvents {+const enum BrowserContextEmittedEvents {/*** Emitted when the url of a target inside the browser context changes.* Contains a {@link Target} instance.diff --git a/packages/renderer/src/browser/BrowserFetcher.ts b/packages/renderer/src/browser/BrowserFetcher.tsindex ade293b6c1..845af408e4 100644--- a/packages/renderer/src/browser/BrowserFetcher.ts+++ b/packages/renderer/src/browser/BrowserFetcher.ts@@ -73,7 +73,7 @@ const browserConfig = {* Supported platforms.* @public*/-export type Platform = 'linux' | 'mac' | 'mac_arm' | 'win32' | 'win64';+type Platform = 'linux' | 'mac' | 'mac_arm' | 'win32' | 'win64';function archiveName(product: Product,@@ -94,10 +94,14 @@ function archiveName(return parseInt(revision, 10) > 591479? 'chrome-win': 'chrome-win32';+ default:+ throw new Error('unknown browser');}case 'firefox':return platform;+ default:+ throw new Error('unknown browser');}}diff --git a/packages/renderer/src/browser/DOMWorld.ts b/packages/renderer/src/browser/DOMWorld.tsindex 09b75ded45..4053a43555 100644--- a/packages/renderer/src/browser/DOMWorld.ts+++ b/packages/renderer/src/browser/DOMWorld.ts@@ -628,7 +628,7 @@ export class DOMWorld {/*** @internal*/-export interface WaitTaskOptions {+interface WaitTaskOptions {domWorld: DOMWorld;predicateBody: Function | string;predicateAcceptsContextElement: boolean;@@ -645,7 +645,7 @@ const noop = (): void => {};/*** @internal*/-export class WaitTask {+class WaitTask {#domWorld: DOMWorld;#polling: string | number;#timeout: number;diff --git a/packages/renderer/src/browser/Errors.ts b/packages/renderer/src/browser/Errors.tsindex bf4dd6b29a..865449c181 100644--- a/packages/renderer/src/browser/Errors.ts+++ b/packages/renderer/src/browser/Errors.ts@@ -17,7 +17,7 @@/*** @public*/-export class CustomError extends Error {+class CustomError extends Error {constructor(message?: string) {super(message);this.name = this.constructor.name;diff --git a/packages/renderer/src/browser/EvalTypes.ts b/packages/renderer/src/browser/EvalTypes.tsindex b05d838f53..87be6cb0b3 100644--- a/packages/renderer/src/browser/EvalTypes.ts+++ b/packages/renderer/src/browser/EvalTypes.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import {ElementHandle, JSHandle} from './JSHandle';+import {JSHandle} from './JSHandle';/*** @public@@ -44,7 +44,7 @@ export type EvaluateHandleFn = string | ((...args: any[]) => any);/*** @public*/-export type Serializable =+type Serializable =| number| string| boolean@@ -56,12 +56,12 @@ export type Serializable =/*** @public*/-export type JSONArray = readonly Serializable[];+type JSONArray = readonly Serializable[];/*** @public*/-export interface JSONObject {+interface JSONObject {[key: string]: Serializable;}@@ -69,15 +69,3 @@ export interface JSONObject {* @public*/export type SerializableOrJSHandle = Serializable | JSHandle;--/**- * Wraps a DOM element into an ElementHandle instance- * @public- **/-export type WrapElementHandle<X> = X extends Element ? ElementHandle<X> : X;--/**- * Unwraps a DOM element out of an ElementHandle instance- * @public- **/-export type UnwrapElementHandle<X> = X extends ElementHandle<infer E> ? E : X;diff --git a/packages/renderer/src/browser/EventEmitter.ts b/packages/renderer/src/browser/EventEmitter.tsindex 0d72aa0360..3eb61028dc 100644--- a/packages/renderer/src/browser/EventEmitter.ts+++ b/packages/renderer/src/browser/EventEmitter.ts@@ -3,7 +3,7 @@ import mitt, {Emitter, EventType, Handler} from './mitt';/*** @public*/-export {EventType, Handler};+export {Handler};/*** @publicdiff --git a/packages/renderer/src/browser/FrameManager.ts b/packages/renderer/src/browser/FrameManager.tsindex 4193ca9aa8..7cb2ff2c26 100644--- a/packages/renderer/src/browser/FrameManager.ts+++ b/packages/renderer/src/browser/FrameManager.ts@@ -591,7 +591,7 @@ export class FrameManager extends EventEmitter {/*** @public*/-export interface FrameWaitForFunctionOptions {+interface FrameWaitForFunctionOptions {/*** An interval at which the `pageFunction` is executed, defaults to `raf`. If* `polling` is a number, then it is treated as an interval in milliseconds at@@ -613,52 +613,6 @@ export interface FrameWaitForFunctionOptions {timeout?: number;}-/**- * @public- */-export interface FrameAddScriptTagOptions {- /**- * the URL of the script to be added.- */- url?: string;- /**- * The path to a JavaScript file to be injected into the frame.- * @remarks- * If `path` is a relative path, it is resolved relative to the current- * working directory (`process.cwd()` in Node.js).- */- path?: string;- /**- * Raw JavaScript content to be injected into the frame.- */- content?: string;- /**- * Set the script's `type`. Use `module` in order to load an ES2015 module.- */- type?: string;-}--/**- * @public- */-export interface FrameAddStyleTagOptions {- /**- * the URL of the CSS file to be added.- */- url?: string;- /**- * The path to a CSS file to be injected into the frame.- * @remarks- * If `path` is a relative path, it is resolved relative to the current- * working directory (`process.cwd()` in Node.js).- */- path?: string;- /**- * Raw CSS content to be injected into the frame.- */- content?: string;-}-/*** At every point of time, page exposes its current frame tree via the* {@link Page.mainFrame | page.mainFrame} and@@ -1008,20 +962,6 @@ export class Frame {return this.#detached;}- /**- * Adds a `<link rel="stylesheet">` tag into the page with the desired url or- * a `<style type="text/css">` tag with the content.- *- * @param options - configure the CSS to add to the page.- *- * @returns a promise that resolves to the added tag when the stylesheets's- * `onload` event fires or when the CSS content was injected into the- * frame.- */- async addStyleTag(options: FrameAddStyleTagOptions): Promise<ElementHandle> {- return this._mainWorld.addStyleTag(options);- }-/*** @remarks*diff --git a/packages/renderer/src/browser/HTTPRequest.ts b/packages/renderer/src/browser/HTTPRequest.tsindex b4a2a5f787..2626b70f18 100644--- a/packages/renderer/src/browser/HTTPRequest.ts+++ b/packages/renderer/src/browser/HTTPRequest.ts@@ -22,19 +22,6 @@ import {Frame} from './FrameManager';import {HTTPResponse} from './HTTPResponse';import {debugError, isString} from './util';-/**- * @public- */-export interface ContinueRequestOverrides {- /**- * If set, the request URL will change. This is not a redirect.- */- url?: string;- method?: string;- postData?: string;- headers?: Record<string, string>;-}-/*** @public*/@@ -139,7 +126,6 @@ export class HTTPRequest {#client: CDPSession;#isNavigationRequest: boolean;- #allowInterception: boolean;#interceptionHandled = false;#url: string;#resourceType: ResourceType;@@ -148,9 +134,6 @@ export class HTTPRequest {#postData?: string;#headers: Record<string, string> = {};#frame: Frame | null;- #continueRequestOverrides: ContinueRequestOverrides;- #responseForRequest: Partial<ResponseForRequest> | null = null;- #abortErrorReason: Protocol.Network.ErrorReason | null = null;#interceptResolutionState: InterceptResolutionState = {action: InterceptResolutionAction.None,};@@ -164,8 +147,6 @@ export class HTTPRequest {constructor(client: CDPSession,frame: Frame | null,- interceptionId: string | undefined,- allowInterception: boolean,event: Protocol.Network.RequestWillBeSentEvent,redirectChain: HTTPRequest[]) {@@ -173,15 +154,12 @@ export class HTTPRequest {this._requestId = event.requestId;this.#isNavigationRequest =event.requestId === event.loaderId && event.type === 'Document';- this._interceptionId = interceptionId;- this.#allowInterception = allowInterception;this.#url = event.request.url;this.#resourceType = (event.type || 'other').toLowerCase() as ResourceType;this.#method = event.request.method;this.#postData = event.request.postData;this.#frame = frame;this._redirectChain = redirectChain;- this.#continueRequestOverrides = {};this.#interceptHandlers = [];this.#initiator = event.initiator;@@ -197,56 +175,6 @@ export class HTTPRequest {return this.#url;}- /**- * @returns the `ContinueRequestOverrides` that will be used- * if the interception is allowed to continue (ie, `abort()` and- * `respond()` aren't called).- */- continueRequestOverrides(): ContinueRequestOverrides {- assert(this.#allowInterception, 'Request Interception is not enabled!');- return this.#continueRequestOverrides;- }-- /**- * @returns The `ResponseForRequest` that gets used if the- * interception is allowed to respond (ie, `abort()` is not called).- */- responseForRequest(): Partial<ResponseForRequest> | null {- assert(this.#allowInterception, 'Request Interception is not enabled!');- return this.#responseForRequest;- }-- /**- * @returns the most recent reason for aborting the request- */- abortErrorReason(): Protocol.Network.ErrorReason | null {- assert(this.#allowInterception, 'Request Interception is not enabled!');- return this.#abortErrorReason;- }-- /**- * @returns An InterceptResolutionState object describing the current resolution- * action and priority.- *- * InterceptResolutionState contains:- * action: InterceptResolutionAction- * priority?: number- *- * InterceptResolutionAction is one of: `abort`, `respond`, `continue`,- * `disabled`, `none`, or `already-handled`.- */- interceptResolutionState(): InterceptResolutionState {- if (!this.#allowInterception) {- return {action: InterceptResolutionAction.Disabled};- }-- if (this.#interceptionHandled) {- return {action: InterceptResolutionAction.AlreadyHandled};- }-- return {...this.#interceptResolutionState};- }-/*** @returns `true` if the intercept resolution has already been handled,* `false` otherwise.@@ -267,29 +195,6 @@ export class HTTPRequest {this.#interceptHandlers.push(pendingHandler);}- /**- * Awaits pending interception handlers and then decides how to fulfill- * the request interception.- */- async finalizeInterceptions(): Promise<void> {- await this.#interceptHandlers.reduce((promiseChain, interceptAction) => {- return promiseChain.then(interceptAction);- }, Promise.resolve());- const {action} = this.interceptResolutionState();- switch (action) {- case 'abort':- return this.#abort(this.#abortErrorReason);- case 'respond':- if (this.#responseForRequest === null) {- throw new Error('Response is missing for the interception');- }-- return this.#respond(this.#responseForRequest);- case 'continue':- return this.#continue(this.#continueRequestOverrides);- }- }-/*** Contains the request's resource type as it was perceived by the rendering* engine.@@ -411,102 +316,6 @@ export class HTTPRequest {};}- /**- * Continues request with optional request overrides.- *- * @remarks- *- * To use this, request- * interception should be enabled with {@link Page.setRequestInterception}.- *- * Exception is immediately thrown if the request interception is not enabled.- *- * @example- * ```js- * await page.setRequestInterception(true);- * page.on('request', request => {- * // Override headers- * const headers = Object.assign({}, request.headers(), {- * foo: 'bar', // set "foo" header- * origin: undefined, // remove "origin" header- * });- * request.continue({headers});- * });- * ```- *- * @param overrides - optional overrides to apply to the request.- * @param priority - If provided, intercept is resolved using- * cooperative handling rules. Otherwise, intercept is resolved- * immediately.- */- async continue(- overrides: ContinueRequestOverrides = {},- priority?: number- ): Promise<void> {- // Request interception is not supported for data: urls.- if (this.#url.startsWith('data:')) {- return;- }-- assert(this.#allowInterception, 'Request Interception is not enabled!');- assert(!this.#interceptionHandled, 'Request is already handled!');- if (priority === undefined) {- return this.#continue(overrides);- }-- this.#continueRequestOverrides = overrides;- if (- this.#interceptResolutionState.priority === undefined ||- priority > this.#interceptResolutionState.priority- ) {- this.#interceptResolutionState = {- action: InterceptResolutionAction.Continue,- priority,- };- return;- }-- if (priority === this.#interceptResolutionState.priority) {- if (- this.#interceptResolutionState.action === 'abort' ||- this.#interceptResolutionState.action === 'respond'- ) {- return;- }-- this.#interceptResolutionState.action =- InterceptResolutionAction.Continue;- }- }-- async #continue(overrides: ContinueRequestOverrides = {}): Promise<void> {- const {url, method, postData, headers} = overrides;- this.#interceptionHandled = true;-- const postDataBinaryBase64 = postData- ? Buffer.from(postData).toString('base64')- : undefined;-- if (this._interceptionId === undefined) {- throw new Error(- 'HTTPRequest is missing _interceptionId needed for Fetch.continueRequest'- );- }-- await this.#client- .send('Fetch.continueRequest', {- requestId: this._interceptionId,- url,- method,- postData: postDataBinaryBase64,- headers: headers ? headersArray(headers) : undefined,- })- .catch((error) => {- this.#interceptionHandled = false;- return handleError(error);- });- }-/*** Fulfills a request with the given response.*@@ -547,13 +356,11 @@ export class HTTPRequest {return;}- assert(this.#allowInterception, 'Request Interception is not enabled!');assert(!this.#interceptionHandled, 'Request is already handled!');if (priority === undefined) {return this.#respond(response);}- this.#responseForRequest = response;if (this.#interceptResolutionState.priority === undefined ||priority > this.#interceptResolutionState.priority@@ -650,13 +457,11 @@ export class HTTPRequest {const errorReason = errorReasons[errorCode];assert(errorReason, 'Unknown error code: ' + errorCode);- assert(this.#allowInterception, 'Request Interception is not enabled!');assert(!this.#interceptionHandled, 'Request is already handled!');if (priority === undefined) {return this.#abort(errorReason);}- this.#abortErrorReason = errorReason;if (this.#interceptResolutionState.priority === undefined ||priority >= this.#interceptResolutionState.prioritydiff --git a/packages/renderer/src/browser/NetworkManager.ts b/packages/renderer/src/browser/NetworkManager.tsindex b5d03b7766..1a222af465 100644--- a/packages/renderer/src/browser/NetworkManager.ts+++ b/packages/renderer/src/browser/NetworkManager.ts@@ -86,8 +86,6 @@ export class NetworkManager extends EventEmitter {#extraHTTPHeaders: Record<string, string> = {};#credentials?: Credentials;#attemptedAuthentications = new Set<string>();- #userRequestInterceptionEnabled = false;- #protocolRequestInterceptionEnabled = false;#userCacheDisabled = false;#emulatedNetworkConditions: InternalNetworkConditions = {offline: false,@@ -140,11 +138,6 @@ export class NetworkManager extends EventEmitter {}}- async authenticate(credentials?: Credentials): Promise<void> {- this.#credentials = credentials;- await this.#updateProtocolRequestInterception();- }-async setExtraHTTPHeaders(extraHTTPHeaders: Record<string, string>): Promise<void> {@@ -216,35 +209,6 @@ export class NetworkManager extends EventEmitter {await this.#updateProtocolCacheDisabled();}- async setRequestInterception(value: boolean): Promise<void> {- this.#userRequestInterceptionEnabled = value;- await this.#updateProtocolRequestInterception();- }-- async #updateProtocolRequestInterception(): Promise<void> {- const enabled =- this.#userRequestInterceptionEnabled || Boolean(this.#credentials);- if (enabled === this.#protocolRequestInterceptionEnabled) {- return;- }-- this.#protocolRequestInterceptionEnabled = enabled;- if (enabled) {- await Promise.all([- this.#updateProtocolCacheDisabled(),- this.#client.send('Fetch.enable', {- handleAuthRequests: true,- patterns: [{urlPattern: '*'}],- }),- ]);- } else {- await Promise.all([- this.#updateProtocolCacheDisabled(),- this.#client.send('Fetch.disable'),- ]);- }- }-#cacheDisabled(): boolean {return this.#userCacheDisabled;}@@ -256,30 +220,6 @@ export class NetworkManager extends EventEmitter {}#onRequestWillBeSent(event: Protocol.Network.RequestWillBeSentEvent): void {- // Request interception doesn't happen for data URLs with Network Service.- if (- this.#userRequestInterceptionEnabled &&- !event.request.url.startsWith('data:')- ) {- const {requestId: networkRequestId} = event;-- this.#networkEventManager.storeRequestWillBeSent(networkRequestId, event);-- /**- * CDP may have sent a Fetch.requestPaused event already. Check for it.- */- const requestPausedEvent =- this.#networkEventManager.getRequestPaused(networkRequestId);- if (requestPausedEvent) {- const {requestId: fetchRequestId} = requestPausedEvent;- this.#patchRequestEventHeaders(event, requestPausedEvent);- this.#onRequest(event, fetchRequestId);- this.#networkEventManager.forgetRequestPaused(networkRequestId);- }-- return;- }-this.#onRequest(event, undefined);}@@ -316,17 +256,6 @@ export class NetworkManager extends EventEmitter {* for the same Network.requestWillBeSent.*/#onRequestPaused(event: Protocol.Fetch.RequestPausedEvent): void {- if (- !this.#userRequestInterceptionEnabled &&- this.#protocolRequestInterceptionEnabled- ) {- this.#client- .send('Fetch.continueRequest', {- requestId: event.requestId,- })- .catch(debugError);- }-const {networkId: networkRequestId, requestId: fetchRequestId} = event;if (!networkRequestId) {@@ -413,17 +342,9 @@ export class NetworkManager extends EventEmitter {? this.#frameManager.frame(event.frameId): null;- const request = new HTTPRequest(- this.#client,- frame,- fetchRequestId,- this.#userRequestInterceptionEnabled,- event,- redirectChain- );+ const request = new HTTPRequest(this.#client, frame, event, redirectChain);this.#networkEventManager.storeRequest(event.requestId, request);this.emit(NetworkManagerEmittedEvents.Request, request);- request.finalizeInterceptions();}#onRequestServedFromCache(@@ -551,11 +472,8 @@ export class NetworkManager extends EventEmitter {#forgetRequest(request: HTTPRequest, events: boolean): void {const requestId = request._requestId;- const interceptionId = request._interceptionId;this.#networkEventManager.forgetRequest(requestId);- interceptionId !== undefined &&- this.#attemptedAuthentications.delete(interceptionId);if (events) {this.#networkEventManager.forget(requestId);diff --git a/packages/renderer/src/browser/Page.ts b/packages/renderer/src/browser/Page.tsindex bc1d20e87d..b87997abb1 100644--- a/packages/renderer/src/browser/Page.ts+++ b/packages/renderer/src/browser/Page.ts@@ -36,11 +36,7 @@ import {HTTPResponse} from './HTTPResponse';import {Keyboard, Mouse, Touchscreen} from './Input';import {ElementHandle, JSHandle, _createJSHandle} from './JSHandle';import {PuppeteerLifeCycleEvent} from './LifecycleWatcher';-import {- Credentials,- NetworkConditions,- NetworkManagerEmittedEvents,-} from './NetworkManager';+import {NetworkConditions, NetworkManagerEmittedEvents} from './NetworkManager';import {Viewport} from './PuppeteerViewport';import {Target} from './Target';import {TaskQueue} from './TaskQueue';@@ -816,42 +812,6 @@ export class Page extends EventEmitter {return this.#frameManager.frames();}- /**- * @param value - Whether to enable request interception.- *- * @remarks- * Activating request interception enables {@link HTTPRequest.abort},- * {@link HTTPRequest.continue} and {@link HTTPRequest.respond} methods. This- * provides the capability to modify network requests that are made by a page.- *- * Once request interception is enabled, every request will stall unless it's- * continued, responded or aborted; or completed using the browser cache.- *- * @example- * An example of a naïve request interceptor that aborts all image requests:- * ```js- * const puppeteer = require('puppeteer');- * (async () => {- * const browser = await puppeteer.launch();- * const page = await browser.newPage();- * await page.setRequestInterception(true);- * page.on('request', interceptedRequest => {- * if (interceptedRequest.url().endsWith('.png') ||- * interceptedRequest.url().endsWith('.jpg'))- * interceptedRequest.abort();- * else- * interceptedRequest.continue();- * });- * await page.goto('https://example.com');- * await browser.close();- * })();- * ```- * NOTE: Enabling request interception disables page caching.- */- async setRequestInterception(value: boolean): Promise<void> {- return this.#frameManager.networkManager().setRequestInterception(value);- }-/*** @param enabled - Whether to enable drag interception.*@@ -1104,20 +1064,6 @@ export class Page extends EventEmitter {}}- /**- * Adds a `<link rel="stylesheet">` tag into the page with the desired URL or a- * `<style type="text/css">` tag with the content.- * @returns Promise which resolves to the added tag when the stylesheet's- * onload fires or when the CSS content was injected into frame.- */- async addStyleTag(options: {- url?: string;- path?: string;- content?: string;- }): Promise<ElementHandle> {- return this.mainFrame().addStyleTag(options);- }-/*** The method adds a function called `name` on the page's `window` object. When* called, the function executes `puppeteerFunction` in node.js and returns a@@ -1212,14 +1158,6 @@ export class Page extends EventEmitter {);}- /**- * Provide credentials for `HTTP authentication`.- * @remarks To disable authentication, pass `null`.- */- async authenticate(credentials: Credentials): Promise<void> {- return this.#frameManager.networkManager().authenticate(credentials);- }-/*** The extra HTTP headers will be sent with every request the page initiates.* NOTE: All HTTP header names are lowercased. (HTTP headers are