a
    >xdω                     @   s  d Z ddlZddlmZ ddlZddlmZ ddlmZm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZmZ ddl m!Z! erddlm"Z" e#e$Z%G dd deZ&G dd de'Z(G dd de'Z)dZ*dS )zFrame Manager module.    N)OrderedDict)SimpleNamespace)Any	AwaitableDict	GeneratorListOptionalUnion)TYPE_CHECKING)EventEmitter)helper)
CDPSession)ElementHandle)NetworkError)ExecutionContextJSHandle)ElementHandleError	PageErrorTimeoutError)
merge_dict)Setc                       sP  e Zd ZdZeddddddZeeedd	 fd
dZ	eddddZ
eddddZeddddZeed dddZed dddZeed dddZeeddddZedd d!d"Zeedd#d$d%Zeddd&d'Zedd(d)d*Zedd+d,d-Zedd.d/d0Zddd1d2Zd9eeed3d4d5Zddd6d7d8Z   Z!S ):FrameManagerzFrameManager class.ZframeattachedZframenavigatedZframedetachedZlifecycleeventZframenavigatedwithindocument)FrameAttachedFrameNavigatedFrameDetachedLifecycleEventFrameNavigatedWithinDocumentN)client	frameTreepagereturnc                    s   t    | _| _t  _d _t  _|	d fdd |	d fdd |	d fdd |	d	 fd
d |	d fdd |	d fdd |	d fdd |	d fdd |	d fdd  
| dS )zMake new frame manager.NzPage.frameAttachedc                    s     | dd| ddS )NframeId parentFrameId)_onFrameAttachedgeteventself O/var/www/html/Ranjet/env/lib/python3.9/site-packages/pyppeteer/frame_manager.py<lambda>2   s   z'FrameManager.__init__.<locals>.<lambda>zPage.frameNavigatedc                    s     | dS )Nframe)_onFrameNavigatedr&   r'   r)   r+   r,   r-   6       zPage.navigatedWithinDocumentc                    s     | d| dS )Nr"   url)_onFrameNavigatedWithinDocumentr&   r'   r)   r+   r,   r-   8   s   zPage.frameDetachedc                    s     | dS Nr"   )_onFrameDetachedr&   r'   r)   r+   r,   r-   <   r0   zPage.frameStoppedLoadingc                    s     | dS r3   )_onFrameStoppedLoadingr&   r'   r)   r+   r,   r-   >   s   zRuntime.executionContextCreatedc                    s     | dS )Ncontext)_onExecutionContextCreatedr&   r'   r)   r+   r,   r-   B   s   z!Runtime.executionContextDestroyedc                    s     | dS )NexecutionContextId)_onExecutionContextDestroyedr&   r'   r)   r+   r,   r-   E   s   z Runtime.executionContextsClearedc                    s      S N)_onExecutionContextsClearedr'   r)   r+   r,   r-   H   r0   zPage.lifecycleEventc                    s
     | S r:   )_onLifecycleEventr'   r)   r+   r,   r-   J   r0   )super__init___client_pager   _frames
_mainFramedict_contextIdToContexton_handleFrameTree)r*   r   r   r    	__class__r)   r,   r>   (   sD    









zFrameManager.__init__)r(   r!   c                 C   s@   | j |d }|sd S ||d |d  | tjj| d S )Nr"   loaderIdname)rA   r&   r<   emitr   Eventsr   )r*   r(   r.   r+   r+   r,   r<   N   s
    zFrameManager._onLifecycleEvent)r"   r!   c                 C   s0   | j |}|sd S |  | tjj| d S r:   )rA   r&   _onLoadingStoppedrK   r   rL   r   r*   r"   r.   r+   r+   r,   r5   U   s
    z#FrameManager._onFrameStoppedLoading)r   r!   c                 C   sV   |d }d|v r$|  |d |d  | | d|vr:d S |d D ]}| | qBd S )Nr.   parentIdidchildFrames)r%   r/   rF   )r*   r   r.   childr+   r+   r,   rF   \   s    
