({ value, status }: Props) => {
  const classes = classnames(
    'w-10 h-10 border-solid border-2 flex items-center justify-center mx-0.5 text-lg font-bold rounded dark:text-white',
    {
      'bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-600':
        !status,
      'border-black dark:border-slate-100': value && !status,
      'bg-slate-400 dark:bg-slate-700 text-white border-slate-400 dark:border-slate-700':
        status === 'absent',
      'bg-green-500 text-white border-green-500': status === 'correct',
      'bg-orange-500 dark:bg-orange-700 text-white border-orange-500 dark:border-orange-700':
        status === 'present',
      'cell-animation': !!value,
    }
  )

  return
{value}

}


type Props = {
  value?: string
  status?: CharStatus
}


export function RequestPopup(props: RequestPopupProps) {

    function handleDecline(){ props.handleOption(PopupPermission.Declined) }
    function handleProceed(){ props.handleOption(PopupPermission.Proceed) }

    return (
            <Modal isOpen={props.isOpen} size={'lg'} onClose={handleDecline}>
                <ModalOverlay />
                <ModalContent>
                    <ModalHeader>Please click proceed to allow signing popup</ModalHeader>
                    <ModalCloseButton />
                    <ModalBody>
                        <HStack>
                            <Button onClick={handleDecline} style={{ margin: "" }}


function handleDecline(){ props.handleOption(PopupPermission.Declined) }


function handleProceed(){ props.handleOption(PopupPermission.Proceed) }


(PopupPermission): void => {}


export enum PopupPermission {
    Proceed=1,
    Declined=2,
    Undecided=3
}


export type RequestPopupProps = {
    isOpen: boolean
    handleOption(PopupPermission)
};


() => {
  const exporter = new Exporter({
    rootPath: path.resolve(__dirname, '.temp'),
  })
  beforeAll(async () => {
    setupJoplinConfig()
    await remove(exporter.config.rootPath)
    await mkdirp(exporter.config.rootPath)
  })
  it('测试 folder', async () => {
    const folderList = await exporter.listFolder()
    console.log('folderList: ', folderList)
    await exporter.writeFolder(folderList)
  })
  it('测试 notes', async () => {
    const folderList = await exporter.listFolder()
    const noteList = await exporter.listNote(folderList)
    console.log(
      'noteList: ',
      noteList.map((item) => item.filePath),
    )
    await exporter.writeNote(noteList)
  })
  it('测试 resource', async () => {
    const resourceList = await exporter.listResource()
    console.log('resourceList: ', resourceList)
    await exporter.writeResource(resourceList)
  })

  it('测试 tag', async () => {
    const { tagList, noteTagRelationList } = await exporter.tag()
    console.log('tagList: ', tagList, noteTagRelationList)
  })

  it('测试 export', async () => {
    await exporter.export()
  })
}


async () => {
    setupJoplinConfig()
    await remove(exporter.config.rootPath)
    await mkdirp(exporter.config.rootPath)
  }


async () => {
    const folderList = await exporter.listFolder()
    console.log('folderList: ', folderList)
    await exporter.writeFolder(folderList)
  }


async () => {
    const folderList = await exporter.listFolder()
    const noteList = await exporter.listNote(folderList)
    console.log(
      'noteList: ',
      noteList.map((item) => item.filePath),
    )
    await exporter.writeNote(noteList)
  }


(item) => item.filePath


async () => {
    const resourceList = await exporter.listResource()
    console.log('resourceList: ', resourceList)
    await exporter.writeResource(resourceList)
  }


async () => {
    const { tagList, noteTagRelationList } = await exporter.tag()
    console.log('tagList: ', tagList, noteTagRelationList)
  }


async () => {
    await exporter.export()
  }


(
	chat: Chat,
	overWriteInfos: string[],
	useOverWriteArray: boolean,
	c: string,
	infos: string[],
	custom: boolean
) => {
	let master = "";
	console.log(infos, useOverWriteArray, overWriteInfos);
	if (useOverWriteArray && overWriteInfos.length) {
		overWriteInfos.forEach((v, idx) => {
			if (chat.classes.length > 1 && !chat.classes.includes("BMTL21a")) {
				master +=
					v +
					"[" +
					c +
					"]" +
					(idx < overWriteInfos.length - 1 ? "\n----------\n" : "");
			} else {
				master += v + (idx < overWriteInfos.length - 1 ? "\n----------\n" : "");
			}
		});
		sendMessage(chat.chat, master);
	} else {
		if (infos.length) {
			infos.forEach((v, idx) => {
				if (chat.classes.length > 1 && !chat.classes.includes("BMTL21a")) {
					master +=
						v +
						"[" +
						c +
						"]" +
						(idx < infos.length - 1 ? "\n----------\n" : "");
				} else {
					master += v + (idx < infos.length - 1 ? "\n----------\n" : "");
				}
			});
			sendMessage(chat.chat, master);
		} else if (custom) {
			sendMessage(chat.chat, "no lessons, enjoy your free time");
		}
	}
}


(v, idx) => {
			if (chat.classes.length > 1 && !chat.classes.includes("BMTL21a")) {
				master +=
					v +
					"[" +
					c +
					"]" +
					(idx < overWriteInfos.length - 1 ? "\n----------\n" : "");
			} else {
				master += v + (idx < overWriteInfos.length - 1 ? "\n----------\n" : "");
			}
		}


(v, idx) => {
				if (chat.classes.length > 1 && !chat.classes.includes("BMTL21a")) {
					master +=
						v +
						"[" +
						c +
						"]" +
						(idx < infos.length - 1 ? "\n----------\n" : "");
				} else {
					master += v + (idx < infos.length - 1 ? "\n----------\n" : "");
				}
			}


function CardTestUser() {
  return (
    <Link href="/test-usuario">

Test para Usuarios

          Haz el test para usuarios, así podrás empezar a tener match con
          distintos proyectos, contesta con honestidad para asegurar un mejor
          resultado con respecto a tus gustos.

    </Link>
  )
}


async function emulateLocale(session: CRSession, locale: string) {
  try {
    await session.send('Emulation.setLocaleOverride', { locale });
  } catch (exception) {
    // All pages in the same renderer share locale. All such pages belong to the same
    // context and if locale is overridden for one of them its value is the same as
    // we are trying to set so it's not a problem.
    if (exception.message.includes('Another locale override is already in effect'))
      return;
    throw exception;
  }
}


async function emulateTimezone(session: CRSession, timezoneId: string) {
  try {
    await session.send('Emulation.setTimezoneOverride', { timezoneId: timezoneId });
  } catch (exception) {
    if (exception.message.includes('Timezone override is already in effect'))
      return;
    if (exception.message.includes('Invalid timezone'))
      throw new Error(`Invalid timezone ID: ${timezoneId}`);
    throw exception;
  }
}


() => this._page._didDisconnect()


async r => {
      await this._page.initOpener(this._opener);
      return r;
    }


async e => {
      await this._page.initOpener(this._opener);
      throw e;
    }


() => {
      this._initializedPage = this._page;
      this._reportAsNew();
      return this._page;
    }


e => {
      this._reportAsNew(e);
      return e;
    }


frameSession => {
      if (frameSession._isMainFrame())
        return cb(frameSession);
      return cb(frameSession).catch(e => {
        // Broadcasting a message to the closed iframe shoule be a noop.
        if (e.message && (e.message.includes('Target closed.') || e.message.includes('Session closed.')))
          return;
        throw e;
      });
    }


e => {
        // Broadcasting a message to the closed iframe shoule be a noop.
        if (e.message && (e.message.includes('Target closed.') || e.message.includes('Session closed.')))
          return;
        throw e;
      }


frame => frame._initBinding(binding)


frame => frame.evaluateExpression(binding.source, false, {}).catch(e => {})


e => {}


frame => frame._removeExposedBindings()


frame => frame._updateExtraHTTPHeaders(false)


frame => frame._updateGeolocation(false)


frame => frame._updateOffline(false)


frame => frame._updateHttpCredentials(false)


frame => frame._updateEmulateMedia(false)


frame => frame._updateRequestInterception()


frame => frame._updateFileChooserInterception(false)


frame => frame._evaluateOnNewDocument(source, world)


frame => frame._removeEvaluatesOnNewDocument()


([injected, node, files]) =>
      injected.setInputFiles(node, files)


e => {
      if (e instanceof Error && e.message.includes('Frame with the given id was not found.'))
        rewriteErrorMessage(e, 'Frame has been detached.');
      throw e;
    }


(e: Error) => {}


(f, r) => {
      this._firstNonInitialNavigationCommittedFulfill = f;
      this._firstNonInitialNavigationCommittedReject = r;
    }


() => {
      this._firstNonInitialNavigationCommittedReject(new Error('Page closed'));
    }


event => this._onLogEntryAdded(event)


event => this._onFileChooserOpened(event)


event => this._onFrameAttached(event.frameId, event.parentFrameId)


event => this._onFrameDetached(event.frameId, event.reason)


event => this._onFrameNavigated(event.frame, false)


event => this._onFrameRequestedNavigation(event)


event => this._onFrameStoppedLoading(event.frameId)


event => this._onDialog(event)


event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)


event => this._onBindingCalled(event)


event => this._onConsoleAPI(event)


exception => this._handleException(exception.exceptionDetails)


event => this._onExecutionContextCreated(event.context)


event => this._onExecutionContextDestroyed(event.executionContextId)


event => this._onExecutionContextsCleared()


event => this._onAttachedToTarget(event)


event => this._onDetachedFromTarget(event)


event => this._onTargetCrashed()


event => this._onScreencastFrame(event)


event => this._onWindowOpen(event)


p => {
        if (p instanceof Error)
          this._stopVideoRecording().catch(() => {});
      }


({ frameTree }) => {
        if (this._isMainFrame()) {
          this._handleFrameTree(frameTree);
          this._addRendererListeners();
        }
        const localFrames = this._isMainFrame() ? this._page.frames() : [ this._page._frameManager.frame(this._targetId)! ];
        for (const frame of localFrames) {
          // Note: frames might be removed before we send these.
          this._client._sendMayFail('Page.createIsolatedWorld', {
            frameId: frame._id,
            grantUniveralAccess: true,
            worldName: UTILITY_WORLD_NAME,
          });
          for (const binding of this._crPage._browserContext._pageBindings.values())
            frame.evaluateExpression(binding.source, false, undefined).catch(e => {});
          for (const source of this._crPage._browserContext.initScripts)
            frame.evaluateExpression(source, false, undefined, 'main').catch(e => {});
        }
        const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';
        if (isInitialEmptyPage) {
          // Ignore lifecycle events for the initial empty page. It is never the final page
          // hence we are going to get more lifecycle updates after the actual navigation has
          // started (even if the target url is about:blank).
          lifecycleEventsEnabled.catch(e => {}).then(() => {
            this._eventListeners.push(eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
          });
        } else {
          this._firstNonInitialNavigationCommittedFulfill();
          this._eventListeners.push(eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
        }
      }


() => {
            this._eventListeners.push(eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
          }


event => this._onLifecycleEvent(event)


() => {
        this._client._sendMayFail('Target.detachFromTarget', { sessionId: event.sessionId });
      }


async event => {
      worker._createExecutionContext(new CRExecutionContext(session, event.context));
    }


event => {
      const args = event.args.map(o => worker._existingExecutionContext!.createHandle(o));
      this._page._addConsoleMessage(event.type, args, toConsoleMessageLocation(event.stackTrace));
    }


o => worker._existingExecutionContext!.createHandle(o)


exception => this._page.emit(Page.Events.PageError, exceptionToError(exception.exceptionDetails))


e => null


() => {
      // Child was not swapped in - that means frameAttached did not happen and
      // this is remote detach rather than remote -> local swap.
      if (!childFrameSession._swappedIn)
        this._page._frameManager.frameDetached(event.targetId!);
      childFrameSession.dispose();
    }


arg => context.createHandle(arg)


name => this._client.send('Runtime.removeBinding', { name })


async (accept: boolean, promptText?: string) => {
          await this._client.send('Page.handleJavaScriptDialog', { accept, promptText });
        }


arg => releaseObject(this._client, arg.objectId!)


() => {
      this._client.send('Page.screencastFrameAck', { sessionId: payload.sessionId }).catch(() => {});
    }


() => this._stopVideoRecording().catch(() => {})


f => this._client.once('Page.screencastFrame', f)


() => {
      this._crPage._browserContext._browser._videoStarted(this._crPage._browserContext, screencastId, options.outputFile, this._crPage.pageOrError());
    }


identifier => this._client.send('Page.removeScriptToEvaluateOnNewDocument', { identifier })


node => {
      const doc = node as Document;
      if (doc.documentElement && doc.documentElement.ownerDocument === doc)
        return doc.documentElement;
      return node.ownerDocument ? node.ownerDocument.documentElement : null;
    }


() => 'done' as const


e => {
      if (e instanceof Error && e.message.includes('Node does not have a layout object'))
        return 'error:notvisible';
      if (e instanceof Error && e.message.includes('Node is detached from document'))
        return 'error:notconnected';
      throw e;
    }


quad => [
      { x: quad[0] + position.x, y: quad[1] + position.y },
      { x: quad[2] + position.x, y: quad[3] + position.y },
      { x: quad[4] + position.x, y: quad[5] + position.y },
      { x: quad[6] + position.x, y: quad[7] + position.y }
    ]


export type WindowBounds = { top?: number, left?: number, width?: number, height?: number };


static mainFrameSession(page: Page): FrameSession {
    const crPage = page._delegate as CRPage;
    return crPage._mainFrameSession;
  }


potentiallyUninitializedPage(): Page {
    return this._page;
  }


private _reportAsNew(error?: Error) {
    if (this._isBackgroundPage) {
      if (!error)
        this._browserContext.emit(CRBrowserContext.CREvents.BackgroundPage, this._page);
    } else {
      this._page.reportAsNew(error);
    }
  }


private async _forAllFrameSessions(cb: (frame: FrameSession) => Promise<any>) {
    const frameSessions = Array.from(this._sessions.values());
    await Promise.all(frameSessions.map(frameSession => {
      if (frameSession._isMainFrame())
        return cb(frameSession);
      return cb(frameSession).catch(e => {
        // Broadcasting a message to the closed iframe shoule be a noop.
        if (e.message && (e.message.includes('Target closed.') || e.message.includes('Session closed.')))
          return;
        throw e;
      });
    }));
  }


_sessionForFrame(frame: frames.Frame): FrameSession {
    // Frame id equals target id.
    while (!this._sessions.has(frame._id)) {
      const parent = frame.parentFrame();
      if (!parent)
        throw new Error(`Frame has been detached.`);
      frame = parent;
    }
    return this._sessions.get(frame._id)!;
  }


private _sessionForHandle(handle: dom.ElementHandle): FrameSession {
    const frame = handle._context.frame;
    return this._sessionForFrame(frame);
  }


willBeginDownload() {
    this._mainFrameSession._willBeginDownload();
  }


async pageOrError(): Promise<Page | Error> {
    return this._pagePromise;
  }


didClose() {
    for (const session of this._sessions.values())
      session.dispose();
    this._page._didClose();
  }


async navigateFrame(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> {
    return this._sessionForFrame(frame)._navigate(frame, url, referrer);
  }


async exposeBinding(binding: PageBinding) {
    await this._forAllFrameSessions(frame => frame._initBinding(binding));
    await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(binding.source, false, {}).catch(e => {})));
  }


async removeExposedBindings() {
    await this._forAllFrameSessions(frame => frame._removeExposedBindings());
  }


async updateExtraHTTPHeaders(): Promise<void> {
    await this._forAllFrameSessions(frame => frame._updateExtraHTTPHeaders(false));
  }


async updateGeolocation(): Promise<void> {
    await this._forAllFrameSessions(frame => frame._updateGeolocation(false));
  }


async updateOffline(): Promise<void> {
    await this._forAllFrameSessions(frame => frame._updateOffline(false));
  }


async updateHttpCredentials(): Promise<void> {
    await this._forAllFrameSessions(frame => frame._updateHttpCredentials(false));
  }


async setEmulatedSize(emulatedSize: types.EmulatedSize): Promise<void> {
    assert(this._page._state.emulatedSize === emulatedSize);
    await this._mainFrameSession._updateViewport();
  }


async bringToFront(): Promise<void> {
    await this._mainFrameSession._client.send('Page.bringToFront');
  }


async updateEmulateMedia(): Promise<void> {
    await this._forAllFrameSessions(frame => frame._updateEmulateMedia(false));
  }


async updateRequestInterception(): Promise<void> {
    await this._forAllFrameSessions(frame => frame._updateRequestInterception());
  }


async updateFileChooserInterception() {
    await this._forAllFrameSessions(frame => frame._updateFileChooserInterception(false));
  }


async reload(): Promise<void> {
    await this._mainFrameSession._client.send('Page.reload');
  }


private async _go(delta: number): Promise<boolean> {
    const history = await this._mainFrameSession._client.send('Page.getNavigationHistory');
    const entry = history.entries[history.currentIndex + delta];
    if (!entry)
      return false;
    await this._mainFrameSession._client.send('Page.navigateToHistoryEntry', { entryId: entry.id });
    return true;
  }


goBack(): Promise<boolean> {
    return this._go(-1);
  }


goForward(): Promise<boolean> {
    return this._go(+1);
  }


async addInitScript(source: string, world: types.World = 'main'): Promise<void> {
    await this._forAllFrameSessions(frame => frame._evaluateOnNewDocument(source, world));
  }


async removeInitScripts() {
    await this._forAllFrameSessions(frame => frame._removeEvaluatesOnNewDocument());
  }


async closePage(runBeforeUnload: boolean): Promise<void> {
    if (runBeforeUnload)
      await this._mainFrameSession._client.send('Page.close');
    else
      await this._browserContext._browser._closePage(this);
  }


async setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void> {
    await this._mainFrameSession._client.send('Emulation.setDefaultBackgroundColorOverride', { color });
  }


async takeScreenshot(progress: Progress, format: 'png' | 'jpeg', documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined, fitsViewport: boolean, scale: 'css' | 'device'): Promise<Buffer> {
    const { visualViewport } = await this._mainFrameSession._client.send('Page.getLayoutMetrics');
    if (!documentRect) {
      documentRect = {
        x: visualViewport.pageX + viewportRect!.x,
        y: visualViewport.pageY + viewportRect!.y,
        ...helper.enclosingIntSize({
          width: viewportRect!.width / visualViewport.scale,
          height: viewportRect!.height / visualViewport.scale,
        })
      };
    }
    // When taking screenshots with documentRect (based on the page content, not viewport),
    // ignore current page scale.
    const clip = { ...documentRect, scale: viewportRect ? visualViewport.scale : 1 };
    if (scale === 'css') {
      const deviceScaleFactor = this._browserContext._options.deviceScaleFactor || 1;
      clip.scale /= deviceScaleFactor;
    }
    progress.throwIfAborted();
    const result = await this._mainFrameSession._client.send('Page.captureScreenshot', { format, quality, clip, captureBeyondViewport: !fitsViewport });
    return Buffer.from(result.data, 'base64');
  }


async getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> {
    return this._sessionForHandle(handle)._getContentFrame(handle);
  }


async getOwnerFrame(handle: dom.ElementHandle): Promise<string | null> {
    return this._sessionForHandle(handle)._getOwnerFrame(handle);
  }


isElementHandle(remoteObject: any): boolean {
    return (remoteObject as Protocol.Runtime.RemoteObject).subtype === 'node';
  }


async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
    return this._sessionForHandle(handle)._getBoundingBox(handle);
  }


async scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<'error:notvisible' | 'error:notconnected' | 'done'> {
    return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);
  }


async setScreencastOptions(options: { width: number, height: number, quality: number } | null): Promise<void> {
    if (options) {
      await this._mainFrameSession._startScreencast(this, {
        format: 'jpeg',
        quality: options.quality,
        maxWidth: options.width,
        maxHeight: options.height
      });
    } else {
      await this._mainFrameSession._stopScreencast(this);
    }
  }


rafCountForStablePosition(): number {
    return 1;
  }


async getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null> {
    return this._sessionForHandle(handle)._getContentQuads(handle);
  }


async setInputFiles(handle: dom.ElementHandle<HTMLInputElement>, files: types.FilePayload[]): Promise<void> {
    await handle.evaluateInUtility(([injected, node, files]) =>
      injected.setInputFiles(node, files), files);
  }


async setInputFilePaths(handle: dom.ElementHandle<HTMLInputElement>, files: string[]): Promise<void> {
    const frame = await handle.ownerFrame();
    if (!frame)
      throw new Error('Cannot set input files to detached input element');
    const parentSession = this._sessionForFrame(frame);
    await parentSession._client.send('DOM.setFileInputFiles', {
      objectId: handle._objectId,
      files
    });
  }


async adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>> {
    return this._sessionForHandle(handle)._adoptElementHandle<T>(handle, to);
  }


async getAccessibilityTree(needle?: dom.ElementHandle) {
    return getAccessibilityTree(this._mainFrameSession._client, needle);
  }


async inputActionEpilogue(): Promise<void> {
    await this._mainFrameSession._client.send('Page.enable').catch(e => {});
  }


async pdf(options: channels.PagePdfParams): Promise<Buffer> {
    return this._pdf.generate(options);
  }


coverage(): CRCoverage {
    return this._coverage;
  }


async getFrameElement(frame: frames.Frame): Promise<dom.ElementHandle> {
    let parent = frame.parentFrame();
    if (!parent)
      throw new Error('Frame has been detached.');
    const parentSession = this._sessionForFrame(parent);
    const { backendNodeId } = await parentSession._client.send('DOM.getFrameOwner', { frameId: frame._id }).catch(e => {
      if (e instanceof Error && e.message.includes('Frame with the given id was not found.'))
        rewriteErrorMessage(e, 'Frame has been detached.');
      throw e;
    });
    parent = frame.parentFrame();
    if (!parent)
      throw new Error('Frame has been detached.');
    return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());
  }


