From ff22ba8679d58e616c112beca16bd032d8af6f75 Mon Sep 17 00:00:00 2001 From: Alex Rudenko Date: Fri, 26 May 2023 11:42:22 +0200 Subject: [PATCH] refactor: rename DeferredPromise to Deferred (#10255) --- packages/puppeteer-core/src/common/Browser.ts | 24 ++++---- .../src/common/ChromeTargetManager.ts | 10 +-- .../puppeteer-core/src/common/Connection.ts | 14 ++--- .../src/common/DeviceRequestPrompt.ts | 33 +++++----- .../src/common/FirefoxTargetManager.ts | 8 +-- packages/puppeteer-core/src/common/Frame.ts | 22 +++---- .../puppeteer-core/src/common/FrameTree.ts | 11 ++-- .../puppeteer-core/src/common/HTTPResponse.ts | 10 +-- .../src/common/IsolatedWorld.ts | 6 +- .../src/common/LifecycleWatcher.ts | 35 +++++------ .../src/common/NetworkManager.ts | 16 ++--- packages/puppeteer-core/src/common/Page.ts | 25 ++++---- packages/puppeteer-core/src/common/Target.ts | 18 +++--- .../puppeteer-core/src/common/WaitTask.ts | 4 +- .../puppeteer-core/src/common/WebWorker.ts | 4 +- .../puppeteer-core/src/injected/Poller.ts | 61 +++++++++---------- .../puppeteer-core/src/injected/injected.ts | 4 +- ...ferredPromise.ts => DebuggableDeferred.ts} | 10 ++- .../util/{DeferredPromise.ts => Deferred.ts} | 8 +-- packages/puppeteer-core/src/util/util.ts | 4 +- ...ferredPromise.spec.ts => Deferred.spec.ts} | 10 +-- 21 files changed, 158 insertions(+), 179 deletions(-) rename packages/puppeteer-core/src/util/{DebuggableDeferredPromise.ts => DebuggableDeferred.ts} (59%) rename packages/puppeteer-core/src/util/{DeferredPromise.ts => Deferred.ts} (90%) rename test/src/{DeferredPromise.spec.ts => Deferred.spec.ts} (86%) diff --git a/packages/puppeteer-core/src/common/Browser.ts b/packages/puppeteer-core/src/common/Browser.ts index dff1dd53..3a0c8351 100644 --- a/packages/puppeteer-core/src/common/Browser.ts +++ b/packages/puppeteer-core/src/common/Browser.ts @@ -33,7 +33,7 @@ import { import {BrowserContext} from '../api/BrowserContext.js'; import {Page} from '../api/Page.js'; import {assert} from '../util/assert.js'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {ChromeTargetManager} from './ChromeTargetManager.js'; import {CDPSession, Connection, ConnectionEmittedEvents} from './Connection.js'; @@ -361,7 +361,7 @@ export class CDPBrowser extends BrowserBase { #onAttachedToTarget = async (target: Target) => { if ( - (await target._initializedPromise.valueOrThrow()) === + (await target._initializedDeferred.valueOrThrow()) === InitializationStatus.SUCCESS ) { this.emit(BrowserEmittedEvents.TargetCreated, target); @@ -372,10 +372,10 @@ export class CDPBrowser extends BrowserBase { }; #onDetachedFromTarget = async (target: Target): Promise => { - target._initializedPromise.resolve(InitializationStatus.ABORTED); - target._isClosedPromise.resolve(); + target._initializedDeferred.resolve(InitializationStatus.ABORTED); + target._isClosedDeferred.resolve(); if ( - (await target._initializedPromise.valueOrThrow()) === + (await target._initializedDeferred.valueOrThrow()) === InitializationStatus.SUCCESS ) { this.emit(BrowserEmittedEvents.TargetDestroyed, target); @@ -438,7 +438,7 @@ export class CDPBrowser extends BrowserBase { throw new Error(`Missing target for page (id = ${targetId})`); } const initialized = - (await target._initializedPromise.valueOrThrow()) === + (await target._initializedDeferred.valueOrThrow()) === InitializationStatus.SUCCESS; if (!initialized) { throw new Error(`Failed to create target for page (id = ${targetId})`); @@ -461,7 +461,7 @@ export class CDPBrowser extends BrowserBase { this.#targetManager.getAvailableTargets().values() ).filter(target => { return ( - target._initializedPromise.value() === InitializationStatus.SUCCESS + target._initializedDeferred.value() === InitializationStatus.SUCCESS ); }); } @@ -501,17 +501,17 @@ export class CDPBrowser extends BrowserBase { options: WaitForTargetOptions = {} ): Promise { const {timeout = 30000} = options; - const targetPromise = createDeferredPromise>(); + const targetDeferred = createDeferred>(); this.on(BrowserEmittedEvents.TargetCreated, check); this.on(BrowserEmittedEvents.TargetChanged, check); try { this.targets().forEach(check); if (!timeout) { - return await targetPromise.valueOrThrow(); + return await targetDeferred.valueOrThrow(); } return await waitWithTimeout( - targetPromise.valueOrThrow(), + targetDeferred.valueOrThrow(), 'target', timeout ); @@ -521,8 +521,8 @@ export class CDPBrowser extends BrowserBase { } async function check(target: Target): Promise { - if ((await predicate(target)) && !targetPromise.resolved()) { - targetPromise.resolve(target); + if ((await predicate(target)) && !targetDeferred.resolved()) { + targetDeferred.resolve(target); } } } diff --git a/packages/puppeteer-core/src/common/ChromeTargetManager.ts b/packages/puppeteer-core/src/common/ChromeTargetManager.ts index b62c65a4..ee7537eb 100644 --- a/packages/puppeteer-core/src/common/ChromeTargetManager.ts +++ b/packages/puppeteer-core/src/common/ChromeTargetManager.ts @@ -18,7 +18,7 @@ import {Protocol} from 'devtools-protocol'; import {TargetFilterCallback} from '../api/Browser.js'; import {assert} from '../util/assert.js'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {CDPSession, Connection} from './Connection.js'; import {EventEmitter} from './EventEmitter.js'; @@ -81,7 +81,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager { (event: Protocol.Target.DetachedFromTargetEvent) => void > = new WeakMap(); - #initializePromise = createDeferredPromise(); + #initializeDeferred = createDeferred(); #targetsIdsForInit: Set = new Set(); constructor( @@ -131,7 +131,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager { autoAttach: true, }); this.#finishInitializationIfReady(); - await this.#initializePromise.valueOrThrow(); + await this.#initializeDeferred.valueOrThrow(); } dispose(): void { @@ -268,7 +268,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager { } const previousURL = target.url(); const wasInitialized = - target._initializedPromise.value() === InitializationStatus.SUCCESS; + target._initializedDeferred.value() === InitializationStatus.SUCCESS; target._targetInfoChanged(event.targetInfo); @@ -391,7 +391,7 @@ export class ChromeTargetManager extends EventEmitter implements TargetManager { #finishInitializationIfReady(targetId?: string): void { targetId !== undefined && this.#targetsIdsForInit.delete(targetId); if (this.#targetsIdsForInit.size === 0) { - this.#initializePromise.resolve(); + this.#initializeDeferred.resolve(); } } diff --git a/packages/puppeteer-core/src/common/Connection.ts b/packages/puppeteer-core/src/common/Connection.ts index 8188c93a..2f50d83c 100644 --- a/packages/puppeteer-core/src/common/Connection.ts +++ b/packages/puppeteer-core/src/common/Connection.ts @@ -18,7 +18,7 @@ import {Protocol} from 'devtools-protocol'; import {ProtocolMapping} from 'devtools-protocol/types/protocol-mapping.js'; import {assert} from '../util/assert.js'; -import {createDeferredPromise, DeferredPromise} from '../util/util.js'; +import {createDeferred, Deferred} from '../util/util.js'; import {ConnectionTransport} from './ConnectionTransport.js'; import {debug} from './Debug.js'; @@ -64,7 +64,7 @@ function createIncrementalIdGenerator(): GetIdFn { class Callback { #id: number; #error = new ProtocolError(); - #promise = createDeferredPromise(); + #deferred = createDeferred(); #timer?: ReturnType; #label: string; @@ -73,7 +73,7 @@ class Callback { this.#label = label; if (timeout) { this.#timer = setTimeout(() => { - this.#promise.reject( + this.#deferred.reject( rewriteError( this.#error, `${label} timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.` @@ -85,20 +85,20 @@ class Callback { resolve(value: unknown): void { clearTimeout(this.#timer); - this.#promise.resolve(value); + this.#deferred.resolve(value); } reject(error: Error): void { clearTimeout(this.#timer); - this.#promise.reject(error); + this.#deferred.reject(error); } get id(): number { return this.#id; } - get promise(): DeferredPromise { - return this.#promise; + get promise(): Deferred { + return this.#deferred; } get error(): ProtocolError { diff --git a/packages/puppeteer-core/src/common/DeviceRequestPrompt.ts b/packages/puppeteer-core/src/common/DeviceRequestPrompt.ts index 75e12f0b..36af82c6 100644 --- a/packages/puppeteer-core/src/common/DeviceRequestPrompt.ts +++ b/packages/puppeteer-core/src/common/DeviceRequestPrompt.ts @@ -18,10 +18,7 @@ import Protocol from 'devtools-protocol'; import {WaitTimeoutOptions} from '../api/Page.js'; import {assert} from '../util/assert.js'; -import { - createDeferredPromise, - DeferredPromise, -} from '../util/DeferredPromise.js'; +import {createDeferred, Deferred} from '../util/Deferred.js'; import {CDPSession} from './Connection.js'; import {TimeoutSettings} from './TimeoutSettings.js'; @@ -81,7 +78,7 @@ export class DeviceRequestPrompt { #updateDevicesHandle = this.#updateDevices.bind(this); #waitForDevicePromises = new Set<{ filter: (device: DeviceRequestPromptDevice) => boolean; - promise: DeferredPromise; + promise: Deferred; }>(); /** @@ -154,14 +151,14 @@ export class DeviceRequestPrompt { } const {timeout = this.#timeoutSettings.timeout()} = options; - const promise = createDeferredPromise({ + const deferred = createDeferred({ message: `Waiting for \`DeviceRequestPromptDevice\` failed: ${timeout}ms exceeded`, timeout, }); - const handle = {filter, promise}; + const handle = {filter, promise: deferred}; this.#waitForDevicePromises.add(handle); try { - return await promise.valueOrThrow(); + return await deferred.valueOrThrow(); } finally { this.#waitForDevicePromises.delete(handle); } @@ -218,9 +215,7 @@ export class DeviceRequestPrompt { export class DeviceRequestPromptManager { #client: CDPSession | null; #timeoutSettings: TimeoutSettings; - #deviceRequestPromptPromises = new Set< - DeferredPromise - >(); + #deviceRequestPrompDeferreds = new Set>(); /** * @internal @@ -248,27 +243,27 @@ export class DeviceRequestPromptManager { this.#client !== null, 'Cannot wait for device prompt through detached session!' ); - const needsEnable = this.#deviceRequestPromptPromises.size === 0; + const needsEnable = this.#deviceRequestPrompDeferreds.size === 0; let enablePromise: Promise | undefined; if (needsEnable) { enablePromise = this.#client.send('DeviceAccess.enable'); } const {timeout = this.#timeoutSettings.timeout()} = options; - const promise = createDeferredPromise({ + const deferred = createDeferred({ message: `Waiting for \`DeviceRequestPrompt\` failed: ${timeout}ms exceeded`, timeout, }); - this.#deviceRequestPromptPromises.add(promise); + this.#deviceRequestPrompDeferreds.add(deferred); try { const [result] = await Promise.all([ - promise.valueOrThrow(), + deferred.valueOrThrow(), enablePromise, ]); return result; } finally { - this.#deviceRequestPromptPromises.delete(promise); + this.#deviceRequestPrompDeferreds.delete(deferred); } } @@ -278,7 +273,7 @@ export class DeviceRequestPromptManager { #onDeviceRequestPrompted( event: Protocol.DeviceAccess.DeviceRequestPromptedEvent ) { - if (!this.#deviceRequestPromptPromises.size) { + if (!this.#deviceRequestPrompDeferreds.size) { return; } @@ -288,9 +283,9 @@ export class DeviceRequestPromptManager { this.#timeoutSettings, event ); - for (const promise of this.#deviceRequestPromptPromises) { + for (const promise of this.#deviceRequestPrompDeferreds) { promise.resolve(devicePrompt); } - this.#deviceRequestPromptPromises.clear(); + this.#deviceRequestPrompDeferreds.clear(); } } diff --git a/packages/puppeteer-core/src/common/FirefoxTargetManager.ts b/packages/puppeteer-core/src/common/FirefoxTargetManager.ts index 4628291f..aee0ef96 100644 --- a/packages/puppeteer-core/src/common/FirefoxTargetManager.ts +++ b/packages/puppeteer-core/src/common/FirefoxTargetManager.ts @@ -18,7 +18,7 @@ import {Protocol} from 'devtools-protocol'; import {TargetFilterCallback} from '../api/Browser.js'; import {assert} from '../util/assert.js'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {CDPSession, Connection} from './Connection.js'; import {EventEmitter} from './EventEmitter.js'; @@ -88,7 +88,7 @@ export class FirefoxTargetManager (event: Protocol.Target.AttachedToTargetEvent) => Promise > = new WeakMap(); - #initializePromise = createDeferredPromise(); + #initializeDeferred = createDeferred(); #targetsIdsForInit: Set = new Set(); constructor( @@ -169,7 +169,7 @@ export class FirefoxTargetManager filter: [{}], }); this.#targetsIdsForInit = new Set(this.#discoveredTargetsByTargetId.keys()); - await this.#initializePromise.valueOrThrow(); + await this.#initializeDeferred.valueOrThrow(); } #onTargetCreated = async ( @@ -253,7 +253,7 @@ export class FirefoxTargetManager #finishInitializationIfReady(targetId: string): void { this.#targetsIdsForInit.delete(targetId); if (this.#targetsIdsForInit.size === 0) { - this.#initializePromise.resolve(); + this.#initializeDeferred.resolve(); } } } diff --git a/packages/puppeteer-core/src/common/Frame.ts b/packages/puppeteer-core/src/common/Frame.ts index 836d9592..9032d53f 100644 --- a/packages/puppeteer-core/src/common/Frame.ts +++ b/packages/puppeteer-core/src/common/Frame.ts @@ -389,8 +389,8 @@ export class Frame extends BaseFrame { return this.worlds[MAIN_WORLD].transferHandle( await this.worlds[PUPPETEER_WORLD].evaluateHandle( - async ({createDeferredPromise}, {url, id, type, content}) => { - const promise = createDeferredPromise(); + async ({createDeferred}, {url, id, type, content}) => { + const deferred = createDeferred(); const script = document.createElement('script'); script.type = type; script.text = content; @@ -399,27 +399,27 @@ export class Frame extends BaseFrame { script.addEventListener( 'load', () => { - return promise.resolve(); + return deferred.resolve(); }, {once: true} ); script.addEventListener( 'error', event => { - promise.reject( + deferred.reject( new Error(event.message ?? 'Could not load script') ); }, {once: true} ); } else { - promise.resolve(); + deferred.resolve(); } if (id) { script.id = id; } document.head.appendChild(script); - await promise.valueOrThrow(); + await deferred.valueOrThrow(); return script; }, LazyArg.create(context => { @@ -457,8 +457,8 @@ export class Frame extends BaseFrame { return this.worlds[MAIN_WORLD].transferHandle( await this.worlds[PUPPETEER_WORLD].evaluateHandle( - async ({createDeferredPromise}, {url, content}) => { - const promise = createDeferredPromise(); + async ({createDeferred}, {url, content}) => { + const deferred = createDeferred(); let element: HTMLStyleElement | HTMLLinkElement; if (!url) { element = document.createElement('style'); @@ -472,14 +472,14 @@ export class Frame extends BaseFrame { element.addEventListener( 'load', () => { - promise.resolve(); + deferred.resolve(); }, {once: true} ); element.addEventListener( 'error', event => { - promise.reject( + deferred.reject( new Error( (event as ErrorEvent).message ?? 'Could not load style' ) @@ -488,7 +488,7 @@ export class Frame extends BaseFrame { {once: true} ); document.head.appendChild(element); - await promise.valueOrThrow(); + await deferred.valueOrThrow(); return element; }, LazyArg.create(context => { diff --git a/packages/puppeteer-core/src/common/FrameTree.ts b/packages/puppeteer-core/src/common/FrameTree.ts index 34effcc5..ca32755f 100644 --- a/packages/puppeteer-core/src/common/FrameTree.ts +++ b/packages/puppeteer-core/src/common/FrameTree.ts @@ -15,10 +15,7 @@ */ import {Frame as BaseFrame} from '../api/Frame.js'; -import { - createDeferredPromise, - DeferredPromise, -} from '../util/DeferredPromise.js'; +import {createDeferred, Deferred} from '../util/Deferred.js'; /** * Keeps track of the page frame tree and it's is managed by @@ -34,7 +31,7 @@ export class FrameTree { // frameID -> childFrameIDs #childIds = new Map>(); #mainFrame?: Frame; - #waitRequests = new Map>>(); + #waitRequests = new Map>>(); getMainFrame(): Frame | undefined { return this.#mainFrame; @@ -53,9 +50,9 @@ export class FrameTree { if (frame) { return Promise.resolve(frame); } - const deferred = createDeferredPromise(); + const deferred = createDeferred(); const callbacks = - this.#waitRequests.get(frameId) || new Set>(); + this.#waitRequests.get(frameId) || new Set>(); callbacks.add(deferred); return deferred.valueOrThrow(); } diff --git a/packages/puppeteer-core/src/common/HTTPResponse.ts b/packages/puppeteer-core/src/common/HTTPResponse.ts index e4c5ff16..84d5be16 100644 --- a/packages/puppeteer-core/src/common/HTTPResponse.ts +++ b/packages/puppeteer-core/src/common/HTTPResponse.ts @@ -20,7 +20,7 @@ import { HTTPResponse as BaseHTTPResponse, RemoteAddress, } from '../api/HTTPResponse.js'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {CDPSession} from './Connection.js'; import {ProtocolError} from './Errors.js'; @@ -34,7 +34,7 @@ export class HTTPResponse extends BaseHTTPResponse { #client: CDPSession; #request: HTTPRequest; #contentPromise: Promise | null = null; - #bodyLoadedPromise = createDeferredPromise(); + #bodyLoadedDeferred = createDeferred(); #remoteAddress: RemoteAddress; #status: number; #statusText: string; @@ -101,9 +101,9 @@ export class HTTPResponse extends BaseHTTPResponse { override _resolveBody(err: Error | null): void { if (err) { - return this.#bodyLoadedPromise.resolve(err); + return this.#bodyLoadedDeferred.resolve(err); } - return this.#bodyLoadedPromise.resolve(); + return this.#bodyLoadedDeferred.resolve(); } override remoteAddress(): RemoteAddress { @@ -136,7 +136,7 @@ export class HTTPResponse extends BaseHTTPResponse { override buffer(): Promise { if (!this.#contentPromise) { - this.#contentPromise = this.#bodyLoadedPromise + this.#contentPromise = this.#bodyLoadedDeferred .valueOrThrow() .then(async error => { if (error) { diff --git a/packages/puppeteer-core/src/common/IsolatedWorld.ts b/packages/puppeteer-core/src/common/IsolatedWorld.ts index 2b8c235e..5481cb73 100644 --- a/packages/puppeteer-core/src/common/IsolatedWorld.ts +++ b/packages/puppeteer-core/src/common/IsolatedWorld.ts @@ -19,7 +19,7 @@ import {Protocol} from 'devtools-protocol'; import type {ClickOptions, ElementHandle} from '../api/ElementHandle.js'; import {JSHandle} from '../api/JSHandle.js'; import {assert} from '../util/assert.js'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {Binding} from './Binding.js'; import {CDPSession} from './Connection.js'; @@ -101,7 +101,7 @@ export interface IsolatedWorldChart { export class IsolatedWorld { #frame: Frame; #document?: ElementHandle; - #context = createDeferredPromise(); + #context = createDeferred(); #detached = false; // Set of bindings that have been registered in the current context. @@ -144,7 +144,7 @@ export class IsolatedWorld { clearContext(): void { this.#document = undefined; - this.#context = createDeferredPromise(); + this.#context = createDeferred(); } setContext(context: ExecutionContext): void { diff --git a/packages/puppeteer-core/src/common/LifecycleWatcher.ts b/packages/puppeteer-core/src/common/LifecycleWatcher.ts index 12e0ce03..9cd5191b 100644 --- a/packages/puppeteer-core/src/common/LifecycleWatcher.ts +++ b/packages/puppeteer-core/src/common/LifecycleWatcher.ts @@ -16,10 +16,7 @@ import {HTTPResponse} from '../api/HTTPResponse.js'; import {assert} from '../util/assert.js'; -import { - DeferredPromise, - createDeferredPromise, -} from '../util/DeferredPromise.js'; +import {Deferred, createDeferred} from '../util/Deferred.js'; import {CDPSessionEmittedEvents} from './Connection.js'; import {TimeoutError} from './Errors.js'; @@ -74,10 +71,10 @@ export class LifecycleWatcher { #eventListeners: PuppeteerEventListener[]; #initialLoaderId: string; - #sameDocumentNavigationPromise = createDeferredPromise(); - #lifecyclePromise = createDeferredPromise(); - #newDocumentNavigationPromise = createDeferredPromise(); - #terminationPromise = createDeferredPromise(); + #sameDocumentNavigationDeferred = createDeferred(); + #lifecycleDeferred = createDeferred(); + #newDocumentNavigationDeferred = createDeferred(); + #terminationDeferred = createDeferred(); #timeoutPromise: Promise; @@ -85,7 +82,7 @@ export class LifecycleWatcher { #hasSameDocumentNavigation?: boolean; #swapped?: boolean; - #navigationResponseReceived?: DeferredPromise; + #navigationResponseReceived?: Deferred; constructor( frameManager: FrameManager, @@ -172,7 +169,7 @@ export class LifecycleWatcher { // navigation requests reported by the backend. This generally should not // happen by it looks like it's possible. this.#navigationResponseReceived?.resolve(); - this.#navigationResponseReceived = createDeferredPromise(); + this.#navigationResponseReceived = createDeferred(); if (request.response() !== null) { this.#navigationResponseReceived?.resolve(); } @@ -194,7 +191,7 @@ export class LifecycleWatcher { #onFrameDetached(frame: Frame): void { if (this.#frame === frame) { - this.#terminationPromise.resolve( + this.#terminationDeferred.resolve( new Error('Navigating frame was detached') ); return; @@ -209,25 +206,25 @@ export class LifecycleWatcher { } #terminate(error: Error): void { - this.#terminationPromise.resolve(error); + this.#terminationDeferred.resolve(error); } sameDocumentNavigationPromise(): Promise { - return this.#sameDocumentNavigationPromise.valueOrThrow(); + return this.#sameDocumentNavigationDeferred.valueOrThrow(); } newDocumentNavigationPromise(): Promise { - return this.#newDocumentNavigationPromise.valueOrThrow(); + return this.#newDocumentNavigationDeferred.valueOrThrow(); } lifecyclePromise(): Promise { - return this.#lifecyclePromise.valueOrThrow(); + return this.#lifecycleDeferred.valueOrThrow(); } timeoutOrTerminationPromise(): Promise { return Promise.race([ this.#timeoutPromise, - this.#terminationPromise.valueOrThrow(), + this.#terminationDeferred.valueOrThrow(), ]); } @@ -271,12 +268,12 @@ export class LifecycleWatcher { if (!checkLifecycle(this.#frame, this.#expectedLifecycle)) { return; } - this.#lifecyclePromise.resolve(); + this.#lifecycleDeferred.resolve(); if (this.#hasSameDocumentNavigation) { - this.#sameDocumentNavigationPromise.resolve(undefined); + this.#sameDocumentNavigationDeferred.resolve(undefined); } if (this.#swapped || this.#frame._loaderId !== this.#initialLoaderId) { - this.#newDocumentNavigationPromise.resolve(undefined); + this.#newDocumentNavigationDeferred.resolve(undefined); } function checkLifecycle( diff --git a/packages/puppeteer-core/src/common/NetworkManager.ts b/packages/puppeteer-core/src/common/NetworkManager.ts index 46817868..df0d6b8d 100644 --- a/packages/puppeteer-core/src/common/NetworkManager.ts +++ b/packages/puppeteer-core/src/common/NetworkManager.ts @@ -17,8 +17,8 @@ import {Protocol} from 'devtools-protocol'; import {assert} from '../util/assert.js'; -import {createDebuggableDeferredPromise} from '../util/DebuggableDeferredPromise.js'; -import {DeferredPromise} from '../util/DeferredPromise.js'; +import {createDebuggableDeferred} from '../util/DebuggableDeferred.js'; +import {Deferred} from '../util/Deferred.js'; import {CDPSession} from './Connection.js'; import {EventEmitter} from './EventEmitter.js'; @@ -88,7 +88,7 @@ export class NetworkManager extends EventEmitter { download: -1, latency: 0, }; - #deferredInitPromise?: DeferredPromise; + #deferredInit?: Deferred; constructor( client: CDPSession, @@ -130,10 +130,10 @@ export class NetworkManager extends EventEmitter { * might not resolve until after the target is resumed causing a deadlock. */ initialize(): Promise { - if (this.#deferredInitPromise) { - return this.#deferredInitPromise.valueOrThrow(); + if (this.#deferredInit) { + return this.#deferredInit.valueOrThrow(); } - this.#deferredInitPromise = createDebuggableDeferredPromise( + this.#deferredInit = createDebuggableDeferred( 'NetworkManager initialization timed out' ); const init = Promise.all([ @@ -144,7 +144,7 @@ export class NetworkManager extends EventEmitter { : null, this.#client.send('Network.enable'), ]); - const deferredInitPromise = this.#deferredInitPromise; + const deferredInitPromise = this.#deferredInit; init .then(() => { deferredInitPromise.resolve(); @@ -152,7 +152,7 @@ export class NetworkManager extends EventEmitter { .catch(err => { deferredInitPromise.reject(err); }); - return this.#deferredInitPromise.valueOrThrow(); + return this.#deferredInit.valueOrThrow(); } async authenticate(credentials?: Credentials): Promise { diff --git a/packages/puppeteer-core/src/common/Page.ts b/packages/puppeteer-core/src/common/Page.ts index ef6f1fe9..af22e2be 100644 --- a/packages/puppeteer-core/src/common/Page.ts +++ b/packages/puppeteer-core/src/common/Page.ts @@ -43,10 +43,7 @@ import { NewDocumentScriptEvaluation, } from '../api/Page.js'; import {assert} from '../util/assert.js'; -import { - createDeferredPromise, - DeferredPromise, -} from '../util/DeferredPromise.js'; +import {createDeferred, Deferred} from '../util/Deferred.js'; import {isErrorLike} from '../util/ErrorLike.js'; import {Accessibility} from './Accessibility.js'; @@ -155,7 +152,7 @@ export class CDPPage extends Page { #viewport: Viewport | null; #screenshotTaskQueue: TaskQueue; #workers = new Map(); - #fileChooserPromises = new Set>(); + #fileChooserPromises = new Set>(); #disconnectPromise?: Promise; #serviceWorkerBypassed = false; @@ -257,7 +254,7 @@ export class CDPPage extends Page { client.on('Page.fileChooserOpened', event => { return this.#onFileChooser(event); }); - this.#target._isClosedPromise + this.#target._isClosedDeferred .valueOrThrow() .then(() => { this.#target @@ -372,23 +369,23 @@ export class CDPPage extends Page { ): Promise { const needsEnable = this.#fileChooserPromises.size === 0; const {timeout = this.#timeoutSettings.timeout()} = options; - const promise = createDeferredPromise({ + const deferred = createDeferred({ message: `Waiting for \`FileChooser\` failed: ${timeout}ms exceeded`, timeout, }); - this.#fileChooserPromises.add(promise); + this.#fileChooserPromises.add(deferred); let enablePromise: Promise | undefined; if (needsEnable) { enablePromise = this.#client.send('Page.setInterceptFileChooserDialog', { enabled: true, }); } - return Promise.all([promise.valueOrThrow(), enablePromise]) + return Promise.all([deferred.valueOrThrow(), enablePromise]) .then(([result]) => { return result; }) .catch(error => { - this.#fileChooserPromises.delete(promise); + this.#fileChooserPromises.delete(deferred); throw error; }); } @@ -1011,7 +1008,7 @@ export class CDPPage extends Page { const networkManager = this.#frameManager.networkManager; - const idlePromise = createDeferredPromise(); + const idleDeferred = createDeferred(); let abortRejectCallback: (error: Error) => void; const abortPromise = new Promise((_, reject) => { @@ -1027,7 +1024,7 @@ export class CDPPage extends Page { const evaluate = () => { idleTimer && clearTimeout(idleTimer); if (networkManager.numRequestsInProgress() === 0) { - idleTimer = setTimeout(idlePromise.resolve, idleTime); + idleTimer = setTimeout(idleDeferred.resolve, idleTime); } }; @@ -1055,7 +1052,7 @@ export class CDPPage extends Page { ]; await Promise.race([ - idlePromise.valueOrThrow(), + idleDeferred.valueOrThrow(), ...eventPromises, this.#sessionClosePromise(), ]).then( @@ -1579,7 +1576,7 @@ export class CDPPage extends Page { await connection.send('Target.closeTarget', { targetId: this.#target._targetId, }); - await this.#target._isClosedPromise.valueOrThrow(); + await this.#target._isClosedDeferred.valueOrThrow(); } } diff --git a/packages/puppeteer-core/src/common/Target.ts b/packages/puppeteer-core/src/common/Target.ts index 39613368..4089dfff 100644 --- a/packages/puppeteer-core/src/common/Target.ts +++ b/packages/puppeteer-core/src/common/Target.ts @@ -19,7 +19,7 @@ import {Protocol} from 'devtools-protocol'; import type {Browser} from '../api/Browser.js'; import type {BrowserContext} from '../api/BrowserContext.js'; import {Page, PageEmittedEvents} from '../api/Page.js'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {CDPSession} from './Connection.js'; import {CDPPage} from './Page.js'; @@ -55,11 +55,11 @@ export class Target { /** * @internal */ - _initializedPromise = createDeferredPromise(); + _initializedDeferred = createDeferred(); /** * @internal */ - _isClosedPromise = createDeferredPromise(); + _isClosedDeferred = createDeferred(); /** * @internal */ @@ -198,15 +198,15 @@ export class Target { * @internal */ protected _initialize(): void { - this._initializedPromise.resolve(InitializationStatus.SUCCESS); + this._initializedDeferred.resolve(InitializationStatus.SUCCESS); } /** * @internal */ protected _checkIfInitialized(): void { - if (!this._initializedPromise.resolved()) { - this._initializedPromise.resolve(InitializationStatus.SUCCESS); + if (!this._initializedDeferred.resolved()) { + this._initializedDeferred.resolve(InitializationStatus.SUCCESS); } } @@ -248,7 +248,7 @@ export class PageTarget extends Target { } protected override _initialize(): void { - this._initializedPromise + this._initializedDeferred .valueOrThrow() .then(async result => { if (result === InitializationStatus.ABORTED) { @@ -294,11 +294,11 @@ export class PageTarget extends Target { } override _checkIfInitialized(): void { - if (this._initializedPromise.resolved()) { + if (this._initializedDeferred.resolved()) { return; } if (this._getTargetInfo().url !== '') { - this._initializedPromise.resolve(InitializationStatus.SUCCESS); + this._initializedDeferred.resolve(InitializationStatus.SUCCESS); } } } diff --git a/packages/puppeteer-core/src/common/WaitTask.ts b/packages/puppeteer-core/src/common/WaitTask.ts index cabeadb5..18c5617f 100644 --- a/packages/puppeteer-core/src/common/WaitTask.ts +++ b/packages/puppeteer-core/src/common/WaitTask.ts @@ -17,7 +17,7 @@ import {ElementHandle} from '../api/ElementHandle.js'; import {JSHandle} from '../api/JSHandle.js'; import type {Poller} from '../injected/Poller.js'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {isErrorLike} from '../util/ErrorLike.js'; import {stringifyFunction} from '../util/Function.js'; @@ -49,7 +49,7 @@ export class WaitTask { #timeout?: NodeJS.Timeout; - #result = createDeferredPromise>(); + #result = createDeferred>(); #poller?: JSHandle>; #signal?: AbortSignal; diff --git a/packages/puppeteer-core/src/common/WebWorker.ts b/packages/puppeteer-core/src/common/WebWorker.ts index beab09e3..8b08233b 100644 --- a/packages/puppeteer-core/src/common/WebWorker.ts +++ b/packages/puppeteer-core/src/common/WebWorker.ts @@ -15,7 +15,7 @@ */ import {Protocol} from 'devtools-protocol'; -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {CDPSession} from './Connection.js'; import {ConsoleMessageType} from './ConsoleMessage.js'; @@ -68,7 +68,7 @@ export type ExceptionThrownCallback = ( * @public */ export class WebWorker extends EventEmitter { - #executionContext = createDeferredPromise(); + #executionContext = createDeferred(); #client: CDPSession; #url: string; diff --git a/packages/puppeteer-core/src/injected/Poller.ts b/packages/puppeteer-core/src/injected/Poller.ts index 685f3eee..a175e3f6 100644 --- a/packages/puppeteer-core/src/injected/Poller.ts +++ b/packages/puppeteer-core/src/injected/Poller.ts @@ -15,10 +15,7 @@ */ import {assert} from '../util/assert.js'; -import { - createDeferredPromise, - DeferredPromise, -} from '../util/DeferredPromise.js'; +import {createDeferred, Deferred} from '../util/Deferred.js'; /** * @internal @@ -38,17 +35,17 @@ export class MutationPoller implements Poller { #root: Node; #observer?: MutationObserver; - #promise?: DeferredPromise; + #deferred?: Deferred; constructor(fn: () => Promise, root: Node) { this.#fn = fn; this.#root = root; } async start(): Promise { - const promise = (this.#promise = createDeferredPromise()); + const deferred = (this.#deferred = createDeferred()); const result = await this.#fn(); if (result) { - promise.resolve(result); + deferred.resolve(result); return; } @@ -57,7 +54,7 @@ export class MutationPoller implements Poller { if (!result) { return; } - promise.resolve(result); + deferred.resolve(result); await this.stop(); }); this.#observer.observe(this.#root, { @@ -68,9 +65,9 @@ export class MutationPoller implements Poller { } async stop(): Promise { - assert(this.#promise, 'Polling never started.'); - if (!this.#promise.finished()) { - this.#promise.reject(new Error('Polling stopped')); + assert(this.#deferred, 'Polling never started.'); + if (!this.#deferred.finished()) { + this.#deferred.reject(new Error('Polling stopped')); } if (this.#observer) { this.#observer.disconnect(); @@ -79,8 +76,8 @@ export class MutationPoller implements Poller { } result(): Promise { - assert(this.#promise, 'Polling never started.'); - return this.#promise.valueOrThrow(); + assert(this.#deferred, 'Polling never started.'); + return this.#deferred.valueOrThrow(); } } @@ -89,21 +86,21 @@ export class MutationPoller implements Poller { */ export class RAFPoller implements Poller { #fn: () => Promise; - #promise?: DeferredPromise; + #deferred?: Deferred; constructor(fn: () => Promise) { this.#fn = fn; } async start(): Promise { - const promise = (this.#promise = createDeferredPromise()); + const deferred = (this.#deferred = createDeferred()); const result = await this.#fn(); if (result) { - promise.resolve(result); + deferred.resolve(result); return; } const poll = async () => { - if (promise.finished()) { + if (deferred.finished()) { return; } const result = await this.#fn(); @@ -111,22 +108,22 @@ export class RAFPoller implements Poller { window.requestAnimationFrame(poll); return; } - promise.resolve(result); + deferred.resolve(result); await this.stop(); }; window.requestAnimationFrame(poll); } async stop(): Promise { - assert(this.#promise, 'Polling never started.'); - if (!this.#promise.finished()) { - this.#promise.reject(new Error('Polling stopped')); + assert(this.#deferred, 'Polling never started.'); + if (!this.#deferred.finished()) { + this.#deferred.reject(new Error('Polling stopped')); } } result(): Promise { - assert(this.#promise, 'Polling never started.'); - return this.#promise.valueOrThrow(); + assert(this.#deferred, 'Polling never started.'); + return this.#deferred.valueOrThrow(); } } @@ -139,17 +136,17 @@ export class IntervalPoller implements Poller { #ms: number; #interval?: NodeJS.Timer; - #promise?: DeferredPromise; + #deferred?: Deferred; constructor(fn: () => Promise, ms: number) { this.#fn = fn; this.#ms = ms; } async start(): Promise { - const promise = (this.#promise = createDeferredPromise()); + const deferred = (this.#deferred = createDeferred()); const result = await this.#fn(); if (result) { - promise.resolve(result); + deferred.resolve(result); return; } @@ -158,15 +155,15 @@ export class IntervalPoller implements Poller { if (!result) { return; } - promise.resolve(result); + deferred.resolve(result); await this.stop(); }, this.#ms); } async stop(): Promise { - assert(this.#promise, 'Polling never started.'); - if (!this.#promise.finished()) { - this.#promise.reject(new Error('Polling stopped')); + assert(this.#deferred, 'Polling never started.'); + if (!this.#deferred.finished()) { + this.#deferred.reject(new Error('Polling stopped')); } if (this.#interval) { clearInterval(this.#interval); @@ -175,7 +172,7 @@ export class IntervalPoller implements Poller { } result(): Promise { - assert(this.#promise, 'Polling never started.'); - return this.#promise.valueOrThrow(); + assert(this.#deferred, 'Polling never started.'); + return this.#deferred.valueOrThrow(); } } diff --git a/packages/puppeteer-core/src/injected/injected.ts b/packages/puppeteer-core/src/injected/injected.ts index 0f6aac78..e3107ebd 100644 --- a/packages/puppeteer-core/src/injected/injected.ts +++ b/packages/puppeteer-core/src/injected/injected.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {createDeferredPromise} from '../util/DeferredPromise.js'; +import {createDeferred} from '../util/Deferred.js'; import {createFunction} from '../util/Function.js'; import * as ARIAQuerySelector from './ARIAQuerySelector.js'; @@ -41,7 +41,7 @@ const PuppeteerUtil = Object.freeze({ ...TextQuerySelector, ...util, ...XPathQuerySelector, - createDeferredPromise, + createDeferred, createFunction, createTextContent, IntervalPoller, diff --git a/packages/puppeteer-core/src/util/DebuggableDeferredPromise.ts b/packages/puppeteer-core/src/util/DebuggableDeferred.ts similarity index 59% rename from packages/puppeteer-core/src/util/DebuggableDeferredPromise.ts rename to packages/puppeteer-core/src/util/DebuggableDeferred.ts index 0632fd5e..e35cb6ee 100644 --- a/packages/puppeteer-core/src/util/DebuggableDeferredPromise.ts +++ b/packages/puppeteer-core/src/util/DebuggableDeferred.ts @@ -1,6 +1,6 @@ import {DEFERRED_PROMISE_DEBUG_TIMEOUT} from '../environment.js'; -import {DeferredPromise, createDeferredPromise} from './DeferredPromise.js'; +import {Deferred, createDeferred} from './Deferred.js'; /** * Creates and returns a deferred promise using DEFERRED_PROMISE_DEBUG_TIMEOUT @@ -8,14 +8,12 @@ import {DeferredPromise, createDeferredPromise} from './DeferredPromise.js'; * * @internal */ -export function createDebuggableDeferredPromise( - message: string -): DeferredPromise { +export function createDebuggableDeferred(message: string): Deferred { if (DEFERRED_PROMISE_DEBUG_TIMEOUT > 0) { - return createDeferredPromise({ + return createDeferred({ message, timeout: DEFERRED_PROMISE_DEBUG_TIMEOUT, }); } - return createDeferredPromise(); + return createDeferred(); } diff --git a/packages/puppeteer-core/src/util/DeferredPromise.ts b/packages/puppeteer-core/src/util/Deferred.ts similarity index 90% rename from packages/puppeteer-core/src/util/DeferredPromise.ts rename to packages/puppeteer-core/src/util/Deferred.ts index 4f8f2ca7..6a27a512 100644 --- a/packages/puppeteer-core/src/util/DeferredPromise.ts +++ b/packages/puppeteer-core/src/util/Deferred.ts @@ -3,7 +3,7 @@ import {TimeoutError} from '../common/Errors.js'; /** * @internal */ -export interface DeferredPromise { +export interface Deferred { finished: () => boolean; resolved: () => boolean; resolve: (value: T) => void; @@ -15,7 +15,7 @@ export interface DeferredPromise { /** * @internal */ -export interface DeferredPromiseOptions { +export interface DeferredOptions { message: string; timeout: number; } @@ -29,9 +29,7 @@ export interface DeferredPromiseOptions { * * @internal */ -export function createDeferredPromise( - opts?: DeferredPromiseOptions -): DeferredPromise { +export function createDeferred(opts?: DeferredOptions): Deferred { let isResolved = false; let isRejected = false; let _value: T | Error | undefined; diff --git a/packages/puppeteer-core/src/util/util.ts b/packages/puppeteer-core/src/util/util.ts index d3160757..a4ad8c75 100644 --- a/packages/puppeteer-core/src/util/util.ts +++ b/packages/puppeteer-core/src/util/util.ts @@ -15,7 +15,7 @@ */ export * from './assert.js'; -export * from './DebuggableDeferredPromise.js'; -export * from './DeferredPromise.js'; +export * from './DebuggableDeferred.js'; +export * from './Deferred.js'; export * from './ErrorLike.js'; export * from './AsyncIterableUtil.js'; diff --git a/test/src/DeferredPromise.spec.ts b/test/src/Deferred.spec.ts similarity index 86% rename from test/src/DeferredPromise.spec.ts rename to test/src/Deferred.spec.ts index aef93b9f..e991a443 100644 --- a/test/src/DeferredPromise.spec.ts +++ b/test/src/Deferred.spec.ts @@ -16,9 +16,9 @@ import expect from 'expect'; import { - DeferredPromise, - createDeferredPromise, -} from 'puppeteer-core/internal/util/DeferredPromise.js'; + Deferred, + createDeferred, +} from 'puppeteer-core/internal/util/Deferred.js'; describe('DeferredPromise', function () { it('should catch errors', async () => { @@ -29,8 +29,8 @@ describe('DeferredPromise', function () { }); } // Async function that fails. - function fails(): DeferredPromise { - const deferred = createDeferredPromise(); + function fails(): Deferred { + const deferred = createDeferred(); setTimeout(() => { deferred.reject(new Error('test')); }, 25);