zFrameManager._handleFrameTreeFramer!   c                 C   s   | j S )zReturn main frame.)rB   r)   r+   r+   r,   	mainFramei   s    zFrameManager.mainFramec                 C   s   t | j S )zReturn all frames.)listrA   valuesr)   r+   r+   r,   framesn   s    zFrameManager.framesc                 C   s   | j |S )z%Return :class:`Frame` of ``frameId``.)rA   r&   )r*   r"   r+   r+   r,   r.   r   s    zFrameManager.frame)r"   r$   r!   c                 C   sF   || j v rd S | j |}t| j||}|| j |< | tjj| d S r:   )rA   r&   rS   r?   rK   r   rL   r   )r*   r"   r$   parentFramer.   r+   r+   r,   r%   v   s    

zFrameManager._onFrameAttachedframePayloadr!   c                 C   s   | d }|r| j}n| j | dd}|s<|s<td|rV|jD ]}| | qF| dd}|r|r| j|jd  ||_nt| j	d |}|| j|< || _|
| | tjj| d S )NrO   rP   r#   zGWe either navigate top level or have old version of the navigated frame)r&   rB   rA   r   rQ   _removeFramesRecursivelypop_idrS   r?   
_navigatedrK   r   rL   r   )r*   r[   ZisMainFramer.   rR   r^   r+   r+   r,   r/   ~   s&    


zFrameManager._onFrameNavigated)r"   r1   r!   c                 C   sB   | j |}|sd S || | tjj| | tjj| d S r:   )rA   r&   _navigatedWithinDocumentrK   r   rL   r   r   )r*   r"   r1   r.   r+   r+   r,   r2      s    
z,FrameManager._onFrameNavigatedWithinDocumentc                 C   s   | j |}|r| | d S r:   )rA   r&   r\   rN   r+   r+   r,   r4      s    zFrameManager._onFrameDetached)contextPayloadr!   c                    sv     dr$ d d r$ d d }nd }|r8j |nd }tj  fdd|}|j d < |rr|| d S )NZauxDataZ	isDefaultr"   c                    s     d | S )NrP   )createJSHandle)objra   r*   r+   r,   r-      r0   z9FrameManager._onExecutionContextCreated.<locals>.<lambda>rP   )r&   rA   r   r?   rD   _setDefaultContext)r*   ra   r"   r.   r6   r+   rd   r,   r7      s    

z'FrameManager._onExecutionContextCreatedr6   r!   c                 C   s.   |j r| j|j  nd }|r*|jr*|d  d S r:   )Z_frameIdrA   Z
_isDefaultre   )r*   r6   r.   r+   r+   r,   _removeContext   s    
zFrameManager._removeContext)r8   r!   c                 C   s*   | j |}|sd S | j |= | | d S r:   )rD   r&   rg   )r*   r8   r6   r+   r+   r,   r9      s
    z)FrameManager._onExecutionContextDestroyedc                 C   s(   | j  D ]}| | q
| j   d S r:   )rD   rW   rg   clear)r*   r6   r+   r+   r,   r;      s    z(FrameManager._onExecutionContextsCleared)	contextIdremoteObjectr!   c                 C   s\   |du rt  }| j|}|s,td| |ddkrNt|| j|| j| S t|| j|S )z@Create JS handle associated to the context id and remote object.Nzmissing context with id = subtypenode)rC   rD   r&   r   r   r?   r@   r   )r*   ri   rj   r6   r+   r+   r,   rb      s    
zFrameManager.createJSHandle)r.   r!   c                 C   sB   |j D ]}| | q|  | j|jd  | tjj	| d S r:   )
rQ   r\   _detachrA   r]   r^   rK   r   rL   r   )r*   r.   rR   r+   r+   r,   r\      s
    