_isMainFrame(): boolean {
    return this._targetId === this._crPage._targetId;
  }


private _addRendererListeners() {
    this._eventListeners.push(...[
      eventsHelper.addEventListener(this._client, 'Log.entryAdded', event => this._onLogEntryAdded(event)),
      eventsHelper.addEventListener(this._client, 'Page.fileChooserOpened', event => this._onFileChooserOpened(event)),
      eventsHelper.addEventListener(this._client, 'Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId)),
      eventsHelper.addEventListener(this._client, 'Page.frameDetached', event => this._onFrameDetached(event.frameId, event.reason)),
      eventsHelper.addEventListener(this._client, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame, false)),
      eventsHelper.addEventListener(this._client, 'Page.frameRequestedNavigation', event => this._onFrameRequestedNavigation(event)),
      eventsHelper.addEventListener(this._client, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)),
      eventsHelper.addEventListener(this._client, 'Page.javascriptDialogOpening', event => this._onDialog(event)),
      eventsHelper.addEventListener(this._client, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),
      eventsHelper.addEventListener(this._client, 'Runtime.bindingCalled', event => this._onBindingCalled(event)),
      eventsHelper.addEventListener(this._client, 'Runtime.consoleAPICalled', event => this._onConsoleAPI(event)),
      eventsHelper.addEventListener(this._client, 'Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails)),
      eventsHelper.addEventListener(this._client, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)),
      eventsHelper.addEventListener(this._client, 'Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId)),
      eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', event => this._onExecutionContextsCleared()),
      eventsHelper.addEventListener(this._client, 'Target.attachedToTarget', event => this._onAttachedToTarget(event)),
      eventsHelper.addEventListener(this._client, 'Target.detachedFromTarget', event => this._onDetachedFromTarget(event)),
    ]);
  }


