🎥 Make videos programmatically with React
metrics
Jonny Burger5a088fb09dcc
diff --git a/packages/renderer/src/browser/FrameManager.ts b/packages/renderer/src/browser/FrameManager.tsindex 7cb2ff2c26..dfc5ccde51 100644--- a/packages/renderer/src/browser/FrameManager.ts+++ b/packages/renderer/src/browser/FrameManager.ts@@ -17,7 +17,7 @@import {Protocol} from 'devtools-protocol';import {assert} from './assert';import {CDPSession, Connection} from './Connection';-import {DOMWorld, WaitForSelectorOptions} from './DOMWorld';+import {DOMWorld} from './DOMWorld';import {EvaluateFn,EvaluateFnReturnType,@@ -28,7 +28,7 @@ import {import {EventEmitter} from './EventEmitter';import {EVALUATION_SCRIPT_URL, ExecutionContext} from './ExecutionContext';import {HTTPResponse} from './HTTPResponse';-import {ElementHandle, JSHandle} from './JSHandle';+import {JSHandle} from './JSHandle';import {LifecycleWatcher, PuppeteerLifeCycleEvent} from './LifecycleWatcher';import {NetworkManager} from './NetworkManager';import {Page} from './Page';@@ -887,15 +887,6 @@ export class Frame {return this._mainWorld.evaluate<T>(pageFunction, ...args);}- /**- * This method evaluates the given XPath expression and returns the results.- *- * @param expression - the XPath expression to evaluate.- */- async $x(expression: string): Promise<ElementHandle[]> {- return this._mainWorld.$x(expression);- }-/*** @returns the full HTML contents of the frame, including the doctype.*/@@ -1021,60 +1012,6 @@ export class Frame {);}- /**- * Causes your script to wait for the given number of milliseconds.- *- * @remarks- * It's generally recommended to not wait for a number of seconds, but instead- * use {@link Frame.waitForSelector}, {@link Frame.waitForXPath} or- * {@link Frame.waitForFunction} to wait for exactly the conditions you want.- *- * @example- *- * Wait for 1 second:- *- * ```- * await frame.waitForTimeout(1000);- * ```- *- * @param milliseconds - the number of milliseconds to wait.- */- waitForTimeout(milliseconds: number): Promise<void> {- return new Promise((resolve) => {- setTimeout(resolve, milliseconds);- });- }-- /**- * @remarks- * Wait for the `xpath` to appear in page. If at the moment of calling the- * method the `xpath` already exists, the method will return immediately. If- * the xpath doesn't appear after the `timeout` milliseconds of waiting, the- * function will throw.- *- * For a code example, see the example for {@link Frame.waitForSelector}. That- * function behaves identically other than taking a CSS selector rather than- * an XPath.- *- * @param xpath - the XPath expression to wait for.- * @param options - options to configure the visiblity of the element and how- * long to wait before timing out.- */- async waitForXPath(- xpath: string,- options: WaitForSelectorOptions = {}- ): Promise<ElementHandle | null> {- const handle = await this._secondaryWorld.waitForXPath(xpath, options);- if (!handle) {- return null;- }-- const mainExecutionContext = await this._mainWorld.executionContext();- const result = await mainExecutionContext._adoptElementHandle(handle);- await handle.dispose();- return result;- }-/*** @remarks*diff --git a/packages/renderer/src/browser/Page.ts b/packages/renderer/src/browser/Page.tsindex 44c9970a53..19ddca2f27 100644--- a/packages/renderer/src/browser/Page.ts+++ b/packages/renderer/src/browser/Page.ts@@ -31,7 +31,7 @@ import {EventEmitter, Handler} from './EventEmitter';import {Frame, FrameManager, FrameManagerEmittedEvents} from './FrameManager';import {HTTPRequest} from './HTTPRequest';import {HTTPResponse} from './HTTPResponse';-import {ElementHandle, JSHandle, _createJSHandle} from './JSHandle';+import {JSHandle, _createJSHandle} from './JSHandle';import {PuppeteerLifeCycleEvent} from './LifecycleWatcher';import {NetworkManagerEmittedEvents} from './NetworkManager';import {Viewport} from './PuppeteerViewport';@@ -47,7 +47,6 @@ import {pageBindingDeliverErrorString,pageBindingDeliverErrorValueString,pageBindingDeliverResultString,- pageBindingInitString,releaseObject,valueFromRemoteObject,waitForEvent,@@ -481,9 +480,6 @@ export class Page extends EventEmitter {client.on('Inspector.targetCrashed', () => {return this.#onTargetCrashed();});- client.on('Performance.metrics', (event) => {- return this.#emitMetrics(event);- });client.on('Log.entryAdded', (event) => {return this.#onLogEntryAdded(event);});@@ -738,256 +734,6 @@ export class Page extends EventEmitter {return context.queryObjects(prototypeHandle);}- /**- * The method evaluates the XPath expression relative to the page document as- * its context node. If there are no such elements, the method resolves to an- * empty array.- * @remarks- * Shortcut for {@link Frame.$x | Page.mainFrame().$x(expression) }.- * @param expression - Expression to evaluate- */- async $x(expression: string): Promise<ElementHandle[]> {- return this.mainFrame().$x(expression);- }-- /**- * If no URLs are specified, this method returns cookies for the current page- * URL. If URLs are specified, only cookies for those URLs are returned.- */- async cookies(...urls: string[]): Promise<Protocol.Network.Cookie[]> {- const originalCookies = (- await this.#client.send('Network.getCookies', {- urls: urls.length ? urls : [this.url()],- })- ).cookies;-- const unsupportedCookieAttributes = ['priority'];- const filterUnsupportedAttributes = (- cookie: Protocol.Network.Cookie- ): Protocol.Network.Cookie => {- for (const attr of unsupportedCookieAttributes) {- delete (cookie as unknown as Record<string, unknown>)[attr];- }-- return cookie;- };-- return originalCookies.map(filterUnsupportedAttributes);- }-- async deleteCookie(- ...cookies: Protocol.Network.DeleteCookiesRequest[]- ): Promise<void> {- const pageURL = this.url();- for (const cookie of cookies) {- const item = {...cookie};- if (!cookie.url && pageURL.startsWith('http')) {- item.url = pageURL;- }-- await this.#client.send('Network.deleteCookies', item);- }- }-- /**- * @example- * ```js- * await page.setCookie(cookieObject1, cookieObject2);- * ```- */- async setCookie(...cookies: Protocol.Network.CookieParam[]): Promise<void> {- const pageURL = this.url();- const startsWithHTTP = pageURL.startsWith('http');- const items = cookies.map((cookie) => {- const item = {...cookie};- if (!item.url && startsWithHTTP) {- item.url = pageURL;- }-- assert(- item.url !== 'about:blank',- `Blank page can not have cookie "${item.name}"`- );- assert(- !String.prototype.startsWith.call(item.url || '', 'data:'),- `Data URL page can not have cookie "${item.name}"`- );- return item;- });- await this.deleteCookie(...items);- if (items.length) {- await this.#client.send('Network.setCookies', {cookies: items});- }- }-- /**- * 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- * `Promise` which resolves to the return value of `puppeteerFunction`.- *- * If the puppeteerFunction returns a `Promise`, it will be awaited.- *- * NOTE: Functions installed via `page.exposeFunction` survive navigations.- * @param name - Name of the function on the window object- * @param puppeteerFunction - Callback function which will be called in- * Puppeteer's context.- * @example- * An example of adding an `md5` function into the page:- * ```js- * const puppeteer = require('puppeteer');- * const crypto = require('crypto');- *- * (async () => {- * const browser = await puppeteer.launch();- * const page = await browser.newPage();- * page.on('console', (msg) => console.log(msg.text()));- * await page.exposeFunction('md5', (text) =>- * crypto.createHash('md5').update(text).digest('hex')- * );- * await page.evaluate(async () => {- * // use window.md5 to compute hashes- * const myString = 'PUPPETEER';- * const myHash = await window.md5(myString);- * console.log(`md5 of ${myString} is ${myHash}`);- * });- * await browser.close();- * })();- * ```- * An example of adding a `window.readfile` function into the page:- * ```js- * const puppeteer = require('puppeteer');- * const fs = require('fs');- *- * (async () => {- * const browser = await puppeteer.launch();- * const page = await browser.newPage();- * page.on('console', (msg) => console.log(msg.text()));- * await page.exposeFunction('readfile', async (filePath) => {- * return new Promise((resolve, reject) => {- * fs.readFile(filePath, 'utf8', (err, text) => {- * if (err) reject(err);- * else resolve(text);- * });- * });- * });- * await page.evaluate(async () => {- * // use window.readfile to read contents of a file- * const content = await window.readfile('/etc/hosts');- * console.log(content);- * });- * await browser.close();- * })();- * ```- */- async exposeFunction(- name: string,- puppeteerFunction: Function | {default: Function}- ): Promise<void> {- if (this.#pageBindings.has(name)) {- throw new Error(- `Failed to add page binding with name ${name}: window['${name}'] already exists!`- );- }-- let exposedFunction: Function;- if (typeof puppeteerFunction === 'function') {- exposedFunction = puppeteerFunction;- } else if (typeof puppeteerFunction.default === 'function') {- exposedFunction = puppeteerFunction.default;- } else {- throw new Error(- `Failed to add page binding with name ${name}: ${puppeteerFunction} is not a function or a module with a default export.`- );- }-- this.#pageBindings.set(name, exposedFunction);-- const expression = pageBindingInitString('exposedFun', name);- await this.#client.send('Runtime.addBinding', {name});- await this.#client.send('Page.addScriptToEvaluateOnNewDocument', {- source: expression,- });- await Promise.all(- this.frames().map((frame) => {- return frame.evaluate(expression).catch(debugError);- })- );- }-- /**- * The extra HTTP headers will be sent with every request the page initiates.- * NOTE: All HTTP header names are lowercased. (HTTP headers are- * case-insensitive, so this shouldn’t impact your server code.)- * NOTE: page.setExtraHTTPHeaders does not guarantee the order of headers in- * the outgoing requests.- * @param headers - An object containing additional HTTP headers to be sent- * with every request. All header values must be strings.- * @returns- */- async setExtraHTTPHeaders(headers: Record<string, string>): Promise<void> {- return this.#frameManager.networkManager().setExtraHTTPHeaders(headers);- }-- /**- * @returns Object containing metrics as key/value pairs.- *- * - `Timestamp` : The timestamp when the metrics sample was taken.- *- * - `Documents` : Number of documents in the page.- *- * - `Frames` : Number of frames in the page.- *- * - `JSEventListeners` : Number of events in the page.- *- * - `Nodes` : Number of DOM nodes in the page.- *- * - `LayoutCount` : Total number of full or partial page layout.- *- * - `RecalcStyleCount` : Total number of page style recalculations.- *- * - `LayoutDuration` : Combined durations of all page layouts.- *- * - `RecalcStyleDuration` : Combined duration of all page style- * recalculations.- *- * - `ScriptDuration` : Combined duration of JavaScript execution.- *- * - `TaskDuration` : Combined duration of all tasks performed by the browser.- *- *- * - `JSHeapUsedSize` : Used JavaScript heap size.- *- * - `JSHeapTotalSize` : Total JavaScript heap size.- * @remarks- * NOTE: All timestamps are in monotonic time: monotonically increasing time- * in seconds since an arbitrary point in the past.- */- async metrics(): Promise<Metrics> {- const response = await this.#client.send('Performance.getMetrics');- return this.#buildMetricsObject(response.metrics);- }-- #emitMetrics(event: Protocol.Performance.MetricsEvent): void {- this.emit(PageEmittedEvents.Metrics, {- title: event.title,- metrics: this.#buildMetricsObject(event.metrics),- });- }-- #buildMetricsObject(metrics?: Protocol.Performance.Metric[]): Metrics {- const result: Record<- Protocol.Performance.Metric['name'],- Protocol.Performance.Metric['value']- > = {};- for (const metric of metrics || []) {- if (supportedMetrics.has(metric.name)) {- result[metric.name] = metric.value;- }- }-- return result;- }-#handleException(exceptionDetails: Protocol.Runtime.ExceptionDetails): void {const message = getExceptionMessage(exceptionDetails);const err = new Error(message);@@ -1570,88 +1316,6 @@ export class Page extends EventEmitter {);}- /**- * Causes your script to wait for the given number of milliseconds.- *- * @remarks- *- * It's generally recommended to not wait for a number of seconds, but instead- * use {@link Page.waitForSelector}, {@link Page.waitForXPath} or- * {@link Page.waitForFunction} to wait for exactly the conditions you want.- *- * @example- *- * Wait for 1 second:- *- * ```- * await page.waitForTimeout(1000);- * ```- *- * @param milliseconds - the number of milliseconds to wait.- */- waitForTimeout(milliseconds: number): Promise<void> {- return this.mainFrame().waitForTimeout(milliseconds);- }-- /**- * Wait for the `xpath` to appear in page. If at the moment of calling the- * method the `xpath` already exists, the method will return immediately. If- * the `xpath` doesn't appear after the `timeout` milliseconds of waiting, the- * function will throw.- *- * This method works across navigation- * ```js- * const puppeteer = require('puppeteer');- * (async () => {- * const browser = await puppeteer.launch();- * const page = await browser.newPage();- * let currentURL;- * page- * .waitForXPath('//img')- * .then(() => console.log('First URL with image: ' + currentURL));- * for (currentURL of [- * 'https://example.com',- * 'https://google.com',- * 'https://bbc.com',- * ]) {- * await page.goto(currentURL);- * }- * await browser.close();- * })();- * ```- * @param xpath - A- * {@link https://developer.mozilla.org/en-US/docs/Web/XPath | xpath} of an- * element to wait for- * @param options - Optional waiting parameters- * @returns Promise which resolves when element specified by xpath string is- * added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is- * not found in DOM.- * @remarks- * The optional Argument `options` have properties:- *- * - `visible`: A boolean to wait for element to be present in DOM and to be- * visible, i.e. to not have `display: none` or `visibility: hidden` CSS- * properties. Defaults to `false`.- *- * - `hidden`: A boolean wait for element to not be found in the DOM or to be- * hidden, i.e. have `display: none` or `visibility: hidden` CSS properties.- * Defaults to `false`.- *- * - `timeout`: A number which is maximum time to wait for in milliseconds.- * Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default- * value can be changed by using the {@link Page.setDefaultTimeout} method.- */- waitForXPath(- xpath: string,- options: {- visible?: boolean;- hidden?: boolean;- timeout?: number;- } = {}- ): Promise<ElementHandle | null> {- return this.mainFrame().waitForXPath(xpath, options);- }-/*** The `waitForFunction` can be used to observe viewport size change:*@@ -1729,19 +1393,3 @@ export class Page extends EventEmitter {return this.mainFrame().waitForFunction(pageFunction, options, ...args);}}--const supportedMetrics = new Set<string>([- 'Timestamp',- 'Documents',- 'Frames',- 'JSEventListeners',- 'Nodes',- 'LayoutCount',- 'RecalcStyleCount',- 'LayoutDuration',- 'RecalcStyleDuration',- 'ScriptDuration',- 'TaskDuration',- 'JSHeapUsedSize',- 'JSHeapTotalSize',-]);