
    	e\                        d 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 ddlmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZm Z  ddl!m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2  ej3        e4          Z5d Z6d Z7 G d de          Z8 G d de          ZdS )zN
Subclasses the bokeh serve commandline handler to extend it in various
ways.
    N)glob)
ModuleType)Application)DocumentLifecycleHandler)FunctionHandler)Serve)!build_single_handler_applications)silence)EMPTY_LAYOUT)ApplicationContext)PeriodicCallback)StaticFileHandler   )BasicProviderOAuthProvider)config)_cleanup_doc)LivenessHandler)record_moduleswatch)REST_PROVIDERS)
INDEX_HTMLget_static_routes
set_curdoc)state)fullpathc                     |                      d          }|d                                         }t          |          dk    rd                    |dd                   }||fS )z
    Parse a key, value pair, separated by '='
    That's the reverse of ShellArgs.

    On the command line (argparse) a declaration will typically look like:
        foo=hello
    or
        foo="hello world"
    =r      N)splitstriplenjoin)sitemskeyvalues       3lib/python3.11/site-packages/panel/command/serve.py	parse_varr)   (   sX     GGCLLE
(..

C
5zzA~~qrr##<    c                 4    t          d | D                       S )zC
    Parse a series of key-value pairs and return a dictionary
    c              3   4   K   | ]}t          |          V  d S N)r)   ).0items     r(   	<genexpr>zparse_vars.<locals>.<genexpr>>   s(      33T4333333r*   )dict)r%   s    r(   
parse_varsr2   :   s!     33U333444r*   c                   :     e Zd Zd fd	Zd Z fdZ fdZ xZS )AdminApplicationContext:  c                 X     t                      j        |fi | || _        d | _        d S r-   )super__init___unused_timeout_cleanup_cb)selfapplicationunused_timeoutkwargs	__class__s       r(   r8   z AdminApplicationContext.__init__C   s8    /////-r*   c                 J   K   |                      | j                   d {V  d S r-   )_cleanup_sessionsr9   )r;   s    r(   cleanup_sessionsz(AdminApplicationContext.cleanup_sessionsH   s5      $$T%9:::::::::::r*   c                     t          | j        | j                  | _        | j                                         t                                                       d S r-   )r   rB   r9   r:   startr7   run_load_hookr;   r?   s    r(   rE   z%AdminApplicationContext.run_load_hookK   sL    +D,A4CWXX   r*   c                     | j         r| j                                          t                                                       d S r-   )r:   stopr7   run_unload_hookrF   s    r(   rI   z'AdminApplicationContext.run_unload_hookP   s?     	$!!###!!!!!r*   )r5   )__name__
__module____qualname__r8   rB   rE   rI   __classcell__r?   s   @r(   r4   r4   A   s~                   
; ; ;         
" " " " " " " " "r*   r4   c            #           e Zd Zej        d eddd          fd eded	          fd
 eded	          fd eded	          fd eded	          fd eded	          fd eded	          fd eded	          fd eded	          fd eded	          fd ededd          fd eded	          fd eded 	          fd! eded"	          fd# eded$	          fd% eded&d'          fd( ed)d*+          fd, eded-d.          fd/ ed)d0+          fd1 ed)d2+          fd3 eded4d5          fd6 edd5d7d89          fd: eded;	          fd< ed)d=+          fd> eded?d5          fd@ ededAd5          fdB ed)dC+          fdD ededEdF          fdG ed)dH+          fdI ed)dJ+          ffz   Zg dKZ	 fdLZ
dM ZdN Z fdOZ xZS )Pr   z--static-dirsz	KEY=VALUE+ziStatic directories to serve specified as key=value pairs mapping from URL route to static file directory.)metavarnargshelpz--basic-authstorez6Password or filepath to use with Basic Authentication.)actiontyperS   z--oauth-providerzThe OAuth2 provider to use.z--oauth-keyzThe OAuth2 key to usez--oauth-secretzThe OAuth2 secret to usez--oauth-redirect-urizThe OAuth2 redirect URIz--oauth-extra-paramszAdditional parameters to use.z--oauth-jwt-userz1The key in the ID JWT token to consider the user.z--oauth-encryption-keyz4A random string used to encode the user information.z--oauth-error-templatez--oauth-expiry-daysz.Expiry off the OAuth cookie in number of days.r   )rU   rV   rS   defaultz--auth-templatez/Template to serve when user is unauthenticated.z--logout-templatezTemplate to serve logout page.z--basic-login-templatez6Template to serve for Basic Authentication login page.z--rest-providerz&The interface to use to serve REST APIz--rest-endpointzEndpoint to store REST API on.restz--rest-session-info
store_truez-Whether to serve session info on the REST API)rU   rS   z--session-historyz,The length of the session history to record.r   z--warmz<Whether to execute scripts on startup to warm up the server.z--adminzWhether to add an admin panel.z--admin-endpointz#Name to use for the admin endpoint.Nz--admin-log-level)debuginfowarningerrorcriticalz9One of: debug (default), info, warning, error or critical)rU   rW   choicesrS   z
--profilerzFThe profiler to use by default, e.g. pyinstrument, snakeviz or memray.z--autoreloadz1Whether to autoreload source when script changes.z--num-threadsz>Whether to start a thread pool which events are dispatched to.z--setupz3Path to a setup script to run before server starts.z
--livenessz#Whether to add a liveness endpoint.z--liveness-endpointz"The endpoint for the liveness API.livenessz--reuse-sessionsz;Whether to reuse sessions when serving the initial request.z--global-loading-spinnerz>Whether to add a global loading spinner to the application(s).)z.pyz.ipynbz.mdc                    |j         r|j                             d          s{|j                             t          j        j                  d         }| j        D ]/}|                    |          r|d t          |                    }0d| |v r|d|          |d<   t                      	                    ||          S )N.html/)
indexendswithr    ospathsep_extensionsr"   r7   customize_applications)r;   argsapplicationsre   extr?   s        r(   rk   zServe.customize_applications   s    : 	>dj11':: 	>J$$RW[11"5E' . .>>#&& .!*CHH9*-E5{{l**$0U$=S!ww--dLAAAr*   c                    ddl m} |                                D ]\  }} ||          }t          |j                  5  t
          j        rd}n3d t          j        |<   |t          j	        |<   |
                                 t          j        d            d d d            n# 1 swxY w Y   t          |j        |            d S )Nr   )generate_sessionFc                     | j         S r-   rh   )rs    r(   <lambda>z)Serve.warm_applications.<locals>.<lambda>  s    qv r*   )destroy)