private _addBrowserListeners() {
    this._eventListeners.push(...[
      eventsHelper.addEventListener(this._client, 'Inspector.targetCrashed', event => this._onTargetCrashed()),
      eventsHelper.addEventListener(this._client, 'Page.screencastFrame', event => this._onScreencastFrame(event)),
      eventsHelper.addEventListener(this._client, 'Page.windowOpen', event => this._onWindowOpen(event)),
    ]);
  }


async _initialize(hasUIWindow: boolean) {
    const isSettingStorageState = this._page._browserContext.isSettingStorageState();
    if (!isSettingStorageState && hasUIWindow &&
      !this._crPage._browserContext._browser.isClank() &&
      !this._crPage._browserContext._options.noDefaultViewport) {
      const { windowId } = await this._client.send('Browser.getWindowForTarget');
      this._windowId = windowId;
    }

    let screencastOptions: types.PageScreencastOptions | undefined;
    if (!isSettingStorageState && this._isMainFrame() && this._crPage._browserContext._options.recordVideo && hasUIWindow) {
      const screencastId = createGuid();
      const outputFile = path.join(this._crPage._browserContext._options.recordVideo.dir, screencastId + '.webm');
      screencastOptions = {
        // validateBrowserContextOptions ensures correct video size.
        ...this._crPage._browserContext._options.recordVideo.size!,
        outputFile,
      };
      await this._crPage._browserContext._ensureVideosPath();
      // Note: it is important to start video recorder before sending Page.startScreencast,
      // and it is equally important to send Page.startScreencast before sending Runtime.runIfWaitingForDebugger.
      await this._createVideoRecorder(screencastId, screencastOptions);
      this._crPage.pageOrError().then(p => {
        if (p instanceof Error)
          this._stopVideoRecording().catch(() => {});
      });
    }

    let lifecycleEventsEnabled: Promise<any>;
    if (!this._isMainFrame())
      this._addRendererListeners();
    this._addBrowserListeners();
    const promises: Promise<any>[] = [
      this._client.send('Page.enable'),
      this._client.send('Page.getFrameTree').then(({ frameTree }) => {
        if (this._isMainFrame()) {
          this._handleFrameTree(frameTree);
          this._addRendererListeners();
        }
        const localFrames = this._isMainFrame() ? this._page.frames() : [ this._page._frameManager.frame(this._targetId)! ];
        for (const frame of localFrames) {
          // Note: frames might be removed before we send these.
          this._client._sendMayFail('Page.createIsolatedWorld', {
            frameId: frame._id,
            grantUniveralAccess: true,
            worldName: UTILITY_WORLD_NAME,
          });
          for (const binding of this._crPage._browserContext._pageBindings.values())
            frame.evaluateExpression(binding.source, false, undefined).catch(e => {});
          for (const source of this._crPage._browserContext.initScripts)
            frame.evaluateExpression(source, false, undefined, 'main').catch(e => {});
        }
        const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ':';
        if (isInitialEmptyPage) {
          // Ignore lifecycle events for the initial empty page. It is never the final page
          // hence we are going to get more lifecycle updates after the actual navigation has
          // started (even if the target url is about:blank).
          lifecycleEventsEnabled.catch(e => {}).then(() => {
            this._eventListeners.push(eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
          });
        } else {
          this._firstNonInitialNavigationCommittedFulfill();
          this._eventListeners.push(eventsHelper.addEventListener(this._client, 'Page.lifecycleEvent', event => this._onLifecycleEvent(event)));
        }
      }),
      this._client.send('Log.enable', {}),
      lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', { enabled: true }),
      this._client.send('Runtime.enable', {}),
      this._client.send('Page.addScriptToEvaluateOnNewDocument', {
        source: '',
        worldName: UTILITY_WORLD_NAME,
      }),
      this._networkManager.initialize(),
      this._client.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }),
    ];
    if (!isSettingStorageState) {
      if (this._isMainFrame())
        promises.push(this._client.send('Emulation.setFocusEmulationEnabled', { enabled: true }));
      const options = this._crPage._browserContext._options;
      if (options.bypassCSP)
        promises.push(this._client.send('Page.setBypassCSP', { enabled: true }));
      if (options.ignoreHTTPSErrors)
        promises.push(this._client.send('Security.setIgnoreCertificateErrors', { ignore: true }));
      if (this._isMainFrame())
        promises.push(this._updateViewport());
      if (options.hasTouch)
        promises.push(this._client.send('Emulation.setTouchEmulationEnabled', { enabled: true }));
      if (options.javaScriptEnabled === false)
        promises.push(this._client.send('Emulation.setScriptExecutionDisabled', { value: true }));
      if (options.userAgent || options.locale)
        promises.push(this._client.send('Emulation.setUserAgentOverride', { userAgent: options.userAgent || '', acceptLanguage: options.locale }));
      if (options.locale)
        promises.push(emulateLocale(this._client, options.locale));
      if (options.timezoneId)
        promises.push(emulateTimezone(this._client, options.timezoneId));
      if (!this._crPage._browserContext._browser.options.headful)
        promises.push(this._setDefaultFontFamilies(this._client));
      promises.push(this._updateGeolocation(true));
      promises.push(this._updateExtraHTTPHeaders(true));
      promises.push(this._updateRequestInterception());
      promises.push(this._updateOffline(true));
      promises.push(this._updateHttpCredentials(true));
      promises.push(this._updateEmulateMedia(true));
      promises.push(this._updateFileChooserInterception(true));
      for (const binding of this._crPage._page.allBindings())
        promises.push(this._initBinding(binding));
      for (const source of this._crPage._browserContext.initScripts)
        promises.push(this._evaluateOnNewDocument(source, 'main'));
      for (const source of this._crPage._page.initScripts)
        promises.push(this._evaluateOnNewDocument(source, 'main'));
      if (screencastOptions)
        promises.push(this._startVideoRecording(screencastOptions));
    }
    promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));
    promises.push(this._firstNonInitialNavigationCommittedPromise);
    await Promise.all(promises);
  }


dispose() {
    for (const childSession of this._childSessions)
      childSession.dispose();
    if (this._parentSession)
      this._parentSession._childSessions.delete(this);
    eventsHelper.removeEventListeners(this._eventListeners);
    this._networkManager.dispose();
    this._crPage._sessions.delete(this._targetId);
  }


async _navigate(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> {
    const response = await this._client.send('Page.navigate', { url, referrer, frameId: frame._id });
    if (response.errorText)
      throw new Error(`${response.errorText} at ${url}`);
    return { newDocumentId: response.loaderId };
  }


_onLifecycleEvent(event: Protocol.Page.lifecycleEventPayload) {
    if (this._eventBelongsToStaleFrame(event.frameId))
      return;
    if (event.name === 'load')
      this._page._frameManager.frameLifecycleEvent(event.frameId, 'load');
    else if (event.name === 'DOMContentLoaded')
      this._page._frameManager.frameLifecycleEvent(event.frameId, 'domcontentloaded');
  }


_onFrameStoppedLoading(frameId: string) {
    if (this._eventBelongsToStaleFrame(frameId))
      return;
    this._page._frameManager.frameStoppedLoading(frameId);
  }


_handleFrameTree(frameTree: Protocol.Page.FrameTree) {
    this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);
    this._onFrameNavigated(frameTree.frame, true);
    if (!frameTree.childFrames)
      return;

    for (const child of frameTree.childFrames)
      this._handleFrameTree(child);
  }


private _eventBelongsToStaleFrame(frameId: string)  {
    const frame = this._page._frameManager.frame(frameId);
    // Subtree may be already gone because some ancestor navigation destroyed the oopif.
    if (!frame)
      return true;
    // When frame goes remote, parent process may still send some events
    // related to the local frame before it sends frameDetached.
    // In this case, we already have a new session for this frame, so events
    // in the old session should be ignored.
    const session = this._crPage._sessionForFrame(frame);
    return session && session !== this && !session._swappedIn;
  }


_onFrameAttached(frameId: string, parentFrameId: string | null) {
    const frameSession = this._crPage._sessions.get(frameId);
    if (frameSession && frameId !== this._targetId) {
      // This is a remote -> local frame transition.
      frameSession._swappedIn = true;
      const frame = this._page._frameManager.frame(frameId);
      // Frame or even a whole subtree may be already gone, because some ancestor did navigate.
      if (frame)
        this._page._frameManager.removeChildFramesRecursively(frame);
      return;
    }
    if (parentFrameId && !this._page._frameManager.frame(parentFrameId)) {
      // Parent frame may be gone already because some ancestor frame navigated and
      // destroyed the whole subtree of some oopif, while oopif's process is still sending us events.
      // Be careful to not confuse this with "main frame navigated cross-process" scenario
      // where parentFrameId is null.
      return;
    }
    this._page._frameManager.frameAttached(frameId, parentFrameId);
  }


