diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 8479c100a1..098ba9616a 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 0.12 +// Type definitions for puppeteer 0.13 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -7,49 +7,122 @@ /// +/** Keyboard provides an api for managing a virtual keyboard. */ export interface Keyboard { + /** + * Dispatches a keydown event. + * @param key Name of key to press, such as ArrowLeft. + * @param options Specifies a input text event. + */ down(key: string, options?: { text?: string }): Promise; + + /** Shortcut for `keyboard.down` and `keyboard.up`. */ press(key: string, options?: { text?: string, delay?: number }): Promise; + + /** Dispatches a `keypress` and `input` event. This does not send a `keydown` or keyup `event`. */ sendCharacter(char: string): Promise; + + /** + * Sends a keydown, keypress/input, and keyup event for each character in the text. + * @param text A text to type into a focused element. + * @param options Specifies the typing options. + */ type(text: string, options?: { delay?: number }): Promise; + + /** + * Dispatches a keyup event. + * @param key Name of key to release, such as ArrowLeft. + */ up(key: string): Promise; } export interface MousePressOptions { + /** + * left, right, or middle. + * @default left + */ button?: MouseButtons; + /** + * The number of clicks. + * @default 1 + */ clickCount?: number; } export interface Mouse { + /** + * Shortcut for `mouse.move`, `mouse.down` and `mouse.up`. + * @param x The x position. + * @param y The y position. + * @param options The click options. + */ click(x: number, y: number, options: ClickOptions): Promise; + /** + * Dispatches a `mousedown` event. + * @param options The mouse press options. + */ down(options?: MousePressOptions): Promise; + + /** + * Dispatches a `mousemove` event. + * @param x The x position. + * @param y The y position. + * @param options The mouse move options. + */ move(x: number, y: number, options?: { steps: number }): Promise; + /** + * Dispatches a `mouseup` event. + * @param options The mouse press options. + */ up(options?: MousePressOptions): Promise; } export interface Touchscreen { + /** + * Dispatches a touchstart and touchend event. + * @param x The x position. + * @param y The y position. + */ tap(x: number, y: number): Promise; } - +/** + * You can use `tracing.start` and `tracing.stop` to create a trace file which can be opened in Chrome DevTools or timeline viewer. + */ export interface Tracing { start(options: { path: string; screenshots?: boolean }): Promise; stop(): Promise; } +/** Dialog objects are dispatched by page via the 'dialog' event. */ export interface Dialog { + /** + * Accepts the dialog. + * @param promptText A text to enter in prompt. Does not cause any effects if the dialog's type is not prompt. + */ accept(promptText?: string): Promise; + + /** If dialog is prompt, returns default prompt value. Otherwise, returns empty string. */ defaultValue(): string; + + /** Dismiss the dialog */ dismiss(): Promise; + + /** Returns the message displayed in the dialog. */ message(): string; + + /** The dialog type. Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. */ type: "alert" | "beforeunload" | "confirm" | "prompt"; } +/** ConsoleMessage objects are dispatched by page via the 'console' event. */ export interface ConsoleMessage { + /** The message arguments. */ args: JSHandle[]; + /** The message text. */ text: string; type: 'log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | - 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | - 'profile' | 'profileEnd' | 'count' | 'timeEnd'; + 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | + 'profile' | 'profileEnd' | 'count' | 'timeEnd'; } export type PageEvents = @@ -66,6 +139,12 @@ export type PageEvents = | "requestfinished" | "response"; +export type BrowserEvents = + | "disconnected" + | "targetchanged" + | "targetcreated" + | "targetdestroyed"; + export interface AuthOptions { username: string; password: string; @@ -85,18 +164,28 @@ export interface ClickOptions { delay?: number; } +/** Represents a browser cookie. */ export interface Cookie { + /** The cookie name. */ name: string; + /** The cookie value. */ value: string; + /** The cookie domain. */ domain: string; + /** The cookie path. */ path: string; + /** The cookie Unix expiration time in seconds. */ expires: number; + /** The cookie http only flag. */ httpOnly: boolean; + /** The cookie secure flag. */ secure: boolean; + /** The cookie same site definition. */ sameSite: "Strict" | "Lax"; } export interface DeleteCookie { + /** The cookie name. */ name: string; url?: string; domain?: string; @@ -105,37 +194,73 @@ export interface DeleteCookie { } export interface SetCookie { + /** The cookie name. */ name: string; + /** The cookie value. */ value: string; + /** The cookie domain. */ domain?: string; + /** The cookie path. */ path?: string; + /** The cookie Unix expiration time in seconds. */ expires?: number; + /** The cookie http only flag. */ httpOnly?: boolean; + /** The cookie secure flag. */ secure?: boolean; + /** The cookie same site definition. */ sameSite?: "Strict" | "Lax"; } export interface Viewport { + /** The page width in pixels. */ width: number; + /** The page height in pixels. */ height: number; + /** + * Specify device scale factor (can be thought of as dpr). + * @default 1 + */ deviceScaleFactor?: number; + /** + * Whether the `meta viewport` tag is taken into account. + * @default false + */ isMobile?: boolean; + /** + * Specifies if viewport supports touch events. + * @default false + */ hasTouch?: boolean; + /** + * Specifies if viewport is in landscape mode. + * @default false + */ isLandscape?: boolean; } +/** Page emulation options. */ export interface EmulateOptions { + /** The viewport emulation options. */ viewport?: Viewport; + /** The emulated user-agent. */ userAgent?: string; } export type EvaluateFn = string | ((...args: any[]) => any); +/** The navigation options. */ export interface NavigationOptions { + /** + * Maximum navigation time in milliseconds, pass 0 to disable timeout. + * @default 30000 + */ timeout?: number; - waitUntil?: "load" | "networkidle" | "networkIdleTimeout"; - networkIdleInflight?: number; - networkIdleTimeout?: number; + /** + * When to consider navigation succeeded. + * @default load Navigation is consider when the `load` event is fired. + */ + waitUntil?: "load" | "domcontentloaded" | "networkidle0" | "networkidle2"; } export type PDFFormat = @@ -151,41 +276,103 @@ export type PDFFormat = | "A5"; export interface PDFOptions { - /** If no path is provided, the PDF won't be saved to the disk. */ + /** + * The file path to save the PDF to. + * If `path` is a relative path, then it is resolved relative to current working directory. + * If no path is provided, the PDF won't be saved to the disk. + */ path?: string; + /** + * Scale of the webpage rendering. + * @default 1 + */ scale?: number; + /** + * Display header and footer. + * @default false + */ displayHeaderFooter?: boolean; + /** + * Print background graphics. + * @default false + */ printBackground?: boolean; + /** + * Paper orientation. + * @default false + */ landscape?: boolean; /** * Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty * string, which means print all pages. */ pageRanges?: string; + /** Paper format. If set, takes priority over width or height options. Defaults to 'Letter'. */ format?: PDFFormat; + /** Paper width, accepts values labeled with units. */ width?: string; + /** Paper height, accepts values labeled with units. */ height?: string; + /** Paper margins, defaults to none. */ margin?: { + /** Top margin, accepts values labeled with units. */ top?: string; + /** Right margin, accepts values labeled with units. */ right?: string; + /** Bottom margin, accepts values labeled with units. */ bottom?: string; + /** Left margin, accepts values labeled with units. */ left?: string; }; } +/** Defines the screenshot options. */ export interface ScreenshotOptions { + /** + * The file path to save the image to. The screenshot type will be inferred from file extension. + * If `path` is a relative path, then it is resolved relative to current working directory. + * If no path is provided, the image won't be saved to the disk. + */ path?: string; + /** + * The screenshot type. + * @default png + */ type?: "jpeg" | "png"; /** The quality of the image, between 0-100. Not applicable to png images. */ quality?: number; + /** + * When true, takes a screenshot of the full scrollable page. + * @default false + */ fullPage?: boolean; + /** + * An object which specifies clipping region of the page. + */ clip?: BoundingBox; + /** + * Hides default white background and allows capturing screenshots with transparency. + * @default false + */ omitBackground?: boolean; } -export interface TagOptions { +/** Options for `addStyleTag` */ +export interface StyleTagOptions { + /** Url of the tag. */ url?: string; + /** Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */ path?: string; + /** Raw CSS content to be injected into frame. */ + content?: string; +} +/** Options for `addScriptTag` */ +export interface ScriptTagOptions { + /** Url of a script to be added. */ + url?: string; + /** Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to current working directory. */ + path?: string; + /** Raw JavaScript content to be injected into frame. */ content?: string; } @@ -195,25 +382,84 @@ export interface PageFnOptions { } export interface BoundingBox { + /** The x-coordinate of top-left corner. */ x: number; + /** The y-coordinate of top-left corner. */ y: number; + /** The width. */ width: number; + /** The height. */ height: number; } +/** + * Represents an in-page DOM element. ElementHandles can be created with the page.$ method. + */ export interface ElementHandle extends JSHandle { - boundingBox(): BoundingBox; + /** + * The method runs element.querySelector within the page. If no element matches the selector, the return value resolve to null. + * @param selector A selector to query element for + * @since 0.13.0 + */ + $(selector: string): Promise; + /** + * The method runs element.querySelectorAll within the page. If no elements match the selector, the return value resolve to []. + * @param selector A selector to query element for + * @since 0.13.0 + */ + $$(selector: string): Promise; + /** + * This method returns the bounding box of the element (relative to the main frame), or null if the element is not visible. + */ + boundingBox(): BoundingBox | null; + /** + * This method scrolls element into view if needed, and then uses page.mouse to click in the center of the element. + * If the element is detached from DOM, the method throws an error. + * @param options Specifies the options. + * @since 0.9.0 + */ click(options?: ClickOptions): Promise; + /** + * Calls focus on the element. + */ focus(): Promise; + /** + * This method scrolls element into view if needed, and then uses page.mouse to hover over the center of the element. + * If the element is detached from DOM, the method throws an error. + */ hover(): Promise; + /** + * Focuses the element, and then uses keyboard.down and keyboard.up. + * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. + * @param options The text and delay options. + */ press(key: string, options?: { text?: string, delay?: number }): Promise; + /** + * This method scrolls element into view if needed, and then uses page.screenshot to take a screenshot of the element. + * If the element is detached from DOM, the method throws an error. + * @param options Same options as in page.screenshot. + */ screenshot(options?: ScreenshotOptions): Promise; + /** + * This method scrolls element into view if needed, and then uses touchscreen.tap to tap in the center of the element. + * If the element is detached from DOM, the method throws an error. + */ tap(): Promise; toString(): string; + /** + * Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text. + * @param text A text to type into a focused element. + * @param options The typing options. + */ type(text: string, options?: { delay: number }): Promise; + /** + * This method expects elementHandle to point to an input element. + * @param filePaths Sets the value of the file input these paths. If some of the filePaths are relative paths, then they are resolved relative to current working directory. + */ uploadFile(...filePaths: string[]): Promise; } +/** The class represents a context for JavaScript execution. */ export interface ExecutionContext { evaluate( fn: EvaluateFn, @@ -226,28 +472,64 @@ export interface ExecutionContext { queryObjects(prototypeHandle: JSHandle): JSHandle; } +/** JSHandle represents an in-page JavaScript object. */ export interface JSHandle { + /** + * Returns a ElementHandle + */ asElement(): ElementHandle; + /** + * Stops referencing the element handle. + */ dispose(): Promise; + /** + * Gets the execution context. + */ executionContext(): ExecutionContext; + /** + * Returns a map with property names as keys and JSHandle instances for the property values. + */ getProperties(): Promise>; + /** + * Fetches a single property from the objectHandle. + * @param propertyName The property to get. + */ getProperty(propertyName: string): Promise; + + /** + * Returns a JSON representation of the object. + * The JSON is generated by running JSON.stringify on the object in page and consequent JSON.parse in puppeteer. + * @throws The method will throw if the referenced object is not stringifiable. + */ jsonValue(): Promise; } export interface Metrics { + /** The timestamp when the metrics sample was taken. */ Timestamp: number; + /** Number of documents in the page. */ Documents: number; + /** Number of frames in the page. */ Frames: number; + /** Number of events in the page. */ JSEventListeners: number; + /** Number of DOM nodes in the page. */ Nodes: number; + /** Total number of full or partial page layout. */ LayoutCount: number; + /** Total number of page style recalculations. */ RecalcStyleCount: number; + /** Combined durations of all page layouts. */ LayoutDuration: number; + /** Combined duration of all page style recalculations. */ RecalcStyleDuration: number; + /** Combined duration of JavaScript execution. */ ScriptDuration: number; + /** Combined duration of all tasks performed by the browser. */ TaskDuration: number; + /** Used JavaScript heap size. */ JSHeapUsedSize: number; + /** Total JavaScript heap size. */ JSHeapTotalSize: number; } @@ -282,48 +564,148 @@ export interface Overrides { headers?: Headers; } +/** Represents a page request. */ export interface Request { + /** + * Aborts request. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + */ abort(): Promise; + + /** + * Continues request with optional request overrides. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + */ continue(overrides?: Overrides): Promise; + + /** + * An object with HTTP headers associated with the request. + * All header names are lower-case. + */ headers: Headers; + /** Returns the request's method (GET, POST, etc.) */ + method: HttpMethod; + + /** Contains the request's post body, if any. */ postData: string | undefined; + + /** Contains the request's resource type as it was perceived by the rendering engine. */ resourceType: ResourceType; + + /** + * Fulfills request with given response. + * To use this, request interception should be enabled with `page.setRequestInterception`. + * @throws An exception is immediately thrown if the request interception is not enabled. + * @param response The response options that will fulfill this request. + */ + respond(response: RespondOptions): Promise; + + /** A matching `Response` object, or `null` if the response has not been received yet. */ response(): Response | null; + + /** Contains the URL of the request. */ url: string; } +/** Options for `Request.respond` method */ +export interface RespondOptions { + /** + * Specifies the response status code. + * @default 200 + */ + status?: number; + /** Specifies the response headers. */ + headers?: Headers; + /** Specifies the Content-Type response header. */ + contentType?: string; + /** Specifies the response body. */ + body?: Buffer | string; +} +/** Response class represents responses which are received by page. */ export interface Response { + /** Promise which resolves to a buffer with response body. */ buffer(): Promise; + /** An object with HTTP headers associated with the response. All header names are lower-case. */ headers: Headers; + /** + * Promise which resolves to a JSON representation of response body. + * @throws This method will throw if the response body is not parsable via `JSON.parse`. + */ json(): Promise; + /** Contains a boolean stating whether the response was successful (status in the range 200-299) or not. */ ok: boolean; + /** A matching Request object. */ request(): Request; + /** Contains the status code of the response (e.g., 200 for a success). */ status: number; + /** Promise which resolves to a text representation of response body. */ text(): Promise; + /** Contains the URL of the response. */ url: string; } export interface FrameBase { - $(selector: string): Promise; + /** + * The method runs document.querySelector within the page. + * If no element matches the selector, the return value resolve to null. + */ + $(selector: string): Promise; + /** + * The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolve to []. + */ $$(selector: string): Promise; - $$eval( - selector: string, - fn: (...args: any[]) => void - ): Promise; + + /** + * This method runs document.querySelector within the page and passes it as the first argument to `fn`. + * If there's no element matching selector, the method throws an error. + * If `fn` returns a Promise, then $eval would wait for the promise to resolve and return its value. + */ $eval( selector: string, fn: (...args: any[]) => void ): Promise; - addScriptTag(options: TagOptions): Promise; - addStyleTag(options: TagOptions): Promise; - injectFile(filePath: string): Promise; + + /** + * This method runs document.querySelectorAll within the page and passes it as the first argument to `fn`. + * If `fn` returns a Promise, then $$eval would wait for the promise to resolve and return its value. + * @param selector A selector to query frame for + * @param fn Function to be evaluated in browser context + * @param args Arguments to pass to pageFunction + * @returns Promise which resolves to the return value of pageFunction + */ + $$eval( + selector: string, + fn: (...args: any[]) => void, + ...args: any[] + ): Promise; + + /** Adds a `