
    osj                       d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlmZ e	j                  dk\  rd dlmZ nd dlmZ d dlZd dlZd dlZd dlmZmZ d dlmZ dd	lmZ dd
lmZmZmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z, ejZ                  r(d dl.m/Z/m0Z0 ddlm1Z1m2Z2m3Z3 ddl m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ejx                  d   Z= ej                  d      Z> ej                  d      Z? eddd      Z@ eddd      ZA G d deB      ZC G d deB      ZD G d  d      ZE G d! dej                        ZG	 	 	 	 d*d"ZH G d# d$ej                  e@         ZJej                  	 d+eeeeddddeeedd%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,d&       ZL G d' d(ej                  eA         ZMej                  	 d+eeeeddddeeedd%	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d-d)       ZOy).    )annotationsN)TracebackType)      )TypeVar)MemoryObjectReceiveStreamMemoryObjectSendStream)CloseReason   )USE_CLIENT_DEFAULT)'DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS&DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDSDEFAULT_MAX_MESSAGE_SIZE_BYTESDEFAULT_QUEUE_SIZE)Headers   )HTTPXWSExceptionWebSocketDisconnectWebSocketInvalidTypeReceivedWebSocketNetworkErrorWebSocketUpgradeError)AsyncPingManagerPingManager)ASGIWebSocketAsyncNetworkStream)AsyncNetworkStreamNetworkStream)AsyncClientClientUseClientDefault)Response)	AuthTypesCookieTypesHeaderTypesQueryParamTypesRequestExtensionsTimeoutTypestextbinaryTaskFunction
TaskResultSyncSessionWebSocketSession)bounddefaultAsyncSessionAsyncWebSocketSessionc                      e Zd Zy)ShouldCloseN__name__
__module____qualname__     I/root/.hermes/venv/lib/python3.12/site-packages/httpx2/websockets/_api.pyr3   r3   @       r9   r3   c                      e Zd Zy)EndOfStreamNr4   r8   r9   r:   r=   r=   D   r;   r9   r=   c                     e Zd ZU dZded<   ded<   eeeedd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ		 	 dd	Z
dd
Z	 	 	 	 	 	 	 	 ddZdddZd dZd!dZd"dZd#d$dZd%d&dZd%d'dZd%d(dZd)d*dZd+d,dZd-dZd%d.dZ	 	 	 	 	 	 	 	 d/dZd0dZy)1r-   a  
    Sync context manager representing an opened WebSocket session.

    Attributes:
        subprotocol (typing.Optional[str]):
            Optional protocol that has been accepted by the server.
        response (Response | None):
            The webSocket handshake response.
    
str | NonesubprotocolResponse | NoneresponseNmax_message_size_bytes
queue_sizekeepalive_ping_interval_secondskeepalive_ping_timeout_secondsrB   c                  || _         t        j                  j                  t        j                  j
                        | _        || _        | j                  +| j                  j                  j                  d      | _	        nd | _	        t        j                  |      | _        t               | _        t        j                          | _        t        j$                         | _        d | _        d | _        || _        || _        || _        || _        y Nsec-websocket-protocol)streamwsproto