_onFrameNavigated(framePayload: Protocol.Page.Frame, initial: boolean) {
    if (this._eventBelongsToStaleFrame(framePayload.id))
      return;
    this._page._frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ''), framePayload.name || '', framePayload.loaderId, initial);
    if (!initial)
      this._firstNonInitialNavigationCommittedFulfill();
  }


_onFrameRequestedNavigation(payload: Protocol.Page.frameRequestedNavigationPayload) {
    if (this._eventBelongsToStaleFrame(payload.frameId))
      return;
    if (payload.disposition === 'currentTab')
      this._page._frameManager.frameRequestedNavigation(payload.frameId);
  }


_onFrameNavigatedWithinDocument(frameId: string, url: string) {
    if (this._eventBelongsToStaleFrame(frameId))
      return;
    this._page._frameManager.frameCommittedSameDocumentNavigation(frameId, url);
  }


_onFrameDetached(frameId: string, reason: 'remove' | 'swap') {
    if (this._crPage._sessions.has(frameId)) {
      // This is a local -> remote frame transtion, where
      // Page.frameDetached arrives after Target.attachedToTarget.
      // We've already handled the new target and frame reattach - nothing to do here.
      return;
    }
    if (reason === 'swap') {
      // This is a local -> remote frame transtion, where
      // Page.frameDetached arrives before Target.attachedToTarget.
      // We should keep the frame in the tree, and it will be used for the new target.
      const frame = this._page._frameManager.frame(frameId);
      if (frame)
        this._page._frameManager.removeChildFramesRecursively(frame);
      return;
    }
    // Just a regular frame detach.
    this._page._frameManager.frameDetached(frameId);
  }


_onExecutionContextCreated(contextPayload: Protocol.Runtime.ExecutionContextDescription) {
    const frame = contextPayload.auxData ? this._page._frameManager.frame(contextPayload.auxData.frameId) : null;
    if (!frame || this._eventBelongsToStaleFrame(frame._id))
      return;
    const delegate = new CRExecutionContext(this._client, contextPayload);
    let worldName: types.World|null = null;
    if (contextPayload.auxData && !!contextPayload.auxData.isDefault)
      worldName = 'main';
    else if (contextPayload.name === UTILITY_WORLD_NAME)
      worldName = 'utility';
    const context = new dom.FrameExecutionContext(delegate, frame, worldName);
    (context as any)[contextDelegateSymbol] = delegate;
    if (worldName)
      frame._contextCreated(worldName, context);
    this._contextIdToContext.set(contextPayload.id, context);
  }


_onExecutionContextDestroyed(executionContextId: number) {
    const context = this._contextIdToContext.get(executionContextId);
    if (!context)
      return;
    this._contextIdToContext.delete(executionContextId);
    context.frame._contextDestroyed(context);
  }


_onExecutionContextsCleared() {
    for (const contextId of Array.from(this._contextIdToContext.keys()))
      this._onExecutionContextDestroyed(contextId);
  }


_onAttachedToTarget(event: Protocol.Target.attachedToTargetPayload) {
    const session = CRConnection.fromSession(this._client).session(event.sessionId)!;

    if (event.targetInfo.type === 'iframe') {
      // Frame id equals target id.
      const targetId = event.targetInfo.targetId;
      const frame = this._page._frameManager.frame(targetId);
      if (!frame)
        return; // Subtree may be already gone due to renderer/browser race.
      this._page._frameManager.removeChildFramesRecursively(frame);
      const frameSession = new FrameSession(this._crPage, session, targetId, this);
      this._crPage._sessions.set(targetId, frameSession);
      frameSession._initialize(false).catch(e => e);
      return;
    }

    if (event.targetInfo.type !== 'worker') {
      // Ideally, detaching should resume any target, but there is a bug in the backend.
      session._sendMayFail('Runtime.runIfWaitingForDebugger').then(() => {
        this._client._sendMayFail('Target.detachFromTarget', { sessionId: event.sessionId });
      });
      return;
    }

    const url = event.targetInfo.url;
    const worker = new Worker(this._page, url);
    this._page._addWorker(event.sessionId, worker);
    session.once('Runtime.executionContextCreated', async event => {
      worker._createExecutionContext(new CRExecutionContext(session, event.context));
    });
    // This might fail if the target is closed before we initialize.
    session._sendMayFail('Runtime.enable');
    session._sendMayFail('Network.enable');
    session._sendMayFail('Runtime.runIfWaitingForDebugger');
    session.on('Runtime.consoleAPICalled', event => {
      const args = event.args.map(o => worker._existingExecutionContext!.createHandle(o));
      this._page._addConsoleMessage(event.type, args, toConsoleMessageLocation(event.stackTrace));
    });
    session.on('Runtime.exceptionThrown', exception => this._page.emit(Page.Events.PageError, exceptionToError(exception.exceptionDetails)));
    // TODO: attribute workers to the right frame.
    this._networkManager.instrumentNetworkEvents(session, this._page._frameManager.frame(this._targetId)!);
  }


_onDetachedFromTarget(event: Protocol.Target.detachedFromTargetPayload) {
    // This might be a worker...
    this._page._removeWorker(event.sessionId);

    // ... or an oopif.
    const childFrameSession = this._crPage._sessions.get(event.targetId!);
    if (!childFrameSession)
      return;

    // Usually, we get frameAttached in this session first and mark child as swappedIn.
    if (childFrameSession._swappedIn) {
      childFrameSession.dispose();
      return;
    }

    // However, sometimes we get detachedFromTarget before frameAttached.
    // In this case we don't know wheter this is a remote frame detach,
    // or just a remote -> local transition. In the latter case, frameAttached
    // is already inflight, so let's make a safe roundtrip to ensure it arrives.
    this._client.send('Page.enable').catch(e => null).then(() => {
      // Child was not swapped in - that means frameAttached did not happen and
      // this is remote detach rather than remote -> local swap.
      if (!childFrameSession._swappedIn)
        this._page._frameManager.frameDetached(event.targetId!);
      childFrameSession.dispose();
    });
  }


_onWindowOpen(event: Protocol.Page.windowOpenPayload) {
    this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);
  }


async _onConsoleAPI(event: Protocol.Runtime.consoleAPICalledPayload) {
    if (event.executionContextId === 0) {
      // DevTools protocol stores the last 1000 console messages. These
      // messages are always reported even for removed execution contexts. In
      // this case, they are marked with executionContextId = 0 and are
      // reported upon enabling Runtime agent.
      //
      // Ignore these messages since:
      // - there's no execution context we can use to operate with message
      //   arguments
      // - these messages are reported before Playwright clients can subscribe
      //   to the 'console'
      //   page event.
      //
      // @see https://github.com/GoogleChrome/puppeteer/issues/3865
      return;
    }
    const context = this._contextIdToContext.get(event.executionContextId);
    if (!context)
      return;
    const values = event.args.map(arg => context.createHandle(arg));
    this._page._addConsoleMessage(event.type, values, toConsoleMessageLocation(event.stackTrace));
  }


async _initBinding(binding: PageBinding) {
    const [ , response ] = await Promise.all([
      this._client.send('Runtime.addBinding', { name: binding.name }),
      this._client.send('Page.addScriptToEvaluateOnNewDocument', { source: binding.source })
    ]);
    this._exposedBindingNames.push(binding.name);
    if (!binding.name.startsWith('__pw'))
      this._evaluateOnNewDocumentIdentifiers.push(response.identifier);
  }


async _removeExposedBindings() {
    const toRetain: string[] = [];
    const toRemove: string[] = [];
    for (const name of this._exposedBindingNames)
      (name.startsWith('__pw_') ? toRetain : toRemove).push(name);
    this._exposedBindingNames = toRetain;
    await Promise.all(toRemove.map(name => this._client.send('Runtime.removeBinding', { name })));
  }


async _onBindingCalled(event: Protocol.Runtime.bindingCalledPayload) {
    const pageOrError = await this._crPage.pageOrError();
    if (!(pageOrError instanceof Error)) {
      const context = this._contextIdToContext.get(event.executionContextId);
      if (context)
        await this._page._onBindingCalled(event.payload, context);
    }
  }


_onDialog(event: Protocol.Page.javascriptDialogOpeningPayload) {
    if (!this._page._frameManager.frame(this._targetId))
      return; // Our frame/subtree may be gone already.
    this._page.emit(Page.Events.Dialog, new dialog.Dialog(
        this._page,
        event.type,
        event.message,
        async (accept: boolean, promptText?: string) => {
          await this._client.send('Page.handleJavaScriptDialog', { accept, promptText });
        },
        event.defaultPrompt));
  }


_handleException(exceptionDetails: Protocol.Runtime.ExceptionDetails) {
    this._page.firePageError(exceptionToError(exceptionDetails));
  }


async _onTargetCrashed() {
    this._client._markAsCrashed();
    this._page._didCrash();
  }


_onLogEntryAdded(event: Protocol.Log.entryAddedPayload) {
    const { level, text, args, source, url, lineNumber } = event.entry;
    if (args)
      args.map(arg => releaseObject(this._client, arg.objectId!));
    if (source !== 'worker') {
      const location: types.ConsoleMessageLocation = {
        url: url || '',
        lineNumber: lineNumber || 0,
        columnNumber: 0,
      };
      this._page._addConsoleMessage(level, [], location, text);
    }
  }


async _onFileChooserOpened(event: Protocol.Page.fileChooserOpenedPayload) {
    const frame = this._page._frameManager.frame(event.frameId);
    if (!frame)
      return;
    let handle;
    try {
      const utilityContext = await frame._utilityContext();
      handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);
    } catch (e) {
      // During async processing, frame/context may go away. We should not throw.
      return;
    }
    await this._page._onFileChooserOpened(handle);
  }


_willBeginDownload() {
    const originPage = this._crPage._initializedPage;
    if (!originPage) {
      // Resume the page creation with an error. The page will automatically close right
      // after the download begins.
      this._firstNonInitialNavigationCommittedReject(new Error('Starting new page download'));
    }
  }


_onScreencastFrame(payload: Protocol.Page.screencastFramePayload) {
    this._page.throttleScreencastFrameAck(() => {
      this._client.send('Page.screencastFrameAck', { sessionId: payload.sessionId }).catch(() => {});
    });
    const buffer = Buffer.from(payload.data, 'base64');
    this._page.emit(Page.Events.ScreencastFrame, {
      buffer,
      timestamp: payload.metadata.timestamp,
      width: payload.metadata.deviceWidth,
      height: payload.metadata.deviceHeight,
    });
  }