z%FrameManager._removeFramesRecursively)N)"__name__
__module____qualname____doc__r   rL   r   r   r   r>   r<   strr5   rF   propertyr	   rU   r   rX   r.   r%   rC   r/   r2   r4   r7   r   rg   r9   r;   r   rb   r\   __classcell__r+   r+   rG   r,   r      s8   & r   c                   @   s  e Zd ZdZeed  eddddZee ddddZ	ee d	d
dZ
eeedddZddeeeedddZeee dddZed	ddZeee dddZeeeedddZeeeee ddd Zeee dd!d"ZeZeZeZeZeZed	d#d$Zedd%d&d'Ze ed	d(d)Z!e ed	d*d+Z"e ed  d	d,d-Z#e ed  d	d.d/Z$ed	d0d1Z%eed2d3d4Z&eed5d6d7Z'eed5d8d9Z(dgee)edd:d;d<Z*eddd=d>Z+eddd?d@Z,eeee dAdBdCZ-edddDdEZ.dheee)eddFdGdHZ/die0ee1e2f e)eee0e3dIf dJdKdLZ4djee)edId:dMdNZ5dkee)edIdOdPdQZ6dlee)eedIdRdSdTZ7dmeee)edIdUdVdWZ8ed	dXdYZ9e)ddZd[d\Z:edd]d^d_Z;eedd`dadbZ<dd	dcddZ=dd	dedfZ>dS )nrS   z_Frame class.

    Frame objects can be obtained via :attr:`pyppeteer.page.Page.mainFrame`.
    N)r   rY   r"   r!   c                 C   sn   || _ || _d| _d| _|| _d | _dd | _| d  t | _	d| _
t | _t | _| jrj| jj|  d S )Nr#   Fc                 S   s   d S r:   r+   _r+   r+   r,   r-      r0   z Frame.__init__.<locals>.<lambda>)r?   _parentFrame_url	_detachedr^   _documentPromise_contextResolveCallbackre   set
_waitTasks	_loaderId_lifecycleEvents_childFramesadd)r*   r   rY   r"   r+   r+   r,   r>      s    

zFrame.__init__rf   c                    sb   |d ur<  | dd  _  jD ]} jj|  q"n"d  _ jj  _ fdd _ d S )Nc                 S   s   d S r:   r+   ru   r+   r+   r,   r-     r0   z*Frame._setDefaultContext.<locals>.<lambda>c                    s    j | S r:   )_contextPromise
set_result)_contextr)   r+   r,   r-     r0   )	r{   r}   r?   _loopcreate_taskrerunrz   create_futurer   )r*   r6   waitTaskr+   r)   r,   re      s    



zFrame._setDefaultContextrT   c                    s   | j I dH S )zReturn execution context of this frame.

        Return :class:`~pyppeteer.execution_context.ExecutionContext`
        associated to this frame.
        N)r   r)   r+   r+   r,   executionContext  s    zFrame.executionContext)pageFunctionargsr!   c                    s6   |   I dH }|du rtd|j|g|R  I dH S )ziExecute function on this frame.

        Details see :meth:`pyppeteer.page.Page.evaluateHandle`.
        Nzthis frame has no context.)r   r   evaluateHandle)r*   r   r   r6   r+   r+   r,   r     s    zFrame.evaluateHandleF)
force_expr)r   r   r   r!   c                   s<   |   I dH }|du rtd|j|g|R d|iI dH S )zhEvaluate pageFunction on this frame.

        Details see :meth:`pyppeteer.page.Page.evaluate`.
        NExecutionContext is None.r   )r   r   evaluate)r*   r   r   r   r6   r+   r+   r,   r     s    zFrame.evaluate)selectorr!   c                    s"   |   I dH }||I dH }|S )zuGet element which matches `selector` string.

        Details see :meth:`pyppeteer.page.Page.querySelector`.
        N)	_documentquerySelectorr*   r   documentvaluer+   r+   r,   r   )  s    zFrame.querySelectorc                    sX   | j r| j S |  I d H }|d u r*td|dI d H  }|| _ |d u rTtd|S )NzNo context exists.r   zCould not find `document`.)rz   r   r   r   	asElement)r*   r6   r   r+   r+   r,   r   2  s    zFrame._document)
