Realm.ts (2825B)
1 /** 2 * @license 3 * Copyright 2023 Google Inc. 4 * SPDX-License-Identifier: Apache-2.0 5 */ 6 7 import type {TimeoutSettings} from '../common/TimeoutSettings.js'; 8 import type { 9 EvaluateFunc, 10 HandleFor, 11 InnerLazyParams, 12 } from '../common/types.js'; 13 import {TaskManager, WaitTask} from '../common/WaitTask.js'; 14 import {disposeSymbol} from '../util/disposable.js'; 15 16 import type {ElementHandle} from './ElementHandle.js'; 17 import type {Environment} from './Environment.js'; 18 import type {JSHandle} from './JSHandle.js'; 19 20 /** 21 * @internal 22 */ 23 export abstract class Realm implements Disposable { 24 protected readonly timeoutSettings: TimeoutSettings; 25 readonly taskManager = new TaskManager(); 26 27 constructor(timeoutSettings: TimeoutSettings) { 28 this.timeoutSettings = timeoutSettings; 29 } 30 31 abstract get environment(): Environment; 32 33 abstract adoptHandle<T extends JSHandle<Node>>(handle: T): Promise<T>; 34 abstract transferHandle<T extends JSHandle<Node>>(handle: T): Promise<T>; 35 abstract evaluateHandle< 36 Params extends unknown[], 37 Func extends EvaluateFunc<Params> = EvaluateFunc<Params>, 38 >( 39 pageFunction: Func | string, 40 ...args: Params 41 ): Promise<HandleFor<Awaited<ReturnType<Func>>>>; 42 abstract evaluate< 43 Params extends unknown[], 44 Func extends EvaluateFunc<Params> = EvaluateFunc<Params>, 45 >( 46 pageFunction: Func | string, 47 ...args: Params 48 ): Promise<Awaited<ReturnType<Func>>>; 49 50 async waitForFunction< 51 Params extends unknown[], 52 Func extends EvaluateFunc<InnerLazyParams<Params>> = EvaluateFunc< 53 InnerLazyParams<Params> 54 >, 55 >( 56 pageFunction: Func | string, 57 options: { 58 polling?: 'raf' | 'mutation' | number; 59 timeout?: number; 60 root?: ElementHandle<Node>; 61 signal?: AbortSignal; 62 } = {}, 63 ...args: Params 64 ): Promise<HandleFor<Awaited<ReturnType<Func>>>> { 65 const { 66 polling = 'raf', 67 timeout = this.timeoutSettings.timeout(), 68 root, 69 signal, 70 } = options; 71 if (typeof polling === 'number' && polling < 0) { 72 throw new Error('Cannot poll with non-positive interval'); 73 } 74 const waitTask = new WaitTask( 75 this, 76 { 77 polling, 78 root, 79 timeout, 80 signal, 81 }, 82 pageFunction as unknown as 83 | ((...args: unknown[]) => Promise<Awaited<ReturnType<Func>>>) 84 | string, 85 ...args, 86 ); 87 return await waitTask.result; 88 } 89 90 abstract adoptBackendNode(backendNodeId?: number): Promise<JSHandle<Node>>; 91 92 get disposed(): boolean { 93 return this.#disposed; 94 } 95 96 #disposed = false; 97 /** @internal */ 98 dispose(): void { 99 this.#disposed = true; 100 this.taskManager.terminateAll( 101 new Error('waitForFunction failed: frame got detached.'), 102 ); 103 } 104 /** @internal */ 105 [disposeSymbol](): void { 106 this.dispose(); 107 } 108 }