async _createVideoRecorder(screencastId: string, options: types.PageScreencastOptions): Promise<void> {
    assert(!this._screencastId);
    const ffmpegPath = registry.findExecutable('ffmpeg')!.executablePathOrDie(this._page._browserContext._browser.options.sdkLanguage);
    this._videoRecorder = await VideoRecorder.launch(this._crPage._page, ffmpegPath, options);
    this._screencastId = screencastId;
  }


async _startVideoRecording(options: types.PageScreencastOptions) {
    const screencastId = this._screencastId;
    assert(screencastId);
    this._page.once(Page.Events.Close, () => this._stopVideoRecording().catch(() => {}));
    const gotFirstFrame = new Promise(f => this._client.once('Page.screencastFrame', f));
    await this._startScreencast(this._videoRecorder, {
      format: 'jpeg',
      quality: 90,
      maxWidth: options.width,
      maxHeight: options.height,
    });
    // Wait for the first frame before reporting video to the client.
    gotFirstFrame.then(() => {
      this._crPage._browserContext._browser._videoStarted(this._crPage._browserContext, screencastId, options.outputFile, this._crPage.pageOrError());
    });
  }


async _stopVideoRecording(): Promise<void> {
    if (!this._screencastId)
      return;
    const screencastId = this._screencastId;
    this._screencastId = null;
    const recorder = this._videoRecorder!;
    this._videoRecorder = null;
    await this._stopScreencast(recorder);
    await recorder.stop().catch(() => {});
    // Keep the video artifact in the map utntil encoding is fully finished, if the context
    // starts closing before the video is fully written to disk it will wait for it.
    const video = this._crPage._browserContext._browser._takeVideo(screencastId);
    video?.reportFinished();
  }


async _startScreencast(client: any, options: Protocol.Page.startScreencastParameters = {}) {
    this._screencastClients.add(client);
    if (this._screencastClients.size === 1)
      await this._client.send('Page.startScreencast', options);
  }


async _stopScreencast(client: any) {
    this._screencastClients.delete(client);
    if (!this._screencastClients.size)
      await this._client._sendMayFail('Page.stopScreencast');
  }


async _updateExtraHTTPHeaders(initial: boolean): Promise<void> {
    const headers = network.mergeHeaders([
      this._crPage._browserContext._options.extraHTTPHeaders,
      this._page._state.extraHTTPHeaders
    ]);
    if (!initial || headers.length)
      await this._client.send('Network.setExtraHTTPHeaders', { headers: headersArrayToObject(headers, false /* lowerCase */) });
  }


async _updateGeolocation(initial: boolean): Promise<void> {
    const geolocation = this._crPage._browserContext._options.geolocation;
    if (!initial || geolocation)
      await this._client.send('Emulation.setGeolocationOverride', geolocation || {});
  }


async _updateOffline(initial: boolean): Promise<void> {
    const offline = !!this._crPage._browserContext._options.offline;
    if (!initial || offline)
      await this._networkManager.setOffline(offline);
  }


async _updateHttpCredentials(initial: boolean): Promise<void> {
    const credentials = this._crPage._browserContext._options.httpCredentials || null;
    if (!initial || credentials)
      await this._networkManager.authenticate(credentials);
  }


async _updateViewport(): Promise<void> {
    if (this._crPage._browserContext._browser.isClank())
      return;
    assert(this._isMainFrame());
    const options = this._crPage._browserContext._options;
    const emulatedSize = this._page._state.emulatedSize;
    if (emulatedSize === null)
      return;
    const viewportSize = emulatedSize.viewport;
    const screenSize = emulatedSize.screen;
    const isLandscape = viewportSize.width > viewportSize.height;
    const promises = [
      this._client.send('Emulation.setDeviceMetricsOverride', {
        mobile: !!options.isMobile,
        width: viewportSize.width,
        height: viewportSize.height,
        screenWidth: screenSize.width,
        screenHeight: screenSize.height,
        deviceScaleFactor: options.deviceScaleFactor || 1,
        screenOrientation: isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' },
      }),
    ];
    if (this._windowId) {
      let insets = { width: 0, height: 0 };
      if (this._crPage._browserContext._browser.options.headful) {
        // TODO: popup windows have their own insets.
        insets = { width: 24, height: 88 };
        if (process.platform === 'win32')
          insets = { width: 16, height: 88 };
        else if (process.platform === 'linux')
          insets = { width: 8, height: 85 };
        else if (process.platform === 'darwin')
          insets = { width: 2, height: 80 };
        if (this._crPage._browserContext.isPersistentContext()) {
          // FIXME: Chrome bug: OOPIF router is confused when hit target is
          // outside browser window.
          // Account for the infobar here to work around the bug.
          insets.height += 46;
        }
      }
      promises.push(this.setWindowBounds({
        width: viewportSize.width + insets.width,
        height: viewportSize.height + insets.height
      }));
    }
    await Promise.all(promises);
  }


async windowBounds(): Promise<WindowBounds> {
    const { bounds } = await this._client.send('Browser.getWindowBounds', {
      windowId: this._windowId!
    });
    return bounds;
  }


async setWindowBounds(bounds: WindowBounds) {
    return await this._client.send('Browser.setWindowBounds', {
      windowId: this._windowId!,
      bounds
    });
  }


async _updateEmulateMedia(initial: boolean): Promise<void> {
    const colorScheme = this._page._state.colorScheme === null ? '' : this._page._state.colorScheme;
    const reducedMotion = this._page._state.reducedMotion === null ? '' : this._page._state.reducedMotion;
    const forcedColors = this._page._state.forcedColors === null ? '' : this._page._state.forcedColors;
    const features = [
      { name: 'prefers-color-scheme', value: colorScheme },
      { name: 'prefers-reduced-motion', value: reducedMotion },
      { name: 'forced-colors', value: forcedColors },
    ];
    // Empty string disables the override.
    await this._client.send('Emulation.setEmulatedMedia', { media: this._page._state.mediaType || '', features });
  }


private async _setDefaultFontFamilies(session: CRSession) {
    const fontFamilies = platformToFontFamilies[this._crPage._browserContext._browser._platform()];
    await session.send('Page.setFontFamilies', fontFamilies);
  }


async _updateRequestInterception(): Promise<void> {
    await this._networkManager.setRequestInterception(this._page._needsRequestInterception());
  }


async _updateFileChooserInterception(initial: boolean) {
    const enabled = this._page._state.interceptFileChooser;
    if (initial && !enabled)
      return;
    await this._client.send('Page.setInterceptFileChooserDialog', { enabled }).catch(e => {}); // target can be closed.
  }


async _evaluateOnNewDocument(source: string, world: types.World): Promise<void> {
    const worldName = world === 'utility' ? UTILITY_WORLD_NAME : undefined;
    const { identifier } = await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source, worldName });
    this._evaluateOnNewDocumentIdentifiers.push(identifier);
  }


async _removeEvaluatesOnNewDocument(): Promise<void> {
    const identifiers = this._evaluateOnNewDocumentIdentifiers;
    this._evaluateOnNewDocumentIdentifiers = [];
    await Promise.all(identifiers.map(identifier => this._client.send('Page.removeScriptToEvaluateOnNewDocument', { identifier })));
  }


async _getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null> {
    const nodeInfo = await this._client.send('DOM.describeNode', {
      objectId: handle._objectId
    });
    if (!nodeInfo || typeof nodeInfo.node.frameId !== 'string')
      return null;
    return this._page._frameManager.frame(nodeInfo.node.frameId);
  }


async _getOwnerFrame(handle: dom.ElementHandle): Promise<string | null> {
    // document.documentElement has frameId of the owner frame.
    const documentElement = await handle.evaluateHandle(node => {
      const doc = node as Document;
      if (doc.documentElement && doc.documentElement.ownerDocument === doc)
        return doc.documentElement;
      return node.ownerDocument ? node.ownerDocument.documentElement : null;
    });
    if (!documentElement)
      return null;
    if (!documentElement._objectId)
      return null;
    const nodeInfo = await this._client.send('DOM.describeNode', {
      objectId: documentElement._objectId
    });
    const frameId = nodeInfo && typeof nodeInfo.node.frameId === 'string' ?
      nodeInfo.node.frameId : null;
    documentElement.dispose();
    return frameId;
  }


async _getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
    const result = await this._client._sendMayFail('DOM.getBoxModel', {
      objectId: handle._objectId
    });
    if (!result)
      return null;
    const quad = result.model.border;
    const x = Math.min(quad[0], quad[2], quad[4], quad[6]);
    const y = Math.min(quad[1], quad[3], quad[5], quad[7]);
    const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;
    const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;
    const position = await this._framePosition();
    if (!position)
      return null;
    return { x: x + position.x, y: y + position.y, width, height };
  }


private async _framePosition(): Promise<types.Point | null> {
    const frame = this._page._frameManager.frame(this._targetId);
    if (!frame)
      return null;
    if (frame === this._page.mainFrame())
      return { x: 0, y: 0 };
    const element = await frame.frameElement();
    const box = await element.boundingBox();
    return box;
  }


async _scrollRectIntoViewIfNeeded(handle: dom.ElementHandle, rect?: types.Rect): Promise<'error:notvisible' | 'error:notconnected' | 'done'> {
    return await this._client.send('DOM.scrollIntoViewIfNeeded', {
      objectId: handle._objectId,
      rect,
    }).then(() => 'done' as const).catch(e => {
      if (e instanceof Error && e.message.includes('Node does not have a layout object'))
        return 'error:notvisible';
      if (e instanceof Error && e.message.includes('Node is detached from document'))
        return 'error:notconnected';
      throw e;
    });
  }


async _getContentQuads(handle: dom.ElementHandle): Promise<types.Quad[] | null> {
    const result = await this._client._sendMayFail('DOM.getContentQuads', {
      objectId: handle._objectId
    });
    if (!result)
      return null;
    const position = await this._framePosition();
    if (!position)
      return null;
    return result.quads.map(quad => [
      { x: quad[0] + position.x, y: quad[1] + position.y },
      { x: quad[2] + position.x, y: quad[3] + position.y },
      { x: quad[4] + position.x, y: quad[5] + position.y },
      { x: quad[6] + position.x, y: quad[7] + position.y }
    ]);
  }


async _adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>> {
    const nodeInfo = await this._client.send('DOM.describeNode', {
      objectId: handle._objectId,
    });
    return this._adoptBackendNodeId(nodeInfo.node.backendNodeId, to) as Promise<dom.ElementHandle<T>>;
  }


