Merge pull request #26489 from ksm2/master

[puppeteer] Update typings to Puppeteer 1.5.0
This commit is contained in:
Paul van Brenk
2018-06-25 15:39:58 -07:00
committed by GitHub
5 changed files with 412 additions and 48 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/smooth-code/jest-puppeteer/tree/master/packages/expect-puppeteer
// Definitions by: Josh Goldberg <https://github.com/JoshuaKGoldberg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
// TypeScript Version: 2.8
/// <reference types="jest" />
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/smooth-code/jest-puppeteer/tree/master/packages/jest-environment-puppeteer
// Definitions by: Josh Goldberg <https://github.com/joshuakgoldberg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.8
import { Browser, Page } from "puppeteer";
+343 -37
View File
@@ -1,15 +1,203 @@
// Type definitions for puppeteer 1.3
// Type definitions for puppeteer 1.5
// Project: https://github.com/GoogleChrome/puppeteer#readme
// Definitions by: Marvin Hagemeister <https://github.com/marvinhagemeister>
// Christopher Deutsch <https://github.com/cdeutsch>
// Konstantin Simon Maria Möllers <https://github.com/ksm2>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// TypeScript Version: 2.8
/// <reference types="node" />
import { EventEmitter } from "events";
import { ChildProcess } from "child_process";
/** Wraps a DOM element into an ElementHandle instance */
export type WrapElementHandle<X> = X extends Element ? ElementHandle<X> : X;
/** Unwraps a DOM element out of an ElementHandle instance */
export type UnwrapElementHandle<X> = X extends ElementHandle<infer E> ? E : X;
/** Defines `$eval` and `$$eval` for Page, Frame and ElementHandle. */
export interface Evalable {
/**
* This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
* If there's no element matching `selector`, the method throws an error.
*
* If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @returns Promise which resolves to the return value of pageFunction
*/
$eval<R>(
selector: string,
pageFunction: (element: Element) => R | Promise<R>,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
* If there's no element matching `selector`, the method throws an error.
*
* If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @param x1 First argument to pass to pageFunction
* @returns Promise which resolves to the return value of pageFunction
*/
$eval<R, X1>(
selector: string,
pageFunction: (element: Element, x1: UnwrapElementHandle<X1>) => R | Promise<R>,
x1: X1,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
* If there's no element matching `selector`, the method throws an error.
*
* If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @param x1 First argument to pass to pageFunction
* @param x2 Second argument to pass to pageFunction
* @returns Promise which resolves to the return value of pageFunction
*/
$eval<R, X1, X2>(
selector: string,
pageFunction: (element: Element, x1: UnwrapElementHandle<X1>, x2: UnwrapElementHandle<X2>) => R | Promise<R>,
x1: X1,
x2: X2,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
* If there's no element matching `selector`, the method throws an error.
*
* If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @param x1 First argument to pass to pageFunction
* @param x2 Second argument to pass to pageFunction
* @param x3 Third argument to pass to pageFunction
* @returns Promise which resolves to the return value of pageFunction
*/
$eval<R, X1, X2, X3>(
selector: string,
pageFunction: (element: Element, x1: UnwrapElementHandle<X1>, x2: UnwrapElementHandle<X2>, x3: UnwrapElementHandle<X3>) => R | Promise<R>,
x1: X1,
x2: X2,
x3: X3,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `document.querySelector` within the context and passes it as the first argument to `pageFunction`.
* If there's no element matching `selector`, the method throws an error.
*
* If `pageFunction` returns a Promise, then `$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction 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<R>(
selector: string,
pageFunction: (element: Element, ...args: any[]) => R | Promise<R>,
...args: any[],
): Promise<WrapElementHandle<R>>;
/**
* This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
* first argument to `pageFunction`.
*
* If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @returns Promise which resolves to the return value of pageFunction
*/
$$eval<R>(
selector: string,
pageFunction: (elements: Element[]) => R | Promise<R>,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
* first argument to `pageFunction`.
*
* If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @param x1 First argument to pass to pageFunction
* @returns Promise which resolves to the return value of pageFunction
*/
$$eval<R, X1>(
selector: string,
pageFunction: (elements: Element[], x1: UnwrapElementHandle<X1>) => R | Promise<R>,
x1: X1,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
* first argument to `pageFunction`.
*
* If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @param x1 First argument to pass to pageFunction
* @param x2 Second argument to pass to pageFunction
* @returns Promise which resolves to the return value of pageFunction
*/
$$eval<R, X1, X2>(
selector: string,
pageFunction: (elements: Element[], x1: UnwrapElementHandle<X1>, x2: UnwrapElementHandle<X2>) => R | Promise<R>,
x1: X1,
x2: X2,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
* first argument to `pageFunction`.
*
* If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction Function to be evaluated in browser context
* @param x1 First argument to pass to pageFunction
* @param x2 Second argument to pass to pageFunction
* @param x3 Third argument to pass to pageFunction
* @returns Promise which resolves to the return value of pageFunction
*/
$$eval<R, X1, X2, X3>(
selector: string,
pageFunction: (elements: Element[], x1: UnwrapElementHandle<X1>, x2: UnwrapElementHandle<X2>, x3: UnwrapElementHandle<X3>) => R | Promise<R>,
x1: X1,
x2: X2,
x3: X3,
): Promise<WrapElementHandle<R>>;
/**
* This method runs `Array.from(document.querySelectorAll(selector))` within the context and passes it as the
* first argument to `pageFunction`.
*
* If `pageFunction` returns a Promise, then `$$eval` would wait for the promise to resolve and return its value.
*
* @param selector A selector to query for
* @param pageFunction 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<R>(
selector: string,
pageFunction: (elements: Element[], ...args: any[]) => R | Promise<R>,
...args: any[]
): Promise<WrapElementHandle<R>>;
}
/** Keyboard provides an api for managing a virtual keyboard. */
export interface Keyboard {
/**
@@ -147,7 +335,9 @@ export type PageEvents =
| "request"
| "requestfailed"
| "requestfinished"
| "response";
| "response"
| "workercreated"
| "workerdestroyed";
export type BrowserEvents =
| "disconnected"
@@ -452,22 +642,57 @@ export interface Box {
y: number;
}
/**
* The Worker class represents a WebWorker.
* The events workercreated and workerdestroyed are emitted on the page object to signal the worker lifecycle.
*/
export interface Worker {
/**
* If the function passed to the `worker.evaluate` returns a Promise,
* then `worker.evaluate` would wait for the promise to resolve and return its value.
*
* If the function passed to the `worker.evaluate` returns a non-Serializable value,
* then `worker.evaluate` resolves to `undefined`.
*/
evaluate<T>(
pageFunction: (...args: any[]) => T | Promise<T>,
...args: any[],
): Promise<T>;
/**
* The only difference between `worker.evaluate` and `worker.evaluateHandle` is
* that `worker.evaluateHandle` returns in-page object (JSHandle).
*/
evaluateHandle<T>(
pageFunction: (...args: any[]) => T | Promise<T>,
...args: any[],
): Promise<T>;
executionContext(): Promise<ExecutionContext>;
url(): string;
}
/**
* Represents an in-page DOM element. ElementHandles can be created with the page.$ method.
*/
export interface ElementHandle extends JSHandle {
export interface ElementHandle<E extends Element = Element> extends JSHandle, Evalable {
/**
* The method runs element.querySelector within the page. If no element matches the selector, the return value resolve to null.
* 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<ElementHandle | null>;
/**
* The method runs element.querySelectorAll within the page. If no elements match the selector, the return value resolve to [].
* 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<ElementHandle[]>;
/**
* @param selector XPath expression to evaluate.
*/
@@ -683,6 +908,10 @@ export interface Request {
* All header names are lower-case.
*/
headers(): Headers;
/** Whether this request is driving frame's navigation. */
isNavigationRequest(): boolean;
/** Returns the request's method (GET, POST, etc.) */
method(): HttpMethod;
@@ -761,46 +990,25 @@ export interface Response {
url(): string;
}
export interface FrameBase {
export interface FrameBase extends Evalable {
/**
* The method runs document.querySelector within the page.
* If no element matches the selector, the return value resolve to null.
* The method queries frame for the selector.
* If there's no such element within the frame, the method will resolve to null.
*/
$(selector: string): Promise<ElementHandle | null>;
/**
* The method runs document.querySelectorAll within the page. If no elements match the selector, the return value resolve to [].
* The method runs document.querySelectorAll within the frame.
* If no elements match the selector, the return value resolve to [].
*/
$$(selector: string): Promise<ElementHandle[]>;
/**
* The method evaluates the XPath expression.
* @param expression XPath expression to evaluate.
*/
$x(expression: string): Promise<ElementHandle[]>;
/**
* 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,
pageFunction: (element: Element, ...args: any[]) => any,
...args: any[]
): Promise<any>;
/**
* 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,
pageFunction: (elements: NodeListOf<Element>, ...args: any[]) => any,
...args: any[]
): Promise<any>;
/** Adds a `<script>` tag into the page with the desired url or content. */
addScriptTag(options: ScriptTagOptions): Promise<void>;
@@ -963,6 +1171,15 @@ export interface PageEventObj {
requestfinished: Request;
/** Emitted when a response is received. */
response: Response;
/** Emitted when a dedicated WebWorker is spawned by the page. */
workercreated: Worker;
/** Emitted when a dedicated WebWorker is terminated. */
workerdestroyed: Worker;
}
export interface PageCloseOptions {
/** Defaults to `false`. Whether to run the before unload page handlers. */
runBeforeUnload?: boolean;
}
/** Page provides methods to interact with a single tab in Chromium. One Browser instance might have multiple Page instances. */
@@ -999,8 +1216,11 @@ export interface Page extends EventEmitter, FrameBase {
/** Brings page to front (activates tab). */
bringToFront(): Promise<void>;
/** Get the browser the page belongs to. */
browser(): Promise<Browser>;
/** Closes the current page. */
close(): Promise<void>;
close(options?: PageCloseOptions): Promise<void>;
/**
* Gets the cookies.
@@ -1080,6 +1300,9 @@ export interface Page extends EventEmitter, FrameBase {
/** Returns the virtual keyboard. */
keyboard: Keyboard;
/** Indicates that the page has been closed. */
isClosed(): boolean;
/** Page is guaranteed to have a main frame which persists during navigation's. */
mainFrame(): Frame;
@@ -1213,6 +1436,9 @@ export interface Page extends EventEmitter, FrameBase {
* @param options The navigation parameters.
*/
waitForNavigation(options?: NavigationOptions): Promise<Response>;
/** This method returns all of the dedicated WebWorkers associated with the page. */
workers(): Worker[];
}
/** A Browser is created when Puppeteer connects to a Chromium instance, either through puppeteer.launch or puppeteer.connect. */
@@ -1240,12 +1466,24 @@ export interface Browser extends EventEmitter {
handler: (e: BrowserEventObj[K], ...args: any[]) => void
): this;
/**
* Returns an array of all open browser contexts.
* In a newly created browser, this will return a single instance of BrowserContext.
*/
browserContexts(): BrowserContext[];
/**
* Closes browser with all the pages (if any were opened).
* The browser object itself is considered to be disposed and can not be used anymore.
*/
close(): Promise<void>;
/**
* Creates a new incognito browser context.
* This won't share cookies/cache with other browser contexts.
*/
createIncognitoBrowserContext(): Promise<BrowserContext>;
/**
* Disconnects Puppeteer from the browser, but leaves the Chromium process running.
* After calling `disconnect`, the browser object is considered disposed and cannot be used anymore.
@@ -1291,15 +1529,83 @@ export interface BrowserEventObj {
targetdestroyed: Target;
}
/**
* BrowserContexts provide a way to operate multiple independent browser sessions.
* When a browser is launched, it has a single BrowserContext used by default.
* The method `browser.newPage()` creates a page in the default browser context.
*/
export interface BrowserContext extends EventEmitter {
/**
* Adds the listener function to the end of the listeners array for the event named `eventName`.
* No checks are made to see if the listener has already been added. Multiple calls passing the same combination of
* `eventName` and listener will result in the listener being added, and called, multiple times.
* @param event The name of the event.
* @param handler The callback function.
*/
on<K extends keyof BrowserContextEventObj>(
eventName: K,
handler: (e: BrowserContextEventObj[K], ...args: any[]) => void
): this;
/**
* Adds a one time listener function for the event named `eventName`.
* The next time `eventName` is triggered, this listener is removed and then invoked.
* @param event The name of the event.
* @param handler The callback function.
*/
once<K extends keyof BrowserContextEventObj>(
eventName: K,
handler: (e: BrowserContextEventObj[K], ...args: any[]) => void
): this;
/** The browser this browser context belongs to. */
browser(): Browser;
/** Closes the browser context. All the targets that belong to the browser context will be closed. */
close(): Promise<void>;
/**
* Returns whether BrowserContext is incognito.
* The default browser context is the only non-incognito browser context.
*/
isIncognito(): boolean;
/** Creates a new page in the browser context. */
newPage(): Promise<Page>;
/** An array of all active targets inside the browser context. */
targets(): Target[];
}
export interface BrowserContextEventObj {
/** Emitted when the url of a target inside the browser context changes. */
targetchanged: Target;
/** Emitted when a target is created, for example when a new page is opened by `window.open` or `browserContext.newPage`. */
targetcreated: Target;
/** Emitted when a target is destroyed, for example when a page is closed. */
targetdestroyed: Target;
}
export interface Target {
/** Get the browser the target belongs to. */
browser(): Browser;
/** The browser context the target belongs to. */
browserContext(): BrowserContext;
/** Creates a Chrome Devtools Protocol session attached to the target. */
createCDPSession(): Promise<CDPSession>;
/** Get the target that opened this target. Top-level targets return `null`. */
opener(): Target | null;
/** Returns the target `Page` or a `null` if the type of the page is not "page". */
page(): Promise<Page>;
/** Identifies what kind of target this is. */
type(): "page" | "service_worker" | "other";
type(): "page" | "background_page" | "service_worker" | "browser" | "other";
/** Returns the target URL. */
url(): string;
+66 -8
View File
@@ -275,15 +275,32 @@ puppeteer.launch().then(async browser => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://example.com");
let elementText = await page.$eval('#someElement', (element) => {
return element.innerHTML;
});
const elementText = await page.$eval(
'#someElement',
(
element, // $ExpectType Element
) => {
element.innerHTML; // $ExpectType string
return element.innerHTML;
}
);
elementText; // $ExpectType string
elementText = await page.$$eval('.someClassName', (elements) => {
console.log(elements.length);
console.log(elements.item(0).outerHTML);
return elements[3].innerHTML;
});
// If one returns a DOM reference, puppeteer will wrap an ElementHandle instead
const someElement = await page.$$eval(
'.someClassName',
(
elements, // $ExpectType Element[]
) => {
console.log(elements.length);
console.log(elements[0].outerHTML);
return elements[3] as HTMLDivElement;
}
);
someElement; // $ExpectType ElementHandle<HTMLDivElement>
// If one passes an ElementHandle, puppeteer will unwrap its DOM reference instead
await page.$eval('.hello-world', (e, x1: HTMLDivElement) => x1.noWrap, someElement);
browser.close();
})();
@@ -338,3 +355,44 @@ puppeteer.launch().then(async browser => {
await page.tracing.start({ path: "trace.json", categories: ["one", "two"] });
});
// 1.5: From the BrowserContext example
(async () => {
const browser = await puppeteer.launch();
// Create a new incognito browser context
const context = await browser.createIncognitoBrowserContext();
// Create a new page inside context.
const page = await context.newPage();
// ... do stuff with page ...
await page.goto('https://example.com');
// Dispose context once it's no longer needed.
await context.close();
});
// 1.5: From the Worker example
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('workercreated', worker => console.log('Worker created: ' + worker.url()));
page.on('workerdestroyed', worker => console.log('Worker destroyed: ' + worker.url()));
console.log('Current workers:');
for (const worker of page.workers())
console.log(' ' + worker.url());
});
// Test conditional types
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const eh = await page.$('tr.something') as puppeteer.ElementHandle<HTMLTableRowElement>;
const index = await page.$eval(
'.demo',
(
e, // $ExpectType Element
x1, // $ExpectType HTMLTableRowElement
) => x1.rowIndex,
eh,
);
index; // $ExpectType number
});
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/storybooks/storybook/tree/master/addons/storyshots
// Definitions by: Bradley Ayers <https://github.com/bradleyayers>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import * as React from 'react';
import { StoryObject } from '@storybook/react';