connection
ConnectionConnectionTypeCLIENTrB   headersgetr@   queueQueue_eventsr   _ping_manager	threadingEvent_should_closeLock_write_lock_should_close_task	_executor_max_message_size_bytes_queue_size _keepalive_ping_interval_seconds_keepalive_ping_timeout_secondsselfrK   rD   rE   rF   rG   rB   s          r:   __init__zWebSocketSession.__init__V   s     !,,778N8N8U8UV ==$#}}44889QRD#DMR[[YcMd(]&__.$>>+JNGK'=$%0O-/M,r9   c                   | j                   Wt        j                  j                         | _        | j                  j                  | j                  j                        | _         | j                  J | j                  | j                   fS N)r\   
concurrentfuturesThreadPoolExecutorr]   submitrY   waitrc   s    r:   _get_executor_should_close_taskz0WebSocketSession._get_executor_should_close_tasku   sn     ""*'//BBDDN&*nn&;&;D<N<N<S<S&TD#~~)))~~t6666r9   c                n   t        j                  | j                  | j                  f      | _        | j                  j                          d | _        | j                  Vt        j                  | j                  | j                  | j                  f      | _        | j                  j                          | S )N)targetargs)
rW   Thread_background_receiver^   _background_receive_taskstart_background_keepalive_ping_taskr`   _background_keepalive_pingra   rl   s    r:   	__enter__zWebSocketSession.__enter__~   s    (1(8(8++43O3O2Q)
% 	%%++-HL,00<3<3C3C6699884D0 00668r9   c                    | j                          | j                  j                          | j                  | j                  j                          y y rf   )closers   joinru   )rc   exc_typeexctbs       r:   __exit__zWebSocketSession.__exit__   sB     	

%%**,//;00557 <r9   c                    | j                   j                  |      \  }}t        j                  j	                  |      }| j                  |       |S )a?  
        Send a Ping message.

        Args:
            payload:
                Payload to attach to the Ping event.
                Internally, it's used to track this specific event.
                If left empty, a random one will be generated.

        Returns:
            An event that can be used to wait for the corresponding Pong response.

        Examples:
            Send a Ping and wait for the Pong

                pong_callback = ws.ping()
                # Will block until the corresponding Pong is received.
                pong_callback.wait()
        rV   createrL   eventsPingsendrc   payloadping_idcallbackevents        r:   pingzWebSocketSession.ping   sD    ( !..55g>##G,		%r9   c                @   ddl }	 | j                  j                  |      }| j                  5  | j                  j                  |       ddd       y# 1 sw Y   yxY w# |j                  $ r0}| j                  t        j                  d       t               |d}~ww xY w)a  
        Send an Event message.

        Mainly useful to send events that are not supported by the library.
        Most of the time, [ping()][httpx_ws.WebSocketSession.ping],
        [send_text()][httpx_ws.WebSocketSession.send_text],
        [send_bytes()][httpx_ws.WebSocketSession.send_bytes]
        and [send_json()][httpx_ws.WebSocketSession.send_json] are preferred.

        Args:
            event: The event to send.

        Raises:
            WebSocketNetworkError: A network error occured.

        Examples:
            Send an event.

                event = wsproto.events.Message(b"Hello!")
                ws.send(event)
        r   NStream write error	httpcore2rM   r   r[   rK   write
WriteErrorry   r
   INTERNAL_ERRORr   rc   r   r   dataes        r:   r   zWebSocketSession.send   s    , 		1??''.D!! (!!$'( ( (## 	1JJ{113GH')q0	1s4   'A A	A AA A B-+BBc                f    t         j                  j                  |      }| j                  |       y)a  
        Send a text message.

        Args:
            data: The text to send.

        Raises:
            WebSocketNetworkError: A network error occured.

        Examples:
            Send a text message.

                ws.send_text("Hello!")
        r   NrL   r   TextMessager   rc   r   r   s      r:   	send_textzWebSocketSession.send_text   s'     ***5		%r9   c                f    t         j                  j                  |      }| j                  |       y)a  
        Send a bytes message.

        Args:
            data: The data to send.

        Raises:
            WebSocketNetworkError: A network error occured.

        Examples:
            Send a bytes message.

                ws.send_bytes(b"Hello!")
        r   NrL   r   BytesMessager   r   s      r:   
send_byteszWebSocketSession.send_bytes   s'     +++6		%r9   c                    |dv sJ t        j                  |      }|dk(  r| j                  |       y| j                  |j	                  d             y)a  
        Send JSON data.

        Args:
            data:
                The data to send. Must be serializable by [json.dumps][json.dumps].
            mode:
                The sending mode. Should either be `'text'` or `'bytes'`.

        Raises:
            WebSocketNetworkError: A network error occured.

        Examples:
            Send JSON data.

                data = {"message": "Hello!"}
                ws.send_json(data)
        r'   r(   utf-8Njsondumpsr   r   encoderc   r   modeserialized_datas       r:   	send_jsonzWebSocketSession.send_json   sK    & ))))**T*6>NN?+OOO227;<r9   c                2   	 | j                   j                  d|      }t        |t              r|t        |t        j                  j                        r t        |j                  |j                        |S # t        j                  $ r}t        |d}~ww xY w)aG  
        Receive an event from the server.

        Mainly useful to receive raw [wsproto.events.Event][wsproto.events.Event].
        Most of the time, [receive_text()][httpx_ws.WebSocketSession.receive_text],
        [receive_bytes()][httpx_ws.WebSocketSession.receive_bytes],
        and [receive_json()][httpx_ws.WebSocketSession.receive_json] are preferred.

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.

        Returns:
            A raw [wsproto.events.Event][wsproto.events.Event].

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.

        Examples:
            Wait for an event until one is available.

                try:
                    event = ws.receive()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for an event for 2 seconds.

                try:
                    event = ws.receive(timeout=2.)
                except TimeoutError:
                    print("No event received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        T)blocktimeoutN)rU   rR   rS   EmptyTimeoutError
isinstancer   rL   r   CloseConnectionr   codereason)rc   r   r   r   s       r:   receivezWebSocketSession.receive  s    N	&LL$$4$AE e-.KeW^^;;<%ejj%,,?? {{ 	&A%	&s   A7 7B
BBc                    | j                  |      }t        |t        j                  j                        r|j
                  S t        |      )a(  
        Receive text from the server.

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.

        Returns:
            Text data.

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.
            WebSocketInvalidTypeReceived: The received event was not a text message.

        Examples:
            Wait for text until available.

                try:
                    text = ws.receive_text()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for text for 2 seconds.

                try:
                    event = ws.receive_text(timeout=2.)
                except TimeoutError:
                    print("No text received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        r   r   rL   r   r   r   r   rc   r   r   s      r:   receive_textzWebSocketSession.receive_textD  s<    F W%eW^^778::*511r9   c                    | j                  |      }t        |t        j                  j                        rt        |j                        S t        |      )a.  
        Receive bytes from the server.

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.

        Returns:
            Bytes data.

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.
            WebSocketInvalidTypeReceived: The received event was not a bytes message.

        Examples:
            Wait for bytes until available.

                try:
                    data = ws.receive_bytes()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for bytes for 2 seconds.

                try:
                    data = ws.receive_bytes(timeout=2.)
                except TimeoutError:
                    print("No data received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        r   r   rL   r   r   bytesr   r   r   s      r:   receive_byteszWebSocketSession.receive_bytesl  sA    F W%eW^^889$$*511r9   c                    |dv sJ |dk(  r| j                  |      }n|dk(  r| j                  |      }t        j                        S )a  
        Receive JSON data from the server.

        The received data should be parseable by [json.loads][json.loads].

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.
            mode:
                Receive mode. Should either be `'text'` or `'bytes'`.

        Returns:
            Parsed JSON data.

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.
            WebSocketInvalidTypeReceived: The received event
                didn't correspond to the specified mode.

        Examples:
            Wait for data until available.

                try:
                    data = ws.receive_json()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for data for 2 seconds.

                try:
                    data = ws.receive_json(timeout=2.)
                except TimeoutError:
                    print("No data received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        r'   r(   r)   r   r   r   loadsrc   r   r   r   s       r:   receive_jsonzWebSocketSession.receive_json  sR    P ))))6>$$W-DX%%g.Dzz$r9   c                   ddl }| j                  j                          | j                  | j                  j	                  d       | j
                  j                  t        j
                  j                  j                  t        j
                  j                  j                  hvrlt        j                  j                  ||      }| j
                  j                  |      }	 | j                  5  | j                  j!                  |       ddd       | j                  j%                          y# 1 sw Y   $xY w# |j"                  $ r Y 8w xY w)a  
        Close the WebSocket session.

        Internally, it'll send the
        [CloseConnection][wsproto.events.CloseConnection] event.

        *This method is automatically called when exiting the context manager.*

        Args:
            code:
                The integer close code to indicate why the connection has closed.
            reason:
                Additional reasoning for why the connection has closed.

        Examples:
            Close the WebSocket session.

                ws.close()
        r   NF)r   rY   setr]   shutdownrM   staterL   ConnectionStateLOCAL_CLOSINGCLOSEDr   r   r   r[   rK   r   r   ry   rc   r   r   r   r   r   s         r:   ry   zWebSocketSession.close  s    ( 	 >>%NN##E*??  ..<<..55)
 
 NN224@E??''.D%% ,KK%%d+, 		, ,'' s*    D7 ,D+D7 +D40D7 7E	E	c                   ddl }d}	 | j                  j                         sB| j                  | j                  |      }| j
                  j                  |       | j
                  j                         D ]  }t        |t        j                  j                        rZ| j
                  j                  |j                               }| j                  5  | j                  j                  |       ddd       t        |t        j                  j                         r&| j"                  j%                  |j&                         t        |t        j                  j(                        r| j                  j+                          t        |t        j                  j,                        r|j.                  s||j0                  }nk||j0                  z  }n[|| j2                  j5                  |       n=t7        |      } |||j0                  z         }d}| j2                  j5                  |       | j2                  j5                  |        | j                  j                         sAyy# 1 sw Y   {xY w# |j8                  |j:                  t<        f$ rF | j?                  t@        jB                  d       | j2                  j5                  tE                      Y ytF        $ r Y yw xY w)ao  
        Background thread listening for data from the server.

        Internally, it'll:

        * Answer to Ping events.
        * Acknowledge Pong events.
        * Put other events in the [_events][_events]
        queue that'll eventually be consumed by the user.

        Args:
            max_bytes: The maximum chunk size to read at each iteration.
        r   NStream error)$r   rY   is_set_wait_until_closed_read_streamrM   receive_datar   r   rL   r   r   rB   r[   rK   r   PongrV   ackr   r   r   Messagemessage_finishedr   rU   puttype	ReadErrorr   r=   ry   r
   r   r   r3   rc   	max_bytesr   partial_message_bufferr   r   
event_typefull_message_events           r:   rr   z$WebSocketSession._background_receive  s5    	59%	((//1..t/@/@)L,,T2!__335 ,E!%)<)<=#33ENN4DE!-- 4 KK--d34 !%)<)<=**..u}}= !%)G)GH**..0!%)?)?@$555=9> 6 6%** D 63; LL,,U3 *.eJ1;<RUZU_U_<_1`.592 LL,,-?@ LL$$U+9, ((//114 44 ##Y%9%9;G 	6JJ{11>BLL245 		s2   C	I3 I&-E5I3 &I0	+I3 3A#K#K#"K#c                   	 | j                   j                         s| j                  | j                   j                  |      }|r
t	               | j                         }|a| j                  |j                  |      }|sC| j                  t        j                  d       | j                  j                  t                      | j                   j                         sy y # t        $ r Y y w xY wNzKeepalive ping timeout)rY   r   r   rk   r3   r   ry   r
   r   rU   r   r   )rc   interval_secondstimeout_secondsshould_closepong_callbackacknowledgeds         r:   rv   z+WebSocketSession._background_keepalive_ping"  s    	((//1#66t7I7I7N7NP`a%-' $		".#'#:#:=;M;M#_L'