expressionr!   c                    s"   |   I dH }||I dH }|S )zEvaluate the XPath expression.

        If there are no such elements in this frame, return an empty list.

        :arg str expression: XPath string to be evaluated.
        N)r   xpath)r*   r   r   r   r+   r+   r,   r   >  s    zFrame.xpath)r   r   r   r!   c                    s(   |   I dH }|j||g|R  I dH S )zExecute function on element which matches selector.

        Details see :meth:`pyppeteer.page.Page.querySelectorEval`.
        N)r   querySelectorEval)r*   r   r   r   r   r+   r+   r,   r   I  s    zFrame.querySelectorEvalc                    s,   |   I dH }|j||g|R  I dH }|S )zExecute function on all elements which matches selector.

        Details see :meth:`pyppeteer.page.Page.querySelectorAllEval`.
        N)r   JJeval)r*   r   r   r   r   r   r+   r+   r,   querySelectorAllEvalR  s    zFrame.querySelectorAllEvalc                    s"   |   I dH }||I dH }|S )zvGet all elements which matches `selector`.

        Details see :meth:`pyppeteer.page.Page.querySelectorAll`.
        N)r   querySelectorAllr   r+   r+   r,   r   \  s    zFrame.querySelectorAllc                    s   |  d I dH S )z(Get the whole HTML contents of the page.z
() => {
  let retVal = '';
  if (document.doctype)
    retVal = new XMLSerializer().serializeToString(document.doctype);
  if (document.documentElement)
    retVal += document.documentElement.outerHTML;
  return retVal;
}
        N)r   stripr)   r+   r+   r,   contentp  s    zFrame.content)htmlr!   c                    s   d}|  ||I dH  dS )zSet content to this page.zS
function(html) {
  document.open();
  document.write(html);
  document.close();
}
Nr   )r*   r   funcr+   r+   r,   
setContent}  s    zFrame.setContentc                 C   s   | j ddS )zGet frame name._namer#   )__dict__r&   r)   r+   r+   r,   rJ     s    z
Frame.namec                 C   s   | j S )zGet url of the frame.rx   r)   r+   r+   r,   r1     s    z	Frame.urlc                 C   s   | j S )zcGet parent frame.

        If this frame is main frame or detached frame, return ``None``.
        )rw   r)   r+   r+   r,   rY     s    zFrame.parentFramec                 C   s
   t | jS )zGet child frames.)rV   r   r)   r+   r+   r,   rQ     s    zFrame.childFramesc                 C   s   | j S )zXReturn ``True`` if this frame is detached.

        Otherwise return ``False``.
        )ry   r)   r+   r+   r,   
isDetached  s    zFrame.isDetached)filePathr!   c                    s`   t d t|}| }W d   n1 s00    Y  |d|dd7 }| |I dH S )z&[Deprecated] Inject file to the frame.zE`injectFile` method is deprecated. Use `addScriptTag` method instead.Nz/* # sourceURL= {} */
r#   )loggerwarningopenreadformatreplacer   )r*   r   fcontentsr+   r+   r,   
injectFile  s
    

&zFrame.injectFile)optionsr!   c           
   
      s  |   I dH }|du rtdd}d}t|dtr|d }||g}d|v r\||d  z|j| I dH  W S  ty } ztd| d|W Y d}~n
d}~0 0 t|d	tr>t	|d	 }|
 }	W d   n1 s0    Y  |	d
|d	 dd }	||	g}d|v r*||d  |j| I dH  S t|dtr||d g}d|v rt||d  |j| I dH  S tddS )zeAdd script tag to this frame.

        Details see :meth:`pyppeteer.page.Page.addScriptTag`.
        Nr   a  
        async function addScriptUrl(url, type) {
            const script = document.createElement('script');
            script.src = url;
            if (type)
                script.type = type;
            const promise = new Promise((res, rej) => {
                script.onload = res;
                script.onerror = rej;
            });
            document.head.appendChild(script);
            await promise;
            return script;
        }a  
        function addScriptContent(content, type = 'text/javascript') {
            const script = document.createElement('script');
            script.type = type;
            script.text = content;
            let error = null;
            script.onerror = e => error = e;
            document.head.appendChild(script);
            if (error)
                throw error;
            return script;
        }r1   typezLoading script from  failedpathz//# sourceURL={}r   r#   r   <Provide an object with a `url`, `path` or `content` property)r   r   
isinstancer&   rr   appendr   r   r   r   r   r   r   
ValueError)
r*   r   r6   ZaddScriptUrlZaddScriptContentr1   r   er   r   r+   r+   r,   addScriptTag  s@    (&

zFrame.addScriptTagc           	   
      s<  |   I dH }|du rtdd}d}t|dtr|d }z|||I dH  W S  ty } ztd| d|W Y d}~n
d}~0 0 t|dtrt|d }|	 }W d   n1 s0    Y  |d	
|d d
d }|||I dH  S t|dtr0|||d I dH  S tddS )zcAdd style tag to this frame.

        Details see :meth:`pyppeteer.page.Page.addStyleTag`.
        Nr   a  
        async function (url) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = url;
            const promise = new Promise((res, rej) => {
                link.onload = res;
                link.onerror = rej;
            });
            document.head.appendChild(link);
            await promise;
            return link;
        }a  
        async function (content) {
            const style = document.createElement('style');
            style.type = 'text/css';
            style.appendChild(document.createTextNode(content));
            const promise = new Promise((res, rej) => {
                style.onload = res;
                style.onerror = rej;
            });
            document.head.appendChild(style);
            await promise;
            return style;
        }r1   zLoading style from r   r   z/*# sourceURL={}*/r   r#   r   r   )r   r   r   r&   rr   r   r   r   r   r   r   r   r   )	r*   r   r6   ZaddStyleUrlZaddStyleContentr1   r   r   r   r+   r+   r,   addStyleTag  s:    (&zFrame.addStyleTag)r   r   kwargsr!   c                    sL   t ||}| |I dH }|s*td| ||I dH  | I dH  dS )zjClick element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.click`.
        NNo node found for selector: )r   Jr   clickdispose)r*   r   r   r   handler+   r+   r,   r   0  s    