async _adoptBackendNodeId(backendNodeId: Protocol.DOM.BackendNodeId, to: dom.FrameExecutionContext): Promise<dom.ElementHandle> {
    const result = await this._client._sendMayFail('DOM.resolveNode', {
      backendNodeId,
      executionContextId: ((to as any)[contextDelegateSymbol] as CRExecutionContext)._contextId,
    });
    if (!result || result.object.subtype === 'null')
      throw new Error(dom.kUnableToAdoptErrorMessage);
    return to.createHandle(result.object).asElement()!;
  }


declare function isCompatTag(tagName?: string): boolean;


declare function buildChildren(node: JSXElement | JSXFragment): ReturnedChild[];


declare function assertNode(node?: any): asserts node is Node;


declare function assertArrayExpression(node: object | null | undefined, opts?: object | null): asserts node is ArrayExpression;


declare function assertAssignmentExpression(node: object | null | undefined, opts?: object | null): asserts node is AssignmentExpression;


declare function assertBinaryExpression(node: object | null | undefined, opts?: object | null): asserts node is BinaryExpression;


declare function assertInterpreterDirective(node: object | null | undefined, opts?: object | null): asserts node is InterpreterDirective;


declare function assertDirective(node: object | null | undefined, opts?: object | null): asserts node is Directive;


declare function assertDirectiveLiteral(node: object | null | undefined, opts?: object | null): asserts node is DirectiveLiteral;


declare function assertBlockStatement(node: object | null | undefined, opts?: object | null): asserts node is BlockStatement;


declare function assertBreakStatement(node: object | null | undefined, opts?: object | null): asserts node is BreakStatement;


declare function assertCallExpression(node: object | null | undefined, opts?: object | null): asserts node is CallExpression;


declare function assertCatchClause(node: object | null | undefined, opts?: object | null): asserts node is CatchClause;


declare function assertConditionalExpression(node: object | null | undefined, opts?: object | null): asserts node is ConditionalExpression;


declare function assertContinueStatement(node: object | null | undefined, opts?: object | null): asserts node is ContinueStatement;


declare function assertDebuggerStatement(node: object | null | undefined, opts?: object | null): asserts node is DebuggerStatement;


declare function assertDoWhileStatement(node: object | null | undefined, opts?: object | null): asserts node is DoWhileStatement;


declare function assertEmptyStatement(node: object | null | undefined, opts?: object | null): asserts node is EmptyStatement;


declare function assertExpressionStatement(node: object | null | undefined, opts?: object | null): asserts node is ExpressionStatement;


declare function assertFile(node: object | null | undefined, opts?: object | null): asserts node is File;


declare function assertForInStatement(node: object | null | undefined, opts?: object | null): asserts node is ForInStatement;


declare function assertForStatement(node: object | null | undefined, opts?: object | null): asserts node is ForStatement;


declare function assertFunctionDeclaration(node: object | null | undefined, opts?: object | null): asserts node is FunctionDeclaration;


declare function assertFunctionExpression(node: object | null | undefined, opts?: object | null): asserts node is FunctionExpression;


declare function assertIdentifier(node: object | null | undefined, opts?: object | null): asserts node is Identifier;


declare function assertIfStatement(node: object | null | undefined, opts?: object | null): asserts node is IfStatement;


declare function assertLabeledStatement(node: object | null | undefined, opts?: object | null): asserts node is LabeledStatement;


declare function assertStringLiteral(node: object | null | undefined, opts?: object | null): asserts node is StringLiteral;


declare function assertNumericLiteral(node: object | null | undefined, opts?: object | null): asserts node is NumericLiteral;


declare function assertNullLiteral(node: object | null | undefined, opts?: object | null): asserts node is NullLiteral;


declare function assertBooleanLiteral(node: object | null | undefined, opts?: object | null): asserts node is BooleanLiteral;


declare function assertRegExpLiteral(node: object | null | undefined, opts?: object | null): asserts node is RegExpLiteral;


declare function assertLogicalExpression(node: object | null | undefined, opts?: object | null): asserts node is LogicalExpression;


declare function assertMemberExpression(node: object | null | undefined, opts?: object | null): asserts node is MemberExpression;


declare function assertNewExpression(node: object | null | undefined, opts?: object | null): asserts node is NewExpression;


declare function assertProgram(node: object | null | undefined, opts?: object | null): asserts node is Program;


declare function assertObjectExpression(node: object | null | undefined, opts?: object | null): asserts node is ObjectExpression;


declare function assertObjectMethod(node: object | null | undefined, opts?: object | null): asserts node is ObjectMethod;


declare function assertObjectProperty(node: object | null | undefined, opts?: object | null): asserts node is ObjectProperty;


declare function assertRestElement(node: object | null | undefined, opts?: object | null): asserts node is RestElement;


declare function assertReturnStatement(node: object | null | undefined, opts?: object | null): asserts node is ReturnStatement;


declare function assertSequenceExpression(node: object | null | undefined, opts?: object | null): asserts node is SequenceExpression;


declare function assertParenthesizedExpression(node: object | null | undefined, opts?: object | null): asserts node is ParenthesizedExpression;


declare function assertSwitchCase(node: object | null | undefined, opts?: object | null): asserts node is SwitchCase;


declare function assertSwitchStatement(node: object | null | undefined, opts?: object | null): asserts node is SwitchStatement;


declare function assertThisExpression(node: object | null | undefined, opts?: object | null): asserts node is ThisExpression;


declare function assertThrowStatement(node: object | null | undefined, opts?: object | null): asserts node is ThrowStatement;


declare function assertTryStatement(node: object | null | undefined, opts?: object | null): asserts node is TryStatement;


declare function assertUnaryExpression(node: object | null | undefined, opts?: object | null): asserts node is UnaryExpression;


declare function assertUpdateExpression(node: object | null | undefined, opts?: object | null): asserts node is UpdateExpression;


declare function assertVariableDeclaration(node: object | null | undefined, opts?: object | null): asserts node is VariableDeclaration;


declare function assertVariableDeclarator(node: object | null | undefined, opts?: object | null): asserts node is VariableDeclarator;


declare function assertWhileStatement(node: object | null | undefined, opts?: object | null): asserts node is WhileStatement;


declare function assertWithStatement(node: object | null | undefined, opts?: object | null): asserts node is WithStatement;


declare function assertAssignmentPattern(node: object | null | undefined, opts?: object | null): asserts node is AssignmentPattern;


declare function assertArrayPattern(node: object | null | undefined, opts?: object | null): asserts node is ArrayPattern;


declare function assertArrowFunctionExpression(node: object | null | undefined, opts?: object | null): asserts node is ArrowFunctionExpression;


declare function assertClassBody(node: object | null | undefined, opts?: object | null): asserts node is ClassBody;


declare function assertClassExpression(node: object | null | undefined, opts?: object | null): asserts node is ClassExpression;


declare function assertClassDeclaration(node: object | null | undefined, opts?: object | null): asserts node is ClassDeclaration;


declare function assertExportAllDeclaration(node: object | null | undefined, opts?: object | null): asserts node is ExportAllDeclaration;


declare function assertExportDefaultDeclaration(node: object | null | undefined, opts?: object | null): asserts node is ExportDefaultDeclaration;


declare function assertExportNamedDeclaration(node: object | null | undefined, opts?: object | null): asserts node is ExportNamedDeclaration;


declare function assertExportSpecifier(node: object | null | undefined, opts?: object | null): asserts node is ExportSpecifier;


declare function assertForOfStatement(node: object | null | undefined, opts?: object | null): asserts node is ForOfStatement;


declare function assertImportDeclaration(node: object | null | undefined, opts?: object | null): asserts node is ImportDeclaration;


declare function assertImportDefaultSpecifier(node: object | null | undefined, opts?: object | null): asserts node is ImportDefaultSpecifier;


declare function assertImportNamespaceSpecifier(node: object | null | undefined, opts?: object | null): asserts node is ImportNamespaceSpecifier;


declare function assertImportSpecifier(node: object | null | undefined, opts?: object | null): asserts node is ImportSpecifier;


declare function assertMetaProperty(node: object | null | undefined, opts?: object | null): asserts node is MetaProperty;


declare function assertClassMethod(node: object | null | undefined, opts?: object | null): asserts node is ClassMethod;


declare function assertObjectPattern(node: object | null | undefined, opts?: object | null): asserts node is ObjectPattern;


declare function assertSpreadElement(node: object | null | undefined, opts?: object | null): asserts node is SpreadElement;


declare function assertSuper(node: object | null | undefined, opts?: object | null): asserts node is Super;


declare function assertTaggedTemplateExpression(node: object | null | undefined, opts?: object | null): asserts node is TaggedTemplateExpression;


declare function assertTemplateElement(node: object | null | undefined, opts?: object | null): asserts node is TemplateElement;


declare function assertTemplateLiteral(node: object | null | undefined, opts?: object | null): asserts node is TemplateLiteral;


declare function assertYieldExpression(node: object | null | undefined, opts?: object | null): asserts node is YieldExpression;


declare function assertAwaitExpression(node: object | null | undefined, opts?: object | null): asserts node is AwaitExpression;


declare function assertImport(node: object | null | undefined, opts?: object | null): asserts node is Import;


declare function assertBigIntLiteral(node: object | null | undefined, opts?: object | null): asserts node is BigIntLiteral;


declare function assertExportNamespaceSpecifier(node: object | null | undefined, opts?: object | null): asserts node is ExportNamespaceSpecifier;


declare function assertOptionalMemberExpression(node: object | null | undefined, opts?: object | null): asserts node is OptionalMemberExpression;


declare function assertOptionalCallExpression(node: object | null | undefined, opts?: object | null): asserts node is OptionalCallExpression;


declare function assertClassProperty(node: object | null | undefined, opts?: object | null): asserts node is ClassProperty;


declare function assertClassAccessorProperty(node: object | null | undefined, opts?: object | null): asserts node is ClassAccessorProperty;


declare function assertClassPrivateProperty(node: object | null | undefined, opts?: object | null): asserts node is ClassPrivateProperty;


declare function assertClassPrivateMethod(node: object | null | undefined, opts?: object | null): asserts node is ClassPrivateMethod;


declare function assertPrivateName(node: object | null | undefined, opts?: object | null): asserts node is PrivateName;


declare function assertStaticBlock(node: object | null | undefined, opts?: object | null): asserts node is StaticBlock;


declare function assertAnyTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is AnyTypeAnnotation;


declare function assertArrayTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is ArrayTypeAnnotation;


declare function assertBooleanTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is BooleanTypeAnnotation;


declare function assertBooleanLiteralTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is BooleanLiteralTypeAnnotation;


declare function assertNullLiteralTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is NullLiteralTypeAnnotation;


declare function assertClassImplements(node: object | null | undefined, opts?: object | null): asserts node is ClassImplements;


declare function assertDeclareClass(node: object | null | undefined, opts?: object | null): asserts node is DeclareClass;


declare function assertDeclareFunction(node: object | null | undefined, opts?: object | null): asserts node is DeclareFunction;