;#=#=?WX(()>)@A ((//1  		s   CC 	C*)C*c                V   	 | j                         \  }} |j                  |g|i |}t        j                  j	                  ||ft        j                  j
                        \  }}||v r
t               ||v sJ |j                         }	|	S # t        $ r}
t               |
d }
~
ww xY w)N)return_when)	rm   rj   rg   rh   rk   FIRST_COMPLETEDr3   resultRuntimeError)rc   callablerp   kwargsexecutorshould_close_task	todo_taskdone_r   r   s              r:   r   z#WebSocketSession._wait_until_closed1  s    	(*.*N*N*P'H''B4B6BI !((---.&..>> . GD! !D(!m#$$$%%'F  	'-Q&	's   )B 	B(B##B(c                Z    | j                   j                  |      }|dk(  r
t               |S Nr9   rK   readr=   rc   r   r   s      r:   r   zWebSocketSession._read_streamD  s*    {{	*3;-r9   )rK   r   rD   intrE   r   rF   float | NonerG   r   rB   rA   returnNone)r   zMtuple[concurrent.futures.ThreadPoolExecutor, concurrent.futures.Future[bool]])r   r-   )r{   ztype[BaseException] | Noner|   zBaseException | Noner}   zTracebackType | Noner   r   r9   )r   r   r   zthreading.Eventr   wsproto.events.Eventr   r   r   strr   r   r   r   r   r   r(   r   
typing.Anyr   JSONModer   r   rf   r   r   r   r   r   r   r   r   r   r   r   r   Nr(   r   r   r   r   r   r   i  Nr   r   r   r?   r   r   r   r   r   r   r   floatr   r   r   r   )r   z typing.Callable[..., TaskResult]rp   r   r   r   r   r+   r   r   r   r   )r5   r6   r7   __doc____annotations__r   r   r   r   rd   rm   rw   r~   r   r   r   r   r   r   r   r   r   ry   rr   rv   r   r   r8   r9   r:   r-   r-   H   s"     'E,8_7]$(NN !$	N
 N *6N )5N "N 
