o
    M,hK                     @   s   d dl Z d dlZd dlmZ d dlmZmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ G dd	 d	ZG d
d dZeG dd dZeG dd dZeG dd dZG dd dZG dd dZG dd dZG dd dZdS )    N)	dataclass)AnyOptional)WebDriverException)command_builder)LogEntryAdded)Sessionc                   @   s   e Zd ZdZdZdZdS )ResultOwnershipz/Represents the possible result ownership types.nonerootN)__name__
__module____qualname____doc__NONEROOT r   r   q/var/www/www-root/data/www/bot.pdev.uz/venv/lib/python3.10/site-packages/selenium/webdriver/common/bidi/script.pyr	      s    r	   c                   @   s0   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
S )	RealmTypez$Represents the possible realm types.windowzdedicated-workerzshared-workerzservice-workerworkerzpaint-workletzaudio-workletworkletN)r   r   r   r   WINDOWDEDICATED_WORKERSHARED_WORKERSERVICE_WORKERWORKERPAINT_WORKLETAUDIO_WORKLETWORKLETr   r   r   r   r   $   s    r   c                   @   sh   e Zd ZU dZeed< eed< eed< dZee ed< dZee ed< e	de
eef d	d fd
dZdS )	RealmInfoz%Represents information about a realm.realmorigintypeNcontextsandboxjsonreturnc                 C   sZ   d|vrt dd|vrt dd|vrt d| |d |d |d |d|dd	S )
zCreates a RealmInfo instance from a dictionary.

        Parameters:
        -----------
            json: A dictionary containing the realm information.

        Returns:
        -------
            RealmInfo: A new instance of RealmInfo.
        r!   z+Missing required field 'realm' in RealmInfor"   z,Missing required field 'origin' in RealmInfor#   z*Missing required field 'type' in RealmInfor$   r%   )r!   r"   r#   r$   r%   
ValueErrorgetclsr&   r   r   r   	from_json;   s   zRealmInfo.from_json)r   r   r   r   str__annotations__r$   r   r%   classmethoddictr   r-   r   r   r   r   r    1   s   
  r    c                   @   sH   e Zd ZU dZeed< dZee ed< ede	ee
