@mcpjam/inspector 0.9.45 → 0.9.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1833,8 +1833,8 @@ ${t.error.stack}`]})]})]})]})}const axe=["error","warn","info","debug","trace"];
1833
1833
  --json-null: var(--muted-foreground);
1834
1834
  color: var(--muted-foreground) !important;
1835
1835
  }
1836
- `}),f.jsx("div",{className:"json-viewer-mcpjam",children:f.jsx(Ol,{src:C,dark:!1,theme:"default",enableClipboard:!0,displaySize:!0,collapsed:2,collapseStringsAfterLength:80,collapseObjectsAfterLength:10,style:{fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, 'SF Mono', monospace",backgroundColor:"hsl(var(--background))",padding:0,borderRadius:0,border:"none"}})})]}):f.jsx("pre",{className:"text-xs bg-background p-2 rounded border mt-1 overflow-auto",children:A.body})})()]},A.id))})})]})]})}class S1{constructor(e){this.serverUrl=e,sessionStorage.setItem("debug-oauth-server-url",e)}get redirectUrl(){return`${window.location.origin}/oauth/callback/debug`}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:"MCPJam",client_uri:"https://github.com/mcpjam/inspector"}}async clientInformation(){const e=`debug-client-info-${this.serverUrl}`,n=sessionStorage.getItem(e);if(n)return JSON.parse(n)}saveClientInformation(e){const n=`debug-client-info-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(e))}async tokens(){const e=`debug-tokens-${this.serverUrl}`,n=sessionStorage.getItem(e);if(n)return JSON.parse(n)}saveTokens(e){const n=`debug-tokens-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(e))}redirectToAuthorization(e){}saveCodeVerifier(e){const n=`debug-verifier-${this.serverUrl}`;sessionStorage.setItem(n,e)}codeVerifier(){const e=`debug-verifier-${this.serverUrl}`,n=sessionStorage.getItem(e);if(!n)throw new Error("No code verifier saved for debug session");return n}saveServerMetadata(e){const n=`debug-server-metadata-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(e))}getServerMetadata(){const e=`debug-server-metadata-${this.serverUrl}`,n=sessionStorage.getItem(e);return n?JSON.parse(n):null}clear(){[`debug-client-info-${this.serverUrl}`,`debug-tokens-${this.serverUrl}`,`debug-verifier-${this.serverUrl}`,`debug-server-metadata-${this.serverUrl}`].forEach(n=>sessionStorage.removeItem(n))}}const Jm={isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null},Qc=({label:t,isComplete:e,isCurrent:n,error:r,children:s})=>f.jsxs("div",{children:[f.jsxs("div",{className:`flex items-center p-2 rounded-md ${n?"bg-accent":""}`,children:[e?f.jsx(VK,{className:"h-5 w-5 text-green-500 mr-2"}):f.jsx(WK,{className:"h-5 w-5 text-muted-foreground mr-2"}),f.jsx("span",{className:`${n?"font-medium":""}`,children:t})]}),(n||e)&&s&&f.jsx("div",{className:"ml-7 mt-1",children:s}),n&&r&&f.jsxs("div",{className:"ml-7 mt-2 p-3 border border-red-300 bg-red-50 dark:bg-red-950/50 rounded-md",children:[f.jsx("p",{className:"text-sm font-medium text-red-700 dark:text-red-400",children:"Error:"}),f.jsx("p",{className:"text-xs text-red-600 dark:text-red-500 mt-1",children:r.message})]})]}),eg=["metadata_discovery","client_registration","authorization_redirect","authorization_code","token_request","complete"],cxe=({serverUrl:t,flowState:e,updateFlowState:n,proceedToNextStep:r})=>{const s=w.useMemo(()=>new S1(t),[t]),[i,o]=w.useState(null),c=eg.findIndex(d=>d===e.oauthStep);w.useEffect(()=>{const d=async()=>{if(e.oauthClientInfo)o(e.oauthClientInfo);else try{const p=await s.clientInformation();p&&o(p)}catch(p){console.error("Failed to fetch client information:",p)}};c>eg.indexOf("client_registration")&&d()},[s,e.oauthStep,e.oauthClientInfo,c]);const u=d=>({isComplete:c>eg.indexOf(d)||c===eg.length-1,isCurrent:e.oauthStep===d,error:e.oauthStep===d?e.latestError:null});return f.jsxs("div",{className:"rounded-md border p-6 space-y-4 mt-4",children:[f.jsx("h3",{className:"text-lg font-medium",children:"OAuth Flow Progress"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Follow these steps to complete OAuth authentication with the server."}),f.jsxs("div",{className:"space-y-3",children:[f.jsx(Qc,{label:"Metadata Discovery",...u("metadata_discovery"),children:e.oauthMetadata&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsxs("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:["OAuth Metadata Sources",!e.resourceMetadata&&" ℹ️"]}),e.resourceMetadata&&f.jsxs("div",{className:"mt-2",children:[f.jsx("p",{className:"font-medium",children:"Resource Metadata:"}),f.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-protected-resource",t).href]}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(e.resourceMetadata,null,2)})]}),e.resourceMetadataError&&f.jsxs("div",{className:"mt-2 p-3 border border-blue-300 bg-blue-50 dark:bg-blue-950/50 rounded-md",children:[f.jsxs("p",{className:"text-sm font-medium text-blue-700 dark:text-blue-400",children:["ℹ️ Problem with resource metadata from"," ",f.jsx("a",{href:new URL("/.well-known/oauth-protected-resource",t).href,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300",children:new URL("/.well-known/oauth-protected-resource",t).href})]}),f.jsxs("p",{className:"text-xs text-blue-600 dark:text-blue-500 mt-1",children:["Resource metadata was added in the"," ",f.jsx("a",{href:"https://modelcontextprotocol.io/specification/draft/basic/authorization#2-3-1-authorization-server-location",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"2025-DRAFT-v2 specification update"}),f.jsx("br",{}),e.resourceMetadataError.message,e.resourceMetadataError instanceof TypeError&&" (This could indicate the endpoint doesn't exist or does not have CORS configured)"]})]}),e.oauthMetadata&&f.jsxs("div",{className:"mt-2",children:[f.jsx("p",{className:"font-medium",children:"Authorization Server Metadata:"}),e.authServerUrl&&f.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-authorization-server",e.authServerUrl).href]}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(e.oauthMetadata,null,2)})]})]})}),f.jsx(Qc,{label:"Client Registration",...u("client_registration"),children:i&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Registered Client Information"}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(i,null,2)})]})}),f.jsx(Qc,{label:"Preparing Authorization",...u("authorization_redirect"),children:e.authorizationUrl&&f.jsxs("div",{className:"mt-2 p-3 border rounded-md bg-muted",children:[f.jsx("p",{className:"font-medium mb-2 text-sm",children:"Authorization URL:"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("p",{className:"text-xs break-all",children:e.authorizationUrl}),f.jsx("a",{href:e.authorizationUrl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300","aria-label":"Open authorization URL in new tab",title:"Open authorization URL",children:f.jsx(KE,{className:"h-4 w-4"})})]}),f.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Click the link to authorize in your browser. After authorization, you'll be redirected back to continue the flow."})]})}),f.jsx(Qc,{label:"Request Authorization and acquire authorization code",...u("authorization_code"),children:f.jsxs("div",{className:"mt-3",children:[f.jsx("label",{htmlFor:"authCode",className:"block text-sm font-medium mb-1",children:"Authorization Code"}),f.jsx("div",{className:"flex gap-2",children:f.jsx("input",{id:"authCode",value:e.authorizationCode,onChange:d=>{n({authorizationCode:d.target.value,validationError:null})},placeholder:"Enter the code from the authorization server",className:`flex h-9 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${e.validationError?"border-red-500":"border-input"}`})}),e.validationError&&f.jsx("p",{className:"text-xs text-red-600 dark:text-red-500 mt-1",children:e.validationError}),f.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once you've completed authorization in the link, paste the code here."})]})}),f.jsx(Qc,{label:"Token Request",...u("token_request"),children:e.oauthMetadata&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Token Request Details"}),f.jsxs("div",{className:"mt-2 p-2 bg-muted rounded-md",children:[f.jsx("p",{className:"font-medium",children:"Token Endpoint:"}),f.jsx("code",{className:"block mt-1 text-xs overflow-x-auto",children:e.oauthMetadata.token_endpoint})]})]})}),f.jsx(Qc,{label:"Authentication Complete",...u("complete"),children:e.oauthTokens&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Access Tokens"}),f.jsx("p",{className:"mt-1 text-sm",children:"Authentication successful! You can now use the authenticated connection. These tokens will be used automatically for server requests."}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(e.oauthTokens,null,2)})]})})]}),f.jsxs("div",{className:"flex gap-3 mt-4",children:[e.oauthStep!=="complete"&&f.jsx(f.Fragment,{children:f.jsx(Ue,{onClick:r,disabled:e.isInitiatingAuth,children:e.isInitiatingAuth?"Processing...":"Continue"})}),e.oauthStep==="authorization_redirect"&&e.authorizationUrl&&f.jsx(Ue,{variant:"outline",onClick:()=>window.open(e.authorizationUrl,"_blank"),children:"Open in New Tab"})]})]})},uxe={metadata_discovery:{canTransition:async()=>!0,execute:async t=>{try{if(t.updateState({latestError:null}),!t.serverUrl)throw new Error("Server URL is required");let e;try{e=new URL(t.serverUrl).toString()}catch{throw new Error(`Invalid server URL: ${t.serverUrl}`)}let n;try{n=new URL("/",e)}catch{throw new Error(`Failed to create base URL from server URL: ${e}`)}let r=null,s=null;try{if(r=await B5(e),r?.authorization_servers?.length){const c=r.authorization_servers[0];try{n=new URL(c)}catch{console.warn(`Invalid authorization server URL: ${c}, using default`)}}}catch(c){s=c instanceof Error?c:new Error(String(c))}const i=await KJ(n.toString());let o=null;try{o=await V5(e,t.provider,r??void 0)??null}catch(c){console.warn("selectResourceURL failed or not provided:",c)}t.updateState({resourceMetadata:r,resourceMetadataError:s,resource:o,authServerUrl:n,oauthMetadata:i,oauthStep:"client_registration"})}catch(e){const n=e instanceof Error?e:new Error(String(e));console.error("Metadata discovery error:",{error:n,serverUrl:t.serverUrl,serverName:t.serverName}),t.updateState({latestError:n,statusMessage:{type:"error",message:`Metadata discovery failed: ${n.message}`}})}}},client_registration:{canTransition:async t=>!!t.state.oauthMetadata,execute:async t=>{try{if(t.updateState({latestError:null}),!t.state.oauthMetadata)throw new Error("OAuth metadata not available");let e;try{const n={...t.provider.clientMetadata},r=t.state.resourceMetadata?.scopes_supported||t.state.oauthMetadata.scopes_supported;r&&r.length>0&&(n.scope=r.join(" "));try{e=await Y5(t.serverUrl,{metadata:t.state.oauthMetadata,clientMetadata:n}),t.provider.saveClientInformation(e)}catch(s){if(e=await t.provider.clientInformation(),!e)throw s}}catch(n){console.warn("Dynamic client registration failed, using static client metadata:",n);const r=await t.provider.clientInformation();r?e=r:(e={client_id:`static_client_${Date.now()}`,...t.provider.clientMetadata},t.provider.saveClientInformation(e))}t.updateState({oauthClientInfo:e,oauthStep:"authorization_redirect",statusMessage:{type:"success",message:"Client registration completed successfully."}})}catch(e){const n=e instanceof Error?e:new Error(String(e));console.error("Client registration error:",{error:n,serverUrl:t.serverUrl,serverName:t.serverName,hasOAuthMetadata:!!t.state.oauthMetadata,oauthMetadata:t.state.oauthMetadata,providerRedirectUrl:t.provider.redirectUrl,providerClientMetadata:t.provider.clientMetadata}),t.updateState({latestError:n,statusMessage:{type:"error",message:`Client registration failed: ${n.message}`}})}}},authorization_redirect:{canTransition:async t=>!!t.state.oauthMetadata&&!!t.state.oauthClientInfo,execute:async t=>{try{if(t.updateState({latestError:null}),!t.state.oauthMetadata||!t.state.oauthClientInfo)throw new Error("OAuth metadata or client info not available");const e=t.state.resourceMetadata?.scopes_supported||t.state.oauthMetadata.scopes_supported,n=e&&e.length>0?e.join(" "):void 0,r=new Uint8Array(32);crypto.getRandomValues(r);const s=Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""),i=await H5(t.serverUrl,{metadata:t.state.oauthMetadata,clientInformation:t.state.oauthClientInfo,redirectUrl:t.provider.redirectUrl,scope:n,state:s,resource:t.state.resource??void 0});t.provider.saveCodeVerifier(i.codeVerifier),t.updateState({authorizationUrl:i.authorizationUrl.toString(),oauthStep:"authorization_code",statusMessage:{type:"info",message:"Authorization URL generated. Please complete authorization in your browser."}})}catch(e){const n=e instanceof Error?e:new Error(String(e));t.updateState({latestError:n,statusMessage:{type:"error",message:`Authorization preparation failed: ${n.message}`}})}}},authorization_code:{canTransition:async t=>!!t.state.authorizationCode.trim(),execute:async t=>{try{if(t.updateState({latestError:null,validationError:null}),!t.state.authorizationCode.trim()){t.updateState({validationError:"Authorization code is required"});return}t.updateState({oauthStep:"token_request"})}catch(e){const n=e instanceof Error?e:new Error(String(e));t.updateState({latestError:n,validationError:n.message})}}},token_request:{canTransition:async t=>!!t.state.authorizationCode.trim()&&!!t.state.oauthMetadata,execute:async t=>{try{if(t.updateState({latestError:null}),!t.state.oauthMetadata||!t.state.authorizationCode.trim()||!t.state.oauthClientInfo)throw new Error("OAuth metadata, authorization code, or client info not available");const e=await G5(t.serverUrl,{metadata:t.state.oauthMetadata,clientInformation:t.state.oauthClientInfo,authorizationCode:t.state.authorizationCode,codeVerifier:t.provider.codeVerifier(),redirectUri:t.provider.redirectUrl});t.updateState({oauthTokens:e,oauthStep:"complete",statusMessage:{type:"success",message:"OAuth authentication completed successfully!"}})}catch(e){const n=e instanceof Error?e:new Error(String(e));t.updateState({latestError:n,statusMessage:{type:"error",message:`Token exchange failed: ${n.message}`}})}}},complete:{canTransition:async()=>!1,execute:async()=>{}}};class dxe{constructor(e){this.context=e}async proceedToNextStep(){const e=this.context.state.oauthStep,n=uxe[e];if(!n)return console.error("No transition found for step:",e),!1;try{return this.context.updateState({isInitiatingAuth:!0}),await n.canTransition(this.context)?(await n.execute(this.context),!0):(console.warn("Cannot transition from step:",e),!1)}catch(r){console.error("Error during state transition:",r);const s=r instanceof Error?r:new Error(String(r));return this.context.updateState({latestError:s,statusMessage:{type:"error",message:s.message}}),!1}finally{this.context.updateState({isInitiatingAuth:!1})}}reset(){this.context.updateState({isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null})}}const fxe=({message:t})=>{let e,n,r;switch(t.type){case"error":e="bg-red-50 dark:bg-red-950/50",n="text-red-700 dark:text-red-400",r="border-red-200 dark:border-red-800";break;case"success":e="bg-green-50 dark:bg-green-950/50",n="text-green-700 dark:text-green-400",r="border-green-200 dark:border-green-800";break;case"info":default:e="bg-blue-50 dark:bg-blue-950/50",n="text-blue-700 dark:text-blue-400",r="border-blue-200 dark:border-blue-800";break}return f.jsx("div",{className:`p-3 rounded-md border ${e} ${r} ${n} mb-4`,children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Ug,{className:"h-4 w-4"}),f.jsx("p",{className:"text-sm",children:t.message})]})})},hxe=({serverConfig:t,serverEntry:e,serverName:n})=>{const[r,s]=w.useState(LP),[i,o]=w.useState(Jm),[c,u]=w.useState(!1),d=w.useCallback(T=>{s(P=>({...P,...T}))},[]),p=w.useCallback(T=>{o(P=>({...P,...T}))},[]),m=w.useCallback(()=>{if(u(!1),p(Jm),r.serverUrl)try{new S1(r.serverUrl).clear()}catch(T){console.warn("Failed to clear debug OAuth provider state:",T)}},[r.serverUrl,p]);w.useEffect(()=>{if(t&&t.url&&n){const T=t.url.toString(),P=mi(n);d({serverUrl:T,tokens:P,error:null,statusMessage:null})}else d(LP)},[t,n,d]),w.useEffect(()=>{m()},[n,m]);const v=w.useCallback(async()=>{if(!t||!r.serverUrl||!n){d({statusMessage:{type:"error",message:"Please select a server before refreshing tokens"}});return}d({isAuthenticating:!0,error:null,statusMessage:null});try{let T;if(r.tokens)T=await uk(n);else{const P={serverName:n,serverUrl:r.serverUrl};T=await nv(P)}if(T.success){const P=mi(n);d({tokens:P,isAuthenticating:!1,statusMessage:{type:"success",message:r.tokens?"Tokens refreshed successfully!":T.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{d({statusMessage:null})},3e3)}else d({isAuthenticating:!1,error:T.error||"OAuth operation failed",statusMessage:{type:"error",message:`Failed: ${T.error||"OAuth operation failed"}`}})}catch(T){d({isAuthenticating:!1,error:T instanceof Error?T.message:String(T),statusMessage:{type:"error",message:`Failed: ${T instanceof Error?T.message:String(T)}`}})}},[t,r.serverUrl,r.tokens,n,d]),y=w.useCallback(async()=>{if(!t||!r.serverUrl||!n){d({statusMessage:{type:"error",message:"Please select a server before starting OAuth"}});return}d({isAuthenticating:!0,error:null,statusMessage:null});try{kh(n);const T={serverName:n,serverUrl:r.serverUrl},P=await nv(T);if(P.success){const N=mi(n);d({tokens:N,isAuthenticating:!1,statusMessage:{type:"success",message:P.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{d({statusMessage:null})},3e3)}else d({isAuthenticating:!1,error:P.error||"OAuth authentication failed",statusMessage:{type:"error",message:`Failed: ${P.error||"OAuth authentication failed"}`}})}catch(T){d({isAuthenticating:!1,error:T instanceof Error?T.message:String(T),statusMessage:{type:"error",message:`Failed: ${T instanceof Error?T.message:String(T)}`}})}},[t,r.serverUrl,n,d]),x=w.useMemo(()=>{if(!t||!n||!r.serverUrl)return null;const T=new S1(r.serverUrl);return new dxe({state:i,serverUrl:r.serverUrl,serverName:n,provider:T,updateState:p})},[t,n,r.serverUrl,i,p]),_=w.useCallback(()=>{m(),u(!0),p(Jm),x&&x.proceedToNextStep()},[x,p,r.serverUrl,n,t,m]),E=w.useCallback(async()=>{x&&await x.proceedToNextStep()},[x]),S=w.useCallback(()=>{if(u(!1),p(Jm),n){const T=mi(n);d({tokens:T})}},[n,d,p]),A=w.useCallback(()=>{t&&r.serverUrl&&n&&(kh(n),d({tokens:null,error:null,statusMessage:{type:"success",message:"OAuth tokens cleared successfully"}}),setTimeout(()=>{d({statusMessage:null})},3e3))},[t,r.serverUrl,n,d]),C=t&&"url"in t,R=C,j=n&&(e?.oauthTokens||mi(n)||e?.connectionStatus==="oauth-flow");return t?R?f.jsx("div",{className:"h-[calc(100vh-120px)] flex flex-col",children:f.jsxs("div",{className:"h-full flex flex-col bg-background",children:[f.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(Vn,{className:"h-4 w-4 text-muted-foreground"}),f.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),f.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:f.jsxs("div",{className:"space-y-6 max-w-2xl",children:[f.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:[f.jsxs("div",{children:["Name: ",e?.name||"Unknown"]}),C&&f.jsxs("div",{children:["URL: ",t.url.toString()]}),f.jsx("div",{children:"Type: HTTP Server"})]})]}),f.jsxs("div",{className:"rounded-md border p-6 space-y-6",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Vn,{className:"h-5 w-5"}),f.jsx("h3",{className:"text-lg font-medium",children:"OAuth Authentication"})]}),f.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:j?"Manage OAuth authentication for this server.":"This server supports OAuth authentication. Use Quick OAuth to authenticate and get tokens."}),r.statusMessage&&f.jsx(fxe,{message:r.statusMessage}),r.error&&!r.statusMessage&&f.jsx("div",{className:"p-3 rounded-md border border-red-200 bg-red-50 text-red-700 mb-4",children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Ug,{className:"h-4 w-4"}),f.jsx("p",{className:"text-sm",children:r.error})]})}),f.jsxs("div",{className:"space-y-4",children:[r.tokens&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("p",{className:"text-sm font-medium",children:"Current Tokens:"}),f.jsxs("div",{className:"bg-muted p-3 rounded-md space-y-2",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Access Token:"}),f.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.access_token.substring(0,40),"..."]})]}),r.tokens.refresh_token&&f.jsxs("div",{children:[f.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Refresh Token:"}),f.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.refresh_token.substring(0,40),"..."]})]}),f.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[f.jsxs("span",{children:["Type: ",r.tokens.token_type]}),r.tokens.expires_in&&f.jsxs("span",{children:["Expires in: ",r.tokens.expires_in,"s"]}),r.tokens.scope&&f.jsxs("span",{children:["Scope: ",r.tokens.scope]})]})]})]}),f.jsxs("div",{className:"flex gap-4",children:[f.jsx(Ue,{onClick:r.tokens?v:y,disabled:r.isAuthenticating||!t,className:"flex items-center gap-2",variant:r.tokens?"outline":"default",children:r.isAuthenticating?f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4 animate-spin"}),r.tokens?"Refreshing...":"Authenticating..."]}):f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4"}),r.tokens?"Quick Refresh":"Quick OAuth"]})}),r.tokens&&f.jsx(Ue,{onClick:y,disabled:r.isAuthenticating||!t,className:"flex items-center gap-2",variant:"default",children:r.isAuthenticating?f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4 animate-spin"}),"Authenticating..."]}):f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4"}),"Quick OAuth"]})}),f.jsx(Ue,{variant:"outline",onClick:A,disabled:!t||!r.tokens,children:"Clear Tokens"}),f.jsx(Ue,{variant:"secondary",onClick:_,disabled:r.isAuthenticating||!t,children:"Guided OAuth Flow"})]}),f.jsx("p",{className:"text-xs text-muted-foreground",children:t?r.tokens?"Use Quick Refresh to renew existing tokens, or Quick OAuth to start a fresh authentication flow.":"Use Quick OAuth to authenticate with the server and get tokens.":"Select a server to manage its OAuth authentication."})]}),c&&r.serverUrl&&f.jsx(cxe,{serverUrl:r.serverUrl,flowState:i,updateFlowState:p,proceedToNextStep:E}),c&&f.jsx("div",{className:"mt-4",children:f.jsx(Ue,{variant:"outline",onClick:S,children:"Exit Guided Flow"})})]})]})})]})}):f.jsx("div",{className:"h-[calc(100vh-120px)] flex flex-col",children:f.jsxs("div",{className:"h-full flex flex-col bg-background",children:[f.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(Vn,{className:"h-4 w-4 text-muted-foreground"}),f.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),f.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:f.jsxs("div",{className:"space-y-6 max-w-2xl",children:[f.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:[f.jsxs("div",{children:["Name: ",e?.name||"Unknown"]}),C&&f.jsxs("div",{children:["URL: ",t.url.toString()]}),!C&&f.jsxs("div",{children:["Command: ",t.command]}),f.jsxs("div",{children:["Type: ",C?"HTTP Server":"STDIO Server"]})]})]}),f.jsx(Pa,{children:f.jsx(Aq,{className:"pt-6",children:f.jsxs("div",{className:"text-center space-y-4",children:[f.jsx("div",{className:"mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center",children:f.jsx(Vn,{className:"h-6 w-6 text-muted-foreground"})}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("h3",{className:"text-lg font-medium",children:C?"No Authentication Required":"No OAuth Support"}),f.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:C?`The HTTP server "${e?.name||"Unknown"}" is connected without OAuth authentication.`:"STDIO servers don't support OAuth authentication."}),C&&f.jsx("p",{className:"text-xs text-muted-foreground max-w-md mx-auto mt-2",children:"If this server supports OAuth, you can reconnect it with OAuth enabled from the Servers tab."})]})]})})})]})})]})}):f.jsx(dp,{icon:QQ,title:"No Server Selected",description:"Connect to an MCP server to manage authentication and OAuth settings."})};function pxe(){const t=new URLSearchParams(window.location.search),e=t.get("code"),n=t.get("error"),r=t.get("error_description");return f.jsx("div",{className:"flex items-center justify-center min-h-[100vh] p-4",children:f.jsx("div",{className:"mt-4 p-4 bg-secondary rounded-md max-w-md w-full border",children:e?f.jsxs(f.Fragment,{children:[f.jsx("p",{className:"mb-2 text-sm",children:"Please copy this authorization code and return to the Auth screen:"}),f.jsx("code",{className:"block p-2 bg-muted rounded-sm overflow-x-auto text-xs",children:e}),f.jsx("p",{className:"mt-4 text-xs text-muted-foreground",children:"Close this tab and paste the code in the OAuth flow to complete authentication."})]}):f.jsxs(f.Fragment,{children:[f.jsx("p",{className:"mb-2 text-sm font-medium",children:"No authorization code found"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:[f.jsxs("div",{children:["Error: ",n||"unknown"]}),r&&f.jsxs("div",{children:["Description: ",decodeURIComponent(r)]})]})]})})})}const cw=768;function mxe(){const[t,e]=w.useState(void 0);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${cw-1}px)`),r=()=>{e(window.innerWidth<cw)};return n.addEventListener("change",r),e(window.innerWidth<cw),()=>n.removeEventListener("change",r)},[]),!!t}function gxe({...t}){return f.jsx(hE,{"data-slot":"sheet",...t})}function vxe({...t}){return f.jsx(pE,{"data-slot":"sheet-portal",...t})}function yxe({className:t,...e}){return f.jsx(mE,{"data-slot":"sheet-overlay",className:Me("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function xxe({className:t,children:e,side:n="right",...r}){return f.jsxs(vxe,{children:[f.jsx(yxe,{}),f.jsxs(gE,{"data-slot":"sheet-content",className:Me("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",n==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",n==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",n==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",n==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",t),...r,children:[e,f.jsxs(Kv,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[f.jsx(ip,{className:"size-4"}),f.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function bxe({className:t,...e}){return f.jsx("div",{"data-slot":"sheet-header",className:Me("flex flex-col gap-1.5 p-4",t),...e})}function _xe({className:t,...e}){return f.jsx(vE,{"data-slot":"sheet-title",className:Me("text-foreground font-semibold",t),...e})}function wxe({className:t,...e}){return f.jsx(yE,{"data-slot":"sheet-description",className:Me("text-muted-foreground text-sm",t),...e})}const Sxe="sidebar_state",Exe=60*60*24*7,kxe="16rem",Cxe="18rem",Txe="3rem",Axe="b",p6=w.createContext(null);function $C(){const t=w.useContext(p6);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}function Rxe({defaultOpen:t=!0,open:e,onOpenChange:n,className:r,style:s,children:i,...o}){const c=mxe(),[u,d]=w.useState(!1),[p,m]=w.useState(t),v=e??p,y=w.useCallback(S=>{const A=typeof S=="function"?S(v):S;n?n(A):m(A),document.cookie=`${Sxe}=${A}; path=/; max-age=${Exe}`},[n,v]),x=w.useCallback(()=>c?d(S=>!S):y(S=>!S),[c,y,d]);w.useEffect(()=>{const S=A=>{A.key===Axe&&(A.metaKey||A.ctrlKey)&&(A.preventDefault(),x())};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[x]);const _=v?"expanded":"collapsed",E=w.useMemo(()=>({state:_,open:v,setOpen:y,isMobile:c,openMobile:u,setOpenMobile:d,toggleSidebar:x}),[_,v,y,c,u,d,x]);return f.jsx(p6.Provider,{value:E,children:f.jsx(hy,{delayDuration:0,children:f.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":kxe,"--sidebar-width-icon":Txe,...s},className:Me("group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",r),...o,children:i})})})}function Nxe({side:t="left",variant:e="sidebar",collapsible:n="offcanvas",className:r,children:s,...i}){const{isMobile:o,state:c,openMobile:u,setOpenMobile:d}=$C();return n==="none"?f.jsx("div",{"data-slot":"sidebar",className:Me("bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",r),...i,children:s}):o?f.jsx(gxe,{open:u,onOpenChange:d,...i,children:f.jsxs(xxe,{"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden",style:{"--sidebar-width":Cxe},side:t,children:[f.jsxs(bxe,{className:"sr-only",children:[f.jsx(_xe,{children:"Sidebar"}),f.jsx(wxe,{children:"Displays the mobile sidebar."})]}),f.jsx("div",{className:"flex h-full w-full flex-col",children:s})]})}):f.jsxs("div",{className:"group peer text-sidebar-foreground hidden md:block","data-state":c,"data-collapsible":c==="collapsed"?n:"","data-variant":e,"data-side":t,"data-slot":"sidebar",children:[f.jsx("div",{"data-slot":"sidebar-gap",className:Me("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",e==="floating"||e==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),f.jsx("div",{"data-slot":"sidebar-container",className:Me("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",t==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",e==="floating"||e==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",r),...i,children:f.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:"bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm",children:s})})]})}function jxe({className:t,onClick:e,...n}){const{toggleSidebar:r}=$C();return f.jsxs(Ue,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon",className:Me("size-7",t),onClick:s=>{e?.(s),r()},...n,children:[f.jsx(MQ,{}),f.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function Pxe({className:t,...e}){return f.jsx("main",{"data-slot":"sidebar-inset",className:Me("bg-background relative flex w-full flex-1 flex-col","md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",t),...e})}function Mxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:Me("flex flex-col gap-2 p-2 drag",t),...e})}function Oxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-footer","data-sidebar":"footer",className:Me("flex flex-col gap-2 p-2",t),...e})}function Dxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:Me("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...e})}function Ixe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-group","data-sidebar":"group",className:Me("relative flex w-full min-w-0 flex-col p-2",t),...e})}function Lxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-group-content","data-sidebar":"group-content",className:Me("w-full text-sm",t),...e})}function m6({className:t,...e}){return f.jsx("ul",{"data-slot":"sidebar-menu","data-sidebar":"menu",className:Me("flex w-full min-w-0 flex-col gap-1",t),...e})}function g6({className:t,...e}){return f.jsx("li",{"data-slot":"sidebar-menu-item","data-sidebar":"menu-item",className:Me("group/menu-item relative",t),...e})}const zxe=fy("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:p-0!"}},defaultVariants:{variant:"default",size:"default"}});function v6({asChild:t=!1,isActive:e=!1,variant:n="default",size:r="default",tooltip:s,className:i,...o}){const c=t?oE:"button",{isMobile:u,state:d}=$C(),p=f.jsx(c,{"data-slot":"sidebar-menu-button","data-sidebar":"menu-button","data-size":r,"data-active":e,className:Me(zxe({variant:n,size:r}),i),...o});return s?(typeof s=="string"&&(s={children:s}),f.jsxs(Ui,{children:[f.jsx(Vi,{asChild:!0,children:p}),f.jsx(Bi,{side:"right",align:"center",hidden:d!=="collapsed"||u,...s})]})):p}function $xe({items:t,onItemClick:e}){const n=s=>{e&&e(s)},r=s=>s.isActive||!1;return f.jsx(Ixe,{children:f.jsx(Lxe,{children:f.jsx(m6,{children:t.map(s=>f.jsx(g6,{children:f.jsxs(v6,{tooltip:s.title,isActive:r(s),onClick:()=>n(s.url),className:r(s)?"[&[data-active=true]]:bg-black/5 dark:[&[data-active=true]]:bg-white/5 cursor-pointer":"cursor-pointer",children:[s.icon&&f.jsx(s.icon,{className:"h-4 w-4"}),f.jsx("span",{children:s.title})]})},s.title))})})})}function Fxe(t){const e=document.documentElement;e.classList.add("disable-transitions"),e.classList.toggle("dark",t==="dark"),requestAnimationFrame(()=>{e.classList.remove("disable-transitions")})}function Uxe(){const t=$h(r=>r.themeMode),e=$h(r=>r.setThemeMode),n=()=>{const r=t==="dark"?"light":"dark";Fxe(r),e(r)};return f.jsxs(v6,{tooltip:`Switch to ${t==="dark"?"light":"dark"} mode`,onClick:n,className:"cursor-pointer",children:[t==="dark"?f.jsx(sX,{className:"h-4 w-4"}):f.jsx(jQ,{className:"h-4 w-4"}),f.jsx("span",{children:t==="dark"?"Light mode":"Dark mode"})]})}const gD=[{id:"connection",items:[{title:"MCP Servers",url:"#servers",icon:Ey},{title:"Playground",url:"#chat",icon:Yw},{title:"Tracing",url:"#tracing",icon:AK}]},{id:"tools",items:[{title:"Tools",url:"#tools",icon:yQ},{title:"Resources",url:"#resources",icon:OK},{title:"Prompts",url:"#prompts",icon:AQ},{title:"Auth",url:"#auth",icon:bQ},{title:"Evals",url:"#evals",icon:y5}]},{id:"beta",items:[{title:"Interceptor (beta)",url:"#interceptor",icon:pQ}]},{id:"settings",items:[{title:"Feedback",url:"https://github.com/MCPJam/inspector/issues/new",icon:Yw},{title:"Settings",url:"#settings",icon:QE}]}];function Vxe({onNavigate:t,activeTab:e,...n}){const r=$h(i=>i.themeMode),s=i=>{t&&i.startsWith("#")?t(i.slice(1)):window.open(i,"_blank")};return f.jsxs(Nxe,{collapsible:"icon",...n,children:[f.jsx(Mxe,{children:f.jsx("div",{className:"flex items-center justify-center px-4 py-4",children:f.jsx("img",{src:r==="dark"?"/mcp_jam_dark.png":"/mcp_jam_light.png",alt:"MCP Jam",className:"h-4 w-auto"})})}),f.jsx(Dxe,{children:gD.map((i,o)=>f.jsxs(w.Fragment,{children:[f.jsx($xe,{items:i.items.map(c=>({...c,isActive:c.url===`#${e}`})),onItemClick:s}),o<gD.length-1&&f.jsx("div",{className:"mx-4 my-2 border-t border-border/50"})]},i.id))}),f.jsx(Oxe,{children:f.jsx(m6,{children:f.jsx(g6,{children:f.jsx(Uxe,{})})})})]})}function Bxe(t){switch(t){case"connected":return"bg-green-500 dark:bg-green-400";case"connecting":return"bg-yellow-500 dark:bg-yellow-400 animate-pulse";case"failed":return"bg-red-500 dark:bg-red-400";case"disconnected":return"bg-muted-foreground";default:return"bg-muted-foreground"}}function qxe(t){switch(t){case"connected":return"Connected";case"connecting":return"Connecting...";case"failed":return"Failed";case"disconnected":return"Disconnected";default:return"Unknown"}}function Hxe({connectedServerConfigs:t,selectedServer:e,selectedMultipleServers:n,isMultiSelectEnabled:r,onServerChange:s,onMultiServerToggle:i,onConnect:o}){const[c,u]=w.useState(!1),d=Object.entries(t).filter(([,p])=>p.enabled!==!1);return d.length===0?null:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-wrap",children:[d.map(([p,m])=>{const v=r?n.includes(p):e===p;return f.jsxs("button",{onClick:()=>r?i(p):s(p),className:Me("group relative flex items-center gap-3 px-4 py-3 border-r border-b border-border transition-all duration-200 cursor-pointer","hover:bg-accent hover:text-accent-foreground",v?"bg-muted text-foreground":"bg-background text-foreground"),children:[r&&f.jsx("div",{className:Me("w-4 h-4 rounded border-2 flex items-center justify-center transition-colors",v?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30 hover:border-primary/50"),children:v&&f.jsx(Fi,{className:"w-3 h-3"})}),f.jsx("div",{className:Me("w-2 h-2 rounded-full",Bxe(m.connectionStatus)),title:qxe(m.connectionStatus)}),f.jsx("span",{className:"text-sm font-medium truncate max-w-36",children:p}),f.jsx("div",{className:"text-xs opacity-70",children:m.config.command?"STDIO":"HTTP"})]},p)}),f.jsxs("button",{onClick:()=>u(!0),className:Me("group relative flex items-center gap-3 px-4 py-3 border-r border-b border-border transition-all duration-200 cursor-pointer","hover:bg-accent hover:text-accent-foreground","bg-background text-muted-foreground border-dashed"),children:[r&&f.jsx("div",{className:"w-4 h-4"}),f.jsx("span",{className:"text-sm font-medium",children:"Add Server"}),f.jsx("div",{className:"text-xs opacity-70",children:"+"})]})]}),f.jsx(vS,{mode:"add",isOpen:c,onClose:()=>u(!1),onSubmit:p=>o(p)})]})}const Gxe="modulepreload",Yxe=function(t){return"/"+t},vD={},Wxe=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let d=function(p){return Promise.all(p.map(m=>Promise.resolve(m).then(v=>({status:"fulfilled",value:v}),v=>({status:"rejected",reason:v}))))};var o=d;document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");s=d(n.map(p=>{if(p=Yxe(p),p in vD)return;vD[p]=!0;const m=p.endsWith(".css"),v=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${v}`))return;const y=document.createElement("link");if(y.rel=m?"stylesheet":Gxe,m||(y.as="script"),y.crossOrigin="",y.href=p,u&&y.setAttribute("nonce",u),document.head.appendChild(y),m)return new Promise((x,_)=>{y.addEventListener("load",x),y.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(c){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=c,window.dispatchEvent(u),!u.defaultPrevented)throw c}return s.then(c=>{for(const u of c||[])u.status==="rejected"&&i(u.reason);return e().catch(i)})},E1={servers:{},selectedServer:"none",selectedMultipleServers:[],isMultiSelectMode:!1},_f=(t,e,n={})=>({...t,connectionStatus:e,...n});function Kxe(t,e){switch(e.type){case"HYDRATE_STATE":return e.payload;case"UPSERT_SERVER":return{...t,servers:{...t.servers,[e.name]:e.server}};case"CONNECT_REQUEST":{const n=t.servers[e.name],r=n?_f(n,"connecting",{enabled:!0}):{name:e.name,config:e.config,lastConnectionTime:new Date,connectionStatus:"connecting",retryCount:0,enabled:!0};return{...t,servers:{...t.servers,[e.name]:{...r,config:e.config}},selectedServer:e.select?e.name:t.selectedServer}}case"CONNECT_SUCCESS":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:_f(n,"connected",{config:e.config,lastConnectionTime:new Date,retryCount:0,lastError:void 0,oauthTokens:e.tokens??n.oauthTokens,enabled:!0})}}:t}case"CONNECT_FAILURE":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:_f(n,"failed",{retryCount:n.retryCount,lastError:e.error})}}:t}case"RECONNECT_REQUEST":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:_f(n,"connecting",{enabled:!0})}}:t}case"DISCONNECT":{const n=t.servers[e.name];if(!n)return t;const r=t.selectedServer===e.name?"none":t.selectedServer;return{...t,servers:{...t.servers,[e.name]:_f(n,"disconnected",{enabled:!1,lastError:e.error??n.lastError})},selectedServer:r,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"REMOVE_SERVER":{const{[e.name]:n,...r}=t.servers;return{...t,servers:r,selectedServer:t.selectedServer===e.name?"none":t.selectedServer,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"SYNC_AGENT_STATUS":{const n=new Map(e.servers.map(s=>[s.id,s.status])),r={};for(const[s,i]of Object.entries(t.servers)){if(i.connectionStatus==="connecting"||i.connectionStatus==="oauth-flow"){r[s]=i;continue}const c=n.get(s);c?r[s]={...i,connectionStatus:c}:r[s]={...i,connectionStatus:"disconnected"}}return{...t,servers:r}}case"SELECT_SERVER":return{...t,selectedServer:e.name};case"SET_MULTI_SELECTED":return{...t,selectedMultipleServers:e.names};case"SET_MULTI_MODE":return{...t,isMultiSelectMode:e.enabled,selectedMultipleServers:e.enabled?[]:t.selectedMultipleServers};default:return t}}const y6="mcp-inspector-state";function Qxe(t){const e=t.config;let n=e;if(e&&typeof e.url=="string")try{n={...e,url:new URL(e.url)}}catch{}return{...t,config:n,connectionStatus:t.connectionStatus||"disconnected",retryCount:t.retryCount||0,lastConnectionTime:t.lastConnectionTime?new Date(t.lastConnectionTime):new Date,enabled:t.enabled!==!1}}function Xxe(){try{const t=localStorage.getItem(y6);if(!t)return E1;const e=JSON.parse(t);return{servers:Object.fromEntries(Object.entries(e.servers||{}).map(([r,s])=>[r,Qxe(s)])),selectedServer:e.selectedServer||"none",selectedMultipleServers:e.selectedMultipleServers||[],isMultiSelectMode:e.isMultiSelectMode||!1}}catch{return E1}}function Zxe(t){const e={...t,servers:Object.fromEntries(Object.entries(t.servers).map(([n,r])=>{const s=r.config,i=s&&s.url instanceof URL?{...s,url:s.url.toString()}:s;return[n,{...r,config:i}]}))};localStorage.setItem(y6,JSON.stringify(e))}async function wf(t,e){return(await fetch("/api/mcp/connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverConfig:t,serverId:e})})).json()}async function Jxe(t){return(await fetch(`/api/mcp/servers/${encodeURIComponent(t)}`,{method:"DELETE"})).json()}async function e0e(){return(await fetch("/api/mcp/servers")).json()}async function t0e(t){if(!t.oauthTokens)return{kind:"ready",serverConfig:t.config,tokens:void 0};const e=await uk(t.name);if(e.success&&e.serverConfig)return{kind:"ready",serverConfig:e.serverConfig,tokens:mi(t.name)};const n=t.config?.url?.toString?.();if(n){kh(t.name);const r={serverName:t.name,serverUrl:n,clientId:t.oauthTokens?.client_id,clientSecret:t.oauthTokens?.client_secret},s=await nv(r);return s.success&&s.serverConfig?{kind:"ready",serverConfig:s.serverConfig,tokens:mi(t.name)}:s.success&&!s.serverConfig?{kind:"redirect"}:{kind:"error",error:s.error||"OAuth init failed"}}return{kind:"error",error:"OAuth refresh failed and no URL present"}}function uw(t){return t.type==="stdio"?{command:t.command,args:t.args,env:t.env}:{url:new URL(t.url),requestInit:{headers:t.headers||{}}}}function n0e(){const t=K5("Connections"),[e,n]=w.useReducer(Kxe,E1),[r,s]=w.useState(!0),i=w.useRef(new Map),o=T=>{const N=(i.current.get(T)??0)+1;return i.current.set(T,N),N},c=(T,P)=>(i.current.get(T)??0)!==P;w.useEffect(()=>{try{const T=Xxe();n({type:"HYDRATE_STATE",payload:T})}catch(T){t.error("Failed to load saved state",{error:T instanceof Error?T.message:"Unknown error"})}finally{s(!1)}},[t]),w.useEffect(()=>{r||Zxe(e)},[e,r]);const u=T=>{if(T.type==="stdio")return!T.command||T.command.trim()===""?"Command is required for STDIO connections":null;if(!T.url||T.url.trim()==="")return"URL is required for HTTP connections";try{new URL(T.url)}catch(P){return`Invalid URL format: ${T.url} ${P}`}return null},d=w.useCallback(()=>{const T=Object.entries(e.servers).filter(([,P])=>P.enabled!==!1).map(([P])=>P);n({type:"SET_MULTI_SELECTED",names:T})},[e.servers]),p=w.useCallback(async T=>{window.history.replaceState({},document.title,window.location.pathname);try{const P=await W5(T);if(P.success&&P.serverConfig&&P.serverName){const N=P.serverName;n({type:"CONNECT_REQUEST",name:N,config:P.serverConfig,select:!0});try{const L=await wf(P.serverConfig,N);L.success?(n({type:"CONNECT_SUCCESS",name:N,config:P.serverConfig,tokens:mi(N)}),t.info("OAuth connection successful",{serverName:N}),Wt.success(`OAuth connection successful! Connected to ${N}.`)):(n({type:"CONNECT_FAILURE",name:N,error:L.error||"Connection test failed after OAuth"}),t.error("OAuth connection test failed",{serverName:N,error:L.error}),Wt.error(`OAuth succeeded but connection test failed: ${L.error}`))}catch(L){const O=L instanceof Error?L.message:"Unknown connection error";n({type:"CONNECT_FAILURE",name:N,error:O}),t.error("OAuth connection test error",{serverName:N,error:O}),Wt.error(`OAuth succeeded but connection test failed: ${O}`)}}else throw new Error(P.error||"OAuth callback failed")}catch(P){const N=P instanceof Error?P.message:"Unknown error";Wt.error(`Error completing OAuth flow: ${N}`),t.error("OAuth callback failed",{error:N})}},[t]);w.useEffect(()=>{if(!r){const T=new URLSearchParams(window.location.search),P=T.get("code"),N=T.get("error");P?p(P):N&&(Wt.error(`OAuth authorization failed: ${N}`),localStorage.removeItem("mcp-oauth-pending"),window.history.replaceState({},document.title,window.location.pathname))}},[r,p]);const m=w.useCallback(async T=>{const P=u(T);if(P){Wt.error(P);return}const N=uw(T);n({type:"CONNECT_REQUEST",name:T.name,config:N,select:!0});const L=o(T.name);try{if(T.type==="http"&&T.useOAuth&&T.url){n({type:"UPSERT_SERVER",name:T.name,server:{name:T.name,config:N,lastConnectionTime:new Date,connectionStatus:"oauth-flow",retryCount:0,enabled:!0}});const{initiateOAuth:z}=await Wxe(async()=>{const{initiateOAuth:Y}=await Promise.resolve().then(()=>JJ);return{initiateOAuth:Y}},void 0),U={serverName:T.name,serverUrl:T.url,clientId:T.clientId,clientSecret:T.clientSecret};T.oauthScopes&&T.oauthScopes.length>0&&(U.scopes=T.oauthScopes);const K=await z(U);if(K.success){if(K.serverConfig){const Y=await wf(K.serverConfig,T.name);if(c(T.name,L))return;Y.success?(n({type:"CONNECT_SUCCESS",name:T.name,config:K.serverConfig,tokens:mi(T.name)}),Wt.success("Connected successfully with OAuth!")):(n({type:"CONNECT_FAILURE",name:T.name,error:Y.error||"OAuth connection test failed"}),Wt.error(`OAuth succeeded but connection failed: ${Y.error}`))}else Wt.success("OAuth flow initiated. You will be redirected to authorize access.");return}else{if(c(T.name,L))return;n({type:"CONNECT_FAILURE",name:T.name,error:K.error||"OAuth initialization failed"}),Wt.error(`OAuth initialization failed: ${K.error}`);return}}const O=await wf(N,T.name);if(c(T.name,L))return;O.success?(n({type:"CONNECT_SUCCESS",name:T.name,config:N}),t.info("Connection successful",{serverName:T.name}),Wt.success("Connected successfully!")):(n({type:"CONNECT_FAILURE",name:T.name,error:O.error||"Connection test failed"}),t.error("Connection failed",{serverName:T.name,error:O.error}),Wt.error(`Failed to connect to ${T.name}`))}catch(O){const z=O instanceof Error?O.message:"Unknown error";if(c(T.name,L))return;n({type:"CONNECT_FAILURE",name:T.name,error:z}),t.error("Connection failed",{serverName:T.name,error:z}),Wt.error(`Network error: ${z}`)}},[e.servers,t]),v=w.useRef(!1);w.useEffect(()=>{!r&&!v.current&&(v.current=!0,fetch("/api/mcp-cli-config").then(T=>T.json()).then(T=>{const P=T.config;if(P){if(P.servers&&Array.isArray(P.servers)){const N=P.autoConnectServer;t.info("Processing CLI-provided MCP servers (from config file)",{serverCount:P.servers.length,autoConnectServer:N||"all",cliConfig:P}),P.servers.forEach(L=>{const O={name:L.name||"CLI Server",type:L.type==="sse"?"http":L.type||"stdio",command:L.command,args:L.args||[],url:L.url,env:L.env||{}},z=uw(O);n({type:"UPSERT_SERVER",name:O.name,server:{name:O.name,config:z,lastConnectionTime:new Date,connectionStatus:"disconnected",retryCount:0,enabled:!1}}),!N||L.name===N?(t.info("Auto-connecting to server",{serverName:L.name}),m(O)):t.info("Skipping auto-connect for server",{serverName:L.name,reason:"filtered out"})});return}if(P.command){t.info("Auto-connecting to CLI-provided MCP server",{cliConfig:P});const N={name:P.name||"CLI Server",type:"stdio",command:P.command,args:P.args||[],env:P.env||{}};m(N)}}}).catch(T=>{t.debug("Could not fetch CLI config from API",{error:T})}))},[r,m,t,e.servers]);const y=w.useCallback(async T=>{const P=e.servers[T];return P?.oauthTokens&&P.oauthTokens.access_token||null},[e.servers]),x=w.useCallback(async T=>{t.info("Disconnecting from server",{serverName:T}),n({type:"DISCONNECT",name:T});try{const P=await Jxe(T);P.success||n({type:"DISCONNECT",name:T,error:P.error})}catch(P){n({type:"DISCONNECT",name:T,error:P instanceof Error?P.message:"Unknown error"})}},[]),_=w.useCallback(async T=>{t.info("Removing server",{serverName:T}),kh(T),n({type:"REMOVE_SERVER",name:T})},[]),E=w.useCallback(async T=>{t.info("Reconnecting to server",{serverName:T});const P=e.servers[T];if(!P)throw new Error(`Server ${T} not found`);n({type:"RECONNECT_REQUEST",name:T});const N=o(T);try{const L=await t0e(P);if(L.kind==="redirect")return;if(L.kind==="error"){if(c(T,N))return;n({type:"CONNECT_FAILURE",name:T,error:L.error}),Wt.error(`Failed to connect: ${T}`);return}const O=await wf(L.serverConfig,T);if(c(T,N))return;if(O.success)return n({type:"CONNECT_SUCCESS",name:T,config:L.serverConfig,tokens:L.tokens}),t.info("Reconnection successful",{serverName:T,result:O}),{success:!0};n({type:"CONNECT_FAILURE",name:T,error:O.error||"Connection test failed"}),t.error("Reconnection failed",{serverName:T,result:O}),Wt.error(`Failed to connect: ${T}`)}catch(L){const O=L instanceof Error?L.message:"Unknown error";if(c(T,N))return;throw n({type:"CONNECT_FAILURE",name:T,error:O}),t.error("Reconnection failed",{serverName:T,error:O}),L}},[e.servers]);w.useEffect(()=>{if(r)return;(async()=>{try{const P=await e0e();P?.success&&P.servers&&n({type:"SYNC_AGENT_STATUS",servers:P.servers})}catch(P){t.debug("Failed to sync server status on startup",{error:P instanceof Error?P.message:"Unknown error"})}})()},[r,t]);const S=w.useCallback(T=>{n({type:"SELECT_SERVER",name:T})},[]),A=w.useCallback(T=>{n({type:"SET_MULTI_SELECTED",names:T})},[]),C=w.useCallback(T=>{n({type:"SET_MULTI_MODE",enabled:T})},[]),R=w.useCallback(T=>{const P=e.selectedMultipleServers,N=P.includes(T)?P.filter(L=>L!==T):[...P,T];n({type:"SET_MULTI_SELECTED",names:N})},[e.selectedMultipleServers]),j=w.useCallback(async(T,P)=>{const N=e.servers[T];if(N?.oauthTokens!=null&&P.useOAuth&&P.name===T&&P.type==="http"&&P.url===(N?.config).url?.toString()&&N){const z=uw(P);n({type:"CONNECT_REQUEST",name:T,config:z});try{if((await wf(N.config,T)).success){n({type:"CONNECT_SUCCESS",name:T,config:z}),Wt.success("Server configuration updated successfully!");return}else console.warn("OAuth connection test failed, falling back to full reconnect")}catch(U){console.warn("OAuth connection test error, falling back to full reconnect",U)}}await x(T),await m(P),e.selectedServer===T&&P.name!==T&&S(P.name)},[e.servers,e.selectedServer,x,m]);return{appState:e,isLoading:r,connectedServerConfigs:e.servers,selectedServerEntry:e.servers[e.selectedServer],selectedMCPConfig:e.servers[e.selectedServer]?.config,selectedMCPConfigs:e.selectedMultipleServers.map(T=>e.servers[T]).filter(Boolean),selectedMCPConfigsMap:e.selectedMultipleServers.reduce((T,P)=>(e.servers[P]&&(T[P]=e.servers[P].config),T),{}),isMultiSelectMode:e.isMultiSelectMode,handleConnect:m,handleDisconnect:x,handleReconnect:E,handleUpdate:j,handleRemoveServer:_,setSelectedServer:S,setSelectedMCPConfigs:A,toggleMultiSelectMode:C,toggleServerSelection:R,getValidAccessToken:y,setSelectedMultipleServersToAllServers:d}}var r0e=(t,e,n,r,s,i,o,c)=>{let u=document.documentElement,d=["light","dark"];function p(y){(Array.isArray(t)?t:[t]).forEach(x=>{let _=x==="class",E=_&&i?s.map(S=>i[S]||S):s;_?(u.classList.remove(...E),u.classList.add(i&&i[y]?i[y]:y)):u.setAttribute(x,y)}),m(y)}function m(y){c&&d.includes(y)&&(u.style.colorScheme=y)}function v(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)p(r);else try{let y=localStorage.getItem(e)||n,x=o&&y==="system"?v():y;p(x)}catch{}},s0e=w.createContext(void 0),i0e={setTheme:t=>{},themes:[]},a0e=()=>{var t;return(t=w.useContext(s0e))!=null?t:i0e};w.memo(({forcedTheme:t,storageKey:e,attribute:n,enableSystem:r,enableColorScheme:s,defaultTheme:i,value:o,themes:c,nonce:u,scriptProps:d})=>{let p=JSON.stringify([n,e,i,t,c,o,r,s]).slice(1,-1);return w.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${r0e.toString()})(${p})`}})});const o0e=({...t})=>{const{theme:e="system"}=a0e();return f.jsx($X,{theme:e,className:"toaster group",closeButton:!0,style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function l0e(){w.useEffect(()=>{if(!window.isElectron||!window.electronAPI?.oauth)return;const t=e=>{console.log("Electron OAuth callback received:",e);try{const n=new URL(e),r=new URLSearchParams(n.search),s=r.get("code"),i=r.get("state"),o=r.get("error");if(o){console.error("OAuth error:",o);return}if(s){console.log("OAuth code received, redirecting to callback page");const c=new URL("/callback",window.location.origin);c.searchParams.set("code",s),i&&c.searchParams.set("state",i),window.location.href=c.toString()}}catch(n){console.error("Failed to parse OAuth callback URL:",n)}};return window.electronAPI.oauth.onCallback(t),()=>{window.electronAPI?.oauth&&window.electronAPI.oauth.removeCallback()}},[])}function c0e(){const{user:t}=tc(),{isAuthenticated:e,isLoading:n}=pd(),r=e6("users:ensureUser"),s=w.useRef(null);w.useEffect(()=>{e||(s.current=null)},[e]),w.useEffect(()=>{if(!n){if(!e&&t)throw console.log("useEnsureDbUser: not authenticated"),new Error("Not authenticated");e&&t&&s.current!==t.id&&r().then(i=>{s.current=t.id}).catch(i=>{console.error("[auth] ensureUser failed",i),s.current=null})}},[e,n,t,r])}function yD({className:t,...e}){return f.jsx(N8,{"data-slot":"avatar",className:Me("relative flex size-8 shrink-0 overflow-hidden rounded-full",t),...e})}function xD({className:t,...e}){return f.jsx(j8,{"data-slot":"avatar-image",className:Me("aspect-square size-full",t),...e})}function bD({className:t,...e}){return f.jsx(P8,{"data-slot":"avatar-fallback",className:Me("bg-muted flex size-full items-center justify-center rounded-full",t),...e})}function u0e(){const{isLoading:t}=pd(),{user:e,signIn:n,signOut:r}=tc();if(t)return f.jsx(Ue,{variant:"outline",size:"sm",disabled:!0,children:f.jsx(Vn,{className:"h-3 w-3 mr-1.5 animate-spin"})});if(!e)return f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Ue,{variant:"outline",onClick:()=>n(),children:"Sign in"}),f.jsx(Ue,{onClick:()=>n(),style:{backgroundColor:"#E55A3A"},children:"Create account"})]});const s=[e.firstName,e.lastName].filter(Boolean).join(" "),i=e.email,o=Tq(s),c=()=>{const u=window.location.origin,p=u.includes("://localhost")?u.replace("://localhost","://127.0.0.1"):u;r({returnTo:p})};return f.jsxs(py,{children:[f.jsx(my,{asChild:!0,children:f.jsx("button",{className:"flex size-10 items-center justify-center rounded-full border border-border/60 bg-background/80 shadow-sm outline-none transition hover:ring-2 hover:ring-ring/20 focus-visible:ring-2 focus-visible:ring-ring",children:f.jsxs(yD,{className:"size-9",children:[f.jsx(xD,{src:e.profilePictureUrl,alt:s}),f.jsx(bD,{className:"bg-muted text-muted-foreground text-sm font-medium",children:o!=="?"?o:f.jsx(Ej,{className:"size-4"})})]})})}),f.jsxs(gy,{className:"w-56",align:"end",children:[f.jsx(VX,{className:"pb-3",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs(yD,{className:"size-10",children:[f.jsx(xD,{src:e.profilePictureUrl,alt:s}),f.jsx(bD,{className:"bg-muted text-muted-foreground text-base font-semibold",children:o!=="?"?o:f.jsx(Ej,{className:"size-5"})})]}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-sm font-medium leading-none truncate",children:s}),f.jsx("p",{className:"text-xs text-muted-foreground truncate",children:i})]})]})}),f.jsx(Rj,{}),f.jsxs(Aa,{onClick:()=>window.location.hash="settings",children:[f.jsx(QE,{className:"size-4"}),"Settings"]}),f.jsx(Rj,{}),f.jsxs(Aa,{variant:"destructive",onClick:c,children:[f.jsx(kQ,{className:"size-4"}),"Log out"]})]})]})}function d0e(){const[t,e]=w.useState("servers");l0e(),c0e();const n=w.useMemo(()=>window.location.pathname.startsWith("/oauth/callback/debug"),[]),r=w.useMemo(()=>window.location.pathname==="/callback",[]),{appState:s,isLoading:i,connectedServerConfigs:o,selectedMCPConfig:c,handleConnect:u,handleDisconnect:d,handleReconnect:p,handleUpdate:m,handleRemoveServer:v,setSelectedServer:y,toggleServerSelection:x,selectedMCPConfigsMap:_,setSelectedMultipleServersToAllServers:E}=n0e();w.useEffect(()=>{const A=()=>{const C=(window.location.hash||"#servers").replace("#","");e(C),C==="chat"&&E()};return A(),window.addEventListener("hashchange",A),()=>window.removeEventListener("hashchange",A)},[E]);const S=A=>{A==="chat"&&E(),window.location.hash=A,e(A)};return n?f.jsx(pxe,{}):r?(w.useEffect(()=>{const A=setTimeout(()=>{window.location.href="/"},5e3);return()=>clearTimeout(A)},[]),f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Completing sign in..."}),f.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If this takes too long, you'll be redirected automatically"})]})})):i?f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})}):f.jsxs(vme,{themeMode:"light",themePreset:"default",children:[f.jsxs(Rxe,{defaultOpen:!0,children:[f.jsx(Vxe,{onNavigate:S,activeTab:t}),f.jsxs(Pxe,{className:"flex flex-col",children:[f.jsx("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear drag",children:f.jsxs("div",{className:"flex w-full items-center justify-between px-4 lg:px-6",children:[f.jsx("div",{className:"flex items-center gap-1 lg:gap-2",children:f.jsx(jxe,{className:"-ml-1"})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsx(u0e,{})})]})}),f.jsxs("div",{className:"flex-1",children:[(t==="tools"||t==="resources"||t==="prompts"||t==="auth"||t==="chat"||t==="interceptor")&&f.jsx(Hxe,{connectedServerConfigs:o,selectedServer:s.selectedServer,onServerChange:y,onConnect:u,isMultiSelectEnabled:t==="chat",onMultiServerToggle:x,selectedMultipleServers:s.selectedMultipleServers}),t==="servers"&&f.jsx(aee,{connectedServerConfigs:o,onConnect:u,onDisconnect:d,onReconnect:p,onUpdate:m,onRemove:v}),t==="tools"&&f.jsx(hre,{serverConfig:c,serverName:s.selectedServer}),t==="evals"&&f.jsx(ove,{}),t==="resources"&&f.jsx(pre,{serverConfig:c,serverName:s.selectedServer}),t==="prompts"&&f.jsx(mre,{serverConfig:c,serverName:s.selectedServer}),t==="auth"&&f.jsx(hxe,{serverConfig:c,serverEntry:s.servers[s.selectedServer],serverName:s.selectedServer}),t==="chat"&&f.jsx(nve,{serverConfigs:_,connectedServerConfigs:o}),t==="interceptor"&&f.jsx(lxe,{connectedServerConfigs:o,selectedServer:s.selectedServer}),t==="tracing"&&f.jsx(oxe,{}),t==="settings"&&f.jsx(nxe,{})]})]})]}),f.jsx(o0e,{})]})}const f0e="phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9",h0e="https://us.i.posthog.com",p0e={api_host:h0e,capture_pageview:!1},m0e=()=>f0e,g0e=()=>p0e;var ve=typeof window<"u"?window:void 0,is=typeof globalThis<"u"?globalThis:ve,x6=Array.prototype,_D=x6.forEach,wD=x6.indexOf,Cs=is?.navigator,Be=is?.document,ts=is?.location,k1=is?.fetch,C1=is!=null&&is.XMLHttpRequest&&"withCredentials"in new is.XMLHttpRequest?is.XMLHttpRequest:void 0,SD=is?.AbortController,es=Cs?.userAgent,st=ve??{},ka={DEBUG:!1,LIB_VERSION:"1.268.1"};function ED(t,e,n,r,s,i,o){try{var c=t[i](o),u=c.value}catch(d){return void n(d)}c.done?e(u):Promise.resolve(u).then(r,s)}function kD(t){return function(){var e=this,n=arguments;return new Promise(function(r,s){var i=t.apply(e,n);function o(u){ED(i,r,s,o,c,"next",u)}function c(u){ED(i,r,s,o,c,"throw",u)}o(void 0)})}}function Le(){return Le=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Le.apply(null,arguments)}function b6(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var v0e=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function Ct(t,e){return t.indexOf(e)!==-1}var By=function(t){return t.trim()},T1=function(t){return t.replace(/^\$/,"")},y0e=Array.isArray,_6=Object.prototype,w6=_6.hasOwnProperty,qy=_6.toString,dn=y0e||function(t){return qy.call(t)==="[object Array]"},Xs=t=>typeof t=="function",Dn=t=>t===Object(t)&&!dn(t),mu=t=>{if(Dn(t)){for(var e in t)if(w6.call(t,e))return!1;return!0}return!1},Oe=t=>t===void 0,In=t=>qy.call(t)=="[object String]",A1=t=>In(t)&&t.trim().length===0,Ga=t=>t===null,Ot=t=>Oe(t)||Ga(t),Nr=t=>qy.call(t)=="[object Number]",vi=t=>qy.call(t)==="[object Boolean]",x0e=t=>t instanceof FormData,b0e=t=>Ct(v0e,t);function R1(t){return t===null||typeof t!="object"}function Cv(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function S6(t){return!Oe(Event)&&function(e,n){try{return e instanceof n}catch{return!1}}(t,Event)}var _0e=[!0,"true",1,"1","yes"],dw=t=>Ct(_0e,t),w0e=[!1,"false",0,"0","no"];function Ts(t,e,n,r,s){return e>n&&(r.warn("min cannot be greater than max."),e=n),Nr(t)?t>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),Ts(s||n,e,n,r))}class E6{stop(){this.t&&(clearInterval(this.t),this.t=void 0)}constructor(e){this.i=e,this.o={},this.h=()=>{Object.keys(this.o).forEach(n=>{var r=this.m(n)+this.S;r>=this.k?delete this.o[n]:this.$(n,r)})},this.m=n=>this.o[String(n)],this.$=(n,r)=>{this.o[String(n)]=r},this.consumeRateLimit=n=>{var r,s=(r=this.m(n))!=null?r:this.k;if((s=Math.max(s-1,0))===0)return!0;this.$(n,s);var i,o=s===0;return o&&((i=this.P)==null||i.call(this,n)),o},this.P=this.i.P,this.k=Ts(this.i.bucketSize,0,100,this.i.I),this.S=Ts(this.i.refillRate,0,this.k,this.i.I),this.R=Ts(this.i.refillInterval,0,864e5,this.i.I),this.t=setInterval(()=>{this.h()},this.R)}}var tg,CD,fw,S0e=t=>t instanceof Error;function E0e(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return fw&&n.length===CD||(CD=n.length,fw=n.reduce((r,s)=>{tg||(tg={});var i=tg[s];if(i)r[i[0]]=i[1];else for(var o=t(s),c=o.length-1;c>=0;c--){var u=o[c],d=u?.filename,p=e[s];if(d&&p){r[d]=p,tg[s]=[d,p];break}}return r},{})),fw}}var Yu="?";function N1(t,e,n,r){var s={platform:"web:javascript",filename:t,function:e==="<anonymous>"?Yu:e,in_app:!0};return Oe(n)||(s.lineno=n),Oe(r)||(s.colno=r),s}var k6=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:Yu,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},k0e=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,C0e=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,T0e=/\((\S*)(?::(\d+))(?::(\d+))\)/,A0e=t=>{var e=k0e.exec(t);if(e){var[,n,r,s]=e;return N1(n,Yu,+r,+s)}var i=C0e.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var o=T0e.exec(i[2]);o&&(i[2]=o[1],i[3]=o[2],i[4]=o[3])}var[c,u]=k6(i[1]||Yu,i[2]);return N1(u,c,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},R0e=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,N0e=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,j0e=t=>{var e=R0e.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=N0e.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],s=e[1]||Yu;return[s,r]=k6(s,r),N1(r,s,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}},TD=/\(error: (.*)\)/,AD=50;function P0e(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return function(r){for(var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=[],o=r.split(`
1836
+ `}),f.jsx("div",{className:"json-viewer-mcpjam",children:f.jsx(Ol,{src:C,dark:!1,theme:"default",enableClipboard:!0,displaySize:!0,collapsed:2,collapseStringsAfterLength:80,collapseObjectsAfterLength:10,style:{fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, 'SF Mono', monospace",backgroundColor:"hsl(var(--background))",padding:0,borderRadius:0,border:"none"}})})]}):f.jsx("pre",{className:"text-xs bg-background p-2 rounded border mt-1 overflow-auto",children:A.body})})()]},A.id))})})]})]})}class S1{constructor(e){this.serverUrl=e,sessionStorage.setItem("debug-oauth-server-url",e)}get redirectUrl(){return`${window.location.origin}/oauth/callback/debug`}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:"MCPJam",client_uri:"https://github.com/mcpjam/inspector"}}async clientInformation(){const e=`debug-client-info-${this.serverUrl}`,n=sessionStorage.getItem(e);if(n)return JSON.parse(n)}saveClientInformation(e){const n=`debug-client-info-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(e))}async tokens(){const e=`debug-tokens-${this.serverUrl}`,n=sessionStorage.getItem(e);if(n)return JSON.parse(n)}saveTokens(e){const n=`debug-tokens-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(e))}redirectToAuthorization(e){}saveCodeVerifier(e){const n=`debug-verifier-${this.serverUrl}`;sessionStorage.setItem(n,e)}codeVerifier(){const e=`debug-verifier-${this.serverUrl}`,n=sessionStorage.getItem(e);if(!n)throw new Error("No code verifier saved for debug session");return n}saveServerMetadata(e){const n=`debug-server-metadata-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(e))}getServerMetadata(){const e=`debug-server-metadata-${this.serverUrl}`,n=sessionStorage.getItem(e);return n?JSON.parse(n):null}clear(){[`debug-client-info-${this.serverUrl}`,`debug-tokens-${this.serverUrl}`,`debug-verifier-${this.serverUrl}`,`debug-server-metadata-${this.serverUrl}`].forEach(n=>sessionStorage.removeItem(n))}}const Jm={isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null},Qc=({label:t,isComplete:e,isCurrent:n,error:r,children:s})=>f.jsxs("div",{children:[f.jsxs("div",{className:`flex items-center p-2 rounded-md ${n?"bg-accent":""}`,children:[e?f.jsx(VK,{className:"h-5 w-5 text-green-500 mr-2"}):f.jsx(WK,{className:"h-5 w-5 text-muted-foreground mr-2"}),f.jsx("span",{className:`${n?"font-medium":""}`,children:t})]}),(n||e)&&s&&f.jsx("div",{className:"ml-7 mt-1",children:s}),n&&r&&f.jsxs("div",{className:"ml-7 mt-2 p-3 border border-red-300 bg-red-50 dark:bg-red-950/50 rounded-md",children:[f.jsx("p",{className:"text-sm font-medium text-red-700 dark:text-red-400",children:"Error:"}),f.jsx("p",{className:"text-xs text-red-600 dark:text-red-500 mt-1",children:r.message})]})]}),eg=["metadata_discovery","client_registration","authorization_redirect","authorization_code","token_request","complete"],cxe=({serverUrl:t,flowState:e,updateFlowState:n,proceedToNextStep:r})=>{const s=w.useMemo(()=>new S1(t),[t]),[i,o]=w.useState(null),c=eg.findIndex(d=>d===e.oauthStep);w.useEffect(()=>{const d=async()=>{if(e.oauthClientInfo)o(e.oauthClientInfo);else try{const p=await s.clientInformation();p&&o(p)}catch(p){console.error("Failed to fetch client information:",p)}};c>eg.indexOf("client_registration")&&d()},[s,e.oauthStep,e.oauthClientInfo,c]);const u=d=>({isComplete:c>eg.indexOf(d)||c===eg.length-1,isCurrent:e.oauthStep===d,error:e.oauthStep===d?e.latestError:null});return f.jsxs("div",{className:"rounded-md border p-6 space-y-4 mt-4",children:[f.jsx("h3",{className:"text-lg font-medium",children:"OAuth Flow Progress"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Follow these steps to complete OAuth authentication with the server."}),f.jsxs("div",{className:"space-y-3",children:[f.jsx(Qc,{label:"Metadata Discovery",...u("metadata_discovery"),children:e.oauthMetadata&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsxs("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:["OAuth Metadata Sources",!e.resourceMetadata&&" ℹ️"]}),e.resourceMetadata&&f.jsxs("div",{className:"mt-2",children:[f.jsx("p",{className:"font-medium",children:"Resource Metadata:"}),f.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-protected-resource",t).href]}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(e.resourceMetadata,null,2)})]}),e.resourceMetadataError&&f.jsxs("div",{className:"mt-2 p-3 border border-blue-300 bg-blue-50 dark:bg-blue-950/50 rounded-md",children:[f.jsxs("p",{className:"text-sm font-medium text-blue-700 dark:text-blue-400",children:["ℹ️ Problem with resource metadata from"," ",f.jsx("a",{href:new URL("/.well-known/oauth-protected-resource",t).href,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300",children:new URL("/.well-known/oauth-protected-resource",t).href})]}),f.jsxs("p",{className:"text-xs text-blue-600 dark:text-blue-500 mt-1",children:["Resource metadata was added in the"," ",f.jsx("a",{href:"https://modelcontextprotocol.io/specification/draft/basic/authorization#2-3-1-authorization-server-location",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"2025-DRAFT-v2 specification update"}),f.jsx("br",{}),e.resourceMetadataError.message,e.resourceMetadataError instanceof TypeError&&" (This could indicate the endpoint doesn't exist or does not have CORS configured)"]})]}),e.oauthMetadata&&f.jsxs("div",{className:"mt-2",children:[f.jsx("p",{className:"font-medium",children:"Authorization Server Metadata:"}),e.authServerUrl&&f.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-authorization-server",e.authServerUrl).href]}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(e.oauthMetadata,null,2)})]})]})}),f.jsx(Qc,{label:"Client Registration",...u("client_registration"),children:i&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Registered Client Information"}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(i,null,2)})]})}),f.jsx(Qc,{label:"Preparing Authorization",...u("authorization_redirect"),children:e.authorizationUrl&&f.jsxs("div",{className:"mt-2 p-3 border rounded-md bg-muted",children:[f.jsx("p",{className:"font-medium mb-2 text-sm",children:"Authorization URL:"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("p",{className:"text-xs break-all",children:e.authorizationUrl}),f.jsx("a",{href:e.authorizationUrl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300","aria-label":"Open authorization URL in new tab",title:"Open authorization URL",children:f.jsx(KE,{className:"h-4 w-4"})})]}),f.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Click the link to authorize in your browser. After authorization, you'll be redirected back to continue the flow."})]})}),f.jsx(Qc,{label:"Request Authorization and acquire authorization code",...u("authorization_code"),children:f.jsxs("div",{className:"mt-3",children:[f.jsx("label",{htmlFor:"authCode",className:"block text-sm font-medium mb-1",children:"Authorization Code"}),f.jsx("div",{className:"flex gap-2",children:f.jsx("input",{id:"authCode",value:e.authorizationCode,onChange:d=>{n({authorizationCode:d.target.value,validationError:null})},placeholder:"Enter the code from the authorization server",className:`flex h-9 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${e.validationError?"border-red-500":"border-input"}`})}),e.validationError&&f.jsx("p",{className:"text-xs text-red-600 dark:text-red-500 mt-1",children:e.validationError}),f.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once you've completed authorization in the link, paste the code here."})]})}),f.jsx(Qc,{label:"Token Request",...u("token_request"),children:e.oauthMetadata&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Token Request Details"}),f.jsxs("div",{className:"mt-2 p-2 bg-muted rounded-md",children:[f.jsx("p",{className:"font-medium",children:"Token Endpoint:"}),f.jsx("code",{className:"block mt-1 text-xs overflow-x-auto",children:e.oauthMetadata.token_endpoint})]})]})}),f.jsx(Qc,{label:"Authentication Complete",...u("complete"),children:e.oauthTokens&&f.jsxs("details",{className:"text-xs mt-2",children:[f.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Access Tokens"}),f.jsx("p",{className:"mt-1 text-sm",children:"Authentication successful! You can now use the authenticated connection. These tokens will be used automatically for server requests."}),f.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(e.oauthTokens,null,2)})]})})]}),f.jsxs("div",{className:"flex gap-3 mt-4",children:[e.oauthStep!=="complete"&&f.jsx(f.Fragment,{children:f.jsx(Ue,{onClick:r,disabled:e.isInitiatingAuth,children:e.isInitiatingAuth?"Processing...":"Continue"})}),e.oauthStep==="authorization_redirect"&&e.authorizationUrl&&f.jsx(Ue,{variant:"outline",onClick:()=>window.open(e.authorizationUrl,"_blank"),children:"Open in New Tab"})]})]})},uxe={metadata_discovery:{canTransition:async()=>!0,execute:async t=>{try{if(t.updateState({latestError:null}),!t.serverUrl)throw new Error("Server URL is required");let e;try{e=new URL(t.serverUrl).toString()}catch{throw new Error(`Invalid server URL: ${t.serverUrl}`)}let n;try{n=new URL("/",e)}catch{throw new Error(`Failed to create base URL from server URL: ${e}`)}let r=null,s=null;try{if(r=await B5(e),r?.authorization_servers?.length){const c=r.authorization_servers[0];try{n=new URL(c)}catch{console.warn(`Invalid authorization server URL: ${c}, using default`)}}}catch(c){s=c instanceof Error?c:new Error(String(c))}const i=await KJ(n.toString());let o=null;try{o=await V5(e,t.provider,r??void 0)??null}catch(c){console.warn("selectResourceURL failed or not provided:",c)}t.updateState({resourceMetadata:r,resourceMetadataError:s,resource:o,authServerUrl:n,oauthMetadata:i,oauthStep:"client_registration"})}catch(e){const n=e instanceof Error?e:new Error(String(e));console.error("Metadata discovery error:",{error:n,serverUrl:t.serverUrl,serverName:t.serverName}),t.updateState({latestError:n,statusMessage:{type:"error",message:`Metadata discovery failed: ${n.message}`}})}}},client_registration:{canTransition:async t=>!!t.state.oauthMetadata,execute:async t=>{try{if(t.updateState({latestError:null}),!t.state.oauthMetadata)throw new Error("OAuth metadata not available");let e;try{const n={...t.provider.clientMetadata},r=t.state.resourceMetadata?.scopes_supported||t.state.oauthMetadata.scopes_supported;r&&r.length>0&&(n.scope=r.join(" "));try{e=await Y5(t.serverUrl,{metadata:t.state.oauthMetadata,clientMetadata:n}),t.provider.saveClientInformation(e)}catch(s){if(e=await t.provider.clientInformation(),!e)throw s}}catch(n){console.warn("Dynamic client registration failed, using static client metadata:",n);const r=await t.provider.clientInformation();r?e=r:(e={client_id:`static_client_${Date.now()}`,...t.provider.clientMetadata},t.provider.saveClientInformation(e))}t.updateState({oauthClientInfo:e,oauthStep:"authorization_redirect",statusMessage:{type:"success",message:"Client registration completed successfully."}})}catch(e){const n=e instanceof Error?e:new Error(String(e));console.error("Client registration error:",{error:n,serverUrl:t.serverUrl,serverName:t.serverName,hasOAuthMetadata:!!t.state.oauthMetadata,oauthMetadata:t.state.oauthMetadata,providerRedirectUrl:t.provider.redirectUrl,providerClientMetadata:t.provider.clientMetadata}),t.updateState({latestError:n,statusMessage:{type:"error",message:`Client registration failed: ${n.message}`}})}}},authorization_redirect:{canTransition:async t=>!!t.state.oauthMetadata&&!!t.state.oauthClientInfo,execute:async t=>{try{if(t.updateState({latestError:null}),!t.state.oauthMetadata||!t.state.oauthClientInfo)throw new Error("OAuth metadata or client info not available");const e=t.state.resourceMetadata?.scopes_supported||t.state.oauthMetadata.scopes_supported,n=e&&e.length>0?e.join(" "):void 0,r=new Uint8Array(32);crypto.getRandomValues(r);const s=Array.from(r,o=>o.toString(16).padStart(2,"0")).join(""),i=await H5(t.serverUrl,{metadata:t.state.oauthMetadata,clientInformation:t.state.oauthClientInfo,redirectUrl:t.provider.redirectUrl,scope:n,state:s,resource:t.state.resource??void 0});t.provider.saveCodeVerifier(i.codeVerifier),t.updateState({authorizationUrl:i.authorizationUrl.toString(),oauthStep:"authorization_code",statusMessage:{type:"info",message:"Authorization URL generated. Please complete authorization in your browser."}})}catch(e){const n=e instanceof Error?e:new Error(String(e));t.updateState({latestError:n,statusMessage:{type:"error",message:`Authorization preparation failed: ${n.message}`}})}}},authorization_code:{canTransition:async t=>!!t.state.authorizationCode.trim(),execute:async t=>{try{if(t.updateState({latestError:null,validationError:null}),!t.state.authorizationCode.trim()){t.updateState({validationError:"Authorization code is required"});return}t.updateState({oauthStep:"token_request"})}catch(e){const n=e instanceof Error?e:new Error(String(e));t.updateState({latestError:n,validationError:n.message})}}},token_request:{canTransition:async t=>!!t.state.authorizationCode.trim()&&!!t.state.oauthMetadata,execute:async t=>{try{if(t.updateState({latestError:null}),!t.state.oauthMetadata||!t.state.authorizationCode.trim()||!t.state.oauthClientInfo)throw new Error("OAuth metadata, authorization code, or client info not available");const e=await G5(t.serverUrl,{metadata:t.state.oauthMetadata,clientInformation:t.state.oauthClientInfo,authorizationCode:t.state.authorizationCode,codeVerifier:t.provider.codeVerifier(),redirectUri:t.provider.redirectUrl});t.updateState({oauthTokens:e,oauthStep:"complete",statusMessage:{type:"success",message:"OAuth authentication completed successfully!"}})}catch(e){const n=e instanceof Error?e:new Error(String(e));t.updateState({latestError:n,statusMessage:{type:"error",message:`Token exchange failed: ${n.message}`}})}}},complete:{canTransition:async()=>!1,execute:async()=>{}}};class dxe{constructor(e){this.context=e}async proceedToNextStep(){const e=this.context.state.oauthStep,n=uxe[e];if(!n)return console.error("No transition found for step:",e),!1;try{return this.context.updateState({isInitiatingAuth:!0}),await n.canTransition(this.context)?(await n.execute(this.context),!0):(console.warn("Cannot transition from step:",e),!1)}catch(r){console.error("Error during state transition:",r);const s=r instanceof Error?r:new Error(String(r));return this.context.updateState({latestError:s,statusMessage:{type:"error",message:s.message}}),!1}finally{this.context.updateState({isInitiatingAuth:!1})}}reset(){this.context.updateState({isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null})}}const fxe=({message:t})=>{let e,n,r;switch(t.type){case"error":e="bg-red-50 dark:bg-red-950/50",n="text-red-700 dark:text-red-400",r="border-red-200 dark:border-red-800";break;case"success":e="bg-green-50 dark:bg-green-950/50",n="text-green-700 dark:text-green-400",r="border-green-200 dark:border-green-800";break;case"info":default:e="bg-blue-50 dark:bg-blue-950/50",n="text-blue-700 dark:text-blue-400",r="border-blue-200 dark:border-blue-800";break}return f.jsx("div",{className:`p-3 rounded-md border ${e} ${r} ${n} mb-4`,children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Ug,{className:"h-4 w-4"}),f.jsx("p",{className:"text-sm",children:t.message})]})})},hxe=({serverConfig:t,serverEntry:e,serverName:n})=>{const[r,s]=w.useState(LP),[i,o]=w.useState(Jm),[c,u]=w.useState(!1),d=w.useCallback(T=>{s(P=>({...P,...T}))},[]),p=w.useCallback(T=>{o(P=>({...P,...T}))},[]),m=w.useCallback(()=>{if(u(!1),p(Jm),r.serverUrl)try{new S1(r.serverUrl).clear()}catch(T){console.warn("Failed to clear debug OAuth provider state:",T)}},[r.serverUrl,p]);w.useEffect(()=>{if(t&&t.url&&n){const T=t.url.toString(),P=mi(n);d({serverUrl:T,tokens:P,error:null,statusMessage:null})}else d(LP)},[t,n,d]),w.useEffect(()=>{m()},[n,m]);const v=w.useCallback(async()=>{if(!t||!r.serverUrl||!n){d({statusMessage:{type:"error",message:"Please select a server before refreshing tokens"}});return}d({isAuthenticating:!0,error:null,statusMessage:null});try{let T;if(r.tokens)T=await uk(n);else{const P={serverName:n,serverUrl:r.serverUrl};T=await nv(P)}if(T.success){const P=mi(n);d({tokens:P,isAuthenticating:!1,statusMessage:{type:"success",message:r.tokens?"Tokens refreshed successfully!":T.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{d({statusMessage:null})},3e3)}else d({isAuthenticating:!1,error:T.error||"OAuth operation failed",statusMessage:{type:"error",message:`Failed: ${T.error||"OAuth operation failed"}`}})}catch(T){d({isAuthenticating:!1,error:T instanceof Error?T.message:String(T),statusMessage:{type:"error",message:`Failed: ${T instanceof Error?T.message:String(T)}`}})}},[t,r.serverUrl,r.tokens,n,d]),y=w.useCallback(async()=>{if(!t||!r.serverUrl||!n){d({statusMessage:{type:"error",message:"Please select a server before starting OAuth"}});return}d({isAuthenticating:!0,error:null,statusMessage:null});try{kh(n);const T={serverName:n,serverUrl:r.serverUrl},P=await nv(T);if(P.success){const N=mi(n);d({tokens:N,isAuthenticating:!1,statusMessage:{type:"success",message:P.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{d({statusMessage:null})},3e3)}else d({isAuthenticating:!1,error:P.error||"OAuth authentication failed",statusMessage:{type:"error",message:`Failed: ${P.error||"OAuth authentication failed"}`}})}catch(T){d({isAuthenticating:!1,error:T instanceof Error?T.message:String(T),statusMessage:{type:"error",message:`Failed: ${T instanceof Error?T.message:String(T)}`}})}},[t,r.serverUrl,n,d]),x=w.useMemo(()=>{if(!t||!n||!r.serverUrl)return null;const T=new S1(r.serverUrl);return new dxe({state:i,serverUrl:r.serverUrl,serverName:n,provider:T,updateState:p})},[t,n,r.serverUrl,i,p]),_=w.useCallback(()=>{m(),u(!0),p(Jm),x&&x.proceedToNextStep()},[x,p,r.serverUrl,n,t,m]),E=w.useCallback(async()=>{x&&await x.proceedToNextStep()},[x]),S=w.useCallback(()=>{if(u(!1),p(Jm),n){const T=mi(n);d({tokens:T})}},[n,d,p]),A=w.useCallback(()=>{t&&r.serverUrl&&n&&(kh(n),d({tokens:null,error:null,statusMessage:{type:"success",message:"OAuth tokens cleared successfully"}}),setTimeout(()=>{d({statusMessage:null})},3e3))},[t,r.serverUrl,n,d]),C=t&&"url"in t,R=C,j=n&&(e?.oauthTokens||mi(n)||e?.connectionStatus==="oauth-flow");return t?R?f.jsx("div",{className:"h-[calc(100vh-120px)] flex flex-col",children:f.jsxs("div",{className:"h-full flex flex-col bg-background",children:[f.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(Vn,{className:"h-4 w-4 text-muted-foreground"}),f.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),f.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:f.jsxs("div",{className:"space-y-6 max-w-2xl",children:[f.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:[f.jsxs("div",{children:["Name: ",e?.name||"Unknown"]}),C&&f.jsxs("div",{children:["URL: ",t.url.toString()]}),f.jsx("div",{children:"Type: HTTP Server"})]})]}),f.jsxs("div",{className:"rounded-md border p-6 space-y-6",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Vn,{className:"h-5 w-5"}),f.jsx("h3",{className:"text-lg font-medium",children:"OAuth Authentication"})]}),f.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:j?"Manage OAuth authentication for this server.":"This server supports OAuth authentication. Use Quick OAuth to authenticate and get tokens."}),r.statusMessage&&f.jsx(fxe,{message:r.statusMessage}),r.error&&!r.statusMessage&&f.jsx("div",{className:"p-3 rounded-md border border-red-200 bg-red-50 text-red-700 mb-4",children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Ug,{className:"h-4 w-4"}),f.jsx("p",{className:"text-sm",children:r.error})]})}),f.jsxs("div",{className:"space-y-4",children:[r.tokens&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("p",{className:"text-sm font-medium",children:"Current Tokens:"}),f.jsxs("div",{className:"bg-muted p-3 rounded-md space-y-2",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Access Token:"}),f.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.access_token.substring(0,40),"..."]})]}),r.tokens.refresh_token&&f.jsxs("div",{children:[f.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Refresh Token:"}),f.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.refresh_token.substring(0,40),"..."]})]}),f.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[f.jsxs("span",{children:["Type: ",r.tokens.token_type]}),r.tokens.expires_in&&f.jsxs("span",{children:["Expires in: ",r.tokens.expires_in,"s"]}),r.tokens.scope&&f.jsxs("span",{children:["Scope: ",r.tokens.scope]})]})]})]}),f.jsxs("div",{className:"flex gap-4",children:[f.jsx(Ue,{onClick:r.tokens?v:y,disabled:r.isAuthenticating||!t,className:"flex items-center gap-2",variant:r.tokens?"outline":"default",children:r.isAuthenticating?f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4 animate-spin"}),r.tokens?"Refreshing...":"Authenticating..."]}):f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4"}),r.tokens?"Quick Refresh":"Quick OAuth"]})}),r.tokens&&f.jsx(Ue,{onClick:y,disabled:r.isAuthenticating||!t,className:"flex items-center gap-2",variant:"default",children:r.isAuthenticating?f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4 animate-spin"}),"Authenticating..."]}):f.jsxs(f.Fragment,{children:[f.jsx(Vn,{className:"h-4 w-4"}),"Quick OAuth"]})}),f.jsx(Ue,{variant:"outline",onClick:A,disabled:!t||!r.tokens,children:"Clear Tokens"}),f.jsx(Ue,{variant:"secondary",onClick:_,disabled:r.isAuthenticating||!t,children:"Guided OAuth Flow"})]}),f.jsx("p",{className:"text-xs text-muted-foreground",children:t?r.tokens?"Use Quick Refresh to renew existing tokens, or Quick OAuth to start a fresh authentication flow.":"Use Quick OAuth to authenticate with the server and get tokens.":"Select a server to manage its OAuth authentication."})]}),c&&r.serverUrl&&f.jsx(cxe,{serverUrl:r.serverUrl,flowState:i,updateFlowState:p,proceedToNextStep:E}),c&&f.jsx("div",{className:"mt-4",children:f.jsx(Ue,{variant:"outline",onClick:S,children:"Exit Guided Flow"})})]})]})})]})}):f.jsx("div",{className:"h-[calc(100vh-120px)] flex flex-col",children:f.jsxs("div",{className:"h-full flex flex-col bg-background",children:[f.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx(Vn,{className:"h-4 w-4 text-muted-foreground"}),f.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),f.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:f.jsxs("div",{className:"space-y-6 max-w-2xl",children:[f.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:[f.jsxs("div",{children:["Name: ",e?.name||"Unknown"]}),C&&f.jsxs("div",{children:["URL: ",t.url.toString()]}),!C&&f.jsxs("div",{children:["Command: ",t.command]}),f.jsxs("div",{children:["Type: ",C?"HTTP Server":"STDIO Server"]})]})]}),f.jsx(Pa,{children:f.jsx(Aq,{className:"pt-6",children:f.jsxs("div",{className:"text-center space-y-4",children:[f.jsx("div",{className:"mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center",children:f.jsx(Vn,{className:"h-6 w-6 text-muted-foreground"})}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("h3",{className:"text-lg font-medium",children:C?"No Authentication Required":"No OAuth Support"}),f.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:C?`The HTTP server "${e?.name||"Unknown"}" is connected without OAuth authentication.`:"STDIO servers don't support OAuth authentication."}),C&&f.jsx("p",{className:"text-xs text-muted-foreground max-w-md mx-auto mt-2",children:"If this server supports OAuth, you can reconnect it with OAuth enabled from the Servers tab."})]})]})})})]})})]})}):f.jsx(dp,{icon:QQ,title:"No Server Selected",description:"Connect to an MCP server to manage authentication and OAuth settings."})};function pxe(){const t=new URLSearchParams(window.location.search),e=t.get("code"),n=t.get("error"),r=t.get("error_description");return f.jsx("div",{className:"flex items-center justify-center min-h-[100vh] p-4",children:f.jsx("div",{className:"mt-4 p-4 bg-secondary rounded-md max-w-md w-full border",children:e?f.jsxs(f.Fragment,{children:[f.jsx("p",{className:"mb-2 text-sm",children:"Please copy this authorization code and return to the Auth screen:"}),f.jsx("code",{className:"block p-2 bg-muted rounded-sm overflow-x-auto text-xs",children:e}),f.jsx("p",{className:"mt-4 text-xs text-muted-foreground",children:"Close this tab and paste the code in the OAuth flow to complete authentication."})]}):f.jsxs(f.Fragment,{children:[f.jsx("p",{className:"mb-2 text-sm font-medium",children:"No authorization code found"}),f.jsxs("div",{className:"text-xs text-muted-foreground",children:[f.jsxs("div",{children:["Error: ",n||"unknown"]}),r&&f.jsxs("div",{children:["Description: ",decodeURIComponent(r)]})]})]})})})}const cw=768;function mxe(){const[t,e]=w.useState(void 0);return w.useEffect(()=>{const n=window.matchMedia(`(max-width: ${cw-1}px)`),r=()=>{e(window.innerWidth<cw)};return n.addEventListener("change",r),e(window.innerWidth<cw),()=>n.removeEventListener("change",r)},[]),!!t}function gxe({...t}){return f.jsx(hE,{"data-slot":"sheet",...t})}function vxe({...t}){return f.jsx(pE,{"data-slot":"sheet-portal",...t})}function yxe({className:t,...e}){return f.jsx(mE,{"data-slot":"sheet-overlay",className:Me("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function xxe({className:t,children:e,side:n="right",...r}){return f.jsxs(vxe,{children:[f.jsx(yxe,{}),f.jsxs(gE,{"data-slot":"sheet-content",className:Me("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",n==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",n==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",n==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",n==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",t),...r,children:[e,f.jsxs(Kv,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[f.jsx(ip,{className:"size-4"}),f.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function bxe({className:t,...e}){return f.jsx("div",{"data-slot":"sheet-header",className:Me("flex flex-col gap-1.5 p-4",t),...e})}function _xe({className:t,...e}){return f.jsx(vE,{"data-slot":"sheet-title",className:Me("text-foreground font-semibold",t),...e})}function wxe({className:t,...e}){return f.jsx(yE,{"data-slot":"sheet-description",className:Me("text-muted-foreground text-sm",t),...e})}const Sxe="sidebar_state",Exe=60*60*24*7,kxe="16rem",Cxe="18rem",Txe="3rem",Axe="b",p6=w.createContext(null);function $C(){const t=w.useContext(p6);if(!t)throw new Error("useSidebar must be used within a SidebarProvider.");return t}function Rxe({defaultOpen:t=!0,open:e,onOpenChange:n,className:r,style:s,children:i,...o}){const c=mxe(),[u,d]=w.useState(!1),[p,m]=w.useState(t),v=e??p,y=w.useCallback(S=>{const A=typeof S=="function"?S(v):S;n?n(A):m(A),document.cookie=`${Sxe}=${A}; path=/; max-age=${Exe}`},[n,v]),x=w.useCallback(()=>c?d(S=>!S):y(S=>!S),[c,y,d]);w.useEffect(()=>{const S=A=>{A.key===Axe&&(A.metaKey||A.ctrlKey)&&(A.preventDefault(),x())};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[x]);const _=v?"expanded":"collapsed",E=w.useMemo(()=>({state:_,open:v,setOpen:y,isMobile:c,openMobile:u,setOpenMobile:d,toggleSidebar:x}),[_,v,y,c,u,d,x]);return f.jsx(p6.Provider,{value:E,children:f.jsx(hy,{delayDuration:0,children:f.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":kxe,"--sidebar-width-icon":Txe,...s},className:Me("group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",r),...o,children:i})})})}function Nxe({side:t="left",variant:e="sidebar",collapsible:n="offcanvas",className:r,children:s,...i}){const{isMobile:o,state:c,openMobile:u,setOpenMobile:d}=$C();return n==="none"?f.jsx("div",{"data-slot":"sidebar",className:Me("bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",r),...i,children:s}):o?f.jsx(gxe,{open:u,onOpenChange:d,...i,children:f.jsxs(xxe,{"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden",style:{"--sidebar-width":Cxe},side:t,children:[f.jsxs(bxe,{className:"sr-only",children:[f.jsx(_xe,{children:"Sidebar"}),f.jsx(wxe,{children:"Displays the mobile sidebar."})]}),f.jsx("div",{className:"flex h-full w-full flex-col",children:s})]})}):f.jsxs("div",{className:"group peer text-sidebar-foreground hidden md:block","data-state":c,"data-collapsible":c==="collapsed"?n:"","data-variant":e,"data-side":t,"data-slot":"sidebar",children:[f.jsx("div",{"data-slot":"sidebar-gap",className:Me("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",e==="floating"||e==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),f.jsx("div",{"data-slot":"sidebar-container",className:Me("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",t==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",e==="floating"||e==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",r),...i,children:f.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:"bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm",children:s})})]})}function jxe({className:t,onClick:e,...n}){const{toggleSidebar:r}=$C();return f.jsxs(Ue,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon",className:Me("size-7",t),onClick:s=>{e?.(s),r()},...n,children:[f.jsx(MQ,{}),f.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function Pxe({className:t,...e}){return f.jsx("main",{"data-slot":"sidebar-inset",className:Me("bg-background relative flex w-full flex-1 flex-col","md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",t),...e})}function Mxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:Me("flex flex-col gap-2 p-2 drag",t),...e})}function Oxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-footer","data-sidebar":"footer",className:Me("flex flex-col gap-2 p-2",t),...e})}function Dxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:Me("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...e})}function Ixe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-group","data-sidebar":"group",className:Me("relative flex w-full min-w-0 flex-col p-2",t),...e})}function Lxe({className:t,...e}){return f.jsx("div",{"data-slot":"sidebar-group-content","data-sidebar":"group-content",className:Me("w-full text-sm",t),...e})}function m6({className:t,...e}){return f.jsx("ul",{"data-slot":"sidebar-menu","data-sidebar":"menu",className:Me("flex w-full min-w-0 flex-col gap-1",t),...e})}function g6({className:t,...e}){return f.jsx("li",{"data-slot":"sidebar-menu-item","data-sidebar":"menu-item",className:Me("group/menu-item relative",t),...e})}const zxe=fy("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:p-0!"}},defaultVariants:{variant:"default",size:"default"}});function v6({asChild:t=!1,isActive:e=!1,variant:n="default",size:r="default",tooltip:s,className:i,...o}){const c=t?oE:"button",{isMobile:u,state:d}=$C(),p=f.jsx(c,{"data-slot":"sidebar-menu-button","data-sidebar":"menu-button","data-size":r,"data-active":e,className:Me(zxe({variant:n,size:r}),i),...o});return s?(typeof s=="string"&&(s={children:s}),f.jsxs(Ui,{children:[f.jsx(Vi,{asChild:!0,children:p}),f.jsx(Bi,{side:"right",align:"center",hidden:d!=="collapsed"||u,...s})]})):p}function $xe({items:t,onItemClick:e}){const n=s=>{e&&e(s)},r=s=>s.isActive||!1;return f.jsx(Ixe,{children:f.jsx(Lxe,{children:f.jsx(m6,{children:t.map(s=>f.jsx(g6,{children:f.jsxs(v6,{tooltip:s.title,isActive:r(s),onClick:()=>n(s.url),className:r(s)?"[&[data-active=true]]:bg-black/5 dark:[&[data-active=true]]:bg-white/5 cursor-pointer":"cursor-pointer",children:[s.icon&&f.jsx(s.icon,{className:"h-4 w-4"}),f.jsx("span",{children:s.title})]})},s.title))})})})}function Fxe(t){const e=document.documentElement;e.classList.add("disable-transitions"),e.classList.toggle("dark",t==="dark"),requestAnimationFrame(()=>{e.classList.remove("disable-transitions")})}function Uxe(){const t=$h(r=>r.themeMode),e=$h(r=>r.setThemeMode),n=()=>{const r=t==="dark"?"light":"dark";Fxe(r),e(r)};return f.jsxs(v6,{tooltip:`Switch to ${t==="dark"?"light":"dark"} mode`,onClick:n,className:"cursor-pointer",children:[t==="dark"?f.jsx(sX,{className:"h-4 w-4"}):f.jsx(jQ,{className:"h-4 w-4"}),f.jsx("span",{children:t==="dark"?"Light mode":"Dark mode"})]})}const gD=[{id:"connection",items:[{title:"MCP Servers",url:"#servers",icon:Ey},{title:"Playground",url:"#chat",icon:Yw},{title:"Tracing",url:"#tracing",icon:AK}]},{id:"tools",items:[{title:"Tools",url:"#tools",icon:yQ},{title:"Resources",url:"#resources",icon:OK},{title:"Prompts",url:"#prompts",icon:AQ},{title:"Auth",url:"#auth",icon:bQ},{title:"Evals",url:"#evals",icon:y5}]},{id:"beta",items:[{title:"Interceptor (beta)",url:"#interceptor",icon:pQ}]},{id:"settings",items:[{title:"Feedback",url:"https://github.com/MCPJam/inspector/issues/new",icon:Yw},{title:"Settings",url:"#settings",icon:QE}]}];function Vxe({onNavigate:t,activeTab:e,...n}){const r=$h(i=>i.themeMode),s=i=>{t&&i.startsWith("#")?t(i.slice(1)):window.open(i,"_blank")};return f.jsxs(Nxe,{collapsible:"icon",...n,children:[f.jsx(Mxe,{children:f.jsx("div",{className:"flex items-center justify-center px-4 py-4",children:f.jsx("img",{src:r==="dark"?"/mcp_jam_dark.png":"/mcp_jam_light.png",alt:"MCP Jam",className:"h-4 w-auto"})})}),f.jsx(Dxe,{children:gD.map((i,o)=>f.jsxs(w.Fragment,{children:[f.jsx($xe,{items:i.items.map(c=>({...c,isActive:c.url===`#${e}`})),onItemClick:s}),o<gD.length-1&&f.jsx("div",{className:"mx-4 my-2 border-t border-border/50"})]},i.id))}),f.jsx(Oxe,{children:f.jsx(m6,{children:f.jsx(g6,{children:f.jsx(Uxe,{})})})})]})}function Bxe(t){switch(t){case"connected":return"bg-green-500 dark:bg-green-400";case"connecting":return"bg-yellow-500 dark:bg-yellow-400 animate-pulse";case"failed":return"bg-red-500 dark:bg-red-400";case"disconnected":return"bg-muted-foreground";default:return"bg-muted-foreground"}}function qxe(t){switch(t){case"connected":return"Connected";case"connecting":return"Connecting...";case"failed":return"Failed";case"disconnected":return"Disconnected";default:return"Unknown"}}function Hxe({connectedServerConfigs:t,selectedServer:e,selectedMultipleServers:n,isMultiSelectEnabled:r,onServerChange:s,onMultiServerToggle:i,onConnect:o}){const[c,u]=w.useState(!1),d=Object.entries(t).filter(([,p])=>p.enabled!==!1);return d.length===0?null:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-wrap",children:[d.map(([p,m])=>{const v=r?n.includes(p):e===p;return f.jsxs("button",{onClick:()=>r?i(p):s(p),className:Me("group relative flex items-center gap-3 px-4 py-3 border-r border-b border-border transition-all duration-200 cursor-pointer","hover:bg-accent hover:text-accent-foreground",v?"bg-muted text-foreground":"bg-background text-foreground"),children:[r&&f.jsx("div",{className:Me("w-4 h-4 rounded border-2 flex items-center justify-center transition-colors",v?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30 hover:border-primary/50"),children:v&&f.jsx(Fi,{className:"w-3 h-3"})}),f.jsx("div",{className:Me("w-2 h-2 rounded-full",Bxe(m.connectionStatus)),title:qxe(m.connectionStatus)}),f.jsx("span",{className:"text-sm font-medium truncate max-w-36",children:p}),f.jsx("div",{className:"text-xs opacity-70",children:m.config.command?"STDIO":"HTTP"})]},p)}),f.jsxs("button",{onClick:()=>u(!0),className:Me("group relative flex items-center gap-3 px-4 py-3 border-r border-b border-border transition-all duration-200 cursor-pointer","hover:bg-accent hover:text-accent-foreground","bg-background text-muted-foreground border-dashed"),children:[r&&f.jsx("div",{className:"w-4 h-4"}),f.jsx("span",{className:"text-sm font-medium",children:"Add Server"}),f.jsx("div",{className:"text-xs opacity-70",children:"+"})]})]}),f.jsx(vS,{mode:"add",isOpen:c,onClose:()=>u(!1),onSubmit:p=>o(p)})]})}const Gxe="modulepreload",Yxe=function(t){return"/"+t},vD={},Wxe=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let d=function(p){return Promise.all(p.map(m=>Promise.resolve(m).then(v=>({status:"fulfilled",value:v}),v=>({status:"rejected",reason:v}))))};var o=d;document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");s=d(n.map(p=>{if(p=Yxe(p),p in vD)return;vD[p]=!0;const m=p.endsWith(".css"),v=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${v}`))return;const y=document.createElement("link");if(y.rel=m?"stylesheet":Gxe,m||(y.as="script"),y.crossOrigin="",y.href=p,u&&y.setAttribute("nonce",u),document.head.appendChild(y),m)return new Promise((x,_)=>{y.addEventListener("load",x),y.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(c){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=c,window.dispatchEvent(u),!u.defaultPrevented)throw c}return s.then(c=>{for(const u of c||[])u.status==="rejected"&&i(u.reason);return e().catch(i)})},E1={servers:{},selectedServer:"none",selectedMultipleServers:[],isMultiSelectMode:!1},_f=(t,e,n={})=>({...t,connectionStatus:e,...n});function Kxe(t,e){switch(e.type){case"HYDRATE_STATE":return e.payload;case"UPSERT_SERVER":return{...t,servers:{...t.servers,[e.name]:e.server}};case"CONNECT_REQUEST":{const n=t.servers[e.name],r=n?_f(n,"connecting",{enabled:!0}):{name:e.name,config:e.config,lastConnectionTime:new Date,connectionStatus:"connecting",retryCount:0,enabled:!0};return{...t,servers:{...t.servers,[e.name]:{...r,config:e.config}},selectedServer:e.select?e.name:t.selectedServer}}case"CONNECT_SUCCESS":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:_f(n,"connected",{config:e.config,lastConnectionTime:new Date,retryCount:0,lastError:void 0,oauthTokens:e.tokens??n.oauthTokens,enabled:!0})}}:t}case"CONNECT_FAILURE":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:_f(n,"failed",{retryCount:n.retryCount,lastError:e.error})}}:t}case"RECONNECT_REQUEST":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:_f(n,"connecting",{enabled:!0})}}:t}case"DISCONNECT":{const n=t.servers[e.name];if(!n)return t;const r=t.selectedServer===e.name?"none":t.selectedServer;return{...t,servers:{...t.servers,[e.name]:_f(n,"disconnected",{enabled:!1,lastError:e.error??n.lastError})},selectedServer:r,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"REMOVE_SERVER":{const{[e.name]:n,...r}=t.servers;return{...t,servers:r,selectedServer:t.selectedServer===e.name?"none":t.selectedServer,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"SYNC_AGENT_STATUS":{const n=new Map(e.servers.map(s=>[s.id,s.status])),r={};for(const[s,i]of Object.entries(t.servers)){if(i.connectionStatus==="connecting"||i.connectionStatus==="oauth-flow"){r[s]=i;continue}const c=n.get(s);c?r[s]={...i,connectionStatus:c}:r[s]={...i,connectionStatus:"disconnected"}}return{...t,servers:r}}case"SELECT_SERVER":return{...t,selectedServer:e.name};case"SET_MULTI_SELECTED":return{...t,selectedMultipleServers:e.names};case"SET_MULTI_MODE":return{...t,isMultiSelectMode:e.enabled,selectedMultipleServers:e.enabled?[]:t.selectedMultipleServers};default:return t}}const y6="mcp-inspector-state";function Qxe(t){const e=t.config;let n=e;if(e&&typeof e.url=="string")try{n={...e,url:new URL(e.url)}}catch{}return{...t,config:n,connectionStatus:t.connectionStatus||"disconnected",retryCount:t.retryCount||0,lastConnectionTime:t.lastConnectionTime?new Date(t.lastConnectionTime):new Date,enabled:t.enabled!==!1}}function Xxe(){try{const t=localStorage.getItem(y6);if(!t)return E1;const e=JSON.parse(t);return{servers:Object.fromEntries(Object.entries(e.servers||{}).map(([r,s])=>[r,Qxe(s)])),selectedServer:e.selectedServer||"none",selectedMultipleServers:e.selectedMultipleServers||[],isMultiSelectMode:e.isMultiSelectMode||!1}}catch{return E1}}function Zxe(t){const e={...t,servers:Object.fromEntries(Object.entries(t.servers).map(([n,r])=>{const s=r.config,i=s&&s.url instanceof URL?{...s,url:s.url.toString()}:s;return[n,{...r,config:i}]}))};localStorage.setItem(y6,JSON.stringify(e))}async function wf(t,e){return(await fetch("/api/mcp/connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverConfig:t,serverId:e})})).json()}async function Jxe(t){return(await fetch(`/api/mcp/servers/${encodeURIComponent(t)}`,{method:"DELETE"})).json()}async function e0e(){return(await fetch("/api/mcp/servers")).json()}async function t0e(t){if(!t.oauthTokens)return{kind:"ready",serverConfig:t.config,tokens:void 0};const e=await uk(t.name);if(e.success&&e.serverConfig)return{kind:"ready",serverConfig:e.serverConfig,tokens:mi(t.name)};const n=t.config?.url?.toString?.();if(n){kh(t.name);const r={serverName:t.name,serverUrl:n,clientId:t.oauthTokens?.client_id,clientSecret:t.oauthTokens?.client_secret},s=await nv(r);return s.success&&s.serverConfig?{kind:"ready",serverConfig:s.serverConfig,tokens:mi(t.name)}:s.success&&!s.serverConfig?{kind:"redirect"}:{kind:"error",error:s.error||"OAuth init failed"}}return{kind:"error",error:"OAuth refresh failed and no URL present"}}function uw(t){return t.type==="stdio"?{command:t.command,args:t.args,env:t.env}:{url:new URL(t.url),requestInit:{headers:t.headers||{}}}}function n0e(){const t=K5("Connections"),[e,n]=w.useReducer(Kxe,E1),[r,s]=w.useState(!0),i=w.useRef(new Map),o=T=>{const N=(i.current.get(T)??0)+1;return i.current.set(T,N),N},c=(T,P)=>(i.current.get(T)??0)!==P;w.useEffect(()=>{try{const T=Xxe();n({type:"HYDRATE_STATE",payload:T})}catch(T){t.error("Failed to load saved state",{error:T instanceof Error?T.message:"Unknown error"})}finally{s(!1)}},[t]),w.useEffect(()=>{r||Zxe(e)},[e,r]);const u=T=>{if(T.type==="stdio")return!T.command||T.command.trim()===""?"Command is required for STDIO connections":null;if(!T.url||T.url.trim()==="")return"URL is required for HTTP connections";try{new URL(T.url)}catch(P){return`Invalid URL format: ${T.url} ${P}`}return null},d=w.useCallback(()=>{const T=Object.entries(e.servers).filter(([,P])=>P.enabled!==!1).map(([P])=>P);n({type:"SET_MULTI_SELECTED",names:T})},[e.servers]),p=w.useCallback(async T=>{window.history.replaceState({},document.title,window.location.pathname);try{const P=await W5(T);if(P.success&&P.serverConfig&&P.serverName){const N=P.serverName;n({type:"CONNECT_REQUEST",name:N,config:P.serverConfig,select:!0});try{const L=await wf(P.serverConfig,N);L.success?(n({type:"CONNECT_SUCCESS",name:N,config:P.serverConfig,tokens:mi(N)}),t.info("OAuth connection successful",{serverName:N}),Wt.success(`OAuth connection successful! Connected to ${N}.`)):(n({type:"CONNECT_FAILURE",name:N,error:L.error||"Connection test failed after OAuth"}),t.error("OAuth connection test failed",{serverName:N,error:L.error}),Wt.error(`OAuth succeeded but connection test failed: ${L.error}`))}catch(L){const O=L instanceof Error?L.message:"Unknown connection error";n({type:"CONNECT_FAILURE",name:N,error:O}),t.error("OAuth connection test error",{serverName:N,error:O}),Wt.error(`OAuth succeeded but connection test failed: ${O}`)}}else throw new Error(P.error||"OAuth callback failed")}catch(P){const N=P instanceof Error?P.message:"Unknown error";Wt.error(`Error completing OAuth flow: ${N}`),t.error("OAuth callback failed",{error:N})}},[t]);w.useEffect(()=>{if(!r){const T=new URLSearchParams(window.location.search),P=T.get("code"),N=T.get("error");P?p(P):N&&(Wt.error(`OAuth authorization failed: ${N}`),localStorage.removeItem("mcp-oauth-pending"),window.history.replaceState({},document.title,window.location.pathname))}},[r,p]);const m=w.useCallback(async T=>{const P=u(T);if(P){Wt.error(P);return}const N=uw(T);n({type:"CONNECT_REQUEST",name:T.name,config:N,select:!0});const L=o(T.name);try{if(T.type==="http"&&T.useOAuth&&T.url){n({type:"UPSERT_SERVER",name:T.name,server:{name:T.name,config:N,lastConnectionTime:new Date,connectionStatus:"oauth-flow",retryCount:0,enabled:!0}});const{initiateOAuth:z}=await Wxe(async()=>{const{initiateOAuth:Y}=await Promise.resolve().then(()=>JJ);return{initiateOAuth:Y}},void 0),U={serverName:T.name,serverUrl:T.url,clientId:T.clientId,clientSecret:T.clientSecret};T.oauthScopes&&T.oauthScopes.length>0&&(U.scopes=T.oauthScopes);const K=await z(U);if(K.success){if(K.serverConfig){const Y=await wf(K.serverConfig,T.name);if(c(T.name,L))return;Y.success?(n({type:"CONNECT_SUCCESS",name:T.name,config:K.serverConfig,tokens:mi(T.name)}),Wt.success("Connected successfully with OAuth!")):(n({type:"CONNECT_FAILURE",name:T.name,error:Y.error||"OAuth connection test failed"}),Wt.error(`OAuth succeeded but connection failed: ${Y.error}`))}else Wt.success("OAuth flow initiated. You will be redirected to authorize access.");return}else{if(c(T.name,L))return;n({type:"CONNECT_FAILURE",name:T.name,error:K.error||"OAuth initialization failed"}),Wt.error(`OAuth initialization failed: ${K.error}`);return}}const O=await wf(N,T.name);if(c(T.name,L))return;O.success?(n({type:"CONNECT_SUCCESS",name:T.name,config:N}),t.info("Connection successful",{serverName:T.name}),Wt.success("Connected successfully!")):(n({type:"CONNECT_FAILURE",name:T.name,error:O.error||"Connection test failed"}),t.error("Connection failed",{serverName:T.name,error:O.error}),Wt.error(`Failed to connect to ${T.name}`))}catch(O){const z=O instanceof Error?O.message:"Unknown error";if(c(T.name,L))return;n({type:"CONNECT_FAILURE",name:T.name,error:z}),t.error("Connection failed",{serverName:T.name,error:z}),Wt.error(`Network error: ${z}`)}},[e.servers,t]),v=w.useRef(!1);w.useEffect(()=>{!r&&!v.current&&(v.current=!0,fetch("/api/mcp-cli-config").then(T=>T.json()).then(T=>{const P=T.config;if(P){if(P.servers&&Array.isArray(P.servers)){const N=P.autoConnectServer;t.info("Processing CLI-provided MCP servers (from config file)",{serverCount:P.servers.length,autoConnectServer:N||"all",cliConfig:P}),P.servers.forEach(L=>{const O={name:L.name||"CLI Server",type:L.type==="sse"?"http":L.type||"stdio",command:L.command,args:L.args||[],url:L.url,env:L.env||{}},z=uw(O);n({type:"UPSERT_SERVER",name:O.name,server:{name:O.name,config:z,lastConnectionTime:new Date,connectionStatus:"disconnected",retryCount:0,enabled:!1}}),!N||L.name===N?(t.info("Auto-connecting to server",{serverName:L.name}),m(O)):t.info("Skipping auto-connect for server",{serverName:L.name,reason:"filtered out"})});return}if(P.command){t.info("Auto-connecting to CLI-provided MCP server",{cliConfig:P});const N={name:P.name||"CLI Server",type:"stdio",command:P.command,args:P.args||[],env:P.env||{}};m(N)}}}).catch(T=>{t.debug("Could not fetch CLI config from API",{error:T})}))},[r,m,t,e.servers]);const y=w.useCallback(async T=>{const P=e.servers[T];return P?.oauthTokens&&P.oauthTokens.access_token||null},[e.servers]),x=w.useCallback(async T=>{t.info("Disconnecting from server",{serverName:T}),n({type:"DISCONNECT",name:T});try{const P=await Jxe(T);P.success||n({type:"DISCONNECT",name:T,error:P.error})}catch(P){n({type:"DISCONNECT",name:T,error:P instanceof Error?P.message:"Unknown error"})}},[]),_=w.useCallback(async T=>{t.info("Removing server",{serverName:T}),kh(T),n({type:"REMOVE_SERVER",name:T})},[]),E=w.useCallback(async T=>{t.info("Reconnecting to server",{serverName:T});const P=e.servers[T];if(!P)throw new Error(`Server ${T} not found`);n({type:"RECONNECT_REQUEST",name:T});const N=o(T);try{const L=await t0e(P);if(L.kind==="redirect")return;if(L.kind==="error"){if(c(T,N))return;n({type:"CONNECT_FAILURE",name:T,error:L.error}),Wt.error(`Failed to connect: ${T}`);return}const O=await wf(L.serverConfig,T);if(c(T,N))return;if(O.success)return n({type:"CONNECT_SUCCESS",name:T,config:L.serverConfig,tokens:L.tokens}),t.info("Reconnection successful",{serverName:T,result:O}),{success:!0};n({type:"CONNECT_FAILURE",name:T,error:O.error||"Connection test failed"}),t.error("Reconnection failed",{serverName:T,result:O}),Wt.error(`Failed to connect: ${T}`)}catch(L){const O=L instanceof Error?L.message:"Unknown error";if(c(T,N))return;throw n({type:"CONNECT_FAILURE",name:T,error:O}),t.error("Reconnection failed",{serverName:T,error:O}),L}},[e.servers]);w.useEffect(()=>{if(r)return;(async()=>{try{const P=await e0e();P?.success&&P.servers&&n({type:"SYNC_AGENT_STATUS",servers:P.servers})}catch(P){t.debug("Failed to sync server status on startup",{error:P instanceof Error?P.message:"Unknown error"})}})()},[r,t]);const S=w.useCallback(T=>{n({type:"SELECT_SERVER",name:T})},[]),A=w.useCallback(T=>{n({type:"SET_MULTI_SELECTED",names:T})},[]),C=w.useCallback(T=>{n({type:"SET_MULTI_MODE",enabled:T})},[]),R=w.useCallback(T=>{const P=e.selectedMultipleServers,N=P.includes(T)?P.filter(L=>L!==T):[...P,T];n({type:"SET_MULTI_SELECTED",names:N})},[e.selectedMultipleServers]),j=w.useCallback(async(T,P)=>{const N=e.servers[T];if(N?.oauthTokens!=null&&P.useOAuth&&P.name===T&&P.type==="http"&&P.url===(N?.config).url?.toString()&&N){const z=uw(P);n({type:"CONNECT_REQUEST",name:T,config:z});try{if((await wf(N.config,T)).success){n({type:"CONNECT_SUCCESS",name:T,config:z}),Wt.success("Server configuration updated successfully!");return}else console.warn("OAuth connection test failed, falling back to full reconnect")}catch(U){console.warn("OAuth connection test error, falling back to full reconnect",U)}}await x(T),await m(P),e.selectedServer===T&&P.name!==T&&S(P.name)},[e.servers,e.selectedServer,x,m]);return{appState:e,isLoading:r,connectedServerConfigs:e.servers,selectedServerEntry:e.servers[e.selectedServer],selectedMCPConfig:e.servers[e.selectedServer]?.config,selectedMCPConfigs:e.selectedMultipleServers.map(T=>e.servers[T]).filter(Boolean),selectedMCPConfigsMap:e.selectedMultipleServers.reduce((T,P)=>(e.servers[P]&&(T[P]=e.servers[P].config),T),{}),isMultiSelectMode:e.isMultiSelectMode,handleConnect:m,handleDisconnect:x,handleReconnect:E,handleUpdate:j,handleRemoveServer:_,setSelectedServer:S,setSelectedMCPConfigs:A,toggleMultiSelectMode:C,toggleServerSelection:R,getValidAccessToken:y,setSelectedMultipleServersToAllServers:d}}var r0e=(t,e,n,r,s,i,o,c)=>{let u=document.documentElement,d=["light","dark"];function p(y){(Array.isArray(t)?t:[t]).forEach(x=>{let _=x==="class",E=_&&i?s.map(S=>i[S]||S):s;_?(u.classList.remove(...E),u.classList.add(i&&i[y]?i[y]:y)):u.setAttribute(x,y)}),m(y)}function m(y){c&&d.includes(y)&&(u.style.colorScheme=y)}function v(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)p(r);else try{let y=localStorage.getItem(e)||n,x=o&&y==="system"?v():y;p(x)}catch{}},s0e=w.createContext(void 0),i0e={setTheme:t=>{},themes:[]},a0e=()=>{var t;return(t=w.useContext(s0e))!=null?t:i0e};w.memo(({forcedTheme:t,storageKey:e,attribute:n,enableSystem:r,enableColorScheme:s,defaultTheme:i,value:o,themes:c,nonce:u,scriptProps:d})=>{let p=JSON.stringify([n,e,i,t,c,o,r,s]).slice(1,-1);return w.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${r0e.toString()})(${p})`}})});const o0e=({...t})=>{const{theme:e="system"}=a0e();return f.jsx($X,{theme:e,className:"toaster group",closeButton:!0,style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...t})};function l0e(){w.useEffect(()=>{if(!window.isElectron||!window.electronAPI?.oauth)return;const t=e=>{console.log("Electron OAuth callback received:",e);try{const n=new URL(e),r=new URLSearchParams(n.search),s=r.get("code"),i=r.get("state"),o=r.get("error");if(o){console.error("OAuth error:",o);return}if(s){console.log("OAuth code received, redirecting to callback page");const c=new URL("/callback",window.location.origin);c.searchParams.set("code",s),i&&c.searchParams.set("state",i),window.location.href=c.toString()}}catch(n){console.error("Failed to parse OAuth callback URL:",n)}};return window.electronAPI.oauth.onCallback(t),()=>{window.electronAPI?.oauth&&window.electronAPI.oauth.removeCallback()}},[])}function c0e(){const{user:t}=tc(),{isAuthenticated:e,isLoading:n}=pd(),r=e6("users:ensureUser"),s=w.useRef(null);w.useEffect(()=>{e||(s.current=null)},[e]),w.useEffect(()=>{if(!n){if(!e&&t)throw console.log("useEnsureDbUser: not authenticated"),new Error("Not authenticated");e&&t&&s.current!==t.id&&r().then(i=>{s.current=t.id}).catch(i=>{console.error("[auth] ensureUser failed",i),s.current=null})}},[e,n,t,r])}function yD({className:t,...e}){return f.jsx(N8,{"data-slot":"avatar",className:Me("relative flex size-8 shrink-0 overflow-hidden rounded-full",t),...e})}function xD({className:t,...e}){return f.jsx(j8,{"data-slot":"avatar-image",className:Me("aspect-square size-full",t),...e})}function bD({className:t,...e}){return f.jsx(P8,{"data-slot":"avatar-fallback",className:Me("bg-muted flex size-full items-center justify-center rounded-full",t),...e})}function u0e(){const{isLoading:t}=pd(),{user:e,signIn:n,signOut:r}=tc();if(t)return f.jsx(Ue,{variant:"outline",size:"sm",disabled:!0,children:f.jsx(Vn,{className:"h-3 w-3 mr-1.5 animate-spin"})});if(!e)return f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Ue,{variant:"outline",onClick:()=>n(),children:"Sign in"}),f.jsx(Ue,{onClick:()=>n(),style:{backgroundColor:"#E55A3A"},children:"Create account"})]});const s=[e.firstName,e.lastName].filter(Boolean).join(" "),i=e.email,o=Tq(s),c=()=>{const d=window.location.origin,m=d.includes("://localhost")?d.replace("://localhost","://127.0.0.1"):d;r({returnTo:m})},u=e.profilePictureUrl||void 0;return f.jsxs(py,{children:[f.jsx(my,{asChild:!0,children:f.jsx("button",{className:"flex size-10 items-center justify-center rounded-full border border-border/60 bg-background/80 shadow-sm outline-none transition hover:ring-2 hover:ring-ring/20 focus-visible:ring-2 focus-visible:ring-ring",children:f.jsxs(yD,{className:"size-9",children:[f.jsx(xD,{src:u,alt:s}),f.jsx(bD,{className:"bg-muted text-muted-foreground text-sm font-medium",children:o!=="?"?o:f.jsx(Ej,{className:"size-4"})})]})})}),f.jsxs(gy,{className:"w-56",align:"end",children:[f.jsx(VX,{className:"pb-3",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs(yD,{className:"size-10",children:[f.jsx(xD,{src:u,alt:s}),f.jsx(bD,{className:"bg-muted text-muted-foreground text-base font-semibold",children:o!=="?"?o:f.jsx(Ej,{className:"size-5"})})]}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-sm font-medium leading-none truncate",children:s}),f.jsx("p",{className:"text-xs text-muted-foreground truncate",children:i})]})]})}),f.jsx(Rj,{}),f.jsxs(Aa,{onClick:()=>window.location.hash="settings",children:[f.jsx(QE,{className:"size-4"}),"Settings"]}),f.jsx(Rj,{}),f.jsxs(Aa,{variant:"destructive",onClick:c,children:[f.jsx(kQ,{className:"size-4"}),"Log out"]})]})]})}function d0e(){const[t,e]=w.useState("servers");l0e(),c0e();const n=w.useMemo(()=>window.location.pathname.startsWith("/oauth/callback/debug"),[]),r=w.useMemo(()=>window.location.pathname==="/callback",[]),{appState:s,isLoading:i,connectedServerConfigs:o,selectedMCPConfig:c,handleConnect:u,handleDisconnect:d,handleReconnect:p,handleUpdate:m,handleRemoveServer:v,setSelectedServer:y,toggleServerSelection:x,selectedMCPConfigsMap:_,setSelectedMultipleServersToAllServers:E}=n0e();w.useEffect(()=>{const A=()=>{const C=(window.location.hash||"#servers").replace("#","");e(C),C==="chat"&&E()};return A(),window.addEventListener("hashchange",A),()=>window.removeEventListener("hashchange",A)},[E]);const S=A=>{A==="chat"&&E(),window.location.hash=A,e(A)};return n?f.jsx(pxe,{}):r?(w.useEffect(()=>{const A=setTimeout(()=>{window.location.href="/"},5e3);return()=>clearTimeout(A)},[]),f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Completing sign in..."}),f.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If this takes too long, you'll be redirected automatically"})]})})):i?f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})}):f.jsxs(vme,{themeMode:"light",themePreset:"default",children:[f.jsxs(Rxe,{defaultOpen:!0,children:[f.jsx(Vxe,{onNavigate:S,activeTab:t}),f.jsxs(Pxe,{className:"flex flex-col",children:[f.jsx("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear drag",children:f.jsxs("div",{className:"flex w-full items-center justify-between px-4 lg:px-6",children:[f.jsx("div",{className:"flex items-center gap-1 lg:gap-2",children:f.jsx(jxe,{className:"-ml-1"})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsx(u0e,{})})]})}),f.jsxs("div",{className:"flex-1",children:[(t==="tools"||t==="resources"||t==="prompts"||t==="auth"||t==="chat"||t==="interceptor")&&f.jsx(Hxe,{connectedServerConfigs:o,selectedServer:s.selectedServer,onServerChange:y,onConnect:u,isMultiSelectEnabled:t==="chat",onMultiServerToggle:x,selectedMultipleServers:s.selectedMultipleServers}),t==="servers"&&f.jsx(aee,{connectedServerConfigs:o,onConnect:u,onDisconnect:d,onReconnect:p,onUpdate:m,onRemove:v}),t==="tools"&&f.jsx(hre,{serverConfig:c,serverName:s.selectedServer}),t==="evals"&&f.jsx(ove,{}),t==="resources"&&f.jsx(pre,{serverConfig:c,serverName:s.selectedServer}),t==="prompts"&&f.jsx(mre,{serverConfig:c,serverName:s.selectedServer}),t==="auth"&&f.jsx(hxe,{serverConfig:c,serverEntry:s.servers[s.selectedServer],serverName:s.selectedServer}),t==="chat"&&f.jsx(nve,{serverConfigs:_,connectedServerConfigs:o}),t==="interceptor"&&f.jsx(lxe,{connectedServerConfigs:o,selectedServer:s.selectedServer}),t==="tracing"&&f.jsx(oxe,{}),t==="settings"&&f.jsx(nxe,{})]})]})]}),f.jsx(o0e,{})]})}const f0e="phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9",h0e="https://us.i.posthog.com",p0e={api_host:h0e,capture_pageview:!1},m0e=()=>f0e,g0e=()=>p0e;var ve=typeof window<"u"?window:void 0,is=typeof globalThis<"u"?globalThis:ve,x6=Array.prototype,_D=x6.forEach,wD=x6.indexOf,Cs=is?.navigator,Be=is?.document,ts=is?.location,k1=is?.fetch,C1=is!=null&&is.XMLHttpRequest&&"withCredentials"in new is.XMLHttpRequest?is.XMLHttpRequest:void 0,SD=is?.AbortController,es=Cs?.userAgent,st=ve??{},ka={DEBUG:!1,LIB_VERSION:"1.268.1"};function ED(t,e,n,r,s,i,o){try{var c=t[i](o),u=c.value}catch(d){return void n(d)}c.done?e(u):Promise.resolve(u).then(r,s)}function kD(t){return function(){var e=this,n=arguments;return new Promise(function(r,s){var i=t.apply(e,n);function o(u){ED(i,r,s,o,c,"next",u)}function c(u){ED(i,r,s,o,c,"throw",u)}o(void 0)})}}function Le(){return Le=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Le.apply(null,arguments)}function b6(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var v0e=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function Ct(t,e){return t.indexOf(e)!==-1}var By=function(t){return t.trim()},T1=function(t){return t.replace(/^\$/,"")},y0e=Array.isArray,_6=Object.prototype,w6=_6.hasOwnProperty,qy=_6.toString,dn=y0e||function(t){return qy.call(t)==="[object Array]"},Xs=t=>typeof t=="function",Dn=t=>t===Object(t)&&!dn(t),mu=t=>{if(Dn(t)){for(var e in t)if(w6.call(t,e))return!1;return!0}return!1},Oe=t=>t===void 0,In=t=>qy.call(t)=="[object String]",A1=t=>In(t)&&t.trim().length===0,Ga=t=>t===null,Ot=t=>Oe(t)||Ga(t),Nr=t=>qy.call(t)=="[object Number]",vi=t=>qy.call(t)==="[object Boolean]",x0e=t=>t instanceof FormData,b0e=t=>Ct(v0e,t);function R1(t){return t===null||typeof t!="object"}function Cv(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function S6(t){return!Oe(Event)&&function(e,n){try{return e instanceof n}catch{return!1}}(t,Event)}var _0e=[!0,"true",1,"1","yes"],dw=t=>Ct(_0e,t),w0e=[!1,"false",0,"0","no"];function Ts(t,e,n,r,s){return e>n&&(r.warn("min cannot be greater than max."),e=n),Nr(t)?t>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),Ts(s||n,e,n,r))}class E6{stop(){this.t&&(clearInterval(this.t),this.t=void 0)}constructor(e){this.i=e,this.o={},this.h=()=>{Object.keys(this.o).forEach(n=>{var r=this.m(n)+this.S;r>=this.k?delete this.o[n]:this.$(n,r)})},this.m=n=>this.o[String(n)],this.$=(n,r)=>{this.o[String(n)]=r},this.consumeRateLimit=n=>{var r,s=(r=this.m(n))!=null?r:this.k;if((s=Math.max(s-1,0))===0)return!0;this.$(n,s);var i,o=s===0;return o&&((i=this.P)==null||i.call(this,n)),o},this.P=this.i.P,this.k=Ts(this.i.bucketSize,0,100,this.i.I),this.S=Ts(this.i.refillRate,0,this.k,this.i.I),this.R=Ts(this.i.refillInterval,0,864e5,this.i.I),this.t=setInterval(()=>{this.h()},this.R)}}var tg,CD,fw,S0e=t=>t instanceof Error;function E0e(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return fw&&n.length===CD||(CD=n.length,fw=n.reduce((r,s)=>{tg||(tg={});var i=tg[s];if(i)r[i[0]]=i[1];else for(var o=t(s),c=o.length-1;c>=0;c--){var u=o[c],d=u?.filename,p=e[s];if(d&&p){r[d]=p,tg[s]=[d,p];break}}return r},{})),fw}}var Yu="?";function N1(t,e,n,r){var s={platform:"web:javascript",filename:t,function:e==="<anonymous>"?Yu:e,in_app:!0};return Oe(n)||(s.lineno=n),Oe(r)||(s.colno=r),s}var k6=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:Yu,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},k0e=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,C0e=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,T0e=/\((\S*)(?::(\d+))(?::(\d+))\)/,A0e=t=>{var e=k0e.exec(t);if(e){var[,n,r,s]=e;return N1(n,Yu,+r,+s)}var i=C0e.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var o=T0e.exec(i[2]);o&&(i[2]=o[1],i[3]=o[2],i[4]=o[3])}var[c,u]=k6(i[1]||Yu,i[2]);return N1(u,c,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},R0e=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,N0e=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,j0e=t=>{var e=R0e.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=N0e.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],s=e[1]||Yu;return[s,r]=k6(s,r),N1(r,s,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}},TD=/\(error: (.*)\)/,AD=50;function P0e(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return function(r){for(var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=[],o=r.split(`
1837
1837
  `),c=s;c<o.length;c++){var u=o[c];if(!(u.length>1024)){var d=TD.test(u)?u.replace(TD,"$1"):u;if(!d.match(/\S*Error: /)){for(var p of e){var m=p(d);if(m){i.push(m);break}}if(i.length>=AD)break}}}return function(v){if(!v.length)return[];var y=Array.from(v);return y.reverse(),y.slice(0,AD).map(x=>{return Le({},x,{filename:x.filename||(_=y,_[_.length-1]||{}).filename,function:x.function||Yu});var _})}(i)}}class M0e{buildFromUnknown(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=n&&n.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(r,n,0).apply(e),i=this.buildParsingContext(),o=this.parseStacktrace(s,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var r,s;return e.cause!=null&&(r=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),n.chunkIdMap)),Le({},e,{cause:r,stack:s})}applyChunkIds(e,n){return e.map(r=>(r.filename&&n&&(r.chunk_id=n[r.filename]),r))}applyCoercers(e,n){for(var r of this.coercers)if(r.match(e))return r.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return kD(function*(){var r=e;for(var s of n.modifiers)r=yield s(r);return r})()}modifyFrames(e){var n=this;return kD(function*(){var r;e.cause!=null&&(r=yield n.modifyFrames(e.cause));var s=[];return e.stack!=null&&(s=yield n.applyModifiers(e.stack)),Le({},e,{cause:r,stack:s})})()}convertToExceptionList(e,n){var r,s,i,o={type:e.type,value:e.value,mechanism:{type:(r=n.type)!=null?r:"generic",handled:(s=n.handled)==null||s,synthetic:(i=e.synthetic)!=null&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var c=[o];return e.cause!=null&&c.push(...this.convertToExceptionList(e.cause,Le({},n,{handled:!0}))),c}buildParsingContext(){return{chunkIdMap:E0e(this.stackParser)}}buildCoercingContext(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,s=(i,o)=>{if(o<=4){var c=this.buildCoercingContext(e,n,o);return this.applyCoercers(i,c)}};return Le({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:e,apply:i=>s(i,r),next:i=>s(i,r+1)})}constructor(e,n,r){e===void 0&&(e=[]),n===void 0&&(n=[]),r===void 0&&(r=[]),this.coercers=e,this.modifiers=r,this.stackParser=P0e(...n)}}class O0e{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var r=In(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Cv(e,"DOMException")}isDOMError(e){return Cv(e,"DOMError")}}class D0e{match(e){return(n=>n instanceof Error)(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var r=e.message;return r.error&&typeof r.error.message=="string"?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class I0e{match(e){return Cv(e,"ErrorEvent")&&e.error!=null}coerce(e,n){var r,s=n.apply(e.error);return s||{type:"ErrorEvent",value:e.message,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}constructor(){}}var L0e=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class z0e{match(e){return typeof e=="string"}coerce(e,n){var r,[s,i]=this.getInfos(e);return{type:s??"Error",value:i??e,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var n="Error",r=e,s=e.match(L0e);return s&&(n=s[1],r=s[2]),[n,r]}}var $0e=["fatal","error","warning","log","info","debug"];function C6(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:40,n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var r=n.length;r>0;r--){var s=n.slice(0,r).join(", ");if(!(s.length>e))return r===n.length||s.length<=e?s:s.slice(0,e)+"..."}return""}class F0e{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return S6(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+C6(e)}isSeverityLevel(e){return In(e)&&!A1(e)&&$0e.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var r=e[n];if(S0e(r))return r}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class U0e{match(e){return S6(e)}coerce(e,n){var r,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+C6(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class V0e{match(e){return R1(e)}coerce(e,n){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class B0e{match(e){return Cv(e,"PromiseRejectionEvent")}coerce(e,n){var r,s=this.getUnhandledRejectionReason(e);return R1(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(s)}getUnhandledRejectionReason(e){if(R1(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var T6=t=>{var e={T:function(n){if(ve&&(ka.DEBUG||st.POSTHOG_DEBUG)&&!Oe(ve.console)&&ve.console){for(var r=("__rrweb_original__"in ve.console[n])?ve.console[n].__rrweb_original__:ve.console[n],s=arguments.length,i=new Array(s>1?s-1:0),o=1;o<s;o++)i[o-1]=arguments[o];r(t,...i)}},info:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.T("log",...r)},warn:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.T("warn",...r)},error:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.T("error",...r)},critical:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];console.error(t,...r)},uninitializedWarning:n=>{e.error("You must initialize PostHog before calling "+n)},createLogger:n=>T6(t+" "+n)};return e},Ve=T6("[PostHog.js]"),or=Ve.createLogger,q0e=or("[ExternalScriptsLoader]"),RD=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return q0e.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=Be?.querySelectorAll("script");if(r){for(var s,i=function(){if(r[o].src===e){var u=r[o];return u.__posthog_loading_callback_fired?{v:n()}:(u.addEventListener("load",d=>{u.__posthog_loading_callback_fired=!0,n(void 0,d)}),u.onerror=d=>n(d),{v:void 0})}},o=0;o<r.length;o++)if(s=i())return s.v}var c=()=>{if(!Be)return n("document not found");var u=Be.createElement("script");if(u.type="text/javascript",u.crossOrigin="anonymous",u.src=e,u.onload=m=>{u.__posthog_loading_callback_fired=!0,n(void 0,m)},u.onerror=m=>n(m),t.config.prepare_external_dependency_script&&(u=t.config.prepare_external_dependency_script(u)),!u)return n("prepare_external_dependency_script returned null");var d,p=Be.querySelectorAll("body > script");p.length>0?(d=p[0].parentNode)==null||d.insertBefore(u,p[0]):Be.body.appendChild(u)};Be!=null&&Be.body?c():Be?.addEventListener("DOMContentLoaded",c)};st.__PosthogExtensions__=st.__PosthogExtensions__||{},st.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{var r="/static/"+e+".js?v="+t.version;if(e==="remote-config"&&(r="/array/"+t.config.token+"/config.js"),e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}var i=t.requestRouter.endpointFor("assets",r);RD(t,i,n)},st.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var r=t.requestRouter.endpointFor("api",e);RD(t,r,n)};var Tv={};function Po(t,e,n){if(dn(t)){if(_D&&t.forEach===_D)t.forEach(e,n);else if("length"in t&&t.length===+t.length){for(var r=0,s=t.length;r<s;r++)if(r in t&&e.call(n,t[r],r)===Tv)return}}}function tn(t,e,n){if(!Ot(t)){if(dn(t))return Po(t,e,n);if(x0e(t)){for(var r of t.entries())if(e.call(n,r[1],r[0])===Tv)return}else for(var s in t)if(w6.call(t,s)&&e.call(n,t[s],s)===Tv)return}}var Bn=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Po(n,function(s){for(var i in s)s[i]!==void 0&&(t[i]=s[i])}),t},Hy=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Po(n,function(s){Po(s,function(i){t.push(i)})}),t};function Ag(t){for(var e=Object.keys(t),n=e.length,r=new Array(n);n--;)r[n]=[e[n],t[e[n]]];return r}var ND=function(t){try{return t()}catch{return}},H0e=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.apply(this,n)}catch(s){Ve.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ve.critical(s)}}},FC=function(t){var e={};return tn(t,function(n,r){(In(n)&&n.length>0||Nr(n))&&(e[r]=n)}),e};function G0e(t,e){return n=t,r=i=>In(i)&&!Ga(e)?i.slice(0,e):i,s=new Set,function i(o,c){return o!==Object(o)?r?r(o,c):o:s.has(o)?void 0:(s.add(o),dn(o)?(u=[],Po(o,d=>{u.push(i(d))})):(u={},tn(o,(d,p)=>{s.has(d)||(u[p]=i(d,p))})),u);var u}(n);var n,r,s}var Y0e=["herokuapp.com","vercel.app","netlify.app"];function W0e(t){var e=t?.hostname;if(!In(e))return!1;var n=e.split(".").slice(-2).join(".");for(var r of Y0e)if(n===r)return!1;return!0}function A6(t,e){for(var n=0;n<t.length;n++)if(e(t[n]))return t[n]}function Cn(t,e,n,r){var{capture:s=!1,passive:i=!0}=r??{};t?.addEventListener(e,n,{capture:s,passive:i})}var R6="$people_distinct_id",qf="__alias",Hf="__timers",jD="$autocapture_disabled_server_side",j1="$heatmaps_enabled_server_side",PD="$exception_capture_enabled_server_side",P1="$error_tracking_suppression_rules",MD="$error_tracking_capture_extension_exceptions",OD="$web_vitals_enabled_server_side",N6="$dead_clicks_enabled_server_side",DD="$web_vitals_allowed_metrics",hw="$session_recording_remote_config",M1="$session_recording_enabled_server_side",ID="$console_log_recording_enabled_server_side",LD="$session_recording_network_payload_capture",zD="$session_recording_masking",$D="$session_recording_canvas_recording",FD="$replay_sample_rate",UD="$replay_minimum_duration",VD="$replay_script_config",Av="$sesid",gu="$session_is_sampled",O1="$session_recording_url_trigger_activated_session",D1="$session_recording_event_trigger_activated_session",vu="$enabled_feature_flags",Gf="$early_access_features",I1="$feature_flag_details",Yf="$stored_person_properties",Cl="$stored_group_properties",L1="$surveys",ng="$surveys_activated",Rv="$flag_call_reported",_a="$user_state",z1="$client_session_props",$1="$capture_rate_limit",F1="$initial_campaign_params",U1="$initial_referrer_info",Nv="$initial_person_info",jv="$epp",j6="__POSTHOG_TOOLBAR__",Sf="$posthog_cookieless",K0e=[R6,qf,"__cmpns",Hf,M1,j1,Av,vu,P1,_a,Gf,I1,Cl,Yf,L1,Rv,z1,$1,F1,U1,jv,Nv];function BD(t){return t instanceof Element&&(t.id===j6||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Gy(t){return!!t&&t.nodeType===1}function Mo(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function P6(t){return!!t&&t.nodeType===3}function M6(t){return!!t&&t.nodeType===11}function UC(t){return t?By(t).split(/\s+/):[]}function qD(t){var e=ve?.location.href;return!!(e&&t&&t.some(n=>e.match(n)))}function Pv(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return UC(e)}function O6(t){return Ot(t)?null:By(t).split(/(\s+)/).filter(e=>Wu(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Yy(t){var e="";return V1(t)&&!$6(t)&&t.childNodes&&t.childNodes.length&&tn(t.childNodes,function(n){var r;P6(n)&&n.textContent&&(e+=(r=O6(n.textContent))!==null&&r!==void 0?r:"")}),By(e)}function D6(t){return Oe(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null;var e}var VC=["a","button","form","input","select","textarea","label"];function I6(t,e){if(Oe(e))return!0;var n,r=function(i){if(e.some(o=>i.matches(o)))return{v:!0}};for(var s of t)if(n=r(s))return n.v;return!1}function L6(t){var e=t.parentNode;return!(!e||!Gy(e))&&e}var HD=[".ph-no-rageclick",".ph-no-capture"],BC=t=>!t||Mo(t,"html")||!Gy(t),z6=(t,e)=>{if(!ve||BC(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[t],s=t;s.parentNode&&!Mo(s,"body");)if(M6(s.parentNode))r.push(s.parentNode.host),s=s.parentNode.host;else{var i=L6(s);if(!i)break;if(e||VC.indexOf(i.tagName.toLowerCase())>-1)n=!0;else{var o=ve.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}r.push(i),s=i}return{parentIsUsefulElement:n,targetElementList:r}};function Q0e(t,e,n,r,s){var i,o,c,u;if(n===void 0&&(n=void 0),!ve||BC(t)||(i=n)!=null&&i.url_allowlist&&!qD(n.url_allowlist)||(o=n)!=null&&o.url_ignorelist&&qD(n.url_ignorelist))return!1;if((c=n)!=null&&c.dom_event_allowlist){var d=n.dom_event_allowlist;if(d&&!d.some(x=>e.type===x))return!1}var{parentIsUsefulElement:p,targetElementList:m}=z6(t,r);if(!function(x,_){var E=_?.element_allowlist;if(Oe(E))return!0;var S,A=function(R){if(E.some(j=>R.tagName.toLowerCase()===j))return{v:!0}};for(var C of x)if(S=A(C))return S.v;return!1}(m,n)||!I6(m,(u=n)==null?void 0:u.css_selector_allowlist))return!1;var v=ve.getComputedStyle(t);if(v&&v.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var y=t.tagName.toLowerCase();switch(y){case"html":return!1;case"form":return(s||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(e.type)>=0;default:return p?(s||["click"]).indexOf(e.type)>=0:(s||["click"]).indexOf(e.type)>=0&&(VC.indexOf(y)>-1||t.getAttribute("contenteditable")==="true")}}function V1(t){for(var e=t;e.parentNode&&!Mo(e,"body");e=e.parentNode){var n=Pv(e);if(Ct(n,"ph-sensitive")||Ct(n,"ph-no-capture"))return!1}if(Ct(Pv(t),"ph-include"))return!0;var r=t.type||"";if(In(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var s=t.name||t.id||"";return!(In(s)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g,"")))}function $6(t){return!!(Mo(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Mo(t,"select")||Mo(t,"textarea")||t.getAttribute("contenteditable")==="true")}var F6="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",X0e=new RegExp("^(?:"+F6+")$"),Z0e=new RegExp(F6),U6="\\d{3}-?\\d{2}-?\\d{4}",J0e=new RegExp("^("+U6+")$"),ebe=new RegExp("("+U6+")");function Wu(t,e){return e===void 0&&(e=!0),!(Ot(t)||In(t)&&(t=By(t),(e?X0e:Z0e).test((t||"").replace(/[- ]/g,""))||(e?J0e:ebe).test(t)))}function V6(t){var e=Yy(t);return Wu(e=(e+" "+B6(t)).trim())?e:""}function B6(t){var e="";return t&&t.childNodes&&t.childNodes.length&&tn(t.childNodes,function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var s=Yy(n);e=(e+" "+s).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+B6(n)).trim())}catch(i){Ve.error("[AutoCapture]",i)}}),e}function tbe(t){return function(e){var n=e.map(r=>{var s,i,o="";if(r.tag_name&&(o+=r.tag_name),r.attr_class)for(var c of(r.attr_class.sort(),r.attr_class))o+="."+c.replace(/"/g,"");var u=Le({},r.text?{text:r.text}:{},{"nth-child":(s=r.nth_child)!==null&&s!==void 0?s:0,"nth-of-type":(i=r.nth_of_type)!==null&&i!==void 0?i:0},r.href?{href:r.href}:{},r.attr_id?{attr_id:r.attr_id}:{},r.attributes),d={};return Ag(u).sort((p,m)=>{var[v]=p,[y]=m;return v.localeCompare(y)}).forEach(p=>{var[m,v]=p;return d[GD(m.toString())]=GD(v.toString())}),o+=":",o+=Ag(d).map(p=>{var[m,v]=p;return m+'="'+v+'"'}).join("")});return n.join(";")}(function(e){return e.map(n=>{var r,s,i={text:(r=n.$el_text)==null?void 0:r.slice(0,400),tag_name:n.tag_name,href:(s=n.attr__href)==null?void 0:s.slice(0,2048),attr_class:nbe(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return Ag(n).filter(o=>{var[c]=o;return c.indexOf("attr__")===0}).forEach(o=>{var[c,u]=o;return i.attributes[c]=u}),i})}(t))}function GD(t){return t.replace(/"|\\"/g,'\\"')}function nbe(t){var e=t.attr__class;return e?dn(e)?e:UC(e):void 0}class q6{constructor(){this.clicks=[]}isRageClick(e,n,r){var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(n-s.y)<30&&r-s.timestamp<1e3){if(this.clicks.push({x:e,y:n,timestamp:r}),this.clicks.length===3)return!0}else this.clicks=[{x:e,y:n,timestamp:r}];return!1}}var pw="$copy_autocapture",Ta=function(t){return t.GZipJS="gzip-js",t.Base64="base64",t}({}),rbe=["localhost","127.0.0.1"],Ku=t=>{var e=Be?.createElement("a");return Oe(e)?null:(e.href=t,e)},sbe=function(t,e){var n,r;e===void 0&&(e="&");var s=[];return tn(t,function(i,o){Oe(i)||Oe(o)||o==="undefined"||(n=encodeURIComponent((c=>c instanceof File)(i)?i.name:i.toString()),r=encodeURIComponent(o),s[s.length]=r+"="+n)}),s.join(e)},Mv=function(t,e){for(var n,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;s<r.length;s++){var i=r[s].split("=");if(i[0]===e){n=i;break}}if(!dn(n)||n.length<2)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{Ve.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},qC=function(t,e,n){if(!t||!e||!e.length)return t;for(var r=t.split("#"),s=r[0]||"",i=r[1],o=s.split("?"),c=o[1],u=o[0],d=(c||"").split("&"),p=[],m=0;m<d.length;m++){var v=d[m].split("=");dn(v)&&(e.includes(v[0])?p.push(v[0]+"="+n):p.push(d[m]))}var y=u;return c!=null&&(y+="?"+p.join("&")),i!=null&&(y+="#"+i),y},Ov=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},YD=or("[AutoCapture]");function mw(t,e){return e.length>t?e.slice(0,t)+"...":e}function ibe(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Gy(e));return e}function abe(t,e,n,r){var s=t.tagName.toLowerCase(),i={tag_name:s};VC.indexOf(s)>-1&&!n&&(s.toLowerCase()==="a"||s.toLowerCase()==="button"?i.$el_text=mw(1024,V6(t)):i.$el_text=mw(1024,Yy(t)));var o=Pv(t);o.length>0&&(i.classes=o.filter(function(p){return p!==""})),tn(t.attributes,function(p){var m;if((!$6(t)||["name","id","class","aria-label"].indexOf(p.name)!==-1)&&(r==null||!r.includes(p.name))&&!e&&Wu(p.value)&&(m=p.name,!In(m)||m.substring(0,10)!=="_ngcontent"&&m.substring(0,7)!=="_nghost")){var v=p.value;p.name==="class"&&(v=UC(v).join(" ")),i["attr__"+p.name]=mw(1024,v)}});for(var c=1,u=1,d=t;d=ibe(d);)c++,d.tagName===t.tagName&&u++;return i.nth_child=c,i.nth_of_type=u,i}function obe(t,e){for(var n,r,{e:s,maskAllElementAttributes:i,maskAllText:o,elementAttributeIgnoreList:c,elementsChainAsString:u}=e,d=[t],p=t;p.parentNode&&!Mo(p,"body");)M6(p.parentNode)?(d.push(p.parentNode.host),p=p.parentNode.host):(d.push(p.parentNode),p=p.parentNode);var m,v=[],y={},x=!1,_=!1;if(tn(d,R=>{var j=V1(R);R.tagName.toLowerCase()==="a"&&(x=R.getAttribute("href"),x=j&&x&&Wu(x)&&x),Ct(Pv(R),"ph-no-capture")&&(_=!0),v.push(abe(R,i,o,c));var T=function(P){if(!V1(P))return{};var N={};return tn(P.attributes,function(L){if(L.name&&L.name.indexOf("data-ph-capture-attribute")===0){var O=L.name.replace("data-ph-capture-attribute-",""),z=L.value;O&&z&&Wu(z)&&(N[O]=z)}}),N}(R);Bn(y,T)}),_)return{props:{},explicitNoCapture:_};if(o||(t.tagName.toLowerCase()==="a"||t.tagName.toLowerCase()==="button"?v[0].$el_text=V6(t):v[0].$el_text=Yy(t)),x){var E,S;v[0].attr__href=x;var A=(E=Ku(x))==null?void 0:E.host,C=ve==null||(S=ve.location)==null?void 0:S.host;A&&C&&A!==C&&(m=x)}return{props:Bn({$event_type:s.type,$ce_version:1},u?{}:{$elements:v},{$elements_chain:tbe(v)},(n=v[0])!=null&&n.$el_text?{$el_text:(r=v[0])==null?void 0:r.$el_text}:{},m&&s.type==="click"?{$external_click_url:m}:{},y)}}class lbe{constructor(e){this.C=!1,this.M=null,this.rageclicks=new q6,this.O=!1,this.instance=e,this.F=null}get A(){var e,n,r=Dn(this.instance.config.autocapture)?this.instance.config.autocapture:{};return r.url_allowlist=(e=r.url_allowlist)==null?void 0:e.map(s=>new RegExp(s)),r.url_ignorelist=(n=r.url_ignorelist)==null?void 0:n.map(s=>new RegExp(s)),r}D(){if(this.isBrowserSupported()){if(ve&&Be){var e=r=>{r=r||ve?.event;try{this.j(r)}catch(s){YD.error("Failed to capture event",s)}};if(Cn(Be,"submit",e,{capture:!0}),Cn(Be,"change",e,{capture:!0}),Cn(Be,"click",e,{capture:!0}),this.A.capture_copied_text){var n=r=>{r=r||ve?.event,this.j(r,pw)};Cn(Be,"copy",n,{capture:!0}),Cn(Be,"cut",n,{capture:!0})}}}else YD.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.C&&(this.D(),this.C=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.O=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[jD]:!!e.autocapture_opt_out}),this.M=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.F=e}getElementSelectors(e){var n,r=[];return(n=this.F)==null||n.forEach(s=>{var i=Be?.querySelectorAll(s);i?.forEach(o=>{e===o&&r.push(s)})}),r}get isEnabled(){var e,n,r=(e=this.instance.persistence)==null?void 0:e.props[jD],s=this.M;if(Ga(s)&&!vi(r)&&!this.instance.L())return!1;var i=(n=this.M)!==null&&n!==void 0?n:!!r;return!!this.instance.config.autocapture&&!i}j(e,n){if(n===void 0&&(n="$autocapture"),this.isEnabled){var r,s=D6(e);P6(s)&&(s=s.parentNode||null),n==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&function(v,y){if(!ve||BC(v))return!1;var x,_;if((x=vi(y)?!!y&&HD:(_=y?.css_selector_ignorelist)!==null&&_!==void 0?_:HD)===!1)return!1;var{targetElementList:E}=z6(v,!1);return!I6(E,x)}(s,this.instance.config.rageclick)&&this.j(e,"$rageclick");var i=n===pw;if(s&&Q0e(s,e,this.A,i,i?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:c}=obe(s,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.A.element_attribute_ignorelist,elementsChainAsString:this.O});if(c)return!1;var u=this.getElementSelectors(s);if(u&&u.length>0&&(o.$element_selectors=u),n===pw){var d,p=O6(ve==null||(d=ve.getSelection())==null?void 0:d.toString()),m=e.type||"clipboard";if(!p)return!1;o.$selected_content=p,o.$copy_type=m}return this.instance.capture(n,o),!0}}}isBrowserSupported(){return Xs(Be?.querySelectorAll)}}Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return Nr(t)&&isFinite(t)&&Math.floor(t)===t});var WD="0123456789abcdef";class Dv{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,r,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(s)||e<0||n<0||r<0||s<0||e>0xffffffffffff||n>4095||r>1073741823||s>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/Math.pow(2,8),i[5]=e,i[6]=112|n>>>8,i[7]=n,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new Dv(i)}toString(){for(var e="",n=0;n<this.bytes.length;n++)e=e+WD.charAt(this.bytes[n]>>>4)+WD.charAt(15&this.bytes[n]),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Dv(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;n<16;n++){var r=this.bytes[n]-e.bytes[n];if(r!==0)return Math.sign(r)}return 0}}class cbe{constructor(){this.N=0,this.U=0,this.q=new ube}generate(){var e=this.generateOrAbort();if(Oe(e)){this.N=0;var n=this.generateOrAbort();if(Oe(n))throw new Error("Could not generate UUID after timestamp reset");return n}return e}generateOrAbort(){var e=Date.now();if(e>this.N)this.N=e,this.B();else{if(!(e+1e4>this.N))return;this.U++,this.U>4398046511103&&(this.N++,this.B())}return Dv.fromFieldsV7(this.N,Math.trunc(this.U/Math.pow(2,30)),this.U&Math.pow(2,30)-1,this.q.nextUint32())}B(){this.U=1024*this.q.nextUint32()+(1023&this.q.nextUint32())}}var KD,H6=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<t.length;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};ve&&!Oe(ve.crypto)&&crypto.getRandomValues&&(H6=t=>crypto.getRandomValues(t));class ube{constructor(){this.H=new Uint32Array(8),this.W=1/0}nextUint32(){return this.W>=this.H.length&&(H6(this.H),this.W=0),this.H[this.W++]}}var jo=()=>dbe().toString(),dbe=()=>(KD||(KD=new cbe)).generate(),Ef="",fbe=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function hbe(t,e){if(e){var n=function(s,i){if(i===void 0&&(i=Be),Ef)return Ef;if(!i||["localhost","127.0.0.1"].includes(s))return"";for(var o=s.split("."),c=Math.min(o.length,8),u="dmn_chk_"+jo();!Ef&&c--;){var d=o.slice(c).join("."),p=u+"=1;domain=."+d+";path=/";i.cookie=p+";max-age=3",i.cookie.includes(u)&&(i.cookie=p+";max-age=0",Ef=d)}return Ef}(t);if(!n){var r=(s=>{var i=s.match(fbe);return i?i[0]:""})(t);r!==n&&Ve.info("Warning: cookie subdomain discovery mismatch",r,n),n=r}return n?"; domain=."+n:""}return""}var Yi={G:()=>!!Be,V:function(t){Ve.error("cookieStore error: "+t)},J:function(t){if(Be){try{for(var e=t+"=",n=Be.cookie.split(";").filter(i=>i.length),r=0;r<n.length;r++){for(var s=n[r];s.charAt(0)==" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return decodeURIComponent(s.substring(e.length,s.length))}}catch{}return null}},K:function(t){var e;try{e=JSON.parse(Yi.J(t))||{}}catch{}return e},Y:function(t,e,n,r,s){if(Be)try{var i="",o="",c=hbe(Be.location.hostname,r);if(n){var u=new Date;u.setTime(u.getTime()+24*n*60*60*1e3),i="; expires="+u.toUTCString()}s&&(o="; secure");var d=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+c+o;return d.length>3686.4&&Ve.warn("cookieStore warning: large cookie, len="+d.length),Be.cookie=d,d}catch{return}},X:function(t,e){if(Be!=null&&Be.cookie)try{Yi.Y(t,"",-1,e)}catch{return}}},gw=null,rr={G:function(){if(!Ga(gw))return gw;var t=!0;if(Oe(ve))t=!1;else try{var e="__mplssupport__";rr.Y(e,"xyz"),rr.J(e)!=='"xyz"'&&(t=!1),rr.X(e)}catch{t=!1}return t||Ve.error("localStorage unsupported; falling back to cookie store"),gw=t,t},V:function(t){Ve.error("localStorage error: "+t)},J:function(t){try{return ve?.localStorage.getItem(t)}catch(e){rr.V(e)}return null},K:function(t){try{return JSON.parse(rr.J(t))||{}}catch{}return null},Y:function(t,e){try{ve?.localStorage.setItem(t,JSON.stringify(e))}catch(n){rr.V(n)}},X:function(t){try{ve?.localStorage.removeItem(t)}catch(e){rr.V(e)}}},pbe=["distinct_id",Av,gu,jv,Nv],rg=Le({},rr,{K:function(t){try{var e={};try{e=Yi.K(t)||{}}catch{}var n=Bn(e,JSON.parse(rr.J(t)||"{}"));return rr.Y(t,n),n}catch{}return null},Y:function(t,e,n,r,s,i){try{rr.Y(t,e,void 0,void 0,i);var o={};pbe.forEach(c=>{e[c]&&(o[c]=e[c])}),Object.keys(o).length&&Yi.Y(t,o,n,r,s,i)}catch(c){rr.V(c)}},X:function(t,e){try{ve?.localStorage.removeItem(t),Yi.X(t,e)}catch(n){rr.V(n)}}}),sg={},mbe={G:function(){return!0},V:function(t){Ve.error("memoryStorage error: "+t)},J:function(t){return sg[t]||null},K:function(t){return sg[t]||null},Y:function(t,e){sg[t]=e},X:function(t){delete sg[t]}},bl=null,Sr={G:function(){if(!Ga(bl))return bl;if(bl=!0,Oe(ve))bl=!1;else try{var t="__support__";Sr.Y(t,"xyz"),Sr.J(t)!=='"xyz"'&&(bl=!1),Sr.X(t)}catch{bl=!1}return bl},V:function(t){Ve.error("sessionStorage error: ",t)},J:function(t){try{return ve?.sessionStorage.getItem(t)}catch(e){Sr.V(e)}return null},K:function(t){try{return JSON.parse(Sr.J(t))||null}catch{}return null},Y:function(t,e){try{ve?.sessionStorage.setItem(t,JSON.stringify(e))}catch(n){Sr.V(n)}},X:function(t){try{ve?.sessionStorage.removeItem(t)}catch(e){Sr.V(e)}}},wa=function(t){return t[t.PENDING=-1]="PENDING",t[t.DENIED=0]="DENIED",t[t.GRANTED=1]="GRANTED",t}({});class gbe{constructor(e){this._instance=e}get A(){return this._instance.config}get consent(){return this.Z()?wa.DENIED:this.tt}isOptedOut(){return this.A.cookieless_mode==="always"||this.consent===wa.DENIED||this.consent===wa.PENDING&&(this.A.opt_out_capturing_by_default||this.A.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===wa.DENIED}optInOut(e){this.it.Y(this.et,e?1:0,this.A.cookie_expiration,this.A.cross_subdomain_cookie,this.A.secure_cookie)}reset(){this.it.X(this.et,this.A.cross_subdomain_cookie)}get et(){var{token:e,opt_out_capturing_cookie_prefix:n,consent_persistence_name:r}=this._instance.config;return r||(n?n+e:"__ph_opt_in_out_"+e)}get tt(){var e=this.it.J(this.et);return dw(e)?wa.GRANTED:Ct(w0e,e)?wa.DENIED:wa.PENDING}get it(){if(!this.rt){var e=this.A.opt_out_capturing_persistence_type;this.rt=e==="localStorage"?rr:Yi;var n=e==="localStorage"?Yi:rr;n.J(this.et)&&(this.rt.J(this.et)||this.optInOut(dw(n.J(this.et))),n.X(this.et,this.A.cross_subdomain_cookie))}return this.rt}Z(){return!!this.A.respect_dnt&&!!A6([Cs?.doNotTrack,Cs?.msDoNotTrack,st.doNotTrack],e=>dw(e))}}var ig=or("[Dead Clicks]"),vbe=()=>!0,ybe=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(N6)),r=t.instance.config.capture_dead_clicks;return vi(r)?r:n};class G6{get lazyLoadedDeadClicksAutocapture(){return this.st}constructor(e,n,r){this.instance=e,this.isEnabled=n,this.onCapture=r,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[N6]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.nt(()=>{this.ot()})}nt(e){var n,r;(n=st.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture&&e(),(r=st.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",s=>{s?ig.error("failed to load script",s):e()})}ot(){var e;if(Be){if(!this.st&&(e=st.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=Dn(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this.st=st.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.st.start(Be),ig.info("starting...")}}else ig.error("`document` not found. Cannot start.")}stop(){this.st&&(this.st.stop(),this.st=void 0,ig.info("stopping..."))}}var kf=or("[ExceptionAutocapture]");class xbe{constructor(e){var n,r,s;this.lt=()=>{var i;if(ve&&this.isEnabled&&(i=st.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var o=st.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,c=st.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,u=st.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.ut&&this.A.capture_unhandled_errors&&(this.ut=o(this.captureException.bind(this))),!this.ht&&this.A.capture_unhandled_rejections&&(this.ht=c(this.captureException.bind(this))),!this.dt&&this.A.capture_console_errors&&(this.dt=u(this.captureException.bind(this)))}catch(d){kf.error("failed to start",d),this.vt()}}},this._instance=e,this.ct=!((n=this._instance.persistence)==null||!n.props[PD]),this.A=this.ft(),this.gt=new E6({refillRate:(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(s=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10,refillInterval:1e4,I:kf}),this.startIfEnabled()}ft(){var e=this._instance.config.capture_exceptions,n={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return Dn(e)?n=Le({},n,e):(Oe(e)?this.ct:e)&&(n=Le({},n,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),n}get isEnabled(){return this.A.capture_console_errors||this.A.capture_unhandled_errors||this.A.capture_unhandled_rejections}startIfEnabled(){this.isEnabled&&(kf.info("enabled"),this.nt(this.lt))}nt(e){var n,r;(n=st.__PosthogExtensions__)!=null&&n.errorWrappingFunctions&&e(),(r=st.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",s=>{if(s)return kf.error("failed to load script",s);e()})}vt(){var e,n,r;(e=this.ut)==null||e.call(this),this.ut=void 0,(n=this.ht)==null||n.call(this),this.ht=void 0,(r=this.dt)==null||r.call(this),this.dt=void 0}onRemoteConfig(e){var n=e.autocaptureExceptions;this.ct=!!n||!1,this.A=this.ft(),this._instance.persistence&&this._instance.persistence.register({[PD]:this.ct}),this.startIfEnabled()}captureException(e){var n,r,s=(n=e==null||(r=e.$exception_list)==null||(r=r[0])==null?void 0:r.type)!==null&&n!==void 0?n:"Exception";this.gt.consumeRateLimit(s)?kf.info("Skipping exception capture because of client rate limiting.",{exception:s}):this._instance.exceptions.sendExceptionEvent(e)}}function QD(t,e,n){try{if(!(e in t))return()=>{};var r=t[e],s=n(r);return Xs(s)&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__posthog_wrapped__:{enumerable:!1,value:!0}})),t[e]=s,()=>{t[e]=r}}catch{return()=>{}}}class bbe{constructor(e){var n;this._instance=e,this._t=(ve==null||(n=ve.location)==null?void 0:n.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(Ve.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.yt&&this.yt(),this.yt=void 0,Ve.info("History API monitoring stopped")}monitorHistoryChanges(){var e,n;if(ve&&ve.history){var r=this;(e=ve.history.pushState)!=null&&e.__posthog_wrapped__||QD(ve.history,"pushState",s=>function(i,o,c){s.call(this,i,o,c),r.bt("pushState")}),(n=ve.history.replaceState)!=null&&n.__posthog_wrapped__||QD(ve.history,"replaceState",s=>function(i,o,c){s.call(this,i,o,c),r.bt("replaceState")}),this.wt()}}bt(e){try{var n,r=ve==null||(n=ve.location)==null?void 0:n.pathname;if(!r)return;r!==this._t&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this._t=r}catch(s){Ve.error("Error capturing "+e+" pageview",s)}}wt(){if(!this.yt){var e=()=>{this.bt("popstate")};Cn(ve,"popstate",e),this.yt=()=>{ve&&ve.removeEventListener("popstate",e)}}}}function Iv(t){var e,n;return((e=JSON.stringify(t,(n=[],function(r,s){if(Dn(s)){for(;n.length>0&&n[n.length-1]!==this;)n.pop();return n.includes(s)?"[Circular]":(n.push(s),s)}return s})))==null?void 0:e.length)||0}function B1(t,e){if(e===void 0&&(e=66060288e-1),t.size>=e&&t.data.length>1){var n=Math.floor(t.data.length/2),r=t.data.slice(0,n),s=t.data.slice(n);return[B1({size:Iv(r),data:r,sessionId:t.sessionId,windowId:t.windowId}),B1({size:Iv(s),data:s,sessionId:t.sessionId,windowId:t.windowId})].flatMap(i=>i)}return[t]}var Sa=(t=>(t[t.DomContentLoaded=0]="DomContentLoaded",t[t.Load=1]="Load",t[t.FullSnapshot=2]="FullSnapshot",t[t.IncrementalSnapshot=3]="IncrementalSnapshot",t[t.Meta=4]="Meta",t[t.Custom=5]="Custom",t[t.Plugin=6]="Plugin",t))(Sa||{}),fi=(t=>(t[t.Mutation=0]="Mutation",t[t.MouseMove=1]="MouseMove",t[t.MouseInteraction=2]="MouseInteraction",t[t.Scroll=3]="Scroll",t[t.ViewportResize=4]="ViewportResize",t[t.Input=5]="Input",t[t.TouchMove=6]="TouchMove",t[t.MediaInteraction=7]="MediaInteraction",t[t.StyleSheetRule=8]="StyleSheetRule",t[t.CanvasMutation=9]="CanvasMutation",t[t.Font=10]="Font",t[t.Log=11]="Log",t[t.Drag=12]="Drag",t[t.StyleDeclaration=13]="StyleDeclaration",t[t.Selection=14]="Selection",t[t.AdoptedStyleSheet=15]="AdoptedStyleSheet",t[t.CustomElement=16]="CustomElement",t))(fi||{}),q1="[SessionRecording]",H1="redacted",ag={initiatorTypes:["audio","beacon","body","css","early-hint","embed","fetch","frame","iframe","icon","image","img","input","link","navigation","object","ping","script","track","video","xmlhttprequest"],maskRequestFn:t=>t,recordHeaders:!1,recordBody:!1,recordInitialRequests:!1,recordPerformance:!1,performanceEntryTypeToObserve:["first-input","navigation","paint","resource"],payloadSizeLimitBytes:1e6,payloadHostDenyList:[".lr-ingest.io",".ingest.sentry.io",".clarity.ms","analytics.google.com","bam.nr-data.net"]},_be=["authorization","x-forwarded-for","authorization","cookie","set-cookie","x-api-key","x-real-ip","remote-addr","forwarded","proxy-authorization","x-csrf-token","x-csrftoken","x-xsrf-token"],wbe=["password","secret","passwd","api_key","apikey","auth","credentials","mysql_pwd","privatekey","private_key","token"],Sbe=["/s/","/e/","/i/"];function XD(t,e,n,r){if(Ot(t))return t;var s=e?.["content-length"]||function(i){return new Blob([i]).size}(t);return In(s)&&(s=parseInt(s)),s>n?q1+" "+r+" body too large to record ("+s+" bytes)":t}function ZD(t,e){if(Ot(t))return t;var n=t;return Wu(n,!1)||(n=q1+" "+e+" body "+H1),tn(wbe,r=>{var s,i;(s=n)!=null&&s.length&&((i=n)==null?void 0:i.indexOf(r))!==-1&&(n=q1+" "+e+" body "+H1+" as might contain: "+r)}),n}var Ebe=(t,e)=>{var n,r,s,i={payloadSizeLimitBytes:ag.payloadSizeLimitBytes,performanceEntryTypeToObserve:[...ag.performanceEntryTypeToObserve],payloadHostDenyList:[...e.payloadHostDenyList||[],...ag.payloadHostDenyList]},o=t.session_recording.recordHeaders!==!1&&e.recordHeaders,c=t.session_recording.recordBody!==!1&&e.recordBody,u=t.capture_performance!==!1&&e.recordPerformance,d=(n=i,s=Math.min(1e6,(r=n.payloadSizeLimitBytes)!==null&&r!==void 0?r:1e6),v=>(v!=null&&v.requestBody&&(v.requestBody=XD(v.requestBody,v.requestHeaders,s,"Request")),v!=null&&v.responseBody&&(v.responseBody=XD(v.responseBody,v.responseHeaders,s,"Response")),v)),p=v=>{return d(((_,E)=>{var S,A=Ku(_.name),C=E.indexOf("http")===0?(S=Ku(E))==null?void 0:S.pathname:E;C==="/"&&(C="");var R=A?.pathname.replace(C||"","");if(!(A&&R&&Sbe.some(j=>R.indexOf(j)===0)))return _})((x=(y=v).requestHeaders,Ot(x)||tn(Object.keys(x??{}),_=>{_be.includes(_.toLowerCase())&&(x[_]=H1)}),y),t.api_host));var y,x},m=Xs(t.session_recording.maskNetworkRequestFn);return m&&Xs(t.session_recording.maskCapturedNetworkRequestFn)&&Ve.warn("Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored."),m&&(t.session_recording.maskCapturedNetworkRequestFn=v=>{var y=t.session_recording.maskNetworkRequestFn({url:v.name});return Le({},v,{name:y?.url})}),i.maskRequestFn=Xs(t.session_recording.maskCapturedNetworkRequestFn)?v=>{var y,x=p(v);return x&&(y=t.session_recording.maskCapturedNetworkRequestFn==null?void 0:t.session_recording.maskCapturedNetworkRequestFn(x))!==null&&y!==void 0?y:void 0}:v=>function(y){if(!Oe(y))return y.requestBody=ZD(y.requestBody,"Request"),y.responseBody=ZD(y.responseBody,"Response"),y}(p(v)),Le({},ag,i,{recordHeaders:o,recordBody:c,recordPerformance:u,recordInitialRequests:u})};class kbe{constructor(e,n){var r,s;n===void 0&&(n={}),this.St={},this.kt=i=>{if(!this.St[i]){var o,c;this.St[i]=!0;var u=this.$t(i);(o=(c=this.i).onBlockedNode)==null||o.call(c,i,u)}},this.xt=i=>{var o=this.$t(i);if(o?.nodeName!=="svg"&&o instanceof Element){var c=o.closest("svg");if(c)return[this._rrweb.mirror.getId(c),c]}return[i,o]},this.$t=i=>this._rrweb.mirror.getNode(i),this.Et=i=>{var o,c,u,d,p,m,v,y;return((o=(c=i.removes)==null?void 0:c.length)!==null&&o!==void 0?o:0)+((u=(d=i.attributes)==null?void 0:d.length)!==null&&u!==void 0?u:0)+((p=(m=i.texts)==null?void 0:m.length)!==null&&p!==void 0?p:0)+((v=(y=i.adds)==null?void 0:y.length)!==null&&v!==void 0?v:0)},this.throttleMutations=i=>{if(i.type!==3||i.data.source!==0)return i;var o=i.data,c=this.Et(o);o.attributes&&(o.attributes=o.attributes.filter(d=>{var[p]=this.xt(d.id);return!this.gt.consumeRateLimit(p)&&d}));var u=this.Et(o);return u!==0||c===u?i:void 0},this._rrweb=e,this.i=n,this.gt=new E6({bucketSize:(r=this.i.bucketSize)!==null&&r!==void 0?r:100,refillRate:(s=this.i.refillRate)!==null&&s!==void 0?s:10,refillInterval:1e3,P:this.kt,I:Ve})}}var Zs=Uint8Array,as=Uint16Array,Qu=Uint32Array,HC=new Zs([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),GC=new Zs([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),JD=new Zs([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Y6=function(t,e){for(var n=new as(31),r=0;r<31;++r)n[r]=e+=1<<t[r-1];var s=new Qu(n[30]);for(r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)s[i]=i-n[r]<<5|r;return[n,s]},W6=Y6(HC,2),Cbe=W6[0],G1=W6[1];Cbe[28]=258,G1[258]=28;for(var eI=Y6(GC,0)[1],K6=new as(32768),fn=0;fn<32768;++fn){var _l=(43690&fn)>>>1|(21845&fn)<<1;_l=(61680&(_l=(52428&_l)>>>2|(13107&_l)<<2))>>>4|(3855&_l)<<4,K6[fn]=((65280&_l)>>>8|(255&_l)<<8)>>>1}var mh=function(t,e,n){for(var r=t.length,s=0,i=new as(e);s<r;++s)++i[t[s]-1];var o,c=new as(e);for(s=0;s<e;++s)c[s]=c[s-1]+i[s-1]<<1;for(o=new as(r),s=0;s<r;++s)o[s]=K6[c[t[s]-1]++]>>>15-t[s];return o},Ql=new Zs(288);for(fn=0;fn<144;++fn)Ql[fn]=8;for(fn=144;fn<256;++fn)Ql[fn]=9;for(fn=256;fn<280;++fn)Ql[fn]=7;for(fn=280;fn<288;++fn)Ql[fn]=8;var Lv=new Zs(32);for(fn=0;fn<32;++fn)Lv[fn]=5;var Tbe=mh(Ql,9),Abe=mh(Lv,5),Q6=function(t){return(t/8>>0)+(7&t&&1)},X6=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var r=new(t instanceof as?as:t instanceof Qu?Qu:Zs)(n-e);return r.set(t.subarray(e,n)),r},xa=function(t,e,n){n<<=7&e;var r=e/8>>0;t[r]|=n,t[r+1]|=n>>>8},Cf=function(t,e,n){n<<=7&e;var r=e/8>>0;t[r]|=n,t[r+1]|=n>>>8,t[r+2]|=n>>>16},vw=function(t,e){for(var n=[],r=0;r<t.length;++r)t[r]&&n.push({s:r,f:t[r]});var s=n.length,i=n.slice();if(!s)return[new Zs(0),0];if(s==1){var o=new Zs(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort(function(j,T){return j.f-T.f}),n.push({s:-1,f:25001});var c=n[0],u=n[1],d=0,p=1,m=2;for(n[0]={s:-1,f:c.f+u.f,l:c,r:u};p!=s-1;)c=n[n[d].f<n[m].f?d++:m++],u=n[d!=p&&n[d].f<n[m].f?d++:m++],n[p++]={s:-1,f:c.f+u.f,l:c,r:u};var v=i[0].s;for(r=1;r<s;++r)i[r].s>v&&(v=i[r].s);var y=new as(v+1),x=Y1(n[p-1],y,0);if(x>e){r=0;var _=0,E=x-e,S=1<<E;for(i.sort(function(j,T){return y[T.s]-y[j.s]||j.f-T.f});r<s;++r){var A=i[r].s;if(!(y[A]>e))break;_+=S-(1<<x-y[A]),y[A]=e}for(_>>>=E;_>0;){var C=i[r].s;y[C]<e?_-=1<<e-y[C]++-1:++r}for(;r>=0&&_;--r){var R=i[r].s;y[R]==e&&(--y[R],++_)}x=e}return[new Zs(y),x]},Y1=function(t,e,n){return t.s==-1?Math.max(Y1(t.l,e,n+1),Y1(t.r,e,n+1)):e[t.s]=n},tI=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new as(++e),r=0,s=t[0],i=1,o=function(u){n[r++]=u},c=1;c<=e;++c)if(t[c]==s&&c!=e)++i;else{if(!s&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(s),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(s);i=1,s=t[c]}return[n.subarray(0,r),e]},Tf=function(t,e){for(var n=0,r=0;r<e.length;++r)n+=t[r]*e[r];return n},W1=function(t,e,n){var r=n.length,s=Q6(e+2);t[s]=255&r,t[s+1]=r>>>8,t[s+2]=255^t[s],t[s+3]=255^t[s+1];for(var i=0;i<r;++i)t[s+i+4]=n[i];return 8*(s+4+r)},nI=function(t,e,n,r,s,i,o,c,u,d,p){xa(e,p++,n),++s[256];for(var m=vw(s,15),v=m[0],y=m[1],x=vw(i,15),_=x[0],E=x[1],S=tI(v),A=S[0],C=S[1],R=tI(_),j=R[0],T=R[1],P=new as(19),N=0;N<A.length;++N)P[31&A[N]]++;for(N=0;N<j.length;++N)P[31&j[N]]++;for(var L=vw(P,7),O=L[0],z=L[1],U=19;U>4&&!O[JD[U-1]];--U);var K,Y,Q,V,G=d+5<<3,H=Tf(s,Ql)+Tf(i,Lv)+o,ee=Tf(s,v)+Tf(i,_)+o+14+3*U+Tf(P,O)+(2*P[16]+3*P[17]+7*P[18]);if(G<=H&&G<=ee)return W1(e,p,t.subarray(u,u+d));if(xa(e,p,1+(ee<H)),p+=2,ee<H){K=mh(v,y),Y=v,Q=mh(_,E),V=_;var M=mh(O,z);for(xa(e,p,C-257),xa(e,p+5,T-1),xa(e,p+10,U-4),p+=14,N=0;N<U;++N)xa(e,p+3*N,O[JD[N]]);p+=3*U;for(var ie=[A,j],fe=0;fe<2;++fe){var D=ie[fe];for(N=0;N<D.length;++N){var X=31&D[N];xa(e,p,M[X]),p+=O[X],X>15&&(xa(e,p,D[N]>>>5&127),p+=D[N]>>>12)}}}else K=Tbe,Y=Ql,Q=Abe,V=Lv;for(N=0;N<c;++N)if(r[N]>255){X=r[N]>>>18&31,Cf(e,p,K[X+257]),p+=Y[X+257],X>7&&(xa(e,p,r[N]>>>23&31),p+=HC[X]);var ue=31&r[N];Cf(e,p,Q[ue]),p+=V[ue],ue>3&&(Cf(e,p,r[N]>>>5&8191),p+=GC[ue])}else Cf(e,p,K[r[N]]),p+=Y[r[N]];return Cf(e,p,K[256]),p+Y[256]},Rbe=new Qu([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Nbe=function(){for(var t=new Qu(256),e=0;e<256;++e){for(var n=e,r=9;--r;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t}(),jbe=function(){var t=4294967295;return{p:function(e){for(var n=t,r=0;r<e.length;++r)n=Nbe[255&n^e[r]]^n>>>8;t=n},d:function(){return 4294967295^t}}},Pbe=function(t,e,n,r,s){return function(i,o,c,u,d,p){var m=i.length,v=new Zs(u+m+5*(1+Math.floor(m/7e3))+d),y=v.subarray(u,v.length-d),x=0;if(!o||m<8)for(var _=0;_<=m;_+=65535){var E=_+65535;E<m?x=W1(y,x,i.subarray(_,E)):(y[_]=p,x=W1(y,x,i.subarray(_,m)))}else{for(var S=Rbe[o-1],A=S>>>13,C=8191&S,R=(1<<c)-1,j=new as(32768),T=new as(R+1),P=Math.ceil(c/3),N=2*P,L=function(Pe){return(i[Pe]^i[Pe+1]<<P^i[Pe+2]<<N)&R},O=new Qu(25e3),z=new as(288),U=new as(32),K=0,Y=0,Q=(_=0,0),V=0,G=0;_<m;++_){var H=L(_),ee=32767&_,M=T[H];if(j[ee]=M,T[H]=ee,V<=_){var ie=m-_;if((K>7e3||Q>24576)&&ie>423){x=nI(i,y,0,O,z,U,Y,Q,G,_-G,x),Q=K=Y=0,G=_;for(var fe=0;fe<286;++fe)z[fe]=0;for(fe=0;fe<30;++fe)U[fe]=0}var D=2,X=0,ue=C,B=ee-M&32767;if(ie>2&&H==L(_-B))for(var $=Math.min(A,ie)-1,q=Math.min(32767,_),ne=Math.min(258,ie);B<=q&&--ue&&ee!=M;){if(i[_+D]==i[_+D-B]){for(var J=0;J<ne&&i[_+J]==i[_+J-B];++J);if(J>D){if(D=J,X=B,J>$)break;var ae=Math.min(B,J-2),xe=0;for(fe=0;fe<ae;++fe){var _e=_-B+fe+32768&32767,Ce=_e-j[_e]+32768&32767;Ce>xe&&(xe=Ce,M=_e)}}}B+=(ee=M)-(M=j[ee])+32768&32767}if(X){O[Q++]=268435456|G1[D]<<18|eI[X];var $e=31&G1[D],De=31&eI[X];Y+=HC[$e]+GC[De],++z[257+$e],++U[De],V=_+D,++K}else O[Q++]=i[_],++z[i[_]]}}x=nI(i,y,p,O,z,U,Y,Q,G,_-G,x)}return X6(v,0,u+Q6(x)+d)}(t,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):12+e.mem,n,r,!0)},K1=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8},Mbe=function(t,e){var n=e.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=e.level<2?4:e.level==9?2:0,t[9]=3,e.mtime!=0&&K1(t,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),n){t[3]=8;for(var r=0;r<=n.length;++r)t[r+10]=n.charCodeAt(r)}},Obe=function(t){return 10+(t.filename&&t.filename.length+1||0)};function Z6(t,e){e===void 0&&(e={});var n=jbe(),r=t.length;n.p(t);var s=Pbe(t,e,Obe(e),8),i=s.length;return Mbe(s,e),K1(s,i-8,n.d()),K1(s,i-4,r),s}function J6(t,e){var n=t.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(t);for(var r=new Zs(t.length+(t.length>>>1)),s=0,i=function(d){r[s++]=d},o=0;o<n;++o){if(s+5>r.length){var c=new Zs(s+8+(n-o<<1));c.set(r),r=c}var u=t.charCodeAt(o);u<128||e?i(u):u<2048?(i(192|u>>>6),i(128|63&u)):u>55295&&u<57344?(i(240|(u=65536+(1047552&u)|1023&t.charCodeAt(++o))>>>18),i(128|u>>>12&63),i(128|u>>>6&63),i(128|63&u)):(i(224|u>>>12),i(128|u>>>6&63),i(128|63&u))}return X6(r,0,s)}function Dbe(t,e){return function(n){for(var r=0,s=0;s<n.length;s++)r=(r<<5)-r+n.charCodeAt(s),r|=0;return Math.abs(r)}(t)%100<Ts(100*e,0,100,Ve)}var Vo="disabled",YC="sampled",zv="active",Xl="buffering",WC="paused",KC="trigger",Wi=KC+"_activated",Or=KC+"_pending",Xi=KC+"_"+Vo;function rI(t,e){return e.some(n=>n.matching==="regex"&&new RegExp(n.url).test(t))}class e9{constructor(e){this.Pt=e}triggerStatus(e){var n=this.Pt.map(r=>r.triggerStatus(e));return n.includes(Wi)?Wi:n.includes(Or)?Or:Xi}stop(){this.Pt.forEach(e=>e.stop())}}class t9{constructor(e){this.Pt=e}triggerStatus(e){var n=new Set;for(var r of this.Pt)n.add(r.triggerStatus(e));switch(n.delete(Xi),n.size){case 0:return Xi;case 1:return Array.from(n)[0];default:return Or}}stop(){this.Pt.forEach(e=>e.stop())}}class Ibe{triggerStatus(){return Or}stop(){}}var $v=t=>"sessionRecording"in t;class Lbe{constructor(e){this.It=[],this.Rt=[],this.urlBlocked=!1,this._instance=e}onConfig(e){var n,r;this.It=($v(e)?(n=e.sessionRecording)==null?void 0:n.urlTriggers:e?.urlTriggers)||[],this.Rt=($v(e)?(r=e.sessionRecording)==null?void 0:r.urlBlocklist:e?.urlBlocklist)||[]}Tt(e){var n;return this.It.length===0?Xi:((n=this._instance)==null?void 0:n.get_property(O1))===e?Wi:Or}triggerStatus(e){var n=this.Tt(e),r=n===Wi?Wi:n===Or?Or:Xi;return this._instance.register_for_session({$sdk_debug_replay_url_trigger_status:r}),r}checkUrlTriggerConditions(e,n,r){if(ve!==void 0&&ve.location.href){var s=ve.location.href,i=this.urlBlocked,o=rI(s,this.Rt);i&&o||(o&&!i?e():!o&&i&&n(),rI(s,this.It)&&r("url"))}}stop(){}}class zbe{constructor(e){this.linkedFlag=null,this.linkedFlagSeen=!1,this.Ct=()=>{},this._instance=e}triggerStatus(){var e=Or;return Ot(this.linkedFlag)&&(e=Xi),this.linkedFlagSeen&&(e=Wi),this._instance.register_for_session({$sdk_debug_replay_linked_flag_trigger_status:e}),e}onConfig(e,n){var r;if(this.linkedFlag=($v(e)?(r=e.sessionRecording)==null?void 0:r.linkedFlag:e?.linkedFlag)||null,!Ot(this.linkedFlag)&&!this.linkedFlagSeen){var s=In(this.linkedFlag)?this.linkedFlag:this.linkedFlag.flag,i=In(this.linkedFlag)?null:this.linkedFlag.variant;this.Ct=this._instance.onFeatureFlags((o,c)=>{var u=!1;if(Dn(c)&&s in c){var d=c[s];u=vi(d)?d===!0:i?d===i:!!d}this.linkedFlagSeen=u,u&&n(s,i)})}}stop(){this.Ct()}}class $be{constructor(e){this.Mt=[],this._instance=e}onConfig(e){var n;this.Mt=($v(e)?(n=e.sessionRecording)==null?void 0:n.eventTriggers:e?.eventTriggers)||[]}Ot(e){var n;return this.Mt.length===0?Xi:((n=this._instance)==null?void 0:n.get_property(D1))===e?Wi:Or}triggerStatus(e){var n=this.Ot(e),r=n===Wi?Wi:n===Or?Or:Xi;return this._instance.register_for_session({$sdk_debug_replay_event_trigger_status:r}),r}stop(){}}function Fbe(t){return t.isRecordingEnabled?Xl:Vo}function Ube(t){if(!t.receivedFlags)return Xl;if(!t.isRecordingEnabled)return Vo;if(t.urlTriggerMatching.urlBlocked)return WC;var e=t.isSampled===!0,n=new e9([t.eventTriggerMatching,t.urlTriggerMatching,t.linkedFlagMatching]).triggerStatus(t.sessionId);return e?YC:n===Wi?zv:n===Or?Xl:t.isSampled===!1?Vo:zv}function Vbe(t){if(!t.receivedFlags)return Xl;if(!t.isRecordingEnabled)return Vo;if(t.urlTriggerMatching.urlBlocked)return WC;var e=new t9([t.eventTriggerMatching,t.urlTriggerMatching,t.linkedFlagMatching]).triggerStatus(t.sessionId),n=e!==Xi,r=vi(t.isSampled);return n&&e===Or?Xl:n&&e===Xi||r&&!t.isSampled?Vo:t.isSampled===!0?YC:zv}var Wf="[SessionRecording]",fr=or(Wf);function og(){var t;return st==null||(t=st.__PosthogExtensions__)==null||(t=t.rrweb)==null?void 0:t.record}var Bbe=3e5,qbe=[fi.MouseMove,fi.MouseInteraction,fi.Scroll,fi.ViewportResize,fi.Input,fi.TouchMove,fi.MediaInteraction,fi.Drag],sI=t=>({rrwebMethod:t,enqueuedAt:Date.now(),attempt:1});function wl(t){return function(e,n){for(var r="",s=0;s<e.length;){var i=e[s++];r+=String.fromCharCode(i)}return r}(Z6(J6(JSON.stringify(t))))}function iI(t){return t.type===Sa.Custom&&t.data.tag==="sessionIdle"}class aI{get sessionId(){return this.Ft}get At(){return this._instance.config.session_recording.session_idle_threshold_ms||3e5}get started(){return this.Dt}get jt(){if(!this._instance.sessionManager)throw new Error(Wf+" must be started with a valid sessionManager.");return this._instance.sessionManager}get Lt(){var e,n;return this.Nt.triggerStatus(this.sessionId)===Or?6e4:(e=(n=this._instance.config.session_recording)==null?void 0:n.full_snapshot_interval_millis)!==null&&e!==void 0?e:Bbe}get Ut(){var e=this._instance.get_property(gu);return vi(e)?e:null}get zt(){var e,n,r=(e=this.H)==null?void 0:e.data[((n=this.H)==null?void 0:n.data.length)-1],{sessionStartTimestamp:s}=this.jt.checkAndGetSessionAndWindowId(!0);return r?r.timestamp-s:null}get qt(){var e=!!this._instance.get_property(M1),n=!this._instance.config.disable_session_recording;return ve&&e&&n}get Bt(){var e=!!this._instance.get_property(ID),n=this._instance.config.enable_recording_console_log;return n??e}get Ht(){var e,n,r,s,i,o,c=this._instance.config.session_recording.captureCanvas,u=this._instance.get_property($D),d=(e=(n=c?.recordCanvas)!==null&&n!==void 0?n:u?.enabled)!==null&&e!==void 0&&e,p=(r=(s=c?.canvasFps)!==null&&s!==void 0?s:u?.fps)!==null&&r!==void 0?r:4,m=(i=(o=c?.canvasQuality)!==null&&o!==void 0?o:u?.quality)!==null&&i!==void 0?i:.4;if(typeof m=="string"){var v=parseFloat(m);m=isNaN(v)?.4:v}return{enabled:d,fps:Ts(p,0,12,fr.createLogger("canvas recording fps"),4),quality:Ts(m,0,1,fr.createLogger("canvas recording quality"),.4)}}get Wt(){var e,n,r=this._instance.get_property(LD),s={recordHeaders:(e=this._instance.config.session_recording)==null?void 0:e.recordHeaders,recordBody:(n=this._instance.config.session_recording)==null?void 0:n.recordBody},i=s?.recordHeaders||r?.recordHeaders,o=s?.recordBody||r?.recordBody,c=Dn(this._instance.config.capture_performance)?this._instance.config.capture_performance.network_timing:this._instance.config.capture_performance,u=!!(vi(c)?c:r?.capturePerformance);return i||o||u?{recordHeaders:i,recordBody:o,recordPerformance:u}:void 0}get Gt(){var e,n,r,s,i,o,c=this._instance.get_property(zD),u={maskAllInputs:(e=this._instance.config.session_recording)==null?void 0:e.maskAllInputs,maskTextSelector:(n=this._instance.config.session_recording)==null?void 0:n.maskTextSelector,blockSelector:(r=this._instance.config.session_recording)==null?void 0:r.blockSelector},d=(s=u?.maskAllInputs)!==null&&s!==void 0?s:c?.maskAllInputs,p=(i=u?.maskTextSelector)!==null&&i!==void 0?i:c?.maskTextSelector,m=(o=u?.blockSelector)!==null&&o!==void 0?o:c?.blockSelector;return Oe(d)&&Oe(p)&&Oe(m)?void 0:{maskAllInputs:d==null||d,maskTextSelector:p,blockSelector:m}}get Vt(){var e=this._instance.get_property(FD);return Nr(e)?e:null}get Jt(){var e=this._instance.get_property(UD);return Nr(e)?e:null}get status(){return this.Kt?this.Yt({receivedFlags:this.Kt,isRecordingEnabled:this.qt,isSampled:this.Ut,urlTriggerMatching:this.Xt,eventTriggerMatching:this.Qt,linkedFlagMatching:this.Zt,sessionId:this.sessionId}):Xl}constructor(e){if(this.Yt=Fbe,this.Kt=!1,this.ti=[],this.ii="unknown",this.ei=Date.now(),this.Nt=new Ibe,this.ri=void 0,this.si=void 0,this.ni=void 0,this.oi=void 0,this.ai=void 0,this._forceAllowLocalhostNetworkCapture=!1,this.li=()=>{this.ui()},this.hi=()=>{this.tryAddCustomEvent("browser offline",{})},this.di=()=>{this.tryAddCustomEvent("browser online",{})},this.vi=()=>{if(Be!=null&&Be.visibilityState){var s="window "+Be.visibilityState;this.tryAddCustomEvent(s,{})}},this._instance=e,this.Dt=!1,this.ci="/s/",this.fi=void 0,this.Kt=!1,!this._instance.sessionManager)throw fr.error("started without valid sessionManager"),new Error(Wf+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Wf+' cannot be used with cookieless_mode="always"');this.Zt=new zbe(this._instance),this.Xt=new Lbe(this._instance),this.Qt=new $be(this._instance);var{sessionId:n,windowId:r}=this.jt.checkAndGetSessionAndWindowId();this.Ft=n,this.pi=r,this.H=this.gi(),this.At>=this.jt.sessionTimeoutMs&&fr.warn("session_idle_threshold_ms ("+this.At+") is greater than the session timeout ("+this.jt.sessionTimeoutMs+"). Session will never be detected as idle")}startIfEnabledOrStop(e){this.qt?(this.mi(e),Cn(ve,"beforeunload",this.li),Cn(ve,"offline",this.hi),Cn(ve,"online",this.di),Cn(ve,"visibilitychange",this.vi),this.yi(),this.bi(),Ot(this.ri)&&(this.ri=this._instance.on("eventCaptured",n=>{try{if(n.event==="$pageview"){var r=n!=null&&n.properties.$current_url?this.wi(n?.properties.$current_url):"";if(!r)return;this.tryAddCustomEvent("$pageview",{href:r})}}catch(s){fr.error("Could not add $pageview to rrweb session",s)}})),this.si||(this.si=this.jt.onSessionId((n,r,s)=>{var i,o;s&&(this.tryAddCustomEvent("$session_id_change",{sessionId:n,windowId:r,changeReason:s}),(i=this._instance)==null||(i=i.persistence)==null||i.unregister(D1),(o=this._instance)==null||(o=o.persistence)==null||o.unregister(O1))}))):this.stopRecording()}stopRecording(){var e,n,r,s;this.Dt&&this.fi&&(this.fi(),this.fi=void 0,this.Dt=!1,ve?.removeEventListener("beforeunload",this.li),ve?.removeEventListener("offline",this.hi),ve?.removeEventListener("online",this.di),ve?.removeEventListener("visibilitychange",this.vi),this.gi(),clearInterval(this.Si),(e=this.ri)==null||e.call(this),this.ri=void 0,(n=this.ai)==null||n.call(this),this.ai=void 0,(r=this.si)==null||r.call(this),this.si=void 0,(s=this.oi)==null||s.call(this),this.oi=void 0,this.Qt.stop(),this.Xt.stop(),this.Zt.stop(),fr.info("stopped"))}ki(){var e;(e=this._instance.persistence)==null||e.unregister(gu)}$i(e){var n,r=this.Ft!==e,s=this.Vt;if(Nr(s)){var i=this.Ut,o=r||!vi(i),c=o?Dbe(e,s):i;o&&(c?this.xi(YC):fr.warn("Sample rate ("+s+") has determined that this sessionId ("+e+") will not be sent to the server."),this.tryAddCustomEvent("samplingDecisionMade",{sampleRate:s,isSampled:c})),(n=this._instance.persistence)==null||n.register({[gu]:c})}else this.ki()}onRemoteConfig(e){var n,r,s,i;this.tryAddCustomEvent("$remote_config_received",e),this.Ei(e),(n=e.sessionRecording)!=null&&n.endpoint&&(this.ci=(i=e.sessionRecording)==null?void 0:i.endpoint),this.yi(),((r=e.sessionRecording)==null?void 0:r.triggerMatchType)==="any"?(this.Yt=Ube,this.Nt=new e9([this.Qt,this.Xt])):(this.Yt=Vbe,this.Nt=new t9([this.Qt,this.Xt])),this._instance.register_for_session({$sdk_debug_replay_remote_trigger_matching_config:(s=e.sessionRecording)==null?void 0:s.triggerMatchType}),this.Xt.onConfig(e),this.Qt.onConfig(e),this.Zt.onConfig(e,(o,c)=>{this.xi("linked_flag_matched",{flag:o,variant:c})}),this.Kt=!0,this.startIfEnabledOrStop()}yi(){Nr(this.Vt)&&Ot(this.oi)&&(this.oi=this.jt.onSessionId(e=>{this.$i(e)}))}Ei(e){if(this._instance.persistence){var n,r=this._instance.persistence,s=()=>{var i,o,c,u,d,p,m,v,y,x=(i=e.sessionRecording)==null?void 0:i.sampleRate,_=Ot(x)?null:parseFloat(x);Ot(_)&&this.ki();var E=(o=e.sessionRecording)==null?void 0:o.minimumDurationMilliseconds;r.register({[M1]:!!e.sessionRecording,[ID]:(c=e.sessionRecording)==null?void 0:c.consoleLogRecordingEnabled,[LD]:Le({capturePerformance:e.capturePerformance},(u=e.sessionRecording)==null?void 0:u.networkPayloadCapture),[zD]:(d=e.sessionRecording)==null?void 0:d.masking,[$D]:{enabled:(p=e.sessionRecording)==null?void 0:p.recordCanvas,fps:(m=e.sessionRecording)==null?void 0:m.canvasFps,quality:(v=e.sessionRecording)==null?void 0:v.canvasQuality},[FD]:_,[UD]:Oe(E)?null:E,[VD]:(y=e.sessionRecording)==null?void 0:y.scriptConfig})};s(),(n=this.ni)==null||n.call(this),this.ni=this.jt.onSessionId(s)}}log(e,n){var r;n===void 0&&(n="log"),(r=this._instance.sessionRecording)==null||r.onRRwebEmit({type:6,data:{plugin:"rrweb/console@1",payload:{level:n,trace:[],payload:[JSON.stringify(e)]}},timestamp:Date.now()})}mi(e){if(!Oe(Object.assign)&&!Oe(Array.from)&&!(this.Dt||this._instance.config.disable_session_recording||this._instance.consent.isOptedOut())){var n;this.Dt=!0,this.jt.checkAndGetSessionAndWindowId(),og()?this.Pi():(n=st.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.Ii,r=>{if(r)return fr.error("could not load recorder",r);this.Pi()}),fr.info("starting"),this.status===zv&&this.xi(e||"recording_initialized")}}get Ii(){var e;return((e=this._instance)==null||(e=e.persistence)==null||(e=e.get_property(VD))==null?void 0:e.script)||"recorder"}Ri(e){var n;return e.type===3&&qbe.indexOf((n=e.data)==null?void 0:n.source)!==-1}Ti(e){var n=this.Ri(e);n||this.ii||e.timestamp-this.ei>this.At&&(this.ii=!0,clearInterval(this.Si),this.tryAddCustomEvent("sessionIdle",{eventTimestamp:e.timestamp,lastActivityTimestamp:this.ei,threshold:this.At,bufferLength:this.H.data.length,bufferSize:this.H.size}),this.ui());var r=!1;if(n&&(this.ei=e.timestamp,this.ii)){var s=this.ii==="unknown";this.ii=!1,s||(this.tryAddCustomEvent("sessionNoLongerIdle",{reason:"user activity",type:e.type}),r=!0)}if(!this.ii){var{windowId:i,sessionId:o}=this.jt.checkAndGetSessionAndWindowId(!n,e.timestamp),c=this.Ft!==o,u=this.pi!==i;this.pi=i,this.Ft=o,c||u?(this.stopRecording(),this.startIfEnabledOrStop("session_id_changed")):r&&this.Ci()}}Mi(e){try{return e.rrwebMethod(),!0}catch(n){return this.ti.length<10?this.ti.push({enqueuedAt:e.enqueuedAt||Date.now(),attempt:e.attempt++,rrwebMethod:e.rrwebMethod}):fr.warn("could not emit queued rrweb event.",n,e),!1}}tryAddCustomEvent(e,n){return this.Mi(sI(()=>og().addCustomEvent(e,n)))}Oi(){return this.Mi(sI(()=>og().takeFullSnapshot()))}Pi(){var e,n,r,s,i={blockClass:"ph-no-capture",blockSelector:void 0,ignoreClass:"ph-ignore-input",maskTextClass:"ph-mask",maskTextSelector:void 0,maskTextFn:void 0,maskAllInputs:!0,maskInputOptions:{password:!0},maskInputFn:void 0,slimDOMOptions:{},collectFonts:!1,inlineStylesheet:!0,recordCrossOriginIframes:!1},o=this._instance.config.session_recording;for(var[c,u]of Object.entries(o||{}))c in i&&(c==="maskInputOptions"?i.maskInputOptions=Le({password:!0},u):i[c]=u);this.Ht&&this.Ht.enabled&&(i.recordCanvas=!0,i.sampling={canvas:this.Ht.fps},i.dataURLOptions={type:"image/webp",quality:this.Ht.quality}),this.Gt&&(i.maskAllInputs=(n=this.Gt.maskAllInputs)===null||n===void 0||n,i.maskTextSelector=(r=this.Gt.maskTextSelector)!==null&&r!==void 0?r:void 0,i.blockSelector=(s=this.Gt.blockSelector)!==null&&s!==void 0?s:void 0);var d=og();if(d){this.Fi=(e=this.Fi)!==null&&e!==void 0?e:new kbe(d,{refillRate:this._instance.config.session_recording.__mutationThrottlerRefillRate,bucketSize:this._instance.config.session_recording.__mutationThrottlerBucketSize,onBlockedNode:(m,v)=>{var y="Too many mutations on node '"+m+"'. Rate limiting. This could be due to SVG animations or something similar";fr.info(y,{node:v}),this.log(Wf+" "+y,"warn")}});var p=this.Ai();this.fi=d(Le({emit:m=>{this.onRRwebEmit(m)},plugins:p},i)),this.ei=Date.now(),this.ii=vi(this.ii)?this.ii:"unknown",this.tryAddCustomEvent("$session_options",{sessionRecordingOptions:i,activePlugins:p.map(m=>m?.name)}),this.tryAddCustomEvent("$posthog_config",{config:this._instance.config})}else fr.error("onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.")}Ci(){if(this.Si&&clearInterval(this.Si),this.ii!==!0){var e=this.Lt;e&&(this.Si=setInterval(()=>{this.Oi()},e))}}Ai(){var e,n,r=[],s=(e=st.__PosthogExtensions__)==null||(e=e.rrwebPlugins)==null?void 0:e.getRecordConsolePlugin;s&&this.Bt&&r.push(s());var i=(n=st.__PosthogExtensions__)==null||(n=n.rrwebPlugins)==null?void 0:n.getRecordNetworkPlugin;return this.Wt&&Xs(i)&&(!rbe.includes(location.hostname)||this._forceAllowLocalhostNetworkCapture?r.push(i(Ebe(this._instance.config,this.Wt))):fr.info("NetworkCapture not started because we are on localhost.")),r}onRRwebEmit(e){var n;if(this.Di(),e&&Dn(e)){if(e.type===Sa.Meta){var r=this.wi(e.data.href);if(this.ji=r,!r)return;e.data.href=r}else this.Li();if(this.Xt.checkUrlTriggerConditions(()=>this.Ni(),()=>this.Ui(),v=>this.zi(v)),!this.Xt.urlBlocked||(s=e).type===Sa.Custom&&s.data.tag==="recording paused"){var s;e.type===Sa.FullSnapshot&&this.Ci(),e.type===Sa.FullSnapshot&&this.Kt&&this.Nt.triggerStatus(this.sessionId)===Or&&this.gi();var i=this.Fi?this.Fi.throttleMutations(e):e;if(i){var o=function(v){var y=v;if(y&&Dn(y)&&y.type===6&&Dn(y.data)&&y.data.plugin==="rrweb/console@1"){y.data.payload.payload.length>10&&(y.data.payload.payload=y.data.payload.payload.slice(0,10),y.data.payload.payload.push("...[truncated]"));for(var x=[],_=0;_<y.data.payload.payload.length;_++)y.data.payload.payload[_]&&y.data.payload.payload[_].length>2e3?x.push(y.data.payload.payload[_].slice(0,2e3)+"...[truncated]"):x.push(y.data.payload.payload[_]);return y.data.payload.payload=x,v}return v}(i);if(this.Ti(o),this.ii!==!0||iI(o)){if(iI(o)){var c=o.data.payload;if(c){var u=c.lastActivityTimestamp,d=c.threshold;o.timestamp=u+d}}var p=(n=this._instance.config.session_recording.compress_events)===null||n===void 0||n?function(v){if(Iv(v)<1024)return v;try{if(v.type===Sa.FullSnapshot)return Le({},v,{data:wl(v.data),cv:"2024-10"});if(v.type===Sa.IncrementalSnapshot&&v.data.source===fi.Mutation)return Le({},v,{cv:"2024-10",data:Le({},v.data,{texts:wl(v.data.texts),attributes:wl(v.data.attributes),removes:wl(v.data.removes),adds:wl(v.data.adds)})});if(v.type===Sa.IncrementalSnapshot&&v.data.source===fi.StyleSheetRule)return Le({},v,{cv:"2024-10",data:Le({},v.data,{adds:v.data.adds?wl(v.data.adds):void 0,removes:v.data.removes?wl(v.data.removes):void 0})})}catch(y){fr.error("could not compress event - will use uncompressed event",y)}return v}(o):o,m={$snapshot_bytes:Iv(p),$snapshot_data:p,$session_id:this.Ft,$window_id:this.pi};this.status!==Vo?this.qi(m):this.gi()}}}}}Li(){if(!this._instance.config.capture_pageview&&ve){var e=this.wi(ve.location.href);this.ji!==e&&(this.tryAddCustomEvent("$url_changed",{href:e}),this.ji=e)}}Di(){if(this.ti.length){var e=[...this.ti];this.ti=[],e.forEach(n=>{Date.now()-n.enqueuedAt<=2e3&&this.Mi(n)})}}wi(e){var n=this._instance.config.session_recording;if(n.maskNetworkRequestFn){var r,s={url:e};return(r=s=n.maskNetworkRequestFn(s))==null?void 0:r.url}return e}gi(){return this.H={size:0,data:[],sessionId:this.Ft,windowId:this.pi},this.H}ui(){this.Bi&&(clearTimeout(this.Bi),this.Bi=void 0);var e=this.Jt,n=this.zt,r=Nr(n)&&n>=0,s=Nr(e)&&r&&n<e;return this.status===Xl||this.status===WC||this.status===Vo||s?(this.Bi=setTimeout(()=>{this.ui()},2e3),this.H):(this.H.data.length>0&&B1(this.H).forEach(i=>{this.Hi({$snapshot_bytes:i.size,$snapshot_data:i.data,$session_id:i.sessionId,$window_id:i.windowId,$lib:"web",$lib_version:ka.LIB_VERSION})}),this.gi())}qi(e){var n,r=2+(((n=this.H)==null?void 0:n.data.length)||0);!this.ii&&(this.H.size+e.$snapshot_bytes+r>943718.4||this.H.sessionId!==this.Ft)&&(this.H=this.ui()),this.H.size+=e.$snapshot_bytes,this.H.data.push(e.$snapshot_data),this.Bi||this.ii||(this.Bi=setTimeout(()=>{this.ui()},2e3))}Hi(e){this._instance.capture("$snapshot",e,{_url:this._instance.requestRouter.endpointFor("api",this.ci),_noTruncate:!0,_batchKey:"recordings",skip_client_rate_limiting:!0})}zi(e){var n;this.Nt.triggerStatus(this.sessionId)===Or&&((n=this._instance)==null||(n=n.persistence)==null||n.register({[e==="url"?O1:D1]:this.Ft}),this.ui(),this.xi(e+"_trigger_matched"))}Ni(){this.Xt.urlBlocked||(this.Xt.urlBlocked=!0,clearInterval(this.Si),fr.info("recording paused due to URL blocker"),this.tryAddCustomEvent("recording paused",{reason:"url blocker"}))}Ui(){this.Xt.urlBlocked&&(this.Xt.urlBlocked=!1,this.Oi(),this.Ci(),this.tryAddCustomEvent("recording resumed",{reason:"left blocked url"}),fr.info("recording resumed"))}bi(){this.Qt.Mt.length!==0&&Ot(this.ai)&&(this.ai=this._instance.on("eventCaptured",e=>{try{this.Qt.Mt.includes(e.event)&&this.zi("event")}catch(n){fr.error("Could not activate event trigger",n)}}))}overrideLinkedFlag(){this.Zt.linkedFlagSeen=!0,this.Oi(),this.xi("linked_flag_overridden")}overrideSampling(){var e;(e=this._instance.persistence)==null||e.register({[gu]:!0}),this.Oi(),this.xi("sampling_overridden")}overrideTrigger(e){this.zi(e)}xi(e,n){this._instance.register_for_session({$session_recording_start_reason:e}),fr.info(e.replace("_"," "),n),Ct(["recording_initialized","session_id_changed"],e)||this.tryAddCustomEvent(e,n)}get sdkDebugProperties(){var{sessionStartTimestamp:e}=this.jt.checkAndGetSessionAndWindowId(!0);return{$recording_status:this.status,$sdk_debug_replay_internal_buffer_length:this.H.data.length,$sdk_debug_replay_internal_buffer_size:this.H.size,$sdk_debug_current_session_duration:this.zt,$sdk_debug_session_start:e}}}var yw=or("[SegmentIntegration]");function Hbe(t,e){var n=t.config.segment;if(!n)return e();(function(r,s){var i=r.config.segment;if(!i)return s();var o=u=>{var d=()=>u.anonymousId()||jo();r.config.get_device_id=d,u.id()&&(r.register({distinct_id:u.id(),$device_id:d()}),r.persistence.set_property(_a,"identified")),s()},c=i.user();"then"in c&&Xs(c.then)?c.then(u=>o(u)):o(c)})(t,()=>{n.register((r=>{Promise&&Promise.resolve||yw.warn("This browser does not have Promise support, and can not use the segment integration");var s=(i,o)=>{if(!o)return i;i.event.userId||i.event.anonymousId===r.get_distinct_id()||(yw.info("No userId set, resetting PostHog"),r.reset()),i.event.userId&&i.event.userId!==r.get_distinct_id()&&(yw.info("UserId set, identifying with PostHog"),r.identify(i.event.userId));var c=r.calculateEventProperties(o,i.event.properties);return i.event.properties=Object.assign({},c,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:i=>s(i,i.event.event),page:i=>s(i,"$pageview"),identify:i=>s(i,"$identify"),screen:i=>s(i,"$screen")}})(t)).then(()=>{e()})})}var n9="posthog-js";function r9(t,e){var{organization:n,projectId:r,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}=e===void 0?{}:e;return c=>{var u,d,p,m,v;if(!(i==="*"||i.includes(c.level))||!t.__loaded)return c;c.tags||(c.tags={});var y=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=y,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var x=((u=c.exception)==null?void 0:u.values)||[],_=x.map(S=>Le({},S,{stacktrace:S.stacktrace?Le({},S.stacktrace,{type:"raw",frames:(S.stacktrace.frames||[]).map(A=>Le({},A,{platform:"web:javascript"}))}):void 0})),E={$exception_message:((d=x[0])==null?void 0:d.value)||c.message,$exception_type:(p=x[0])==null?void 0:p.type,$exception_personURL:y,$exception_level:c.level,$exception_list:_,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((m=x[0])==null?void 0:m.value)||c.message,$sentry_exception_type:(v=x[0])==null?void 0:v.type,$sentry_tags:c.tags};return n&&r&&(E.$sentry_url=(s||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+c.event_id),o&&t.exceptions.sendExceptionEvent(E),c}}class Gbe{constructor(e,n,r,s,i,o){this.name=n9,this.setupOnce=function(c){c(r9(e,{organization:n,projectId:r,prefix:s,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}var Ybe=ve!=null&&ve.location?Ov(ve.location.hash,"__posthog")||Ov(location.hash,"state"):null,oI="_postHogToolbarParams",lI=or("[Toolbar]"),Co=function(t){return t[t.UNINITIALIZED=0]="UNINITIALIZED",t[t.LOADING=1]="LOADING",t[t.LOADED=2]="LOADED",t}(Co||{});class Wbe{constructor(e){this.instance=e}Wi(e){st.ph_toolbar_state=e}Gi(){var e;return(e=st.ph_toolbar_state)!==null&&e!==void 0?e:Co.UNINITIALIZED}maybeLoadToolbar(e,n,r){if(e===void 0&&(e=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),!ve||!Be)return!1;e=e??ve.location,r=r??ve.history;try{if(!n){try{ve.localStorage.setItem("test","test"),ve.localStorage.removeItem("test")}catch{return!1}n=ve?.localStorage}var s,i=Ybe||Ov(e.hash,"__posthog")||Ov(e.hash,"state"),o=i?ND(()=>JSON.parse(atob(decodeURIComponent(i))))||ND(()=>JSON.parse(decodeURIComponent(i))):null;return o&&o.action==="ph_authorize"?((s=o).source="url",s&&Object.keys(s).length>0&&(o.desiredHash?e.hash=o.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(n.getItem(oI)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token)&&(this.loadToolbar(s),!0)}catch{return!1}}Vi(e){var n=st.ph_load_toolbar||st.ph_load_editor;!Ot(n)&&Xs(n)?n(e,this.instance):lI.warn("No toolbar load function found")}loadToolbar(e){var n=!(Be==null||!Be.getElementById(j6));if(!ve||n)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,s=Le({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(ve.localStorage.setItem(oI,JSON.stringify(Le({},s,{source:void 0}))),this.Gi()===Co.LOADED)this.Vi(s);else if(this.Gi()===Co.UNINITIALIZED){var i;this.Wi(Co.LOADING),(i=st.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",o=>{if(o)return lI.error("[Toolbar] Failed to load",o),void this.Wi(Co.UNINITIALIZED);this.Wi(Co.LOADED),this.Vi(s)}),Cn(ve,"turbolinks:load",()=>{this.Wi(Co.UNINITIALIZED),this.loadToolbar(s)})}return!0}Ji(e){return this.loadToolbar(e)}maybeLoadEditor(e,n,r){return e===void 0&&(e=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),this.maybeLoadToolbar(e,n,r)}}var Kbe=or("[TracingHeaders]");class Qbe{constructor(e){this.Ki=void 0,this.Yi=void 0,this.lt=()=>{var n,r;Oe(this.Ki)&&((n=st.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),Oe(this.Yi)&&((r=st.__PosthogExtensions__)==null||(r=r.tracingHeadersPatchFns)==null||r._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}nt(e){var n,r;(n=st.__PosthogExtensions__)!=null&&n.tracingHeadersPatchFns&&e(),(r=st.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",s=>{if(s)return Kbe.error("failed to load script",s);e()})}startIfEnabledOrStop(){var e,n;this._instance.config.__add_tracing_headers?this.nt(this.lt):((e=this.Ki)==null||e.call(this),(n=this.Yi)==null||n.call(this),this.Ki=void 0,this.Yi=void 0)}}var bo=or("[Web Vitals]"),cI=9e5;class Xbe{constructor(e){var n;this.Xi=!1,this.C=!1,this.H={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Qi=()=>{clearTimeout(this.Zi),this.H.metrics.length!==0&&(this._instance.capture("$web_vitals",this.H.metrics.reduce((r,s)=>Le({},r,{["$web_vitals_"+s.name+"_event"]:Le({},s),["$web_vitals_"+s.name+"_value"]:s.value}),{})),this.H={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.te=r=>{var s,i=(s=this._instance.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0);if(Oe(i))bo.error("Could not read session ID. Dropping metrics!");else{this.H=this.H||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.ie();Oe(o)||(Ot(r?.name)||Ot(r?.value)?bo.error("Invalid metric received",r):this.ee&&r.value>=this.ee?bo.error("Ignoring metric with value >= "+this.ee,r):(this.H.url!==o&&(this.Qi(),this.Zi=setTimeout(this.Qi,this.flushToCaptureTimeoutMs)),Oe(this.H.url)&&(this.H.url=o),this.H.firstMetricTimestamp=Oe(this.H.firstMetricTimestamp)?Date.now():this.H.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.H.metrics.push(Le({},r,{$current_url:o,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.H.metrics.length===this.allowedMetrics.length&&this.Qi()))}},this.lt=()=>{var r,s,i,o,c=st.__PosthogExtensions__;Oe(c)||Oe(c.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:s,onFCP:i,onINP:o}=c.postHogWebVitalsCallbacks),r&&s&&i&&o?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.te.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&s(this.te.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.te.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.te.bind(this)),this.C=!0):bo.error("web vitals callbacks not loaded - not starting")},this._instance=e,this.Xi=!((n=this._instance.persistence)==null||!n.props[OD]),this.startIfEnabled()}get allowedMetrics(){var e,n,r=Dn(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return Oe(r)?((n=this._instance.persistence)==null?void 0:n.props[DD])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return(Dn(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get ee(){var e=Dn(this._instance.config.capture_performance)&&Nr(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:cI;return 0<e&&e<=6e4?cI:e}get isEnabled(){var e=ts?.protocol;if(e!=="http:"&&e!=="https:")return bo.info("Web Vitals are disabled on non-http/https protocols"),!1;var n=Dn(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:vi(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return vi(n)?n:this.Xi}startIfEnabled(){this.isEnabled&&!this.C&&(bo.info("enabled, starting..."),this.nt(this.lt))}onRemoteConfig(e){var n=Dn(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=Dn(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[OD]:n}),this._instance.persistence.register({[DD]:r})),this.Xi=n,this.startIfEnabled()}nt(e){var n,r;(n=st.__PosthogExtensions__)!=null&&n.postHogWebVitalsCallbacks&&e(),(r=st.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"web-vitals",s=>{s?bo.error("failed to load script",s):e()})}ie(){var e=ve?ve.location.href:void 0;return e||bo.error("Could not determine current URL"),e}}var Zbe=or("[Heatmaps]");function uI(t){return Dn(t)&&"clientX"in t&&"clientY"in t&&Nr(t.clientX)&&Nr(t.clientY)}class Jbe{constructor(e){var n;this.rageclicks=new q6,this.Xi=!1,this.C=!1,this.re=null,this.instance=e,this.Xi=!((n=this.instance.persistence)==null||!n.props[j1])}get flushIntervalMilliseconds(){var e=5e3;return Dn(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return Oe(this.instance.config.capture_heatmaps)?Oe(this.instance.config.enable_heatmaps)?this.Xi:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.C)return;Zbe.info("starting..."),this.se(),this.re=setInterval(this.ne.bind(this),this.flushIntervalMilliseconds)}else{var e,n;clearInterval((e=this.re)!==null&&e!==void 0?e:void 0),(n=this.oe)==null||n.stop(),this.getAndClearBuffer()}}onRemoteConfig(e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[j1]:n}),this.Xi=n,this.startIfEnabled()}getAndClearBuffer(){var e=this.H;return this.H=void 0,e}ae(e){this.le(e.originalEvent,"deadclick")}se(){ve&&Be&&(Cn(ve,"beforeunload",this.ne.bind(this)),Cn(Be,"click",e=>this.le(e||ve?.event),{capture:!0}),Cn(Be,"mousemove",e=>this.ue(e||ve?.event),{capture:!0}),this.oe=new G6(this.instance,vbe,this.ae.bind(this)),this.oe.startIfEnabled(),this.C=!0)}he(e,n){var r=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),o=function(c,u,d){for(var p=c;p&&Gy(p)&&!Mo(p,"body");){if(p===d)return!1;if(Ct(u,ve?.getComputedStyle(p).position))return!0;p=L6(p)}return!1}(D6(e),["fixed","sticky"],i);return{x:e.clientX+(o?0:s),y:e.clientY+(o?0:r),target_fixed:o,type:n}}le(e,n){var r;if(n===void 0&&(n="click"),!BD(e.target)&&uI(e)){var s=this.he(e,n);(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.de(Le({},s,{type:"rageclick"})),this.de(s)}}ue(e){!BD(e.target)&&uI(e)&&(clearTimeout(this.ve),this.ve=setTimeout(()=>{this.de(this.he(e,"mousemove"))},500))}de(e){if(ve){var n=ve.location.href;this.H=this.H||{},this.H[n]||(this.H[n]=[]),this.H[n].push(e)}}ne(){this.H&&!mu(this.H)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class e_e{constructor(e){this._instance=e}doPageView(e,n){var r,s=this.ce(e,n);return this.fe={pathname:(r=ve?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var n;return this.ce(e,(n=this.fe)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.fe)==null?void 0:e.pageViewId}}ce(e,n){var r=this.fe;if(!r)return{$pageview_id:n};var s={$pageview_id:n,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:c,maxScrollY:u,maxContentHeight:d,lastContentY:p,maxContentY:m}=i;if(!(Oe(o)||Oe(c)||Oe(u)||Oe(d)||Oe(p)||Oe(m))){o=Math.ceil(o),c=Math.ceil(c),u=Math.ceil(u),d=Math.ceil(d),p=Math.ceil(p),m=Math.ceil(m);var v=o<=1?1:Ts(c/o,0,1,Ve),y=o<=1?1:Ts(u/o,0,1,Ve),x=d<=1?1:Ts(p/d,0,1,Ve),_=d<=1?1:Ts(m/d,0,1,Ve);s=Bn(s,{$prev_pageview_last_scroll:c,$prev_pageview_last_scroll_percentage:v,$prev_pageview_max_scroll:u,$prev_pageview_max_scroll_percentage:y,$prev_pageview_last_content:p,$prev_pageview_last_content_percentage:x,$prev_pageview_max_content:m,$prev_pageview_max_content_percentage:_})}}return r.pathname&&(s.$prev_pageview_pathname=r.pathname),r.timestamp&&(s.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),s}}var t_e=function(t){var e,n,r,s,i="";for(e=n=0,r=(t=(t+"").replace(/\r\n/g,`
1838
1838
  `).replace(/\r/g,`
1839
1839
  `)).length,s=0;s<r;s++){var o=t.charCodeAt(s),c=null;o<128?n++:c=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),Ga(c)||(n>e&&(i+=t.substring(e,n)),i+=c,e=n=s+1)}return n>e&&(i+=t.substring(e,t.length)),i},n_e=!!C1||!!k1,dI="text/plain",Fv=(t,e)=>{var[n,r]=t.split("?"),s=Le({},e);r?.split("&").forEach(o=>{var[c]=o.split("=");delete s[c]});var i=sbe(s);return n+"?"+(i=i?(r?r+"&":"")+i:r)},Kf=(t,e)=>JSON.stringify(t,(n,r)=>typeof r=="bigint"?r.toString():r,e),xw=t=>{var{data:e,compression:n}=t;if(e){if(n===Ta.GZipJS){var r=Z6(J6(Kf(e)),{mtime:0}),s=new Blob([r],{type:dI});return{contentType:dI,body:s,estimatedSize:s.size}}if(n===Ta.Base64){var i=function(u){var d,p,m,v,y,x="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_=0,E=0,S="",A=[];if(!u)return u;u=t_e(u);do d=(y=u.charCodeAt(_++)<<16|u.charCodeAt(_++)<<8|u.charCodeAt(_++))>>18&63,p=y>>12&63,m=y>>6&63,v=63&y,A[E++]=x.charAt(d)+x.charAt(p)+x.charAt(m)+x.charAt(v);while(_<u.length);switch(S=A.join(""),u.length%3){case 1:S=S.slice(0,-2)+"==";break;case 2:S=S.slice(0,-1)+"="}return S}(Kf(e)),o=(u=>"data="+encodeURIComponent(typeof u=="string"?u:Kf(u)))(i);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var c=Kf(e);return{contentType:"application/json",body:c,estimatedSize:new Blob([c]).size}}},Rg=[];k1&&Rg.push({transport:"fetch",method:t=>{var e,n,{contentType:r,body:s,estimatedSize:i}=(e=xw(t))!==null&&e!==void 0?e:{},o=new Headers;tn(t.headers,function(p,m){o.append(m,p)}),r&&o.append("Content-Type",r);var c=t.url,u=null;if(SD){var d=new SD;u={signal:d.signal,timeout:setTimeout(()=>d.abort(),t.timeout)}}k1(c,Le({method:t?.method||"GET",headers:o,keepalive:t.method==="POST"&&(i||0)<52428.8,body:s,signal:(n=u)==null?void 0:n.signal},t.fetchOptions)).then(p=>p.text().then(m=>{var v={statusCode:p.status,text:m};if(p.status===200)try{v.json=JSON.parse(m)}catch(y){Ve.error(y)}t.callback==null||t.callback(v)})).catch(p=>{Ve.error(p),t.callback==null||t.callback({statusCode:0,text:p})}).finally(()=>u?clearTimeout(u.timeout):null)}}),C1&&Rg.push({transport:"XHR",method:t=>{var e,n=new C1;n.open(t.method||"GET",t.url,!0);var{contentType:r,body:s}=(e=xw(t))!==null&&e!==void 0?e:{};tn(t.headers,function(i,o){n.setRequestHeader(o,i)}),r&&n.setRequestHeader("Content-Type",r),t.timeout&&(n.timeout=t.timeout),t.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var i={statusCode:n.status,text:n.responseText};if(n.status===200)try{i.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(i)}},n.send(s)}}),Cs!=null&&Cs.sendBeacon&&Rg.push({transport:"sendBeacon",method:t=>{var e=Fv(t.url,{beacon:"1"});try{var n,{contentType:r,body:s}=(n=xw(t))!==null&&n!==void 0?n:{},i=typeof s=="string"?new Blob([s],{type:r}):s;Cs.sendBeacon(e,i)}catch{}}});var Xu=function(t,e){if(!function(n){try{new RegExp(n)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function fI(t,e,n){return Kf({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var s9={exact:(t,e)=>e.some(n=>t.some(r=>n===r)),is_not:(t,e)=>e.every(n=>t.every(r=>n!==r)),regex:(t,e)=>e.some(n=>t.some(r=>Xu(n,r))),not_regex:(t,e)=>e.every(n=>t.every(r=>!Xu(n,r))),icontains:(t,e)=>e.map(lg).some(n=>t.map(lg).some(r=>n.includes(r))),not_icontains:(t,e)=>e.map(lg).every(n=>t.map(lg).every(r=>!n.includes(r)))},lg=t=>t.toLowerCase(),hI=or("[Error tracking]");class r_e{constructor(e){var n,r;this.pe=[],this.ge=new M0e([new O0e,new B0e,new I0e,new D0e,new U0e,new F0e,new z0e,new V0e],[A0e,j0e]),this._instance=e,this.pe=(n=(r=this._instance.persistence)==null?void 0:r.get_property(P1))!==null&&n!==void 0?n:[]}onRemoteConfig(e){var n,r,s,i=(n=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&n!==void 0?n:[],o=(s=e.errorTracking)==null?void 0:s.captureExtensionExceptions;this.pe=i,this._instance.persistence&&this._instance.persistence.register({[P1]:this.pe,[MD]:o})}get _e(){var e,n=!!this._instance.get_property(MD),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??n)!==null&&e!==void 0&&e}buildProperties(e,n){return this.ge.buildFromUnknown(e,{syntheticException:n?.syntheticException,mechanism:{handled:n?.handled}})}sendExceptionEvent(e){if(this.me(e))hI.info("Skipping exception capture because a suppression rule matched");else{if(this._e||!this.ye(e))return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"});hI.info("Skipping exception capture because it was thrown by an extension")}}me(e){var n=e.$exception_list;if(!n||!dn(n)||n.length===0)return!1;var r=n.reduce((s,i)=>{var{type:o,value:c}=i;return In(o)&&o.length>0&&s.$exception_types.push(o),In(c)&&c.length>0&&s.$exception_values.push(c),s},{$exception_types:[],$exception_values:[]});return this.pe.some(s=>{var i=s.values.map(o=>{var c,u=s9[o.operator],d=dn(o.value)?o.value:[o.value],p=(c=r[o.key])!==null&&c!==void 0?c:[];return d.length>0&&u(d,p)});return s.type==="OR"?i.some(Boolean):i.every(Boolean)})}ye(e){var n=e.$exception_list;return!(!n||!dn(n))&&n.flatMap(r=>{var s,i;return(s=(i=r.stacktrace)==null?void 0:i.frames)!==null&&s!==void 0?s:[]}).some(r=>r.filename&&r.filename.startsWith("chrome-extension://"))}}var Js="Mobile",Uv="iOS",zi="Android",Hh="Tablet",i9=zi+" "+Hh,a9="iPad",o9="Apple",l9=o9+" Watch",Gh="Safari",Zu="BlackBerry",c9="Samsung",u9=c9+"Browser",d9=c9+" Internet",Zl="Chrome",s_e=Zl+" OS",f9=Zl+" "+Uv,QC="Internet Explorer",h9=QC+" "+Js,XC="Opera",i_e=XC+" Mini",ZC="Edge",p9="Microsoft "+ZC,Nu="Firefox",m9=Nu+" "+Uv,Yh="Nintendo",Wh="PlayStation",ju="Xbox",g9=zi+" "+Js,v9=Js+" "+Gh,Qf="Windows",Q1=Qf+" Phone",pI="Nokia",X1="Ouya",y9="Generic",a_e=y9+" "+Js.toLowerCase(),x9=y9+" "+Hh.toLowerCase(),Z1="Konqueror",Ur="(\\d+(\\.\\d+)?)",bw=new RegExp("Version/"+Ur),o_e=new RegExp(ju,"i"),l_e=new RegExp(Wh+" \\w+","i"),c_e=new RegExp(Yh+" \\w+","i"),JC=new RegExp(Zu+"|PlayBook|BB10","i"),u_e={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},d_e=(t,e)=>e&&Ct(e,o9)||function(n){return Ct(n,Gh)&&!Ct(n,Zl)&&!Ct(n,zi)}(t),b9=function(t,e){return e=e||"",Ct(t," OPR/")&&Ct(t,"Mini")?i_e:Ct(t," OPR/")?XC:JC.test(t)?Zu:Ct(t,"IE"+Js)||Ct(t,"WPDesktop")?h9:Ct(t,u9)?d9:Ct(t,ZC)||Ct(t,"Edg/")?p9:Ct(t,"FBIOS")?"Facebook "+Js:Ct(t,"UCWEB")||Ct(t,"UCBrowser")?"UC Browser":Ct(t,"CriOS")?f9:Ct(t,"CrMo")||Ct(t,Zl)?Zl:Ct(t,zi)&&Ct(t,Gh)?g9:Ct(t,"FxiOS")?m9:Ct(t.toLowerCase(),Z1.toLowerCase())?Z1:d_e(t,e)?Ct(t,Js)?v9:Gh:Ct(t,Nu)?Nu:Ct(t,"MSIE")||Ct(t,"Trident/")?QC:Ct(t,"Gecko")?Nu:""},f_e={[h9]:[new RegExp("rv:"+Ur)],[p9]:[new RegExp(ZC+"?\\/"+Ur)],[Zl]:[new RegExp("("+Zl+"|CrMo)\\/"+Ur)],[f9]:[new RegExp("CriOS\\/"+Ur)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Ur)],[Gh]:[bw],[v9]:[bw],[XC]:[new RegExp("(Opera|OPR)\\/"+Ur)],[Nu]:[new RegExp(Nu+"\\/"+Ur)],[m9]:[new RegExp("FxiOS\\/"+Ur)],[Z1]:[new RegExp("Konqueror[:/]?"+Ur,"i")],[Zu]:[new RegExp(Zu+" "+Ur),bw],[g9]:[new RegExp("android\\s"+Ur,"i")],[d9]:[new RegExp(u9+"\\/"+Ur)],[QC]:[new RegExp("(rv:|MSIE )"+Ur)],Mozilla:[new RegExp("rv:"+Ur)]},h_e=function(t,e){var n=b9(t,e),r=f_e[n];if(Oe(r))return null;for(var s=0;s<r.length;s++){var i=r[s],o=t.match(i);if(o)return parseFloat(o[o.length-2])}return null},mI=[[new RegExp(ju+"; "+ju+" (.*?)[);]","i"),t=>[ju,t&&t[1]||""]],[new RegExp(Yh,"i"),[Yh,""]],[new RegExp(Wh,"i"),[Wh,""]],[JC,[Zu,""]],[new RegExp(Qf,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Q1,""];if(new RegExp(Js).test(e)&&!/IEMobile\b/.test(e))return[Qf+" "+Js,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var r=n[1],s=u_e[r]||"";return/arm/i.test(e)&&(s="RT"),[Qf,s]}return[Qf,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[Uv,e.join(".")]}return[Uv,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=Oe(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+zi+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+zi+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[zi,e.join(".")]}return[zi,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[s_e,""]],[/Linux|debian/i,["Linux",""]]],gI=function(t){return c_e.test(t)?Yh:l_e.test(t)?Wh:o_e.test(t)?ju:new RegExp(X1,"i").test(t)?X1:new RegExp("("+Q1+"|WPDesktop)","i").test(t)?Q1:/iPad/.test(t)?a9:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?l9:JC.test(t)?Zu:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(pI,"i").test(t)?pI:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?!new RegExp(Js).test(t)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)?/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?zi:i9:zi:new RegExp("(pda|"+Js+")","i").test(t)?a_e:new RegExp(Hh,"i").test(t)&&!new RegExp(Hh+" pc","i").test(t)?x9:""},cg="https?://(.*)",Wy=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],p_e=Hy(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Wy),eT="<masked>",m_e=["li_fat_id"];function _9(t,e,n){if(!Be)return{};var r,s=e?Hy([],Wy,n||[]):[],i=w9(qC(Be.URL,s,eT),t),o=(r={},tn(m_e,function(c){var u=Yi.J(c);r[c]=u||null}),r);return Bn(o,i)}function w9(t,e){var n=p_e.concat(e||[]),r={};return tn(n,function(s){var i=Mv(t,s);r[s]=i||null}),r}function S9(t){var e=function(i){return i?i.search(cg+"google.([^/?]*)")===0?"google":i.search(cg+"bing.com")===0?"bing":i.search(cg+"yahoo.com")===0?"yahoo":i.search(cg+"duckduckgo.com")===0?"duckduckgo":null:null}(t),n=e!="yahoo"?"q":"p",r={};if(!Ga(e)){r.$search_engine=e;var s=Be?Mv(Be.referrer,n):"";s.length&&(r.ph_keyword=s)}return r}function vI(){return navigator.language||navigator.userLanguage}function E9(){return Be?.referrer||"$direct"}function k9(t,e){var n=t?Hy([],Wy,e||[]):[],r=ts?.href.substring(0,1e3);return{r:E9().substring(0,1e3),u:r?qC(r,n,eT):void 0}}function C9(t){var e,{r:n,u:r}=t,s={$referrer:n,$referring_domain:n==null?void 0:n=="$direct"?"$direct":(e=Ku(n))==null?void 0:e.host};if(r){s.$current_url=r;var i=Ku(r);s.$host=i?.host,s.$pathname=i?.pathname;var o=w9(r);Bn(s,o)}if(n){var c=S9(n);Bn(s,c)}return s}function T9(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function g_e(){try{return new Date().getTimezoneOffset()}catch{return}}function v_e(t,e){if(!es)return{};var n,r,s,i=t?Hy([],Wy,e||[]):[],[o,c]=function(u){for(var d=0;d<mI.length;d++){var[p,m]=mI[d],v=p.exec(u),y=v&&(Xs(m)?m(v,u):m);if(y)return y}return["",""]}(es);return Bn(FC({$os:o,$os_version:c,$browser:b9(es,navigator.vendor),$device:gI(es),$device_type:(r=es,s=gI(r),s===a9||s===i9||s==="Kobo"||s==="Kindle Fire"||s===x9?Hh:s===Yh||s===ju||s===Wh||s===X1?"Console":s===l9?"Wearable":s?Js:"Desktop"),$timezone:T9(),$timezone_offset:g_e()}),{$current_url:qC(ts?.href,i,eT),$host:ts?.host,$pathname:ts?.pathname,$raw_user_agent:es.length>1e3?es.substring(0,997)+"...":es,$browser_version:h_e(es,navigator.vendor),$browser_language:vI(),$browser_language_prefix:(n=vI(),typeof n=="string"?n.split("-")[0]:void 0),$screen_height:ve?.screen.height,$screen_width:ve?.screen.width,$viewport_height:ve?.innerHeight,$viewport_width:ve?.innerWidth,$lib:"web",$lib_version:ka.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var Pi=or("[FeatureFlags]"),_w="$active_feature_flags",Xc="$override_feature_flags",yI="$feature_flag_payloads",Af="$override_feature_flag_payloads",xI="$feature_flag_request_id",bI=t=>{var e={};for(var[n,r]of Ag(t||{}))r&&(e[n]=r);return e},y_e=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map(n=>{var r;return[n,(r=e[n].variant)!==null&&r!==void 0?r:e[n].enabled]})),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(n=>e[n].enabled).filter(n=>{var r;return(r=e[n].metadata)==null?void 0:r.payload}).map(n=>{var r;return[n,(r=e[n].metadata)==null?void 0:r.payload]}))):Pi.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},x_e=function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t}({});class b_e{constructor(e){this.be=!1,this.we=!1,this.Se=!1,this.ke=!1,this.$e=!1,this.xe=!1,this.Ee=!1,this._instance=e,this.featureFlagEventHandlers=[]}flags(){if(this._instance.config.__preview_remote_config)this.xe=!0;else{var e=!this.Pe&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.Ie({disableFlags:e})}}get hasLoadedFlags(){return this.we}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(I1),n=this._instance.get_property(Xc),r=this._instance.get_property(Af);if(!r&&!n)return e||{};var s=Bn({},e||{}),i=[...new Set([...Object.keys(r||{}),...Object.keys(n||{})])];for(var o of i){var c,u,d=s[o],p=n?.[o],m=Oe(p)?(c=d?.enabled)!==null&&c!==void 0&&c:!!p,v=Oe(p)?d.variant:typeof p=="string"?p:void 0,y=r?.[o],x=Le({},d,{enabled:m,variant:m?v??d?.variant:void 0});m!==d?.enabled&&(x.original_enabled=d?.enabled),v!==d?.variant&&(x.original_variant=d?.variant),y&&(x.metadata=Le({},d?.metadata,{payload:y,original_payload:d==null||(u=d.metadata)==null?void 0:u.payload})),s[o]=x}return this.be||(Pi.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:s}),this.be=!0),s}getFlagVariants(){var e=this._instance.get_property(vu),n=this._instance.get_property(Xc);if(!n)return e||{};for(var r=Bn({},e),s=Object.keys(n),i=0;i<s.length;i++)r[s[i]]=n[s[i]];return this.be||(Pi.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:n,finalFlags:r}),this.be=!0),r}getFlagPayloads(){var e=this._instance.get_property(yI),n=this._instance.get_property(Af);if(!n)return e||{};for(var r=Bn({},e||{}),s=Object.keys(n),i=0;i<s.length;i++)r[s[i]]=n[s[i]];return this.be||(Pi.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:n,finalPayloads:r}),this.be=!0),r}reloadFeatureFlags(){this.ke||this._instance.config.advanced_disable_feature_flags||this.Pe||(this.Pe=setTimeout(()=>{this.Ie()},5))}Re(){clearTimeout(this.Pe),this.Pe=void 0}ensureFlagsLoaded(){this.we||this.Se||this.Pe||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ke=e}Ie(e){var n;if(this.Re(),!this._instance.L())if(this.Se)this.$e=!0;else{var r={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:Le({},((n=this._instance.persistence)==null?void 0:n.get_initial_props())||{},this._instance.get_property(Yf)||{}),group_properties:this._instance.get_property(Cl)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(r.disable_flags=!0);var s=this._instance.config.__preview_remote_config,i=s?"/flags/?v=2":"/flags/?v=2&config=true",o=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",c=this._instance.requestRouter.endpointFor("api",i+o);s&&(r.timezone=T9()),this.Se=!0,this._instance.Te({method:"POST",url:c,data:r,compression:this._instance.config.disable_compression?void 0:Ta.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:u=>{var d,p,m=!0;if(u.statusCode===200&&(this.$e||(this.$anon_distinct_id=void 0),m=!1),this.Se=!1,this.xe||(this.xe=!0,this._instance.Ce((p=u.json)!==null&&p!==void 0?p:{})),!r.disable_flags||this.$e)if(this.Ee=!m,u.json&&(d=u.json.quotaLimited)!=null&&d.includes(x_e.FeatureFlags))Pi.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var v;r.disable_flags||this.receivedFeatureFlags((v=u.json)!==null&&v!==void 0?v:{},m),this.$e&&(this.$e=!1,this.Ie())}}})}}getFeatureFlag(e,n){if(n===void 0&&(n={}),this.we||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants()[e],s=""+r,i=this._instance.get_property(xI)||void 0,o=this._instance.get_property(Rv)||{};if((n.send_event||!("send_event"in n))&&(!(e in o)||!o[e].includes(s))){var c,u,d,p,m,v,y,x,_;dn(o[e])?o[e].push(s):o[e]=[s],(c=this._instance.persistence)==null||c.register({[Rv]:o});var E=this.getFeatureFlagDetails(e),S={$feature_flag:e,$feature_flag_response:r,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:i,$feature_flag_bootstrapped_response:((u=this._instance.config.bootstrap)==null||(u=u.featureFlags)==null?void 0:u[e])||null,$feature_flag_bootstrapped_payload:((d=this._instance.config.bootstrap)==null||(d=d.featureFlagPayloads)==null?void 0:d[e])||null,$used_bootstrap_value:!this.Ee};Oe(E==null||(p=E.metadata)==null?void 0:p.version)||(S.$feature_flag_version=E.metadata.version);var A,C=(m=E==null||(v=E.reason)==null?void 0:v.description)!==null&&m!==void 0?m:E==null||(y=E.reason)==null?void 0:y.code;C&&(S.$feature_flag_reason=C),E!=null&&(x=E.metadata)!=null&&x.id&&(S.$feature_flag_id=E.metadata.id),Oe(E?.original_variant)&&Oe(E?.original_enabled)||(S.$feature_flag_original_response=Oe(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(_=E.metadata)!=null&&_.original_payload&&(S.$feature_flag_original_payload=E==null||(A=E.metadata)==null?void 0:A.original_payload),this._instance.capture("$feature_flag_called",S)}return r}Pi.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,n){var r=this._instance.config.token;this._instance.Te({method:"POST",url:this._instance.requestRouter.endpointFor("api","/flags/?v=2&config=true"),data:{distinct_id:this._instance.get_distinct_id(),token:r},compression:this._instance.config.disable_compression?void 0:Ta.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:s=>{var i,o=(i=s.json)==null?void 0:i.featureFlagPayloads;n(o?.[e]||void 0)}})}isFeatureEnabled(e,n){if(n===void 0&&(n={}),this.we||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,n);return Oe(r)?void 0:!!r}Pi.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(n=>n!==e)}receivedFeatureFlags(e,n){if(this._instance.persistence){this.we=!0;var r=this.getFlagVariants(),s=this.getFlagPayloads(),i=this.getFlagsWithDetails();(function(o,c,u,d,p){u===void 0&&(u={}),d===void 0&&(d={}),p===void 0&&(p={});var m=y_e(o),v=m.flags,y=m.featureFlags,x=m.featureFlagPayloads;if(y){var _=o.requestId;if(dn(y)){Pi.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var E={};if(y)for(var S=0;S<y.length;S++)E[y[S]]=!0;c&&c.register({[_w]:y,[vu]:E})}else{var A=y,C=x,R=v;o.errorsWhileComputingFlags&&(A=Le({},u,A),C=Le({},d,C),R=Le({},p,R)),c&&c.register(Le({[_w]:Object.keys(bI(A)),[vu]:A||{},[yI]:C||{},[I1]:R||{}},_?{[xI]:_}:{}))}}})(e,this._instance.persistence,r,s,i),this.Me(n)}}override(e,n){n===void 0&&(n=!1),Pi.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:n})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return Pi.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(Xc),this._instance.persistence.unregister(Af),void this.Me();if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,r=e;if(this.be=!!((n=r.suppressWarning)!==null&&n!==void 0&&n),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister(Xc);else if(r.flags)if(dn(r.flags)){for(var s={},i=0;i<r.flags.length;i++)s[r.flags[i]]=!0;this._instance.persistence.register({[Xc]:s})}else this._instance.persistence.register({[Xc]:r.flags})}return"payloads"in r&&(r.payloads===!1?this._instance.persistence.unregister(Af):r.payloads&&this._instance.persistence.register({[Af]:r.payloads})),void this.Me()}this.Me()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.we){var{flags:n,flagVariants:r}=this.Oe();e(n,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,n,r){var s,i=(this._instance.get_property(Gf)||[]).find(d=>d.flagKey===e),o={["$feature_enrollment/"+e]:n},c={$feature_flag:e,$feature_enrollment:n,$set:o};i&&(c.$early_access_feature_name=i.name),r&&(c.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",c),this.setPersonPropertiesForFlags(o,!1);var u=Le({},this.getFlagVariants(),{[e]:n});(s=this._instance.persistence)==null||s.register({[_w]:Object.keys(bI(u)),[vu]:u}),this.Me()}getEarlyAccessFeatures(e,n,r){n===void 0&&(n=!1);var s=this._instance.get_property(Gf),i=r?"&"+r.map(o=>"stage="+o).join("&"):"";if(s&&!n)return e(s);this._instance.Te({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+i),method:"GET",callback:o=>{var c,u;if(o.json){var d=o.json.earlyAccessFeatures;return(c=this._instance.persistence)==null||c.unregister(Gf),(u=this._instance.persistence)==null||u.register({[Gf]:d}),e(d)}}})}Oe(){var e=this.getFlags(),n=this.getFlagVariants();return{flags:e.filter(r=>n[r]),flagVariants:Object.keys(n).filter(r=>n[r]).reduce((r,s)=>(r[s]=n[s],r),{})}}Me(e){var{flags:n,flagVariants:r}=this.Oe();this.featureFlagEventHandlers.forEach(s=>s(n,r,{errorsLoading:e}))}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0);var r=this._instance.get_property(Yf)||{};this._instance.register({[Yf]:Le({},r,e)}),n&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Yf)}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0);var r=this._instance.get_property(Cl)||{};Object.keys(r).length!==0&&Object.keys(r).forEach(s=>{r[s]=Le({},r[s],e[s]),delete e[s]}),this._instance.register({[Cl]:Le({},r,e)}),n&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var n=this._instance.get_property(Cl)||{};this._instance.register({[Cl]:Le({},n,{[e]:{}})})}else this._instance.unregister(Cl)}reset(){this.we=!1,this.Se=!1,this.ke=!1,this.$e=!1,this.xe=!1,this.Ee=!1,this.$anon_distinct_id=void 0,this.Re(),this.be=!1}}var __e=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class ww{constructor(e,n){this.A=e,this.props={},this.Fe=!1,this.Ae=(r=>{var s="";return r.token&&(s=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+s+"_posthog"})(e),this.it=this.De(e),this.load(),e.debug&&Ve.info("Persistence loaded",e.persistence,Le({},this.props)),this.update_config(e,e,n),this.save()}isDisabled(){return!!this.je}De(e){__e.indexOf(e.persistence.toLowerCase())===-1&&(Ve.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n=e.persistence.toLowerCase();return n==="localstorage"&&rr.G()?rr:n==="localstorage+cookie"&&rg.G()?rg:n==="sessionstorage"&&Sr.G()?Sr:n==="memory"?mbe:n==="cookie"?Yi:rg.G()?rg:Yi}properties(){var e={};return tn(this.props,function(n,r){if(r===vu&&Dn(n))for(var s=Object.keys(n),i=0;i<s.length;i++)e["$feature/"+s[i]]=n[s[i]];else c=r,u=!1,(Ga(o=K0e)?u:wD&&o.indexOf===wD?o.indexOf(c)!=-1:(tn(o,function(d){if(u||(u=d===c))return Tv}),u))||(e[r]=n);var o,c,u}),e}load(){if(!this.je){var e=this.it.K(this.Ae);e&&(this.props=Bn({},e))}}save(){this.je||this.it.Y(this.Ae,this.props,this.Le,this.Ne,this.Ue,this.A.debug)}remove(){this.it.X(this.Ae,!1),this.it.X(this.Ae,!0)}clear(){this.remove(),this.props={}}register_once(e,n,r){if(Dn(e)){Oe(n)&&(n="None"),this.Le=Oe(r)?this.ze:r;var s=!1;if(tn(e,(i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.props[o]=i,s=!0)}),s)return this.save(),!0}return!1}register(e,n){if(Dn(e)){this.Le=Oe(n)?this.ze:n;var r=!1;if(tn(e,(s,i)=>{e.hasOwnProperty(i)&&this.props[i]!==s&&(this.props[i]=s,r=!0)}),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Fe){var e=_9(this.A.custom_campaign_params,this.A.mask_personal_data_properties,this.A.custom_personal_data_properties);mu(FC(e))||this.register(e),this.Fe=!0}}update_search_keyword(){var e;this.register((e=Be?.referrer)?S9(e):{})}update_referrer_info(){var e;this.register_once({$referrer:E9(),$referring_domain:Be!=null&&Be.referrer&&((e=Ku(Be.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[F1]||this.props[U1]||this.register_once({[Nv]:k9(this.A.mask_personal_data_properties,this.A.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};tn([U1,F1],o=>{var c=this.props[o];c&&tn(c,function(u,d){e["$initial_"+T1(d)]=u})});var n,r,s=this.props[Nv];if(s){var i=(n=C9(s),r={},tn(n,function(o,c){r["$initial_"+T1(c)]=o}),r);Bn(e,i)}return e}safe_merge(e){return tn(this.props,function(n,r){r in e||(e[r]=n)}),e}update_config(e,n,r){if(this.ze=this.Le=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==n.persistence){var s=this.De(e),i=this.props;this.clear(),this.it=s,this.props=i,this.save()}}set_disabled(e){this.je=e,this.je?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ne&&(this.Ne=e,this.remove(),this.save())}set_secure(e){e!==this.Ue&&(this.Ue=e,this.remove(),this.save())}set_event_timer(e,n){var r=this.props[Hf]||{};r[e]=n,this.props[Hf]=r,this.save()}remove_event_timer(e){var n=(this.props[Hf]||{})[e];return Oe(n)||(delete this.props[Hf][e],this.save()),n}get_property(e){return this.props[e]}set_property(e,n){this.props[e]=n,this.save()}}(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({});(function(t){return t.TopLeft="top_left",t.TopRight="top_right",t.TopCenter="top_center",t.MiddleLeft="middle_left",t.MiddleRight="middle_right",t.MiddleCenter="middle_center",t.Left="left",t.Center="center",t.Right="right",t.NextToTrigger="next_to_trigger",t})({});var Sw=function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t}({});(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({});(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({});(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({});var Ng=function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t}({}),_I=function(t){return t.SURVEY_ID="$survey_id",t.SURVEY_NAME="$survey_name",t.SURVEY_RESPONSE="$survey_response",t.SURVEY_ITERATION="$survey_iteration",t.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",t.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",t.SURVEY_SUBMISSION_ID="$survey_submission_id",t.SURVEY_QUESTIONS="$survey_questions",t.SURVEY_COMPLETED="$survey_completed",t}({}),A9=function(t){return t.Popover="popover",t.Inline="inline",t}({});class R9{constructor(){this.qe={},this.qe={}}on(e,n){return this.qe[e]||(this.qe[e]=[]),this.qe[e].push(n),()=>{this.qe[e]=this.qe[e].filter(r=>r!==n)}}emit(e,n){for(var r of this.qe[e]||[])r(n);for(var s of this.qe["*"]||[])s(e,n)}}class Tl{constructor(e){this.Be=new R9,this.He=(n,r)=>this.We(n,r)&&this.Ge(n,r)&&this.Ve(n,r),this.We=(n,r)=>r==null||!r.event||n?.event===r?.event,this._instance=e,this.Je=new Set,this.Ke=new Set}init(){var e;if(!Oe((e=this._instance)==null?void 0:e.Ye)){var n;(n=this._instance)==null||n.Ye((r,s)=>{this.on(r,s)})}}register(e){var n,r;if(!Oe((n=this._instance)==null?void 0:n.Ye)&&(e.forEach(o=>{var c,u;(c=this.Ke)==null||c.add(o),(u=o.steps)==null||u.forEach(d=>{var p;(p=this.Je)==null||p.add(d?.event||"")})}),(r=this._instance)!=null&&r.autocapture)){var s,i=new Set;e.forEach(o=>{var c;(c=o.steps)==null||c.forEach(u=>{u!=null&&u.selector&&i.add(u?.selector)})}),(s=this._instance)==null||s.autocapture.setElementSelectors(i)}}on(e,n){var r;n!=null&&e.length!=0&&(this.Je.has(e)||this.Je.has(n?.event))&&this.Ke&&((r=this.Ke)==null?void 0:r.size)>0&&this.Ke.forEach(s=>{this.Xe(n,s)&&this.Be.emit("actionCaptured",s.name)})}Qe(e){this.onAction("actionCaptured",n=>e(n))}Xe(e,n){if(n?.steps==null)return!1;for(var r of n.steps)if(this.He(e,r))return!0;return!1}onAction(e,n){return this.Be.on(e,n)}Ge(e,n){if(n!=null&&n.url){var r,s=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!s||typeof s!="string"||!Tl.Ze(s,n?.url,n?.url_matching||"contains"))return!1}return!0}static Ze(e,n,r){switch(r){case"regex":return!!ve&&Xu(e,n);case"exact":return n===e;case"contains":var s=Tl.tr(n).replace(/_/g,".").replace(/%/g,".*");return Xu(e,s);default:return!1}}static tr(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}Ve(e,n){if((n!=null&&n.href||n!=null&&n.tag_name||n!=null&&n.text)&&!this.ir(e).some(i=>!(n!=null&&n.href&&!Tl.Ze(i.href||"",n?.href,n?.href_matching||"exact"))&&(n==null||!n.tag_name||i.tag_name===n?.tag_name)&&!(n!=null&&n.text&&!Tl.Ze(i.text||"",n?.text,n?.text_matching||"exact")&&!Tl.Ze(i.$el_text||"",n?.text,n?.text_matching||"exact"))))return!1;if(n!=null&&n.selector){var r,s=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(!s||!s.includes(n?.selector))return!1}return!0}ir(e){return e?.properties.$elements==null?[]:e?.properties.$elements}}var en=or("[Surveys]"),J1="seenSurvey_",w_e=(t,e)=>{var n="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(n="$survey_"+e+"/"+t.id+"/"+t.current_iteration),n},wI=t=>{var e=""+J1+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+J1+t.id+"_"+t.current_iteration),e},S_e=[Sw.Popover,Sw.Widget,Sw.API],E_e={ignoreConditions:!1,ignoreDelay:!1,displayType:A9.Popover};class k_e{constructor(e){this._instance=e,this.er=new Map,this.rr=new Map}register(e){var n;Oe((n=this._instance)==null?void 0:n.Ye)||(this.sr(e),this.nr(e))}nr(e){var n=e.filter(r=>{var s,i;return((s=r.conditions)==null?void 0:s.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0});n.length!==0&&(this.ar==null&&(this.ar=new Tl(this._instance),this.ar.init(),this.ar.Qe(r=>{this.onAction(r)})),n.forEach(r=>{var s,i,o,c,u;r.conditions&&(s=r.conditions)!=null&&s.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((c=this.ar)==null||c.register(r.conditions.actions.values),(u=r.conditions)==null||(u=u.actions)==null||(u=u.values)==null||u.forEach(d=>{if(d&&d.name){var p=this.rr.get(d.name);p&&p.push(r.id),this.rr.set(d.name,p||[r.id])}}))}))}sr(e){var n;e.filter(r=>{var s,i;return((s=r.conditions)==null?void 0:s.events)&&((i=r.conditions)==null||(i=i.events)==null||(i=i.values)==null?void 0:i.length)>0}).length!==0&&((n=this._instance)==null||n.Ye((r,s)=>{this.onEvent(r,s)}),e.forEach(r=>{var s;(s=r.conditions)==null||(s=s.events)==null||(s=s.values)==null||s.forEach(i=>{if(i&&i.name){var o=this.er.get(i.name);o&&o.push(r.id),this.er.set(i.name,o||[r.id])}})}))}onEvent(e,n){var r,s,i=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[ng])||[];if(Ng.SHOWN===e&&n&&i.length>0){var o;en.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:n,existingActivatedSurveys:i});var c=n==null||(o=n.properties)==null?void 0:o.$survey_id;if(c){var u=i.indexOf(c);u>=0&&(i.splice(u,1),this.lr(i))}}else if(this.er.has(e)){en.info("survey event name matched",{event:e,eventPayload:n,surveys:this.er.get(e)});var d=[];(s=this._instance)==null||s.getSurveys(m=>{d=m.filter(v=>{var y;return(y=this.er.get(e))==null?void 0:y.includes(v.id)})});var p=d.filter(m=>{var v,y=(v=m.conditions)==null||(v=v.events)==null||(v=v.values)==null?void 0:v.find(x=>x.name===e);return!!y&&(!y.propertyFilters||Object.entries(y.propertyFilters).every(x=>{var _,[E,S]=x,A=n==null||(_=n.properties)==null?void 0:_[E];if(Oe(A)||Ga(A))return!1;var C=[String(A)],R=s9[S.operator];return R?R(S.values,C):(en.warn("Unknown property comparison operator: "+S.operator),!1)}))});this.lr(i.concat(p.map(m=>m.id)||[]))}}onAction(e){var n,r=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[ng])||[];this.rr.has(e)&&this.lr(r.concat(this.rr.get(e)||[]))}lr(e){var n;en.info("updating activated surveys",{activatedSurveys:e}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[ng]:[...new Set(e)]})}getSurveys(){var e,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[ng];return n||[]}getEventToSurveys(){return this.er}ur(){return this.ar}}class C_e{constructor(e){this.hr=void 0,this._surveyManager=null,this.dr=!1,this.vr=!1,this.cr=[],this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var n=e.surveys;if(Ot(n))return en.warn("Flags not loaded yet. Not loading surveys.");var r=dn(n);this.hr=r?n.length>0:n,en.info("flags response received, isSurveysEnabled: "+this.hr),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;n<localStorage.length;n++){var r=localStorage.key(n);(r!=null&&r.startsWith(J1)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach(s=>localStorage.removeItem(s))}loadIfEnabled(){if(!this._surveyManager)if(this.vr)en.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)en.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())en.info("Not loading surveys in cookieless mode without consent.");else{var e=st?.__PosthogExtensions__;if(e){if(!Oe(this.hr)||this._instance.config.advanced_enable_surveys){var n=this.hr||this._instance.config.advanced_enable_surveys;this.vr=!0;try{var r=e.generateSurveys;if(r)return void this.pr(r,n);var s=e.loadExternalDependency;if(!s)return void this.gr("PostHog loadExternalDependency extension not found.");s(this._instance,"surveys",i=>{i||!e.generateSurveys?this.gr("Could not load surveys script",i):this.pr(e.generateSurveys,n)})}catch(i){throw this.gr("Error initializing surveys",i),i}finally{this.vr=!1}}}else en.error("PostHog Extensions not found.")}}pr(e,n){this._surveyManager=e(this._instance,n),this._surveyEventReceiver=new k_e(this._instance),en.info("Surveys loaded successfully"),this._r({isLoaded:!0})}gr(e,n){en.error(e,n),this._r({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.cr.push(e),this._surveyManager&&this._r({isLoaded:!0}),()=>{this.cr=this.cr.filter(n=>n!==e)}}getSurveys(e,n){if(n===void 0&&(n=!1),this._instance.config.disable_surveys)return en.info("Disabled. Not loading surveys."),e([]);var r=this._instance.get_property(L1);if(r&&!n)return e(r,{isLoaded:!0});if(this.dr)return e([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.dr=!0,this._instance.Te({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:s=>{var i;this.dr=!1;var o=s.statusCode;if(o!==200||!s.json){var c="Surveys API could not be loaded, status: "+o;return en.error(c),e([],{isLoaded:!1,error:c})}var u,d=s.json.surveys||[],p=d.filter(m=>function(v){return!(!v.start_date||v.end_date)}(m)&&(function(v){var y;return!((y=v.conditions)==null||(y=y.events)==null||(y=y.values)==null||!y.length)}(m)||function(v){var y;return!((y=v.conditions)==null||(y=y.actions)==null||(y=y.values)==null||!y.length)}(m)));return p.length>0&&((u=this._surveyEventReceiver)==null||u.register(p)),(i=this._instance.persistence)==null||i.register({[L1]:d}),e(d,{isLoaded:!0})}})}catch(s){throw this.dr=!1,s}}_r(e){for(var n of this.cr)try{if(!e.isLoaded)return n([],e);this.getSurveys(n)}catch(r){en.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,n){if(n===void 0&&(n=!1),!Ot(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,n);en.warn("init was not called")}mr(e){var n=null;return this.getSurveys(r=>{var s;n=(s=r.find(i=>i.id===e))!==null&&s!==void 0?s:null}),n}yr(e){if(Ot(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var n=typeof e=="string"?this.mr(e):e;return n?this._surveyManager.checkSurveyEligibility(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Ot(this._surveyManager))return en.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=this.yr(e);return{visible:n.eligible,disabledReason:n.reason}}canRenderSurveyAsync(e,n){return Ot(this._surveyManager)?(en.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(r=>{this.getSurveys(s=>{var i,o=(i=s.find(u=>u.id===e))!==null&&i!==void 0?i:null;if(o){var c=this.yr(o);r({visible:c.eligible,disabledReason:c.reason})}else r({visible:!1,disabledReason:"Survey not found"})},n)})}renderSurvey(e,n){var r;if(Ot(this._surveyManager))en.warn("init was not called");else{var s=typeof e=="string"?this.mr(e):e;if(s!=null&&s.id)if(S_e.includes(s.type)){var i=Be?.querySelector(n);if(i)return(r=s.appearance)!=null&&r.surveyPopupDelaySeconds?(en.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var o,c;en.info("Rendering survey "+s.id+" with delay of "+((o=s.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(c=this._surveyManager)==null||c.renderSurvey(s,i),en.info("Survey "+s.id+" rendered")},1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,i);en.warn("Survey element not found")}else en.warn("Surveys of type "+s.type+" cannot be rendered in the app");else en.warn("Survey not found")}}displaySurvey(e,n){var r;if(Ot(this._surveyManager))en.warn("init was not called");else{var s=this.mr(e);if(s){var i=s;if((r=s.appearance)!=null&&r.surveyPopupDelaySeconds&&n.ignoreDelay&&(i=Le({},s,{appearance:Le({},s.appearance,{surveyPopupDelaySeconds:0})})),n.ignoreConditions===!1){var o=this.canRenderSurvey(s);if(!o.visible)return void en.warn("Survey is not eligible to be displayed: ",o.disabledReason)}n.displayType!==A9.Inline?this._surveyManager.handlePopoverSurvey(i):this.renderSurvey(i,n.selector)}else en.warn("Survey not found")}}}var SI=or("[RateLimiter]");class T_e{constructor(e){var n,r;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var i=s.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach(o=>{SI.info((o||"events")+" is quota limited."),this.serverLimits[o]=new Date().getTime()+6e4})}catch(o){return void SI.warn('could not rate limit - continuing. Error: "'+o?.message+'"',{text:i})}},this.instance=e,this.captureEventsPerSecond=((n=e.config.rate_limiting)==null?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((r=e.config.rate_limiting)==null?void 0:r.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var n,r,s;e===void 0&&(e=!1);var i=new Date().getTime(),o=(n=(r=this.instance.persistence)==null?void 0:r.get_property($1))!==null&&n!==void 0?n:{tokens:this.captureEventsBurstLimit,last:i};o.tokens+=(i-o.last)/1e3*this.captureEventsPerSecond,o.last=i,o.tokens>this.captureEventsBurstLimit&&(o.tokens=this.captureEventsBurstLimit);var c=o.tokens<1;return c||e||(o.tokens=Math.max(0,o.tokens-1)),!c||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=c,(s=this.instance.persistence)==null||s.set_property($1,o),{isRateLimited:c,remainingTokens:o.tokens}}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()<n}}var Sl=or("[RemoteConfig]");class A_e{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=st._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}br(e){var n,r;(n=st.__PosthogExtensions__)!=null&&n.loadExternalDependency?(r=st.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",()=>e(this.remoteConfig)):(Sl.error("PostHog Extensions not found. Cannot load remote config."),e())}wr(e){this._instance.Te({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:n=>{e(n.json)}})}load(){try{if(this.remoteConfig)return Sl.info("Using preloaded remote config",this.remoteConfig),void this.Ce(this.remoteConfig);if(this._instance.L())return void Sl.warn("Remote config is disabled. Falling back to local config.");this.br(e=>{if(!e)return Sl.info("No config found after loading remote JS config. Falling back to JSON."),void this.wr(n=>{this.Ce(n)});this.Ce(e)})}catch(e){Sl.error("Error loading remote config",e)}}Ce(e){e?this._instance.config.__preview_remote_config?(this._instance.Ce(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Sl.info("__preview_remote_config is disabled. Logging config instead",e):Sl.error("Failed to fetch remote config from PostHog.")}}var eE=3e3;class R_e{constructor(e,n){this.Sr=!0,this.kr=[],this.$r=Ts(n?.flush_interval_ms||eE,250,5e3,Ve.createLogger("flush interval"),eE),this.Er=e}enqueue(e){this.kr.push(e),this.Pr||this.Ir()}unload(){this.Rr();var e=this.kr.length>0?this.Tr():{},n=Object.values(e);[...n.filter(r=>r.url.indexOf("/e")===0),...n.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.Er(Le({},r,{transport:"sendBeacon"}))})}enable(){this.Sr=!1,this.Ir()}Ir(){var e=this;this.Sr||(this.Pr=setTimeout(()=>{if(this.Rr(),this.kr.length>0){var n=this.Tr(),r=function(){var i=n[s],o=new Date().getTime();i.data&&dn(i.data)&&tn(i.data,c=>{c.offset=Math.abs(c.timestamp-o),delete c.timestamp}),e.Er(i)};for(var s in n)r()}},this.$r))}Rr(){clearTimeout(this.Pr),this.Pr=void 0}Tr(){var e={};return tn(this.kr,n=>{var r,s=n,i=(s?s.batchKey:null)||s.url;Oe(e[i])&&(e[i]=Le({},s,{data:[]})),(r=e[i].data)==null||r.push(s.data)}),this.kr=[],e}}var N_e=["retriesPerformedSoFar"];class j_e{constructor(e){this.Cr=!1,this.Mr=3e3,this.kr=[],this._instance=e,this.kr=[],this.Or=!0,!Oe(ve)&&"onLine"in ve.navigator&&(this.Or=ve.navigator.onLine,Cn(ve,"online",()=>{this.Or=!0,this.ne()}),Cn(ve,"offline",()=>{this.Or=!1}))}get length(){return this.kr.length}retriableRequest(e){var{retriesPerformedSoFar:n}=e,r=b6(e,N_e);Nr(n)&&n>0&&(r.url=Fv(r.url,{retry_count:n})),this._instance.Te(Le({},r,{callback:s=>{s.statusCode!==200&&(s.statusCode<400||s.statusCode>=500)&&(n??0)<10?this.Fr(Le({retriesPerformedSoFar:n},r)):r.callback==null||r.callback(s)}}))}Fr(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var r=function(o){var c=3e3*Math.pow(2,o),u=c/2,d=Math.min(18e5,c),p=(Math.random()-.5)*(d-u);return Math.ceil(d+p)}(n),s=Date.now()+r;this.kr.push({retryAt:s,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),Ve.warn(i),this.Cr||(this.Cr=!0,this.Ar())}Ar(){this.Dr&&clearTimeout(this.Dr),this.Dr=setTimeout(()=>{this.Or&&this.kr.length>0&&this.ne(),this.Ar()},this.Mr)}ne(){var e=Date.now(),n=[],r=this.kr.filter(i=>i.retryAt<e||(n.push(i),!1));if(this.kr=n,r.length>0)for(var{requestOptions:s}of r)this.retriableRequest(s)}unload(){for(var{requestOptions:e}of(this.Dr&&(clearTimeout(this.Dr),this.Dr=void 0),this.kr))try{this._instance.Te(Le({},e,{transport:"sendBeacon"}))}catch(n){Ve.error(n)}this.kr=[]}}class P_e{constructor(e){this.jr=()=>{var n,r,s,i;this.Lr||(this.Lr={});var o=this.scrollElement(),c=this.scrollY(),u=o?Math.max(0,o.scrollHeight-o.clientHeight):0,d=c+(o?.clientHeight||0),p=o?.scrollHeight||0;this.Lr.lastScrollY=Math.ceil(c),this.Lr.maxScrollY=Math.max(c,(n=this.Lr.maxScrollY)!==null&&n!==void 0?n:0),this.Lr.maxScrollHeight=Math.max(u,(r=this.Lr.maxScrollHeight)!==null&&r!==void 0?r:0),this.Lr.lastContentY=d,this.Lr.maxContentY=Math.max(d,(s=this.Lr.maxContentY)!==null&&s!==void 0?s:0),this.Lr.maxContentHeight=Math.max(p,(i=this.Lr.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=e}getContext(){return this.Lr}resetContext(){var e=this.Lr;return setTimeout(this.jr,0),e}startMeasuringScrollPosition(){Cn(ve,"scroll",this.jr,{capture:!0}),Cn(ve,"scrollend",this.jr,{capture:!0}),Cn(ve,"resize",this.jr)}scrollElement(){if(!this._instance.config.scroll_root_selector)return ve?.document.documentElement;var e=dn(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var n of e){var r=ve?.document.querySelector(n);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return ve&&(ve.scrollY||ve.pageYOffset||ve.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return ve&&(ve.scrollX||ve.pageXOffset||ve.document.documentElement.scrollLeft)||0}}var M_e=t=>k9(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties);class EI{constructor(e,n,r,s){this.Nr=i=>{var o=this.Ur();if(!o||o.sessionId!==i){var c={sessionId:i,props:this.zr(this._instance)};this.qr.register({[z1]:c})}},this._instance=e,this.Br=n,this.qr=r,this.zr=s||M_e,this.Br.onSessionId(this.Nr)}Ur(){return this.qr.props[z1]}getSetOnceProps(){var e,n=(e=this.Ur())==null?void 0:e.props;return n?"r"in n?C9(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return tn(FC(this.getSetOnceProps()),(n,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+T1(r)]=n}),e}}var Ew=or("[SessionId]");class kI{constructor(e,n,r){var s;if(this.Hr=[],this.Wr=(p,m)=>Math.abs(p-m)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.A=e.config,this.qr=e.persistence,this.pi=void 0,this.Ft=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Gr=n||jo,this.Vr=r||jo;var i=this.A.persistence_name||this.A.token,o=this.A.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Ts(o,60,36e3,Ew.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Jr(),this.Kr="ph_"+i+"_window_id",this.Yr="ph_"+i+"_primary_window_exists",this.Xr()){var c=Sr.K(this.Kr),u=Sr.K(this.Yr);c&&!u?this.pi=c:Sr.X(this.Kr),Sr.Y(this.Yr,!0)}if((s=this.A.bootstrap)!=null&&s.sessionID)try{var d=(p=>{var m=p.replace(/-/g,"");if(m.length!==32)throw new Error("Not a valid UUID");if(m[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(m.substring(0,12),16)})(this.A.bootstrap.sessionID);this.Qr(this.A.bootstrap.sessionID,new Date().getTime(),d)}catch(p){Ew.error("Invalid sessionID in bootstrap",p)}this.Zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return Oe(this.Hr)&&(this.Hr=[]),this.Hr.push(e),this.Ft&&e(this.Ft,this.pi),()=>{this.Hr=this.Hr.filter(n=>n!==e)}}Xr(){return this.A.persistence!=="memory"&&!this.qr.je&&Sr.G()}ts(e){e!==this.pi&&(this.pi=e,this.Xr()&&Sr.Y(this.Kr,e))}es(){return this.pi?this.pi:this.Xr()?Sr.K(this.Kr):null}Qr(e,n,r){e===this.Ft&&n===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.Ft=e,this.qr.register({[Av]:[n,e,r]}))}rs(){if(this.Ft&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this.Ft,this._sessionStartTimestamp];var e=this.qr.props[Av];return dn(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Qr(null,null,null)}Zr(){Cn(ve,"beforeunload",()=>{this.Xr()&&Sr.X(this.Yr)},{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.A.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),[s,i,o]=this.rs(),c=this.es(),u=Nr(o)&&o>0&&Math.abs(r-o)>864e5,d=!1,p=!i,m=!e&&this.Wr(r,s);p||m||u?(i=this.Gr(),c=this.Vr(),Ew.info("new session ID generated",{sessionId:i,windowId:c,changeReason:{noSessionId:p,activityTimeout:m,sessionPastMaximumLength:u}}),o=r,d=!0):c||(c=this.Vr(),d=!0);var v=s===0||!e||u?r:s,y=o===0?new Date().getTime():o;return this.ts(c),this.Qr(i,v,y),e||this.Jr(),d&&this.Hr.forEach(x=>x(i,c,d?{noSessionId:p,activityTimeout:m,sessionPastMaximumLength:u}:void 0)),{sessionId:i,windowId:c,sessionStartTimestamp:y,changeReason:d?{noSessionId:p,activityTimeout:m,sessionPastMaximumLength:u}:void 0,lastActivityTimestamp:s}}Jr(){clearTimeout(this.ss),this.ss=setTimeout(()=>{var[e]=this.rs();this.Wr(new Date().getTime(),e)&&this.resetSessionId()},1.1*this.sessionTimeoutMs)}}var O_e=["$set_once","$set"],_o=or("[SiteApps]");class D_e{constructor(e){this._instance=e,this.ns=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}os(e,n){if(n){var r=this.globalsForEvent(n);this.ns.push(r),this.ns.length>1e3&&(this.ns=this.ns.slice(10))}}get siteAppLoaders(){var e;return(e=st._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Ye(this.os.bind(this));this.ls=()=>{e(),this.ns=[],this.ls=void 0}}}globalsForEvent(e){var n,r,s,i,o,c,u;if(!e)throw new Error("Event payload is required");var d={},p=this._instance.get_property("$groups")||[],m=this._instance.get_property("$stored_group_properties")||{};for(var[v,y]of Object.entries(m))d[v]={id:p[v],type:v,properties:y};var{$set_once:x,$set:_}=e;return{event:Le({},b6(e,O_e),{properties:Le({},e.properties,_?{$set:Le({},(n=(r=e.properties)==null?void 0:r.$set)!==null&&n!==void 0?n:{},_)}:{},x?{$set_once:Le({},(s=(i=e.properties)==null?void 0:i.$set_once)!==null&&s!==void 0?s:{},x)}:{}),elements_chain:(o=(c=e.properties)==null?void 0:c.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(u=e.properties)==null?void 0:u.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:d}}setupSiteApp(e){var n=this.apps[e.id],r=()=>{var c;!n.errored&&this.ns.length&&(_o.info("Processing "+this.ns.length+" events for site app with id "+e.id),this.ns.forEach(u=>n.processEvent==null?void 0:n.processEvent(u)),n.processedBuffer=!0),Object.values(this.apps).every(u=>u.processedBuffer||u.errored)&&((c=this.ls)==null||c.call(this))},s=!1,i=c=>{n.errored=!c,n.loaded=!0,_o.info("Site app with id "+e.id+" "+(c?"loaded":"errored")),s&&r()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:c=>{i(c)}});o&&(n.processEvent=o),s=!0}catch(c){_o.error("Error while initializing PostHog app with config id "+e.id,c),i(!1)}if(s&&n.loaded)try{r()}catch(c){_o.error("Error while processing buffered events PostHog app with config id "+e.id,c),n.errored=!0}}us(){var e=this.siteAppLoaders||[];for(var n of e)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}hs(e){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(n)}catch(s){_o.error("Error while processing event "+e.event+" for site app "+r.id,s)}}}onRemoteConfig(e){var n,r,s,i=this;if((n=this.siteAppLoaders)!=null&&n.length)return this.isEnabled?(this.us(),void this._instance.on("eventCaptured",d=>this.hs(d))):void _o.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.ls)==null||r.call(this),(s=e.siteApps)!=null&&s.length)if(this.isEnabled){var o=function(d){var p;st["__$$ph_site_app_"+d]=i._instance,(p=st.__PosthogExtensions__)==null||p.loadSiteApp==null||p.loadSiteApp(i._instance,u,m=>{if(m)return _o.error("Error while initializing PostHog app with config id "+d,m)})};for(var{id:c,url:u}of e.siteApps)o(c)}else _o.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var I_e=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],CI=function(t,e){if(!t)return!1;var n=t.toLowerCase();return I_e.concat(e||[]).some(r=>{var s=r.toLowerCase();return n.indexOf(s)!==-1})},N9=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&CI(n,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some(s=>CI(s?.brand,e)))return!0}catch{}return!!t.webdriver},Xf=function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t}({}),TI="i.posthog.com";class L_e{constructor(e){this.ds={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+TI,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.ds[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.ds[this.apiHost]=Xf.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.ds[this.apiHost]=Xf.EU:this.ds[this.apiHost]=Xf.CUSTOM),this.ds[this.apiHost]}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(this.region===Xf.CUSTOM)return this.apiHost+n;var r=TI+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}var z_e={icontains:(t,e)=>!!ve&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!ve&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!ve&&Xu(e.href,t),not_regex:(t,e)=>!!ve&&!Xu(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t};class Rr{constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments(s=>{Rr.vs("retrieved web experiments from the server"),n.cs=new Map,s.forEach(i=>{if(i.feature_flag_key){var o;n.cs&&(Rr.vs("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=n.cs)==null||o.set(i.feature_flag_key,i));var c=n._instance.getFeatureFlag(i.feature_flag_key);In(c)&&i.variants[c]&&n.fs(i.name,c,i.variants[c].transforms)}else if(i.variants)for(var u in i.variants){var d=i.variants[u];Rr.ps(d)&&n.fs(i.name,u,d.transforms)}})},r)},this._instance=e,this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}onFeatureFlags(e){if(this._is_bot())Rr.vs("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(Ot(this.cs))return this.cs=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Rr.vs("applying feature flags",e),e.forEach(n=>{var r;if(this.cs&&(r=this.cs)!=null&&r.has(n)){var s,i=this._instance.getFeatureFlag(n),o=(s=this.cs)==null?void 0:s.get(n);i&&o!=null&&o.variants[i]&&this.fs(o.name,i,o.variants[i].transforms)}})}}previewWebExperiment(){var e=Rr.getWindowLocation();if(e!=null&&e.search){var n=Mv(e?.search,"__experiment_id"),r=Mv(e?.search,"__experiment_variant");n&&r&&(Rr.vs("previewing web experiments "+n+" && "+r),this.getWebExperiments(s=>{this.gs(parseInt(n),r,s)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var s=this._instance.get_property("$web_experiments");if(s&&!n)return e(s);this._instance.Te({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:i=>{if(i.statusCode!==200||!i.json)return e([]);var o=i.json.experiments||[];return e(o)}})}gs(e,n,r){var s=r.filter(i=>i.id===e);s&&s.length>0&&(Rr.vs("Previewing web experiment ["+s[0].name+"] with variant ["+n+"]"),this.fs(s[0].name,n,s[0].variants[n].transforms))}static ps(e){return!Ot(e.conditions)&&Rr._s(e)&&Rr.ys(e)}static _s(e){var n;if(Ot(e.conditions)||Ot((n=e.conditions)==null?void 0:n.url))return!0;var r,s,i,o=Rr.getWindowLocation();return!!o&&((r=e.conditions)==null||!r.url||z_e[(s=(i=e.conditions)==null?void 0:i.urlMatchType)!==null&&s!==void 0?s:"icontains"](e.conditions.url,o))}static getWindowLocation(){return ve?.location}static ys(e){var n;if(Ot(e.conditions)||Ot((n=e.conditions)==null?void 0:n.utm))return!0;var r=_9();if(r.utm_source){var s,i,o,c,u,d,p,m,v=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,y=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((c=e.conditions)==null||(c=c.utm)==null?void 0:c.utm_source)==r.utm_source,x=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_medium||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_medium)==r.utm_medium,_=(p=e.conditions)==null||(p=p.utm)==null||!p.utm_term||((m=e.conditions)==null||(m=m.utm)==null?void 0:m.utm_term)==r.utm_term;return v&&x&&_&&y}return!1}static vs(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];Ve.info("[WebExperiments] "+e,r)}fs(e,n,r){this._is_bot()?Rr.vs("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?r.forEach(s=>{if(s.selector){var i;Rr.vs("applying transform of variant "+n+" for experiment "+e+" ",s);var o=(i=document)==null?void 0:i.querySelectorAll(s.selector);o?.forEach(c=>{var u=c;s.html&&(u.innerHTML=s.html),s.css&&u.setAttribute("style",s.css)})}}):Rr.vs("Control variants leave the page unmodified.")}_is_bot(){return Cs&&this._instance?N9(Cs,this._instance.config.custom_blocked_useragents):void 0}}var $_e=or("[PostHog ExternalIntegrations]"),F_e={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class U_e{constructor(e){this._instance=e}nt(e,n){var r;(r=st.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,s=>{if(s)return $_e.error("failed to load script",s);n()})}startIfEnabledOrStop(){var e=this,n=function(o){var c,u,d;!s||(c=st.__PosthogExtensions__)!=null&&(c=c.integrations)!=null&&c[o]||e.nt(F_e[o],()=>{var p;(p=st.__PosthogExtensions__)==null||(p=p.integrations)==null||(p=p[o])==null||p.start(e._instance)}),!s&&(u=st.__PosthogExtensions__)!=null&&(u=u.integrations)!=null&&u[o]&&((d=st.__PosthogExtensions__)==null||(d=d.integrations)==null||(d=d[o])==null||d.stop())};for(var[r,s]of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;n(r)}}}var tE="[SessionRecording]",Rf=or(tE);class V_e{get started(){var e;return!((e=this.bs)==null||!e.isStarted)}get status(){var e;return((e=this.bs)==null?void 0:e.status)||"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.ni=void 0,this._instance=e,!this._instance.sessionManager)throw Rf.error("started without valid sessionManager"),new Error(tE+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(tE+' cannot be used with cookieless_mode="always"')}get qt(){var e,n=!((e=this._instance.get_property(hw))==null||!e.enabled),r=!this._instance.config.disable_session_recording,s=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return ve&&n&&r&&!s}startIfEnabledOrStop(e){var n;if(!this.qt||(n=this.bs)==null||!n.isStarted){var r=!Oe(Object.assign)&&!Oe(Array.from);this.qt&&r?(this.ws(e),Rf.info("starting")):this.stopRecording()}}ws(e){var n,r,s;this.qt&&(st!=null&&(n=st.__PosthogExtensions__)!=null&&(n=n.rrweb)!=null&&n.record&&(r=st.__PosthogExtensions__)!=null&&r.initSessionRecording?this.Pi(e):(s=st.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,this.Ii,i=>{if(i)return Rf.error("could not load recorder",i);this.Pi(e)}))}stopRecording(){var e;(e=this.bs)==null||e.stop()}ki(){var e;(e=this._instance.persistence)==null||e.unregister(gu)}Ei(e){if(this._instance.persistence){var n,r,s=this._instance.persistence,i=()=>{var o=e.sessionRecording,c=o?.sampleRate,u=Ot(c)?null:parseFloat(c);Ot(u)&&this.ki();var d=o?.minimumDurationMilliseconds;s.register({[hw]:Le({enabled:!!o},o,{networkPayloadCapture:Le({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:Oe(d)?null:d,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};i(),(n=this.ni)==null||n.call(this),this.ni=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(i)}}onRemoteConfig(e){"sessionRecording"in e?(this.Ei(e),this.startIfEnabledOrStop()):Rf.info("skipping remote config with no sessionRecording",e)}log(e,n){var r;n===void 0&&(n="log"),(r=this.bs)!=null&&r.log?this.bs.log(e,n):Rf.warn("log called before recorder was ready")}get Ii(){var e,n,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(hw);return(r==null||(n=r.scriptConfig)==null?void 0:n.script)||"lazy-recorder"}Pi(e){var n,r;if((n=st.__PosthogExtensions__)==null||!n.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.bs||(this.bs=(r=st.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.bs._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.bs.start(e)}onRRwebEmit(e){var n;(n=this.bs)==null||n.onRRwebEmit==null||n.onRRwebEmit(e)}overrideLinkedFlag(){var e;(e=this.bs)==null||e.overrideLinkedFlag()}overrideSampling(){var e;(e=this.bs)==null||e.overrideSampling()}overrideTrigger(e){var n;(n=this.bs)==null||n.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.bs)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,n){var r;return!((r=this.bs)==null||!r.tryAddCustomEvent(e,n))}}var gh={},nE=()=>{},iu="posthog",j9=!n_e&&es?.indexOf("MSIE")===-1&&es?.indexOf("Mozilla")===-1,AI=t=>{var e;return{api_host:"https://us.i.posthog.com",ui_host:null,token:"",autocapture:!0,rageclick:!0,cross_subdomain_cookie:W0e(Be?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:nE,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageview:t!=="2025-05-24"||"history_change",capture_pageleave:"if_capture_pageview",defaults:t??"unset",debug:ts&&In(ts?.search)&&ts.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(ve==null||(e=ve.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,session_recording:{},mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:n=>{var r="Bad HTTP status: "+n.statusCode+" "+n.text;Ve.error(r)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:eE},error_tracking:{},_onCapture:nE,__preview_eager_load_replay:!0}},RI=t=>{var e={};Oe(t.process_person)||(e.person_profiles=t.process_person),Oe(t.xhr_headers)||(e.request_headers=t.xhr_headers),Oe(t.cookie_name)||(e.persistence_name=t.cookie_name),Oe(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),Oe(t.store_google)||(e.save_campaign_params=t.store_google),Oe(t.verbose)||(e.debug=t.verbose);var n=Bn({},e,t);return dn(t.property_blacklist)&&(Oe(t.property_denylist)?n.property_denylist=t.property_blacklist:dn(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:Ve.error("Invalid value for property_denylist config: "+t.property_denylist)),n};class B_e{constructor(){this.__forceAllowLocalhost=!1}get Ss(){return this.__forceAllowLocalhost}set Ss(e){Ve.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ky{get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new B_e,this.ks=!1,this.version=ka.LIB_VERSION,this.$s=new R9,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=AI(),this.SentryIntegration=Gbe,this.sentryIntegration=e=>function(n,r){var s=r9(n,r);return{name:n9,processEvent:i=>s(i)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.xs=!1,this.Es=null,this.Ps=null,this.Is=null,this.featureFlags=new b_e(this),this.toolbar=new Wbe(this),this.scrollManager=new P_e(this),this.pageViewManager=new e_e(this),this.surveys=new C_e(this),this.experiments=new Rr(this),this.exceptions=new r_e(this),this.rateLimiter=new T_e(this),this.requestRouter=new L_e(this),this.consent=new gbe(this),this.externalIntegrations=new U_e(this),this.people={set:(e,n,r)=>{var s=In(e)?{[e]:n}:e;this.setPersonProperties(s),r?.({})},set_once:(e,n,r)=>{var s=In(e)?{[e]:n}:e;this.setPersonProperties(void 0,s),r?.({})}},this.on("eventCaptured",e=>Ve.info('send "'+e?.event+'"',e))}init(e,n,r){if(r&&r!==iu){var s,i=(s=gh[r])!==null&&s!==void 0?s:new Ky;return i._init(e,n,r),gh[r]=i,gh[iu][r]=i,i}return this._init(e,n,r)}_init(e,n,r){var s,i;if(n===void 0&&(n={}),Oe(e)||A1(e))return Ve.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return Ve.warn("You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},this.Rs=n,this.Ts=[],n.person_profiles&&(this.Ps=n.person_profiles),this.set_config(Bn({},AI(n.defaults),RI(n),{name:r,token:e})),this.config.on_xhr_error&&Ve.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ta.GZipJS;var o=this.Cs();this.persistence=new ww(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ww(Le({},this.config,{persistence:"sessionStorage"}),o);var c=Le({},this.persistence.props),u=Le({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Ms=new R_e(C=>this.Os(C),this.config.request_queue_config),this.Fs=new j_e(this),this.__request_queue=[];var d=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(d||(this.sessionManager=new kI(this),this.sessionPropsManager=new EI(this,this.sessionManager,this.persistence)),new Qbe(this).startIfEnabledOrStop(),this.siteApps=new D_e(this),(s=this.siteApps)==null||s.init(),d||(this.config.__preview_eager_load_replay?this.sessionRecording=new aI(this):this.sessionRecording=new V_e(this),this.sessionRecording.startIfEnabledOrStop()),this.config.disable_scroll_properties||this.scrollManager.startMeasuringScrollPosition(),this.autocapture=new lbe(this),this.autocapture.startIfEnabled(),this.surveys.loadIfEnabled(),this.heatmaps=new Jbe(this),this.heatmaps.startIfEnabled(),this.webVitalsAutocapture=new Xbe(this),this.exceptionObserver=new xbe(this),this.exceptionObserver.startIfEnabled(),this.deadClicksAutocapture=new G6(this,ybe),this.deadClicksAutocapture.startIfEnabled(),this.historyAutocapture=new bbe(this),this.historyAutocapture.startIfEnabled(),ka.DEBUG=ka.DEBUG||this.config.debug,ka.DEBUG&&Ve.info("Starting in debug mode",{this:this,config:n,thisC:Le({},this.config),p:c,s:u}),((i=n.bootstrap)==null?void 0:i.distinctID)!==void 0){var p,m,v=this.config.get_device_id(jo()),y=(p=n.bootstrap)!=null&&p.isIdentifiedID?v:n.bootstrap.distinctID;this.persistence.set_property(_a,(m=n.bootstrap)!=null&&m.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.bootstrap.distinctID,$device_id:y})}if(this.As()){var x,_,E=Object.keys(((x=n.bootstrap)==null?void 0:x.featureFlags)||{}).filter(C=>{var R;return!((R=n.bootstrap)==null||(R=R.featureFlags)==null||!R[C])}).reduce((C,R)=>{var j;return C[R]=((j=n.bootstrap)==null||(j=j.featureFlags)==null?void 0:j[R])||!1,C},{}),S=Object.keys(((_=n.bootstrap)==null?void 0:_.featureFlagPayloads)||{}).filter(C=>E[C]).reduce((C,R)=>{var j,T;return(j=n.bootstrap)!=null&&(j=j.featureFlagPayloads)!=null&&j[R]&&(C[R]=(T=n.bootstrap)==null||(T=T.featureFlagPayloads)==null?void 0:T[R]),C},{});this.featureFlags.receivedFeatureFlags({featureFlags:E,featureFlagPayloads:S})}if(d)this.register_once({distinct_id:Sf,$device_id:null},"");else if(!this.get_distinct_id()){var A=this.config.get_device_id(jo());this.register_once({distinct_id:A,$device_id:A},""),this.persistence.set_property(_a,"anonymous")}return Cn(ve,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),n.segment?Hbe(this,()=>this.Ds()):this.Ds(),Xs(this.config._onCapture)&&this.config._onCapture!==nE&&(Ve.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",C=>this.config._onCapture(C.event,C))),this.config.ip&&Ve.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}Ce(e){var n,r,s,i,o,c,u,d;if(!Be||!Be.body)return Ve.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.Ce(e)},500);this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=Ct(e.supportedCompression,Ta.GZipJS)?Ta.GZipJS:Ct(e.supportedCompression,Ta.Base64)?Ta.Base64:void 0),(n=e.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Ps?this.Ps:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(s=this.sessionRecording)==null||s.onRemoteConfig(e),(i=this.autocapture)==null||i.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),(c=this.webVitalsAutocapture)==null||c.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(d=this.deadClicksAutocapture)==null||d.onRemoteConfig(e)}Ds(){try{this.config.loaded(this)}catch(e){Ve.critical("`loaded` function failed",e)}this.js(),this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Ls()},1),new A_e(this).load(),this.featureFlags.flags()}js(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Ms)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Po(this.__request_queue,e=>this.Os(e)),this.__request_queue=[],this.js()}_handle_unload(){var e,n;this.config.request_batching?(this.Ns()&&this.capture("$pageleave"),(e=this.Ms)==null||e.unload(),(n=this.Fs)==null||n.unload()):this.Ns()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}Te(e){this.__loaded&&(j9?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=Fv(e.url,{ip:this.config.ip?1:0}),e.headers=Le({},this.config.request_headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var r,s,i,o=Le({},n);o.timeout=o.timeout||6e4,o.url=Fv(o.url,{_:new Date().getTime().toString(),ver:ka.LIB_VERSION,compression:o.compression});var c=(r=o.transport)!==null&&r!==void 0?r:"fetch",u=Rg.filter(p=>!o.disableTransport||!p.transport||!o.disableTransport.includes(p.transport)),d=(s=(i=A6(u,p=>p.transport===c))==null?void 0:i.method)!==null&&s!==void 0?s:u[0].method;if(!d)throw new Error("No available transport method");d(o)})(Le({},e,{callback:n=>{var r,s;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((r=(s=this.config).on_request_error)==null||r.call(s,n)),e.callback==null||e.callback(n)}}))))}Os(e){this.Fs?this.Fs.retriableRequest(e):this.Te(e)}_execute_array(e){var n,r=[],s=[],i=[];Po(e,c=>{c&&(n=c[0],dn(n)?i.push(c):Xs(c)?c.call(this):dn(c)&&n==="alias"?r.push(c):dn(c)&&n.indexOf("capture")!==-1&&Xs(this[n])?i.push(c):s.push(c))});var o=function(c,u){Po(c,function(d){if(dn(d[0])){var p=u;tn(d,function(m){p=p[m[0]].apply(p,m.slice(1))})}else this[d[0]].apply(this,d.slice(1))},u)};o(r,this),o(s,this),o(i,this)}As(){var e,n;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((n=this.config.bootstrap)==null?void 0:n.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,n,r){var s;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Ms){if(this.is_capturing())if(!Oe(e)&&In(e)){if(this.config.opt_out_useragent_filter||!this._is_bot()){var i=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){n!=null&&n.$current_url&&!In(n?.$current_url)&&(Ve.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var o=new Date,c=r?.timestamp||o,u=jo(),d={uuid:u,event:e,properties:this.calculateEventProperties(e,n||{},c,u)};i&&(d.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),r?.$set&&(d.$set=r?.$set);var p,m=this.Us(r?.$set_once);if(m&&(d.$set_once=m),(d=G0e(d,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=c,Oe(r?.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=o),e===Ng.DISMISSED||e===Ng.SENT){var v=n?.[_I.SURVEY_ID],y=n?.[_I.SURVEY_ITERATION];p={id:v,current_iteration:y},localStorage.getItem(wI(p))||localStorage.setItem(wI(p),"true"),d.$set=Le({},d.$set,{[w_e({id:v,current_iteration:y},e===Ng.SENT?"responded":"dismissed")]:!0})}var x=Le({},d.properties.$set,d.$set);if(mu(x)||this.setPersonPropertiesForFlags(x),!Ot(this.config.before_send)){var _=this.zs(d);if(!_)return;d=_}this.$s.emit("eventCaptured",d);var E={method:"POST",url:(s=r?._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:d,compression:"best-available",batchKey:r?._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Os(E):this.Ms.enqueue(E),d}Ve.critical("This capture call is ignored due to client rate limiting.")}}else Ve.error("No event name provided to posthog.capture")}else Ve.uninitializedWarning("posthog.capture")}Ye(e){return this.on("eventCaptured",n=>e(n.event,n))}calculateEventProperties(e,n,r,s,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var o=i?void 0:this.persistence.remove_event_timer(e),c=Le({},n);if(c.token=this.config.token,c.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(c.$cookieless_mode=!0),e==="$snapshot"){var u=Le({},this.persistence.properties(),this.sessionPersistence.properties());return c.distinct_id=u.distinct_id,(!In(c.distinct_id)&&!Nr(c.distinct_id)||A1(c.distinct_id))&&Ve.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),c}var d,p=v_e(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:m,windowId:v}=this.sessionManager.checkAndGetSessionAndWindowId(i,r.getTime());c.$session_id=m,c.$window_id=v}this.sessionPropsManager&&Bn(c,this.sessionPropsManager.getSessionProps());try{var y;this.sessionRecording&&Bn(c,this.sessionRecording.sdkDebugProperties),c.$sdk_debug_retry_queue_size=(y=this.Fs)==null?void 0:y.length}catch(S){c.$sdk_debug_error_capturing_properties=String(S)}if(this.requestRouter.region===Xf.CUSTOM&&(c.$lib_custom_api_host=this.config.api_host),d=e!=="$pageview"||i?e!=="$pageleave"||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,s),c=Bn(c,d),e==="$pageview"&&Be&&(c.title=Be.title),!Oe(o)){var x=r.getTime()-o;c.$duration=parseFloat((x/1e3).toFixed(3))}es&&this.config.opt_out_useragent_filter&&(c.$browser_type=this._is_bot()?"bot":"browser"),(c=Bn({},p,this.persistence.properties(),this.sessionPersistence.properties(),c)).$is_identified=this._isIdentified(),dn(this.config.property_denylist)?tn(this.config.property_denylist,function(S){delete c[S]}):Ve.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var _=this.config.sanitize_properties;_&&(Ve.error("sanitize_properties is deprecated. Use before_send instead"),c=_(c,e));var E=this.qs();return c.$process_person_profile=E,E&&!i&&this.Bs("_calculate_event_properties"),c}Us(e){var n;if(!this.persistence||!this.qs()||this.ks)return e;var r=this.persistence.get_initial_props(),s=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),i=Bn({},r,s||{},e||{}),o=this.config.sanitize_properties;return o&&(Ve.error("sanitize_properties is deprecated. Use before_send instead"),i=o(i,"$set_once")),this.ks=!0,mu(i)?void 0:i}register(e,n){var r;(r=this.persistence)==null||r.register(e,n)}register_once(e,n,r){var s;(s=this.persistence)==null||s.register_once(e,n,r)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e)}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e)}Hs(e,n){this.register({[e]:n})}getFeatureFlag(e,n){return this.featureFlags.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(n)}catch{return n}}isFeatureEnabled(e,n){return this.featureFlags.isFeatureEnabled(e,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,n,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,n,r)}getEarlyAccessFeatures(e,n,r){return n===void 0&&(n=!1),this.featureFlags.getEarlyAccessFeatures(e,n,r)}on(e,n){return this.$s.on(e,n)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var n,r;return(n=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys.getSurveys(e,n)}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys.getActiveMatchingSurveys(e,n)}renderSurvey(e,n){this.surveys.renderSurvey(e,n)}displaySurvey(e,n){n===void 0&&(n=E_e),this.surveys.displaySurvey(e,n)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,n){return n===void 0&&(n=!1),this.surveys.canRenderSurveyAsync(e,n)}identify(e,n,r){if(!this.__loaded||!this.persistence)return Ve.uninitializedWarning("posthog.identify");if(Nr(e)&&(e=e.toString(),Ve.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))Ve.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Sf){if(this.Bs("posthog.identify")){var s=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var i=s;this.register_once({$had_persisted_distinct_id:!0,$device_id:i},"")}e!==s&&e!==this.get_property(qf)&&(this.unregister(qf),this.register({distinct_id:e}));var o=(this.persistence.get_property(_a)||"anonymous")==="anonymous";e!==s&&o?(this.persistence.set_property(_a,"identified"),this.setPersonPropertiesForFlags(Le({},r||{},n||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:s},{$set:n||{},$set_once:r||{}}),this.Is=fI(e,n,r),this.featureFlags.setAnonymousDistinctId(s)):(n||r)&&this.setPersonProperties(n,r),e!==s&&(this.reloadFeatureFlags(),this.unregister(Rv))}}else Ve.critical('The string "'+Sf+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else Ve.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,n){if((e||n)&&this.Bs("posthog.setPersonProperties")){var r=fI(this.get_distinct_id(),e,n);this.Is!==r?(this.setPersonPropertiesForFlags(Le({},n||{},e||{})),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Is=r):Ve.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,n,r){if(e&&n){if(this.Bs("posthog.group")){var s=this.getGroups();s[e]!==n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:Le({},s,{[e]:n})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:n,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),s[e]===n||r||this.reloadFeatureFlags()}}else Ve.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0),this.featureFlags.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0),this.Bs("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,n)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var n,r,s,i;if(Ve.info("reset"),!this.__loaded)return Ve.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(s=this.persistence)==null||s.set_property(_a,"anonymous"),(i=this.sessionManager)==null||i.resetSessionId(),this.Is=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Sf,$device_id:null},"");else{var c=this.config.get_device_id(jo());this.register_once({distinct_id:c,$device_id:e?c:o},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(e!=null&&e.withTimestamp&&r){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return s}alias(e,n){return e===this.get_property(R6)?(Ve.critical("Attempting to create alias for existing People user - aborting."),-2):this.Bs("posthog.alias")?(Oe(n)&&(n=this.get_distinct_id()),e!==n?(this.Hs(qf,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(Ve.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=Le({},this.config);if(Dn(e)){var r,s,i,o,c;Bn(this.config,RI(e));var u=this.Cs();(r=this.persistence)==null||r.update_config(this.config,n,u),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new ww(Le({},this.config,{persistence:"sessionStorage"}),u),rr.G()&&rr.J("ph_debug")==="true"&&(this.config.debug=!0),this.config.debug&&(ka.DEBUG=!0,Ve.info("set_config",{config:e,oldConfig:n,newConfig:Le({},this.config)})),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),(i=this.autocapture)==null||i.startIfEnabled(),(o=this.heatmaps)==null||o.startIfEnabled(),this.surveys.loadIfEnabled(),this.Ws(),(c=this.externalIntegrations)==null||c.startIfEnabledOrStop()}}startSessionRecording(e){var n=e===!0,r={sampling:n||!(e==null||!e.sampling),linked_flag:n||!(e==null||!e.linked_flag),url_trigger:n||!(e==null||!e.url_trigger),event_trigger:n||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var s,i,o,c,u;(s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),r.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),r.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),r.url_trigger&&((c=this.sessionRecording)==null||c.overrideTrigger("url")),r.event_trigger&&((u=this.sessionRecording)==null||u.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){var r=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(Le({},s,n))}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:iu;return n!==iu&&(n=iu+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(_a))==="identified"||((n=this.sessionPersistence)==null?void 0:n.get_property(_a))==="identified"}qs(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&mu(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[qf])&&((n=this.persistence)==null||(n=n.props)==null||!n[jv]))}Ns(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.qs()||this.Bs("posthog.createPersonProfile")&&this.setPersonProperties({},{})}Bs(e){return this.config.person_profiles==="never"?(Ve.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Hs(jv,!0),!0)}Cs(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),n=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!n}Ws(){var e,n,r,s,i=this.Cs();return((e=this.persistence)==null?void 0:e.je)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((n=this.sessionPersistence)==null?void 0:n.je)!==i&&((s=this.sessionPersistence)==null||s.set_disabled(i)),i}opt_in_capturing(e){if(this.config.cookieless_mode!=="always"){var n;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),this.sessionManager=new kI(this),this.persistence&&(this.sessionPropsManager=new EI(this,this.sessionManager,this.persistence)),this.sessionRecording=new aI(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Ws(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(Oe(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((n=e?.captureEventName)!==null&&n!==void 0?n:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Ls()}else Ve.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Ws(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Sf,$device_id:null}),this.sessionManager=void 0,this.sessionPropsManager=void 0,(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,this.Ls())):Ve.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===wa.GRANTED?"granted":e===wa.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Ws()}_is_bot(){return Cs?N9(Cs,this.config.custom_blocked_useragents):void 0}Ls(){Be&&(Be.visibilityState==="visible"?this.xs||(this.xs=!0,this.capture("$pageview",{title:Be.title},{send_instantly:!0}),this.Es&&(Be.removeEventListener("visibilitychange",this.Es),this.Es=null)):this.Es||(this.Es=this.Ls.bind(this),Cn(Be,"visibilitychange",this.Es)))}debug(e){e===!1?(ve?.console.log("You've disabled debug mode."),localStorage&&localStorage.removeItem("ph_debug"),this.set_config({debug:!1})):(ve?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),localStorage&&localStorage.setItem("ph_debug","true"),this.set_config({debug:!0}))}L(){var e,n,r,s,i,o,c,u=this.Rs||{};return"advanced_disable_flags"in u?!!u.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Ve.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(r="advanced_disable_decide",s=!1,i=Ve,o=(n="advanced_disable_flags")in(e=u)&&!Oe(e[n]),c=r in e&&!Oe(e[r]),o?e[n]:c?(i&&i.warn("Config field '"+r+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),e[r]):s)}zs(e){if(Ot(this.config.before_send))return e;var n=dn(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var s of n){if(r=s(r),Ot(r)){var i="Event '"+e.event+"' was rejected in beforeSend function";return b0e(e.event)?Ve.warn(i+". This can cause unexpected behavior."):Ve.info(i),null}r.properties&&!mu(r.properties)||Ve.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.fe)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(r)})}}(function(t,e){for(var n=0;n<e.length;n++)t.prototype[e[n]]=H0e(t.prototype[e[n]])})(Ky,["identify"]);var NI,au=(NI=gh[iu]=new Ky,function(){function t(){t.done||(t.done=!0,j9=!1,tn(gh,function(e){e._dom_loaded()}))}Be!=null&&Be.addEventListener?Be.readyState==="complete"?t():Cn(Be,"DOMContentLoaded",t,{capture:!1}):ve&&Ve.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),NI),P9=w.createContext({client:au});function M9(t,e,n){if(n===void 0&&(n=new WeakMap),t===e)return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;if(n.has(t)&&n.get(t)===e)return!0;n.set(t,e);var r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(var i=0,o=r;i<o.length;i++){var c=o[i];if(!s.includes(c)||!M9(t[c],e[c],n))return!1}return!0}function q_e(t){var e=t.children,n=t.client,r=t.apiKey,s=t.options,i=w.useRef(null),o=w.useMemo(function(){return n?(r&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),s&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),n):(r||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),au)},[n,r,JSON.stringify(s)]);return w.useEffect(function(){if(!n){var c=i.current;c?(r!==c.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),s&&!M9(s,c.options)&&au.set_config(s),i.current={apiKey:r,options:s??{}}):(au.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),au.init(r,s),i.current={apiKey:r,options:s??{}})}},[n,r,JSON.stringify(s)]),Ee.createElement(P9.Provider,{value:{client:o}},e)}var rE=function(t,e){return rE=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},rE(t,e)};function H_e(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");rE(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var kw=function(t){return typeof t=="function"},G_e={componentStack:null,exceptionEvent:null,error:null},Y_e={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."};(function(t){H_e(e,t);function e(n){var r=t.call(this,n)||this;return r.state=G_e,r}return e.prototype.componentDidCatch=function(n,r){var s=this.props.additionalProperties,i;kw(s)?i=s(n):typeof s=="object"&&(i=s);var o=this.context.client,c=o.captureException(n,i),u=r.componentStack;this.setState({error:n,componentStack:u,exceptionEvent:c})},e.prototype.render=function(){var n=this.props,r=n.children,s=n.fallback,i=this.state;if(i.componentStack==null)return kw(r)?r():r;var o=kw(s)?Ee.createElement(s,{error:i.error,componentStack:i.componentStack,exceptionEvent:i.exceptionEvent}):s;return Ee.isValidElement(o)?o:(console.warn(Y_e.INVALID_FALLBACK),Ee.createElement(Ee.Fragment,null))},e.contextType=P9,e})(Ee.Component);function W_e({children:t,client:e,useAuth:n}){const r=K_e(n);return f.jsx(Kge,{client:e,useAuth:r,children:t})}function K_e(t){return w.useMemo(()=>function(){const{isLoading:n,user:r,getAccessToken:s}=t(),i=w.useCallback(async()=>{try{return await s()}catch{return null}},[s]);return w.useMemo(()=>({isLoading:n,isAuthenticated:!!r,fetchAccessToken:i}),[n,r,i])},[t])}const Q_e="https://outstanding-fennec-304.convex.cloud",X_e="client_01K4C1TVPBE7JTBFQJF9SDW9P9",Z_e=(()=>{const t="mcpjam://oauth/callback";return typeof window>"u"?t:window.location.protocol==="http:"||window.location.protocol==="https:"?`${window.location.origin}/callback`:t})(),J_e=new $ge(Q_e),ewe=YB.createRoot(document.getElementById("root")),twe=f.jsx(qre,{clientId:X_e,redirectUri:Z_e,children:f.jsx(W_e,{client:J_e,useAuth:tc,children:f.jsx(d0e,{})})});ewe.render(f.jsx(w.StrictMode,{children:f.jsx(q_e,{apiKey:m0e(),options:g0e(),children:twe})}));
1840
- //# sourceMappingURL=index-Cya2uzZV.js.map
1840
+ //# sourceMappingURL=index-DPG1329o.js.map