N>7	V7&	8,	8 "	8 !		8
 
	821@$$=4/b&2P&2P. `$L6p8AKWa	&r9   c                     e Zd ZU dZded<   ded<   ded<   ded	<   eeeed
d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	e
j                  dd       ZdddZddZd dZd!dZd"d#dZd$d%dZd$d&dZd$d'dZd(d)dZd*d+dZd,dZd$d-dZd.dZy
)/r1   a  
    Async context manager representing an opened WebSocket session.

    Internally, this session uses an anyio task group to manage background tasks.
    As a result, exceptions that are not caught inside the context manager
    and propagate out of the `async with` block will be wrapped
    in an [ExceptionGroup][ExceptionGroup].

    To handle them, use the `except*` syntax:

        async with AsyncWebSocketSession(stream) as ws:
            try:
                data = await ws.receive_text()
            except WebSocketDisconnect:
                # Caught inside the context manager: plain exception.
                print("Connection closed")

        # If not caught inside:
        try:
            async with AsyncWebSocketSession(stream) as ws:
                data = await ws.receive_text()
        except* WebSocketDisconnect:
            # Propagated out of the context manager: wrapped in ExceptionGroup.
            print("Connection closed")

    Attributes:
        subprotocol (typing.Optional[str]):
            Optional protocol that has been accepted by the server.
        response (Response | None):
            The webSocket handshake response.
    r?   r@   rA   rB   z?MemoryObjectSendStream[wsproto.events.Event | HTTPXWSException]_send_eventzBMemoryObjectReceiveStream[wsproto.events.Event | HTTPXWSException]_receive_eventNrC   c                  || _         t        j                  j                  t        j                  j
                        | _        || _        | j                  +| j                  j                  j                  d      | _	        nd | _	        t               | _        t        j                         | _        t        j                         | _        || _        || _        t'        |t(              rd | _        d | _        y || _        || _        y rI   )rK   rL   rM   rN   rO   rP   rB   rQ   rR   r@   r   rV   anyiorX   rY   rZ   r[   r^   r_   r   r   r`   ra   rb   s          r:   rd   zAsyncWebSocketSession.__init__q  s     !,,778N8N8U8UV ==$#}}44889QRD#D-/"[[] ::<'=$% f=>48D137D04SD13QD0r9   c                 K   t        j                  t        j                  j                  t
        z            \  | _        | _        t        j                         | _	        | j                  4 d {    | j                  4 d {    | j                  4 d {    | j                  j                  | j                  | j                         | j                  ;| j                  j                  | j                  | j                  | j                         	 |  | j                  j                   j#                          t        j$                  d      5  | j'                          d {    d d d        d d d       d {    d d d       d {    d d d       d {    y 7 87 &7 7 F# 1 sw Y   ExY w# | j                  j                   j#                          t        j$                  d      5  | j'                          d {  7   d d d        w # 1 sw Y   w xY wxY w7 # 1 d {  7  sw Y   xY w7 # 1 d {  7  sw Y   xY w7 # 1 d {  7  sw Y   y xY ww)NT)shield)r  create_memory_object_streamrL   r   rX   r   r  r  create_task_group_background_task_group
start_soonrr   r^   r`   rv   ra   cancel_scopecancelCancelScopery   rl   s    r:   __asynccontextmanager__z-AsyncWebSocketSession.__asynccontextmanager__  s    050Q0QNN  #331
 1-$- ',&=&=&?### 	' 	'T%8%8 	' 	'$:U:U 	' 	'''2243K3KTMiMij44@++66339988'
++88??A&&d3 '**,&&'	' 	' 	' 	' 	' 	' 	' 	' 	' '' ' ++88??A&&d3 '**,&&' ' '	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's?  A-I0/F'0I03IF*IIF-
IA8H-F>:H-F2	)F0*F2	.H-6IH+IIIII0!I"I0*I-I0F2	2F;7H->;H(	9HHH	H(	H%!H(	(H-+I-H?3H64H?;III	
II	II0I-!I$"I-)I0c                   K   | j                   j                  |      \  }}t        j                  j	                  |      }| j                  |       d{    |S 7 w)aK  
        Send a Ping message.

        Args:
            payload:
                Payload to attach to the Ping event.
                Internally, it's used to track this specific event.
                If left empty, a random one will be generated.

        Returns:
            An event that can be used to wait for the corresponding Pong response.

        Examples:
            Send a Ping and wait for the Pong

                pong_callback = await ws.ping()
                # Will block until the corresponding Pong is received.
                await pong_callback.wait()
        Nr   r   s        r:   r   zAsyncWebSocketSession.ping  sS     ( !..55g>##G,ii 	s   AAAAc                  K   ddl }	 | j                  j                  |      }| j                  4 d{    | j                  j                  |       d{    ddd      d{    y7 87 7 	# 1 d{  7  sw Y   yxY w# |j                  $ r9}| j                  t        j                  d       d{  7   t               |d}~ww xY ww)a|  
        Send an Event message.

        Mainly useful to send events that are not supported by the library.
        Most of the time, [ping()][httpx_ws.AsyncWebSocketSession.ping],
        [send_text()][httpx_ws.AsyncWebSocketSession.send_text],
        [send_bytes()][httpx_ws.AsyncWebSocketSession.send_bytes]
        and [send_json()][httpx_ws.AsyncWebSocketSession.send_json] are preferred.

        Args:
            event: The event to send.

        Raises:
            WebSocketNetworkError: A network error occured.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Send an event.

                event = await wsproto.events.Message(b"Hello!")
                ws.send(event)
        r   Nr   r   r   s        r:   r   zAsyncWebSocketSession.send  s     6 		1??''.D'' . .kk''---. . .-. . . .## 	1**[779MNNN')q0	1s   C+B A,B A2A.A2B &A0'B +C,B .A20B 2B8A;9B B CB C#C
9B<:C

CCc                   K   t         j                  j                  |      }| j                  |       d{    y7 w)a  
        Send a text message.

        Args:
            data: The text to send.

        Raises:
            WebSocketNetworkError: A network error occured.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Send a text message.

                await ws.send_text("Hello!")
        r   Nr   r   s      r:   r   zAsyncWebSocketSession.send_text  s1     ( ***5ii   5?=?c                   K   t         j                  j                  |      }| j                  |       d{    y7 w)a  
        Send a bytes message.

        Args:
            data: The data to send.

        Raises:
            WebSocketNetworkError: A network error occured.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Send a bytes message.

                await ws.send_bytes(b"Hello!")
        r   Nr   r   s      r:   r   z AsyncWebSocketSession.send_bytes  s1     ( +++6iir  c                   K   |dv sJ t        j                  |      }|dk(  r| j                  |       d{    y| j                  |j	                  d             d{    y7 .7 w)a  
        Send JSON data.

        Args:
            data:
                The data to send. Must be serializable by [json.dumps][json.dumps].
            mode:
                The sending mode. Should either be `'text'` or `'bytes'`.

        Raises:
            WebSocketNetworkError: A network error occured.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Send JSON data.

                data = {"message": "Hello!"}
                await ws.send_json(data)
        r'   r(   Nr   r   r   s       r:   r   zAsyncWebSocketSession.send_json  sd     0 ))))**T*6>..111///"8"8"ABBB 2Bs!   5A*A&(A* A(!A*(A*c                V  K   t        j                  |      5  | j                  j                          d{   }ddd       t	        t
              r|t	        |t        j                  j                        r t        |j                  |j                        |S 7 d# 1 sw Y   cxY ww)a:  
        Receive an event from the server.

        Mainly useful to receive raw [wsproto.events.Event][wsproto.events.Event].
        Most of the time, [receive_text()][httpx_ws.AsyncWebSocketSession.receive_text],
        [receive_bytes()][httpx_ws.AsyncWebSocketSession.receive_bytes],
        and [receive_json()][httpx_ws.AsyncWebSocketSession.receive_json] are preferred.

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.

        Returns:
            A raw [wsproto.events.Event][wsproto.events.Event].

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Wait for an event until one is available.

                try:
                    event = await ws.receive()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for an event for 2 seconds.

                try:
                    event = await ws.receive(timeout=2.)
                except TimeoutError:
                    print("No event received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        N)r  
fail_afterr  r   r   r   rL   r   r   r   r   r   r   s      r:   r   zAsyncWebSocketSession.receive4  s     X g& 	8--5577E	8e-.KeW^^;;<%ejj%,,?? 8	8 	8s,   B)BBBA B)BB&"B)c                   K   | j                  |       d{   }t        |t        j                  j                        r|j
                  S t        |      7 ?w)a  
        Receive text from the server.

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.

        Returns:
            Text data.

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.
            WebSocketInvalidTypeReceived: The received event was not a text message.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Wait for text until available.

                try:
                    text = await ws.receive_text()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for text for 2 seconds.

                try:
                    event = await ws.receive_text(timeout=2.)
                except TimeoutError:
                    print("No text received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        Nr   r   s      r:   r   z"AsyncWebSocketSession.receive_texth  sH     P ll7++eW^^778::*511 ,s   AAA Ac                   K   | j                  |       d{   }t        |t        j                  j                        rt        |j                        S t        |      7 Hw)a  
        Receive bytes from the server.

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.

        Returns:
            Bytes data.

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.
            WebSocketInvalidTypeReceived: The received event was not a bytes message.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Wait for bytes until available.

                try:
                    data = await ws.receive_bytes()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for bytes for 2 seconds.

                try:
                    data = await ws.receive_bytes(timeout=2.)
                except TimeoutError:
                    print("No data received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        Nr   r   s      r:   r   z#AsyncWebSocketSession.receive_bytes  sM     P ll7++eW^^889$$*511 ,s   A"A A	A"c                   K   |dv sJ |dk(  r| j                  |       d{   }n|dk(  r| j                  |       d{   }t        j                        S 7 87 w)a  
        Receive JSON data from the server.

        The received data should be parseable by [json.loads][json.loads].

        Args:
            timeout:
                Number of seconds to wait for an event.
                If `None`, will block until an event is available.
            mode:
                Receive mode. Should either be `'text'` or `'bytes'`.

        Returns:
            Parsed JSON data.

        Raises:
            TimeoutError: No event was received before the timeout delay.
            WebSocketDisconnect: The server closed the websocket.
            WebSocketNetworkError: A network error occured.
            WebSocketInvalidTypeReceived: The received event
                didn't correspond to the specified mode.

        Note:
            Exceptions not caught inside the context manager will be
            wrapped in an [ExceptionGroup][ExceptionGroup]. Use `except*` to catch them
            outside the `async with` block.

        Examples:
            Wait for data until available.

                try:
                    data = await ws.receive_json()
                except WebSocketDisconnect:
                    print("Connection closed")

            Wait for data for 2 seconds.

                try:
                    data = await ws.receive_json(timeout=2.)
                except TimeoutError:
                    print("No data received.")
                except WebSocketDisconnect:
                    print("Connection closed")
        r'   r(   Nr)   r   r   s       r:   r   z"AsyncWebSocketSession.receive_json  se     Z ))))6>**733DX++G44Dzz$ 44s!    AAAAAAc                  K   ddl }| j                  j                          | j                  j                  t
        j                  j                  j                  t
        j                  j                  j                  hvrt
        j                  j                  ||      }| j                  j                  |      }	 | j                  4 d{    | j                  j                  |       d{    ddd      d{    | j                  j!                          d{    y7 Z7 97 +# 1 d{  7  sw Y   ;xY w# |j                  $ r Y Ow xY w7 5w)a  
        Close the WebSocket session.

        Internally, it'll send the
        [CloseConnection][wsproto.events.CloseConnection] event.

        *This method is automatically called when exiting the context manager.*

        Args:
            code:
                The integer close code to indicate why the connection has closed.
            reason:
                Additional reasoning for why the connection has closed.

        Examples:
            Close the WebSocket session.

                await ws.close()
        r   N)r   rY   r   rM   r   rL   r   r   r   r   r   r   r[   rK   r   r   acloser   s         r:   ry   zAsyncWebSocketSession.close  s    ( 	 ??  ..<<..55)
 
 NN224@E??''.D++ 2 2++++D1112 2 kk  """	212 2 2 2'' "s   B8E;E D&E D,.D(/D,3E >D*?E E E!E&E (D,*E ,D>2D53D>:E EEEEc                t  K   ddl }d}	 | j                  j                         so| j                  |       d{   }| j                  j                  |       | j                  j                         D ]   }t        |t        j                  j                        rr| j                  j                  |j                               }| j                  4 d{    | j                  j                  |       d{    ddd      d{    t        |t        j                  j                        r&| j                   j#                  |j$                         t        |t        j                  j&                        r| j                  j)                          t        |t        j                  j*                        r|j,                  s||j.                  }n{||j.                  z  }nk|$| j0                  j                  |       d{    nEt3        |      } |||j.                  z         }d}| j0                  j                  |       d{    | j0                  j                  |       d{     | j                  j                         snyy7 \7 7 7 # 1 d{  7  sw Y   xY w7 7 n7 K# |j4                  |j6                  t8        f$ rX | j;                  t<        j>                  d       d{  7   | j0                  j                  tA                      d{  7   Y yw xY ww)am  
        Background task listening for data from the server.

        Internally, it'll:

        * Answer to Ping events.
        * Acknowledge Pong events.
        * Put other events in the [_events][_events]
        queue that'll eventually be consumed by the user.

        Args:
            max_bytes: The maximum chunk size to read at each iteration.
        r   Nr   )!r   rY   r   r   rM   r   r   r   rL   r   r   rB   r[   rK   r   r   rV   r   r   r   r   r   r   r   r  r   r   r   r=   ry   r
   r   r   r   s           r:   rr   z)AsyncWebSocketSession._background_receive  s     	59#	A((//1!..y99,,T2!__335 7E!%)<)<=#33ENN4DE#'#3#3 : :"&++"3"3D"999: : !%)<)<=**..u}}= !%)G)GH**..0!%)?)?@$555=9> 6 6%** D 63;"&"2"2"7"7">>> *.eJ1;<RUZU_U_<_1`.592"&"2"2"7"78J"KKK **//66697 ((//119
:9: : : :" ? L6##Y%9%9;G 	A**[77HHH""''(=(?@@@	As   L8/J= JBJ= JJ= J!7J8J!<J= JC<J= J7AJ= 
J9$J= /J;0!J= L8J= J= J!J= !J4	'J*(J4	/	J= 9J= ;J= =AL5 L+L5,L/-L52L84L55L8c                  K   | j                   j                         st        j                  |       d {    	 | j	                          d {   }|7	 t        j                  |      5  |j                          d {    d d d        | j                   j                         sy y 7 s7 \# t
        j                  j                  $ r Y y w xY w7 P# 1 sw Y   OxY w# t        $ rX | j                  t        j                  d       d {  7   | j                  j                  t!                      d {  7   Y w xY wwr   )rY   r   r  sleepr   rL   	utilitiesLocalProtocolErrorr#  rk   r   ry   r
   r   r  r   r   )rc   r   r   r   s       r:   rv   z0AsyncWebSocketSession._background_keepalive_pingQ  s
    $$++-++.///&*iik 1
 *I))/: 3+002223 $$++-/ !2$$77  33 3# I**[%?%?AYZZZ**//0E0GHHHIs   3EB)EB- B+B- EC +C?C CC E'E+B- -C
