
    5iR                       U d Z ddlmZ ddlmZ ddlmZ ddl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mZmZmZmZmZmZmZmZmZmZmZm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( erHddl)m*Z*m+Z+m,Z,m-Z- ddlm.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA de dde dde dfZBdeCd<   d"dZDd#dZEd$dZF G d d      ZGdd gZHy!)%z2Starlette application for serving a Streamlit app.    )annotations)asynccontextmanager)Path)TYPE_CHECKINGAnyFinal)config)get_cookie_secret)generate_random_hex_string)create_auth_routes)BASE_ROUTE_COMPONENTBASE_ROUTE_COREBASE_ROUTE_MEDIABASE_ROUTE_UPLOAD_FILE create_app_static_serving_routescreate_bidi_component_routescreate_component_routescreate_health_routescreate_host_config_routescreate_media_routescreate_metrics_routescreate_script_health_routescreate_upload_routes)GZIP_COMPRESSLEVELGZIP_MINIMUM_SIZESESSION_COOKIE_NAME)%create_streamlit_static_assets_routes)create_websocket_routes)AsyncIteratorCallableMappingSequence)AbstractAsyncContextManager	Starlette
Middleware)	BaseRoute)ExceptionHandlerReceiveScopeSend)Runtime)MediaFileManagerMemoryMediaFileStorageMemoryUploadedFileManager/zFinal[tuple[str, ...]]_RESERVED_ROUTE_PREFIXESc                   | j                   }| j                  }|j                  }| j                  }| j                  }t        j                  d      }t        t        j                  d            }g }|j                  t        | |             |j                  t        | |             |j                  t        |             |j                  t        ||             |j                  t        | ||             |j                  t        ||             |j                  t        ||             |j                  t!        | |             |j                  t#        |             t        j                  d      r(t%        | dd      }	|j                  t'        |	|             t        j                  d      r|j                  t)        | |             |s|j                  t+        |             |S )a  Create the Streamlit-internal routes for the application.

    This function creates all the routes required for Streamlit's core functionality
    including WebSocket communication, health checks, media serving, file uploads,
    and static file serving.

    Parameters
    ----------
    runtime
        The Streamlit Runtime instance that manages the application state.

    Returns
    -------
    list[BaseRoute]
        A list of Starlette route objects for Streamlit's core functionality.
    zserver.baseUrlPathzglobal.developmentModezserver.enableStaticServing_main_script_pathNzserver.scriptHealthCheckEnabled)base_url)media_file_mgruploaded_file_mgr_storagecomponent_registrybidi_component_registryr	   
get_optionboolextendr   r   r   r   r   r   r   r   r   getattrr   r   r   )
runtimemedia_manager
upload_mgrmedia_storager;   bidi_component_managerr7   dev_moderoutesmain_script_paths
             v/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/streamlit/web/server/starlette/starlette_app.pycreate_streamlit_routesrJ   L   s   $ '.&<&<M,3,E,EJ,9,B,BM 33$<<  !56HF%%&>?@H F MM&w9:
MM':;
MM+H56
MM%mX>?
MM&w
HEF
MM)*<hGH
MM./ExPQ MM)'8<= MM$X./ 56 #7,?F67GRS :;1'8DE ;XNOM    c                    ddl m}  ddlm} ddlm} g }|j                   | |t               xs
 t               dt        t        j                  d            t                     |j                   | |t        t                     |S )	aB  Create the Streamlit-internal middleware stack.

    This function creates the middleware required for Streamlit's core functionality
    including session management and GZip compression.

    Returns
    -------
    list[Middleware]
        A list of Starlette Middleware objects for Streamlit's core functionality.
    r   r&   )SessionMiddleware)MediaAwareGZipMiddlewarelaxzserver.sslCertFile)
secret_key	same_site
https_onlysession_cookie)minimum_sizecompresslevel)starlette.middlewarer'   starlette.middleware.sessionsrM   8streamlit.web.server.starlette.starlette_gzip_middlewarerN   appendr
   r   r>   r	   r=   r   r   r   )r'   rM   rN   