io.sessionrp   r%   r   documentr   session_key_funcr   _session_key_funcs	_sessionsblock_expiration_on_loadr   )r;   rm   reuse_sessionsrp   rh   appsessions          r(   warm_applicationszServe.warm_applications   s%   111111%++-- 
	G 
	GID#&&s++GG,-- % %* /%*NN5E5EE,T2,3EOD),,...t$$$% % % % % % % % % % % % % % % )~3EFFFFF
	G 
	Gs   AB""B&	)B&	c                   ( t          |          }d|vrt          |d<   nC|d                             d          r(t          j                            |d                   |d<   |                    dg           x|d<   }j        rt          j                  ni }|t          |          z  }g }j
        D ]A}j        r#|                    t          |                     ,|                    |           Bj        rj                            d          sd}| j        D ]K}	j                            |	          rj        n
j         |	 (t!          (fd|D                       rd}L|D ]Y}dt          j                            |          v r$j        t          j                            |          k    sj        |k    rd}Z|st%          d(d	          j        t(          v r6t)          j                 |j                  }
|                    |
           nj        t%          dj        z            j        t.          _        j        t.          _        j        t.          _        t.          j        r|D ]}t5          |           j        rŉj        }t9          |          5 }|                                }d
d
d
           n# 1 swxY w Y   t=          j        |t          j         |                    }tC          ||dd          }d}tE          |          }tG          |          |j$        d<   tK          ||j$                   |tL          _'        j(        sj        rfd|D             }tS          ||          }j        rBtU                      5  | +                    |j                   d