ECECCC ,D?
D+D?6D97D?<E>D??Ec                v   K   | j                   j                  |       d {   }|dk(  r
t               |S 7 wr   r   r   s      r:   r   z"AsyncWebSocketSession._read_streamc  s6     [[%%i003;- 1s   979)rK   r   rD   r   rE   r   rF   r   rG   r   rB   rA   r   r   )r   2typing.AsyncGenerator[AsyncWebSocketSession, None]r   )r   r   r   zanyio.Eventr   r   r   r   r   rf   r   r  r  r  r  r  r  r  r  r
  )r5   r6   r7   r  r  r   r   r   r   rd   
contextlibasynccontextmanagerr  r   r   r   r   r   r   r   r   r   ry   rr   rv   r   r8   r9   r:   r1   r1   K  s    @ PPVV 'E,8_7]$(R"R !$	R
 R *6R )5R "R 
RB ##' $',2#1J..C>2h+2Z+2Z3 j"#H4AlI$r9   c                    ddt        j                  t        j                  d            j	                  d      dd}| dj                  |       |d<   |S )	Nupgrade	websocket   r   13)rM   r3  zsec-websocket-keyzsec-websocket-versionz, rJ   )base64	b64encodesecretstoken_bytesdecoderz   )subprotocolsrQ   s     r:   _get_headersr=  j  sY      #--g.A.A".EFMMgV!%	G ,0IIl,C()Nr9   c            
          e Zd ZdZeeeeed	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	e