middlewares       rI   create_streamlit_middlewarer[      s     0? $&J (*J.H.JF--.BCD.	
  $*,	
 rK   c                     	 ddl m} t        d fd       }t               }t               } ||||      S # t        $ r}t        d      |d}~ww xY w)a   Create a Starlette application for serving Streamlit.

    This factory function creates a fully configured Starlette app that provides
    the full web-server functionality required for Streamlit:
    - WebSocket endpoint for client-server communication
    - Health check endpoints
    - Media file serving with range request support
    - File upload handling
    - Custom component serving
    - Static file serving with SPA fallback
    - XSRF protection
    - Session middleware
    - GZip compression
    r   r$   zdStarlette is not installed. Run `pip install streamlit[starlette]` or disable `server.useStarlette`.Nc               l   K   j                          d {    d  j                          y 7 w)N)startstop)_apprA   s    rI   	_lifespanz'create_starlette_app.<locals>._lifespan   s)      mmo 	s   424)rG   rZ   lifespanr`   r%   returnzAsyncIterator[None])starlette.applicationsr%   ModuleNotFoundErrorRuntimeErrorr   rJ   r[   )rA   r%   excra   rG   rZ   s   `     rI   create_starlette_appri      sm    4   %W-F,.J FzINN)  0
 	s   8 	AAAc                      e Zd ZdZdddddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZedd       Zedd       Zdd	Z	dd
Z
ddZedd       ZddZddZy)Appa	  ASGI-compatible Streamlit application.

    .. warning::
        This feature is experimental and may change or be removed in future
        versions without warning. Use at your own risk.

    This class provides a way to configure and run Streamlit applications
    with custom routes, middleware, lifespan hooks, and exception handlers.

    Parameters
    ----------
    script_path : str | Path
        Path to the main Streamlit script. Can be absolute or relative. Relative
        paths are resolved based on context: when started via ``streamlit run``,
        they resolve relative to the main script; when started directly via uvicorn
        or another ASGI server, they resolve relative to the current working directory.
    lifespan : Callable[[App], AbstractAsyncContextManager[dict[str, Any] | None]] | None
        Async context manager for startup/shutdown logic. The context manager
        receives the App instance and can yield a dictionary of state that will
        be accessible via ``app.state``.
    routes : Sequence[BaseRoute] | None
        Additional routes to mount alongside Streamlit. User routes are checked
        against reserved Streamlit routes and will raise ValueError if they conflict.
    middleware : Sequence[Middleware] | None
        Middleware stack to apply to all requests. User middleware runs before
        Streamlit's internal middleware.
    exception_handlers : Mapping[Any, ExceptionHandler] | None
        Custom exception handlers for user routes.
    debug : bool
        Enable debug mode for the underlying Starlette application.

    Examples
    --------
    Basic usage:

    >>> from streamlit.web.server.starlette import App
    >>> app = App("main.py")

    With lifespan hooks:

    >>> from contextlib import asynccontextmanager
    >>> from streamlit.web.server.starlette import App
    >>>
    >>> @asynccontextmanager
    ... async def lifespan(app):
    ...     print("Starting up...")
    ...     yield {"model": "loaded"}
    ...     print("Shutting down...")
    >>>
    >>> app = App("main.py", lifespan=lifespan)

    With custom routes:

    >>> from starlette.routing import Route
    >>> from starlette.responses import JSONResponse
    >>> from streamlit.web.server.starlette import App
    >>>
    >>> async def health(request):
    ...     return JSONResponse({"status": "ok"})
    >>>
    >>> app = App("main.py", routes=[Route("/health", health)])
    NF)rb   rG   rZ   exception_handlersdebugc                  t        |      | _        || _        |rt        |      ng | _        |rt        |      ng | _        |rt        |      ni | _        || _        d | _	        d | _
        i | _        d| _        | j                          y )NF)r   _script_path_user_lifespanlist_user_routes_user_middlewaredict_exception_handlers_debug_runtime_starlette_app_state_external_lifespan_validate_routes)selfscript_pathrb   rG   rZ   rl   rm   s          rI   __init__zApp.__init__#  s     !-&,2DL4>Z 0B(:D#$ 	  (,04&((- 	rK   c           	         | j                   D ]T  }t        |dd      }|st        D ]9  }|j                  |      s||j	                  d      k(  s)t        d| d| d       V y)zHValidate that user routes don't conflict with reserved Streamlit routes.pathNr3   zRoute 'z2' conflicts with reserved Streamlit route prefix 'z('. Use a different path like '/api/...'.)rr   r@   r4   