d
d
           n# 1 swxY w Y   n| +                    |j                   j,        rBfd|D             }tS          ||          }|dj-        z  t\          t          |          fgz  }j/        t.          _/        j0        r5ddl1m2} ddl3m4} d}j5        r#j5        }|6                    d          r|nd| }dt.          _7        tq          ts          |                    }j:        pd}tw          |||          xtL          _<        }t{          d |j>        D                       r!|?                    t                                 g }|D ]/}||d         z   }d|i}|                    ||d         |f           0d
}|D ]%}|d                             d          r|d         }&|st          d           |D ]}||d         d!<   	 dd
lB}t          j        C                    t          j        D                    |jE                  d"          } |                    d#t          t          | $          f           n# t          $ r Y nw xY w|                    |           jH        Qt          jI                            d%          rt%          d&          jH        J                                t.          _H        jK        t.          _K        jL        rGt)          d'         |d(          }
|                    |
           tM          jM        d)tL          d)g           jN        ,t.          jO        t%          d*          jN        t.          _O        jP        rpt          jR        jP                  }!|!S                                st%          d+jP         d,          t          |!U                                          t.          _P        jV        r9t          t          jR        jV                  U                                          }"nd
}"jW        rt.          jW        rt%          d-          jW        rjW        t.          _W        t.          jW        r`jX        rCjX        }#t          jR        |#          }!|!S                                st%          d+|# d,          nd
}#t          |#|".          |d/<   jZ        rt.          jZ        rt%          d0          jZ        rjZ        t.          _Z        j[        rt.          j[        rt%          d1          j[        rj[        t.          _[        t.          j[        rj\        t.          _]        t.          j^        rj^        rt%          d2          j^        rj^        t.          _^        nt.          j^        st%          d3          t.          jZ        st%          d4          t.          j_        rj_        rt%          d5          j_        rj_        t.          __        nt.          j_        st%          d6          j`        r#t=          ja        j`                  t.          _`        t.          jb        rjb        rt%          d7          jb        r|jb        c                    d8          }$	 t          je        |$          }%n# t          $ r t%          d9          w xY wt          |%          d:k    rt%          d;          |$t.          _b        nt.          jb        st          d<           t.          jb        rD	 dd=lhmi}& n# t          $ r t          d>          w xY w |&t.          jb                  tL          _k        jl        r9t          t          jR        jl                  U                                          }'nt.          jP        rt.          jP        }'nd
}'t          |'|"?          |d/<   jn        rt.          jn        rt%          d@          jn        rjn        t.          _n        jo        rt.          jo        rt%          dA          jo        rjo        t.          _o        t.          jZ        rt.          jZ        |dB<   |S )CzAllows subclasses to customize ``server_kwargs``.

        Should modify and return a copy of the ``server_kwargs`` dictionary.
        re   rb   extra_patternsFc              3   B   K   | ]}|                               V  d S r-   )rf   )r.   fre   s     r(   r0   z)Serve.customize_kwargs.<locals>.<genexpr>*  s/      88Qqzz%((888888r*   T.zThe --index argument must either specify a jinja2 template with a .html file extension or select one of the applications being served as the default. The specified application z could not be found.Nz rest-provider %r not recognized.exec)filenamemodedont_inheritpanel_setup_module__file__c                      i | ]
}|j         S  rl   r.   r   rl   s     r(   
<dictcomp>z*Serve.customize_kwargs.<locals>.<dictcomp>W      111aQ	111r*   c                      i | ]
}|j         S r   r   r   s     r(   r   z*Serve.customize_kwargs.<locals>.<dictcomp>b  r   r*   z/%s)rm   r   )admin_panel)per_app_patternsz/adminrd   r5   )r=   urlc              3   B   K   | ]}t          |t                     V  d S r-   )
isinstancer   )r.   handlers     r(   r0   z)Serve.customize_kwargs.<locals>.<genexpr>w  s0      bbz'+CDDDbbbbbbr*   r   application_contextr   z/wszCouldn't find websocket pathbokeh_websocket_pathstaticz/snakeviz/static/(.*)rr   PANEL_ADMIN_LOG_LEVELzadmin_log_level supplied both using the environment variable PANEL_ADMIN_LOG_LEVEL and as an explicit argument, only the value supplied to the environment variable is used paramrX   session_infozpSupply num_threads either using the environment variable PANEL_NUM_THREADS or as an explicit argument, not both.zThe supplied auth-template z@ does not exist, ensure you supply and existing Jinja2 template.zZTurn on Basic authentication using environment variable or via explicit argument, not both)basic_login_templatelogout_templateauth_providerzZSupply cookie secret either using environment variable or via explicit argument, not both.z[Supply OAuth provider either using environment variable or via explicit argument, not both.zVSupply OAuth key either using environment variable or via explicit argument, not both.zWhen enabling an OAuth provider you must supply a valid oauth_key either using the --oauth-key CLI argument or PANEL_OAUTH_KEY environment variable.zWhen enabling an OAuth provider you must supply a valid cookie_secret either using the --cookie-secret CLI argument or the PANEL_COOKIE_SECRET environment variable.zYSupply OAuth secret either using environment variable or via explicit argument, not both.zWhen enabling an OAuth provider you must supply a valid OAuth secret either using the --oauth-secret CLI argument or PANEL_OAUTH_SECRET environment variable.zaSupply OAuth encryption key either using environment variable or via explicit argument, not both.asciizOAuth encryption key was not a valid base64 string. Generate an encryption key with `panel oauth-secret` and ensure you did not truncate the returned string.    z>OAuth encryption key must be 32 url-safe base64-encoded bytes.av  WARNING: OAuth has not been configured with an encryption key and will potentially leak credentials in cookies and a JWT token embedded in the served website. Use at your own risk or generate a key with the `panel oauth-secret` CLI command and then provide it to `panel serve` using the PANEL_OAUTH_ENCRYPTION environment variable or the --oauth-encryption-key CLI argument.)FernetzUsing OAuth2 provider with Panel requires the cryptography library. Install it with `pip install cryptography` or `conda install cryptography`.)error_templater   z_Supply OAuth redirect URI either using environment variable or via explicit argument, not both.z[Supply OAuth JWT user either using environment variable or via explicit argument, not both.cookie_secret)pr1   r   rf   rg   rh   abspathgetstatic_dirsr2   r   filesr   extendappendre   rj   anybasename
ValueErrorrest_providerr   rest_endpoint
autoreloadr   global_loading_spinnerr}   r   setupopenreadastparsefspathcompiler   r   __dict__r   r   _setup_modulewarmr	   r   r   r`   liveness_endpointr   profileradminio.adminr   	io.serverr   admin_endpoint
startswith_adminr   r   check_unused_sessionsr4   _admin_contextall	_handlersaddr   RuntimeErrorsnakevizr#   dirnamer   r   	Exceptionadmin_log_levelenvironuppersession_historyrest_session_infopublishnum_threadsnthreadsauth_templatepathlibPathis_filestrabsoluter   
basic_authr   r   r   oauth_provideroauth_expiry_daysoauth_expiry	oauth_keyoauth_secretoauth_extra_paramsliteral_evaloauth_encryption_keyencodebase64urlsafe_b64decoder"   printcryptography.fernetr   ImportError
encryptionoauth_error_templater   oauth_redirect_urioauth_jwt_user))r;   rl   server_kwargsr>   patternsr   r   r   foundrn   pattern
setup_pathsetup_sourcenodescodemodule_namemoduleargvsrm   r   r   
admin_pathr~   r=   app_ctxapp_patternsproutecontextwebsocket_pathrs   r   SNAKEVIZ_PATHauthpathr   r   encryption_keyr&   r   r   re   s)    `                                      @r(   customize_kwargszServe.customize_kwargs  s   
 m$$&  (F7OOG_%%g.. 	? goofWo>>F7O /5jj9I2.N.NN 86:6FNj!1222B%k222 	  	 Ay  T!WW%%%%Q: 	dj11':: 	E' ! !&*j&9&9#&>&>X

tzDXSVDXDX8888%88888 ! E ! !"'**1----:!1!1!!4!444
a E   27     //$T%78@RSSGOOG$$$$+?$BTTUUU O(,(C% $ 3 	  a: 
	)Jj!! (Q vvxx( ( ( ( ( ( ( ( ( ( ( ( ( ( (IlBIj,A,ABBE5:FQUVVVD.K,,F*2:*>*>FOJ'v'''"(E9 		J 		J11115111E<UEJJL J#%%  **$d&9                
 &&|T5HIII= 	n11115111E<UEJJL&4#99?D^jLkLkLklmmH-: 1	J......444444 "J" \!0
+5+@+@+E+E[ZZK[zK[K[
 FMok::;;C!7@5N-DN
. . . E 7 bbTWTabbbbb 4022333L% < <"QqT)0':##UAaD'$:;;;;!N! * *Q4=='' *%&qTN! C"#ABBB! > >/=!+,, "RW__X=N-O-OQY Z Z##,.?=AYAYAYZ       OOL)))#/:>>"9:: J$N   .2-A-G-G-I-IF*!%!5! 	C$W-eV<<GOOG$$$M.%.1ABBB'* N   #.FO 	<|D$677H##%%  M$2D M M M   $'x'8'8':':#;#;F   	#!',t/C"D"D"M"M"O"OPPOO"O? 	v0 	5   ? 	0 $F 	( 	,'+'@$"<(<=='')) $Q6J Q Q Q   (,$&3%9 /' ' 'F?#
  	6&"6 	6?    	6#'#5F   	6#8 	 :    	8$($7F!  n	<"&"8F DN  :    #'>  %      '      " t'8  :   " &*&7##(      & V,/,<T=T,U,U)* #t/H # C   * #!%!:!A!A'!J!JF 2>BBCC  F F F$ &E F F FF
 s88r>>$0   /=++0 	# " # # # * 	G:::::::"   %I   $*6&*E#F#F ( &!$W\$2K%L%L%U%U%W%W!X!X% &!'!5!%&3-' ' 'F?# & D6+D D C   ( D,0,C)" <v'< < C   $ <(,(;% 	;&,&:F?#sO   2KKK"O

OOA1X 
XX i i/	k k*c                 t    t          t          d           t                                          |           d S )NT)r
   r   r7   invoke)r;   rl   r?   s     r(   r  zServe.invokeT  s1     	d###tr*   )rJ   rK   rL   _BkServerl   r1   r   floatintrj   rk   r   r  r  rM   rN   s   @r(   r   r   V   s       =	$$K
 
 
 	 
M
 
 
 	
 
TT2
 
 
 	
 
-
 
 
 	
 
440
 
 
 	
 
 /"
 "
 "
 	
 
 5"
 "
 "
 	
 
TTI
 
 
 	
 
"44L$
 $
 $
 	
 
"44L$
 $
 $
 	
 
F	!
 !
 !
 	 
DDG
 
 
 	
 
dd6
 
 
 	
 
"44N$
 $
 $
 	
 
DD=
 
 
 	
 
DD6	
 
 
 	 
"E!
 !
 !
 	 
ddD	
 
 
 	 
44"T
 
 
 	 
DD"6
 
 
 	 
TT;	
 
 
 	 
ddGQ	
 
 
 	 
tt^
 
 
 	
 
"I
 
 
 	 
$$V	
 
 
 	 
DDK	
 
 
 	 
tt";
 
 
 	 
: 	!
 !
 !
 	 
TT"S
 
 
 	 
$TT"V&
 &
 &
 	kY YDx +**KB B B B BG G GD D DL
        r*   r   )9__doc__r   r   loggingrg   r   r   typesr   bokeh.applicationr   -bokeh.application.handlers.document_lifecycler   #bokeh.application.handlers.functionr   bokeh.command.subcommands.server   r  bokeh.command.utilr	   bokeh.core.validationr
   bokeh.core.validation.warningsr   bokeh.server.contextsr   tornado.ioloopr   tornado.webr   authr   r   r   io.documentr   io.livenessr   	io.reloadr   r   io.restr   r   r   r   r   io.stater   utilr   	getLoggerrJ   logr)   r2   r4   r   r*   r(   <module>r!     sx   
 


   				              ) ) ) ) ) )      @ ? ? ? ? ? = = = = = = @ @ @ @ @ @ ) ) ) ) ) ) 7 7 7 7 7 7 4 4 4 4 4 4 + + + + + + ) ) ) ) ) ) / / / / / / / /       & & & & & & ) ) ) ) ) ) - - - - - - - - $ $ $ $ $ $ A A A A A A A A A A            g!!  $5 5 5" " " " "0 " " "*B B B B BH B B B B Br*   