j                  ddddeeedd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zy)	WebSocketClienta  
    A sync WebSocket client.

    This class provides an API for connecting to WebSocket.

    Attributes:
        client:
            HTTPX client to use.
        max_message_size_bytes:
            Message size in bytes to receive from the server.
            Defaults to 65 KiB.
        queue_size:
            Size of the queue where the received messages will be held
            until they are consumed.
            If the queue is full, the client will stop receive messages
            from the server until the queue has room available.
            Defaults to 512.
        keepalive_ping_interval_seconds:
            Interval at which the client will automatically send a Ping event
            to keep the connection alive. Set it to `None` to disable this mechanism.
            Defaults to 20 seconds.
        keepalive_ping_timeout_seconds:
            Maximum delay the client will wait for an answer to its Ping event.
            If the delay is exceeded,
            [WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
            will be raised and the connection closed.
            Defaults to 20 seconds.
        session_class:
            The session class to use.
            Defaults to [WebSocketSession][httpx_ws.WebSocketSession].
    rD   rE   rF   rG   session_classc               X    || _         || _        || _        || _        || _        || _        y rf   clientrD   rE   rF   rG   rA  rc   rD  rD   rE   rF   rG   rA  s          r:   rd   zWebSocketClient.__init__  2     &<#$/N,.L+*r9   Nr<  paramsrQ   cookiesauthfollow_redirectsr   
extensionsc             #    K   | j                   j                  d||t        |      t        |      z  |||||		      5 }
|
j                  dk7  rt        |
      | j                  |
j                  d   | j                  | j                  | j                  | j                  |
      }|5  | ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY ww)a  
        Start a sync WebSocket session.

        It returns a context manager that'll automatically
        call [close()][httpx_ws.WebSocketSession.close] when exiting.

        Args:
            url: The WebSocket URL.
            subprotocols:
                Optional list of subprotocols to negotiate with the server.
            params:
                Query parameters to include in the handshake request.
            headers:
                Headers to include in the handshake request.
            cookies:
                Cookies to include in the handshake request.
            auth:
                Authentication to use for the handshake request.
            follow_redirects:
                Whether to follow redirects on the handshake request.
            timeout:
                Timeout configuration for the handshake request.
            extensions:
                Request extensions for the handshake request.

        Returns:
            A [context manager][contextlib.AbstractContextManager]
                for [WebSocketSession][httpx_ws.WebSocketSession].

        Examples:
            Initialize the client and connect to a WebSocket.

                with httpx2.Client() as client:
                    ws_client = WebSocketClient(client)
                    with ws_client.connect("http://localhost:8000/ws") as ws:
                        message = ws.receive_text()
                        print(message)
                        ws.send_text("Hello!")
        GETrH  rQ   rI  rJ  rK  r   rL  e   network_streamrC   NrD  rK   r   r=  status_coder   rA  rL  rD   rE   rF   rG   rc   urlr<  rH  rQ   rI  rJ  rK  r   rL  rB   sessions               r:   connectzWebSocketClient.connect  s     j [[G$|L'AA-!   

 	 ##s*+H55((##$45'+'B'B??040T0T/3/R/R! ) G  -	 	, -	 	s5   :CA)C%B;*C2	C;C	 CCC)rD  r   rD   r   rE   r   rF   r   rG   r   rA  ztype[SyncSession]r   r   )rU  r   r<  list[str] | NonerH  QueryParamTypes | NonerQ   HeaderTypes | NonerI  CookieTypes | NonerJ  #AuthTypes | UseClientDefault | NonerK  bool | UseClientDefaultr   TimeoutTypes | UseClientDefaultrL  RequestExtensions | Noner   z)typing.Generator[SyncSession, None, None])r5   r6   r7   r  r   r   r   r   r-   rd   r0  contextmanagerr   rW  r8   r9   r:   r?  r?  x  s   H 'E,8_7]+;++ !$	+
 + *6+ )5+ )+ 
