-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathWaitForHelper.ts
More file actions
194 lines (173 loc) · 5.17 KB
/
WaitForHelper.ts
File metadata and controls
194 lines (173 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {logger} from './logger.js';
import type {Page, Protocol, CdpPage} from './third_party/index.js';
import type {PredefinedNetworkConditions} from './third_party/index.js';
export class WaitForHelper {
#abortController = new AbortController();
#page: CdpPage;
#stableDomTimeout: number;
#stableDomFor: number;
#expectNavigationIn: number;
#navigationTimeout: number;
constructor(
page: Page,
cpuTimeoutMultiplier: number,
networkTimeoutMultiplier: number,
) {
this.#stableDomTimeout = 3000 * cpuTimeoutMultiplier;
this.#stableDomFor = 100 * cpuTimeoutMultiplier;
this.#expectNavigationIn = 100 * cpuTimeoutMultiplier;
this.#navigationTimeout = 3000 * networkTimeoutMultiplier;
this.#page = page as unknown as CdpPage;
}
/**
* A wrapper that executes a action and waits for
* a potential navigation, after which it waits
* for the DOM to be stable before returning.
*/
async waitForStableDom(): Promise<void> {
const stableDomObserver = await this.#page.evaluateHandle(timeout => {
let timeoutId: ReturnType<typeof setTimeout>;
function callback() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
domObserver.resolver.resolve();
domObserver.observer.disconnect();
}, timeout);
}
const domObserver = {
resolver: Promise.withResolvers<void>(),
observer: new MutationObserver(callback),
};
// It's possible that the DOM is not gonna change so we
// need to start the timeout initially.
callback();
domObserver.observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
});
return domObserver;
}, this.#stableDomFor);
this.#abortController.signal.addEventListener('abort', async () => {
try {
await stableDomObserver.evaluate(observer => {
observer.observer.disconnect();
observer.resolver.resolve();
});
await stableDomObserver.dispose();
} catch {
// Ignored cleanup errors
}
});
return Promise.race([
stableDomObserver.evaluate(async observer => {
return await observer.resolver.promise;
}),
this.timeout(this.#stableDomTimeout).then(() => {
throw new Error('Timeout');
}),
]);
}
async waitForNavigationStarted() {
// Currently Puppeteer does not have API
// For when a navigation is about to start
const navigationStartedPromise = new Promise<boolean>(resolve => {
const listener = (event: Protocol.Page.FrameStartedNavigatingEvent) => {
if (
[
'historySameDocument',
'historyDifferentDocument',
'sameDocument',
].includes(event.navigationType)
) {
resolve(false);
return;
}
resolve(true);
};
this.#page._client().on('Page.frameStartedNavigating', listener);
this.#abortController.signal.addEventListener('abort', () => {
resolve(false);
this.#page._client().off('Page.frameStartedNavigating', listener);
});
});
return await Promise.race([
navigationStartedPromise,
this.timeout(this.#expectNavigationIn).then(() => false),
]);
}
timeout(time: number): Promise<void> {
return new Promise<void>(res => {
const id = setTimeout(res, time);
this.#abortController.signal.addEventListener('abort', () => {
res();
clearTimeout(id);
});
});
}
async waitForEventsAfterAction(
action: () => Promise<unknown>,
options?: {timeout?: number},
): Promise<WaitForEventsResult> {
let navigated = false;
const navigationFinished = this.waitForNavigationStarted()
.then(navigationStated => {
if (navigationStated) {
navigated = true;
return this.#page.waitForNavigation({
timeout: options?.timeout ?? this.#navigationTimeout,
signal: this.#abortController.signal,
});
}
return;
})
.catch(error => logger(error));
try {
await action();
} catch (error) {
// Clear up pending promises
this.#abortController.abort();
throw error;
}
try {
await navigationFinished;
// Wait for stable dom after navigation so we execute in
// the correct context
await this.waitForStableDom();
} catch (error) {
logger(error);
} finally {
this.#abortController.abort();
}
return {navigated};
}
}
export interface WaitForEventsResult {
/**
* Whether a cross-document navigation started and finished during the
* action. Same-document (history API) navigations are not reported.
*/
navigated: boolean;
}
export function getNetworkMultiplierFromString(
condition: string | null,
): number {
const puppeteerCondition =
condition as keyof typeof PredefinedNetworkConditions;
switch (puppeteerCondition) {
case 'Fast 4G':
return 1;
case 'Slow 4G':
return 2.5;
case 'Fast 3G':
return 5;
case 'Slow 3G':
return 10;
}
return 1;
}