f dd fddZdS )	Sourcez*Represents the source of a script message.r!   Nr$   r&   r'   c                 C   s&   d|vrt d| |d |ddS )zCreates a Source instance from a dictionary.

        Parameters:
        -----------
            json: A dictionary containing the source information.

        Returns:
        -------
            Source: A new instance of Source.
        r!   z(Missing required field 'realm' in Sourcer$   )r!   r$   r(   r+   r   r   r   r-   ^   s   zSource.from_json)r   r   r   r   r.   r/   r$   r   r0   r1   r   r-   r   r   r   r   r2   W   s   
  r2   c                   @   s`   e Zd ZU dZeed< eed< dZee ed< dZ	ee ed< e
deeef dd fd	d
ZdS )EvaluateResultz+Represents the result of script evaluation.r#   r!   Nresultexception_detailsr&   r'   c                 C   sD   d|vrt dd|vrt d| |d |d |d|ddS )a  Creates an EvaluateResult instance from a dictionary.

        Parameters:
        -----------
            json: A dictionary containing the evaluation result.

        Returns:
        -------
            EvaluateResult: A new instance of EvaluateResult.
        r!   z0Missing required field 'realm' in EvaluateResultr#   z/Missing required field 'type' in EvaluateResultr4   exceptionDetails)r#   r!   r4   r5   r(   r+   r   r   r   r-   |   s   zEvaluateResult.from_json)r   r   r   r   r.   r/   r4   r   r1   r5   r0   r   r-   r   r   r   r   r3   s   s   
  r3   c                   @   sH   e Zd ZdZdZdededefddZe	deee
f d	d fd
dZdS )ScriptMessagez"Represents a script message event.script.messagechanneldatasourcec                 C   s   || _ || _|| _d S Nr9   r:   r;   )selfr9   r:   r;   r   r   r   __init__   s   
zScriptMessage.__init__r&   r'   c                 C   sP   d|vrt dd|vrt dd|vrt d| |d |d t|d dS )a  Creates a ScriptMessage instance from a dictionary.

        Parameters:
        -----------
            json: A dictionary containing the script message.

        Returns:
        -------
            ScriptMessage: A new instance of ScriptMessage.
        r9   z1Missing required field 'channel' in ScriptMessager:   z.Missing required field 'data' in ScriptMessager;   z0Missing required field 'source' in ScriptMessager=   )r)   r2   r-   r+   r   r   r   r-      s   zScriptMessage.from_jsonN)r   r   r   r   event_classr.   r1   r2   r?   r0   r   r-   r   r   r   r   r7      s     r7   c                   @   s@   e Zd ZdZdZdefddZedee	e
f dd fdd	Zd
S )RealmCreatedz!Represents a realm created event.script.realmCreated
realm_infoc                 C   
   || _ d S r<   rC   )r>   rC   r   r   r   r?         
zRealmCreated.__init__r&   r'   c                 C   s   | t |dS )a  Creates a RealmCreated instance from a dictionary.

        Parameters:
        -----------
            json: A dictionary containing the realm created event.

        Returns:
        -------
            RealmCreated: A new instance of RealmCreated.
        rE   r    r-   r+   r   r   r   r-      s   zRealmCreated.from_jsonN)r   r   r   r   r@   r    r?   r0   r1   r.   r   r-   r   r   r   r   rA           rA   c                   @   s@   e Zd ZdZdZdefddZedeee	f dd fdd	Z
d
S )RealmDestroyedz#Represents a realm destroyed event.script.realmDestroyedr!   c                 C   rD   r<   r!   )r>   r!   r   r   r   r?      rF   zRealmDestroyed.__init__r&   r'   c                 C   s   d|vrt d| |d dS )a  Creates a RealmDestroyed instance from a dictionary.

        Parameters:
        -----------
            json: A dictionary containing the realm destroyed event.

        Returns:
        -------
            RealmDestroyed: A new instance of RealmDestroyed.
        r!   z0Missing required field 'realm' in RealmDestroyedrK   )r)   r+   r   r   r   r-      s   zRealmDestroyed.from_jsonN)r   r   r   r   r@   r.   r?   r0   r1   r   r-   r   r   r   r   rI      rH   rI   c                   @   s  e Zd ZdZddddZd<ddZd	d
 Zdd Zdd ZeZ	de
de
fddZde
ddfddZde
defddZdefddZ				d=de
deeee
ef   deee
  deee
  dee
 de
fdd Zde
ddfd!d"Zd#ee
 d$eddfd%d&Z					'd>de
d(ed$edeee  d)ee
 d*ee d+ee d,edefd-d.Z			'd?d/e
d$ed(ed)ee
 d*ee d,edefd0d1Z		d@d2ee
 d3ee
 dee fd4d5Zd6d7 Zd8d9 Zd:d; ZdS )AScriptz)BiDi implementation of the script module.r8   rB   rJ   )messagerealm_createdrealm_destroyedNc                 C   s"   || _ || _d| _i | _i | _d S NF)conndriverlog_entry_subscribedsubscriptions	callbacks)r>   rQ   rR   r   r   r   r?      s
   
zScript.__init__c                 C      |    | jt| d|S )Nconsole_subscribe_to_log_entriesrQ   add_callbackr   _handle_log_entryr>   handlerr   r   r   add_console_message_handler      z"Script.add_console_message_handlerc                 C   rV   )N
javascriptrX   r\   r   r   r   add_javascript_error_handler   r_   z#Script.add_javascript_error_handlerc                 C   s   | j t| |   d S r<   )rQ   remove_callbackr   _unsubscribe_from_log_entries)r>   idr   r   r   remove_console_message_handler  s   z%Script.remove_console_message_handlerscriptr'   c                 C   s
   |  |S )zPins a script to the current browsing context.

        Parameters:
        -----------
            script: The script to pin.

        Returns:
        -------
            str: The ID of the pinned script.
        )_add_preload_script)r>   rf   r   r   r   pin
  s   
z
Script.pin	script_idc                 C   s   |  | dS )zUnpins a script from the current browsing context.

        Parameters:
        -----------
            script_id: The ID of the pinned script to unpin.
        N)_remove_preload_script)r>   ri   r   r   r   unpin  s   zScript.unpinc           	      G   s   | j du r	td| j j}g }|D ]
}|| | qd|i}| j|d||r)|ndd}|jdkr<|jdur:|jS i S d}|jrcd|jv rT|d	|jd  7 }t|d
|jv rc|d	|jd
  7 }t|)a  Executes a script in the current browsing context.

        Parameters:
        -----------
            script: The script function to execute.
            *args: Arguments to pass to the script function.

        Returns:
        -------
            dict: The result value from the script execution.

        Raises:
        ------
            WebDriverException: If the script execution fails.
        Nz1Driver reference is required for script executionr$   T)function_declarationawait_promisetarget	argumentssuccesszError while executing scripttextz: rM   )	rR   r   current_window_handleappend_Script__convert_to_local_value_call_functionr#   r4   r5   )	r>   rf   argsbrowsing_context_idro   argrn   r4   error_messager   r   r   execute   s(   



zScript.executec                    s  |du rddiS t |trd|dS t |ttfrht |trLt|r(dddS t|r;|dkr6dd	dS dd
dS |dkrLtd|dk rLdddS d}t |trc||ks\|| k rcdt|dS d|dS t |trrd|dS t |t	j	rd|j
du r| d dS | dS t |t	jrt	j	|t	jjjt	jjd}d| dS t |trd fdd|D dS t |ttfrd fdd|D dS t |trd fdd| D dS dt|dS )zD
        Converts a Python value to BiDi LocalValue format.
        Nr#   nullboolean)r#   valuenumberNaNr   Infinityz	-Infinityg        g      ?z-0l    bigintstringdateZ)tzinfosetc                       g | ]}  |qS r   rt   .0itemr>   r   r   
<listcomp>p      z3Script.__convert_to_local_value.<locals>.<listcomp>arrayc                    r   r   r   r   r   r   r   r   r  r   objectc                    s$   g | ]\}}  |  |gqS r   r   )r   kvr   r   r   r   v  s    )
isinstanceboolintfloatmathisnanisinfcopysignr.   datetimer   	isoformatr   combinetimeminreplacetimezoneutcr   listtupler1   items)r>   r}   JS_MAX_SAFE_INTEGERdtr   r   r   __convert_to_local_valueL  sH   











(


zScript.__convert_to_local_valuerl   ro   contextsuser_contextsr%   c                 C   sz   |dur|durt dd|i}|dur||d< |dur ||d< |dur(||d< |dur0||d< | jtd|}|d	 S )
aM  Adds a preload script.

        Parameters:
        -----------
            function_declaration: The function declaration to preload.
            arguments: The arguments to pass to the function.
            contexts: The browsing context IDs to apply the script to.
            user_contexts: The user context IDs to apply the script to.
            sandbox: The sandbox name to apply the script to.

        Returns:
        -------
            str: The preload script ID.

        Raises:
        ------
            ValueError: If both contexts and user_contexts are provided.
        Nz.Cannot specify both contexts and user_contextsfunctionDeclarationro   r   userContextsr%   zscript.addPreloadScriptrf   )r)   rQ   rz   r   )r>   rl   ro   r   r   r%   paramsr4   r   r   r   rg     s   zScript._add_preload_scriptc                 C   s   d|i}| j td| dS )zRemoves a preload script.

        Parameters:
        -----------
            script_id: The preload script ID to remove.
        rf   zscript.removePreloadScriptNrQ   rz   r   )r>   ri   r   r   r   r   rj     s   zScript._remove_preload_scripthandlesrn   c                 C   s    ||d}| j td| dS )zDisowns the given handles.

        Parameters:
        -----------
            handles: The handles to disown.
            target: The target realm or context.
        )r   rn   zscript.disownNr   )r>   r   rn   r   r   r   r   _disown  s   	zScript._disownFrm   result_ownershipserialization_optionsthisuser_activationc	                 C   sj   ||||d}	|dur||	d< |dur||	d< |dur||	d< |dur'||	d< | j td|	}
t|
S )a  Calls a provided function with given arguments in a given realm.

        Parameters:
        -----------
            function_declaration: The function declaration to call.
            await_promise: Whether to await promise resolution.
            target: The target realm or context.
            arguments: The arguments to pass to the function.
            result_ownership: The result ownership type.
            serialization_options: The serialization options.
            this: The 'this' value for the function call.
            user_activation: Whether to trigger user activation.

        Returns:
        -------
            EvaluateResult: The result of the function call.
        )r   awaitPromisern   userActivationNro   resultOwnershipserializationOptionsr   zscript.callFunctionrQ   rz   r   r3   r-   )r>   rl   rm   rn   ro   r   r   r   r   r   r4   r   r   r   ru     s   
zScript._call_function
expressionc           	      C   sJ   ||||d}|dur||d< |dur||d< | j td|}t|S )a&  Evaluates a provided script in a given realm.

        Parameters:
        -----------
            expression: The script expression to evaluate.
            target: The target realm or context.
            await_promise: Whether to await promise resolution.
            result_ownership: The result ownership type.
            serialization_options: The serialization options.
            user_activation: Whether to trigger user activation.

        Returns:
        -------
            EvaluateResult: The result of the script evaluation.
        )r   rn   r   r   Nr   r   zscript.evaluater   )	r>   r   rn   rm   r   r   r   r   r4   r   r   r   	_evaluate  s   
zScript._evaluater$   r#   c                 C   sH   i }|dur
||d< |dur||d< | j td|}dd |d D S )a*  Returns a list of all realms, optionally filtered.

        Parameters:
        -----------
            context: The browsing context ID to filter by.
            type: The realm type to filter by.

        Returns:
        -------
            List[RealmInfo]: A list of realm information.
        Nr$   r#   zscript.getRealmsc                 S   s   g | ]}t |qS r   rG   )r   r!   r   r   r   r   0  r   z&Script._get_realms.<locals>.<listcomp>realmsr   )r>   r$   r#   r   r4   r   r   r   _get_realms  s   zScript._get_realmsc                 C   s2   | j st| j}| j|tj d| _ d S d S )NT)rS   r   rQ   rz   	subscriber   r@   r>   sessionr   r   r   rY   2  s
   

z Script._subscribe_to_log_entriesc                 C   sD   | j rtj| jjvr t| j}| j|tj d| _ d S d S d S rP   )rS   r   r@   rQ   rU   r   rz   unsubscriber   r   r   r   rc   8  s
   

z$Script._unsubscribe_from_log_entriesc                    s    fdd}|S )Nc                    s   | j kr |  d S d S r<   )type_)	log_entryr]   r#   r   r   r[   ?  s   
z3Script._handle_log_entry.<locals>._handle_log_entryr   )r>   r#   r]   r[   r   r   r   r[   >  s   zScript._handle_log_entryr<   )NNNN)NNNNF)NNF)NN)r   r   r   r   EVENTSr?   r^   ra   re   remove_javascript_error_handlerr.   rh   rk   r1   rz   rt   r   r   r   rg   rj   r   r   r3   ru   r   r    r   rY   rc   r[   r   r   r   r   rL      s    
		,6


+

	

4
)
rL   )r   r   dataclassesr   typingr   r   selenium.common.exceptionsr   %selenium.webdriver.common.bidi.commonr   "selenium.webdriver.common.bidi.logr   &selenium.webdriver.common.bidi.sessionr   r	   r   r    r2   r3   r7   rA   rI   rL   r   r   r   r   <module>   s(   %!$