+" 
 *.)-&*&*4F4F3E/3KK '	K
 'K $K $K 2K 2K 1K -K 
3K Kr9   r?  )rD   rE   rF   rG   r<  rH  rQ   rI  rJ  rK  r   rL  c             #  
  K   |ddl m}  |       }nt        j                  |      }|5 }t	        |||||      }|j                  | ||||	|
|||	      5 }| ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY ww)a%
  
    Start a sync WebSocket session.

    It returns a context manager that'll automatically
    call [close()][httpx_ws.WebSocketSession.close] when exiting.

    Args:
        url: The WebSocket URL.
        client:
            HTTPX client to use.
            If not provided, a default one will be initialized.
        max_message_size_bytes:
            Message size in bytes to receive from the server.
            Defaults to 65 KiB.
        queue_size:
            Size of the queue where the received messages will be held
            until they are consumed.
            If the queue is full, the client will stop receive messages
            from the server until the queue has room available.
            Defaults to 512.
        keepalive_ping_interval_seconds:
            Interval at which the client will automatically send a Ping event
            to keep the connection alive. Set it to `None` to disable this mechanism.
            Defaults to 20 seconds.
        keepalive_ping_timeout_seconds:
            Maximum delay the client will wait for an answer to its Ping event.
            If the delay is exceeded,
            [WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
            will be raised and the connection closed.
            Defaults to 20 seconds.
        subprotocols:
            Optional list of subprotocols to negotiate with the server.
        params:
            Query parameters to include in the handshake request.
        headers:
            Headers to include in the handshake request.
        cookies:
            Cookies to include in the handshake request.
        auth:
            Authentication to use for the handshake request.
        follow_redirects:
            Whether to follow redirects on the handshake request.
        timeout:
            Timeout configuration for the handshake request.
        extensions:
            Request extensions for the handshake request.

    Returns:
        A [context manager][contextlib.AbstractContextManager]
            for [WebSocketSession][httpx_ws.WebSocketSession].

    Examples:
        Without explicit HTTPX client.

            with connect_ws("http://localhost:8000/ws") as ws:
                message = ws.receive_text()
                print(message)
                ws.send_text("Hello!")

        With explicit HTTPX client.

            with httpx2.Client() as client:
                with connect_ws("http://localhost:8000/ws", client) as ws:
                    message = ws.receive_text()
                    print(message)
                    ws.send_text("Hello!")
    Nr   )r   rD  rD   rE   rF   rG   rG  )_clientr   r0  nullcontextr?  rW  )rU  rD  rD   rE   rF   rG   r<  rH  rQ   rI  rJ  rK  r   rL  r   owned_client	ws_clientr4  s                     r:   