zFrame.clickc                    sD   |  |I dH }|s td| | d|I dH  | I dH  dS )zjFocus element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.focus`.
        Nr   zelement => element.focus())r   r   r   r   r*   r   r   r+   r+   r,   focus=  s
    zFrame.focusc                    s@   |  |I dH }|s td| | I dH  | I dH  dS )ztMouse hover the element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.hover`.
        Nr   )r   r   hoverr   r   r+   r+   r,   r   H  s
    zFrame.hover)r   rW   r!   c                    s@   |D ]&}t |tstd| dt| q| |d|I dH S )zlSelect options and return selected values.

        Details see :meth:`pyppeteer.page.Page.select`.
        zValues must be string. Found z	 of type al  
(element, values) => {
    if (element.nodeName.toLowerCase() !== 'select')
        throw new Error('Element is not a <select> element.');

    const options = Array.from(element.options);
    element.value = undefined;
    for (const option of options) {
        option.selected = values.includes(option.value);
        if (option.selected && !element.multiple)
            break;
    }

    element.dispatchEvent(new Event('input', { 'bubbles': true }));
    element.dispatchEvent(new Event('change', { 'bubbles': true }));
    return options.filter(option => option.selected).map(options => options.value)
}
        N)r   rr   	TypeErrorr   r   )r*   r   rW   r   r+   r+   r,   selectS  s    
zFrame.selectc                    s@   |  |I dH }|s td| | I dH  | I dH  dS )znTap the element which matches the ``selector``.

        Details see :meth:`pyppeteer.page.Page.tap`.
        Nr   )r   r   tapr   r   r+   r+   r,   r   r  s
    z	Frame.tap)r   textr   r   r!   c                    sT   t ||}| |I dH }|du r0td||||I dH  | I dH  dS )zxType ``text`` on the element which matches ``selector``.

        Details see :meth:`pyppeteer.page.Page.type`.
        NzCannot find {} on this page)r   r   r   r   r   r   )r*   r   r   r   r   r   r+   r+   r,   r   }  s    
z
Frame.typeWaitTask)selectorOrFunctionOrTimeoutr   r   r   r!   c                 O   s   t ||}t|ttfr4| jjt|d }|S t|t	sh| jj
 }|tdt	t|  |S |svt|r| j||g|R  S |dr| ||S | ||S )zlWait until `selectorOrFunctionOrTimeout`.

        Details see :meth:`pyppeteer.page.Page.waitFor`.
          zUnsupported target type: z//)r   r   intfloatr?   r   r   asynciosleeprr   r   set_exceptionr   r   r   	is_jsfuncwaitForFunction
startswithwaitForXPathwaitForSelector)r*   r   r   r   r   futr+   r+   r,   waitFor  s.    



zFrame.waitForc                 K   s   t ||}| |d|S )zWait until element which matches ``selector`` appears on page.

        Details see :meth:`pyppeteer.page.Page.waitForSelector`.
        Fr   _waitForSelectorOrXPath)r*   r   r   r   r+   r+   r,   r     s    