declare function assertDeclareInterface(node: object | null | undefined, opts?: object | null): asserts node is DeclareInterface;


declare function assertDeclareModule(node: object | null | undefined, opts?: object | null): asserts node is DeclareModule;


declare function assertDeclareModuleExports(node: object | null | undefined, opts?: object | null): asserts node is DeclareModuleExports;


declare function assertDeclareTypeAlias(node: object | null | undefined, opts?: object | null): asserts node is DeclareTypeAlias;


declare function assertDeclareOpaqueType(node: object | null | undefined, opts?: object | null): asserts node is DeclareOpaqueType;


declare function assertDeclareVariable(node: object | null | undefined, opts?: object | null): asserts node is DeclareVariable;


declare function assertDeclareExportDeclaration(node: object | null | undefined, opts?: object | null): asserts node is DeclareExportDeclaration;


declare function assertDeclareExportAllDeclaration(node: object | null | undefined, opts?: object | null): asserts node is DeclareExportAllDeclaration;


declare function assertDeclaredPredicate(node: object | null | undefined, opts?: object | null): asserts node is DeclaredPredicate;


declare function assertExistsTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is ExistsTypeAnnotation;


declare function assertFunctionTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is FunctionTypeAnnotation;


declare function assertFunctionTypeParam(node: object | null | undefined, opts?: object | null): asserts node is FunctionTypeParam;


declare function assertGenericTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is GenericTypeAnnotation;


declare function assertInferredPredicate(node: object | null | undefined, opts?: object | null): asserts node is InferredPredicate;


declare function assertInterfaceExtends(node: object | null | undefined, opts?: object | null): asserts node is InterfaceExtends;


declare function assertInterfaceDeclaration(node: object | null | undefined, opts?: object | null): asserts node is InterfaceDeclaration;


declare function assertInterfaceTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is InterfaceTypeAnnotation;


declare function assertIntersectionTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is IntersectionTypeAnnotation;


declare function assertMixedTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is MixedTypeAnnotation;


declare function assertEmptyTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is EmptyTypeAnnotation;


declare function assertNullableTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is NullableTypeAnnotation;


declare function assertNumberLiteralTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is NumberLiteralTypeAnnotation;


declare function assertNumberTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is NumberTypeAnnotation;


declare function assertObjectTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is ObjectTypeAnnotation;


declare function assertObjectTypeInternalSlot(node: object | null | undefined, opts?: object | null): asserts node is ObjectTypeInternalSlot;


declare function assertObjectTypeCallProperty(node: object | null | undefined, opts?: object | null): asserts node is ObjectTypeCallProperty;


declare function assertObjectTypeIndexer(node: object | null | undefined, opts?: object | null): asserts node is ObjectTypeIndexer;


declare function assertObjectTypeProperty(node: object | null | undefined, opts?: object | null): asserts node is ObjectTypeProperty;


declare function assertObjectTypeSpreadProperty(node: object | null | undefined, opts?: object | null): asserts node is ObjectTypeSpreadProperty;


declare function assertOpaqueType(node: object | null | undefined, opts?: object | null): asserts node is OpaqueType;


declare function assertQualifiedTypeIdentifier(node: object | null | undefined, opts?: object | null): asserts node is QualifiedTypeIdentifier;


declare function assertStringLiteralTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is StringLiteralTypeAnnotation;


declare function assertStringTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is StringTypeAnnotation;


declare function assertSymbolTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is SymbolTypeAnnotation;


declare function assertThisTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is ThisTypeAnnotation;


declare function assertTupleTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is TupleTypeAnnotation;


declare function assertTypeofTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is TypeofTypeAnnotation;


declare function assertTypeAlias(node: object | null | undefined, opts?: object | null): asserts node is TypeAlias;


declare function assertTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is TypeAnnotation;


declare function assertTypeCastExpression(node: object | null | undefined, opts?: object | null): asserts node is TypeCastExpression;


declare function assertTypeParameter(node: object | null | undefined, opts?: object | null): asserts node is TypeParameter;


declare function assertTypeParameterDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TypeParameterDeclaration;


declare function assertTypeParameterInstantiation(node: object | null | undefined, opts?: object | null): asserts node is TypeParameterInstantiation;


declare function assertUnionTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is UnionTypeAnnotation;


declare function assertVariance(node: object | null | undefined, opts?: object | null): asserts node is Variance;


declare function assertVoidTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is VoidTypeAnnotation;


declare function assertEnumDeclaration(node: object | null | undefined, opts?: object | null): asserts node is EnumDeclaration;


declare function assertEnumBooleanBody(node: object | null | undefined, opts?: object | null): asserts node is EnumBooleanBody;


declare function assertEnumNumberBody(node: object | null | undefined, opts?: object | null): asserts node is EnumNumberBody;


declare function assertEnumStringBody(node: object | null | undefined, opts?: object | null): asserts node is EnumStringBody;


declare function assertEnumSymbolBody(node: object | null | undefined, opts?: object | null): asserts node is EnumSymbolBody;


declare function assertEnumBooleanMember(node: object | null | undefined, opts?: object | null): asserts node is EnumBooleanMember;


declare function assertEnumNumberMember(node: object | null | undefined, opts?: object | null): asserts node is EnumNumberMember;


declare function assertEnumStringMember(node: object | null | undefined, opts?: object | null): asserts node is EnumStringMember;


declare function assertEnumDefaultedMember(node: object | null | undefined, opts?: object | null): asserts node is EnumDefaultedMember;


declare function assertIndexedAccessType(node: object | null | undefined, opts?: object | null): asserts node is IndexedAccessType;


declare function assertOptionalIndexedAccessType(node: object | null | undefined, opts?: object | null): asserts node is OptionalIndexedAccessType;


declare function assertJSXAttribute(node: object | null | undefined, opts?: object | null): asserts node is JSXAttribute;


declare function assertJSXClosingElement(node: object | null | undefined, opts?: object | null): asserts node is JSXClosingElement;


declare function assertJSXElement(node: object | null | undefined, opts?: object | null): asserts node is JSXElement;


declare function assertJSXEmptyExpression(node: object | null | undefined, opts?: object | null): asserts node is JSXEmptyExpression;


declare function assertJSXExpressionContainer(node: object | null | undefined, opts?: object | null): asserts node is JSXExpressionContainer;


declare function assertJSXSpreadChild(node: object | null | undefined, opts?: object | null): asserts node is JSXSpreadChild;


declare function assertJSXIdentifier(node: object | null | undefined, opts?: object | null): asserts node is JSXIdentifier;


declare function assertJSXMemberExpression(node: object | null | undefined, opts?: object | null): asserts node is JSXMemberExpression;


declare function assertJSXNamespacedName(node: object | null | undefined, opts?: object | null): asserts node is JSXNamespacedName;


declare function assertJSXOpeningElement(node: object | null | undefined, opts?: object | null): asserts node is JSXOpeningElement;


declare function assertJSXSpreadAttribute(node: object | null | undefined, opts?: object | null): asserts node is JSXSpreadAttribute;


declare function assertJSXText(node: object | null | undefined, opts?: object | null): asserts node is JSXText;


declare function assertJSXFragment(node: object | null | undefined, opts?: object | null): asserts node is JSXFragment;


declare function assertJSXOpeningFragment(node: object | null | undefined, opts?: object | null): asserts node is JSXOpeningFragment;


declare function assertJSXClosingFragment(node: object | null | undefined, opts?: object | null): asserts node is JSXClosingFragment;


declare function assertNoop(node: object | null | undefined, opts?: object | null): asserts node is Noop;


declare function assertPlaceholder(node: object | null | undefined, opts?: object | null): asserts node is Placeholder;


declare function assertV8IntrinsicIdentifier(node: object | null | undefined, opts?: object | null): asserts node is V8IntrinsicIdentifier;


declare function assertArgumentPlaceholder(node: object | null | undefined, opts?: object | null): asserts node is ArgumentPlaceholder;


declare function assertBindExpression(node: object | null | undefined, opts?: object | null): asserts node is BindExpression;


declare function assertImportAttribute(node: object | null | undefined, opts?: object | null): asserts node is ImportAttribute;


declare function assertDecorator(node: object | null | undefined, opts?: object | null): asserts node is Decorator;


declare function assertDoExpression(node: object | null | undefined, opts?: object | null): asserts node is DoExpression;


declare function assertExportDefaultSpecifier(node: object | null | undefined, opts?: object | null): asserts node is ExportDefaultSpecifier;


declare function assertRecordExpression(node: object | null | undefined, opts?: object | null): asserts node is RecordExpression;


declare function assertTupleExpression(node: object | null | undefined, opts?: object | null): asserts node is TupleExpression;


declare function assertDecimalLiteral(node: object | null | undefined, opts?: object | null): asserts node is DecimalLiteral;


declare function assertModuleExpression(node: object | null | undefined, opts?: object | null): asserts node is ModuleExpression;


declare function assertTopicReference(node: object | null | undefined, opts?: object | null): asserts node is TopicReference;


declare function assertPipelineTopicExpression(node: object | null | undefined, opts?: object | null): asserts node is PipelineTopicExpression;


declare function assertPipelineBareFunction(node: object | null | undefined, opts?: object | null): asserts node is PipelineBareFunction;


declare function assertPipelinePrimaryTopicReference(node: object | null | undefined, opts?: object | null): asserts node is PipelinePrimaryTopicReference;


declare function assertTSParameterProperty(node: object | null | undefined, opts?: object | null): asserts node is TSParameterProperty;


declare function assertTSDeclareFunction(node: object | null | undefined, opts?: object | null): asserts node is TSDeclareFunction;


declare function assertTSDeclareMethod(node: object | null | undefined, opts?: object | null): asserts node is TSDeclareMethod;


declare function assertTSQualifiedName(node: object | null | undefined, opts?: object | null): asserts node is TSQualifiedName;


declare function assertTSCallSignatureDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSCallSignatureDeclaration;


declare function assertTSConstructSignatureDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSConstructSignatureDeclaration;


declare function assertTSPropertySignature(node: object | null | undefined, opts?: object | null): asserts node is TSPropertySignature;


declare function assertTSMethodSignature(node: object | null | undefined, opts?: object | null): asserts node is TSMethodSignature;


declare function assertTSIndexSignature(node: object | null | undefined, opts?: object | null): asserts node is TSIndexSignature;


declare function assertTSAnyKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSAnyKeyword;


declare function assertTSBooleanKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSBooleanKeyword;


declare function assertTSBigIntKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSBigIntKeyword;


declare function assertTSIntrinsicKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSIntrinsicKeyword;


declare function assertTSNeverKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSNeverKeyword;


declare function assertTSNullKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSNullKeyword;


declare function assertTSNumberKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSNumberKeyword;


declare function assertTSObjectKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSObjectKeyword;


declare function assertTSStringKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSStringKeyword;