connect_wsrg    s     j ~$BH(!--f5	 ##9!,K+I
	 %-!  

 	 O	 	 	 s4   (B+A7A+A7"	B+A4	0A77B <Bc            
          e Zd ZdZeeeeed	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	e
j                  ddddeeedd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Zy)	AsyncWebSocketClienta(  
    An async WebSocket client.

    This class provides an API for connecting to WebSocket.

    Attributes:
        client:
            HTTPX client to use.
        max_message_size_bytes:
            Message size in bytes to receive from the server.
            Defaults to 65 KiB.
        queue_size:
            Size of the queue where the received messages will be held
            until they are consumed.
            If the queue is full, the client will stop receive messages
            from the server until the queue has room available.
            Defaults to 512.
        keepalive_ping_interval_seconds:
            Interval at which the client will automatically send a Ping event
            to keep the connection alive. Set it to `None` to disable this mechanism.
            Defaults to 20 seconds.
        keepalive_ping_timeout_seconds:
            Maximum delay the client will wait for an answer to its Ping event.
            If the delay is exceeded,
            [WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
            will be raised in an [ExceptionGroup][ExceptionGroup] and the connection closed.
            Defaults to 20 seconds.
        session_class:
            The session class to use.
            Defaults to [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].
    r@  c               X    || _         || _        || _        || _        || _        || _        y rf   rC  rE  s          r:   rd   zAsyncWebSocketClient.__init__  rF  r9   NrG  c                 K   | j                   j                  d||t        |      t        |      z  |||||		      4 d{   }
|
j                  dk7  rt        |
      | j                  |
j                  d   | j                  | j                  | j                  | j                  |
      }|4 d{    | ddd      d{    ddd      d{    y7 7 ,7 # 1 d{  7  sw Y   )xY w7  # 1 d{  7  sw Y   yxY ww)a  
        Start an async WebSocket session.

        It returns an async context manager that'll automatically
        call [close()][httpx_ws.AsyncWebSocketSession.close] when exiting.

        Args:
            url: The WebSocket URL.
            subprotocols:
                Optional list of subprotocols to negotiate with the server.
            params:
                Query parameters to include in the handshake request.
            headers:
                Headers to include in the handshake request.
            cookies:
                Cookies to include in the handshake request.
            auth:
                Authentication to use for the handshake request.
            follow_redirects:
                Whether to follow redirects on the handshake request.
            timeout:
                Timeout configuration for the handshake request.
            extensions:
                Request extensions for the handshake request.

        Returns:
            An [async context manager][contextlib.AbstractAsyncContextManager]
                for [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].

        Examples:
            Initialize the client and connect to a WebSocket.

                async with httpx2.AsyncClient() as client:
                    ws_client = AsyncWebSocketClient(client)
                    async with ws_client.connect("http://localhost:8000/ws") as ws:
                        message = await ws.receive_text()
                        print(message)
                        await ws.send_text("Hello!")
        rN  rO  NrP  rQ  rC   rR  rT  s               r:   rW  zAsyncWebSocketClient.connect  s    j ;;%%G$|L'AA-! & 

 	 	 ##s*+H55((##$45'+'B'B??040T0T/3/R/R! ) G    -	 	 	,    -	 	 	 	s   >D CDA-C91C2C95C";C9C C9DC7DC9 C9"C4	(C+)C4	0C97D9D?D DD)rD  r   rD   r   rE   r   rF   r   rG   r   rA  ztype[AsyncSession]r   r   )rU  r   r<  rX  rH  rY  rQ   rZ  rI  r[  rJ  r\  rK  r]  r   r^  rL  r_  r   z)typing.AsyncGenerator[AsyncSession, None])r5   r6   r7   r  r   r   r   r   r1   rd   r0  r1  r   rW  r8   r9   r:   ri  ri  k  s   H 'E,8_7],A++ !$	+
 + *6+ )5+ *+ 
+" ##
 *.)-&*&*4F4F3E/3KK '	K
 'K $K $K 2K 2K 1K -K 
3K $Kr9   ri  c                K   |ddl m}  |       }nt        j                  |      }|4 d{   }t	        |||||      }|j                  | ||||	|
|||	      4 d{   }| ddd      d{    ddd      d{    y7 ]7 ,7 # 1 d{  7  sw Y   )xY w7  # 1 d{  7  sw Y   yxY ww)a
  
    Start an async WebSocket session.

    It returns an async context manager that'll automatically
    call [close()][httpx_ws.AsyncWebSocketSession.close] when exiting.

    Args:
        url: The WebSocket URL.
        client:
            HTTPX client to use.
            If not provided, a default one will be initialized.
        max_message_size_bytes:
            Message size in bytes to receive from the server.
            Defaults to 65 KiB.
        queue_size:
            Size of the queue where the received messages will be held
            until they are consumed.
            If the queue is full, the client will stop receive messages
            from the server until the queue has room available.
            Defaults to 512.
        keepalive_ping_interval_seconds:
            Interval at which the client will automatically send a Ping event
            to keep the connection alive. Set it to `None` to disable this mechanism.
            Defaults to 20 seconds.
        keepalive_ping_timeout_seconds:
            Maximum delay the client will wait for an answer to its Ping event.
            If the delay is exceeded,
            [WebSocketNetworkError][httpx_ws.WebSocketNetworkError]
            will be raised in an [ExceptionGroup][ExceptionGroup] and the connection closed.
            Defaults to 20 seconds.
        subprotocols:
            Optional list of subprotocols to negotiate with the server.
        params:
            Query parameters to include in the handshake request.
        headers:
            Headers to include in the handshake request.
        cookies:
            Cookies to include in the handshake request.
        auth:
            Authentication to use for the handshake request.
        follow_redirects:
            Whether to follow redirects on the handshake request.
        timeout:
            Timeout configuration for the handshake request.
        extensions:
            Request extensions for the handshake request.

    Returns:
        An [async context manager][contextlib.AbstractAsyncContextManager]
            for [AsyncWebSocketSession][httpx_ws.AsyncWebSocketSession].

    Examples:
        Without explicit HTTPX client.

            async with aconnect_ws("http://localhost:8000/ws") as ws:
                message = await ws.receive_text()
                print(message)
                await ws.send_text("Hello!")

        With explicit HTTPX client.

            async with httpx2.AsyncClient() as client:
                async with aconnect_ws("http://localhost:8000/ws", client) as ws:
                    message = await ws.receive_text()
                    print(message)
                    await ws.send_text("Hello!")
    Nr   )r   rb  rG  )rc  r   r0  rd  ri  rW  )rU  rD  rD   rE   rF   rG   r<  rH  rQ   rI  rJ  rK  r   rL  r   re  rf  r4  s                     r:   aconnect_wsrm    s     j ~)LWM!--f5  v(#9!,K+I
	 $$%-! % 

 	 	 O	 	  	 	 	 	 	   s   ,B>BB>/B)!B"B)%B+B)6B7B);B>B'B>B)B)B$	BB$	 B)'B>)B;/B20B;7B>)r<  rX  r   zdict[str, typing.Any]rf   )rU  r   rD  zClient | NonerD   r   rE   r   rF   r   rG   r   r<  rX  rH  rY  rQ   rZ  rI  r[  rJ  r\  rK  r]  r   r^  rL  r_  r   z.typing.Generator[WebSocketSession, None, None])rU  r   rD  zAsyncClient | NonerD   r   rE   r   rF   r   rG   r   r<  rX  rH  rY  rQ   rZ  rI  r[  rJ  r\  rK  r]  r   r^  rL  r_  r   r/  )P
__future__r   r7  concurrent.futuresrg   r0  r   rS   r9  sysrW   typingtypesr   version_infor   typing_extensionsr  rL   wsproto.utilitiesanyio.streams.memoryr   r	   wsproto.frame_protocolr
   rc  r   _configr   r   r   r   _modelsr   _exceptionsr   r   r   r   r   _pingr   r   
_transportr   TYPE_CHECKINGr   r   r   r   r   r   r    _typesr!   r"   r#   r$   r%   r&   Literalr   r*   r+   r,   r0   	Exceptionr3   r=   r-   AsyncContextManagerMixinr1   r=  Genericr?  r`  rg  ri  r1  rm  r8   r9   r:   <module>r     s;   "       
   w)    R . (    1 7	;??"  >>*+v~~n-V^^L)
m+=GYZ~-DNef	) 		) 	@ @F\E:: \~"~fnn[1 ~B  !n #A(4[3Y%)%)"&"&0B0B/A+/n	nn  	n
 n &2n %1n #n #n  n  n .n .n -n )n  4!n nb~6>>,7 ~B  "&n #A(4[3Y%)%)"&"&0B0B/A+/n	nn  	n
 n &2n %1n #n #n  n  n .n .n -n )n  8!n  nr9   