zFrame.waitForSelector)r   r   r   r!   c                 K   s   t ||}| |d|S )zWait until element which matches ``xpath`` appears on page.

        Details see :meth:`pyppeteer.page.Page.waitForXPath`.
        Tr   )r*   r   r   r   r+   r+   r,   r     s    
zFrame.waitForXPath)r   r   r   r   r!   c                 O   s@   t ||}|dd}|dd}t| |d||| jjg|R  S )zmWait until the function completes.

        Details see :meth:`pyppeteer.page.Page.waitForFunction`.
        timeout0u  pollingraffunction)r   r&   r   r?   r   )r*   r   r   r   r   r   r   r+   r+   r,   r     s    
zFrame.waitForFunction)selectorOrXPathisXPathr   r   r!   c           
      K   sx   t ||}|dd}t|d}t|d}|s:|r>dnd}d}	t| |	|rTdnd	 d
| d||| jj||||
S )Nr   r   visibleZhiddenr   mutationa  
(selectorOrXPath, isXPath, waitForVisible, waitForHidden) => {
    const node = isXPath
        ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
        : document.querySelector(selectorOrXPath);
    if (!node)
        return waitForHidden;
    if (!waitForVisible && !waitForHidden)
        return node;
    const element = /** @type {Element} */ (node.nodeType === Node.TEXT_NODE ? node.parentElement : node);

    const style = window.getComputedStyle(element);
    const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();
    const success = (waitForVisible === isVisible || waitForHidden === !isVisible)
    return success ? node : null

    function hasVisibleBoundingBox() {
        const rect = element.getBoundingClientRect();
        return !!(rect.top || rect.bottom || rect.width || rect.height);
    }
}
        ZXPathr   z "")r   r&   boolr   r?   r   )
r*   r   r   r   r   r   ZwaitForVisibleZwaitForHiddenr   	predicater+   r+   r,   r     s$    
zFrame._waitForSelectorOrXPathc                    s   |  dI dH S )zGet title of the frame.z() => document.titleNr   r)   r+   r+   r,   title  s    zFrame.titlerZ   c                 C   s.   | dd| _| dd| _| dd| _d S )NrJ   r#   r1   )r&   r   Z_navigationURLrx   )r*   r[   r+   r+   r,   r_     s    zFrame._navigated)r1   r!   c                 C   s
   || _ d S r:   r   )r*   r1   r+   r+   r,   r`     s    zFrame._navigatedWithinDocument)rI   rJ   r!   c                 C   s*   |dkr|| _ | j  n| j| d S )Ninit)r~   r   rh   r   )r*   rI   rJ   r+   r+   r,   r<     s    zFrame._onLifecycleEventc                 C   s   | j d | j d d S )NZDOMContentLoadedload)r   r   r)   r+   r+   r,   rM     s    zFrame._onLoadingStoppedc                 C   s>   | j D ]}|td qd| _| jr4| jj|  d | _d S )Nz+waitForFunction failed: frame got detached.T)r}   	terminater   ry   rw   r   remove)r*   r   r+   r+   r,   rm     s    
zFrame._detach)N)N)N)N)N)N)N)?rn   ro   rp   rq   r   r	   rr   r>   r   re   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ZJxZJevalZJJr   r   r   rs   rJ   r1   rY   rQ   r   r   r   r   rC   r   r   r   r   r   r   r
   r   r   r   r   r   r   r   r   r   r_   r`   r<   rM   rm   r+   r+   r+   r,   rS      s   		

	E< 
		 +rS   c                	   @   sp   e Zd ZdZeeeeeef ee	j
eddddZedddZedd	d
dZddddZddddZdS )r   z>WaitTask class.

    Instance of this class is awaitable.
    N)r.   predicateBodyr   r   r   loopr   r!   c           	         s  t |tr"|dvrVtd| n4t |ttfrH|dkrVtd| ntd| | _| _| _| _|s|t	
|rd| d _nd|  _| _d _d	 _d	 _|j   j  _tttf d d
 fdd}|r j| j _ j   _d S )N)r   r   zUnknown polling: r   z(Cannot poll with non-positive interval: zUnknown polling option: zreturn (z
)(...args)zreturn F)r   r!   c                    s:   t | d I d H  d _ td d|  d d S )Nr   TzWaiting for z failed: timeout zms exceeds.)r   r   _timeoutErrorr   r   )r   r*   r   r+   r,   timer3  s
    z WaitTask.__init__.<locals>.timer)r   rr   r   r   r   _frame_polling_timeoutr   r   r   _predicateBody_args	_runCount_terminatedr   r}   r   r   promiser
   r   _timeoutTimerr   Z_runningTask)	r*   r.   r   r   r   r   r   r   r   r+   r   r,   r>     s4    