declare function assertTSSymbolKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSSymbolKeyword;


declare function assertTSUndefinedKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSUndefinedKeyword;


declare function assertTSUnknownKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSUnknownKeyword;


declare function assertTSVoidKeyword(node: object | null | undefined, opts?: object | null): asserts node is TSVoidKeyword;


declare function assertTSThisType(node: object | null | undefined, opts?: object | null): asserts node is TSThisType;


declare function assertTSFunctionType(node: object | null | undefined, opts?: object | null): asserts node is TSFunctionType;


declare function assertTSConstructorType(node: object | null | undefined, opts?: object | null): asserts node is TSConstructorType;


declare function assertTSTypeReference(node: object | null | undefined, opts?: object | null): asserts node is TSTypeReference;


declare function assertTSTypePredicate(node: object | null | undefined, opts?: object | null): asserts node is TSTypePredicate;


declare function assertTSTypeQuery(node: object | null | undefined, opts?: object | null): asserts node is TSTypeQuery;


declare function assertTSTypeLiteral(node: object | null | undefined, opts?: object | null): asserts node is TSTypeLiteral;


declare function assertTSArrayType(node: object | null | undefined, opts?: object | null): asserts node is TSArrayType;


declare function assertTSTupleType(node: object | null | undefined, opts?: object | null): asserts node is TSTupleType;


declare function assertTSOptionalType(node: object | null | undefined, opts?: object | null): asserts node is TSOptionalType;


declare function assertTSRestType(node: object | null | undefined, opts?: object | null): asserts node is TSRestType;


declare function assertTSNamedTupleMember(node: object | null | undefined, opts?: object | null): asserts node is TSNamedTupleMember;


declare function assertTSUnionType(node: object | null | undefined, opts?: object | null): asserts node is TSUnionType;


declare function assertTSIntersectionType(node: object | null | undefined, opts?: object | null): asserts node is TSIntersectionType;


declare function assertTSConditionalType(node: object | null | undefined, opts?: object | null): asserts node is TSConditionalType;


declare function assertTSInferType(node: object | null | undefined, opts?: object | null): asserts node is TSInferType;


declare function assertTSParenthesizedType(node: object | null | undefined, opts?: object | null): asserts node is TSParenthesizedType;


declare function assertTSTypeOperator(node: object | null | undefined, opts?: object | null): asserts node is TSTypeOperator;


declare function assertTSIndexedAccessType(node: object | null | undefined, opts?: object | null): asserts node is TSIndexedAccessType;


declare function assertTSMappedType(node: object | null | undefined, opts?: object | null): asserts node is TSMappedType;


declare function assertTSLiteralType(node: object | null | undefined, opts?: object | null): asserts node is TSLiteralType;


declare function assertTSExpressionWithTypeArguments(node: object | null | undefined, opts?: object | null): asserts node is TSExpressionWithTypeArguments;


declare function assertTSInterfaceDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSInterfaceDeclaration;


declare function assertTSInterfaceBody(node: object | null | undefined, opts?: object | null): asserts node is TSInterfaceBody;


declare function assertTSTypeAliasDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSTypeAliasDeclaration;


declare function assertTSAsExpression(node: object | null | undefined, opts?: object | null): asserts node is TSAsExpression;


declare function assertTSTypeAssertion(node: object | null | undefined, opts?: object | null): asserts node is TSTypeAssertion;


declare function assertTSEnumDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSEnumDeclaration;


declare function assertTSEnumMember(node: object | null | undefined, opts?: object | null): asserts node is TSEnumMember;


declare function assertTSModuleDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSModuleDeclaration;


declare function assertTSModuleBlock(node: object | null | undefined, opts?: object | null): asserts node is TSModuleBlock;


declare function assertTSImportType(node: object | null | undefined, opts?: object | null): asserts node is TSImportType;


declare function assertTSImportEqualsDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSImportEqualsDeclaration;


declare function assertTSExternalModuleReference(node: object | null | undefined, opts?: object | null): asserts node is TSExternalModuleReference;


declare function assertTSNonNullExpression(node: object | null | undefined, opts?: object | null): asserts node is TSNonNullExpression;


declare function assertTSExportAssignment(node: object | null | undefined, opts?: object | null): asserts node is TSExportAssignment;


declare function assertTSNamespaceExportDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSNamespaceExportDeclaration;


declare function assertTSTypeAnnotation(node: object | null | undefined, opts?: object | null): asserts node is TSTypeAnnotation;


declare function assertTSTypeParameterInstantiation(node: object | null | undefined, opts?: object | null): asserts node is TSTypeParameterInstantiation;


declare function assertTSTypeParameterDeclaration(node: object | null | undefined, opts?: object | null): asserts node is TSTypeParameterDeclaration;


declare function assertTSTypeParameter(node: object | null | undefined, opts?: object | null): asserts node is TSTypeParameter;


declare function assertStandardized(node: object | null | undefined, opts?: object | null): asserts node is Standardized;


declare function assertExpression(node: object | null | undefined, opts?: object | null): asserts node is Expression;


declare function assertBinary(node: object | null | undefined, opts?: object | null): asserts node is Binary;


declare function assertScopable(node: object | null | undefined, opts?: object | null): asserts node is Scopable;


declare function assertBlockParent(node: object | null | undefined, opts?: object | null): asserts node is BlockParent;


declare function assertBlock(node: object | null | undefined, opts?: object | null): asserts node is Block;


declare function assertStatement(node: object | null | undefined, opts?: object | null): asserts node is Statement;


declare function assertTerminatorless(node: object | null | undefined, opts?: object | null): asserts node is Terminatorless;


declare function assertCompletionStatement(node: object | null | undefined, opts?: object | null): asserts node is CompletionStatement;


declare function assertConditional(node: object | null | undefined, opts?: object | null): asserts node is Conditional;


declare function assertLoop(node: object | null | undefined, opts?: object | null): asserts node is Loop;


declare function assertWhile(node: object | null | undefined, opts?: object | null): asserts node is While;


declare function assertExpressionWrapper(node: object | null | undefined, opts?: object | null): asserts node is ExpressionWrapper;


declare function assertFor(node: object | null | undefined, opts?: object | null): asserts node is For;


declare function assertForXStatement(node: object | null | undefined, opts?: object | null): asserts node is ForXStatement;


declare function assertFunction(node: object | null | undefined, opts?: object | null): asserts node is Function;


declare function assertFunctionParent(node: object | null | undefined, opts?: object | null): asserts node is FunctionParent;


declare function assertPureish(node: object | null | undefined, opts?: object | null): asserts node is Pureish;


declare function assertDeclaration(node: object | null | undefined, opts?: object | null): asserts node is Declaration;


declare function assertPatternLike(node: object | null | undefined, opts?: object | null): asserts node is PatternLike;


declare function assertLVal(node: object | null | undefined, opts?: object | null): asserts node is LVal;


declare function assertTSEntityName(node: object | null | undefined, opts?: object | null): asserts node is TSEntityName;


declare function assertLiteral(node: object | null | undefined, opts?: object | null): asserts node is Literal;


declare function assertImmutable(node: object | null | undefined, opts?: object | null): asserts node is Immutable;


declare function assertUserWhitespacable(node: object | null | undefined, opts?: object | null): asserts node is UserWhitespacable;


declare function assertMethod(node: object | null | undefined, opts?: object | null): asserts node is Method;


declare function assertObjectMember(node: object | null | undefined, opts?: object | null): asserts node is ObjectMember;


declare function assertProperty(node: object | null | undefined, opts?: object | null): asserts node is Property;


declare function assertUnaryLike(node: object | null | undefined, opts?: object | null): asserts node is UnaryLike;


declare function assertPattern(node: object | null | undefined, opts?: object | null): asserts node is Pattern;


declare function assertClass(node: object | null | undefined, opts?: object | null): asserts node is Class;


declare function assertModuleDeclaration(node: object | null | undefined, opts?: object | null): asserts node is ModuleDeclaration;


declare function assertExportDeclaration(node: object | null | undefined, opts?: object | null): asserts node is ExportDeclaration;


declare function assertModuleSpecifier(node: object | null | undefined, opts?: object | null): asserts node is ModuleSpecifier;


declare function assertAccessor(node: object | null | undefined, opts?: object | null): asserts node is Accessor;


declare function assertPrivate(node: object | null | undefined, opts?: object | null): asserts node is Private;


declare function assertFlow(node: object | null | undefined, opts?: object | null): asserts node is Flow;


declare function assertFlowType(node: object | null | undefined, opts?: object | null): asserts node is FlowType;


declare function assertFlowBaseAnnotation(node: object | null | undefined, opts?: object | null): asserts node is FlowBaseAnnotation;


declare function assertFlowDeclaration(node: object | null | undefined, opts?: object | null): asserts node is FlowDeclaration;


declare function assertFlowPredicate(node: object | null | undefined, opts?: object | null): asserts node is FlowPredicate;


declare function assertEnumBody(node: object | null | undefined, opts?: object | null): asserts node is EnumBody;


declare function assertEnumMember(node: object | null | undefined, opts?: object | null): asserts node is EnumMember;


declare function assertJSX(node: object | null | undefined, opts?: object | null): asserts node is JSX;


declare function assertMiscellaneous(node: object | null | undefined, opts?: object | null): asserts node is Miscellaneous;


declare function assertTypeScript(node: object | null | undefined, opts?: object | null): asserts node is TypeScript;


declare function assertTSTypeElement(node: object | null | undefined, opts?: object | null): asserts node is TSTypeElement;


declare function assertTSType(node: object | null | undefined, opts?: object | null): asserts node is TSType;


declare function assertTSBaseType(node: object | null | undefined, opts?: object | null): asserts node is TSBaseType;


declare function assertNumberLiteral(node: any, opts: any): void;


declare function assertRegexLiteral(node: any, opts: any): void;


declare function assertRestProperty(node: any, opts: any): void;


declare function assertSpreadProperty(node: any, opts: any): void;


//# sourceMappingURL=createTypeAnnotationBasedOnTypeof.d.ts.map
/**
 * Takes an array of `types` and flattens them, removing duplicates and
 * returns a `UnionTypeAnnotation` node containing them.
 */
declare function createFlowUnionType<T extends FlowType>(types: [T] | Array<T>): T | UnionTypeAnnotation;


/**
 * Takes an array of `types` and flattens them, removing duplicates and
 * returns a `UnionTypeAnnotation` node containing them.
 */
declare function createTSUnionType(typeAnnotations: Array<TSTypeAnnotation>): TSType;


declare function arrayExpression(elements?: Array<null | Expression | SpreadElement>): ArrayExpression;


declare function assignmentExpression(operator: string, left: LVal, right: Expression): AssignmentExpression;


declare function binaryExpression(operator: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", left: Expression | PrivateName, right: Expression): BinaryExpression;