startswithrstrip
ValueError)r|   router   reserveds       rI   r{   zApp._validate_routes@  sz    && 	E5&$/D 8 Hx0DHOOC<P4P(%dV ,''/j0XZ 	rK   c                    | j                   S )zThe entry point script path.)ro   r|   s    rI   r}   zApp.script_pathL  s        rK   c                    | j                   S )z9Application state, populated by lifespan context manager.)ry   r   s    rI   statez	App.stateQ  s     {{rK   c                j    | j                   | j                         | _         d| _        | j                  S )a9  Get a lifespan context manager for mounting on external ASGI frameworks.

        Use this when mounting st.App as a sub-application on another framework
        like FastAPI. The Streamlit runtime lifecycle will be managed by the
        parent framework's lifespan instead of st.App's internal lifespan.

        Returns
        -------
        Callable[[Any], AbstractAsyncContextManager[None]]
            A lifespan context manager compatible with Starlette/FastAPI.

        Examples
        --------
        Mount st.App on FastAPI:

        >>> from fastapi import FastAPI
        >>> from streamlit.starlette import App
        >>>
        >>> streamlit_app = App("dashboard.py")
        >>> fastapi_app = FastAPI(lifespan=streamlit_app.lifespan())
        >>> fastapi_app.mount("/dashboard", streamlit_app)
        T)rw   _create_runtimerz   _combined_lifespanr   s    rI   rb   zApp.lifespanV  s4    0 ==  002DM #'&&&rK   c                   | j                   j                         r| j                   S t        j                  r>t	        t        j                        j
                  | j                   z  j                         S | j                   j                         S )a6  Resolve the script path to an absolute path.

        Resolution order:
        1. If already absolute, return as-is
        2. If CLI set main_script_path (via `streamlit run`), resolve relative to it
        3. Otherwise, resolve relative to current working directory (e.g. when started via uvicorn)
        )ro   is_absoluter	   r6   r   parentresolver   s    rI   _resolve_script_pathzApp._resolve_script_pathv  so     ((*$$$ ##11299D<M<MMVVXX   ((**rK   c                p   ddl m}m} ddlm} ddlm} ddlm} ddl	m
} | j                         }|j                         st        d| d| j                   d	       |d
t               } |d
t                }	 | |t#        |      d||	 |       d |t%        j&                  d                        S )z6Create the Streamlit runtime (but don't start it yet).r   )r-   RuntimeConfigr/   )MemorySessionStorager1   )$create_default_cache_storage_managerzStreamlit script not found: 'z '. Please verify that the path 'z' is correct.r3   NFzserver.disconnectedSessionTTL)ttl_seconds)r}   command_linemedia_file_storageuploaded_file_managercache_storage_manageris_hellosession_storage)streamlit.runtimer-   r   +streamlit.runtime.memory_media_file_storager0   (streamlit.runtime.memory_session_storager   .streamlit.runtime.memory_uploaded_file_managerr2   *streamlit.web.cache_storage_manager_configr   r   is_fileFileNotFoundErrorro   r   r   strr	   r=   )
r|   r-   r   r0   r   r2   r   r}   r   r9   s
             rI   r   zApp._create_runtime  s    <VQ	
	
 //1 ""$#/} =0040A0A/B-Q 
 4a8H7I4JK5:P9Q6RS,!#5&7&J&L 4 & 1 12Q R!

 	