zWaitTask.__init__rT   c                 c   s   | j E dH }t|tr||S )zMake this class **awaitable**.N)r   r   	Exception)r*   resultr+   r+   r,   	__await__>  s    
zWaitTask.__await__)errorr!   c                 C   s(   d| _ | j s| j| |   dS )zTerminate this task.TN)r   r   doner   _cleanup)r*   r   r+   r+   r,   r   E  s    
zWaitTask.terminatec              
      s  | j d  }| _ d}d}zJ| j I dH }|du r:td|jt| j| j| jg| j	R  I dH }W n( t
y } z|}W Y d}~n
d}~0 0 | j rdS | js|| j kr|r| I dH  dS z4|s|r| jd|I dH r| I dH  W dS W n. ty"   |dur| I dH  Y dS 0 t|trDd|jd v rDdS t|trdd|jd v rddS |rx| j| n| j| |   dS )zStart polling.   NzNo execution context.zs => !szExecution context was destroyedr   z%Cannot find context with specified id)r   r   r   r   r   waitForPredicatePageFunctionr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r*   ZrunCountsuccessr   r6   r   r+   r+   r,   r   L  sZ    


zWaitTask.rerunc                 C   s(   | j r| js| j  | jj|  d S r:   )r   r   r   cancelr   r}   r   r)   r+   r+   r,   r     s    
zWaitTask._cleanup)rn   ro   rp   rq   rS   rr   r
   r   r   r   AbstractEventLoopr   r>   r   r   r   r   r   r   r+   r+   r+   r,   r     s   )9r   a  
async function waitForPredicatePageFunction(predicateBody, polling, timeout, ...args) {
  const predicate = new Function('...args', predicateBody);
  let timedOut = false;
  if (timeout)
    setTimeout(() => timedOut = true, timeout);
  if (polling === 'raf')
    return await pollRaf();
  if (polling === 'mutation')
    return await pollMutation();
  if (typeof polling === 'number')
    return await pollInterval(polling);

  /**
   * @return {!Promise<*>}
   */
  function pollMutation() {
    const success = predicate.apply(null, args);
    if (success)
      return Promise.resolve(success);

    let fulfill;
    const result = new Promise(x => fulfill = x);
    const observer = new MutationObserver(mutations => {
      if (timedOut) {
        observer.disconnect();
        fulfill();
      }
      const success = predicate.apply(null, args);
      if (success) {
        observer.disconnect();
        fulfill(success);
      }
    });
    observer.observe(document, {
      childList: true,
      subtree: true,
      attributes: true
    });
    return result;
  }

  /**
   * @return {!Promise<*>}
   */
  function pollRaf() {
    let fulfill;
    const result = new Promise(x => fulfill = x);
    onRaf();
    return result;

    function onRaf() {
      if (timedOut) {
        fulfill();
        return;
      }
      const success = predicate.apply(null, args);
      if (success)
        fulfill(success);
      else
        requestAnimationFrame(onRaf);
    }
  }

  /**
   * @param {number} pollInterval
   * @return {!Promise<*>}
   */
  function pollInterval(pollInterval) {
    let fulfill;
    const result = new Promise(x => fulfill = x);
    onTimeout();
    return result;

    function onTimeout() {
      if (timedOut) {
        fulfill();
        return;
      }
      const success = predicate.apply(null, args);
      if (success)
        fulfill(success);
      else
        setTimeout(onTimeout, pollInterval);
    }
  }
}
)+rq   r   collectionsr   loggingtypesr   typingr   r   r   r   r   r	   r
   r   Zpyeer   Z	pyppeteerr   Zpyppeteer.connectionr   Zpyppeteer.element_handler   Zpyppeteer.errorsr   Zpyppeteer.execution_contextr   r   r   r   r   Zpyppeteer.utilr   r   	getLoggerrn   r   r   objectrS   r   r  r+   r+   r+   r,   <module>   s4   $
 I    .|