rK   c                 K   ddl m} | j                  t        d      | j                  rdt
        _        nt
        j                  dt
        _         |t        | j                                      | j                  j                          d{    	 | j                  rM| j                  |       4 d{   }|r| j                  j                  |       d ddd      d{    nd | j                  j                          y7 ~7 Y7 )# 1 d{  7  sw Y   3xY w# | j                  j                          w xY ww)zCombine Streamlit runtime lifecycle with user's lifespan.

        The runtime must already be created (via _create_runtime) before this
        lifespan runs. This lifespan handles starting and stopping the runtime.
        r   )prepare_streamlit_environmentNz>Runtime not initialized. Call _create_runtime before lifespan.zasgi-mountedzasgi-server)streamlit.web.bootstrapr   rw   rg   rz   r	   _server_moder   r   r^   rp   ry   updater_   )r|   r`   r   r   s       rI   r   zApp._combined_lifespan  s     	J== P  "" #1F  ("/F 	&c$*C*C*E&FG mm!!###	!""..t4  **51  
  MM  	$
     MM sr   BEDE!D) 6D7D) :#DD) (D)
D) 3ED) D) D&DD&"D) )EEc                   ddl m} ddlm} | j                  r@| j
                  du xs# | j
                  j                  |j                  k(  }|rt        d      | j
                  | j                         | _        t        | j
                        }| j                  |z   }t               }| j                  |z   }| j                  rdn| j                  } || j                  ||| j                   |      S )z?Build the Starlette application with all routes and middleware.r   r$   )RuntimeStateNzCannot use App as standalone ASGI application after calling lifespan(). The lifespan() method should only be used when mounting this App on another ASGI framework like FastAPI.)rm   rG   rZ   rl   rb   )re   r%   r   r   rz   rw   r   INITIALrg   r   rJ   rr   r[   rs   r   rv   ru   )	r|   r%   r   runtime_not_startedstreamlit_routes
all_routesstreamlit_middlewareall_middlewareapp_lifespans	            rI   _build_starlette_appzApp._build_starlette_app  s    42 ""%T)<)<@T@T)T   #"P  ==  002DM 34==A &&)99
  ;< ..1EE  $66tD<S<S++%#77!
 	
rK   c                   K   | j                   | j                         | _         | j                  |||       d{    y7 w)zASGI interface.N)rx   r   )r|   scopereceivesends       rI   __call__zApp.__call__  s;     &"&";";"=D!!%$777s   8AA A)r}   z
str | Pathrb   zJCallable[[App], AbstractAsyncContextManager[dict[str, Any] | None]] | NonerG   zSequence[BaseRoute] | NonerZ   zSequence[Middleware] | Nonerl   z%Mapping[Any, ExceptionHandler] | Nonerm   r>   rd   None)rd   r   )rd   r   )rd   zdict[str, Any])rd   z2Callable[[Any], AbstractAsyncContextManager[None]])rd   r-   rc   )rd   r%   )r   r+   r   r*   r   r,   rd   r   )__name__
__module____qualname____doc__r~   r{   propertyr}   r   rb   r   r   r   r   r   r    rK   rI   rk   rk      s    =J -126DH  
 W  +  0  B    
 :
 ! !  '@+&$
L ,! ,!\0
d8rK   rk   ri   N)rA   r-   rd   zlist[BaseRoute])rd   zlist[Middleware])rA   r-   rd   r%   )Ir   
__future__r   
contextlibr   pathlibr   typingr   r   r   	streamlitr	    streamlit.web.server.server_utilr
   2streamlit.web.server.starlette.starlette_app_utilsr   4streamlit.web.server.starlette.starlette_auth_routesr   /streamlit.web.server.starlette.starlette_routesr   r   r   r   r   r   r   r   r   r   r   r   r   6streamlit.web.server.starlette.starlette_server_configr   r   r   6streamlit.web.server.starlette.starlette_static_routesr   2streamlit.web.server.starlette.starlette_websocketr   collections.abcr   r    r!   r"   r#   re   r%   rV   r'   starlette.routingr(   starlette.typesr)   r*   r+   r,   r   r-   $streamlit.runtime.media_file_managerr.   r   r0   r   r2   r4   __annotations__rJ   r[   ri   rk   __all__r   rK   rI   <module>r      s    9 " *  , ,  > T    
 WJJ60/+FF)ERX Q4 0 <~-`%OPr8 r8j	 (
)rK   