@mcp-use/inspector 0.13.2-canary.0 → 0.13.2
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.
- package/README.md +3 -2
- package/dist/client/assets/{browser-CjAOLOLG.js → browser-DZ15LLaB.js} +3 -3
- package/dist/client/assets/{display-A5IEINAP-CCawiSD1.js → display-A5IEINAP-HkQbiJ2E.js} +2 -2
- package/dist/client/assets/{embeddings-B1NZ17xy.js → embeddings-C0rUXJ5F.js} +1 -1
- package/dist/client/assets/{index-DclCkKwz.js → index-B5kLR_Rv.js} +1 -1
- package/dist/client/assets/{index-DznD3Siw.js → index-BYR-I2bf.js} +1 -1
- package/dist/client/assets/{index-QOx227bY.js → index-CR9w_74S.js} +1 -1
- package/dist/client/assets/{index-C8vT7FsO.js → index-CkHH_UI9.js} +6 -6
- package/dist/client/assets/{index-CN3Oy0EC.js → index-ClpBZU-N.js} +1 -1
- package/dist/client/assets/{index-hi9BvHA1.js → index-DiwCBW8I.js} +1 -1
- package/dist/client/assets/{index-C5-2vkyr.js → index-Dj6Mccu_.js} +1 -1
- package/dist/client/assets/{index-4TL1WWR9.js → index-Zctd0Z8B.js} +1 -1
- package/dist/client/assets/{index-CCasFtk_.js → index-sQyTG4jp.js} +1 -1
- package/dist/client/assets/{llms-C-8mo9aG.js → llms-BDMth6TQ.js} +1 -1
- package/dist/client/assets/{path-BvasDz8_.js → path-BOQPmbms.js} +1 -1
- package/dist/client/assets/{winston-s0jZ6WoA.js → winston-CEUa9Wj-.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/middleware.d.ts +2 -2
- package/package.json +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/winston-
|
|
2
|
-
var sJ=Object.defineProperty;var lJ=(e,t,n)=>t in e?sJ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Uf=(e,t,n)=>lJ(e,typeof t!="symbol"?t+"":t,n);function cJ(e,t){for(var n=0;n<t.length;n++){const a=t[n];if(typeof a!="string"&&!Array.isArray(a)){for(const r in a)if(r!=="default"&&!(r in e)){const i=Object.getOwnPropertyDescriptor(a,r);i&&Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:()=>a[r]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&a(s)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();function ry(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function QTe(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function a(){var r=!1;try{r=this instanceof a}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(a){var r=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:function(){return e[a]}})}),n}var MS={exports:{}},zf={};var lM;function uJ(){if(lM)return zf;lM=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(a,r,i){var s=null;if(i!==void 0&&(s=""+i),r.key!==void 0&&(s=""+r.key),"key"in r){i={};for(var c in r)c!=="key"&&(i[c]=r[c])}else i=r;return r=i.ref,{$$typeof:e,type:a,key:s,ref:r!==void 0?r:null,props:i}}return zf.Fragment=t,zf.jsx=n,zf.jsxs=n,zf}var cM;function dJ(){return cM||(cM=1,MS.exports=uJ()),MS.exports}var f=dJ();const fJ="modulepreload",pJ=function(e){return"/inspector/"+e},uM={},Jn=function(t,n,a){let r=Promise.resolve();if(n&&n.length>0){let u=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),c=s?.nonce||s?.getAttribute("nonce");r=u(n.map(d=>{if(d=pJ(d),d in uM)return;uM[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":fJ,m||(g.as="script"),g.crossOrigin="",g.href=d,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((v,x)=>{g.addEventListener("load",v),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(s){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=s,window.dispatchEvent(c),!c.defaultPrevented)throw s}return r.then(s=>{for(const c of s||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};var mJ=Object.defineProperty,Be=(e,t)=>mJ(e,"name",{value:t,configurable:!0}),Eo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Jc={};async function lF(){if(typeof process<"u")try{const e=await Jn(()=>import("./fs-u42MReIY.js").then(n=>n.f),[]),t=await Jn(()=>import("./path-MNZaYwxc.js").then(n=>n.p),[]);return{fs:e.default,path:t.default}}catch{return{fs:null,path:null}}return{fs:null,path:null}}Be(lF,"getNodeModules");var ha=null;function cF(){if(typeof Eo<"u")try{ha=Eo("winston")}catch{}}Be(cF,"loadWinstonSync");async function uF(){return ha||(ha=await Jn(()=>import("./winston-s0jZ6WoA.js").then(e=>e.w),__vite__mapDeps([0,1,2,3,4,5]))),ha}Be(uF,"getWinston");var r_="mcp-use";function Jb(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"}catch{return!1}}Be(Jb,"isNodeJSEnvironment");var Au,hJ=(Au=class{_level;name;constructor(t=r_,n="info"){this.name=t,this._level=n}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],a=n.indexOf(this._level);return n.indexOf(t)<=a}formatMessage(t,n){return`${new Date().toLocaleTimeString("en-US",{hour12:!1})} [${this.name}] ${t}: ${n}`}error(t){this.shouldLog("error")&&console.error(this.formatMessage("error",t))}warn(t){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",t))}info(t){this.shouldLog("info")&&console.info(this.formatMessage("info",t))}debug(t){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",t))}http(t){this.shouldLog("http")&&console.log(this.formatMessage("http",t))}verbose(t){this.shouldLog("verbose")&&console.log(this.formatMessage("verbose",t))}silly(t){this.shouldLog("silly")&&console.log(this.formatMessage("silly",t))}get level(){return this._level}set level(t){this._level=t}},Be(Au,"SimpleConsoleLogger"),Au);function kb(e){switch((typeof process<"u"&&Jc?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}Be(kb,"resolveLevel");var To,dF=(To=class{static get(t=r_){if(!Jb()){if(!this.simpleInstances[t]){const n=typeof process<"u"&&Jc?.DEBUG||void 0;this.simpleInstances[t]=new hJ(t,kb(n))}return this.simpleInstances[t]}if(!this.instances[t]){if(!ha)throw new Error("Winston not loaded - call Logger.configure() first");const{createLogger:n,format:a}=ha,{combine:r,timestamp:i,label:s,colorize:c,splat:u}=a;this.instances[t]=n({level:kb(Jc.DEBUG),format:r(c(),u(),s({label:t}),i({format:"HH:mm:ss"}),this.getFormatter()),transports:[new ha.transports.Console]})}return this.instances[t]}static getFormatter(){if(!ha)throw new Error("Winston not loaded");const{format:t}=ha,{printf:n}=t,a=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s}: ${c}`),r=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`),i=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`);switch(this.currentFormat){case"minimal":return a;case"detailed":return r;case"emoji":return i;default:return a}}static async configure(t={}){const{level:n,console:a=!0,file:r,format:i="minimal"}=t,s=typeof process<"u"&&Jc?.DEBUG||void 0,c=n??kb(s);if(this.currentFormat=i,!Jb()){Object.values(this.simpleInstances).forEach(w=>{w.level=c});return}if(await uF(),!ha)throw new Error("Failed to load winston");const u=this.get();u.level=c;const d=u;if(d.clear(),a&&d.add(new ha.transports.Console),r){const{fs:w,path:E}=await lF();if(w&&E){const _=E.dirname(E.resolve(r));w.existsSync(_)||w.mkdirSync(_,{recursive:!0}),d.add(new ha.transports.File({filename:r}))}}const{format:m}=ha,{combine:h,timestamp:g,label:v,colorize:x,splat:S}=m;Object.values(this.instances).forEach(w=>{w&&"format"in w&&(w.level=c,w.format=h(x(),S(),v({label:r_}),g({format:"HH:mm:ss"}),this.getFormatter()))})}static setDebug(t){let n;t===2||t===!0?n="debug":n="info",Object.values(this.simpleInstances).forEach(a=>{a.level=n}),Object.values(this.instances).forEach(a=>{a&&(a.level=n)}),typeof process<"u"&&Jc&&(Jc.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},Be(To,"Logger"),Uf(To,"instances",{}),Uf(To,"simpleInstances",{}),Uf(To,"currentFormat","minimal"),To);Jb()&&(cF(),ha&&dF.configure());var Ce=dF.get(),Tb={},fF=typeof globalThis.Deno<"u";function gJ(e){return fF?globalThis.Deno.env.get(e):Tb[e]}Be(gJ,"getEnv");function bJ(){return fF?globalThis.Deno.cwd():process.cwd()}Be(bJ,"getCwd");function El(){return globalThis.crypto.randomUUID()}Be(El,"generateUUID");var vJ="1.11.2-canary.0";function Qb(){return vJ}Be(Qb,"getPackageVersion");var Iu,Ci=(Iu=class{},Be(Iu,"BaseTelemetryEvent"),Iu),Ou,yJ=(Ou=class extends Ci{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},Be(Ou,"MCPAgentExecutionEvent"),Ou);function pF(e,t){const n=Array.from(e.registrations.tools.values()),a=Array.from(e.registrations.prompts.values()),r=Array.from(e.registrations.resources.values()),i=Array.from(e.registrations.resourceTemplates.values()),s=r.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,uri:m.config.uri??null,mime_type:m.config.mimeType??null})),c=s.filter(m=>m.mime_type==="text/html+skybridge"),u=s.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),d=s.filter(m=>m.mime_type==="text/html+mcp");return{transport:t,toolsNumber:e.registeredTools.length,resourcesNumber:e.registeredResources.length,promptsNumber:e.registeredPrompts.length,auth:!!e.oauthProvider,name:e.config.name,description:e.config.description??null,baseUrl:e.serverBaseUrl??null,toolNames:e.registeredTools.length>0?e.registeredTools:null,resourceNames:e.registeredResources.length>0?e.registeredResources:null,promptNames:e.registeredPrompts.length>0?e.registeredPrompts:null,tools:n.length>0?n.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,input_schema:m.config.schema?JSON.stringify(m.config.schema):null,output_schema:m.config.outputSchema?JSON.stringify(m.config.outputSchema):null})):null,resources:s.length>0?s:null,prompts:a.length>0?a.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,args:m.config.args?JSON.stringify(m.config.args):null})):null,templates:i.length>0?i.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:c.length>0?c:null,appsSdkResourcesNumber:c.length,mcpUiResources:u.length>0?u:null,mcpUiResourcesNumber:u.length,mcpAppsResources:d.length>0?d:null,mcpAppsResourcesNumber:d.length}}Be(pF,"createServerRunEventData");var Du,wJ=(Du=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_run"}get properties(){return{transport:this.data.transport,tools_number:this.data.toolsNumber,resources_number:this.data.resourcesNumber,prompts_number:this.data.promptsNumber,auth:this.data.auth,name:this.data.name,description:this.data.description??null,base_url:this.data.baseUrl??null,tool_names:this.data.toolNames??null,resource_names:this.data.resourceNames??null,prompt_names:this.data.promptNames??null,tools:this.data.tools??null,resources:this.data.resources??null,prompts:this.data.prompts??null,templates:this.data.templates??null,capabilities:this.data.capabilities?JSON.stringify(this.data.capabilities):null,apps_sdk_resources:this.data.appsSdkResources?JSON.stringify(this.data.appsSdkResources):null,apps_sdk_resources_number:this.data.appsSdkResourcesNumber??0,mcp_ui_resources:this.data.mcpUiResources?JSON.stringify(this.data.mcpUiResources):null,mcp_ui_resources_number:this.data.mcpUiResourcesNumber??0,mcp_apps_resources:this.data.mcpAppsResources?JSON.stringify(this.data.mcpAppsResources):null,mcp_apps_resources_number:this.data.mcpAppsResourcesNumber??0}}},Be(Du,"ServerRunEvent"),Du),ju,SJ=(ju=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_initialize_call"}get properties(){return{protocol_version:this.data.protocolVersion,client_info:JSON.stringify(this.data.clientInfo),client_capabilities:JSON.stringify(this.data.clientCapabilities),session_id:this.data.sessionId??null}}},Be(ju,"ServerInitializeEvent"),ju),$u,xJ=($u=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_tool_call"}get properties(){return{tool_name:this.data.toolName,length_input_argument:this.data.lengthInputArgument,success:this.data.success,error_type:this.data.errorType??null,execution_time_ms:this.data.executionTimeMs??null}}},Be($u,"ServerToolCallEvent"),$u),Lu,_J=(Lu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_resource_call"}get properties(){return{name:this.data.name,description:this.data.description,contents:this.data.contents,success:this.data.success,error_type:this.data.errorType??null}}},Be(Lu,"ServerResourceCallEvent"),Lu),Mu,EJ=(Mu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_prompt_call"}get properties(){return{name:this.data.name,description:this.data.description,success:this.data.success,error_type:this.data.errorType??null}}},Be(Mu,"ServerPromptCallEvent"),Mu),Pu,kJ=(Pu=class extends Ci{constructor(t){super(),this.data=t}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},Be(Pu,"ServerContextEvent"),Pu),Uu,TJ=(Uu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"mcpclient_init"}get properties(){return{code_mode:this.data.codeMode,sandbox:this.data.sandbox,all_callbacks:this.data.allCallbacks,verify:this.data.verify,servers:this.data.servers,num_servers:this.data.numServers,is_browser:this.data.isBrowser}}},Be(Uu,"MCPClientInitEvent"),Uu),zu,NJ=(zu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"connector_init"}get properties(){return{connector_type:this.data.connectorType,server_command:this.data.serverCommand??null,server_args:this.data.serverArgs??null,server_url:this.data.serverUrl??null,public_identifier:this.data.publicIdentifier??null}}},Be(zu,"ConnectorInitEvent"),zu),Fu,CJ=(Fu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,a=n.url;return{server_name:t,server_url_domain:a?this._extractHostname(a):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},Be(Fu,"ClientAddServerEvent"),Fu),Bu,RJ=(Bu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},Be(Bu,"ClientRemoveServerEvent"),Bu);function mF(e){return e._llm_type||e.constructor.name.toLowerCase()}Be(mF,"getModelProvider");function hF(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}Be(hF,"getModelName");function AJ(e){return[mF(e),hF(e)]}Be(AJ,"extractModelInfo");function Nb(){if(typeof window<"u"&&window.crypto&&typeof window.crypto.getRandomValues=="function"){const e=new Uint8Array(8);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}try{return Eo("crypto").randomBytes(8).toString("hex")}catch{return Math.random().toString(36).substring(2,15)}}Be(Nb,"secureRandomString");var dM="mcp_use_user_id";function gF(){try{return typeof globalThis.Bun<"u"?"bun":typeof globalThis.Deno<"u"?"deno":typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")?"cloudflare-workers":typeof globalThis.EdgeRuntime<"u"?"edge":typeof window<"u"&&typeof document<"u"?"browser":typeof process<"u"&&typeof process.versions?.node<"u"?"node":"unknown"}catch{return"unknown"}}Be(gF,"detectRuntimeEnvironment");function bF(e){switch(e){case"node":case"bun":return"filesystem";case"browser":try{if(typeof localStorage<"u")return localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__"),"localStorage"}catch{}return"session-only";case"deno":return"session-only";default:return"session-only"}}Be(bF,"getStorageCapability");var PS=null;function vF(){return PS===null&&(PS=gF()),PS}Be(vF,"getRuntimeEnvironment");var Hu,IJ=(Hu=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch(n){Ce.debug(`Failed to send Scarf event: ${n}`)}}},Be(Hu,"ScarfEventLogger"),Hu),gi,yF=(gi=class{PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogNodeClient=null;_posthogBrowserClient=null;_posthogLoading=null;_scarfClient=null;_runtimeEnvironment;_storageCapability;_source;_userIdPath=null;_versionDownloadPath=null;constructor(){this._runtimeEnvironment=vF(),this._storageCapability=bF(this._runtimeEnvironment),this._source=typeof process<"u"&&Tb?.MCP_USE_TELEMETRY_SOURCE||this._runtimeEnvironment;const t=this._checkTelemetryDisabled(),n=this._runtimeEnvironment!=="unknown";if(t)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug("Telemetry disabled via environment/localStorage");else if(!n)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`);else{if(Ce.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."),this._posthogLoading=this._initPostHog(),this._runtimeEnvironment!=="browser")try{this._scarfClient=new IJ(this.SCARF_GATEWAY_URL,3e3)}catch(a){Ce.warn(`Failed to initialize Scarf telemetry: ${a}`),this._scarfClient=null}else this._scarfClient=null;this._storageCapability==="filesystem"&&this._scarfClient&&setTimeout(()=>{this.trackPackageDownload({triggered_by:"initialization"}).catch(a=>Ce.debug(`Failed to track package download: ${a}`))},0)}}_checkTelemetryDisabled(){return typeof process<"u"&&Tb?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}async _initPostHog(){this._runtimeEnvironment==="browser"?await this._initPostHogBrowser():await this._initPostHogNode()}async _initPostHogBrowser(){try{const t=await Jn(()=>import("./module-D4IOASh4.js"),[]),n=t.default||t.posthog;if(!n||typeof n.init!="function")throw new Error("posthog-js module did not export expected interface");n.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:"localStorage",autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:Be(()=>{Ce.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=n}catch(t){Ce.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}async _initPostHogNode(){try{const{PostHog:t}=await Jn(async()=>{const{PostHog:r}=await import("./posthog-node-CuYhrq1Q.js");return{PostHog:r}},[]),n=["cloudflare-workers","edge","deno"].includes(this._runtimeEnvironment),a={host:this.HOST,disableGeoip:!1};n&&(a.flushAt=1,a.flushInterval=0),this._posthogNodeClient=new t(this.PROJECT_API_KEY,a),Ce.debug("PostHog Node.js client initialized")}catch(t){Ce.warn(`Failed to initialize PostHog Node.js telemetry: ${t}`),this._posthogNodeClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return gi.instance||(gi.instance=new gi),gi.instance}setSource(t){this._source=t,Ce.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get isEnabled(){return this._posthogNodeClient!==null||this._posthogBrowserClient!==null||this._scarfClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case"filesystem":this._currUserId=this._getUserIdFromFilesystem();break;case"localStorage":this._currUserId=this._getUserIdFromLocalStorage();break;case"session-only":default:try{this._currUserId=`session-${El()}`}catch{this._currUserId=`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromFilesystem(){try{let t,n,a;try{t=Eo("fs"),n=Eo("os"),a=Eo("path")}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}}if(this._userIdPath||(this._userIdPath=a.join(this._getCacheHome(n,a),"mcp_use_3","telemetry_user_id")),!t.existsSync(this._userIdPath)){t.mkdirSync(a.dirname(this._userIdPath),{recursive:!0});let s;try{s=El()}catch{s=`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}return t.writeFileSync(this._userIdPath,s),s}return t.readFileSync(this._userIdPath,"utf-8").trim()}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Nb()}`}}}_getUserIdFromLocalStorage(){try{let t=localStorage.getItem(dM);if(!t){try{t=El()}catch{t=`${Date.now()}-${Nb()}`}localStorage.setItem(dM,t)}return t}catch{let n;try{n=`session-${El()}`}catch{n=`session-${Date.now()}-${Nb()}`}return n}}_getCacheHome(t,n){const a=Tb.XDG_CACHE_HOME;if(a&&n.isAbsolute(a))return a;const r=t.homedir();return n.join(r,".cache")}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogNodeClient&&!this._posthogBrowserClient&&!this._scarfClient)return;const n=this.userId,a={...t.properties};if(a.mcp_use_version=Qb(),a.language="typescript",a.source=this._source,a.runtime=this._runtimeEnvironment,this._posthogNodeClient)try{this._posthogNodeClient.capture({distinctId:n,event:t.name,properties:a})}catch(r){Ce.debug(`Failed to track PostHog Node event ${t.name}: ${r}`)}if(this._posthogBrowserClient)try{this._posthogBrowserClient.capture(t.name,{...a,distinct_id:n})}catch(r){Ce.debug(`Failed to track PostHog Browser event ${t.name}: ${r}`)}if(this._scarfClient)try{const r={...a,user_id:n,event:t.name};await this._scarfClient.logEvent(r)}catch(r){Ce.debug(`Failed to track Scarf event ${t.name}: ${r}`)}}async trackPackageDownload(t){return this._trackPackageDownloadInternal(this.userId,t)}async _trackPackageDownloadInternal(t,n){if(this._scarfClient&&this._storageCapability==="filesystem")try{const a=Eo("fs"),r=Eo("path"),i=Eo("os");this._versionDownloadPath||(this._versionDownloadPath=r.join(this._getCacheHome(i,r),"mcp_use","download_version"));const s=Qb();let c=!1,u=!1;if(!a.existsSync(this._versionDownloadPath))c=!0,u=!0,a.mkdirSync(r.dirname(this._versionDownloadPath),{recursive:!0}),a.writeFileSync(this._versionDownloadPath,s);else{const d=a.readFileSync(this._versionDownloadPath,"utf-8").trim();s>d&&(c=!0,u=!1,a.writeFileSync(this._versionDownloadPath,s))}if(c){Ce.debug(`Tracking package download event with properties: ${JSON.stringify(n)}`);const d={...n||{}};d.mcp_use_version=s,d.user_id=t,d.event="package_download",d.first_download=u,d.language="typescript",d.source=this._source,d.runtime=this._runtimeEnvironment,await this._scarfClient.logEvent(d)}}catch(a){Ce.debug(`Failed to track Scarf package_download event: ${a}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new yJ(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const a=pF(t,n),r=new wJ(a);await this.capture(r)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new SJ(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new xJ(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new _J(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new EJ(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new kJ(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new TJ(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new NJ(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const a=new CJ({serverName:t,serverConfig:n});await this.capture(a)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new RJ({serverName:t});await this.capture(n)}async trackUseMcpConnection(t){this.isEnabled&&await this.capture({name:"usemcp_connection",properties:{url_domain:new URL(t.url).hostname,transport_type:t.transportType,success:t.success,error_type:t.errorType??null,connection_time_ms:t.connectionTimeMs??null,has_oauth:t.hasOAuth,has_sampling:t.hasSampling,has_elicitation:t.hasElicitation}})}async trackUseMcpToolCall(t){this.isEnabled&&await this.capture({name:"usemcp_tool_call",properties:{tool_name:t.toolName,success:t.success,error_type:t.errorType??null,execution_time_ms:t.executionTimeMs??null}})}async trackUseMcpResourceRead(t){this.isEnabled&&await this.capture({name:"usemcp_resource_read",properties:{resource_uri_scheme:t.resourceUri.split(":")[0],success:t.success,error_type:t.errorType??null}})}identify(t,n){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(t,n)}catch(a){Ce.debug(`Failed to identify user: ${a}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){Ce.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){if(this._posthogNodeClient)try{this._posthogNodeClient.flush(),Ce.debug("PostHog client telemetry queue flushed")}catch(t){Ce.debug(`Failed to flush PostHog client: ${t}`)}}shutdown(){if(this._posthogNodeClient)try{this._posthogNodeClient.shutdown(),Ce.debug("PostHog client shutdown successfully")}catch(t){Ce.debug(`Error shutting down PostHog client: ${t}`)}}},Be(gi,"Telemetry"),Uf(gi,"instance",null),gi),zi=yF;function OJ(e){zi.getInstance().setSource(e)}Be(OJ,"setTelemetrySource");const wF=Object.freeze({status:"aborted"});function he(e,t,n){function a(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=s.prototype,m=Object.keys(d);for(let h=0;h<m.length;h++){const g=m[h];g in c||(c[g]=d[g].bind(c))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(c){var u;const d=n?.Parent?new i:this;a(d,c),(u=d._zod).deferred??(u.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}const SF=Symbol("zod_brand");class $l extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ay extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const ev={};function Gr(e){return e&&Object.assign(ev,e),ev}function DJ(e){return e}function jJ(e){return e}function $J(e){}function LJ(e){throw new Error("Unexpected value in exhaustive check")}function MJ(e){}function sk(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function ze(e,t="|"){return e.map(n=>pt(n)).join(t)}function tv(e,t){return typeof t=="bigint"?t.toString():t}function cm(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ec(e){return e==null}function iy(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function xF(e,t){const n=(e.toString().split(".")[1]||"").length,a=t.toString();let r=(a.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(a)){const u=a.match(/\d?e-(\d?)/);u?.[1]&&(r=Number.parseInt(u[1]))}const i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),c=Number.parseInt(t.toFixed(i).replace(".",""));return s%c/10**i}const fM=Symbol("evaluating");function Ht(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==fM)return a===void 0&&(a=fM,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function PJ(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Gs(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ho(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function UJ(e){return Ho(e._zod.def)}function zJ(e,t){return t?t.reduce((n,a)=>n?.[a],e):e}function FJ(e){const t=Object.keys(e),n=t.map(a=>e[a]);return Promise.all(n).then(a=>{const r={};for(let i=0;i<t.length;i++)r[t[i]]=a[i];return r})}function BJ(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let a=0;a<e;a++)n+=t[Math.floor(Math.random()*t.length)];return n}function a_(e){return JSON.stringify(e)}function _F(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const lk="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ju(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const EF=cm(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Fl(e){if(Ju(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ju(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function oy(e){return Fl(e)?{...e}:Array.isArray(e)?[...e]:e}function HJ(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const VJ=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},nv=new Set(["string","number","symbol"]),kF=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Lo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function Oe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function GJ(e){let t;return new Proxy({},{get(n,a,r){return t??(t=e()),Reflect.get(t,a,r)},set(n,a,r,i){return t??(t=e()),Reflect.set(t,a,r,i)},has(n,a){return t??(t=e()),Reflect.has(t,a)},deleteProperty(n,a){return t??(t=e()),Reflect.deleteProperty(t,a)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,a){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)},defineProperty(n,a,r){return t??(t=e()),Reflect.defineProperty(t,a,r)}})}function pt(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function TF(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const NF={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},CF={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function RF(e,t){const n=e._zod.def,a=Ho(e._zod.def,{get shape(){const r={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function AF(e,t){const n=e._zod.def,a=Ho(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function IF(e,t){if(!Fl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=Ho(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Gs(this,"shape",i),i},checks:[]});return ni(e,r)}function OF(e,t){if(!Fl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const a={...e._zod.def.shape,...t};return Gs(this,"shape",a),a},checks:e._zod.def.checks};return ni(e,n)}function DF(e,t){const n=Ho(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Gs(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:[]});return ni(e,n)}function jF(e,t,n){const a=Ho(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)i[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function $F(e,t,n){const a=Ho(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function Rl(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function bi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function qf(e){return typeof e=="string"?e:e?.message}function ti(e,t,n){const a={...e,path:e.path??[]};if(!e.message){const r=qf(e.inst?._zod.def?.error?.(e))??qf(t?.error?.(e))??qf(n.customError?.(e))??qf(n.localeError?.(e))??"Invalid input";a.message=r}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function sy(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ly(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Qu(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}function WJ(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function LF(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);return n}function MF(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function KJ(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return LF(t+n)}function ZJ(e){return MF(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function YJ(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let a=0;a<t.length;a+=2)n[a/2]=Number.parseInt(t.slice(a,a+2),16);return n}function qJ(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class XJ{constructor(...t){}}const PF=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:CF,Class:XJ,NUMBER_FORMAT_RANGES:NF,aborted:Rl,allowsEval:EF,assert:MJ,assertEqual:DJ,assertIs:$J,assertNever:LJ,assertNotEqual:jJ,assignProp:Gs,base64ToUint8Array:LF,base64urlToUint8Array:KJ,cached:cm,captureStackTrace:lk,cleanEnum:WJ,cleanRegex:iy,clone:ni,cloneDef:UJ,createTransparentProxy:GJ,defineLazy:Ht,esc:a_,escapeRegex:Lo,extend:IF,finalizeIssue:ti,floatSafeRemainder:xF,getElementAtPath:zJ,getEnumValues:sk,getLengthableOrigin:ly,getParsedType:VJ,getSizableOrigin:sy,hexToUint8Array:YJ,isObject:Ju,isPlainObject:Fl,issue:Qu,joinValues:ze,jsonStringifyReplacer:tv,merge:DF,mergeDefs:Ho,normalizeParams:Oe,nullish:ec,numKeys:HJ,objectClone:PJ,omit:AF,optionalKeys:TF,partial:jF,pick:RF,prefixIssues:bi,primitiveTypes:kF,promiseAllObject:FJ,propertyKeyTypes:nv,randomString:BJ,required:$F,safeExtend:OF,shallowClone:oy,slugify:_F,stringifyPrimitive:pt,uint8ArrayToBase64:MF,uint8ArrayToBase64url:ZJ,uint8ArrayToHex:qJ,unwrapMessage:qf},Symbol.toStringTag,{value:"Module"})),UF=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,tv,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ck=he("$ZodError",UF),Ma=he("$ZodError",UF,{Parent:Error});function uk(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function dk(e,t=n=>n.message){const n={_errors:[]},a=r=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>a({issues:s}));else if(i.code==="invalid_key")a({issues:i.issues});else if(i.code==="invalid_element")a({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let s=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(t(i))):s[u]=s[u]||{_errors:[]},s=s[u],c++}}};return a(e),n}function zF(e,t=n=>n.message){const n={errors:[]},a=(r,i=[])=>{var s,c;for(const u of r.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(d=>a({issues:d},u.path));else if(u.code==="invalid_key")a({issues:u.issues},u.path);else if(u.code==="invalid_element")a({issues:u.issues},u.path);else{const d=[...i,...u.path];if(d.length===0){n.errors.push(t(u));continue}let m=n,h=0;for(;h<d.length;){const g=d[h],v=h===d.length-1;typeof g=="string"?(m.properties??(m.properties={}),(s=m.properties)[g]??(s[g]={errors:[]}),m=m.properties[g]):(m.items??(m.items=[]),(c=m.items)[g]??(c[g]={errors:[]}),m=m.items[g]),v&&m.errors.push(t(u)),h++}}};return a(e),n}function FF(e){const t=[],n=e.map(a=>typeof a=="object"?a.key:a);for(const a of n)typeof a=="number"?t.push(`[${a}]`):typeof a=="symbol"?t.push(`[${JSON.stringify(String(a))}]`):/[^\w$]/.test(a)?t.push(`[${JSON.stringify(a)}]`):(t.length&&t.push("."),t.push(a));return t.join("")}function BF(e){const t=[],n=[...e.issues].sort((a,r)=>(a.path??[]).length-(r.path??[]).length);for(const a of n)t.push(`✖ ${a.message}`),a.path?.length&&t.push(` → at ${FF(a.path)}`);return t.join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/winston-CEUa9Wj-.js","assets/util-t-trnxQI.js","assets/index-DRz5BQNA.js","assets/path-BOQPmbms.js","assets/fs-u42MReIY.js","assets/path-MNZaYwxc.js","assets/index-B5kLR_Rv.js","assets/index-CR9w_74S.js","assets/index-Zctd0Z8B.js","assets/llms-BDMth6TQ.js","assets/embeddings-C0rUXJ5F.js","assets/index-DiwCBW8I.js","assets/index-sQyTG4jp.js","assets/index-BYR-I2bf.js","assets/browser-DZ15LLaB.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var sJ=Object.defineProperty;var lJ=(e,t,n)=>t in e?sJ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Uf=(e,t,n)=>lJ(e,typeof t!="symbol"?t+"":t,n);function cJ(e,t){for(var n=0;n<t.length;n++){const a=t[n];if(typeof a!="string"&&!Array.isArray(a)){for(const r in a)if(r!=="default"&&!(r in e)){const i=Object.getOwnPropertyDescriptor(a,r);i&&Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:()=>a[r]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&a(s)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();function ry(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function QTe(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function a(){var r=!1;try{r=this instanceof a}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(a){var r=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:function(){return e[a]}})}),n}var MS={exports:{}},zf={};var lM;function uJ(){if(lM)return zf;lM=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(a,r,i){var s=null;if(i!==void 0&&(s=""+i),r.key!==void 0&&(s=""+r.key),"key"in r){i={};for(var c in r)c!=="key"&&(i[c]=r[c])}else i=r;return r=i.ref,{$$typeof:e,type:a,key:s,ref:r!==void 0?r:null,props:i}}return zf.Fragment=t,zf.jsx=n,zf.jsxs=n,zf}var cM;function dJ(){return cM||(cM=1,MS.exports=uJ()),MS.exports}var f=dJ();const fJ="modulepreload",pJ=function(e){return"/inspector/"+e},uM={},Jn=function(t,n,a){let r=Promise.resolve();if(n&&n.length>0){let u=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),c=s?.nonce||s?.getAttribute("nonce");r=u(n.map(d=>{if(d=pJ(d),d in uM)return;uM[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":fJ,m||(g.as="script"),g.crossOrigin="",g.href=d,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((v,x)=>{g.addEventListener("load",v),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(s){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=s,window.dispatchEvent(c),!c.defaultPrevented)throw s}return r.then(s=>{for(const c of s||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};var mJ=Object.defineProperty,Be=(e,t)=>mJ(e,"name",{value:t,configurable:!0}),Eo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Jc={};async function lF(){if(typeof process<"u")try{const e=await Jn(()=>import("./fs-u42MReIY.js").then(n=>n.f),[]),t=await Jn(()=>import("./path-MNZaYwxc.js").then(n=>n.p),[]);return{fs:e.default,path:t.default}}catch{return{fs:null,path:null}}return{fs:null,path:null}}Be(lF,"getNodeModules");var ha=null;function cF(){if(typeof Eo<"u")try{ha=Eo("winston")}catch{}}Be(cF,"loadWinstonSync");async function uF(){return ha||(ha=await Jn(()=>import("./winston-CEUa9Wj-.js").then(e=>e.w),__vite__mapDeps([0,1,2,3,4,5]))),ha}Be(uF,"getWinston");var r_="mcp-use";function Jb(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"}catch{return!1}}Be(Jb,"isNodeJSEnvironment");var Au,hJ=(Au=class{_level;name;constructor(t=r_,n="info"){this.name=t,this._level=n}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],a=n.indexOf(this._level);return n.indexOf(t)<=a}formatMessage(t,n){return`${new Date().toLocaleTimeString("en-US",{hour12:!1})} [${this.name}] ${t}: ${n}`}error(t){this.shouldLog("error")&&console.error(this.formatMessage("error",t))}warn(t){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",t))}info(t){this.shouldLog("info")&&console.info(this.formatMessage("info",t))}debug(t){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",t))}http(t){this.shouldLog("http")&&console.log(this.formatMessage("http",t))}verbose(t){this.shouldLog("verbose")&&console.log(this.formatMessage("verbose",t))}silly(t){this.shouldLog("silly")&&console.log(this.formatMessage("silly",t))}get level(){return this._level}set level(t){this._level=t}},Be(Au,"SimpleConsoleLogger"),Au);function kb(e){switch((typeof process<"u"&&Jc?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}Be(kb,"resolveLevel");var To,dF=(To=class{static get(t=r_){if(!Jb()){if(!this.simpleInstances[t]){const n=typeof process<"u"&&Jc?.DEBUG||void 0;this.simpleInstances[t]=new hJ(t,kb(n))}return this.simpleInstances[t]}if(!this.instances[t]){if(!ha)throw new Error("Winston not loaded - call Logger.configure() first");const{createLogger:n,format:a}=ha,{combine:r,timestamp:i,label:s,colorize:c,splat:u}=a;this.instances[t]=n({level:kb(Jc.DEBUG),format:r(c(),u(),s({label:t}),i({format:"HH:mm:ss"}),this.getFormatter()),transports:[new ha.transports.Console]})}return this.instances[t]}static getFormatter(){if(!ha)throw new Error("Winston not loaded");const{format:t}=ha,{printf:n}=t,a=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s}: ${c}`),r=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`),i=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`);switch(this.currentFormat){case"minimal":return a;case"detailed":return r;case"emoji":return i;default:return a}}static async configure(t={}){const{level:n,console:a=!0,file:r,format:i="minimal"}=t,s=typeof process<"u"&&Jc?.DEBUG||void 0,c=n??kb(s);if(this.currentFormat=i,!Jb()){Object.values(this.simpleInstances).forEach(w=>{w.level=c});return}if(await uF(),!ha)throw new Error("Failed to load winston");const u=this.get();u.level=c;const d=u;if(d.clear(),a&&d.add(new ha.transports.Console),r){const{fs:w,path:E}=await lF();if(w&&E){const _=E.dirname(E.resolve(r));w.existsSync(_)||w.mkdirSync(_,{recursive:!0}),d.add(new ha.transports.File({filename:r}))}}const{format:m}=ha,{combine:h,timestamp:g,label:v,colorize:x,splat:S}=m;Object.values(this.instances).forEach(w=>{w&&"format"in w&&(w.level=c,w.format=h(x(),S(),v({label:r_}),g({format:"HH:mm:ss"}),this.getFormatter()))})}static setDebug(t){let n;t===2||t===!0?n="debug":n="info",Object.values(this.simpleInstances).forEach(a=>{a.level=n}),Object.values(this.instances).forEach(a=>{a&&(a.level=n)}),typeof process<"u"&&Jc&&(Jc.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},Be(To,"Logger"),Uf(To,"instances",{}),Uf(To,"simpleInstances",{}),Uf(To,"currentFormat","minimal"),To);Jb()&&(cF(),ha&&dF.configure());var Ce=dF.get(),Tb={},fF=typeof globalThis.Deno<"u";function gJ(e){return fF?globalThis.Deno.env.get(e):Tb[e]}Be(gJ,"getEnv");function bJ(){return fF?globalThis.Deno.cwd():process.cwd()}Be(bJ,"getCwd");function El(){return globalThis.crypto.randomUUID()}Be(El,"generateUUID");var vJ="1.11.2";function Qb(){return vJ}Be(Qb,"getPackageVersion");var Iu,Ci=(Iu=class{},Be(Iu,"BaseTelemetryEvent"),Iu),Ou,yJ=(Ou=class extends Ci{constructor(t){super(),this.data=t}get name(){return"mcp_agent_execution"}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}},Be(Ou,"MCPAgentExecutionEvent"),Ou);function pF(e,t){const n=Array.from(e.registrations.tools.values()),a=Array.from(e.registrations.prompts.values()),r=Array.from(e.registrations.resources.values()),i=Array.from(e.registrations.resourceTemplates.values()),s=r.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,uri:m.config.uri??null,mime_type:m.config.mimeType??null})),c=s.filter(m=>m.mime_type==="text/html+skybridge"),u=s.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),d=s.filter(m=>m.mime_type==="text/html+mcp");return{transport:t,toolsNumber:e.registeredTools.length,resourcesNumber:e.registeredResources.length,promptsNumber:e.registeredPrompts.length,auth:!!e.oauthProvider,name:e.config.name,description:e.config.description??null,baseUrl:e.serverBaseUrl??null,toolNames:e.registeredTools.length>0?e.registeredTools:null,resourceNames:e.registeredResources.length>0?e.registeredResources:null,promptNames:e.registeredPrompts.length>0?e.registeredPrompts:null,tools:n.length>0?n.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,input_schema:m.config.schema?JSON.stringify(m.config.schema):null,output_schema:m.config.outputSchema?JSON.stringify(m.config.outputSchema):null})):null,resources:s.length>0?s:null,prompts:a.length>0?a.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,args:m.config.args?JSON.stringify(m.config.args):null})):null,templates:i.length>0?i.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:c.length>0?c:null,appsSdkResourcesNumber:c.length,mcpUiResources:u.length>0?u:null,mcpUiResourcesNumber:u.length,mcpAppsResources:d.length>0?d:null,mcpAppsResourcesNumber:d.length}}Be(pF,"createServerRunEventData");var Du,wJ=(Du=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_run"}get properties(){return{transport:this.data.transport,tools_number:this.data.toolsNumber,resources_number:this.data.resourcesNumber,prompts_number:this.data.promptsNumber,auth:this.data.auth,name:this.data.name,description:this.data.description??null,base_url:this.data.baseUrl??null,tool_names:this.data.toolNames??null,resource_names:this.data.resourceNames??null,prompt_names:this.data.promptNames??null,tools:this.data.tools??null,resources:this.data.resources??null,prompts:this.data.prompts??null,templates:this.data.templates??null,capabilities:this.data.capabilities?JSON.stringify(this.data.capabilities):null,apps_sdk_resources:this.data.appsSdkResources?JSON.stringify(this.data.appsSdkResources):null,apps_sdk_resources_number:this.data.appsSdkResourcesNumber??0,mcp_ui_resources:this.data.mcpUiResources?JSON.stringify(this.data.mcpUiResources):null,mcp_ui_resources_number:this.data.mcpUiResourcesNumber??0,mcp_apps_resources:this.data.mcpAppsResources?JSON.stringify(this.data.mcpAppsResources):null,mcp_apps_resources_number:this.data.mcpAppsResourcesNumber??0}}},Be(Du,"ServerRunEvent"),Du),ju,SJ=(ju=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_initialize_call"}get properties(){return{protocol_version:this.data.protocolVersion,client_info:JSON.stringify(this.data.clientInfo),client_capabilities:JSON.stringify(this.data.clientCapabilities),session_id:this.data.sessionId??null}}},Be(ju,"ServerInitializeEvent"),ju),$u,xJ=($u=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_tool_call"}get properties(){return{tool_name:this.data.toolName,length_input_argument:this.data.lengthInputArgument,success:this.data.success,error_type:this.data.errorType??null,execution_time_ms:this.data.executionTimeMs??null}}},Be($u,"ServerToolCallEvent"),$u),Lu,_J=(Lu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_resource_call"}get properties(){return{name:this.data.name,description:this.data.description,contents:this.data.contents,success:this.data.success,error_type:this.data.errorType??null}}},Be(Lu,"ServerResourceCallEvent"),Lu),Mu,EJ=(Mu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"server_prompt_call"}get properties(){return{name:this.data.name,description:this.data.description,success:this.data.success,error_type:this.data.errorType??null}}},Be(Mu,"ServerPromptCallEvent"),Mu),Pu,kJ=(Pu=class extends Ci{constructor(t){super(),this.data=t}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},Be(Pu,"ServerContextEvent"),Pu),Uu,TJ=(Uu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"mcpclient_init"}get properties(){return{code_mode:this.data.codeMode,sandbox:this.data.sandbox,all_callbacks:this.data.allCallbacks,verify:this.data.verify,servers:this.data.servers,num_servers:this.data.numServers,is_browser:this.data.isBrowser}}},Be(Uu,"MCPClientInitEvent"),Uu),zu,NJ=(zu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"connector_init"}get properties(){return{connector_type:this.data.connectorType,server_command:this.data.serverCommand??null,server_args:this.data.serverArgs??null,server_url:this.data.serverUrl??null,public_identifier:this.data.publicIdentifier??null}}},Be(zu,"ConnectorInitEvent"),zu),Fu,CJ=(Fu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,a=n.url;return{server_name:t,server_url_domain:a?this._extractHostname(a):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},Be(Fu,"ClientAddServerEvent"),Fu),Bu,RJ=(Bu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},Be(Bu,"ClientRemoveServerEvent"),Bu);function mF(e){return e._llm_type||e.constructor.name.toLowerCase()}Be(mF,"getModelProvider");function hF(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}Be(hF,"getModelName");function AJ(e){return[mF(e),hF(e)]}Be(AJ,"extractModelInfo");function Nb(){if(typeof window<"u"&&window.crypto&&typeof window.crypto.getRandomValues=="function"){const e=new Uint8Array(8);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}try{return Eo("crypto").randomBytes(8).toString("hex")}catch{return Math.random().toString(36).substring(2,15)}}Be(Nb,"secureRandomString");var dM="mcp_use_user_id";function gF(){try{return typeof globalThis.Bun<"u"?"bun":typeof globalThis.Deno<"u"?"deno":typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")?"cloudflare-workers":typeof globalThis.EdgeRuntime<"u"?"edge":typeof window<"u"&&typeof document<"u"?"browser":typeof process<"u"&&typeof process.versions?.node<"u"?"node":"unknown"}catch{return"unknown"}}Be(gF,"detectRuntimeEnvironment");function bF(e){switch(e){case"node":case"bun":return"filesystem";case"browser":try{if(typeof localStorage<"u")return localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__"),"localStorage"}catch{}return"session-only";case"deno":return"session-only";default:return"session-only"}}Be(bF,"getStorageCapability");var PS=null;function vF(){return PS===null&&(PS=gF()),PS}Be(vF,"getRuntimeEnvironment");var Hu,IJ=(Hu=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch(n){Ce.debug(`Failed to send Scarf event: ${n}`)}}},Be(Hu,"ScarfEventLogger"),Hu),gi,yF=(gi=class{PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogNodeClient=null;_posthogBrowserClient=null;_posthogLoading=null;_scarfClient=null;_runtimeEnvironment;_storageCapability;_source;_userIdPath=null;_versionDownloadPath=null;constructor(){this._runtimeEnvironment=vF(),this._storageCapability=bF(this._runtimeEnvironment),this._source=typeof process<"u"&&Tb?.MCP_USE_TELEMETRY_SOURCE||this._runtimeEnvironment;const t=this._checkTelemetryDisabled(),n=this._runtimeEnvironment!=="unknown";if(t)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug("Telemetry disabled via environment/localStorage");else if(!n)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`);else{if(Ce.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."),this._posthogLoading=this._initPostHog(),this._runtimeEnvironment!=="browser")try{this._scarfClient=new IJ(this.SCARF_GATEWAY_URL,3e3)}catch(a){Ce.warn(`Failed to initialize Scarf telemetry: ${a}`),this._scarfClient=null}else this._scarfClient=null;this._storageCapability==="filesystem"&&this._scarfClient&&setTimeout(()=>{this.trackPackageDownload({triggered_by:"initialization"}).catch(a=>Ce.debug(`Failed to track package download: ${a}`))},0)}}_checkTelemetryDisabled(){return typeof process<"u"&&Tb?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}async _initPostHog(){this._runtimeEnvironment==="browser"?await this._initPostHogBrowser():await this._initPostHogNode()}async _initPostHogBrowser(){try{const t=await Jn(()=>import("./module-D4IOASh4.js"),[]),n=t.default||t.posthog;if(!n||typeof n.init!="function")throw new Error("posthog-js module did not export expected interface");n.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:"localStorage",autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:Be(()=>{Ce.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=n}catch(t){Ce.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}async _initPostHogNode(){try{const{PostHog:t}=await Jn(async()=>{const{PostHog:r}=await import("./posthog-node-CuYhrq1Q.js");return{PostHog:r}},[]),n=["cloudflare-workers","edge","deno"].includes(this._runtimeEnvironment),a={host:this.HOST,disableGeoip:!1};n&&(a.flushAt=1,a.flushInterval=0),this._posthogNodeClient=new t(this.PROJECT_API_KEY,a),Ce.debug("PostHog Node.js client initialized")}catch(t){Ce.warn(`Failed to initialize PostHog Node.js telemetry: ${t}`),this._posthogNodeClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return gi.instance||(gi.instance=new gi),gi.instance}setSource(t){this._source=t,Ce.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get isEnabled(){return this._posthogNodeClient!==null||this._posthogBrowserClient!==null||this._scarfClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case"filesystem":this._currUserId=this._getUserIdFromFilesystem();break;case"localStorage":this._currUserId=this._getUserIdFromLocalStorage();break;case"session-only":default:try{this._currUserId=`session-${El()}`}catch{this._currUserId=`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromFilesystem(){try{let t,n,a;try{t=Eo("fs"),n=Eo("os"),a=Eo("path")}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}}if(this._userIdPath||(this._userIdPath=a.join(this._getCacheHome(n,a),"mcp_use_3","telemetry_user_id")),!t.existsSync(this._userIdPath)){t.mkdirSync(a.dirname(this._userIdPath),{recursive:!0});let s;try{s=El()}catch{s=`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}return t.writeFileSync(this._userIdPath,s),s}return t.readFileSync(this._userIdPath,"utf-8").trim()}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Nb()}`}}}_getUserIdFromLocalStorage(){try{let t=localStorage.getItem(dM);if(!t){try{t=El()}catch{t=`${Date.now()}-${Nb()}`}localStorage.setItem(dM,t)}return t}catch{let n;try{n=`session-${El()}`}catch{n=`session-${Date.now()}-${Nb()}`}return n}}_getCacheHome(t,n){const a=Tb.XDG_CACHE_HOME;if(a&&n.isAbsolute(a))return a;const r=t.homedir();return n.join(r,".cache")}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogNodeClient&&!this._posthogBrowserClient&&!this._scarfClient)return;const n=this.userId,a={...t.properties};if(a.mcp_use_version=Qb(),a.language="typescript",a.source=this._source,a.runtime=this._runtimeEnvironment,this._posthogNodeClient)try{this._posthogNodeClient.capture({distinctId:n,event:t.name,properties:a})}catch(r){Ce.debug(`Failed to track PostHog Node event ${t.name}: ${r}`)}if(this._posthogBrowserClient)try{this._posthogBrowserClient.capture(t.name,{...a,distinct_id:n})}catch(r){Ce.debug(`Failed to track PostHog Browser event ${t.name}: ${r}`)}if(this._scarfClient)try{const r={...a,user_id:n,event:t.name};await this._scarfClient.logEvent(r)}catch(r){Ce.debug(`Failed to track Scarf event ${t.name}: ${r}`)}}async trackPackageDownload(t){return this._trackPackageDownloadInternal(this.userId,t)}async _trackPackageDownloadInternal(t,n){if(this._scarfClient&&this._storageCapability==="filesystem")try{const a=Eo("fs"),r=Eo("path"),i=Eo("os");this._versionDownloadPath||(this._versionDownloadPath=r.join(this._getCacheHome(i,r),"mcp_use","download_version"));const s=Qb();let c=!1,u=!1;if(!a.existsSync(this._versionDownloadPath))c=!0,u=!0,a.mkdirSync(r.dirname(this._versionDownloadPath),{recursive:!0}),a.writeFileSync(this._versionDownloadPath,s);else{const d=a.readFileSync(this._versionDownloadPath,"utf-8").trim();s>d&&(c=!0,u=!1,a.writeFileSync(this._versionDownloadPath,s))}if(c){Ce.debug(`Tracking package download event with properties: ${JSON.stringify(n)}`);const d={...n||{}};d.mcp_use_version=s,d.user_id=t,d.event="package_download",d.first_download=u,d.language="typescript",d.source=this._source,d.runtime=this._runtimeEnvironment,await this._scarfClient.logEvent(d)}}catch(a){Ce.debug(`Failed to track Scarf package_download event: ${a}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new yJ(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const a=pF(t,n),r=new wJ(a);await this.capture(r)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new SJ(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new xJ(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new _J(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new EJ(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new kJ(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new TJ(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new NJ(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const a=new CJ({serverName:t,serverConfig:n});await this.capture(a)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new RJ({serverName:t});await this.capture(n)}async trackUseMcpConnection(t){this.isEnabled&&await this.capture({name:"usemcp_connection",properties:{url_domain:new URL(t.url).hostname,transport_type:t.transportType,success:t.success,error_type:t.errorType??null,connection_time_ms:t.connectionTimeMs??null,has_oauth:t.hasOAuth,has_sampling:t.hasSampling,has_elicitation:t.hasElicitation}})}async trackUseMcpToolCall(t){this.isEnabled&&await this.capture({name:"usemcp_tool_call",properties:{tool_name:t.toolName,success:t.success,error_type:t.errorType??null,execution_time_ms:t.executionTimeMs??null}})}async trackUseMcpResourceRead(t){this.isEnabled&&await this.capture({name:"usemcp_resource_read",properties:{resource_uri_scheme:t.resourceUri.split(":")[0],success:t.success,error_type:t.errorType??null}})}identify(t,n){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(t,n)}catch(a){Ce.debug(`Failed to identify user: ${a}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){Ce.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){if(this._posthogNodeClient)try{this._posthogNodeClient.flush(),Ce.debug("PostHog client telemetry queue flushed")}catch(t){Ce.debug(`Failed to flush PostHog client: ${t}`)}}shutdown(){if(this._posthogNodeClient)try{this._posthogNodeClient.shutdown(),Ce.debug("PostHog client shutdown successfully")}catch(t){Ce.debug(`Error shutting down PostHog client: ${t}`)}}},Be(gi,"Telemetry"),Uf(gi,"instance",null),gi),zi=yF;function OJ(e){zi.getInstance().setSource(e)}Be(OJ,"setTelemetrySource");const wF=Object.freeze({status:"aborted"});function he(e,t,n){function a(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=s.prototype,m=Object.keys(d);for(let h=0;h<m.length;h++){const g=m[h];g in c||(c[g]=d[g].bind(c))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(c){var u;const d=n?.Parent?new i:this;a(d,c),(u=d._zod).deferred??(u.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}const SF=Symbol("zod_brand");class $l extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ay extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const ev={};function Gr(e){return e&&Object.assign(ev,e),ev}function DJ(e){return e}function jJ(e){return e}function $J(e){}function LJ(e){throw new Error("Unexpected value in exhaustive check")}function MJ(e){}function sk(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function ze(e,t="|"){return e.map(n=>pt(n)).join(t)}function tv(e,t){return typeof t=="bigint"?t.toString():t}function cm(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ec(e){return e==null}function iy(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function xF(e,t){const n=(e.toString().split(".")[1]||"").length,a=t.toString();let r=(a.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(a)){const u=a.match(/\d?e-(\d?)/);u?.[1]&&(r=Number.parseInt(u[1]))}const i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),c=Number.parseInt(t.toFixed(i).replace(".",""));return s%c/10**i}const fM=Symbol("evaluating");function Ht(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==fM)return a===void 0&&(a=fM,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function PJ(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Gs(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ho(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function UJ(e){return Ho(e._zod.def)}function zJ(e,t){return t?t.reduce((n,a)=>n?.[a],e):e}function FJ(e){const t=Object.keys(e),n=t.map(a=>e[a]);return Promise.all(n).then(a=>{const r={};for(let i=0;i<t.length;i++)r[t[i]]=a[i];return r})}function BJ(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let a=0;a<e;a++)n+=t[Math.floor(Math.random()*t.length)];return n}function a_(e){return JSON.stringify(e)}function _F(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const lk="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ju(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const EF=cm(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Fl(e){if(Ju(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ju(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function oy(e){return Fl(e)?{...e}:Array.isArray(e)?[...e]:e}function HJ(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const VJ=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},nv=new Set(["string","number","symbol"]),kF=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Lo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function Oe(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function GJ(e){let t;return new Proxy({},{get(n,a,r){return t??(t=e()),Reflect.get(t,a,r)},set(n,a,r,i){return t??(t=e()),Reflect.set(t,a,r,i)},has(n,a){return t??(t=e()),Reflect.has(t,a)},deleteProperty(n,a){return t??(t=e()),Reflect.deleteProperty(t,a)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,a){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)},defineProperty(n,a,r){return t??(t=e()),Reflect.defineProperty(t,a,r)}})}function pt(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function TF(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const NF={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},CF={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function RF(e,t){const n=e._zod.def,a=Ho(e._zod.def,{get shape(){const r={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function AF(e,t){const n=e._zod.def,a=Ho(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function IF(e,t){if(!Fl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=Ho(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Gs(this,"shape",i),i},checks:[]});return ni(e,r)}function OF(e,t){if(!Fl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const a={...e._zod.def.shape,...t};return Gs(this,"shape",a),a},checks:e._zod.def.checks};return ni(e,n)}function DF(e,t){const n=Ho(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Gs(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:[]});return ni(e,n)}function jF(e,t,n){const a=Ho(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)i[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function $F(e,t,n){const a=Ho(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function Rl(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function bi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function qf(e){return typeof e=="string"?e:e?.message}function ti(e,t,n){const a={...e,path:e.path??[]};if(!e.message){const r=qf(e.inst?._zod.def?.error?.(e))??qf(t?.error?.(e))??qf(n.customError?.(e))??qf(n.localeError?.(e))??"Invalid input";a.message=r}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function sy(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ly(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Qu(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}function WJ(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function LF(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);return n}function MF(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function KJ(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return LF(t+n)}function ZJ(e){return MF(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function YJ(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let a=0;a<t.length;a+=2)n[a/2]=Number.parseInt(t.slice(a,a+2),16);return n}function qJ(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class XJ{constructor(...t){}}const PF=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:CF,Class:XJ,NUMBER_FORMAT_RANGES:NF,aborted:Rl,allowsEval:EF,assert:MJ,assertEqual:DJ,assertIs:$J,assertNever:LJ,assertNotEqual:jJ,assignProp:Gs,base64ToUint8Array:LF,base64urlToUint8Array:KJ,cached:cm,captureStackTrace:lk,cleanEnum:WJ,cleanRegex:iy,clone:ni,cloneDef:UJ,createTransparentProxy:GJ,defineLazy:Ht,esc:a_,escapeRegex:Lo,extend:IF,finalizeIssue:ti,floatSafeRemainder:xF,getElementAtPath:zJ,getEnumValues:sk,getLengthableOrigin:ly,getParsedType:VJ,getSizableOrigin:sy,hexToUint8Array:YJ,isObject:Ju,isPlainObject:Fl,issue:Qu,joinValues:ze,jsonStringifyReplacer:tv,merge:DF,mergeDefs:Ho,normalizeParams:Oe,nullish:ec,numKeys:HJ,objectClone:PJ,omit:AF,optionalKeys:TF,partial:jF,pick:RF,prefixIssues:bi,primitiveTypes:kF,promiseAllObject:FJ,propertyKeyTypes:nv,randomString:BJ,required:$F,safeExtend:OF,shallowClone:oy,slugify:_F,stringifyPrimitive:pt,uint8ArrayToBase64:MF,uint8ArrayToBase64url:ZJ,uint8ArrayToHex:qJ,unwrapMessage:qf},Symbol.toStringTag,{value:"Module"})),UF=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,tv,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ck=he("$ZodError",UF),Ma=he("$ZodError",UF,{Parent:Error});function uk(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function dk(e,t=n=>n.message){const n={_errors:[]},a=r=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>a({issues:s}));else if(i.code==="invalid_key")a({issues:i.issues});else if(i.code==="invalid_element")a({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let s=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(t(i))):s[u]=s[u]||{_errors:[]},s=s[u],c++}}};return a(e),n}function zF(e,t=n=>n.message){const n={errors:[]},a=(r,i=[])=>{var s,c;for(const u of r.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(d=>a({issues:d},u.path));else if(u.code==="invalid_key")a({issues:u.issues},u.path);else if(u.code==="invalid_element")a({issues:u.issues},u.path);else{const d=[...i,...u.path];if(d.length===0){n.errors.push(t(u));continue}let m=n,h=0;for(;h<d.length;){const g=d[h],v=h===d.length-1;typeof g=="string"?(m.properties??(m.properties={}),(s=m.properties)[g]??(s[g]={errors:[]}),m=m.properties[g]):(m.items??(m.items=[]),(c=m.items)[g]??(c[g]={errors:[]}),m=m.items[g]),v&&m.errors.push(t(u)),h++}}};return a(e),n}function FF(e){const t=[],n=e.map(a=>typeof a=="object"?a.key:a);for(const a of n)typeof a=="number"?t.push(`[${a}]`):typeof a=="symbol"?t.push(`[${JSON.stringify(String(a))}]`):/[^\w$]/.test(a)?t.push(`[${JSON.stringify(a)}]`):(t.length&&t.push("."),t.push(a));return t.join("")}function BF(e){const t=[],n=[...e.issues].sort((a,r)=>(a.path??[]).length-(r.path??[]).length);for(const a of n)t.push(`✖ ${a.message}`),a.path?.length&&t.push(` → at ${FF(a.path)}`);return t.join(`
|
|
3
3
|
`)}const um=e=>(t,n,a,r)=>{const i=a?Object.assign(a,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new $l;if(s.issues.length){const c=new(r?.Err??e)(s.issues.map(u=>ti(u,i,Gr())));throw lk(c,r?.callee),c}return s.value},i_=um(Ma),dm=e=>async(t,n,a,r)=>{const i=a?Object.assign(a,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const c=new(r?.Err??e)(s.issues.map(u=>ti(u,i,Gr())));throw lk(c,r?.callee),c}return s.value},o_=dm(Ma),fm=e=>(t,n,a)=>{const r=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new $l;return i.issues.length?{success:!1,error:new(e??ck)(i.issues.map(s=>ti(s,r,Gr())))}:{success:!0,data:i.value}},fk=fm(Ma),pm=e=>async(t,n,a)=>{const r=a?Object.assign(a,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>ti(s,r,Gr())))}:{success:!0,data:i.value}},HF=pm(Ma),pk=e=>(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return um(e)(t,n,r)},JJ=pk(Ma),mk=e=>(t,n,a)=>um(e)(t,n,a),QJ=mk(Ma),hk=e=>async(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return dm(e)(t,n,r)},eQ=hk(Ma),gk=e=>async(t,n,a)=>dm(e)(t,n,a),tQ=gk(Ma),bk=e=>(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return fm(e)(t,n,r)},nQ=bk(Ma),vk=e=>(t,n,a)=>fm(e)(t,n,a),rQ=vk(Ma),yk=e=>async(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return pm(e)(t,n,r)},aQ=yk(Ma),wk=e=>async(t,n,a)=>pm(e)(t,n,a),iQ=wk(Ma),VF=/^[cC][^\s-]{8,}$/,GF=/^[0-9a-z]+$/,WF=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,KF=/^[0-9a-vA-V]{20}$/,ZF=/^[A-Za-z0-9]{27}$/,YF=/^[a-zA-Z0-9_-]{21}$/,qF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oQ=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,XF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ed=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,sQ=ed(4),lQ=ed(6),cQ=ed(7),JF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,dQ=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,QF=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,fQ=QF,pQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,mQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function e3(){return new RegExp(mQ,"u")}const t3=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,n3=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,r3=e=>{const t=Lo(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},a3=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,i3=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,o3=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Sk=/^[A-Za-z0-9_-]*$/,s3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,l3=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,c3=/^\+(?:[0-9]){6,14}[0-9]$/,u3="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",d3=new RegExp(`^${u3}$`);function f3(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function p3(e){return new RegExp(`^${f3(e)}$`)}function m3(e){const t=f3({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const a=`${t}(?:${n.join("|")})`;return new RegExp(`^${u3}T(?:${a})$`)}const h3=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},g3=/^-?\d+n?$/,b3=/^-?\d+$/,v3=/^-?\d+(?:\.\d+)?/,y3=/^(?:true|false)$/i,w3=/^null$/i,S3=/^undefined$/i,x3=/^[^A-Z]*$/,_3=/^[^a-z]*$/,E3=/^[0-9a-fA-F]*$/;function mm(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function hm(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const hQ=/^[0-9a-fA-F]{32}$/,gQ=mm(22,"=="),bQ=hm(22),vQ=/^[0-9a-fA-F]{40}$/,yQ=mm(27,"="),wQ=hm(27),SQ=/^[0-9a-fA-F]{64}$/,xQ=mm(43,"="),_Q=hm(43),EQ=/^[0-9a-fA-F]{96}$/,kQ=mm(64,""),TQ=hm(64),NQ=/^[0-9a-fA-F]{128}$/,CQ=mm(86,"=="),RQ=hm(86),xk=Object.freeze(Object.defineProperty({__proto__:null,base64:o3,base64url:Sk,bigint:g3,boolean:y3,browserEmail:pQ,cidrv4:a3,cidrv6:i3,cuid:VF,cuid2:GF,date:d3,datetime:m3,domain:l3,duration:qF,e164:c3,email:JF,emoji:e3,extendedDuration:oQ,guid:XF,hex:E3,hostname:s3,html5Email:uQ,idnEmail:fQ,integer:b3,ipv4:t3,ipv6:n3,ksuid:ZF,lowercase:x3,mac:r3,md5_base64:gQ,md5_base64url:bQ,md5_hex:hQ,nanoid:YF,null:w3,number:v3,rfc5322Email:dQ,sha1_base64:yQ,sha1_base64url:wQ,sha1_hex:vQ,sha256_base64:xQ,sha256_base64url:_Q,sha256_hex:SQ,sha384_base64:kQ,sha384_base64url:TQ,sha384_hex:EQ,sha512_base64:CQ,sha512_base64url:RQ,sha512_hex:NQ,string:h3,time:p3,ulid:WF,undefined:S3,unicodeEmail:QF,uppercase:_3,uuid:ed,uuid4:sQ,uuid6:lQ,uuid7:cQ,xid:KF},Symbol.toStringTag,{value:"Module"})),zn=he("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),k3={number:"number",bigint:"bigint",object:"date"},_k=he("$ZodCheckLessThan",(e,t)=>{zn.init(e,t);const n=k3[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:n,code:"too_big",maximum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ek=he("$ZodCheckGreaterThan",(e,t)=>{zn.init(e,t);const n=k3[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:n,code:"too_small",minimum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),T3=he("$ZodCheckMultipleOf",(e,t)=>{zn.init(e,t),e._zod.onattach.push(n=>{var a;(a=n._zod.bag).multipleOf??(a.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):xF(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),N3=he("$ZodCheckNumberFormat",(e,t)=>{zn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[r,i]=NF[t.format];e._zod.onattach.push(s=>{const c=s._zod.bag;c.format=t.format,c.minimum=r,c.maximum=i,n&&(c.pattern=b3)}),e._zod.check=s=>{const c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort});return}}c<r&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>i&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:e})}}),C3=he("$ZodCheckBigIntFormat",(e,t)=>{zn.init(e,t);const[n,a]=CF[t.format];e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,i.minimum=n,i.maximum=a}),e._zod.check=r=>{const i=r.value;i<n&&r.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),i>a&&r.issues.push({origin:"bigint",input:i,code:"too_big",maximum:a,inst:e})}}),R3=he("$ZodCheckMaxSize",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.size!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;r.size<=t.maximum||a.issues.push({origin:sy(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),A3=he("$ZodCheckMinSize",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.size!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;r.size>=t.minimum||a.issues.push({origin:sy(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),I3=he("$ZodCheckSizeEquals",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.size!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=a=>{const r=a.value,i=r.size;if(i===t.size)return;const s=i>t.size;a.issues.push({origin:sy(r),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),O3=he("$ZodCheckMaxLength",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;if(r.length<=t.maximum)return;const s=ly(r);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),D3=he("$ZodCheckMinLength",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;if(r.length>=t.minimum)return;const s=ly(r);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),j3=he("$ZodCheckLengthEquals",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=a=>{const r=a.value,i=r.length;if(i===t.length)return;const s=ly(r),c=i>t.length;a.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),gm=he("$ZodCheckStringFormat",(e,t)=>{var n,a;zn.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),$3=he("$ZodCheckRegex",(e,t)=>{gm.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),L3=he("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=x3),gm.init(e,t)}),M3=he("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=_3),gm.init(e,t)}),P3=he("$ZodCheckIncludes",(e,t)=>{zn.init(e,t);const n=Lo(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),U3=he("$ZodCheckStartsWith",(e,t)=>{zn.init(e,t);const n=new RegExp(`^${Lo(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=a=>{a.value.startsWith(t.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:a.value,inst:e,continue:!t.abort})}}),z3=he("$ZodCheckEndsWith",(e,t)=>{zn.init(e,t);const n=new RegExp(`.*${Lo(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=a=>{a.value.endsWith(t.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:a.value,inst:e,continue:!t.abort})}});function pM(e,t,n){e.issues.length&&t.issues.push(...bi(n,e.issues))}const F3=he("$ZodCheckProperty",(e,t)=>{zn.init(e,t),e._zod.check=n=>{const a=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(a instanceof Promise)return a.then(r=>pM(r,n,t.property));pM(a,n,t.property)}}),B3=he("$ZodCheckMimeType",(e,t)=>{zn.init(e,t);const n=new Set(t.mime);e._zod.onattach.push(a=>{a._zod.bag.mime=t.mime}),e._zod.check=a=>{n.has(a.value.type)||a.issues.push({code:"invalid_value",values:t.mime,input:a.value.type,inst:e,continue:!t.abort})}}),H3=he("$ZodCheckOverwrite",(e,t)=>{zn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class V3{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
|
|
4
4
|
`).filter(s=>s),r=Math.min(...a.map(s=>s.length-s.trimStart().length)),i=a.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,r.join(`
|
|
5
5
|
`))}}const G3={major:4,minor:2,patch:0},wt=he("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=G3;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const r of a)for(const i of r._zod.onattach)i(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(s,c,u)=>{let d=Rl(s),m;for(const h of c){if(h._zod.def.when){if(!h._zod.def.when(s))continue}else if(d)continue;const g=s.issues.length,v=h._zod.check(s);if(v instanceof Promise&&u?.async===!1)throw new $l;if(m||v instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await v,s.issues.length!==g&&(d||(d=Rl(s,g)))});else{if(s.issues.length===g)continue;d||(d=Rl(s,g))}}return m?m.then(()=>s):s},i=(s,c,u)=>{if(Rl(s))return s.aborted=!0,s;const d=r(c,a,u);if(d instanceof Promise){if(u.async===!1)throw new $l;return d.then(m=>e._zod.parse(m,u))}return e._zod.parse(d,u)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(m=>i(m,s,c)):i(d,s,c)}const u=e._zod.parse(s,c);if(u instanceof Promise){if(c.async===!1)throw new $l;return u.then(d=>r(d,a,c))}return r(u,a,c)}}e["~standard"]={validate:r=>{try{const i=fk(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return HF(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),bm=he("$ZodString",(e,t)=>{wt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??h3(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Tn=he("$ZodStringFormat",(e,t)=>{gm.init(e,t),bm.init(e,t)}),W3=he("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=XF),Tn.init(e,t)}),K3=he("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ed(a))}else t.pattern??(t.pattern=ed());Tn.init(e,t)}),Z3=he("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=JF),Tn.init(e,t)}),Y3=he("$ZodURL",(e,t)=>{Tn.init(e,t),e._zod.check=n=>{try{const a=n.value.trim(),r=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),q3=he("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=e3()),Tn.init(e,t)}),X3=he("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=YF),Tn.init(e,t)}),J3=he("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=VF),Tn.init(e,t)}),Q3=he("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=GF),Tn.init(e,t)}),eB=he("$ZodULID",(e,t)=>{t.pattern??(t.pattern=WF),Tn.init(e,t)}),tB=he("$ZodXID",(e,t)=>{t.pattern??(t.pattern=KF),Tn.init(e,t)}),nB=he("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ZF),Tn.init(e,t)}),rB=he("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=m3(t)),Tn.init(e,t)}),aB=he("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=d3),Tn.init(e,t)}),iB=he("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=p3(t)),Tn.init(e,t)}),oB=he("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=qF),Tn.init(e,t)}),sB=he("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=t3),Tn.init(e,t),e._zod.bag.format="ipv4"}),lB=he("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=n3),Tn.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),cB=he("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=r3(t.delimiter)),Tn.init(e,t),e._zod.bag.format="mac"}),uB=he("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=a3),Tn.init(e,t)}),dB=he("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=i3),Tn.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[r,i]=a;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function kk(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const fB=he("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=o3),Tn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{kk(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function pB(e){if(!Sk.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return kk(n)}const mB=he("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Sk),Tn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{pB(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),hB=he("$ZodE164",(e,t)=>{t.pattern??(t.pattern=c3),Tn.init(e,t)});function gB(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const r=JSON.parse(atob(a));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const bB=he("$ZodJWT",(e,t)=>{Tn.init(e,t),e._zod.check=n=>{gB(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),vB=he("$ZodCustomStringFormat",(e,t)=>{Tn.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),Tk=he("$ZodNumber",(e,t)=>{wt.init(e,t),e._zod.pattern=e._zod.bag.pattern??v3,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),n}}),yB=he("$ZodNumberFormat",(e,t)=>{N3.init(e,t),Tk.init(e,t)}),Nk=he("$ZodBoolean",(e,t)=>{wt.init(e,t),e._zod.pattern=y3,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Ck=he("$ZodBigInt",(e,t)=>{wt.init(e,t),e._zod.pattern=g3,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),wB=he("$ZodBigIntFormat",(e,t)=>{C3.init(e,t),Ck.init(e,t)}),SB=he("$ZodSymbol",(e,t)=>{wt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;return typeof r=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),n}}),xB=he("$ZodUndefined",(e,t)=>{wt.init(e,t),e._zod.pattern=S3,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,a)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),_B=he("$ZodNull",(e,t)=>{wt.init(e,t),e._zod.pattern=w3,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),EB=he("$ZodAny",(e,t)=>{wt.init(e,t),e._zod.parse=n=>n}),kB=he("$ZodUnknown",(e,t)=>{wt.init(e,t),e._zod.parse=n=>n}),TB=he("$ZodNever",(e,t)=>{wt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),NB=he("$ZodVoid",(e,t)=>{wt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),CB=he("$ZodDate",(e,t)=>{wt.init(e,t),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}const r=n.value,i=r instanceof Date;return i&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...i?{received:"Invalid Date"}:{},inst:e}),n}});function mM(e,t,n){e.issues.length&&t.issues.push(...bi(n,e.issues)),t.value[n]=e.value}const RB=he("$ZodArray",(e,t)=>{wt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const i=[];for(let s=0;s<r.length;s++){const c=r[s],u=t.element._zod.run({value:c,issues:[]},a);u instanceof Promise?i.push(u.then(d=>mM(d,n,s))):mM(u,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function rv(e,t,n,a){e.issues.length&&t.issues.push(...bi(n,e.issues)),e.value===void 0?n in a&&(t.value[n]=void 0):t.value[n]=e.value}function AB(e){const t=Object.keys(e.shape);for(const a of t)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=TF(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function IB(e,t,n,a,r,i){const s=[],c=r.keySet,u=r.catchall._zod,d=u.def.type;for(const m in t){if(c.has(m))continue;if(d==="never"){s.push(m);continue}const h=u.run({value:t[m],issues:[]},a);h instanceof Promise?e.push(h.then(g=>rv(g,n,m,t))):rv(h,n,m,t)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const OB=he("$ZodObject",(e,t)=>{if(wt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}const a=cm(()=>AB(t));Ht(e._zod,"propValues",()=>{const c=t.shape,u={};for(const d in c){const m=c[d]._zod;if(m.values){u[d]??(u[d]=new Set);for(const h of m.values)u[d].add(h)}}return u});const r=Ju,i=t.catchall;let s;e._zod.parse=(c,u)=>{s??(s=a.value);const d=c.value;if(!r(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const m=[],h=s.shape;for(const g of s.keys){const x=h[g]._zod.run({value:d[g],issues:[]},u);x instanceof Promise?m.push(x.then(S=>rv(S,c,g,d))):rv(x,c,g,d)}return i?IB(m,d,c,u,a.value,e):m.length?Promise.all(m).then(()=>c):c}}),DB=he("$ZodObjectJIT",(e,t)=>{OB.init(e,t);const n=e._zod.parse,a=cm(()=>AB(t)),r=g=>{const v=new V3(["shape","payload","ctx"]),x=a.value,S=k=>{const C=a_(k);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};v.write("const input = payload.value;");const w=Object.create(null);let E=0;for(const k of x.keys)w[k]=`key_${E++}`;v.write("const newResult = {};");for(const k of x.keys){const C=w[k],R=a_(k);v.write(`const ${C} = ${S(k)};`),v.write(`
|
|
@@ -32,7 +32,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
32
32
|
`;break;case"id":c=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?a(parseInt(w,10)):n(new QP(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:E}));break;default:n(new QP(`Unknown field "${S.length>20?`${S.slice(0,20)}…`:S}"`,{type:"unknown-field",field:S,value:w,line:E}));break}}function v(){u.length>0&&t({id:c,event:d||void 0,data:u.endsWith(`
|
|
33
33
|
`)?u.slice(0,-1):u}),c=void 0,u="",d=""}function x(S={}){i&&S.consume&&h(i),s=!0,c=void 0,u="",d="",i=""}return{feed:m,reset:x}}function hoe(e){const t=[];let n="",a=0;for(;a<e.length;){const r=e.indexOf("\r",a),i=e.indexOf(`
|
|
34
34
|
`,a);let s=-1;if(r!==-1&&i!==-1?s=Math.min(r,i):r!==-1?r===e.length-1?s=-1:s=r:i!==-1&&(s=i),s===-1){n=e.slice(a);break}else{const c=e.slice(a,s);t.push(c),a=s+1,e[a-1]==="\r"&&e[a]===`
|
|
35
|
-
`&&a++}}return[t,n]}class goe extends TransformStream{constructor({onError:t,onRetry:n,onComment:a}={}){let r;super({start(i){r=e9({onEvent:s=>{i.enqueue(s)},onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:n,onComment:a})},transform(i){r.feed(i)}})}}const boe={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kl extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class voe{constructor(t,n){var a;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=zV(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=(a=n?.reconnectionOptions)!==null&&a!==void 0?a:boe}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=mv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}async _startOrAuthSse(t){var n,a,r,i;const{resumptionToken:s}=t;try{const c=await this._commonHeaders();c.set("Accept","text/event-stream"),s&&c.set("last-event-id",s);const u=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:c,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!u.ok){if(await((r=u.body)===null||r===void 0?void 0:r.cancel()),u.status===401&&this._authProvider)return await this._authThenStart();if(u.status===405)return;throw new kl(u.status,`Failed to open SSE stream: ${u.statusText}`)}this._handleSseStream(u.body,t,!0)}catch(c){throw(i=this.onerror)===null||i===void 0||i.call(this,c),c}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(a,t),r)}_scheduleReconnection(t,n=0){var a;const r=this._reconnectionOptions.maxRetries;if(n>=r){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const i=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,n+1)})},i)}_handleSseStream(t,n,a){if(!t)return;const{onresumptiontoken:r,replayMessageId:i}=n;let s,c=!1,u=!1;(async()=>{var m,h,g,v;try{const x=t.pipeThrough(new TextDecoderStream).pipeThrough(new goe({onRetry:E=>{this._serverRetryMs=E}})).getReader();for(;;){const{value:E,done:_}=await x.read();if(_)break;if(E.id&&(s=E.id,c=!0,r?.(E.id)),!!E.data&&(!E.event||E.event==="message"))try{const k=Rb.parse(JSON.parse(E.data));Qf(k)&&(u=!0,i!==void 0&&(k.id=i)),(m=this.onmessage)===null||m===void 0||m.call(this,k)}catch(k){(h=this.onerror)===null||h===void 0||h.call(this,k)}}(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(x){if((g=this.onerror)===null||g===void 0||g.call(this,new Error(`SSE stream disconnected: ${x}`)),(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(E){(v=this.onerror)===null||v===void 0||v.call(this,new Error(`Failed to reconnect: ${E instanceof Error?E.message:String(E)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Ro(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var a,r,i,s,c,u,d;try{const{resumptionToken:m,onresumptiontoken:h}=n||{};if(m){this._startOrAuthSse({resumptionToken:m,replayMessageId:f_(t)?t.id:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const g=await this._commonHeaders();g.set("content-type","application/json"),g.set("accept","application/json, text/event-stream");const v={...this._requestInit,method:"POST",headers:g,body:JSON.stringify(t),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},x=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,v),S=x.headers.get("mcp-session-id");if(S&&(this._sessionId=S),!x.ok){const k=await x.text().catch(()=>null);if(x.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kl(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:C,scope:R}=Lp(x);if(this._resourceMetadataUrl=C,this._scope=R,await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this._hasCompletedAuthFlow=!0,this.send(t)}if(x.status===403&&this._authProvider){const{resourceMetadataUrl:C,scope:R,error:I}=Lp(x);if(I==="insufficient_scope"){const A=x.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===A)throw new kl(403,"Server returned 403 after trying upscoping");if(R&&(this._scope=R),C&&(this._resourceMetadataUrl=C),this._lastUpscopingHeader=A??void 0,await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qa;return this.send(t)}}throw new kl(x.status,`Error POSTing to endpoint: ${k}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,x.status===202){await((i=x.body)===null||i===void 0?void 0:i.cancel()),cre(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const E=(Array.isArray(t)?t:[t]).filter(k=>"method"in k&&"id"in k&&k.id!==void 0).length>0,_=x.headers.get("content-type");if(E)if(_?.includes("text/event-stream"))this._handleSseStream(x.body,{onresumptiontoken:h},!1);else if(_?.includes("application/json")){const k=await x.json(),C=Array.isArray(k)?k.map(R=>Rb.parse(R)):[Rb.parse(k)];for(const R of C)(s=this.onmessage)===null||s===void 0||s.call(this,R)}else throw await((c=x.body)===null||c===void 0?void 0:c.cancel()),new kl(-1,`Unexpected content type: ${_}`);else await((u=x.body)===null||u===void 0?void 0:u.cancel())}catch(m){throw(d=this.onerror)===null||d===void 0||d.call(this,m),m}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,a,r;if(this._sessionId)try{const i=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},c=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(await((a=c.body)===null||a===void 0?void 0:a.cancel()),!c.ok&&c.status!==405)throw new kl(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(i){throw(r=this.onerror)===null||r===void 0||r.call(this,i),i}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class eU extends Event{constructor(t,n){var a,r;super(t),this.code=(a=n?.code)!=null?a:void 0,this.message=(r=n?.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,a){return a(tU(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(tU(this),n)}}function yoe(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function k_(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(k_).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${k_(e.cause)}`:e.message:`${e}`}function tU(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var t9=e=>{throw TypeError(e)},vN=(e,t,n)=>t.has(e)||t9("Cannot "+n),Ft=(e,t,n)=>(vN(e,t,"read from private field"),n?n.call(e):t.get(e)),dr=(e,t,n)=>t.has(e)?t9("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Mn=(e,t,n,a)=>(vN(e,t,"write to private field"),t.set(e,n),n),_o=(e,t,n)=>(vN(e,t,"access private method"),n),ba,Nl,Qc,Ib,yv,dp,uu,fp,Cs,eu,Su,tu,ep,fi,T_,N_,C_,nU,R_,A_,tp,I_,O_;class Ob extends EventTarget{constructor(t,n){var a,r;super(),dr(this,fi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,dr(this,ba),dr(this,Nl),dr(this,Qc),dr(this,Ib),dr(this,yv),dr(this,dp),dr(this,uu),dr(this,fp,null),dr(this,Cs),dr(this,eu),dr(this,Su,null),dr(this,tu,null),dr(this,ep,null),dr(this,N_,async i=>{var s;Ft(this,eu).reset();const{body:c,redirected:u,status:d,headers:m}=i;if(d===204){_o(this,fi,tp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Mn(this,Qc,new URL(i.url)):Mn(this,Qc,void 0),d!==200){_o(this,fi,tp).call(this,`Non-200 status code (${d})`,d);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){_o(this,fi,tp).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.OPEN);const h=new Event("open");if((s=Ft(this,ep))==null||s.call(this,h),this.dispatchEvent(h),typeof c!="object"||!c||!("getReader"in c)){_o(this,fi,tp).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}const g=new TextDecoder,v=c.getReader();let x=!0;do{const{done:S,value:w}=await v.read();w&&Ft(this,eu).feed(g.decode(w,{stream:!S})),S&&(x=!1,Ft(this,eu).reset(),_o(this,fi,I_).call(this))}while(x)}),dr(this,C_,i=>{Mn(this,Cs,void 0),!(i.name==="AbortError"||i.type==="aborted")&&_o(this,fi,I_).call(this,k_(i))}),dr(this,R_,i=>{typeof i.id=="string"&&Mn(this,fp,i.id);const s=new MessageEvent(i.event||"message",{data:i.data,origin:Ft(this,Qc)?Ft(this,Qc).origin:Ft(this,Nl).origin,lastEventId:i.id||""});Ft(this,tu)&&(!i.event||i.event==="message")&&Ft(this,tu).call(this,s),this.dispatchEvent(s)}),dr(this,A_,i=>{Mn(this,dp,i)}),dr(this,O_,()=>{Mn(this,uu,void 0),Ft(this,ba)===this.CONNECTING&&_o(this,fi,T_).call(this)});try{if(t instanceof URL)Mn(this,Nl,t);else if(typeof t=="string")Mn(this,Nl,new URL(t,woe()));else throw new Error("Invalid URL")}catch{throw yoe("An invalid or illegal string was specified")}Mn(this,eu,e9({onEvent:Ft(this,R_),onRetry:Ft(this,A_)})),Mn(this,ba,this.CONNECTING),Mn(this,dp,3e3),Mn(this,yv,(a=n?.fetch)!=null?a:globalThis.fetch),Mn(this,Ib,(r=n?.withCredentials)!=null?r:!1),_o(this,fi,T_).call(this)}get readyState(){return Ft(this,ba)}get url(){return Ft(this,Nl).href}get withCredentials(){return Ft(this,Ib)}get onerror(){return Ft(this,Su)}set onerror(t){Mn(this,Su,t)}get onmessage(){return Ft(this,tu)}set onmessage(t){Mn(this,tu,t)}get onopen(){return Ft(this,ep)}set onopen(t){Mn(this,ep,t)}addEventListener(t,n,a){const r=n;super.addEventListener(t,r,a)}removeEventListener(t,n,a){const r=n;super.removeEventListener(t,r,a)}close(){Ft(this,uu)&&clearTimeout(Ft(this,uu)),Ft(this,ba)!==this.CLOSED&&(Ft(this,Cs)&&Ft(this,Cs).abort(),Mn(this,ba,this.CLOSED),Mn(this,Cs,void 0))}}ba=new WeakMap,Nl=new WeakMap,Qc=new WeakMap,Ib=new WeakMap,yv=new WeakMap,dp=new WeakMap,uu=new WeakMap,fp=new WeakMap,Cs=new WeakMap,eu=new WeakMap,Su=new WeakMap,tu=new WeakMap,ep=new WeakMap,fi=new WeakSet,T_=function(){Mn(this,ba,this.CONNECTING),Mn(this,Cs,new AbortController),Ft(this,yv)(Ft(this,Nl),_o(this,fi,nU).call(this)).then(Ft(this,N_)).catch(Ft(this,C_))},N_=new WeakMap,C_=new WeakMap,nU=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ft(this,fp)?{"Last-Event-ID":Ft(this,fp)}:void 0},cache:"no-store",signal:(e=Ft(this,Cs))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},R_=new WeakMap,A_=new WeakMap,tp=function(e,t){var n;Ft(this,ba)!==this.CLOSED&&Mn(this,ba,this.CLOSED);const a=new eU("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a)},I_=function(e,t){var n;if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.CONNECTING);const a=new eU("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a),Mn(this,uu,setTimeout(Ft(this,O_),Ft(this,dp)))},O_=new WeakMap,Ob.CONNECTING=0,Ob.OPEN=1,Ob.CLOSED=2;function woe(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class Soe extends Error{constructor(t,n,a){super(`SSE error: ${n}`),this.code=t,this.event=a}}class xoe{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n?.eventSourceInit,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=zV(n?.fetch,n?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=mv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}_startOrAuth(){var t,n,a;const r=(a=(n=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&n!==void 0?n:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((i,s)=>{this._eventSource=new Ob(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{const d=await this._commonHeaders();d.set("Accept","text/event-stream");const m=await r(c,{...u,headers:d});if(m.status===401&&m.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:g}=Lp(m);this._resourceMetadataUrl=h,this._scope=g}return m}}),this._abortController=new AbortController,this._eventSource.onerror=c=>{var u;if(c.code===401&&this._authProvider){this._authThenStart().then(i,s);return}const d=new Soe(c.code,c.message,c);s(d),(u=this.onerror)===null||u===void 0||u.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;const d=c;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(m){s(m),(u=this.onerror)===null||u===void 0||u.call(this,m),this.close();return}i()}),this._eventSource.onmessage=c=>{var u,d;const m=c;let h;try{h=Rb.parse(JSON.parse(m.data))}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g);return}(d=this.onmessage)===null||d===void 0||d.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Ro(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n,a;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(t){var n,a,r,i;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const c={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},u=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,c);if(!u.ok){const d=await u.text().catch(()=>null);if(u.status===401&&this._authProvider){const{resourceMetadataUrl:m,scope:h}=Lp(u);if(this._resourceMetadataUrl=m,this._scope=h,await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${d}`)}await((r=u.body)===null||r===void 0?void 0:r.cancel())}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}}var Vu,_oe=(Vu=class{connector;autoConnect;constructor(t,n=!0){this.connector=t,this.autoConnect=n}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}on(t,n){t==="notification"&&this.connector.onNotification(n)}async setRoots(t){return this.connector.setRoots(t)}getRoots(){return this.connector.getRoots()}get tools(){return this.connector.tools}async listTools(t){return this.connector.listTools(t)}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n={},a){return this.connector.callTool(t,n,a)}async listResources(t,n){return this.connector.listResources(t,n)}async listAllResources(t){return this.connector.listAllResources(t)}async listResourceTemplates(t){return this.connector.listResourceTemplates(t)}async readResource(t,n){return this.connector.readResource(t,n)}async subscribeToResource(t,n){return this.connector.subscribeToResource(t,n)}async unsubscribeFromResource(t,n){return this.connector.unsubscribeFromResource(t,n)}async listPrompts(){return this.connector.listPrompts()}async getPrompt(t,n){return this.connector.getPrompt(t,n)}async request(t,n=null,a){return this.connector.request(t,n,a)}},Be(Vu,"MCPSession"),Vu),Gu,Eoe=(Gu=class{config={};sessions={};activeSessions=[];constructor(t){t&&(this.config=t)}static fromDict(t){throw new Error("fromDict must be implemented by concrete class")}addServer(t,n){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[t]=n,zi.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),zi.getInstance().trackClientRemoveServer(t))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(t){return this.config.mcpServers?.[t]}getConfig(){return this.config??{}}async createSession(t,n=!0){const a=this.config.mcpServers??{};if(Object.keys(a).length===0&&Ce.warn("No MCP servers defined in config"),!a[t])throw new Error(`Server '${t}' not found in config`);const r=this.createConnectorFromConfig(a[t]),i=new _oe(r);return n&&await i.initialize(),this.sessions[t]=i,this.activeSessions.includes(t)||this.activeSessions.push(t),i}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&Ce.warn("No MCP servers defined in config");for(const a of Object.keys(n))await this.createSession(a,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}requireSession(t){const n=this.sessions[t];if(!n)throw new Error(`Session '${t}' not found. Available sessions: ${this.activeSessions.join(", ")||"none"}`);return n}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){Ce.warn(`No session exists for server ${t}, nothing to close`);return}try{Ce.debug(`Closing session for server ${t}`),await n.disconnect()}catch(a){Ce.error(`Error closing session for server '${t}': ${a}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(a=>a!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const a of t)try{Ce.debug(`Closing session for server ${a}`),await this.closeSession(a)}catch(r){const i=`Failed to close session for server '${a}': ${r}`;Ce.error(i),n.push(i)}n.length?Ce.error(`Encountered ${n.length} errors while closing sessions`):Ce.debug("All sessions closed successfully")}},Be(Gu,"BaseMCPClient"),Gu),Wu,koe=(Wu=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;opts;notificationHandlers=[];rootsCache=[];constructor(t={}){this.opts=t,t.roots&&(this.rootsCache=[...t.roots])}trackConnectorInit(t){const n=this.constructor.name;yF.getInstance().trackConnectorInit({connectorType:n,...t}).catch(a=>Ce.debug(`Failed to track connector init: ${a}`))}onNotification(t){this.notificationHandlers.push(t),this.client&&this.setupNotificationHandler()}setupNotificationHandler(){this.client&&(this.client.fallbackNotificationHandler=async t=>{switch(t.method){case"notifications/tools/list_changed":await this.refreshToolsCache();break;case"notifications/resources/list_changed":await this.onResourcesListChanged();break;case"notifications/prompts/list_changed":await this.onPromptsListChanged();break}for(const n of this.notificationHandlers)try{await n(t)}catch(a){Ce.error("Error in notification handler:",a)}})}async refreshToolsCache(){if(this.client)try{Ce.debug("[Auto] Refreshing tools cache due to list_changed notification");const t=await this.client.listTools();this.toolsCache=t.tools??[],Ce.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(t){Ce.warn("[Auto] Failed to refresh tools cache:",t)}}async onResourcesListChanged(){Ce.debug("[Auto] Resources list changed - clients should re-fetch if needed")}async onPromptsListChanged(){Ce.debug("[Auto] Prompts list changed - clients should re-fetch if needed")}async setRoots(t){this.rootsCache=[...t],this.client&&(Ce.debug(`Sending roots/list_changed notification with ${t.length} root(s)`),await this.client.sendRootsListChanged())}getRoots(){return[...this.rootsCache]}setupRootsHandler(){this.client&&this.client.setRequestHandler(AV,async(t,n)=>(Ce.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){Ce.debug("setupSamplingHandler: No client available");return}if(!this.opts.samplingCallback){Ce.debug("setupSamplingHandler: No sampling callback provided");return}Ce.debug("setupSamplingHandler: Setting up sampling request handler"),this.client.setRequestHandler(cN,async(t,n)=>(Ce.debug("Server requested sampling, forwarding to callback"),await this.opts.samplingCallback(t.params))),Ce.debug("setupSamplingHandler: Sampling handler registered successfully")}setupElicitationHandler(){if(!this.client){Ce.debug("setupElicitationHandler: No client available");return}if(!this.opts.elicitationCallback){Ce.debug("setupElicitationHandler: No elicitation callback provided");return}Ce.debug("setupElicitationHandler: Setting up elicitation request handler"),this.client.setRequestHandler(dN,async(t,n)=>(Ce.debug("Server requested elicitation, forwarding to callback"),await this.opts.elicitationCallback(t.params))),Ce.debug("setupElicitationHandler: Elicitation handler registered successfully")}async disconnect(){if(!this.connected){Ce.debug("Not connected to MCP implementation");return}Ce.debug("Disconnecting from MCP implementation"),await this.cleanupResources(),this.connected=!1,Ce.debug("Disconnected from MCP implementation")}get isClientConnected(){return this.client!=null}async initialize(t=this.opts.defaultRequestOptions??{}){if(!this.client)throw new Error("MCP client is not connected");Ce.debug("Caching server capabilities & tools");const n=this.client.getServerCapabilities();this.capabilitiesCache=n||null;const a=this.client.getServerVersion();this.serverInfoCache=a||null;const r=await this.client.listTools(void 0,t);return this.toolsCache=r.tools??[],Ce.debug(`Fetched ${this.toolsCache.length} tools from server`),Ce.debug("Server capabilities:",n),Ce.debug("Server info:",a),n}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized; call initialize() first");return this.toolsCache}get serverCapabilities(){return this.capabilitiesCache||{}}get serverInfo(){return this.serverInfoCache}async callTool(t,n,a){if(!this.client)throw new Error("MCP client is not connected");const r=a?{...a}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},Ce.debug(`[BaseConnector] Added onprogress callback for tool '${t}' to enable progressToken`)),Ce.debug(`Calling tool '${t}' with args`,n);const i=await this.client.callTool({name:t,arguments:n},void 0,r);return Ce.debug(`Tool '${t}' returned`,i),i}async listTools(t){if(!this.client)throw new Error("MCP client is not connected");return(await this.client.listTools(void 0,t)).tools??[]}async listResources(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resources",t?`with cursor: ${t}`:""),await this.client.listResources({cursor:t},n)}async listAllResources(t){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.resources)return Ce.debug("Server does not advertise resources capability, skipping"),{resources:[]};try{Ce.debug("Listing all resources (with auto-pagination)");const n=[];let a;do{const r=await this.client.listResources({cursor:a},t);n.push(...r.resources||[]),a=r.nextCursor}while(a);return{resources:n}}catch(n){if(n.code===-32601)return Ce.debug("Server advertised resources but method not found"),{resources:[]};throw n}}async listResourceTemplates(t){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resource templates"),await this.client.listResourceTemplates(void 0,t)}async readResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Reading resource ${t}`),await this.client.readResource({uri:t},n)}async subscribeToResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Subscribing to resource: ${t}`),await this.client.subscribeResource({uri:t},n)}async unsubscribeFromResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Unsubscribing from resource: ${t}`),await this.client.unsubscribeResource({uri:t},n)}async listPrompts(){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.prompts)return Ce.debug("Server does not advertise prompts capability, skipping"),{prompts:[]};try{return Ce.debug("Listing prompts"),await this.client.listPrompts()}catch(t){if(t.code===-32601)return Ce.debug("Server advertised prompts but method not found"),{prompts:[]};throw t}}async getPrompt(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Getting prompt ${t}`),await this.client.getPrompt({name:t,arguments:n})}async request(t,n=null,a){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Sending raw request '${t}' with params`,n),await this.client.request({method:t,params:n??{}},void 0,a)}async cleanupResources(){const t=[];if(this.client)try{typeof this.client.close=="function"&&await this.client.close()}catch(n){const a=`Error closing client: ${n}`;Ce.warn(a),t.push(a)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(n){const a=`Error stopping connection manager: ${n}`;Ce.warn(a),t.push(a)}finally{this.connectionManager=null}this.toolsCache=null,t.length&&Ce.warn(`Resource cleanup finished with ${t.length} issue(s)`)}},Be(Wu,"BaseConnector"),Wu),Ku,Toe=(Ku=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),Ce.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw new Error("Connection was not established");return this._connection}async stop(){if(this._task&&this._abortController){Ce.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?Ce.debug(`${this.constructor.name} task aborted successfully`):Ce.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,Ce.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(t=>this._readyResolver=t),this._donePromise=new Promise(t=>this._doneResolver=t),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){Ce.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),Ce.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,Ce.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){Ce.warn(`Error closing connection in ${this.constructor.name}: ${t}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((t,n)=>{if(!this._abortController)return;const a=this._abortController.signal;if(a.aborted){t();return}const r=Be(()=>{a.removeEventListener("abort",r),t()},"onAbort");a.addEventListener("abort",r)})}},Be(Ku,"ConnectionManager"),Ku),Zu,Noe=(Zu=class extends Toe{url;opts;_transport=null;reinitializing=!1;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){const t=new xoe(this.url,this.opts),n=t.send.bind(t);return t.send=async a=>{const r=Be(async i=>{if(Array.isArray(i))for(const s of i)await n(s);else await n(i)},"sendMessage");try{await r(a)}catch(i){if(i?.code===404&&t.sessionId&&!this.reinitializing){Ce.warn("[SSE] Session not found (404), re-initializing per MCP spec..."),this.reinitializing=!0;try{t.sessionId=void 0,await this.reinitialize(t),Ce.info("[SSE] Re-initialization successful, retrying request"),await r(a)}finally{this.reinitializing=!1}}else throw i}},this._transport=t,Ce.debug(`${this.constructor.name} connected successfully`),t}async reinitialize(t){Ce.debug("[SSE] Re-initialization triggered")}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){Ce.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},Be(Zu,"SseConnectionManager"),Zu),Yu,Coe=(Yu=class extends koe{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;disableSseFallback;transportType=null;streamableTransport=null;constructor(t,n={}){super(n),this.baseUrl=t.replace(/\/$/,""),this.headers={...n.headers??{}},n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`),this.timeout=n.timeout??3e4,this.sseReadTimeout=n.sseReadTimeout??3e5,this.clientInfo=n.clientInfo??{name:"http-connector",version:"1.0.0"},this.preferSse=n.preferSse??!1,this.disableSseFallback=n.disableSseFallback??!1}async connect(){if(this.connected){Ce.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){Ce.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}Ce.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{Ce.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),Ce.info("✅ Successfully connected via streamable HTTP")}catch(n){let a="Unknown error",r=!1;if(n instanceof kl){const i=n;r=i.code===401,i.code===400&&i.message.includes("Missing session ID")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.code===404||i.code===405?(a=`Server returned ${i.code} - server likely doesn't support streamable HTTP`,Ce.debug(a)):(a=`Server returned ${i.code}: ${i.message}`,Ce.debug(a))}else if(n instanceof Error){const i=n.toString(),s=n.message||"";r=i.includes("401")||s.includes("Unauthorized"),i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||s.includes("FastMCP session ID error")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.includes("405 Method Not Allowed")||i.includes("404 Not Found")?(a="Server doesn't support streamable HTTP (405/404)",Ce.debug(a)):(a=`Streamable HTTP failed: ${n.message}`,Ce.debug(a))}if(r){Ce.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const i=new Error("Authentication required");throw i.code=401,i}if(this.disableSseFallback)throw Ce.info("SSE fallback disabled - failing connection"),await this.cleanupResources(),new Error(`Streamable HTTP connection failed: ${a}. SSE fallback is disabled.`);Ce.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(i){if(Ce.error("Failed to connect with both transports:"),Ce.error(` Streamable HTTP: ${a}`),Ce.error(` SSE: ${i}`),await this.cleanupResources(),i?.message?.includes("401")||i?.message?.includes("Unauthorized")){const c=new Error("Authentication required");throw c.code=401,c}throw new Error("Could not connect to server with any available transport")}}}async connectWithStreamableHttp(t){try{const n=new voe(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let a=n;if(this.opts.wrapTransport){const i=this.baseUrl;a=this.opts.wrapTransport(a,i)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities:",JSON.stringify(r.capabilities,null,2)),this.client=new YP(this.clientInfo,r),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect");try{await this.client.connect(a,{timeout:Math.min(this.timeout,3e3)});const i=n.sessionId;i?Ce.debug(`Session ID obtained: ${i}`):Ce.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(i){if(i instanceof Error){const s=i.message||i.toString();if(s.includes("Missing session ID")||s.includes("Bad Request: Missing session ID")||s.includes("Mcp-Session-Id header is required")){const c=new Error(`Session ID error: ${s}. The SDK should automatically extract session ID from initialize response.`);throw c.cause=i,c}}throw i}this.streamableTransport=n,this.connectionManager={stop:Be(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(i){Ce.warn(`Error closing Streamable HTTP transport: ${i}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via streamable HTTP: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (streamable-http)`})}catch(n){throw await this.cleanupResources(),n}}async connectWithSse(t){try{this.connectionManager=new Noe(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const r=this.baseUrl;n=this.opts.wrapTransport(n,r)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities (SSE):",JSON.stringify(a.capabilities,null,2)),this.client=new YP(this.clientInfo,a),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (sse)`})}catch(n){throw await this.cleanupResources(),n}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown"}}getTransportType(){return this.transportType}},Be(Yu,"HttpConnector"),Yu),zl,Roe=(zl=class extends Eoe{static getPackageVersion(){return Qb()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});zi.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>Ce.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new zl(t)}createConnectorFromConfig(t){const{url:n,headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h}=t;if(!n)throw new Error("Server URL is required");const g={headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h};return c?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(c,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),new Coe(n,g)}},Be(zl,"BrowserMCPClient"),zl);function du(e){const t=Be(()=>{throw new Error(`Invalid url to pass to open(): ${e}`)},"abort");let n;try{n=new URL(e)}catch{t()}return n.protocol!=="https:"&&n.protocol!=="http:"&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&(n.username=encodeURIComponent(n.username)),n.password&&(n.password=encodeURIComponent(n.password)),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,"/"),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(n9).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}Be(du,"sanitizeUrl");function n9([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}Be(n9,"sanitizeParam");var qu,Db=(qu=class{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;callbackUrl;preventAutoAuth;useRedirectFlow;onPopupWindow;constructor(t,n={}){this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||"mcp:auth",this.serverUrlHash=this.hashString(t),this.clientName=n.clientName||"mcp-use",this.clientUri=n.clientUri||(typeof window<"u"?window.location.origin:""),this.callbackUrl=du(n.callbackUrl||(typeof window<"u"?new URL("/oauth/callback",window.location.origin).toString():"/oauth/callback")),this.preventAutoAuth=n.preventAutoAuth,this.useRedirectFlow=n.useRedirectFlow,this.onPopupWindow=n.onPopupWindow}get redirectUrl(){return du(this.callbackUrl)}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:this.clientName,client_uri:this.clientUri}}async clientInformation(){const t=this.getKey("client_info"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,a),localStorage.removeItem(t);return}}async saveClientInformation(t){const n=this.getKey("client_info");localStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=this.getKey("tokens"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,a),localStorage.removeItem(t);return}}async saveTokens(t){const n=this.getKey("tokens");localStorage.setItem(n,JSON.stringify(t)),localStorage.removeItem(this.getKey("code_verifier")),localStorage.removeItem(this.getKey("last_auth_url"))}async saveCodeVerifier(t){const n=this.getKey("code_verifier");localStorage.setItem(n,t)}async codeVerifier(){const t=this.getKey("code_verifier"),n=localStorage.getItem(t);if(!n)throw new Error(`[${this.storageKeyPrefix}] Code verifier not found in storage for key ${t}. Auth flow likely corrupted or timed out.`);return n}async prepareAuthorizationUrl(t){const n=globalThis.crypto.randomUUID(),a=`${this.storageKeyPrefix}:state_${n}`,r={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,providerOptions:{serverUrl:this.serverUrl,storageKeyPrefix:this.storageKeyPrefix,clientName:this.clientName,clientUri:this.clientUri,callbackUrl:this.callbackUrl},flowType:this.useRedirectFlow?"redirect":"popup",returnUrl:this.useRedirectFlow&&typeof window<"u"?window.location.href:void 0};localStorage.setItem(a,JSON.stringify(r)),t.searchParams.set("state",n);const i=t.toString(),s=du(i);return localStorage.setItem(this.getKey("last_auth_url"),s),s}async redirectToAuthorization(t){const n=await this.prepareAuthorizationUrl(t);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=n;return}const a="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const r=window.open(n,`mcp_auth_${this.serverUrlHash}`,a);this.onPopupWindow&&this.onPopupWindow(n,a,r),!r||r.closed||typeof r.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(r.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(r){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,r)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?du(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,a=[];let r=0;for(let s=0;s<localStorage.length;s++){const c=localStorage.key(s);if(c){if(c.startsWith(t))a.push(c);else if(c.startsWith(n))try{const u=localStorage.getItem(c);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&a.push(c)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${c} during clearStorage:`,u)}}}return[...new Set(a)].forEach(s=>{localStorage.removeItem(s),r++}),r}hashString(t){let n=0;for(let a=0;a<t.length;a++){const r=t.charCodeAt(a);n=(n<<5)-n+r,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},Be(qu,"BrowserOAuthClientProvider"),qu);async function yN(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),a=e.get("error"),r=e.get("error_description"),i="[mcp-callback]";console.log(`${i} Handling callback...`,{code:t,state:n,error:a,errorDescription:r});let s=null,c=null;const u=n?`mcp:auth:state_${n}`:null;try{if(a)throw new Error(`OAuth error: ${a} - ${r||"No description provided."}`);if(!t)throw new Error("Authorization code not found in callback query parameters.");if(!n||!u)throw new Error("State parameter not found or invalid in callback query parameters.");const d=localStorage.getItem(u);if(!d)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{c=JSON.parse(d)}catch{throw new Error("Failed to parse stored OAuth state.")}if(!c.expiry||c.expiry<Date.now())throw localStorage.removeItem(u),new Error("OAuth state has expired. Please try initiating authentication again.");if(!c.providerOptions)throw new Error("Stored state is missing required provider options.");const{serverUrl:m,...h}=c.providerOptions;console.log(`${i} Re-instantiating provider for server: ${m}`),s=new Db(m,h),console.log(`${i} Calling SDK auth() to exchange code...`);const g=new URL(m).origin,v=await Ro(s,{serverUrl:g,authorizationCode:t});if(v==="AUTHORIZED")if(console.log(`${i} Authorization successful via SDK auth().`),c.flowType==="redirect"&&c.returnUrl)console.log(`${i} Redirect flow complete. Returning to: ${c.returnUrl}`),localStorage.removeItem(u),window.location.href=c.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${i} Popup flow complete. Notifying opener...`),window.opener.postMessage({type:"mcp_auth_callback",success:!0},window.location.origin),localStorage.removeItem(u),window.close();else{console.warn(`${i} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const S=window.location.pathname.split("/").filter(Boolean),w=S.length>0&&S[S.length-1]==="callback"?"/"+S.slice(0,-2).join("/"):"/";window.location.href=w||"/"}else throw console.warn(`${i} SDK auth() returned unexpected status: ${v}`),new Error(`Unexpected result from authentication library: ${v}`)}catch(d){console.error(`${i} Error during OAuth callback handling:`,d);const m=d instanceof Error?d.message:String(d);window.opener&&!window.opener.closed&&window.opener.postMessage({type:"mcp_auth_callback",success:!1,error:m},window.location.origin);try{document.body.innerHTML="";const h=document.createElement("div");h.style.fontFamily="sans-serif",h.style.padding="20px";const g=document.createElement("h1");g.textContent="Authentication Error",h.appendChild(g);const v=document.createElement("p");v.style.color="red",v.style.backgroundColor="#ffebeb",v.style.border="1px solid red",v.style.padding="10px",v.style.borderRadius="4px",v.textContent=m,h.appendChild(v);const x=document.createElement("p");x.textContent="You can close this window or ";const S=document.createElement("a");if(S.href="#",S.textContent="click here to close",S.onclick=w=>(w.preventDefault(),window.close(),!1),x.appendChild(S),x.appendChild(document.createTextNode(".")),h.appendChild(x),d instanceof Error&&d.stack){const w=document.createElement("pre");w.style.fontSize="0.8em",w.style.color="#555",w.style.marginTop="20px",w.style.whiteSpace="pre-wrap",w.textContent=d.stack,h.appendChild(w)}document.body.appendChild(h)}catch(h){console.error(`${i} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),s&&(localStorage.removeItem(s.getKey("code_verifier")),localStorage.removeItem(s.getKey("last_auth_url")))}}Be(yN,"onMcpAuthorization");var nx={exports:{}},yt={};var rU;function Aoe(){if(rU)return yt;rU=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),s=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function v(j){return j===null||typeof j!="object"?null:(j=g&&j[g]||j["@@iterator"],typeof j=="function"?j:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,w={};function E(j,V,z){this.props=j,this.context=V,this.refs=w,this.updater=z||x}E.prototype.isReactComponent={},E.prototype.setState=function(j,V){if(typeof j!="object"&&typeof j!="function"&&j!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,j,V,"setState")},E.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function _(){}_.prototype=E.prototype;function k(j,V,z){this.props=j,this.context=V,this.refs=w,this.updater=z||x}var C=k.prototype=new _;C.constructor=k,S(C,E.prototype),C.isPureReactComponent=!0;var R=Array.isArray;function I(){}var A={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function M(j,V,z){var $=z.ref;return{$$typeof:e,type:j,key:V,ref:$!==void 0?$:null,props:z}}function P(j,V){return M(j.type,V,j.props)}function B(j){return typeof j=="object"&&j!==null&&j.$$typeof===e}function K(j){var V={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(z){return V[z]})}var Q=/\/+/g;function ee(j,V){return typeof j=="object"&&j!==null&&j.key!=null?K(""+j.key):V.toString(36)}function ae(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then(I,I):(j.status="pending",j.then(function(V){j.status==="pending"&&(j.status="fulfilled",j.value=V)},function(V){j.status==="pending"&&(j.status="rejected",j.reason=V)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function H(j,V,z,$,L){var F=typeof j;(F==="undefined"||F==="boolean")&&(j=null);var W=!1;if(j===null)W=!0;else switch(F){case"bigint":case"string":case"number":W=!0;break;case"object":switch(j.$$typeof){case e:case t:W=!0;break;case m:return W=j._init,H(W(j._payload),V,z,$,L)}}if(W)return L=L(j),W=$===""?"."+ee(j,0):$,R(L)?(z="",W!=null&&(z=W.replace(Q,"$&/")+"/"),H(L,V,z,"",function(ue){return ue})):L!=null&&(B(L)&&(L=P(L,z+(L.key==null||j&&j.key===L.key?"":(""+L.key).replace(Q,"$&/")+"/")+W)),V.push(L)),1;W=0;var ne=$===""?".":$+":";if(R(j))for(var le=0;le<j.length;le++)$=j[le],F=ne+ee($,le),W+=H($,V,z,F,L);else if(le=v(j),typeof le=="function")for(j=le.call(j),le=0;!($=j.next()).done;)$=$.value,F=ne+ee($,le++),W+=H($,V,z,F,L);else if(F==="object"){if(typeof j.then=="function")return H(ae(j),V,z,$,L);throw V=String(j),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys(j).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.")}return W}function Z(j,V,z){if(j==null)return j;var $=[],L=0;return H(j,$,"","",function(F){return V.call(z,F,L++)}),$}function G(j){if(j._status===-1){var V=j._result;V=V(),V.then(function(z){(j._status===0||j._status===-1)&&(j._status=1,j._result=z)},function(z){(j._status===0||j._status===-1)&&(j._status=2,j._result=z)}),j._status===-1&&(j._status=0,j._result=V)}if(j._status===1)return j._result.default;throw j._result}var re=typeof reportError=="function"?reportError:function(j){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var V=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof j=="object"&&j!==null&&typeof j.message=="string"?String(j.message):String(j),error:j});if(!window.dispatchEvent(V))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",j);return}console.error(j)},te={map:Z,forEach:function(j,V,z){Z(j,function(){V.apply(this,arguments)},z)},count:function(j){var V=0;return Z(j,function(){V++}),V},toArray:function(j){return Z(j,function(V){return V})||[]},only:function(j){if(!B(j))throw Error("React.Children.only expected to receive a single React element child.");return j}};return yt.Activity=h,yt.Children=te,yt.Component=E,yt.Fragment=n,yt.Profiler=r,yt.PureComponent=k,yt.StrictMode=a,yt.Suspense=u,yt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,yt.__COMPILER_RUNTIME={__proto__:null,c:function(j){return A.H.useMemoCache(j)}},yt.cache=function(j){return function(){return j.apply(null,arguments)}},yt.cacheSignal=function(){return null},yt.cloneElement=function(j,V,z){if(j==null)throw Error("The argument must be a React element, but you passed "+j+".");var $=S({},j.props),L=j.key;if(V!=null)for(F in V.key!==void 0&&(L=""+V.key),V)!O.call(V,F)||F==="key"||F==="__self"||F==="__source"||F==="ref"&&V.ref===void 0||($[F]=V[F]);var F=arguments.length-2;if(F===1)$.children=z;else if(1<F){for(var W=Array(F),ne=0;ne<F;ne++)W[ne]=arguments[ne+2];$.children=W}return M(j.type,L,$)},yt.createContext=function(j){return j={$$typeof:s,_currentValue:j,_currentValue2:j,_threadCount:0,Provider:null,Consumer:null},j.Provider=j,j.Consumer={$$typeof:i,_context:j},j},yt.createElement=function(j,V,z){var $,L={},F=null;if(V!=null)for($ in V.key!==void 0&&(F=""+V.key),V)O.call(V,$)&&$!=="key"&&$!=="__self"&&$!=="__source"&&(L[$]=V[$]);var W=arguments.length-2;if(W===1)L.children=z;else if(1<W){for(var ne=Array(W),le=0;le<W;le++)ne[le]=arguments[le+2];L.children=ne}if(j&&j.defaultProps)for($ in W=j.defaultProps,W)L[$]===void 0&&(L[$]=W[$]);return M(j,F,L)},yt.createRef=function(){return{current:null}},yt.forwardRef=function(j){return{$$typeof:c,render:j}},yt.isValidElement=B,yt.lazy=function(j){return{$$typeof:m,_payload:{_status:-1,_result:j},_init:G}},yt.memo=function(j,V){return{$$typeof:d,type:j,compare:V===void 0?null:V}},yt.startTransition=function(j){var V=A.T,z={};A.T=z;try{var $=j(),L=A.S;L!==null&&L(z,$),typeof $=="object"&&$!==null&&typeof $.then=="function"&&$.then(I,re)}catch(F){re(F)}finally{V!==null&&z.types!==null&&(V.types=z.types),A.T=V}},yt.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},yt.use=function(j){return A.H.use(j)},yt.useActionState=function(j,V,z){return A.H.useActionState(j,V,z)},yt.useCallback=function(j,V){return A.H.useCallback(j,V)},yt.useContext=function(j){return A.H.useContext(j)},yt.useDebugValue=function(){},yt.useDeferredValue=function(j,V){return A.H.useDeferredValue(j,V)},yt.useEffect=function(j,V){return A.H.useEffect(j,V)},yt.useEffectEvent=function(j){return A.H.useEffectEvent(j)},yt.useId=function(){return A.H.useId()},yt.useImperativeHandle=function(j,V,z){return A.H.useImperativeHandle(j,V,z)},yt.useInsertionEffect=function(j,V){return A.H.useInsertionEffect(j,V)},yt.useLayoutEffect=function(j,V){return A.H.useLayoutEffect(j,V)},yt.useMemo=function(j,V){return A.H.useMemo(j,V)},yt.useOptimistic=function(j,V){return A.H.useOptimistic(j,V)},yt.useReducer=function(j,V,z){return A.H.useReducer(j,V,z)},yt.useRef=function(j){return A.H.useRef(j)},yt.useState=function(j){return A.H.useState(j)},yt.useSyncExternalStore=function(j,V,z){return A.H.useSyncExternalStore(j,V,z)},yt.useTransition=function(){return A.H.useTransition()},yt.version="19.2.3",yt}var aU;function wN(){return aU||(aU=1,nx.exports=Aoe()),nx.exports}var y=wN();const ce=ry(y),kd=cJ({__proto__:null,default:ce},[y]);function D_(e,t){if(!e)throw new Error(t)}Be(D_,"assert");var iU=3e3,Ioe=5e3;function SN(e){const{url:t,enabled:n=!0,clientName:a,clientUri:r,callbackUrl:i=typeof window<"u"?du(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:s="mcp:auth",clientConfig:c={},customHeaders:u={},debug:d=!1,autoRetry:m=!1,autoReconnect:h=iU,transportType:g="auto",preventAutoAuth:v=!1,useRedirectFlow:x=!1,onPopupWindow:S,timeout:w=3e4,sseReadTimeout:E=3e5,wrapTransport:_,onNotification:k,samplingCallback:C,onElicitation:R}=e,[I,A]=y.useState("discovering"),[O,M]=y.useState([]),[P,B]=y.useState([]),[K,Q]=y.useState([]),[ee,ae]=y.useState([]),[H,Z]=y.useState(),[G,re]=y.useState(),[te,j]=y.useState(void 0),[V,z]=y.useState([]),[$,L]=y.useState(void 0),F=y.useRef(null),W=y.useRef(null),ne=y.useRef(!1),le=y.useRef(!0),ue=y.useRef(0),X=y.useRef(null),q=y.useRef(I),oe=y.useRef(h),me=y.useRef(null);y.useEffect(()=>{q.current=I,oe.current=h},[I,h]);const ie=y.useCallback((Ve,Le,...Ee)=>{const je=Ee.length>0?`${Le} ${Ee.map(Fe=>JSON.stringify(Fe)).join(" ")}`:Le;console[Ve](`[useMcp] ${je}`),le.current&&z(Fe=>[...Fe.slice(-100),{level:Ve,message:je,timestamp:Date.now()}])},[]),Ne=y.useCallback(async(Ve=!1)=>{if(Ve||ie("info","Disconnecting..."),ne.current=!1,X.current&&clearTimeout(X.current),X.current=null,F.current)try{const Le="inspector-server",Ee=F.current.getSession(Le);Ee&&Ee._healthCheckCleanup&&(Ee._healthCheckCleanup(),Ee._healthCheckCleanup=null),await F.current.closeSession(Le)}catch(Le){Ve||ie("warn","Error closing session:",Le)}F.current=null,le.current&&!Ve&&(A("discovering"),M([]),B([]),Q([]),ae([]),j(void 0),L(void 0))},[ie]),He=y.useCallback((Ve,Le)=>{if(ie("error",Ve,Le??""),le.current){A("failed"),j(Ve);const Ee=W.current?.getLastAttemptedAuthUrl();Ee&&(L(Ee),ie("info","Manual authentication URL may be available.",Ee))}ne.current=!1,t&&zi.getInstance().trackUseMcpConnection({url:t,transportType:g,success:!1,errorType:Le?.name||"UnknownError",hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{})},[ie,t,g,C,R]),ye=y.useCallback(async()=>{if(!n||!t){ie("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(ne.current){ie("debug","Connection attempt already in progress.");return}if(!le.current){ie("debug","Connect called after unmount, aborting.");return}ne.current=!0,ue.current+=1,j(void 0),L(void 0),me.current=null,A("discovering"),ie("info",`Connecting attempt #${ue.current} to ${t}...`),W.current||(W.current=new Db(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),ie("debug","BrowserOAuthClientProvider initialized in connect.")),F.current||(F.current=new Roe,ie("debug","BrowserMCPClient initialized in connect."));const Ve=Be(async(Ee,je=!1)=>{ie("info",`Attempting connection with transport: ${Ee}`);try{const Fe="inspector-server",We={url:t,transport:Ee==="sse"?"http":Ee,disableSseFallback:Ee==="http",preferSse:Ee==="sse"};if(u&&Object.keys(u).length>0&&(We.headers=u),W.current){const Ze=await W.current.tokens();Ze?.access_token&&(We.headers={...We.headers,Authorization:`Bearer ${Ze.access_token}`})}F.current.addServer(Fe,{...We,authProvider:W.current,clientOptions:c,samplingCallback:C,elicitationCallback:R,wrapTransport:_?Ze=>(console.log("[useMcp] Applying transport wrapper for server:",Fe,"url:",t),_(Ze,t)):void 0});const Je=await F.current.createSession(Fe,!1);Je.on("notification",Ze=>{k?.(Ze),Ze.method==="notifications/tools/list_changed"?(ie("info","Tools list changed, auto-refreshing..."),nt().catch(mt=>ie("warn","Auto-refresh tools failed:",mt))):Ze.method==="notifications/resources/list_changed"?(ie("info","Resources list changed, auto-refreshing..."),ct().catch(mt=>ie("warn","Auto-refresh resources failed:",mt))):Ze.method==="notifications/prompts/list_changed"&&(ie("info","Prompts list changed, auto-refreshing..."),bt().catch(mt=>ie("warn","Auto-refresh prompts failed:",mt)))}),await Je.initialize(),ie("info","✅ Successfully connected to MCP server"),ie("info","Server info:",Je.connector.serverInfo),ie("info","Server capabilities:",Je.connector.serverCapabilities),console.log("[useMcp] Server info:",Je.connector.serverInfo),console.log("[useMcp] Server capabilities:",Je.connector.serverCapabilities),A("ready"),me.current=Ee;const St=Be(()=>{let Ze=null,mt=Date.now();const At=1e4,er=3e4;return Ze=setInterval(Be(async()=>{if(!le.current||q.current!=="ready"){Ze&&(clearInterval(Ze),Ze=null);return}try{await Je.connector.listTools(),mt=Date.now()}catch{const $n=Date.now()-mt;$n>er&&(ie("warn",`Connection appears to be broken (no response for ${Math.round($n/1e3)}s), attempting to reconnect...`),Ze&&(clearInterval(Ze),Ze=null),oe.current&&le.current&&(A("discovering"),ie("info","Auto-reconnecting to MCP server..."),setTimeout(()=>{le.current&&q.current==="discovering"&&ye()},typeof oe.current=="number"?oe.current:iU)))}},"checkConnectionHealth"),At),()=>{Ze&&(clearInterval(Ze),Ze=null)}},"setupConnectionMonitoring");if(h){const Ze=St();Je._healthCheckCleanup=Ze}zi.getInstance().trackUseMcpConnection({url:t,transportType:Ee,success:!0,hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{}),M(Je.connector.tools||[]);const ht=await Je.connector.listAllResources();B(ht.resources||[]);const Mt=await Je.connector.listPrompts();ae(Mt.prompts||[]);const rn=Je.connector.serverInfo,Ke=Je.connector.serverCapabilities;return rn&&(console.log("[useMcp] Server info:",rn),Z(rn)),Ke&&(console.log("[useMcp] Server capabilities:",Ke),re(Ke)),"success"}catch(Fe){const We=Fe,Je=We?.message||String(Fe);if(We.code===401||Je.includes("401")||Je.includes("Unauthorized")){if(W.current){ie("info","Authentication required. OAuth provider available.");try{const{auth:St}=await Jn(async()=>{const{auth:Mt}=await Promise.resolve().then(()=>JP);return{auth:Mt}},void 0),ht=new URL(t).origin;St(W.current,{serverUrl:ht}).catch(()=>{}),setTimeout(()=>{if(le.current){const Mt=W.current?.getLastAttemptedAuthUrl();Mt?(L(Mt),ie("info","Manual authentication URL available:",Mt)):ie("warn","Could not generate authentication URL")}},100)}catch(St){ie("warn","Error generating auth URL:",St)}return le.current&&A("pending_auth"),ne.current=!1,"auth_redirect"}return u&&Object.keys(u).length>0?(He("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(He("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return He(Je,We instanceof Error?We:new Error(String(We))),"failed"}},"tryConnectWithTransport");let Le="failed";if(g==="sse")ie("debug","Using SSE-only transport mode"),Le=await Ve("sse");else if(g==="http")ie("debug","Using HTTP-only transport mode"),Le=await Ve("http");else{ie("debug","Using auto transport mode (HTTP with SSE fallback)");const Ee=await Ve("http");Ee==="fallback"&&le.current&&q.current!=="authenticating"?(ie("info","HTTP failed, attempting SSE fallback..."),Le=await Ve("sse")):Le=Ee}(Le==="success"||Le==="failed"||Le==="auth_redirect")&&(ne.current=!1),ie("debug",`Connection sequence finished with status: ${Le}`)},[ie,He,Ne,t,s,a,r,i,c.name,c.version,u,g,v,x,S,n,w,E]),Se=y.useCallback(async(Ve,Le,Ee)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot call tool "${Ve}".`);ie("info",`Calling tool: ${Ve}`,Le);const je=Date.now();try{const We=F.current.getSession("inspector-server");if(!We)throw new Error("No active session found");const Je=await We.connector.callTool(Ve,Le||{},Ee);return ie("info",`Tool "${Ve}" call successful:`,Je),zi.getInstance().trackUseMcpToolCall({toolName:Ve,success:!0,executionTimeMs:Date.now()-je}).catch(()=>{}),Je}catch(Fe){throw ie("error",`Tool "${Ve}" call failed:`,Fe),zi.getInstance().trackUseMcpToolCall({toolName:Ve,success:!1,errorType:Fe instanceof Error?Fe.name:"UnknownError",executionTimeMs:Date.now()-je}).catch(()=>{}),Fe}},[I]),Pe=y.useCallback(()=>{q.current==="failed"?(ie("info","Retry requested..."),ye()):ie("warn",`Retry called but state is not 'failed' (state: ${q.current}). Ignoring.`)},[ie,ye]),fe=y.useCallback(async()=>{ie("info","Manual authentication requested...");const Ve=q.current;if(Ve==="failed")ie("info","Attempting to reconnect and authenticate via retry..."),Pe();else if(Ve==="pending_auth"){ie("info","Proceeding with authentication from pending state...");try{D_(W.current,"Auth Provider not available for manual auth"),D_(t,"Server URL is required for authentication"),ie("info","Clearing all OAuth state and initiating fresh flow...");const Le=`${s}:${W.current.serverUrlHash}`;Object.keys(localStorage).forEach(We=>{We.startsWith(Le)&&(ie("debug",`Removing stale OAuth key: ${We}`),localStorage.removeItem(We)),We.startsWith(`${s}:state_`)&&(ie("debug",`Removing orphaned state: ${We}`),localStorage.removeItem(We))}),A("authenticating");const Ee=new Db(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:!1,useRedirectFlow:x,onPopupWindow:S});W.current=Ee,ie("info","Triggering fresh OAuth authorization...");const{auth:je}=await Jn(async()=>{const{auth:We}=await Promise.resolve().then(()=>JP);return{auth:We}},void 0),Fe=new URL(t).origin;je(Ee,{serverUrl:Fe}).catch(We=>{ie("info","OAuth flow initiated:",We instanceof Error?We.message:"Redirecting...")})}catch(Le){if(!le.current)return;A("pending_auth"),ie("error",`Manual authentication failed: ${Le instanceof Error?Le.message:String(Le)}`)}}else if(Ve==="authenticating"){ie("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const Le=W.current?.getLastAttemptedAuthUrl();Le&&!$&&(L(Le),ie("info","Manual authentication URL retrieved:",Le))}else ie("info",`Client not in a state requiring manual authentication trigger (state: ${Ve}). If needed, try disconnecting and reconnecting.`)},[ie,Pe,$,t,x,S,s,a,r,i]),Ae=y.useCallback(()=>{if(W.current){const Ve=W.current.clearStorage();ie("info",`Cleared ${Ve} item(s) from localStorage for ${t}.`),L(void 0),Ne()}else ie("warn","Auth provider not initialized, cannot clear storage.")},[t,ie,Ne]),Me=y.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list resources.`);ie("info","Listing resources");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Ee=await Le.connector.listAllResources();B(Ee.resources||[]),ie("info","Resources listed successfully")}catch(Ve){throw ie("error","List resources failed:",Ve),Ve}},[I]),_e=y.useCallback(async Ve=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot read resource.`);ie("info",`Reading resource: ${Ve}`);try{const Ee=F.current.getSession("inspector-server");if(!Ee)throw new Error("No active session found");const je=await Ee.connector.readResource(Ve);return ie("info","Resource read successful:",je),zi.getInstance().trackUseMcpResourceRead({resourceUri:Ve,success:!0}).catch(()=>{}),je}catch(Le){throw ie("error","Resource read failed:",Le),zi.getInstance().trackUseMcpResourceRead({resourceUri:Ve,success:!1,errorType:Le instanceof Error?Le.name:"UnknownError"}).catch(()=>{}),Le}},[I]),rt=y.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list prompts.`);ie("info","Listing prompts");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Ee=await Le.connector.listPrompts();ae(Ee.prompts||[]),ie("info","Prompts listed successfully")}catch(Ve){throw ie("error","List prompts failed:",Ve),Ve}},[I]),nt=y.useCallback(async()=>{if(q.current!=="ready"||!F.current){ie("debug","Cannot refresh tools - client not ready");return}ie("debug","Refreshing tools list");try{const Le=F.current.getSession("inspector-server");if(!Le){ie("warn","No active session found for tools refresh");return}const Ee=await Le.connector.listTools();M(Ee||[]),ie("info","Tools list refreshed successfully")}catch(Ve){ie("warn","Failed to refresh tools:",Ve)}},[ie]),ct=y.useCallback(async()=>{if(q.current!=="ready"||!F.current){ie("debug","Cannot refresh resources - client not ready");return}ie("debug","Refreshing resources list");try{const Le=F.current.getSession("inspector-server");if(!Le){ie("warn","No active session found for resources refresh");return}const Ee=await Le.connector.listAllResources();B(Ee.resources||[]),ie("info","Resources list refreshed successfully")}catch(Ve){ie("warn","Failed to refresh resources:",Ve)}},[ie]),bt=y.useCallback(async()=>{if(q.current!=="ready"||!F.current){ie("debug","Cannot refresh prompts - client not ready");return}ie("debug","Refreshing prompts list");try{const Le=F.current.getSession("inspector-server");if(!Le){ie("warn","No active session found for prompts refresh");return}const Ee=await Le.connector.listPrompts();ae(Ee.prompts||[]),ie("info","Prompts list refreshed successfully")}catch(Ve){ie("warn","Failed to refresh prompts:",Ve)}},[ie]),ut=y.useCallback(async()=>{ie("info","Refreshing all lists (tools, resources, prompts)"),await Promise.all([nt(),ct(),bt()])},[nt,ct,bt,ie]),nn=y.useCallback(async(Ve,Le)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot get prompt.`);ie("info",`Getting prompt: ${Ve}`,Le);try{const je=F.current.getSession("inspector-server");if(!je)throw new Error("No active session found");const Fe=await je.connector.getPrompt(Ve,Le||{});return ie("info",`Prompt "${Ve}" retrieved successfully:`,Fe),Fe}catch(Ee){throw ie("error",`Prompt "${Ve}" retrieval failed:`,Ee),Ee}},[I]),Qn=y.useRef(ye),ot=y.useRef(He);return y.useEffect(()=>{Qn.current=ye,ot.current=He}),y.useEffect(()=>{const Ve=Be(Le=>{Le.origin===window.location.origin&&Le.data?.type==="mcp_auth_callback"&&(ie("info","Received auth callback message.",Le.data),X.current&&clearTimeout(X.current),X.current=null,Le.data.success?(ie("info","Authentication successful via popup. Reconnecting client..."),ne.current&&ie("debug","Connection attempt already in progress, resetting flag to allow reconnection."),ne.current=!1,setTimeout(()=>{le.current&&(ie("debug","Initiating reconnection after successful auth callback."),Qn.current())},100)):ot.current(`Authentication failed in callback: ${Le.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",Ve),ie("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",Ve),ie("debug","Auth callback message listener removed."),X.current&&clearTimeout(X.current)}},[ie]),y.useEffect(()=>(le.current=!0,!n||!t?(ie("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),A("discovering"),()=>{le.current=!1}):(ie("debug","useMcp mounted, initiating connection."),ue.current=0,(!W.current||W.current.serverUrl!==t)&&(W.current=new Db(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),ie("debug","BrowserOAuthClientProvider initialized/updated on mount/option change.")),ye(),()=>{le.current=!1,ie("debug","useMcp unmounting, disconnecting."),Ne(!0)})),[t,n,s,i,a,r,c.name,c.version,x]),y.useEffect(()=>{let Ve=null;if(I==="failed"&&m&&ue.current>0){const Le=typeof m=="number"?m:Ioe;ie("info",`Connection failed, auto-retrying in ${Le}ms...`),Ve=setTimeout(()=>{le.current&&q.current==="failed"&&Pe()},Le)}return()=>{Ve&&clearTimeout(Ve)}},[I,m,Pe,ie]),{state:I,tools:O,resources:P,resourceTemplates:K,prompts:ee,serverInfo:H,capabilities:G,error:te,log:V,authUrl:$,client:F.current,callTool:Se,readResource:_e,listResources:Me,listPrompts:rt,getPrompt:nn,refreshTools:nt,refreshResources:ct,refreshPrompts:bt,refreshAll:ut,retry:Pe,disconnect:Ne,authenticate:fe,clearStorage:Ae}}Be(SN,"useMcp");var Xu,Ooe=(Xu=class extends ce.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Widget Error:",t,n)}render(){return this.state.hasError?ce.createElement("div",{className:"p-4 border border-red-500 bg-red-50 text-red-900 rounded-md dark:bg-red-900/20 dark:text-red-100"},ce.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),ce.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},Be(Xu,"ErrorBoundary"),Xu),pp="openai:set_globals";function di(e){return y.useSyncExternalStore(t=>{const n=Be(a=>{a.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener(pp,n),()=>{typeof window<"u"&&window.removeEventListener(pp,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}Be(di,"useOpenAiGlobal");function Td(e){const[t,n]=y.useState(()=>typeof window<"u"&&!!window.openai);y.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const P=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},100),B=Be(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},"handleSetGlobals");typeof window<"u"&&window.addEventListener(pp,B);const K=setTimeout(()=>{clearInterval(P),typeof window<"u"&&window.removeEventListener(pp,B)},5e3);return()=>{clearInterval(P),clearTimeout(K),typeof window<"u"&&window.removeEventListener(pp,B)}},[]);const a=y.useMemo(()=>t?"openai":"mcp-ui",[t]),r=typeof window<"u"?window.location.search:"",i=y.useMemo(()=>{const P=new URLSearchParams(r);return P.has("mcpUseParams")?JSON.parse(P.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[r]),s=a==="openai"?di("toolInput"):i.toolInput,c=a==="openai"?di("toolOutput"):i.toolOutput,u=di("toolResponseMetadata"),d=y.useMemo(()=>{if(u&&typeof u=="object"){const P=u["mcp-use/props"];if(P)return P}return e||{}},[u,e]),m=di("widgetState"),h=di("theme"),g=di("displayMode"),v=di("safeArea"),x=di("maxHeight"),S=di("userAgent"),w=di("locale"),E=y.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,k]=y.useState(null);y.useEffect(()=>{m!==void 0&&k(m)},[m]);const C=y.useCallback(async(P,B)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(P,B)},[]),R=y.useCallback(async P=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:P})},[]),I=y.useCallback(P=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:P})},[]),A=y.useCallback(async P=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:P})},[]),O=y.useCallback(async P=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const K=typeof P=="function"?P(m!==void 0?m:_):P;return k(K),window.openai.setWidgetState(K)},[m,_]),M=y.useMemo(()=>a==="openai"&&u===null,[a,u]);return{props:d,toolInput:s||{},output:c??null,metadata:u??null,state:_,setState:O,theme:h||"light",displayMode:g||"inline",safeArea:v||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:x||600,userAgent:S||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:w||"en",mcp_url:E,callTool:C,sendFollowUpMessage:R,openExternal:I,requestDisplayMode:A,isAvailable:t,isPending:M}}Be(Td,"useWidget");function Doe(e){const{props:t}=Td(e);return t}Be(Doe,"useWidgetProps");function joe(){const{theme:e}=Td();return e}Be(joe,"useWidgetTheme");function $oe(e){const{state:t,setState:n}=Td();return y.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}Be($oe,"useWidgetState");var oU=Be(({children:e})=>{const{theme:t,isAvailable:n}=Td();console.log("theme",t);const[a,r]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");y.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(prefers-color-scheme: dark)"),c=Be(u=>{r(u.matches?"dark":"light")},"handleChange");return s.addEventListener("change",c),()=>s.removeEventListener("change",c)},[]);const i=n?t:a;return y.useLayoutEffect(()=>{typeof document>"u"||(i==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[i]),ce.createElement(ce.Fragment,null,e)},"ThemeProvider");function r9({children:e,className:t="",position:n="top-right",attachTo:a,showLabels:r=!0,debugger:i=!1,viewControls:s=!1}){const{props:c,output:u,metadata:d,state:m,theme:h,displayMode:g,safeArea:v,maxHeight:x,userAgent:S,locale:w,isAvailable:E,callTool:_,sendFollowUpMessage:k,openExternal:C,requestDisplayMode:R,setState:I}=Td(),[A,O]=y.useState(!1),[M,P]=y.useState(!1),B=y.useRef(null),K=y.useRef(null),[Q,ee]=y.useState([]),[ae,H]=y.useState(""),[Z,G]=y.useState("get-my-city"),[re,te]=y.useState("{}"),[j,V]=y.useState("Test follow-up message"),[z,$]=y.useState("https://docs.mcp-use.com"),L=g==="fullscreen"&&E,F=g==="pip"&&E,W=typeof window<"u"&&window.location.pathname.includes("/inspector/api/");y.useEffect(()=>{const _e=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const rt=Object.keys(window.openai);ee(rt)}catch{ee([])}else ee([])},100);return()=>{clearTimeout(_e)}},[]);const ne=h==="dark",le=Be(()=>{const _e=["absolute","z-[1000]","flex","gap-2","transition-opacity","duration-200","ease-in-out",A?"opacity-100":"opacity-0",A?"pointer-events-auto":"pointer-events-none"];switch(n){case"top-left":return[..._e,"top-4","left-4"];case"top-center":return[..._e,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[..._e,"top-4","right-4"];case"center-left":return[..._e,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[..._e,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[..._e,"bottom-4","left-4"];case"bottom-center":return[..._e,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[..._e,"bottom-4","right-4"];default:return[..._e,"top-4","right-4"]}},"getPositionClasses"),ue=Be(()=>{const rt=v?.insets?.top?Math.max(16,v.insets.top+8):16,nt=v?.insets?.right?Math.max(16,v.insets.right+8):16,ct=v?.insets?.bottom?Math.max(16,v.insets.bottom+8):16,bt=v?.insets?.left?Math.max(16,v.insets.left+8):16,ut={};switch(n){case"top-left":ut.top=`${rt}px`,ut.left=`${bt}px`;break;case"top-center":ut.top=`${rt}px`;break;case"top-right":ut.top=`${rt}px`,ut.right=`${nt}px`;break;case"center-left":ut.left=`${bt}px`;break;case"center-right":ut.right=`${nt}px`;break;case"bottom-left":ut.bottom=`${ct}px`,ut.left=`${bt}px`;break;case"bottom-center":ut.bottom=`${ct}px`;break;case"bottom-right":ut.bottom=`${ct}px`,ut.right=`${nt}px`;break;default:ut.top=`${rt}px`,ut.right=`${nt}px`;break}return ut},"getPositionOffsetStyles");y.useEffect(()=>{if(!a)return;const _e=Be(()=>O(!0),"handleMouseEnter"),rt=Be(()=>O(!1),"handleMouseLeave");return a.addEventListener("mouseenter",_e),a.addEventListener("mouseleave",rt),()=>{a.removeEventListener("mouseenter",_e),a.removeEventListener("mouseleave",rt)}},[a]),y.useEffect(()=>{if(!M)return;const _e=Be(rt=>{K.current&&!K.current.contains(rt.target)&&P(!1)},"handleClickOutside");return document.addEventListener("mousedown",_e),()=>{document.removeEventListener("mousedown",_e)}},[M]),y.useEffect(()=>(M?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[M]);const X=Be(()=>{P(!M)},"handleToggleOverlay"),q=Be(async()=>{try{H("Calling tool...");const _e=re.trim()?JSON.parse(re):{},rt=await _(Z,_e);H(`Success: ${JSON.stringify(rt,null,2)}`)}catch(_e){H(`Error: ${_e.message}`)}},"handleCallTool"),oe=Be(async()=>{try{H("Sending follow-up message..."),await k(j),H("Follow-up message sent successfully")}catch(_e){H(`Error: ${_e.message}`)}},"handleSendFollowUpMessage"),me=Be(()=>{try{C(z),H(`Opened external link: ${z}`)}catch(_e){H(`Error: ${_e.message}`)}},"handleOpenExternal"),ie=Be(async _e=>{try{H(`Requesting display mode: ${_e}...`);const rt=await R(_e);H(`Display mode granted: ${rt.mode}`)}catch(rt){H(`Error: ${rt.message}`)}},"handleRequestDisplayMode"),Ne=Be(async()=>{try{const _e=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};H("Setting state..."),await I(_e),H(`State updated: ${JSON.stringify(_e,null,2)}`)}catch(_e){H(`Error: ${_e.message}`)}},"handleSetState"),He=Be(async()=>{try{await R("fullscreen")}catch(_e){console.error("Failed to go fullscreen:",_e)}},"handleFullscreen"),ye=Be(async()=>{try{await R("pip")}catch(_e){console.error("Failed to go pip:",_e)}},"handlePip"),Se=Be(()=>{const _e=["absolute","px-2","py-1","bg-black/90","text-white","rounded","text-xs","whitespace-nowrap","pointer-events-none","transition-opacity","duration-200","ease-in-out"];switch(n){case"top-right":return[..._e,"top-full","right-0","mt-2"];case"top-left":return[..._e,"top-full","left-0","mt-2"];case"top-center":return[..._e,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[..._e,"bottom-full","right-0","mb-2"];case"bottom-left":return[..._e,"bottom-full","left-0","mb-2"];case"bottom-center":return[..._e,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[..._e,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[..._e,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[..._e,"top-full","right-0","mt-2"]}},"getTooltipClasses"),Pe=Be(({onClick:_e,label:rt,children:nt})=>{const[ct,bt]=y.useState(!1),ut=Se();return ce.createElement("button",{className:`p-2 ${ne?"bg-white/10 hover:bg-white/20":"bg-black/70 hover:bg-black/90"} text-white border-none rounded-lg cursor-pointer flex items-center justify-center w-8 h-8 transition-colors duration-200 backdrop-blur-md ${ne?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>bt(!0),onMouseLeave:()=>bt(!1),onClick:_e,"aria-label":rt},ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"block"},nt),r&&ce.createElement("span",{className:`${ut.join(" ")} ${ct?"opacity-100":"opacity-0"}`},rt))},"IconButton"),fe=Be(_e=>{if(_e===null)return"null";if(_e===void 0)return"undefined";if(typeof _e=="object")try{return JSON.stringify(_e,null,2)}catch{return String(_e)}return String(_e)},"formatValue"),Ae=Be(_e=>_e?`${_e.device?.type||"unknown"}`:"N/A","formatUserAgent"),Me=Be(_e=>{if(!_e?.insets)return"N/A";const{top:rt,bottom:nt,left:ct,right:bt}=_e.insets;return`T:${rt} B:${nt} L:${ct} R:${bt}`},"formatSafeArea");return ce.createElement(ce.Fragment,null,ce.createElement("div",{ref:B,className:`${t} relative h-fit`,onMouseEnter:()=>!a&&O(!0),onMouseLeave:()=>!a&&O(!1)},ce.createElement("div",{className:le().join(" "),style:ue()},!W&&ce.createElement(ce.Fragment,null,!L&&!F&&ce.createElement(ce.Fragment,null,(s===!0||s==="fullscreen")&&ce.createElement(Pe,{onClick:He,label:"Fullscreen"},ce.createElement("path",{d:"M15 3h6v6"}),ce.createElement("path",{d:"m21 3-7 7"}),ce.createElement("path",{d:"m3 21 7-7"}),ce.createElement("path",{d:"M9 21H3v-6"})),(s===!0||s==="pip")&&ce.createElement(Pe,{onClick:ye,label:"Picture in Picture"},ce.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),ce.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),i&&ce.createElement(Pe,{onClick:X,label:"Debug Info"},ce.createElement("path",{d:"M12 20v-9"}),ce.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),ce.createElement("path",{d:"M14.12 3.88 16 2"}),ce.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),ce.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),ce.createElement("path",{d:"M22 13h-4"}),ce.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),ce.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),ce.createElement("path",{d:"M6 13H2"}),ce.createElement("path",{d:"m8 2 1.88 1.88"}),ce.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),M&&i&&ce.createElement("div",{ref:K,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:_e=>{_e.target===K.current&&P(!1)}},ce.createElement("button",{onClick:()=>P(!1),className:"absolute top-4 right-4 bg-white/10 text-white border-none rounded w-8 h-8 cursor-pointer flex items-center justify-center text-lg leading-none","aria-label":"Close"},"×"),ce.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},ce.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),ce.createElement("table",{className:"w-full border-collapse border-spacing-0"},ce.createElement("tbody",null,ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(c))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(u))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(d))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(m))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),ce.createElement("td",{className:"p-2"},h)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),ce.createElement("td",{className:"p-2"},g)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),ce.createElement("td",{className:"p-2"},w)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),ce.createElement("td",{className:"p-2"},x,"px")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),ce.createElement("td",{className:"p-2"},Ae(S))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),ce.createElement("td",{className:"p-2"},Me(v))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),ce.createElement("td",{className:"p-2"},E?"Yes":"No")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),ce.createElement("td",{className:"p-2"},Q.length>0?Q.join(", "):"N/A")))),ce.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),ce.createElement("div",{className:"flex flex-col gap-3"},ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:Z,onChange:_e=>G(_e.target.value),placeholder:"Tool name",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs w-[150px]"}),ce.createElement("input",{type:"text",value:re,onChange:_e=>te(_e.target.value),placeholder:'{"key": "value"}',className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ce.createElement("button",{onClick:q,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:j,onChange:_e=>V(_e.target.value),placeholder:"Follow-up message",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ce.createElement("button",{onClick:oe,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Send Follow-Up")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:z,onChange:_e=>$(_e.target.value),placeholder:"External URL",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ce.createElement("button",{onClick:me,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),ce.createElement("button",{onClick:()=>ie("inline"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Inline"),ce.createElement("button",{onClick:()=>ie("pip"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"PiP"),ce.createElement("button",{onClick:()=>ie("fullscreen"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Fullscreen")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("button",{onClick:Ne,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Set State (Add Timestamp)")),ae&&ce.createElement("div",{className:"mt-2 p-2 bg-[#1a1a1a] border border-gray-700 rounded whitespace-pre-wrap break-all text-[11px] max-h-[200px] overflow-auto"},ce.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),ae,ce.createElement("button",{onClick:()=>H(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}Be(r9,"WidgetControls");function a9(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}Be(a9,"getBasename");var Loe=150,Moe=5;function Poe({children:e,debugger:t=!1,viewControls:n=!1,autoSize:a=!1}){const r=a9(),i=y.useRef(null),s=y.useRef(0),c=y.useRef(null),u=y.useRef(!1),[d,m]=y.useState(null),[h,g]=y.useState(null),[v,x]=y.useState(!0);y.useEffect(()=>{let _=!0;return(async()=>{try{const k=await Jn(()=>import("./index-CN3Oy0EC.js"),[]);_&&(m(()=>k.BrowserRouter),x(!1))}catch{_&&(g(new Error(`❌ react-router not installed!
|
|
35
|
+
`&&a++}}return[t,n]}class goe extends TransformStream{constructor({onError:t,onRetry:n,onComment:a}={}){let r;super({start(i){r=e9({onEvent:s=>{i.enqueue(s)},onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:n,onComment:a})},transform(i){r.feed(i)}})}}const boe={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kl extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class voe{constructor(t,n){var a;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=zV(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=(a=n?.reconnectionOptions)!==null&&a!==void 0?a:boe}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=mv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}async _startOrAuthSse(t){var n,a,r,i;const{resumptionToken:s}=t;try{const c=await this._commonHeaders();c.set("Accept","text/event-stream"),s&&c.set("last-event-id",s);const u=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:c,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!u.ok){if(await((r=u.body)===null||r===void 0?void 0:r.cancel()),u.status===401&&this._authProvider)return await this._authThenStart();if(u.status===405)return;throw new kl(u.status,`Failed to open SSE stream: ${u.statusText}`)}this._handleSseStream(u.body,t,!0)}catch(c){throw(i=this.onerror)===null||i===void 0||i.call(this,c),c}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(a,t),r)}_scheduleReconnection(t,n=0){var a;const r=this._reconnectionOptions.maxRetries;if(n>=r){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const i=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,n+1)})},i)}_handleSseStream(t,n,a){if(!t)return;const{onresumptiontoken:r,replayMessageId:i}=n;let s,c=!1,u=!1;(async()=>{var m,h,g,v;try{const x=t.pipeThrough(new TextDecoderStream).pipeThrough(new goe({onRetry:E=>{this._serverRetryMs=E}})).getReader();for(;;){const{value:E,done:_}=await x.read();if(_)break;if(E.id&&(s=E.id,c=!0,r?.(E.id)),!!E.data&&(!E.event||E.event==="message"))try{const k=Rb.parse(JSON.parse(E.data));Qf(k)&&(u=!0,i!==void 0&&(k.id=i)),(m=this.onmessage)===null||m===void 0||m.call(this,k)}catch(k){(h=this.onerror)===null||h===void 0||h.call(this,k)}}(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(x){if((g=this.onerror)===null||g===void 0||g.call(this,new Error(`SSE stream disconnected: ${x}`)),(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(E){(v=this.onerror)===null||v===void 0||v.call(this,new Error(`Failed to reconnect: ${E instanceof Error?E.message:String(E)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Ro(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var a,r,i,s,c,u,d;try{const{resumptionToken:m,onresumptiontoken:h}=n||{};if(m){this._startOrAuthSse({resumptionToken:m,replayMessageId:f_(t)?t.id:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const g=await this._commonHeaders();g.set("content-type","application/json"),g.set("accept","application/json, text/event-stream");const v={...this._requestInit,method:"POST",headers:g,body:JSON.stringify(t),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},x=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,v),S=x.headers.get("mcp-session-id");if(S&&(this._sessionId=S),!x.ok){const k=await x.text().catch(()=>null);if(x.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kl(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:C,scope:R}=Lp(x);if(this._resourceMetadataUrl=C,this._scope=R,await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this._hasCompletedAuthFlow=!0,this.send(t)}if(x.status===403&&this._authProvider){const{resourceMetadataUrl:C,scope:R,error:I}=Lp(x);if(I==="insufficient_scope"){const A=x.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===A)throw new kl(403,"Server returned 403 after trying upscoping");if(R&&(this._scope=R),C&&(this._resourceMetadataUrl=C),this._lastUpscopingHeader=A??void 0,await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qa;return this.send(t)}}throw new kl(x.status,`Error POSTing to endpoint: ${k}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,x.status===202){await((i=x.body)===null||i===void 0?void 0:i.cancel()),cre(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const E=(Array.isArray(t)?t:[t]).filter(k=>"method"in k&&"id"in k&&k.id!==void 0).length>0,_=x.headers.get("content-type");if(E)if(_?.includes("text/event-stream"))this._handleSseStream(x.body,{onresumptiontoken:h},!1);else if(_?.includes("application/json")){const k=await x.json(),C=Array.isArray(k)?k.map(R=>Rb.parse(R)):[Rb.parse(k)];for(const R of C)(s=this.onmessage)===null||s===void 0||s.call(this,R)}else throw await((c=x.body)===null||c===void 0?void 0:c.cancel()),new kl(-1,`Unexpected content type: ${_}`);else await((u=x.body)===null||u===void 0?void 0:u.cancel())}catch(m){throw(d=this.onerror)===null||d===void 0||d.call(this,m),m}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,a,r;if(this._sessionId)try{const i=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},c=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(await((a=c.body)===null||a===void 0?void 0:a.cancel()),!c.ok&&c.status!==405)throw new kl(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(i){throw(r=this.onerror)===null||r===void 0||r.call(this,i),i}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class eU extends Event{constructor(t,n){var a,r;super(t),this.code=(a=n?.code)!=null?a:void 0,this.message=(r=n?.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,a){return a(tU(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(tU(this),n)}}function yoe(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function k_(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(k_).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${k_(e.cause)}`:e.message:`${e}`}function tU(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var t9=e=>{throw TypeError(e)},vN=(e,t,n)=>t.has(e)||t9("Cannot "+n),Ft=(e,t,n)=>(vN(e,t,"read from private field"),n?n.call(e):t.get(e)),dr=(e,t,n)=>t.has(e)?t9("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Mn=(e,t,n,a)=>(vN(e,t,"write to private field"),t.set(e,n),n),_o=(e,t,n)=>(vN(e,t,"access private method"),n),ba,Nl,Qc,Ib,yv,dp,uu,fp,Cs,eu,Su,tu,ep,fi,T_,N_,C_,nU,R_,A_,tp,I_,O_;class Ob extends EventTarget{constructor(t,n){var a,r;super(),dr(this,fi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,dr(this,ba),dr(this,Nl),dr(this,Qc),dr(this,Ib),dr(this,yv),dr(this,dp),dr(this,uu),dr(this,fp,null),dr(this,Cs),dr(this,eu),dr(this,Su,null),dr(this,tu,null),dr(this,ep,null),dr(this,N_,async i=>{var s;Ft(this,eu).reset();const{body:c,redirected:u,status:d,headers:m}=i;if(d===204){_o(this,fi,tp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Mn(this,Qc,new URL(i.url)):Mn(this,Qc,void 0),d!==200){_o(this,fi,tp).call(this,`Non-200 status code (${d})`,d);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){_o(this,fi,tp).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.OPEN);const h=new Event("open");if((s=Ft(this,ep))==null||s.call(this,h),this.dispatchEvent(h),typeof c!="object"||!c||!("getReader"in c)){_o(this,fi,tp).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}const g=new TextDecoder,v=c.getReader();let x=!0;do{const{done:S,value:w}=await v.read();w&&Ft(this,eu).feed(g.decode(w,{stream:!S})),S&&(x=!1,Ft(this,eu).reset(),_o(this,fi,I_).call(this))}while(x)}),dr(this,C_,i=>{Mn(this,Cs,void 0),!(i.name==="AbortError"||i.type==="aborted")&&_o(this,fi,I_).call(this,k_(i))}),dr(this,R_,i=>{typeof i.id=="string"&&Mn(this,fp,i.id);const s=new MessageEvent(i.event||"message",{data:i.data,origin:Ft(this,Qc)?Ft(this,Qc).origin:Ft(this,Nl).origin,lastEventId:i.id||""});Ft(this,tu)&&(!i.event||i.event==="message")&&Ft(this,tu).call(this,s),this.dispatchEvent(s)}),dr(this,A_,i=>{Mn(this,dp,i)}),dr(this,O_,()=>{Mn(this,uu,void 0),Ft(this,ba)===this.CONNECTING&&_o(this,fi,T_).call(this)});try{if(t instanceof URL)Mn(this,Nl,t);else if(typeof t=="string")Mn(this,Nl,new URL(t,woe()));else throw new Error("Invalid URL")}catch{throw yoe("An invalid or illegal string was specified")}Mn(this,eu,e9({onEvent:Ft(this,R_),onRetry:Ft(this,A_)})),Mn(this,ba,this.CONNECTING),Mn(this,dp,3e3),Mn(this,yv,(a=n?.fetch)!=null?a:globalThis.fetch),Mn(this,Ib,(r=n?.withCredentials)!=null?r:!1),_o(this,fi,T_).call(this)}get readyState(){return Ft(this,ba)}get url(){return Ft(this,Nl).href}get withCredentials(){return Ft(this,Ib)}get onerror(){return Ft(this,Su)}set onerror(t){Mn(this,Su,t)}get onmessage(){return Ft(this,tu)}set onmessage(t){Mn(this,tu,t)}get onopen(){return Ft(this,ep)}set onopen(t){Mn(this,ep,t)}addEventListener(t,n,a){const r=n;super.addEventListener(t,r,a)}removeEventListener(t,n,a){const r=n;super.removeEventListener(t,r,a)}close(){Ft(this,uu)&&clearTimeout(Ft(this,uu)),Ft(this,ba)!==this.CLOSED&&(Ft(this,Cs)&&Ft(this,Cs).abort(),Mn(this,ba,this.CLOSED),Mn(this,Cs,void 0))}}ba=new WeakMap,Nl=new WeakMap,Qc=new WeakMap,Ib=new WeakMap,yv=new WeakMap,dp=new WeakMap,uu=new WeakMap,fp=new WeakMap,Cs=new WeakMap,eu=new WeakMap,Su=new WeakMap,tu=new WeakMap,ep=new WeakMap,fi=new WeakSet,T_=function(){Mn(this,ba,this.CONNECTING),Mn(this,Cs,new AbortController),Ft(this,yv)(Ft(this,Nl),_o(this,fi,nU).call(this)).then(Ft(this,N_)).catch(Ft(this,C_))},N_=new WeakMap,C_=new WeakMap,nU=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ft(this,fp)?{"Last-Event-ID":Ft(this,fp)}:void 0},cache:"no-store",signal:(e=Ft(this,Cs))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},R_=new WeakMap,A_=new WeakMap,tp=function(e,t){var n;Ft(this,ba)!==this.CLOSED&&Mn(this,ba,this.CLOSED);const a=new eU("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a)},I_=function(e,t){var n;if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.CONNECTING);const a=new eU("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a),Mn(this,uu,setTimeout(Ft(this,O_),Ft(this,dp)))},O_=new WeakMap,Ob.CONNECTING=0,Ob.OPEN=1,Ob.CLOSED=2;function woe(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class Soe extends Error{constructor(t,n,a){super(`SSE error: ${n}`),this.code=t,this.event=a}}class xoe{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n?.eventSourceInit,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=zV(n?.fetch,n?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=mv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}_startOrAuth(){var t,n,a;const r=(a=(n=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&n!==void 0?n:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((i,s)=>{this._eventSource=new Ob(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{const d=await this._commonHeaders();d.set("Accept","text/event-stream");const m=await r(c,{...u,headers:d});if(m.status===401&&m.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:g}=Lp(m);this._resourceMetadataUrl=h,this._scope=g}return m}}),this._abortController=new AbortController,this._eventSource.onerror=c=>{var u;if(c.code===401&&this._authProvider){this._authThenStart().then(i,s);return}const d=new Soe(c.code,c.message,c);s(d),(u=this.onerror)===null||u===void 0||u.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;const d=c;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(m){s(m),(u=this.onerror)===null||u===void 0||u.call(this,m),this.close();return}i()}),this._eventSource.onmessage=c=>{var u,d;const m=c;let h;try{h=Rb.parse(JSON.parse(m.data))}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g);return}(d=this.onmessage)===null||d===void 0||d.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Ro(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n,a;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(t){var n,a,r,i;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const c={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},u=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,c);if(!u.ok){const d=await u.text().catch(()=>null);if(u.status===401&&this._authProvider){const{resourceMetadataUrl:m,scope:h}=Lp(u);if(this._resourceMetadataUrl=m,this._scope=h,await Ro(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${d}`)}await((r=u.body)===null||r===void 0?void 0:r.cancel())}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}}var Vu,_oe=(Vu=class{connector;autoConnect;constructor(t,n=!0){this.connector=t,this.autoConnect=n}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}on(t,n){t==="notification"&&this.connector.onNotification(n)}async setRoots(t){return this.connector.setRoots(t)}getRoots(){return this.connector.getRoots()}get tools(){return this.connector.tools}async listTools(t){return this.connector.listTools(t)}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n={},a){return this.connector.callTool(t,n,a)}async listResources(t,n){return this.connector.listResources(t,n)}async listAllResources(t){return this.connector.listAllResources(t)}async listResourceTemplates(t){return this.connector.listResourceTemplates(t)}async readResource(t,n){return this.connector.readResource(t,n)}async subscribeToResource(t,n){return this.connector.subscribeToResource(t,n)}async unsubscribeFromResource(t,n){return this.connector.unsubscribeFromResource(t,n)}async listPrompts(){return this.connector.listPrompts()}async getPrompt(t,n){return this.connector.getPrompt(t,n)}async request(t,n=null,a){return this.connector.request(t,n,a)}},Be(Vu,"MCPSession"),Vu),Gu,Eoe=(Gu=class{config={};sessions={};activeSessions=[];constructor(t){t&&(this.config=t)}static fromDict(t){throw new Error("fromDict must be implemented by concrete class")}addServer(t,n){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[t]=n,zi.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),zi.getInstance().trackClientRemoveServer(t))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(t){return this.config.mcpServers?.[t]}getConfig(){return this.config??{}}async createSession(t,n=!0){const a=this.config.mcpServers??{};if(Object.keys(a).length===0&&Ce.warn("No MCP servers defined in config"),!a[t])throw new Error(`Server '${t}' not found in config`);const r=this.createConnectorFromConfig(a[t]),i=new _oe(r);return n&&await i.initialize(),this.sessions[t]=i,this.activeSessions.includes(t)||this.activeSessions.push(t),i}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&Ce.warn("No MCP servers defined in config");for(const a of Object.keys(n))await this.createSession(a,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}requireSession(t){const n=this.sessions[t];if(!n)throw new Error(`Session '${t}' not found. Available sessions: ${this.activeSessions.join(", ")||"none"}`);return n}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){Ce.warn(`No session exists for server ${t}, nothing to close`);return}try{Ce.debug(`Closing session for server ${t}`),await n.disconnect()}catch(a){Ce.error(`Error closing session for server '${t}': ${a}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(a=>a!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const a of t)try{Ce.debug(`Closing session for server ${a}`),await this.closeSession(a)}catch(r){const i=`Failed to close session for server '${a}': ${r}`;Ce.error(i),n.push(i)}n.length?Ce.error(`Encountered ${n.length} errors while closing sessions`):Ce.debug("All sessions closed successfully")}},Be(Gu,"BaseMCPClient"),Gu),Wu,koe=(Wu=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;opts;notificationHandlers=[];rootsCache=[];constructor(t={}){this.opts=t,t.roots&&(this.rootsCache=[...t.roots])}trackConnectorInit(t){const n=this.constructor.name;yF.getInstance().trackConnectorInit({connectorType:n,...t}).catch(a=>Ce.debug(`Failed to track connector init: ${a}`))}onNotification(t){this.notificationHandlers.push(t),this.client&&this.setupNotificationHandler()}setupNotificationHandler(){this.client&&(this.client.fallbackNotificationHandler=async t=>{switch(t.method){case"notifications/tools/list_changed":await this.refreshToolsCache();break;case"notifications/resources/list_changed":await this.onResourcesListChanged();break;case"notifications/prompts/list_changed":await this.onPromptsListChanged();break}for(const n of this.notificationHandlers)try{await n(t)}catch(a){Ce.error("Error in notification handler:",a)}})}async refreshToolsCache(){if(this.client)try{Ce.debug("[Auto] Refreshing tools cache due to list_changed notification");const t=await this.client.listTools();this.toolsCache=t.tools??[],Ce.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(t){Ce.warn("[Auto] Failed to refresh tools cache:",t)}}async onResourcesListChanged(){Ce.debug("[Auto] Resources list changed - clients should re-fetch if needed")}async onPromptsListChanged(){Ce.debug("[Auto] Prompts list changed - clients should re-fetch if needed")}async setRoots(t){this.rootsCache=[...t],this.client&&(Ce.debug(`Sending roots/list_changed notification with ${t.length} root(s)`),await this.client.sendRootsListChanged())}getRoots(){return[...this.rootsCache]}setupRootsHandler(){this.client&&this.client.setRequestHandler(AV,async(t,n)=>(Ce.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){Ce.debug("setupSamplingHandler: No client available");return}if(!this.opts.samplingCallback){Ce.debug("setupSamplingHandler: No sampling callback provided");return}Ce.debug("setupSamplingHandler: Setting up sampling request handler"),this.client.setRequestHandler(cN,async(t,n)=>(Ce.debug("Server requested sampling, forwarding to callback"),await this.opts.samplingCallback(t.params))),Ce.debug("setupSamplingHandler: Sampling handler registered successfully")}setupElicitationHandler(){if(!this.client){Ce.debug("setupElicitationHandler: No client available");return}if(!this.opts.elicitationCallback){Ce.debug("setupElicitationHandler: No elicitation callback provided");return}Ce.debug("setupElicitationHandler: Setting up elicitation request handler"),this.client.setRequestHandler(dN,async(t,n)=>(Ce.debug("Server requested elicitation, forwarding to callback"),await this.opts.elicitationCallback(t.params))),Ce.debug("setupElicitationHandler: Elicitation handler registered successfully")}async disconnect(){if(!this.connected){Ce.debug("Not connected to MCP implementation");return}Ce.debug("Disconnecting from MCP implementation"),await this.cleanupResources(),this.connected=!1,Ce.debug("Disconnected from MCP implementation")}get isClientConnected(){return this.client!=null}async initialize(t=this.opts.defaultRequestOptions??{}){if(!this.client)throw new Error("MCP client is not connected");Ce.debug("Caching server capabilities & tools");const n=this.client.getServerCapabilities();this.capabilitiesCache=n||null;const a=this.client.getServerVersion();this.serverInfoCache=a||null;const r=await this.client.listTools(void 0,t);return this.toolsCache=r.tools??[],Ce.debug(`Fetched ${this.toolsCache.length} tools from server`),Ce.debug("Server capabilities:",n),Ce.debug("Server info:",a),n}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized; call initialize() first");return this.toolsCache}get serverCapabilities(){return this.capabilitiesCache||{}}get serverInfo(){return this.serverInfoCache}async callTool(t,n,a){if(!this.client)throw new Error("MCP client is not connected");const r=a?{...a}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},Ce.debug(`[BaseConnector] Added onprogress callback for tool '${t}' to enable progressToken`)),Ce.debug(`Calling tool '${t}' with args`,n);const i=await this.client.callTool({name:t,arguments:n},void 0,r);return Ce.debug(`Tool '${t}' returned`,i),i}async listTools(t){if(!this.client)throw new Error("MCP client is not connected");return(await this.client.listTools(void 0,t)).tools??[]}async listResources(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resources",t?`with cursor: ${t}`:""),await this.client.listResources({cursor:t},n)}async listAllResources(t){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.resources)return Ce.debug("Server does not advertise resources capability, skipping"),{resources:[]};try{Ce.debug("Listing all resources (with auto-pagination)");const n=[];let a;do{const r=await this.client.listResources({cursor:a},t);n.push(...r.resources||[]),a=r.nextCursor}while(a);return{resources:n}}catch(n){if(n.code===-32601)return Ce.debug("Server advertised resources but method not found"),{resources:[]};throw n}}async listResourceTemplates(t){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resource templates"),await this.client.listResourceTemplates(void 0,t)}async readResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Reading resource ${t}`),await this.client.readResource({uri:t},n)}async subscribeToResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Subscribing to resource: ${t}`),await this.client.subscribeResource({uri:t},n)}async unsubscribeFromResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Unsubscribing from resource: ${t}`),await this.client.unsubscribeResource({uri:t},n)}async listPrompts(){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.prompts)return Ce.debug("Server does not advertise prompts capability, skipping"),{prompts:[]};try{return Ce.debug("Listing prompts"),await this.client.listPrompts()}catch(t){if(t.code===-32601)return Ce.debug("Server advertised prompts but method not found"),{prompts:[]};throw t}}async getPrompt(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Getting prompt ${t}`),await this.client.getPrompt({name:t,arguments:n})}async request(t,n=null,a){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Sending raw request '${t}' with params`,n),await this.client.request({method:t,params:n??{}},void 0,a)}async cleanupResources(){const t=[];if(this.client)try{typeof this.client.close=="function"&&await this.client.close()}catch(n){const a=`Error closing client: ${n}`;Ce.warn(a),t.push(a)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(n){const a=`Error stopping connection manager: ${n}`;Ce.warn(a),t.push(a)}finally{this.connectionManager=null}this.toolsCache=null,t.length&&Ce.warn(`Resource cleanup finished with ${t.length} issue(s)`)}},Be(Wu,"BaseConnector"),Wu),Ku,Toe=(Ku=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),Ce.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw new Error("Connection was not established");return this._connection}async stop(){if(this._task&&this._abortController){Ce.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?Ce.debug(`${this.constructor.name} task aborted successfully`):Ce.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,Ce.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(t=>this._readyResolver=t),this._donePromise=new Promise(t=>this._doneResolver=t),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){Ce.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),Ce.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,Ce.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){Ce.warn(`Error closing connection in ${this.constructor.name}: ${t}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((t,n)=>{if(!this._abortController)return;const a=this._abortController.signal;if(a.aborted){t();return}const r=Be(()=>{a.removeEventListener("abort",r),t()},"onAbort");a.addEventListener("abort",r)})}},Be(Ku,"ConnectionManager"),Ku),Zu,Noe=(Zu=class extends Toe{url;opts;_transport=null;reinitializing=!1;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){const t=new xoe(this.url,this.opts),n=t.send.bind(t);return t.send=async a=>{const r=Be(async i=>{if(Array.isArray(i))for(const s of i)await n(s);else await n(i)},"sendMessage");try{await r(a)}catch(i){if(i?.code===404&&t.sessionId&&!this.reinitializing){Ce.warn("[SSE] Session not found (404), re-initializing per MCP spec..."),this.reinitializing=!0;try{t.sessionId=void 0,await this.reinitialize(t),Ce.info("[SSE] Re-initialization successful, retrying request"),await r(a)}finally{this.reinitializing=!1}}else throw i}},this._transport=t,Ce.debug(`${this.constructor.name} connected successfully`),t}async reinitialize(t){Ce.debug("[SSE] Re-initialization triggered")}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){Ce.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},Be(Zu,"SseConnectionManager"),Zu),Yu,Coe=(Yu=class extends koe{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;disableSseFallback;transportType=null;streamableTransport=null;constructor(t,n={}){super(n),this.baseUrl=t.replace(/\/$/,""),this.headers={...n.headers??{}},n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`),this.timeout=n.timeout??3e4,this.sseReadTimeout=n.sseReadTimeout??3e5,this.clientInfo=n.clientInfo??{name:"http-connector",version:"1.0.0"},this.preferSse=n.preferSse??!1,this.disableSseFallback=n.disableSseFallback??!1}async connect(){if(this.connected){Ce.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){Ce.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}Ce.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{Ce.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),Ce.info("✅ Successfully connected via streamable HTTP")}catch(n){let a="Unknown error",r=!1;if(n instanceof kl){const i=n;r=i.code===401,i.code===400&&i.message.includes("Missing session ID")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.code===404||i.code===405?(a=`Server returned ${i.code} - server likely doesn't support streamable HTTP`,Ce.debug(a)):(a=`Server returned ${i.code}: ${i.message}`,Ce.debug(a))}else if(n instanceof Error){const i=n.toString(),s=n.message||"";r=i.includes("401")||s.includes("Unauthorized"),i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||s.includes("FastMCP session ID error")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.includes("405 Method Not Allowed")||i.includes("404 Not Found")?(a="Server doesn't support streamable HTTP (405/404)",Ce.debug(a)):(a=`Streamable HTTP failed: ${n.message}`,Ce.debug(a))}if(r){Ce.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const i=new Error("Authentication required");throw i.code=401,i}if(this.disableSseFallback)throw Ce.info("SSE fallback disabled - failing connection"),await this.cleanupResources(),new Error(`Streamable HTTP connection failed: ${a}. SSE fallback is disabled.`);Ce.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(i){if(Ce.error("Failed to connect with both transports:"),Ce.error(` Streamable HTTP: ${a}`),Ce.error(` SSE: ${i}`),await this.cleanupResources(),i?.message?.includes("401")||i?.message?.includes("Unauthorized")){const c=new Error("Authentication required");throw c.code=401,c}throw new Error("Could not connect to server with any available transport")}}}async connectWithStreamableHttp(t){try{const n=new voe(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let a=n;if(this.opts.wrapTransport){const i=this.baseUrl;a=this.opts.wrapTransport(a,i)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities:",JSON.stringify(r.capabilities,null,2)),this.client=new YP(this.clientInfo,r),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect");try{await this.client.connect(a,{timeout:Math.min(this.timeout,3e3)});const i=n.sessionId;i?Ce.debug(`Session ID obtained: ${i}`):Ce.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(i){if(i instanceof Error){const s=i.message||i.toString();if(s.includes("Missing session ID")||s.includes("Bad Request: Missing session ID")||s.includes("Mcp-Session-Id header is required")){const c=new Error(`Session ID error: ${s}. The SDK should automatically extract session ID from initialize response.`);throw c.cause=i,c}}throw i}this.streamableTransport=n,this.connectionManager={stop:Be(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(i){Ce.warn(`Error closing Streamable HTTP transport: ${i}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via streamable HTTP: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (streamable-http)`})}catch(n){throw await this.cleanupResources(),n}}async connectWithSse(t){try{this.connectionManager=new Noe(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const r=this.baseUrl;n=this.opts.wrapTransport(n,r)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities (SSE):",JSON.stringify(a.capabilities,null,2)),this.client=new YP(this.clientInfo,a),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (sse)`})}catch(n){throw await this.cleanupResources(),n}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown"}}getTransportType(){return this.transportType}},Be(Yu,"HttpConnector"),Yu),zl,Roe=(zl=class extends Eoe{static getPackageVersion(){return Qb()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});zi.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>Ce.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new zl(t)}createConnectorFromConfig(t){const{url:n,headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h}=t;if(!n)throw new Error("Server URL is required");const g={headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h};return c?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(c,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),new Coe(n,g)}},Be(zl,"BrowserMCPClient"),zl);function du(e){const t=Be(()=>{throw new Error(`Invalid url to pass to open(): ${e}`)},"abort");let n;try{n=new URL(e)}catch{t()}return n.protocol!=="https:"&&n.protocol!=="http:"&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&(n.username=encodeURIComponent(n.username)),n.password&&(n.password=encodeURIComponent(n.password)),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,"/"),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(n9).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}Be(du,"sanitizeUrl");function n9([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}Be(n9,"sanitizeParam");var qu,Db=(qu=class{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;callbackUrl;preventAutoAuth;useRedirectFlow;onPopupWindow;constructor(t,n={}){this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||"mcp:auth",this.serverUrlHash=this.hashString(t),this.clientName=n.clientName||"mcp-use",this.clientUri=n.clientUri||(typeof window<"u"?window.location.origin:""),this.callbackUrl=du(n.callbackUrl||(typeof window<"u"?new URL("/oauth/callback",window.location.origin).toString():"/oauth/callback")),this.preventAutoAuth=n.preventAutoAuth,this.useRedirectFlow=n.useRedirectFlow,this.onPopupWindow=n.onPopupWindow}get redirectUrl(){return du(this.callbackUrl)}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:this.clientName,client_uri:this.clientUri}}async clientInformation(){const t=this.getKey("client_info"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,a),localStorage.removeItem(t);return}}async saveClientInformation(t){const n=this.getKey("client_info");localStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=this.getKey("tokens"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,a),localStorage.removeItem(t);return}}async saveTokens(t){const n=this.getKey("tokens");localStorage.setItem(n,JSON.stringify(t)),localStorage.removeItem(this.getKey("code_verifier")),localStorage.removeItem(this.getKey("last_auth_url"))}async saveCodeVerifier(t){const n=this.getKey("code_verifier");localStorage.setItem(n,t)}async codeVerifier(){const t=this.getKey("code_verifier"),n=localStorage.getItem(t);if(!n)throw new Error(`[${this.storageKeyPrefix}] Code verifier not found in storage for key ${t}. Auth flow likely corrupted or timed out.`);return n}async prepareAuthorizationUrl(t){const n=globalThis.crypto.randomUUID(),a=`${this.storageKeyPrefix}:state_${n}`,r={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,providerOptions:{serverUrl:this.serverUrl,storageKeyPrefix:this.storageKeyPrefix,clientName:this.clientName,clientUri:this.clientUri,callbackUrl:this.callbackUrl},flowType:this.useRedirectFlow?"redirect":"popup",returnUrl:this.useRedirectFlow&&typeof window<"u"?window.location.href:void 0};localStorage.setItem(a,JSON.stringify(r)),t.searchParams.set("state",n);const i=t.toString(),s=du(i);return localStorage.setItem(this.getKey("last_auth_url"),s),s}async redirectToAuthorization(t){const n=await this.prepareAuthorizationUrl(t);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=n;return}const a="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const r=window.open(n,`mcp_auth_${this.serverUrlHash}`,a);this.onPopupWindow&&this.onPopupWindow(n,a,r),!r||r.closed||typeof r.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(r.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(r){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,r)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?du(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,a=[];let r=0;for(let s=0;s<localStorage.length;s++){const c=localStorage.key(s);if(c){if(c.startsWith(t))a.push(c);else if(c.startsWith(n))try{const u=localStorage.getItem(c);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&a.push(c)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${c} during clearStorage:`,u)}}}return[...new Set(a)].forEach(s=>{localStorage.removeItem(s),r++}),r}hashString(t){let n=0;for(let a=0;a<t.length;a++){const r=t.charCodeAt(a);n=(n<<5)-n+r,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},Be(qu,"BrowserOAuthClientProvider"),qu);async function yN(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),a=e.get("error"),r=e.get("error_description"),i="[mcp-callback]";console.log(`${i} Handling callback...`,{code:t,state:n,error:a,errorDescription:r});let s=null,c=null;const u=n?`mcp:auth:state_${n}`:null;try{if(a)throw new Error(`OAuth error: ${a} - ${r||"No description provided."}`);if(!t)throw new Error("Authorization code not found in callback query parameters.");if(!n||!u)throw new Error("State parameter not found or invalid in callback query parameters.");const d=localStorage.getItem(u);if(!d)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{c=JSON.parse(d)}catch{throw new Error("Failed to parse stored OAuth state.")}if(!c.expiry||c.expiry<Date.now())throw localStorage.removeItem(u),new Error("OAuth state has expired. Please try initiating authentication again.");if(!c.providerOptions)throw new Error("Stored state is missing required provider options.");const{serverUrl:m,...h}=c.providerOptions;console.log(`${i} Re-instantiating provider for server: ${m}`),s=new Db(m,h),console.log(`${i} Calling SDK auth() to exchange code...`);const g=new URL(m).origin,v=await Ro(s,{serverUrl:g,authorizationCode:t});if(v==="AUTHORIZED")if(console.log(`${i} Authorization successful via SDK auth().`),c.flowType==="redirect"&&c.returnUrl)console.log(`${i} Redirect flow complete. Returning to: ${c.returnUrl}`),localStorage.removeItem(u),window.location.href=c.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${i} Popup flow complete. Notifying opener...`),window.opener.postMessage({type:"mcp_auth_callback",success:!0},window.location.origin),localStorage.removeItem(u),window.close();else{console.warn(`${i} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const S=window.location.pathname.split("/").filter(Boolean),w=S.length>0&&S[S.length-1]==="callback"?"/"+S.slice(0,-2).join("/"):"/";window.location.href=w||"/"}else throw console.warn(`${i} SDK auth() returned unexpected status: ${v}`),new Error(`Unexpected result from authentication library: ${v}`)}catch(d){console.error(`${i} Error during OAuth callback handling:`,d);const m=d instanceof Error?d.message:String(d);window.opener&&!window.opener.closed&&window.opener.postMessage({type:"mcp_auth_callback",success:!1,error:m},window.location.origin);try{document.body.innerHTML="";const h=document.createElement("div");h.style.fontFamily="sans-serif",h.style.padding="20px";const g=document.createElement("h1");g.textContent="Authentication Error",h.appendChild(g);const v=document.createElement("p");v.style.color="red",v.style.backgroundColor="#ffebeb",v.style.border="1px solid red",v.style.padding="10px",v.style.borderRadius="4px",v.textContent=m,h.appendChild(v);const x=document.createElement("p");x.textContent="You can close this window or ";const S=document.createElement("a");if(S.href="#",S.textContent="click here to close",S.onclick=w=>(w.preventDefault(),window.close(),!1),x.appendChild(S),x.appendChild(document.createTextNode(".")),h.appendChild(x),d instanceof Error&&d.stack){const w=document.createElement("pre");w.style.fontSize="0.8em",w.style.color="#555",w.style.marginTop="20px",w.style.whiteSpace="pre-wrap",w.textContent=d.stack,h.appendChild(w)}document.body.appendChild(h)}catch(h){console.error(`${i} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),s&&(localStorage.removeItem(s.getKey("code_verifier")),localStorage.removeItem(s.getKey("last_auth_url")))}}Be(yN,"onMcpAuthorization");var nx={exports:{}},yt={};var rU;function Aoe(){if(rU)return yt;rU=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),s=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function v(j){return j===null||typeof j!="object"?null:(j=g&&j[g]||j["@@iterator"],typeof j=="function"?j:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,w={};function E(j,V,z){this.props=j,this.context=V,this.refs=w,this.updater=z||x}E.prototype.isReactComponent={},E.prototype.setState=function(j,V){if(typeof j!="object"&&typeof j!="function"&&j!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,j,V,"setState")},E.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function _(){}_.prototype=E.prototype;function k(j,V,z){this.props=j,this.context=V,this.refs=w,this.updater=z||x}var C=k.prototype=new _;C.constructor=k,S(C,E.prototype),C.isPureReactComponent=!0;var R=Array.isArray;function I(){}var A={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function M(j,V,z){var $=z.ref;return{$$typeof:e,type:j,key:V,ref:$!==void 0?$:null,props:z}}function P(j,V){return M(j.type,V,j.props)}function B(j){return typeof j=="object"&&j!==null&&j.$$typeof===e}function K(j){var V={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(z){return V[z]})}var Q=/\/+/g;function ee(j,V){return typeof j=="object"&&j!==null&&j.key!=null?K(""+j.key):V.toString(36)}function ae(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then(I,I):(j.status="pending",j.then(function(V){j.status==="pending"&&(j.status="fulfilled",j.value=V)},function(V){j.status==="pending"&&(j.status="rejected",j.reason=V)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function H(j,V,z,$,L){var F=typeof j;(F==="undefined"||F==="boolean")&&(j=null);var W=!1;if(j===null)W=!0;else switch(F){case"bigint":case"string":case"number":W=!0;break;case"object":switch(j.$$typeof){case e:case t:W=!0;break;case m:return W=j._init,H(W(j._payload),V,z,$,L)}}if(W)return L=L(j),W=$===""?"."+ee(j,0):$,R(L)?(z="",W!=null&&(z=W.replace(Q,"$&/")+"/"),H(L,V,z,"",function(ue){return ue})):L!=null&&(B(L)&&(L=P(L,z+(L.key==null||j&&j.key===L.key?"":(""+L.key).replace(Q,"$&/")+"/")+W)),V.push(L)),1;W=0;var ne=$===""?".":$+":";if(R(j))for(var le=0;le<j.length;le++)$=j[le],F=ne+ee($,le),W+=H($,V,z,F,L);else if(le=v(j),typeof le=="function")for(j=le.call(j),le=0;!($=j.next()).done;)$=$.value,F=ne+ee($,le++),W+=H($,V,z,F,L);else if(F==="object"){if(typeof j.then=="function")return H(ae(j),V,z,$,L);throw V=String(j),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys(j).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.")}return W}function Z(j,V,z){if(j==null)return j;var $=[],L=0;return H(j,$,"","",function(F){return V.call(z,F,L++)}),$}function G(j){if(j._status===-1){var V=j._result;V=V(),V.then(function(z){(j._status===0||j._status===-1)&&(j._status=1,j._result=z)},function(z){(j._status===0||j._status===-1)&&(j._status=2,j._result=z)}),j._status===-1&&(j._status=0,j._result=V)}if(j._status===1)return j._result.default;throw j._result}var re=typeof reportError=="function"?reportError:function(j){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var V=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof j=="object"&&j!==null&&typeof j.message=="string"?String(j.message):String(j),error:j});if(!window.dispatchEvent(V))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",j);return}console.error(j)},te={map:Z,forEach:function(j,V,z){Z(j,function(){V.apply(this,arguments)},z)},count:function(j){var V=0;return Z(j,function(){V++}),V},toArray:function(j){return Z(j,function(V){return V})||[]},only:function(j){if(!B(j))throw Error("React.Children.only expected to receive a single React element child.");return j}};return yt.Activity=h,yt.Children=te,yt.Component=E,yt.Fragment=n,yt.Profiler=r,yt.PureComponent=k,yt.StrictMode=a,yt.Suspense=u,yt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,yt.__COMPILER_RUNTIME={__proto__:null,c:function(j){return A.H.useMemoCache(j)}},yt.cache=function(j){return function(){return j.apply(null,arguments)}},yt.cacheSignal=function(){return null},yt.cloneElement=function(j,V,z){if(j==null)throw Error("The argument must be a React element, but you passed "+j+".");var $=S({},j.props),L=j.key;if(V!=null)for(F in V.key!==void 0&&(L=""+V.key),V)!O.call(V,F)||F==="key"||F==="__self"||F==="__source"||F==="ref"&&V.ref===void 0||($[F]=V[F]);var F=arguments.length-2;if(F===1)$.children=z;else if(1<F){for(var W=Array(F),ne=0;ne<F;ne++)W[ne]=arguments[ne+2];$.children=W}return M(j.type,L,$)},yt.createContext=function(j){return j={$$typeof:s,_currentValue:j,_currentValue2:j,_threadCount:0,Provider:null,Consumer:null},j.Provider=j,j.Consumer={$$typeof:i,_context:j},j},yt.createElement=function(j,V,z){var $,L={},F=null;if(V!=null)for($ in V.key!==void 0&&(F=""+V.key),V)O.call(V,$)&&$!=="key"&&$!=="__self"&&$!=="__source"&&(L[$]=V[$]);var W=arguments.length-2;if(W===1)L.children=z;else if(1<W){for(var ne=Array(W),le=0;le<W;le++)ne[le]=arguments[le+2];L.children=ne}if(j&&j.defaultProps)for($ in W=j.defaultProps,W)L[$]===void 0&&(L[$]=W[$]);return M(j,F,L)},yt.createRef=function(){return{current:null}},yt.forwardRef=function(j){return{$$typeof:c,render:j}},yt.isValidElement=B,yt.lazy=function(j){return{$$typeof:m,_payload:{_status:-1,_result:j},_init:G}},yt.memo=function(j,V){return{$$typeof:d,type:j,compare:V===void 0?null:V}},yt.startTransition=function(j){var V=A.T,z={};A.T=z;try{var $=j(),L=A.S;L!==null&&L(z,$),typeof $=="object"&&$!==null&&typeof $.then=="function"&&$.then(I,re)}catch(F){re(F)}finally{V!==null&&z.types!==null&&(V.types=z.types),A.T=V}},yt.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},yt.use=function(j){return A.H.use(j)},yt.useActionState=function(j,V,z){return A.H.useActionState(j,V,z)},yt.useCallback=function(j,V){return A.H.useCallback(j,V)},yt.useContext=function(j){return A.H.useContext(j)},yt.useDebugValue=function(){},yt.useDeferredValue=function(j,V){return A.H.useDeferredValue(j,V)},yt.useEffect=function(j,V){return A.H.useEffect(j,V)},yt.useEffectEvent=function(j){return A.H.useEffectEvent(j)},yt.useId=function(){return A.H.useId()},yt.useImperativeHandle=function(j,V,z){return A.H.useImperativeHandle(j,V,z)},yt.useInsertionEffect=function(j,V){return A.H.useInsertionEffect(j,V)},yt.useLayoutEffect=function(j,V){return A.H.useLayoutEffect(j,V)},yt.useMemo=function(j,V){return A.H.useMemo(j,V)},yt.useOptimistic=function(j,V){return A.H.useOptimistic(j,V)},yt.useReducer=function(j,V,z){return A.H.useReducer(j,V,z)},yt.useRef=function(j){return A.H.useRef(j)},yt.useState=function(j){return A.H.useState(j)},yt.useSyncExternalStore=function(j,V,z){return A.H.useSyncExternalStore(j,V,z)},yt.useTransition=function(){return A.H.useTransition()},yt.version="19.2.3",yt}var aU;function wN(){return aU||(aU=1,nx.exports=Aoe()),nx.exports}var y=wN();const ce=ry(y),kd=cJ({__proto__:null,default:ce},[y]);function D_(e,t){if(!e)throw new Error(t)}Be(D_,"assert");var iU=3e3,Ioe=5e3;function SN(e){const{url:t,enabled:n=!0,clientName:a,clientUri:r,callbackUrl:i=typeof window<"u"?du(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:s="mcp:auth",clientConfig:c={},customHeaders:u={},debug:d=!1,autoRetry:m=!1,autoReconnect:h=iU,transportType:g="auto",preventAutoAuth:v=!1,useRedirectFlow:x=!1,onPopupWindow:S,timeout:w=3e4,sseReadTimeout:E=3e5,wrapTransport:_,onNotification:k,samplingCallback:C,onElicitation:R}=e,[I,A]=y.useState("discovering"),[O,M]=y.useState([]),[P,B]=y.useState([]),[K,Q]=y.useState([]),[ee,ae]=y.useState([]),[H,Z]=y.useState(),[G,re]=y.useState(),[te,j]=y.useState(void 0),[V,z]=y.useState([]),[$,L]=y.useState(void 0),F=y.useRef(null),W=y.useRef(null),ne=y.useRef(!1),le=y.useRef(!0),ue=y.useRef(0),X=y.useRef(null),q=y.useRef(I),oe=y.useRef(h),me=y.useRef(null);y.useEffect(()=>{q.current=I,oe.current=h},[I,h]);const ie=y.useCallback((Ve,Le,...Ee)=>{const je=Ee.length>0?`${Le} ${Ee.map(Fe=>JSON.stringify(Fe)).join(" ")}`:Le;console[Ve](`[useMcp] ${je}`),le.current&&z(Fe=>[...Fe.slice(-100),{level:Ve,message:je,timestamp:Date.now()}])},[]),Ne=y.useCallback(async(Ve=!1)=>{if(Ve||ie("info","Disconnecting..."),ne.current=!1,X.current&&clearTimeout(X.current),X.current=null,F.current)try{const Le="inspector-server",Ee=F.current.getSession(Le);Ee&&Ee._healthCheckCleanup&&(Ee._healthCheckCleanup(),Ee._healthCheckCleanup=null),await F.current.closeSession(Le)}catch(Le){Ve||ie("warn","Error closing session:",Le)}F.current=null,le.current&&!Ve&&(A("discovering"),M([]),B([]),Q([]),ae([]),j(void 0),L(void 0))},[ie]),He=y.useCallback((Ve,Le)=>{if(ie("error",Ve,Le??""),le.current){A("failed"),j(Ve);const Ee=W.current?.getLastAttemptedAuthUrl();Ee&&(L(Ee),ie("info","Manual authentication URL may be available.",Ee))}ne.current=!1,t&&zi.getInstance().trackUseMcpConnection({url:t,transportType:g,success:!1,errorType:Le?.name||"UnknownError",hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{})},[ie,t,g,C,R]),ye=y.useCallback(async()=>{if(!n||!t){ie("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(ne.current){ie("debug","Connection attempt already in progress.");return}if(!le.current){ie("debug","Connect called after unmount, aborting.");return}ne.current=!0,ue.current+=1,j(void 0),L(void 0),me.current=null,A("discovering"),ie("info",`Connecting attempt #${ue.current} to ${t}...`),W.current||(W.current=new Db(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),ie("debug","BrowserOAuthClientProvider initialized in connect.")),F.current||(F.current=new Roe,ie("debug","BrowserMCPClient initialized in connect."));const Ve=Be(async(Ee,je=!1)=>{ie("info",`Attempting connection with transport: ${Ee}`);try{const Fe="inspector-server",We={url:t,transport:Ee==="sse"?"http":Ee,disableSseFallback:Ee==="http",preferSse:Ee==="sse"};if(u&&Object.keys(u).length>0&&(We.headers=u),W.current){const Ze=await W.current.tokens();Ze?.access_token&&(We.headers={...We.headers,Authorization:`Bearer ${Ze.access_token}`})}F.current.addServer(Fe,{...We,authProvider:W.current,clientOptions:c,samplingCallback:C,elicitationCallback:R,wrapTransport:_?Ze=>(console.log("[useMcp] Applying transport wrapper for server:",Fe,"url:",t),_(Ze,t)):void 0});const Je=await F.current.createSession(Fe,!1);Je.on("notification",Ze=>{k?.(Ze),Ze.method==="notifications/tools/list_changed"?(ie("info","Tools list changed, auto-refreshing..."),nt().catch(mt=>ie("warn","Auto-refresh tools failed:",mt))):Ze.method==="notifications/resources/list_changed"?(ie("info","Resources list changed, auto-refreshing..."),ct().catch(mt=>ie("warn","Auto-refresh resources failed:",mt))):Ze.method==="notifications/prompts/list_changed"&&(ie("info","Prompts list changed, auto-refreshing..."),bt().catch(mt=>ie("warn","Auto-refresh prompts failed:",mt)))}),await Je.initialize(),ie("info","✅ Successfully connected to MCP server"),ie("info","Server info:",Je.connector.serverInfo),ie("info","Server capabilities:",Je.connector.serverCapabilities),console.log("[useMcp] Server info:",Je.connector.serverInfo),console.log("[useMcp] Server capabilities:",Je.connector.serverCapabilities),A("ready"),me.current=Ee;const St=Be(()=>{let Ze=null,mt=Date.now();const At=1e4,er=3e4;return Ze=setInterval(Be(async()=>{if(!le.current||q.current!=="ready"){Ze&&(clearInterval(Ze),Ze=null);return}try{await Je.connector.listTools(),mt=Date.now()}catch{const $n=Date.now()-mt;$n>er&&(ie("warn",`Connection appears to be broken (no response for ${Math.round($n/1e3)}s), attempting to reconnect...`),Ze&&(clearInterval(Ze),Ze=null),oe.current&&le.current&&(A("discovering"),ie("info","Auto-reconnecting to MCP server..."),setTimeout(()=>{le.current&&q.current==="discovering"&&ye()},typeof oe.current=="number"?oe.current:iU)))}},"checkConnectionHealth"),At),()=>{Ze&&(clearInterval(Ze),Ze=null)}},"setupConnectionMonitoring");if(h){const Ze=St();Je._healthCheckCleanup=Ze}zi.getInstance().trackUseMcpConnection({url:t,transportType:Ee,success:!0,hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{}),M(Je.connector.tools||[]);const ht=await Je.connector.listAllResources();B(ht.resources||[]);const Mt=await Je.connector.listPrompts();ae(Mt.prompts||[]);const rn=Je.connector.serverInfo,Ke=Je.connector.serverCapabilities;return rn&&(console.log("[useMcp] Server info:",rn),Z(rn)),Ke&&(console.log("[useMcp] Server capabilities:",Ke),re(Ke)),"success"}catch(Fe){const We=Fe,Je=We?.message||String(Fe);if(We.code===401||Je.includes("401")||Je.includes("Unauthorized")){if(W.current){ie("info","Authentication required. OAuth provider available.");try{const{auth:St}=await Jn(async()=>{const{auth:Mt}=await Promise.resolve().then(()=>JP);return{auth:Mt}},void 0),ht=new URL(t).origin;St(W.current,{serverUrl:ht}).catch(()=>{}),setTimeout(()=>{if(le.current){const Mt=W.current?.getLastAttemptedAuthUrl();Mt?(L(Mt),ie("info","Manual authentication URL available:",Mt)):ie("warn","Could not generate authentication URL")}},100)}catch(St){ie("warn","Error generating auth URL:",St)}return le.current&&A("pending_auth"),ne.current=!1,"auth_redirect"}return u&&Object.keys(u).length>0?(He("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(He("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return He(Je,We instanceof Error?We:new Error(String(We))),"failed"}},"tryConnectWithTransport");let Le="failed";if(g==="sse")ie("debug","Using SSE-only transport mode"),Le=await Ve("sse");else if(g==="http")ie("debug","Using HTTP-only transport mode"),Le=await Ve("http");else{ie("debug","Using auto transport mode (HTTP with SSE fallback)");const Ee=await Ve("http");Ee==="fallback"&&le.current&&q.current!=="authenticating"?(ie("info","HTTP failed, attempting SSE fallback..."),Le=await Ve("sse")):Le=Ee}(Le==="success"||Le==="failed"||Le==="auth_redirect")&&(ne.current=!1),ie("debug",`Connection sequence finished with status: ${Le}`)},[ie,He,Ne,t,s,a,r,i,c.name,c.version,u,g,v,x,S,n,w,E]),Se=y.useCallback(async(Ve,Le,Ee)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot call tool "${Ve}".`);ie("info",`Calling tool: ${Ve}`,Le);const je=Date.now();try{const We=F.current.getSession("inspector-server");if(!We)throw new Error("No active session found");const Je=await We.connector.callTool(Ve,Le||{},Ee);return ie("info",`Tool "${Ve}" call successful:`,Je),zi.getInstance().trackUseMcpToolCall({toolName:Ve,success:!0,executionTimeMs:Date.now()-je}).catch(()=>{}),Je}catch(Fe){throw ie("error",`Tool "${Ve}" call failed:`,Fe),zi.getInstance().trackUseMcpToolCall({toolName:Ve,success:!1,errorType:Fe instanceof Error?Fe.name:"UnknownError",executionTimeMs:Date.now()-je}).catch(()=>{}),Fe}},[I]),Pe=y.useCallback(()=>{q.current==="failed"?(ie("info","Retry requested..."),ye()):ie("warn",`Retry called but state is not 'failed' (state: ${q.current}). Ignoring.`)},[ie,ye]),fe=y.useCallback(async()=>{ie("info","Manual authentication requested...");const Ve=q.current;if(Ve==="failed")ie("info","Attempting to reconnect and authenticate via retry..."),Pe();else if(Ve==="pending_auth"){ie("info","Proceeding with authentication from pending state...");try{D_(W.current,"Auth Provider not available for manual auth"),D_(t,"Server URL is required for authentication"),ie("info","Clearing all OAuth state and initiating fresh flow...");const Le=`${s}:${W.current.serverUrlHash}`;Object.keys(localStorage).forEach(We=>{We.startsWith(Le)&&(ie("debug",`Removing stale OAuth key: ${We}`),localStorage.removeItem(We)),We.startsWith(`${s}:state_`)&&(ie("debug",`Removing orphaned state: ${We}`),localStorage.removeItem(We))}),A("authenticating");const Ee=new Db(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:!1,useRedirectFlow:x,onPopupWindow:S});W.current=Ee,ie("info","Triggering fresh OAuth authorization...");const{auth:je}=await Jn(async()=>{const{auth:We}=await Promise.resolve().then(()=>JP);return{auth:We}},void 0),Fe=new URL(t).origin;je(Ee,{serverUrl:Fe}).catch(We=>{ie("info","OAuth flow initiated:",We instanceof Error?We.message:"Redirecting...")})}catch(Le){if(!le.current)return;A("pending_auth"),ie("error",`Manual authentication failed: ${Le instanceof Error?Le.message:String(Le)}`)}}else if(Ve==="authenticating"){ie("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const Le=W.current?.getLastAttemptedAuthUrl();Le&&!$&&(L(Le),ie("info","Manual authentication URL retrieved:",Le))}else ie("info",`Client not in a state requiring manual authentication trigger (state: ${Ve}). If needed, try disconnecting and reconnecting.`)},[ie,Pe,$,t,x,S,s,a,r,i]),Ae=y.useCallback(()=>{if(W.current){const Ve=W.current.clearStorage();ie("info",`Cleared ${Ve} item(s) from localStorage for ${t}.`),L(void 0),Ne()}else ie("warn","Auth provider not initialized, cannot clear storage.")},[t,ie,Ne]),Me=y.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list resources.`);ie("info","Listing resources");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Ee=await Le.connector.listAllResources();B(Ee.resources||[]),ie("info","Resources listed successfully")}catch(Ve){throw ie("error","List resources failed:",Ve),Ve}},[I]),_e=y.useCallback(async Ve=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot read resource.`);ie("info",`Reading resource: ${Ve}`);try{const Ee=F.current.getSession("inspector-server");if(!Ee)throw new Error("No active session found");const je=await Ee.connector.readResource(Ve);return ie("info","Resource read successful:",je),zi.getInstance().trackUseMcpResourceRead({resourceUri:Ve,success:!0}).catch(()=>{}),je}catch(Le){throw ie("error","Resource read failed:",Le),zi.getInstance().trackUseMcpResourceRead({resourceUri:Ve,success:!1,errorType:Le instanceof Error?Le.name:"UnknownError"}).catch(()=>{}),Le}},[I]),rt=y.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list prompts.`);ie("info","Listing prompts");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Ee=await Le.connector.listPrompts();ae(Ee.prompts||[]),ie("info","Prompts listed successfully")}catch(Ve){throw ie("error","List prompts failed:",Ve),Ve}},[I]),nt=y.useCallback(async()=>{if(q.current!=="ready"||!F.current){ie("debug","Cannot refresh tools - client not ready");return}ie("debug","Refreshing tools list");try{const Le=F.current.getSession("inspector-server");if(!Le){ie("warn","No active session found for tools refresh");return}const Ee=await Le.connector.listTools();M(Ee||[]),ie("info","Tools list refreshed successfully")}catch(Ve){ie("warn","Failed to refresh tools:",Ve)}},[ie]),ct=y.useCallback(async()=>{if(q.current!=="ready"||!F.current){ie("debug","Cannot refresh resources - client not ready");return}ie("debug","Refreshing resources list");try{const Le=F.current.getSession("inspector-server");if(!Le){ie("warn","No active session found for resources refresh");return}const Ee=await Le.connector.listAllResources();B(Ee.resources||[]),ie("info","Resources list refreshed successfully")}catch(Ve){ie("warn","Failed to refresh resources:",Ve)}},[ie]),bt=y.useCallback(async()=>{if(q.current!=="ready"||!F.current){ie("debug","Cannot refresh prompts - client not ready");return}ie("debug","Refreshing prompts list");try{const Le=F.current.getSession("inspector-server");if(!Le){ie("warn","No active session found for prompts refresh");return}const Ee=await Le.connector.listPrompts();ae(Ee.prompts||[]),ie("info","Prompts list refreshed successfully")}catch(Ve){ie("warn","Failed to refresh prompts:",Ve)}},[ie]),ut=y.useCallback(async()=>{ie("info","Refreshing all lists (tools, resources, prompts)"),await Promise.all([nt(),ct(),bt()])},[nt,ct,bt,ie]),nn=y.useCallback(async(Ve,Le)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot get prompt.`);ie("info",`Getting prompt: ${Ve}`,Le);try{const je=F.current.getSession("inspector-server");if(!je)throw new Error("No active session found");const Fe=await je.connector.getPrompt(Ve,Le||{});return ie("info",`Prompt "${Ve}" retrieved successfully:`,Fe),Fe}catch(Ee){throw ie("error",`Prompt "${Ve}" retrieval failed:`,Ee),Ee}},[I]),Qn=y.useRef(ye),ot=y.useRef(He);return y.useEffect(()=>{Qn.current=ye,ot.current=He}),y.useEffect(()=>{const Ve=Be(Le=>{Le.origin===window.location.origin&&Le.data?.type==="mcp_auth_callback"&&(ie("info","Received auth callback message.",Le.data),X.current&&clearTimeout(X.current),X.current=null,Le.data.success?(ie("info","Authentication successful via popup. Reconnecting client..."),ne.current&&ie("debug","Connection attempt already in progress, resetting flag to allow reconnection."),ne.current=!1,setTimeout(()=>{le.current&&(ie("debug","Initiating reconnection after successful auth callback."),Qn.current())},100)):ot.current(`Authentication failed in callback: ${Le.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",Ve),ie("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",Ve),ie("debug","Auth callback message listener removed."),X.current&&clearTimeout(X.current)}},[ie]),y.useEffect(()=>(le.current=!0,!n||!t?(ie("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),A("discovering"),()=>{le.current=!1}):(ie("debug","useMcp mounted, initiating connection."),ue.current=0,(!W.current||W.current.serverUrl!==t)&&(W.current=new Db(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),ie("debug","BrowserOAuthClientProvider initialized/updated on mount/option change.")),ye(),()=>{le.current=!1,ie("debug","useMcp unmounting, disconnecting."),Ne(!0)})),[t,n,s,i,a,r,c.name,c.version,x]),y.useEffect(()=>{let Ve=null;if(I==="failed"&&m&&ue.current>0){const Le=typeof m=="number"?m:Ioe;ie("info",`Connection failed, auto-retrying in ${Le}ms...`),Ve=setTimeout(()=>{le.current&&q.current==="failed"&&Pe()},Le)}return()=>{Ve&&clearTimeout(Ve)}},[I,m,Pe,ie]),{state:I,tools:O,resources:P,resourceTemplates:K,prompts:ee,serverInfo:H,capabilities:G,error:te,log:V,authUrl:$,client:F.current,callTool:Se,readResource:_e,listResources:Me,listPrompts:rt,getPrompt:nn,refreshTools:nt,refreshResources:ct,refreshPrompts:bt,refreshAll:ut,retry:Pe,disconnect:Ne,authenticate:fe,clearStorage:Ae}}Be(SN,"useMcp");var Xu,Ooe=(Xu=class extends ce.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Widget Error:",t,n)}render(){return this.state.hasError?ce.createElement("div",{className:"p-4 border border-red-500 bg-red-50 text-red-900 rounded-md dark:bg-red-900/20 dark:text-red-100"},ce.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),ce.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},Be(Xu,"ErrorBoundary"),Xu),pp="openai:set_globals";function di(e){return y.useSyncExternalStore(t=>{const n=Be(a=>{a.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener(pp,n),()=>{typeof window<"u"&&window.removeEventListener(pp,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}Be(di,"useOpenAiGlobal");function Td(e){const[t,n]=y.useState(()=>typeof window<"u"&&!!window.openai);y.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const P=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},100),B=Be(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},"handleSetGlobals");typeof window<"u"&&window.addEventListener(pp,B);const K=setTimeout(()=>{clearInterval(P),typeof window<"u"&&window.removeEventListener(pp,B)},5e3);return()=>{clearInterval(P),clearTimeout(K),typeof window<"u"&&window.removeEventListener(pp,B)}},[]);const a=y.useMemo(()=>t?"openai":"mcp-ui",[t]),r=typeof window<"u"?window.location.search:"",i=y.useMemo(()=>{const P=new URLSearchParams(r);return P.has("mcpUseParams")?JSON.parse(P.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[r]),s=a==="openai"?di("toolInput"):i.toolInput,c=a==="openai"?di("toolOutput"):i.toolOutput,u=di("toolResponseMetadata"),d=y.useMemo(()=>{if(u&&typeof u=="object"){const P=u["mcp-use/props"];if(P)return P}return e||{}},[u,e]),m=di("widgetState"),h=di("theme"),g=di("displayMode"),v=di("safeArea"),x=di("maxHeight"),S=di("userAgent"),w=di("locale"),E=y.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,k]=y.useState(null);y.useEffect(()=>{m!==void 0&&k(m)},[m]);const C=y.useCallback(async(P,B)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(P,B)},[]),R=y.useCallback(async P=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:P})},[]),I=y.useCallback(P=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:P})},[]),A=y.useCallback(async P=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:P})},[]),O=y.useCallback(async P=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const K=typeof P=="function"?P(m!==void 0?m:_):P;return k(K),window.openai.setWidgetState(K)},[m,_]),M=y.useMemo(()=>a==="openai"&&u===null,[a,u]);return{props:d,toolInput:s||{},output:c??null,metadata:u??null,state:_,setState:O,theme:h||"light",displayMode:g||"inline",safeArea:v||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:x||600,userAgent:S||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:w||"en",mcp_url:E,callTool:C,sendFollowUpMessage:R,openExternal:I,requestDisplayMode:A,isAvailable:t,isPending:M}}Be(Td,"useWidget");function Doe(e){const{props:t}=Td(e);return t}Be(Doe,"useWidgetProps");function joe(){const{theme:e}=Td();return e}Be(joe,"useWidgetTheme");function $oe(e){const{state:t,setState:n}=Td();return y.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}Be($oe,"useWidgetState");var oU=Be(({children:e})=>{const{theme:t,isAvailable:n}=Td();console.log("theme",t);const[a,r]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");y.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(prefers-color-scheme: dark)"),c=Be(u=>{r(u.matches?"dark":"light")},"handleChange");return s.addEventListener("change",c),()=>s.removeEventListener("change",c)},[]);const i=n?t:a;return y.useLayoutEffect(()=>{typeof document>"u"||(i==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[i]),ce.createElement(ce.Fragment,null,e)},"ThemeProvider");function r9({children:e,className:t="",position:n="top-right",attachTo:a,showLabels:r=!0,debugger:i=!1,viewControls:s=!1}){const{props:c,output:u,metadata:d,state:m,theme:h,displayMode:g,safeArea:v,maxHeight:x,userAgent:S,locale:w,isAvailable:E,callTool:_,sendFollowUpMessage:k,openExternal:C,requestDisplayMode:R,setState:I}=Td(),[A,O]=y.useState(!1),[M,P]=y.useState(!1),B=y.useRef(null),K=y.useRef(null),[Q,ee]=y.useState([]),[ae,H]=y.useState(""),[Z,G]=y.useState("get-my-city"),[re,te]=y.useState("{}"),[j,V]=y.useState("Test follow-up message"),[z,$]=y.useState("https://docs.mcp-use.com"),L=g==="fullscreen"&&E,F=g==="pip"&&E,W=typeof window<"u"&&window.location.pathname.includes("/inspector/api/");y.useEffect(()=>{const _e=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const rt=Object.keys(window.openai);ee(rt)}catch{ee([])}else ee([])},100);return()=>{clearTimeout(_e)}},[]);const ne=h==="dark",le=Be(()=>{const _e=["absolute","z-[1000]","flex","gap-2","transition-opacity","duration-200","ease-in-out",A?"opacity-100":"opacity-0",A?"pointer-events-auto":"pointer-events-none"];switch(n){case"top-left":return[..._e,"top-4","left-4"];case"top-center":return[..._e,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[..._e,"top-4","right-4"];case"center-left":return[..._e,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[..._e,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[..._e,"bottom-4","left-4"];case"bottom-center":return[..._e,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[..._e,"bottom-4","right-4"];default:return[..._e,"top-4","right-4"]}},"getPositionClasses"),ue=Be(()=>{const rt=v?.insets?.top?Math.max(16,v.insets.top+8):16,nt=v?.insets?.right?Math.max(16,v.insets.right+8):16,ct=v?.insets?.bottom?Math.max(16,v.insets.bottom+8):16,bt=v?.insets?.left?Math.max(16,v.insets.left+8):16,ut={};switch(n){case"top-left":ut.top=`${rt}px`,ut.left=`${bt}px`;break;case"top-center":ut.top=`${rt}px`;break;case"top-right":ut.top=`${rt}px`,ut.right=`${nt}px`;break;case"center-left":ut.left=`${bt}px`;break;case"center-right":ut.right=`${nt}px`;break;case"bottom-left":ut.bottom=`${ct}px`,ut.left=`${bt}px`;break;case"bottom-center":ut.bottom=`${ct}px`;break;case"bottom-right":ut.bottom=`${ct}px`,ut.right=`${nt}px`;break;default:ut.top=`${rt}px`,ut.right=`${nt}px`;break}return ut},"getPositionOffsetStyles");y.useEffect(()=>{if(!a)return;const _e=Be(()=>O(!0),"handleMouseEnter"),rt=Be(()=>O(!1),"handleMouseLeave");return a.addEventListener("mouseenter",_e),a.addEventListener("mouseleave",rt),()=>{a.removeEventListener("mouseenter",_e),a.removeEventListener("mouseleave",rt)}},[a]),y.useEffect(()=>{if(!M)return;const _e=Be(rt=>{K.current&&!K.current.contains(rt.target)&&P(!1)},"handleClickOutside");return document.addEventListener("mousedown",_e),()=>{document.removeEventListener("mousedown",_e)}},[M]),y.useEffect(()=>(M?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[M]);const X=Be(()=>{P(!M)},"handleToggleOverlay"),q=Be(async()=>{try{H("Calling tool...");const _e=re.trim()?JSON.parse(re):{},rt=await _(Z,_e);H(`Success: ${JSON.stringify(rt,null,2)}`)}catch(_e){H(`Error: ${_e.message}`)}},"handleCallTool"),oe=Be(async()=>{try{H("Sending follow-up message..."),await k(j),H("Follow-up message sent successfully")}catch(_e){H(`Error: ${_e.message}`)}},"handleSendFollowUpMessage"),me=Be(()=>{try{C(z),H(`Opened external link: ${z}`)}catch(_e){H(`Error: ${_e.message}`)}},"handleOpenExternal"),ie=Be(async _e=>{try{H(`Requesting display mode: ${_e}...`);const rt=await R(_e);H(`Display mode granted: ${rt.mode}`)}catch(rt){H(`Error: ${rt.message}`)}},"handleRequestDisplayMode"),Ne=Be(async()=>{try{const _e=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};H("Setting state..."),await I(_e),H(`State updated: ${JSON.stringify(_e,null,2)}`)}catch(_e){H(`Error: ${_e.message}`)}},"handleSetState"),He=Be(async()=>{try{await R("fullscreen")}catch(_e){console.error("Failed to go fullscreen:",_e)}},"handleFullscreen"),ye=Be(async()=>{try{await R("pip")}catch(_e){console.error("Failed to go pip:",_e)}},"handlePip"),Se=Be(()=>{const _e=["absolute","px-2","py-1","bg-black/90","text-white","rounded","text-xs","whitespace-nowrap","pointer-events-none","transition-opacity","duration-200","ease-in-out"];switch(n){case"top-right":return[..._e,"top-full","right-0","mt-2"];case"top-left":return[..._e,"top-full","left-0","mt-2"];case"top-center":return[..._e,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[..._e,"bottom-full","right-0","mb-2"];case"bottom-left":return[..._e,"bottom-full","left-0","mb-2"];case"bottom-center":return[..._e,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[..._e,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[..._e,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[..._e,"top-full","right-0","mt-2"]}},"getTooltipClasses"),Pe=Be(({onClick:_e,label:rt,children:nt})=>{const[ct,bt]=y.useState(!1),ut=Se();return ce.createElement("button",{className:`p-2 ${ne?"bg-white/10 hover:bg-white/20":"bg-black/70 hover:bg-black/90"} text-white border-none rounded-lg cursor-pointer flex items-center justify-center w-8 h-8 transition-colors duration-200 backdrop-blur-md ${ne?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>bt(!0),onMouseLeave:()=>bt(!1),onClick:_e,"aria-label":rt},ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"block"},nt),r&&ce.createElement("span",{className:`${ut.join(" ")} ${ct?"opacity-100":"opacity-0"}`},rt))},"IconButton"),fe=Be(_e=>{if(_e===null)return"null";if(_e===void 0)return"undefined";if(typeof _e=="object")try{return JSON.stringify(_e,null,2)}catch{return String(_e)}return String(_e)},"formatValue"),Ae=Be(_e=>_e?`${_e.device?.type||"unknown"}`:"N/A","formatUserAgent"),Me=Be(_e=>{if(!_e?.insets)return"N/A";const{top:rt,bottom:nt,left:ct,right:bt}=_e.insets;return`T:${rt} B:${nt} L:${ct} R:${bt}`},"formatSafeArea");return ce.createElement(ce.Fragment,null,ce.createElement("div",{ref:B,className:`${t} relative h-fit`,onMouseEnter:()=>!a&&O(!0),onMouseLeave:()=>!a&&O(!1)},ce.createElement("div",{className:le().join(" "),style:ue()},!W&&ce.createElement(ce.Fragment,null,!L&&!F&&ce.createElement(ce.Fragment,null,(s===!0||s==="fullscreen")&&ce.createElement(Pe,{onClick:He,label:"Fullscreen"},ce.createElement("path",{d:"M15 3h6v6"}),ce.createElement("path",{d:"m21 3-7 7"}),ce.createElement("path",{d:"m3 21 7-7"}),ce.createElement("path",{d:"M9 21H3v-6"})),(s===!0||s==="pip")&&ce.createElement(Pe,{onClick:ye,label:"Picture in Picture"},ce.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),ce.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),i&&ce.createElement(Pe,{onClick:X,label:"Debug Info"},ce.createElement("path",{d:"M12 20v-9"}),ce.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),ce.createElement("path",{d:"M14.12 3.88 16 2"}),ce.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),ce.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),ce.createElement("path",{d:"M22 13h-4"}),ce.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),ce.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),ce.createElement("path",{d:"M6 13H2"}),ce.createElement("path",{d:"m8 2 1.88 1.88"}),ce.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),M&&i&&ce.createElement("div",{ref:K,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:_e=>{_e.target===K.current&&P(!1)}},ce.createElement("button",{onClick:()=>P(!1),className:"absolute top-4 right-4 bg-white/10 text-white border-none rounded w-8 h-8 cursor-pointer flex items-center justify-center text-lg leading-none","aria-label":"Close"},"×"),ce.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},ce.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),ce.createElement("table",{className:"w-full border-collapse border-spacing-0"},ce.createElement("tbody",null,ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(c))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(u))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(d))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(m))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),ce.createElement("td",{className:"p-2"},h)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),ce.createElement("td",{className:"p-2"},g)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),ce.createElement("td",{className:"p-2"},w)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),ce.createElement("td",{className:"p-2"},x,"px")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),ce.createElement("td",{className:"p-2"},Ae(S))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),ce.createElement("td",{className:"p-2"},Me(v))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),ce.createElement("td",{className:"p-2"},E?"Yes":"No")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),ce.createElement("td",{className:"p-2"},Q.length>0?Q.join(", "):"N/A")))),ce.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),ce.createElement("div",{className:"flex flex-col gap-3"},ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:Z,onChange:_e=>G(_e.target.value),placeholder:"Tool name",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs w-[150px]"}),ce.createElement("input",{type:"text",value:re,onChange:_e=>te(_e.target.value),placeholder:'{"key": "value"}',className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ce.createElement("button",{onClick:q,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:j,onChange:_e=>V(_e.target.value),placeholder:"Follow-up message",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ce.createElement("button",{onClick:oe,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Send Follow-Up")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:z,onChange:_e=>$(_e.target.value),placeholder:"External URL",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ce.createElement("button",{onClick:me,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),ce.createElement("button",{onClick:()=>ie("inline"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Inline"),ce.createElement("button",{onClick:()=>ie("pip"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"PiP"),ce.createElement("button",{onClick:()=>ie("fullscreen"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Fullscreen")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("button",{onClick:Ne,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Set State (Add Timestamp)")),ae&&ce.createElement("div",{className:"mt-2 p-2 bg-[#1a1a1a] border border-gray-700 rounded whitespace-pre-wrap break-all text-[11px] max-h-[200px] overflow-auto"},ce.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),ae,ce.createElement("button",{onClick:()=>H(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}Be(r9,"WidgetControls");function a9(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}Be(a9,"getBasename");var Loe=150,Moe=5;function Poe({children:e,debugger:t=!1,viewControls:n=!1,autoSize:a=!1}){const r=a9(),i=y.useRef(null),s=y.useRef(0),c=y.useRef(null),u=y.useRef(!1),[d,m]=y.useState(null),[h,g]=y.useState(null),[v,x]=y.useState(!0);y.useEffect(()=>{let _=!0;return(async()=>{try{const k=await Jn(()=>import("./index-ClpBZU-N.js"),[]);_&&(m(()=>k.BrowserRouter),x(!1))}catch{_&&(g(new Error(`❌ react-router not installed!
|
|
36
36
|
|
|
37
37
|
To use MCP widgets with McpUseProvider, you need to install:
|
|
38
38
|
|
|
@@ -90,7 +90,7 @@ Please change the parent <Route path="${_}"> to <Route path="${_==="/"?"*":`${_}
|
|
|
90
90
|
`)},WU=function(){var e=parseInt(document.body.getAttribute(_u)||"0",10);return isFinite(e)?e:0},Wde=function(){y.useEffect(function(){return document.body.setAttribute(_u,(WU()+1).toString()),function(){var e=WU()-1;e<=0?document.body.removeAttribute(_u):document.body.setAttribute(_u,e.toString())}},[])},Kde=function(e){var t=e.noRelative,n=e.noImportant,a=e.gapMode,r=a===void 0?"margin":a;Wde();var i=y.useMemo(function(){return Hde(r)},[r]);return y.createElement(Vde,{styles:Gde(i,!t,r,n?"":"!important")})},H_=!1;if(typeof window<"u")try{var sb=Object.defineProperty({},"passive",{get:function(){return H_=!0,!0}});window.addEventListener("test",sb,sb),window.removeEventListener("test",sb,sb)}catch{H_=!1}var Zc=H_?{passive:!1}:!1,Zde=function(e){return e.tagName==="TEXTAREA"},k8=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Zde(e)&&n[t]==="visible")},Yde=function(e){return k8(e,"overflowY")},qde=function(e){return k8(e,"overflowX")},KU=function(e,t){var n=t.ownerDocument,a=t;do{typeof ShadowRoot<"u"&&a instanceof ShadowRoot&&(a=a.host);var r=T8(e,a);if(r){var i=N8(e,a),s=i[1],c=i[2];if(s>c)return!0}a=a.parentNode}while(a&&a!==n.body);return!1},Xde=function(e){var t=e.scrollTop,n=e.scrollHeight,a=e.clientHeight;return[t,n,a]},Jde=function(e){var t=e.scrollLeft,n=e.scrollWidth,a=e.clientWidth;return[t,n,a]},T8=function(e,t){return e==="v"?Yde(t):qde(t)},N8=function(e,t){return e==="v"?Xde(t):Jde(t)},Qde=function(e,t){return e==="h"&&t==="rtl"?-1:1},efe=function(e,t,n,a,r){var i=Qde(e,window.getComputedStyle(t).direction),s=i*a,c=n.target,u=t.contains(c),d=!1,m=s>0,h=0,g=0;do{if(!c)break;var v=N8(e,c),x=v[0],S=v[1],w=v[2],E=S-w-i*x;(x||E)&&T8(e,c)&&(h+=E,g+=x);var _=c.parentNode;c=_&&_.nodeType===Node.DOCUMENT_FRAGMENT_NODE?_.host:_}while(!u&&c!==document.body||u&&(t.contains(c)||t===c));return(m&&Math.abs(h)<1||!m&&Math.abs(g)<1)&&(d=!0),d},lb=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},ZU=function(e){return[e.deltaX,e.deltaY]},YU=function(e){return e&&"current"in e?e.current:e},tfe=function(e,t){return e[0]===t[0]&&e[1]===t[1]},nfe=function(e){return`
|
|
91
91
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
92
92
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
93
|
-
`)},rfe=0,Yc=[];function afe(e){var t=y.useRef([]),n=y.useRef([0,0]),a=y.useRef(),r=y.useState(rfe++)[0],i=y.useState(E8)[0],s=y.useRef(e);y.useEffect(function(){s.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var S=kde([e.lockRef.current],(e.shards||[]).map(YU),!0).filter(Boolean);return S.forEach(function(w){return w.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),S.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var c=y.useCallback(function(S,w){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!s.current.allowPinchZoom;var E=lb(S),_=n.current,k="deltaX"in S?S.deltaX:_[0]-E[0],C="deltaY"in S?S.deltaY:_[1]-E[1],R,I=S.target,A=Math.abs(k)>Math.abs(C)?"h":"v";if("touches"in S&&A==="h"&&I.type==="range")return!1;var O=window.getSelection(),M=O&&O.anchorNode,P=M?M===I||M.contains(I):!1;if(P)return!1;var B=KU(A,I);if(!B)return!0;if(B?R=A:(R=A==="v"?"h":"v",B=KU(A,I)),!B)return!1;if(!a.current&&"changedTouches"in S&&(k||C)&&(a.current=R),!R)return!0;var K=a.current||R;return efe(K,w,S,K==="h"?k:C)},[]),u=y.useCallback(function(S){var w=S;if(!(!Yc.length||Yc[Yc.length-1]!==i)){var E="deltaY"in w?ZU(w):lb(w),_=t.current.filter(function(R){return R.name===w.type&&(R.target===w.target||w.target===R.shadowParent)&&tfe(R.delta,E)})[0];if(_&&_.should){w.cancelable&&w.preventDefault();return}if(!_){var k=(s.current.shards||[]).map(YU).filter(Boolean).filter(function(R){return R.contains(w.target)}),C=k.length>0?c(w,k[0]):!s.current.noIsolation;C&&w.cancelable&&w.preventDefault()}}},[]),d=y.useCallback(function(S,w,E,_){var k={name:S,delta:w,target:E,should:_,shadowParent:ife(E)};t.current.push(k),setTimeout(function(){t.current=t.current.filter(function(C){return C!==k})},1)},[]),m=y.useCallback(function(S){n.current=lb(S),a.current=void 0},[]),h=y.useCallback(function(S){d(S.type,ZU(S),S.target,c(S,e.lockRef.current))},[]),g=y.useCallback(function(S){d(S.type,lb(S),S.target,c(S,e.lockRef.current))},[]);y.useEffect(function(){return Yc.push(i),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,Zc),document.addEventListener("touchmove",u,Zc),document.addEventListener("touchstart",m,Zc),function(){Yc=Yc.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,Zc),document.removeEventListener("touchmove",u,Zc),document.removeEventListener("touchstart",m,Zc)}},[]);var v=e.removeScrollBar,x=e.inert;return y.createElement(y.Fragment,null,x?y.createElement(i,{styles:nfe(r)}):null,v?y.createElement(Kde,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function ife(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ofe=jde(_8,afe);var Om=y.forwardRef(function(e,t){return y.createElement(Hy,Fi({},e,{ref:t,sideCar:ofe}))});Om.classNames=Hy.classNames;var V_=["Enter"," "],sfe=["ArrowDown","PageUp","Home"],C8=["ArrowUp","PageDown","End"],lfe=[...sfe,...C8],cfe={ltr:[...V_,"ArrowRight"],rtl:[...V_,"ArrowLeft"]},ufe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Dm="Menu",[zp,dfe,ffe]=CN(Dm),[nc,R8]=Ii(Dm,[ffe,Zs,h8]),Vy=Zs(),A8=h8(),[pfe,rc]=nc(Dm),[mfe,jm]=nc(Dm),I8=e=>{const{__scopeMenu:t,open:n=!1,children:a,dir:r,onOpenChange:i,modal:s=!0}=e,c=Vy(t),[u,d]=y.useState(null),m=y.useRef(!1),h=Zi(i),g=RN(r);return y.useEffect(()=>{const v=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.jsx(Uy,{...c,children:f.jsx(pfe,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:d,children:f.jsx(mfe,{scope:t,onClose:y.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:s,children:a})})})};I8.displayName=Dm;var hfe="MenuAnchor",UN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Vy(n);return f.jsx(Am,{...r,...a,ref:t})});UN.displayName=hfe;var zN="MenuPortal",[gfe,O8]=nc(zN,{forceMount:void 0}),D8=e=>{const{__scopeMenu:t,forceMount:n,children:a,container:r}=e,i=rc(zN,t);return f.jsx(gfe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};D8.displayName=zN;var Qa="MenuContent",[bfe,FN]=nc(Qa),j8=y.forwardRef((e,t)=>{const n=O8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:s.modal?f.jsx(vfe,{...r,ref:t}):f.jsx(yfe,{...r,ref:t})})})})}),vfe=y.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu),a=y.useRef(null),r=Jt(t,a);return y.useEffect(()=>{const i=a.current;if(i)return By(i)},[]),f.jsx(BN,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),yfe=y.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu);return f.jsx(BN,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),wfe=Vl("MenuContent.ScrollLock"),BN=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:a=!1,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,disableOutsideScroll:x,...S}=e,w=rc(Qa,n),E=jm(Qa,n),_=Vy(n),k=A8(n),C=dfe(n),[R,I]=y.useState(null),A=y.useRef(null),O=Jt(t,A,w.onContentChange),M=y.useRef(0),P=y.useRef(""),B=y.useRef(0),K=y.useRef(null),Q=y.useRef("right"),ee=y.useRef(0),ae=x?Om:y.Fragment,H=x?{as:wfe,allowPinchZoom:!0}:void 0,Z=re=>{const te=P.current+re,j=C().filter(W=>!W.disabled),V=document.activeElement,z=j.find(W=>W.ref.current===V)?.textValue,$=j.map(W=>W.textValue),L=Ofe($,te,z),F=j.find(W=>W.textValue===L)?.ref.current;(function W(ne){P.current=ne,window.clearTimeout(M.current),ne!==""&&(M.current=window.setTimeout(()=>W(""),1e3))})(te),F&&setTimeout(()=>F.focus())};y.useEffect(()=>()=>window.clearTimeout(M.current),[]),jy();const G=y.useCallback(re=>Q.current===K.current?.side&&jfe(re,K.current?.area),[]);return f.jsx(bfe,{scope:n,searchRef:P,onItemEnter:y.useCallback(re=>{G(re)&&re.preventDefault()},[G]),onItemLeave:y.useCallback(re=>{G(re)||(A.current?.focus(),I(null))},[G]),onTriggerLeave:y.useCallback(re=>{G(re)&&re.preventDefault()},[G]),pointerGraceTimerRef:B,onPointerGraceIntentChange:y.useCallback(re=>{K.current=re},[]),children:f.jsx(ae,{...H,children:f.jsx(Cm,{asChild:!0,trapped:r,onMountAutoFocus:Ge(i,re=>{re.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,children:f.jsx(wde,{asChild:!0,...k,dir:E.dir,orientation:"vertical",loop:a,currentTabStopId:R,onCurrentTabStopIdChange:I,onEntryFocus:Ge(u,re=>{E.isUsingKeyboardRef.current||re.preventDefault()}),preventScrollOnEntryFocus:!0,children:f.jsx(zy,{role:"menu","aria-orientation":"vertical","data-state":q8(w.open),"data-radix-menu-content":"",dir:E.dir,..._,...S,ref:O,style:{outline:"none",...S.style},onKeyDown:Ge(S.onKeyDown,re=>{const j=re.target.closest("[data-radix-menu-content]")===re.currentTarget,V=re.ctrlKey||re.altKey||re.metaKey,z=re.key.length===1;j&&(re.key==="Tab"&&re.preventDefault(),!V&&z&&Z(re.key));const $=A.current;if(re.target!==$||!lfe.includes(re.key))return;re.preventDefault();const F=C().filter(W=>!W.disabled).map(W=>W.ref.current);C8.includes(re.key)&&F.reverse(),Afe(F)}),onBlur:Ge(e.onBlur,re=>{re.currentTarget.contains(re.target)||(window.clearTimeout(M.current),P.current="")}),onPointerMove:Ge(e.onPointerMove,Fp(re=>{const te=re.target,j=ee.current!==re.clientX;if(re.currentTarget.contains(te)&&j){const V=re.clientX>ee.current?"right":"left";Q.current=V,ee.current=re.clientX}}))})})})})})})});j8.displayName=Qa;var Sfe="MenuGroup",HN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(Et.div,{role:"group",...a,ref:t})});HN.displayName=Sfe;var xfe="MenuLabel",$8=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(Et.div,{...a,ref:t})});$8.displayName=xfe;var Nv="MenuItem",qU="menu.itemSelect",Gy=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:a,...r}=e,i=y.useRef(null),s=jm(Nv,e.__scopeMenu),c=FN(Nv,e.__scopeMenu),u=Jt(t,i),d=y.useRef(!1),m=()=>{const h=i.current;if(!n&&h){const g=new CustomEvent(qU,{bubbles:!0,cancelable:!0});h.addEventListener(qU,v=>a?.(v),{once:!0}),H9(h,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.jsx(L8,{...r,ref:u,disabled:n,onClick:Ge(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),d.current=!0},onPointerUp:Ge(e.onPointerUp,h=>{d.current||h.currentTarget?.click()}),onKeyDown:Ge(e.onKeyDown,h=>{const g=c.searchRef.current!=="";n||g&&h.key===" "||V_.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Gy.displayName=Nv;var L8=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:a=!1,textValue:r,...i}=e,s=FN(Nv,n),c=A8(n),u=y.useRef(null),d=Jt(t,u),[m,h]=y.useState(!1),[g,v]=y.useState("");return y.useEffect(()=>{const x=u.current;x&&v((x.textContent??"").trim())},[i.children]),f.jsx(zp.ItemSlot,{scope:n,disabled:a,textValue:r??g,children:f.jsx(Sde,{asChild:!0,...c,focusable:!a,children:f.jsx(Et.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":a||void 0,"data-disabled":a?"":void 0,...i,ref:d,onPointerMove:Ge(e.onPointerMove,Fp(x=>{a?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ge(e.onPointerLeave,Fp(x=>s.onItemLeave(x))),onFocus:Ge(e.onFocus,()=>h(!0)),onBlur:Ge(e.onBlur,()=>h(!1))})})})}),_fe="MenuCheckboxItem",M8=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:a,...r}=e;return f.jsx(B8,{scope:e.__scopeMenu,checked:n,children:f.jsx(Gy,{role:"menuitemcheckbox","aria-checked":Cv(n)?"mixed":n,...r,ref:t,"data-state":GN(n),onSelect:Ge(r.onSelect,()=>a?.(Cv(n)?!0:!n),{checkForDefaultPrevented:!1})})})});M8.displayName=_fe;var P8="MenuRadioGroup",[Efe,kfe]=nc(P8,{value:void 0,onValueChange:()=>{}}),U8=y.forwardRef((e,t)=>{const{value:n,onValueChange:a,...r}=e,i=Zi(a);return f.jsx(Efe,{scope:e.__scopeMenu,value:n,onValueChange:i,children:f.jsx(HN,{...r,ref:t})})});U8.displayName=P8;var z8="MenuRadioItem",F8=y.forwardRef((e,t)=>{const{value:n,...a}=e,r=kfe(z8,e.__scopeMenu),i=n===r.value;return f.jsx(B8,{scope:e.__scopeMenu,checked:i,children:f.jsx(Gy,{role:"menuitemradio","aria-checked":i,...a,ref:t,"data-state":GN(i),onSelect:Ge(a.onSelect,()=>r.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});F8.displayName=z8;var VN="MenuItemIndicator",[B8,Tfe]=nc(VN,{checked:!1}),H8=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:a,...r}=e,i=Tfe(VN,n);return f.jsx(Ua,{present:a||Cv(i.checked)||i.checked===!0,children:f.jsx(Et.span,{...r,ref:t,"data-state":GN(i.checked)})})});H8.displayName=VN;var Nfe="MenuSeparator",V8=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(Et.div,{role:"separator","aria-orientation":"horizontal",...a,ref:t})});V8.displayName=Nfe;var Cfe="MenuArrow",G8=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Vy(n);return f.jsx(Fy,{...r,...a,ref:t})});G8.displayName=Cfe;var Rfe="MenuSub",[eNe,W8]=nc(Rfe),np="MenuSubTrigger",K8=y.forwardRef((e,t)=>{const n=rc(np,e.__scopeMenu),a=jm(np,e.__scopeMenu),r=W8(np,e.__scopeMenu),i=FN(np,e.__scopeMenu),s=y.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},m=y.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return y.useEffect(()=>m,[m]),y.useEffect(()=>{const h=c.current;return()=>{window.clearTimeout(h),u(null)}},[c,u]),f.jsx(UN,{asChild:!0,...d,children:f.jsx(L8,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":r.contentId,"data-state":q8(n.open),...e,ref:Ki(t,r.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ge(e.onPointerMove,Fp(h=>{i.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:Ge(e.onPointerLeave,Fp(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const v=n.content?.dataset.side,x=v==="right",S=x?-5:5,w=g[x?"left":"right"],E=g[x?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+S,y:h.clientY},{x:w,y:g.top},{x:E,y:g.top},{x:E,y:g.bottom},{x:w,y:g.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Ge(e.onKeyDown,h=>{const g=i.searchRef.current!=="";e.disabled||g&&h.key===" "||cfe[a.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});K8.displayName=np;var Z8="MenuSubContent",Y8=y.forwardRef((e,t)=>{const n=O8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu),c=W8(Z8,e.__scopeMenu),u=y.useRef(null),d=Jt(t,u);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:f.jsx(BN,{id:c.contentId,"aria-labelledby":c.triggerId,...r,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{s.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Ge(e.onFocusOutside,m=>{m.target!==c.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Ge(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:Ge(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=ufe[s.dir].includes(m.key);h&&g&&(i.onOpenChange(!1),c.trigger?.focus(),m.preventDefault())})})})})})});Y8.displayName=Z8;function q8(e){return e?"open":"closed"}function Cv(e){return e==="indeterminate"}function GN(e){return Cv(e)?"indeterminate":e?"checked":"unchecked"}function Afe(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Ife(e,t){return e.map((n,a)=>e[(t+a)%e.length])}function Ofe(e,t,n){const r=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=Ife(e,Math.max(i,0));r.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(r.toLowerCase()));return u!==n?u:void 0}function Dfe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function jfe(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Dfe(n,t)}function Fp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var $fe=I8,Lfe=UN,Mfe=D8,Pfe=j8,Ufe=HN,zfe=$8,Ffe=Gy,Bfe=M8,Hfe=U8,Vfe=F8,Gfe=H8,Wfe=V8,Kfe=G8,Zfe=K8,Yfe=Y8,Wy="DropdownMenu",[qfe]=Ii(Wy,[R8]),ia=R8(),[Xfe,X8]=qfe(Wy),J8=e=>{const{__scopeDropdownMenu:t,children:n,dir:a,open:r,defaultOpen:i,onOpenChange:s,modal:c=!0}=e,u=ia(t),d=y.useRef(null),[m,h]=Po({prop:r,defaultProp:i??!1,onChange:s,caller:Wy});return f.jsx(Xfe,{scope:t,triggerId:$r(),triggerRef:d,contentId:$r(),open:m,onOpenChange:h,onOpenToggle:y.useCallback(()=>h(g=>!g),[h]),modal:c,children:f.jsx($fe,{...u,open:m,onOpenChange:h,dir:a,modal:c,children:n})})};J8.displayName=Wy;var Q8="DropdownMenuTrigger",eG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:a=!1,...r}=e,i=X8(Q8,n),s=ia(n);return f.jsx(Lfe,{asChild:!0,...s,children:f.jsx(Et.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":a?"":void 0,disabled:a,...r,ref:Ki(t,i.triggerRef),onPointerDown:Ge(e.onPointerDown,c=>{!a&&c.button===0&&c.ctrlKey===!1&&(i.onOpenToggle(),i.open||c.preventDefault())}),onKeyDown:Ge(e.onKeyDown,c=>{a||(["Enter"," "].includes(c.key)&&i.onOpenToggle(),c.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});eG.displayName=Q8;var Jfe="DropdownMenuPortal",tG=e=>{const{__scopeDropdownMenu:t,...n}=e,a=ia(t);return f.jsx(Mfe,{...a,...n})};tG.displayName=Jfe;var nG="DropdownMenuContent",rG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=X8(nG,n),i=ia(n),s=y.useRef(!1);return f.jsx(Pfe,{id:r.contentId,"aria-labelledby":r.triggerId,...i,...a,ref:t,onCloseAutoFocus:Ge(e.onCloseAutoFocus,c=>{s.current||r.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:Ge(e.onInteractOutside,c=>{const u=c.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,m=u.button===2||d;(!r.modal||m)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});rG.displayName=nG;var Qfe="DropdownMenuGroup",epe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ufe,{...r,...a,ref:t})});epe.displayName=Qfe;var tpe="DropdownMenuLabel",aG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(zfe,{...r,...a,ref:t})});aG.displayName=tpe;var npe="DropdownMenuItem",iG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ffe,{...r,...a,ref:t})});iG.displayName=npe;var rpe="DropdownMenuCheckboxItem",oG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Bfe,{...r,...a,ref:t})});oG.displayName=rpe;var ape="DropdownMenuRadioGroup",ipe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Hfe,{...r,...a,ref:t})});ipe.displayName=ape;var ope="DropdownMenuRadioItem",sG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Vfe,{...r,...a,ref:t})});sG.displayName=ope;var spe="DropdownMenuItemIndicator",lpe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Gfe,{...r,...a,ref:t})});lpe.displayName=spe;var cpe="DropdownMenuSeparator",lG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Wfe,{...r,...a,ref:t})});lG.displayName=cpe;var upe="DropdownMenuArrow",dpe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Kfe,{...r,...a,ref:t})});dpe.displayName=upe;var fpe="DropdownMenuSubTrigger",cG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Zfe,{...r,...a,ref:t})});cG.displayName=fpe;var ppe="DropdownMenuSubContent",uG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Yfe,{...r,...a,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});uG.displayName=ppe;var mpe=J8,hpe=eG,gpe=tG,dG=rG,fG=aG,pG=iG,bpe=oG,vpe=sG,mG=lG,ype=cG,wpe=uG;const G_=mpe,W_=hpe;ype.displayName;wpe.displayName;function Rv({ref:e,className:t,sideOffset:n=4,...a}){return f.jsx(gpe,{children:f.jsx(dG,{ref:e,sideOffset:n,className:De("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})}Rv.displayName=dG.displayName;function Ao({ref:e,className:t,inset:n,...a}){return f.jsx(pG,{ref:e,className:De("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",t),...a})}Ao.displayName=pG.displayName;bpe.displayName;vpe.displayName;function K_({ref:e,className:t,inset:n,...a}){return f.jsx(fG,{ref:e,className:De("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...a})}K_.displayName=fG.displayName;function rp({ref:e,className:t,...n}){return f.jsx(mG,{ref:e,className:De("-mx-1 my-1 h-px bg-muted",t),...n})}rp.displayName=mG.displayName;var Spe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Wo=Spe.reduce((e,t)=>{const n=E9(`Primitive.${t}`),a=y.forwardRef((r,i)=>{const{asChild:s,...c}=r,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),f.jsx(u,{...c,ref:i})});return a.displayName=`Primitive.${t}`,{...e,[t]:a}},{}),xpe="Label",hG=y.forwardRef((e,t)=>f.jsx(Wo.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));hG.displayName=xpe;var _pe=hG;function Kt({className:e,...t}){return f.jsx(_pe,{"data-slot":"label",className:De("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Md({message:e,className:t="",vertical:n,noBorder:a}){return f.jsx("div",{className:De(`mt-2 rounded-md p-6 ${t}`,!a&&"border"),children:f.jsxs("p",{className:De("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[f.jsx("svg",{width:"40",height:"40",viewBox:"0 0 273 273",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:"flex-shrink-0",children:f.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:f.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[f.jsx("path",{d:"M49.953025,-2.10854389 C63.26892,-2.21867124 76.6185256,2.70621155 86.9019463,12.6653164 L86.9019463,12.6653164 L87.505627,13.2592944 C97.5154947,23.2654892 102.640454,36.3074513 102.880738,49.4222247 C103.08932,77.4533067 113.877287,105.391753 135.242867,126.757333 C156.613383,148.127849 184.559216,158.914875 212.568138,159.119313 L212.568138,159.119313 L213.212264,159.134159 C225.843948,159.517566 238.363557,164.434972 248.121998,173.886137 L248.121998,173.886137 L248.725621,174.480088 C258.982114,184.732164 264.11035,198.171134 264.11035,211.6101 C264.11035,225.04592 258.984514,238.481745 248.732867,248.732867 C238.592792,258.872942 225.336706,263.997882 212.046872,264.107794 C198.731075,264.21792 185.381569,259.293085 175.098248,249.334078 L175.098248,249.334078 L174.494602,248.740134 C163.75802,238.008189 158.640853,223.784027 159.143413,209.719372 C158.258245,182.640933 147.489786,155.83332 126.828333,135.171867 C106.351297,114.694831 79.8363505,103.934873 53.0237258,102.891841 L53.0237258,102.891841 L52.2811438,102.865674 C38.4791718,103.347421 24.5325234,98.4328111 13.8776628,88.1140866 L13.8776628,88.1140866 L13.2739843,87.5201168 C3.12895117,77.3789607 -1.9984796,64.1195994 -2.10841888,50.8264755 C-2.21854669,37.5105567 2.70635908,24.1609269 12.6655135,13.8774565 L12.6655135,13.8774565 L13.2594878,13.2737797 C23.4005926,3.12880025 36.659927,-1.99860507 49.953025,-2.10854389 Z"}),f.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),f.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function gG({className:e,color:t,children:n,grayscaled:a=!1}){const r=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return a?0:.2},[t,a]),i=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return a?.3:.4},[t,a]),s=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[2]||"0")}return Math.floor(Math.random()*360)},[t]),c=y.useMemo(()=>t||`oklch(${Math.min(i,1)} ${r} ${s})`,[s,r,i]),u=y.useMemo(()=>`oklch(${Math.min(i*2,1)} ${r} ${s})`,[s,r,i,t]),d=y.useMemo(()=>Math.floor(Math.random()*360),[s]),m=y.useMemo(()=>"1000%",[]);return f.jsx("section",{className:De("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:f.jsxs("div",{className:"isolate relative w-full h-full",children:[f.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${d}deg, ${c}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&f.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}function WN(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ky="Switch",[Epe]=Ii(Ky),[kpe,Tpe]=Epe(Ky),bG=y.forwardRef((e,t)=>{const{__scopeSwitch:n,name:a,checked:r,defaultChecked:i,required:s,disabled:c,value:u="on",onCheckedChange:d,form:m,...h}=e,[g,v]=y.useState(null),x=Jt(t,k=>v(k)),S=y.useRef(!1),w=g?m||!!g.closest("form"):!0,[E,_]=Po({prop:r,defaultProp:i??!1,onChange:d,caller:Ky});return f.jsxs(kpe,{scope:n,checked:E,disabled:c,children:[f.jsx(Et.button,{type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":SG(E),"data-disabled":c?"":void 0,disabled:c,value:u,...h,ref:x,onClick:Ge(e.onClick,k=>{_(C=>!C),w&&(S.current=k.isPropagationStopped(),S.current||k.stopPropagation())})}),w&&f.jsx(wG,{control:g,bubbles:!S.current,name:a,value:u,checked:E,required:s,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});bG.displayName=Ky;var vG="SwitchThumb",yG=y.forwardRef((e,t)=>{const{__scopeSwitch:n,...a}=e,r=Tpe(vG,n);return f.jsx(Et.span,{"data-state":SG(r.checked),"data-disabled":r.disabled?"":void 0,...a,ref:t})});yG.displayName=vG;var Npe="SwitchBubbleInput",wG=y.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:a=!0,...r},i)=>{const s=y.useRef(null),c=Jt(s,i),u=WN(n),d=LN(t);return y.useEffect(()=>{const m=s.current;if(!m)return;const h=window.HTMLInputElement.prototype,v=Object.getOwnPropertyDescriptor(h,"checked").set;if(u!==n&&v){const x=new Event("click",{bubbles:a});v.call(m,n),m.dispatchEvent(x)}},[u,n,a]),f.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...r,tabIndex:-1,ref:c,style:{...r.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});wG.displayName=Npe;function SG(e){return e?"checked":"unchecked"}var xG=bG,Cpe=yG;function Zy({ref:e,className:t,...n}){return f.jsx(xG,{className:De("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...n,ref:e,children:f.jsx(Cpe,{className:De("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})})}Zy.displayName=xG.displayName;var _G=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Rpe="VisuallyHidden",EG=y.forwardRef((e,t)=>f.jsx(Et.span,{...e,ref:t,style:{..._G,...e.style}}));EG.displayName=Rpe;var Ape=EG,[Yy]=Ii("Tooltip",[Zs]),qy=Zs(),kG="TooltipProvider",Ipe=700,Z_="tooltip.open",[Ope,KN]=Yy(kG),TG=e=>{const{__scopeTooltip:t,delayDuration:n=Ipe,skipDelayDuration:a=300,disableHoverableContent:r=!1,children:i}=e,s=y.useRef(!0),c=y.useRef(!1),u=y.useRef(0);return y.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),f.jsx(Ope,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:y.useCallback(()=>{window.clearTimeout(u.current),s.current=!1},[]),onClose:y.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>s.current=!0,a)},[a]),isPointerInTransitRef:c,onPointerInTransitChange:y.useCallback(d=>{c.current=d},[]),disableHoverableContent:r,children:i})};TG.displayName=kG;var Bp="Tooltip",[Dpe,$m]=Yy(Bp),NG=e=>{const{__scopeTooltip:t,children:n,open:a,defaultOpen:r,onOpenChange:i,disableHoverableContent:s,delayDuration:c}=e,u=KN(Bp,e.__scopeTooltip),d=qy(t),[m,h]=y.useState(null),g=$r(),v=y.useRef(0),x=s??u.disableHoverableContent,S=c??u.delayDuration,w=y.useRef(!1),[E,_]=Po({prop:a,defaultProp:r??!1,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(Z_))):u.onClose(),i?.(A)},caller:Bp}),k=y.useMemo(()=>E?w.current?"delayed-open":"instant-open":"closed",[E]),C=y.useCallback(()=>{window.clearTimeout(v.current),v.current=0,w.current=!1,_(!0)},[_]),R=y.useCallback(()=>{window.clearTimeout(v.current),v.current=0,_(!1)},[_]),I=y.useCallback(()=>{window.clearTimeout(v.current),v.current=window.setTimeout(()=>{w.current=!0,_(!0),v.current=0},S)},[S,_]);return y.useEffect(()=>()=>{v.current&&(window.clearTimeout(v.current),v.current=0)},[]),f.jsx(Uy,{...d,children:f.jsx(Dpe,{scope:t,contentId:g,open:E,stateAttribute:k,trigger:m,onTriggerChange:h,onTriggerEnter:y.useCallback(()=>{u.isOpenDelayedRef.current?I():C()},[u.isOpenDelayedRef,I,C]),onTriggerLeave:y.useCallback(()=>{x?R():(window.clearTimeout(v.current),v.current=0)},[R,x]),onOpen:C,onClose:R,disableHoverableContent:x,children:n})})};NG.displayName=Bp;var Y_="TooltipTrigger",CG=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=$m(Y_,n),i=KN(Y_,n),s=qy(n),c=y.useRef(null),u=Jt(t,c,r.onTriggerChange),d=y.useRef(!1),m=y.useRef(!1),h=y.useCallback(()=>d.current=!1,[]);return y.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),f.jsx(Am,{asChild:!0,...s,children:f.jsx(Et.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...a,ref:u,onPointerMove:Ge(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(r.onTriggerEnter(),m.current=!0)}),onPointerLeave:Ge(e.onPointerLeave,()=>{r.onTriggerLeave(),m.current=!1}),onPointerDown:Ge(e.onPointerDown,()=>{r.open&&r.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:Ge(e.onFocus,()=>{d.current||r.onOpen()}),onBlur:Ge(e.onBlur,r.onClose),onClick:Ge(e.onClick,r.onClose)})})});CG.displayName=Y_;var ZN="TooltipPortal",[jpe,$pe]=Yy(ZN,{forceMount:void 0}),RG=e=>{const{__scopeTooltip:t,forceMount:n,children:a,container:r}=e,i=$m(ZN,t);return f.jsx(jpe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};RG.displayName=ZN;var dd="TooltipContent",AG=y.forwardRef((e,t)=>{const n=$pe(dd,e.__scopeTooltip),{forceMount:a=n.forceMount,side:r="top",...i}=e,s=$m(dd,e.__scopeTooltip);return f.jsx(Ua,{present:a||s.open,children:s.disableHoverableContent?f.jsx(IG,{side:r,...i,ref:t}):f.jsx(Lpe,{side:r,...i,ref:t})})}),Lpe=y.forwardRef((e,t)=>{const n=$m(dd,e.__scopeTooltip),a=KN(dd,e.__scopeTooltip),r=y.useRef(null),i=Jt(t,r),[s,c]=y.useState(null),{trigger:u,onClose:d}=n,m=r.current,{onPointerInTransitChange:h}=a,g=y.useCallback(()=>{c(null),h(!1)},[h]),v=y.useCallback((x,S)=>{const w=x.currentTarget,E={x:x.clientX,y:x.clientY},_=zpe(E,w.getBoundingClientRect()),k=Fpe(E,_),C=Bpe(S.getBoundingClientRect()),R=Vpe([...k,...C]);c(R),h(!0)},[h]);return y.useEffect(()=>()=>g(),[g]),y.useEffect(()=>{if(u&&m){const x=w=>v(w,m),S=w=>v(w,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",S)}}},[u,m,v,g]),y.useEffect(()=>{if(s){const x=S=>{const w=S.target,E={x:S.clientX,y:S.clientY},_=u?.contains(w)||m?.contains(w),k=!Hpe(E,s);_?g():k&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,s,d,g]),f.jsx(IG,{...e,ref:i})}),[Mpe,Ppe]=Yy(Bp,{isInside:!1}),Upe=yce("TooltipContent"),IG=y.forwardRef((e,t)=>{const{__scopeTooltip:n,children:a,"aria-label":r,onEscapeKeyDown:i,onPointerDownOutside:s,...c}=e,u=$m(dd,n),d=qy(n),{onClose:m}=u;return y.useEffect(()=>(document.addEventListener(Z_,m),()=>document.removeEventListener(Z_,m)),[m]),y.useEffect(()=>{if(u.trigger){const h=g=>{g.target?.contains(u.trigger)&&m()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[u.trigger,m]),f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:f.jsxs(zy,{"data-state":u.stateAttribute,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[f.jsx(Upe,{children:a}),f.jsx(Mpe,{scope:n,isInside:!0,children:f.jsx(Ape,{id:u.contentId,role:"tooltip",children:r||a})})]})})});AG.displayName=dd;var OG="TooltipArrow",DG=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=qy(n);return Ppe(OG,n).isInside?null:f.jsx(Fy,{...r,...a,ref:t})});DG.displayName=OG;function zpe(e,t){const n=Math.abs(t.top-e.y),a=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,a,r,i)){case i:return"left";case r:return"right";case n:return"top";case a:return"bottom";default:throw new Error("unreachable")}}function Fpe(e,t,n=5){const a=[];switch(t){case"top":a.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":a.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":a.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":a.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return a}function Bpe(e){const{top:t,right:n,bottom:a,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:a},{x:r,y:a}]}function Hpe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function Vpe(e){const t=e.slice();return t.sort((n,a)=>n.x<a.x?-1:n.x>a.x?1:n.y<a.y?-1:n.y>a.y?1:0),Gpe(t)}function Gpe(e){if(e.length<=1)return e.slice();const t=[];for(let a=0;a<e.length;a++){const r=e[a];for(;t.length>=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let a=e.length-1;a>=0;a--){const r=e[a];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Wpe=TG,Kpe=NG,Zpe=CG,Ype=RG,qpe=AG,Xpe=DG;function YN({delayDuration:e=0,...t}){return f.jsx(Wpe,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Nt({...e}){return f.jsx(YN,{children:f.jsx(Kpe,{"data-slot":"tooltip",...e})})}function Ct({...e}){return f.jsx(Zpe,{"data-slot":"tooltip-trigger",...e})}function Rt({className:e,sideOffset:t=0,children:n,...a}){return f.jsx(Ype,{children:f.jsxs(qpe,{"data-slot":"tooltip-content",sideOffset:t,className:De("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...a,children:[n,f.jsx(Xpe,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class Jpe{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class XU{name="mcp_tool_execution";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId,success:t.success,duration:t.duration,error:t.error}}}class JU{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class QU{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class ez{name="mcp_chat_message";properties;constructor(t){this.properties={server_id:t.serverId,provider:t.provider,model:t.model,message_count:t.messageCount,tool_calls_count:t.toolCallsCount,success:t.success,execution_mode:t.executionMode,duration:t.duration,error:t.error}}}class Qpe{name="mcp_server_added";properties;constructor(t){this.properties={server_id:t.serverId,server_url:t.serverUrl,connection_type:t.connectionType,via_proxy:t.viaProxy}}}class eme{name="mcp_server_removed";properties;constructor(t){this.properties={server_id:t.serverId}}}class tme{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class nme{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function Sx(){try{return"0.13.2-canary.0"}catch{return"0.0.0"}}var rme={};function xx(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class tz{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch{}}}function ws(e){return`mcp_inspector_telemetry_${e}`}class yr{static instance=null;POSTHOG_PROXY_URL="/inspector/api/tel/posthog";SCARF_PROXY_URL="/inspector/api/tel/scarf";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="inspector";constructor(){const t=xx(),n=this.isTelemetryDisabled();if(this._source=this.getStoredSource()||"inspector",n)this._posthogClient=null,this._scarfClient=null;else if(!t)this._posthogClient=null,this._scarfClient=null;else{try{this._posthogClient=new tz(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new tz(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(ws("disabled"))==="true"||typeof process<"u"&&rme?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(ws("source")):null}static getInstance(){return yr.instance||(yr.instance=new yr),yr.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(ws("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!xx())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(ws("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(ws("user_id"),n),this._currUserId=n}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(()=>{})}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}generateUserId(){const t=window.crypto;if(t){const n=new Uint8Array(16);t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;const a=Array.from(n).map(r=>r.toString(16).padStart(2,"0")).join("");return a.slice(0,8)+"-"+a.slice(8,12)+"-"+a.slice(12,16)+"-"+a.slice(16,20)+"-"+a.slice(20,32)}else return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=Math.random()*16|0;return(n==="x"?a:a&3|8).toString(16)})}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={event:t.name,user_id:this.userId,properties:{...t.properties,mcp_use_version:Sx(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=Sx(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,n.package="inspector",await this._scarfClient.logEvent(n)}catch{}}}async trackPackageDownload(t){if(this._scarfClient&&xx())try{const n=Sx();let a=!1,r=!1;const i=localStorage.getItem(ws("download_version"));if(i?n>i&&(a=!0,r=!1,localStorage.setItem(ws("download_version"),n)):(a=!0,r=!0,localStorage.setItem(ws("download_version"),n)),a){const s={...t||{}};s.mcp_use_version=n,s.user_id=this.userId,s.event="package_download",s.first_download=r,s.language="typescript",s.source=this._source,s.package="inspector",await this._scarfClient.logEvent(s)}}catch{}}async trackInspectorOpen(t){const n=new Jpe(t);await this.capture(n)}}const ame={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function ime({requestId:e,serverName:t,onViewDetails:n,onApprove:a,onDeny:r}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Sampling Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),n()},children:"View Details"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),a(ame)},children:"Approve"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),r()},children:"Deny"})]})]})}function ome({requestId:e,serverName:t,mode:n,message:a,url:r,onViewDetails:i,onOpenUrl:s,onCancel:c}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Elicitation Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["From ",t,": ",a]}),n==="url"&&r&&f.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono",children:r})]}),f.jsxs("div",{className:"flex gap-2 flex-wrap",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),i()},children:"View Details"}),n==="url"&&s&&f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),s()},children:"Open URL"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),c()},children:"Cancel"})]})]})}const cb=()=>{},ub=()=>{},db=()=>{},fb=()=>{},jG=y.createContext(null);function qN(){const e=y.use(jG);if(!e)throw new Error("useMcpContext must be used within a McpProvider");return e}function sme({url:e,name:t,proxyConfig:n,transportType:a,connectionId:r,onUpdate:i,onRemove:s}){const c=typeof window<"u"?new URL("/inspector/oauth/callback",window.location.origin).toString():"/inspector/oauth/callback";let u=e,d={};if(n?.proxyAddress){const $=new URL(n.proxyAddress),L=new URL(e);u=`${$.origin}${$.pathname}${L.pathname}${L.search}`,d["X-Target-URL"]=e}n?.customHeaders&&(d={...d,...n.customHeaders});const[m,h]=y.useState([]),g=y.useRef(0),[v,x]=y.useState([]),S=y.useRef(0),w=y.useMemo(()=>m.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[m]),E=y.useMemo(()=>v.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[v]),_=y.useRef(null),[k,C]=y.useState(!1),R=y.useRef(!1);y.useEffect(()=>{typeof window<"u"&&!R.current&&(R.current=!0,Jn(()=>import("./transport-wrapper-browser-BI4dDu3b.js"),[]).then($=>{_.current=$.wrapTransportForLogging,C(!0),console.log("[McpContext] Transport wrapper loaded")}).catch($=>{console.error("[McpContext] Failed to load transport wrapper:",$)}))},[]);const I=y.useMemo(()=>{if(!(!k||!_.current))return($,L)=>{const F=r;return console.log("[McpContext] Applying transport wrapper, serverId:",F,"from connector:",L),_.current($,F)}},[k,r]),A=`mcp-inspector-notifications-${r}`,O=500,[M,P]=y.useState([]);y.useEffect(()=>{try{const $=localStorage.getItem(A);if($){const L=JSON.parse($);Array.isArray(L)&&P(L)}}catch($){console.error("Failed to load notifications from localStorage:",$)}},[A]),y.useEffect(()=>{try{localStorage.setItem(A,JSON.stringify(M))}catch($){console.error("Failed to save notifications to localStorage:",$)}},[M,A]);const B=y.useCallback($=>{P(L=>L.map(F=>F.id===$?{...F,read:!0}:F))},[]),K=y.useCallback(()=>{P($=>$.map(L=>({...L,read:!0})))},[]),Q=y.useCallback(()=>{P([])},[]),ee=y.useCallback($=>{P(L=>{const F=[$,...L];return F.length>O?F.slice(0,O):F})},[]),ae=y.useCallback(($,L)=>{h(F=>{const W=F.find(ne=>ne.id===$);return W?(W.resolve(L),F.filter(ne=>ne.id!==$)):F})},[]),H=y.useCallback(($,L)=>{h(F=>{const W=F.find(ne=>ne.id===$);return W?(W.reject(new Error(L||"User rejected sampling request")),F.filter(ne=>ne.id!==$)):F})},[]),Z=y.useCallback(($,L)=>{x(F=>{const W=F.find(ne=>ne.id===$);return W?(W.resolve(L),F.filter(ne=>ne.id!==$)):F})},[]),G=y.useCallback(($,L)=>{x(F=>{const W=F.find(ne=>ne.id===$);return W?(W.reject(new Error(L||"User rejected elicitation request")),F.filter(ne=>ne.id!==$)):F})},[]),re=y.useCallback(async $=>new Promise((L,F)=>{const W=`sampling-${g.current++}`,ne={id:W,request:{params:$},timestamp:Date.now(),serverName:t,resolve:L,reject:F};h(le=>[...le,ne]),typeof window<"u"&&Jn(async()=>{const{toast:le}=await Promise.resolve().then(()=>lz);return{toast:le}},void 0).then(({toast:le})=>{const ue=le(f.jsx(ime,{requestId:W,serverName:t,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-sampling",{detail:{requestId:W}});window.dispatchEvent(X),le.dismiss(ue)},onApprove:X=>{h(q=>{const oe=q.find(me=>me.id===W);return oe?(oe.resolve(X),le.success("Sampling request approved"),q.filter(me=>me.id!==W)):q}),le.dismiss(ue)},onDeny:()=>{h(X=>{const q=X.find(oe=>oe.id===W);return q?(q.reject(new Error("User denied sampling request from toast")),le.error("Sampling request denied"),X.filter(oe=>oe.id!==W)):X}),le.dismiss(ue)}}),{duration:5e3})})}),[t]),te=y.useCallback(async $=>new Promise((L,F)=>{const W=`elicitation-${S.current++}`,ne={id:W,request:$,timestamp:Date.now(),serverName:t,resolve:L,reject:F};x(le=>[...le,ne]),typeof window<"u"&&Jn(async()=>{const{toast:le}=await Promise.resolve().then(()=>lz);return{toast:le}},void 0).then(({toast:le})=>{const ue=le(f.jsx(ome,{requestId:W,serverName:t,mode:$.mode||"form",message:$.message,url:$.mode==="url"?$.url:void 0,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-elicitation",{detail:{requestId:W}});window.dispatchEvent(X),le.dismiss(ue)},onOpenUrl:$.mode==="url"?()=>{window.open($.url,"_blank"),le.dismiss(ue)}:void 0,onCancel:()=>{x(X=>{const q=X.find(oe=>oe.id===W);return q?(q.reject(new Error("User cancelled elicitation request from toast")),le.error("Elicitation request cancelled"),X.filter(oe=>oe.id!==W)):X}),le.dismiss(ue)}}),{duration:5e3})})}),[t]),j=SN({url:u,callbackUrl:c,timeout:5e3,customHeaders:Object.keys(d).length>0?d:void 0,transportType:a||"http",preventAutoAuth:!0,useRedirectFlow:!0,enabled:k,wrapTransport:I,onNotification:$=>{ee({id:globalThis.crypto.randomUUID(),method:$.method,params:$.params,timestamp:Date.now(),read:!1})},samplingCallback:re,onElicitation:te}),V=y.useRef(i),z=y.useRef(null);return y.useEffect(()=>{V.current=i},[i]),y.useEffect(()=>{if(typeof queueMicrotask<"u")queueMicrotask(()=>{j.state==="ready"&&j.serverInfo&&console.log("[McpContext] Server info available:",j.serverInfo);const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:Q,pendingSamplingRequests:w,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))});else{const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:Q,pendingSamplingRequests:w,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))}},[e,t,a,n,d,r,j.state,j.tools,j.resources,j.prompts,j.error,j.authUrl,j.serverInfo,j.capabilities,j.client,M,B,K,Q,j.callTool,j.readResource,j.listPrompts,j.getPrompt,j.authenticate,j.retry,j.clearStorage,m,ae,H,E,Z,G]),null}function lme({children:e}){const[t,n]=y.useState([]),[a,r]=y.useState(!1),[i,s]=y.useState(!0),[c,u]=y.useState([]);y.useEffect(()=>{try{const w=localStorage.getItem("mcp-inspector-connections");if(w){const _=JSON.parse(w);Array.isArray(_)&&(u(_),n(_.map(k=>({id:k.id||k.url,url:k.url,name:k.name||"MCP Server",state:"discovering",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:k.proxyConfig?.customHeaders,transportType:k.transportType,proxyConfig:k.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}))))}const E=localStorage.getItem("mcp-inspector-auto-connect");E!==null&&s(E==="true")}catch(w){console.error("Failed to load connections from localStorage:",w)}finally{r(!0)}},[]),y.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-connections",JSON.stringify(c))},[c,a]),y.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-auto-connect",String(i))},[i,a]);const d=y.useCallback((w,E,_,k)=>{const C=c.find(A=>A.url===w),R=t.find(A=>A.url===w);if(C&&R){if(JSON.stringify(C.proxyConfig)!==JSON.stringify(_)&&_){u(O=>O.filter(M=>M.url!==w)),n(O=>O.filter(M=>M.url!==w)),setTimeout(()=>{const O={id:w,url:w,name:E||C.name||"MCP Server",proxyConfig:_,transportType:k||C.transportType};u(M=>[...M,O]),n(M=>[...M,{id:w,url:w,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k||C.transportType,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},10);return}return}if(C&&!R){(_||k)&&u(A=>A.map(O=>O.url===w?{...O,proxyConfig:_||O.proxyConfig,transportType:k||O.transportType,name:E||O.name}:O)),n(A=>[...A,{id:C.id||w,url:w,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders||C.proxyConfig?.customHeaders,transportType:k||C.transportType,proxyConfig:_||C.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}]);return}const I={id:w,url:w,name:E||"MCP Server",proxyConfig:_,transportType:k};u(A=>[...A,I]),n(A=>[...A,{id:w,url:w,name:E||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},[c,t]),m=y.useCallback(w=>{const E=t.find(k=>k.id===w);E&&(console.log(`[McpContext] Cleaning up connection: ${w}`),E.disconnect&&(console.log(`[McpContext] Disconnecting from server: ${w}`),E.disconnect()),E.clearStorage&&(console.log(`[McpContext] Clearing OAuth storage for connection: ${w}`),E.clearStorage())),u(k=>k.filter(C=>C.id!==w)),n(k=>k.filter(C=>C.id!==w));const _=localStorage.getItem("mcp-inspector-connections");if(_)try{const C=JSON.parse(_).filter(R=>(R.id||R.url)!==w);localStorage.setItem("mcp-inspector-connections",JSON.stringify(C))}catch(k){console.error("Failed to update localStorage on remove:",k)}yr.getInstance().capture(new eme({serverId:w}))},[t]),h=y.useCallback((w,E)=>{u(_=>_.map(k=>k.id===w||k.url===w?{...k,...E}:k)),n(_=>_.map(k=>k.id===w?{...k,...E}:k))},[]),g=y.useCallback(w=>{n(E=>{const _=E.findIndex(R=>R.id===w.id);if(_===-1)return E;const k=E[_];if(k.state===w.state&&k.tools===w.tools&&k.resources===w.resources&&k.prompts===w.prompts&&k.error===w.error&&k.serverInfo===w.serverInfo&&k.client===w.client&&k.notifications===w.notifications&&k.unreadNotificationCount===w.unreadNotificationCount&&k.pendingSamplingRequests.length===w.pendingSamplingRequests.length&&k.pendingElicitationRequests.length===w.pendingElicitationRequests.length)return E;const C=[...E];return C[_]=w,C})},[]),v=y.useCallback(w=>{console.log("Connect requested for:",w)},[]),x=y.useCallback(w=>{console.log("Disconnect requested for:",w)},[]),S=y.useMemo(()=>({connections:t,addConnection:d,removeConnection:m,updateConnectionConfig:h,autoConnect:i,setAutoConnect:s,connectServer:v,disconnectServer:x,configLoaded:a}),[t,d,m,h,i,v,x,a]);return f.jsxs(jG.Provider,{value:S,children:[e,a&&i&&c.map(w=>{const E=`${w.id||w.url}-${w.proxyConfig?.proxyAddress?"proxy":"direct"}`;return console.warn("[McpContext] Rendering McpConnectionWrapper with key:",E,"proxyConfig:",w.proxyConfig),f.jsx(sme,{url:w.url,name:w.name,proxyConfig:w.proxyConfig,transportType:w.transportType,connectionId:w.id||w.url,onUpdate:g,onRemove:()=>m(w.id||w.url)},E)})]})}const cme=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ume=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),nz=e=>{const t=ume(e);return t.charAt(0).toUpperCase()+t.slice(1)},$G=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),dme=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var fme={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const pme=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:s,...c},u)=>y.createElement("svg",{ref:u,...fme,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:$G("lucide",r),...!i&&!dme(c)&&{"aria-hidden":"true"},...c},[...s.map(([d,m])=>y.createElement(d,m)),...Array.isArray(i)?i:[i]]));const et=(e,t)=>{const n=y.forwardRef(({className:a,...r},i)=>y.createElement(pme,{ref:i,iconNode:t,className:$G(`lucide-${cme(nz(e))}`,`lucide-${e}`,a),...r}));return n.displayName=nz(e),n};const mme=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],hme=et("arrow-down-to-line",mme);const gme=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],bme=et("arrow-up-from-line",gme);const vme=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],yme=et("arrow-up",vme);const wme=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],XN=et("bell",wme);const Sme=[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]],LG=et("brush",Sme);const xme=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],_me=et("bug",xme);const Eme=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ra=et("check",Eme);const kme=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ac=et("chevron-down",kme);const Tme=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Xy=et("chevron-left",Tme);const Nme=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],MG=et("chevron-right",Nme);const Cme=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Rme=et("chevron-up",Cme);const Ame=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],Ime=et("chevrons-up-down",Ame);const Ome=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],rz=et("circle-minus",Ome);const Dme=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fd=et("clock",Dme);const jme=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],JN=et("code",jme);const $me=[["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}]],Lme=et("cog",$me);const Mme=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],Pme=et("command",Mme);const Ume=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Lr=et("copy",Ume);const zme=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Jy=et("database",zme);const Fme=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Lm=et("download",Fme);const Bme=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Hme=et("ellipsis-vertical",Bme);const Vme=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],q_=et("external-link",Vme);const Gme=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],PG=et("eye-off",Gme);const Wme=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],X_=et("eye",Wme);const Kme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Zme=et("file-code",Kme);const Yme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],qme=et("file-image",Yme);const Xme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],QN=et("file-text",Xme);const Jme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Qme=et("file",Jme);const ehe=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],the=et("folder-open",ehe);const nhe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],rhe=et("globe",nhe);const ahe=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],ihe=et("grip-vertical",ahe);const ohe=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],UG=et("hash",ohe);const she=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Av=et("history",she);const lhe=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],zG=et("key",lhe);const che=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],zs=et("loader-circle",che);const uhe=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],eC=et("maximize-2",uhe);const dhe=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],tC=et("maximize",dhe);const fhe=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],phe=et("message-circle",fhe);const mhe=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Hp=et("message-square",mhe);const hhe=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],ghe=et("minimize",hhe);const bhe=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],az=et("monitor",bhe);const vhe=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],yhe=et("moon",vhe);const whe=[["path",{d:"M2 10h6V4",key:"zwrco"}],["path",{d:"m2 4 6 6",key:"ug085t"}],["path",{d:"M21 10V7a2 2 0 0 0-2-2h-7",key:"git5jr"}],["path",{d:"M3 14v2a2 2 0 0 0 2 2h3",key:"1f7fh3"}],["rect",{x:"12",y:"14",width:"10",height:"7",rx:"1",key:"1wjs3o"}]],She=et("picture-in-picture",whe);const xhe=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],FG=et("play",xhe);const _he=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],BG=et("plus",_he);const Ehe=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],iz=et("rotate-ccw",Ehe);const khe=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],nC=et("save",khe);const The=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Pd=et("search",The);const Nhe=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Che=et("send",Nhe);const Rhe=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Ahe=et("server",Rhe);const Ihe=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Eu=et("settings",Ihe);const Ohe=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Dhe=et("shield",Ohe);const jhe=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],$he=et("sparkles",jhe);const Lhe=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],HG=et("square-check-big",Lhe);const Mhe=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],Phe=et("square-pen",Mhe);const Uhe=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]],zhe=et("sun-dim",Uhe);const Fhe=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],_x=et("terminal",Fhe);const Bhe=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Fs=et("trash-2",Bhe);const Hhe=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Vhe=et("trash",Hhe);const Ghe=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Wl=et("wrench",Ghe);const Whe=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ji=et("x",Whe);const Khe=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Vp=et("zap",Khe);function Zhe(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const Yhe=e=>{switch(e){case"success":return Jhe;case"info":return ege;case"warning":return Qhe;case"error":return tge;default:return null}},qhe=Array(12).fill(0),Xhe=({visible:e,className:t})=>ce.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ce.createElement("div",{className:"sonner-spinner"},qhe.map((n,a)=>ce.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${a}`})))),Jhe=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Qhe=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),ege=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),tge=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),nge=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ce.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ce.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),rge=()=>{const[e,t]=ce.useState(document.hidden);return ce.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let J_=1;class age{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:a,...r}=t,i=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:J_++,s=this.toasts.find(u=>u.id===i),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),s?this.toasts=this.toasts.map(u=>u.id===i?(this.publish({...u,...t,id:i,title:a}),{...u,...t,id:i,dismissible:c,title:a}):u):this.addToast({title:a,...r,dismissible:c,id:i}),i},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(a=>a({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let a;n.loading!==void 0&&(a=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const r=Promise.resolve(t instanceof Function?t():t);let i=a!==void 0,s;const c=r.then(async d=>{if(s=["resolve",d],ce.isValidElement(d))i=!1,this.create({id:a,type:"default",message:d});else if(oge(d)&&!d.ok){i=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(d instanceof Error){i=!1;const h=typeof n.error=="function"?await n.error(d):n.error,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(n.success!==void 0){i=!1;const h=typeof n.success=="function"?await n.success(d):n.success,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:a,type:"success",description:g,...x})}}).catch(async d=>{if(s=["reject",d],n.error!==void 0){i=!1;const m=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description,v=typeof m=="object"&&!ce.isValidElement(m)?m:{message:m};this.create({id:a,type:"error",description:h,...v})}}).finally(()=>{i&&(this.dismiss(a),a=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,m)=>c.then(()=>s[0]==="reject"?m(s[1]):d(s[1])).catch(m));return typeof a!="string"&&typeof a!="number"?{unwrap:u}:Object.assign(a,{unwrap:u})},this.custom=(t,n)=>{const a=n?.id||J_++;return this.create({jsx:t(a),id:a,...n}),a},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ga=new age,ige=(e,t)=>{const n=t?.id||J_++;return ga.addToast({title:e,...t,id:n}),n},oge=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",sge=ige,lge=()=>ga.toasts,cge=()=>ga.getActiveToasts(),Xt=Object.assign(sge,{success:ga.success,info:ga.info,warning:ga.warning,error:ga.error,custom:ga.custom,message:ga.message,promise:ga.promise,dismiss:ga.dismiss,loading:ga.loading},{getHistory:lge,getToasts:cge});Zhe("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function pb(e){return e.label!==void 0}const uge=3,dge="24px",fge="16px",oz=4e3,pge=356,mge=14,hge=45,gge=200;function Ui(...e){return e.filter(Boolean).join(" ")}function bge(e){const[t,n]=e.split("-"),a=[];return t&&a.push(t),n&&a.push(n),a}const vge=e=>{var t,n,a,r,i,s,c,u,d;const{invert:m,toast:h,unstyled:g,interacting:v,setHeights:x,visibleToasts:S,heights:w,index:E,toasts:_,expanded:k,removeToast:C,defaultRichColors:R,closeButton:I,style:A,cancelButtonStyle:O,actionButtonStyle:M,className:P="",descriptionClassName:B="",duration:K,position:Q,gap:ee,expandByDefault:ae,classNames:H,icons:Z,closeButtonAriaLabel:G="Close toast"}=e,[re,te]=ce.useState(null),[j,V]=ce.useState(null),[z,$]=ce.useState(!1),[L,F]=ce.useState(!1),[W,ne]=ce.useState(!1),[le,ue]=ce.useState(!1),[X,q]=ce.useState(!1),[oe,me]=ce.useState(0),[ie,Ne]=ce.useState(0),He=ce.useRef(h.duration||K||oz),ye=ce.useRef(null),Se=ce.useRef(null),Pe=E===0,fe=E+1<=S,Ae=h.type,Me=h.dismissible!==!1,_e=h.className||"",rt=h.descriptionClassName||"",nt=ce.useMemo(()=>w.findIndex(Ke=>Ke.toastId===h.id)||0,[w,h.id]),ct=ce.useMemo(()=>{var Ke;return(Ke=h.closeButton)!=null?Ke:I},[h.closeButton,I]),bt=ce.useMemo(()=>h.duration||K||oz,[h.duration,K]),ut=ce.useRef(0),nn=ce.useRef(0),Qn=ce.useRef(0),ot=ce.useRef(null),[Ve,Le]=Q.split("-"),Ee=ce.useMemo(()=>w.reduce((Ke,Ze,mt)=>mt>=nt?Ke:Ke+Ze.height,0),[w,nt]),je=rge(),Fe=h.invert||m,We=Ae==="loading";nn.current=ce.useMemo(()=>nt*ee+Ee,[nt,Ee]),ce.useEffect(()=>{He.current=bt},[bt]),ce.useEffect(()=>{$(!0)},[]),ce.useEffect(()=>{const Ke=Se.current;if(Ke){const Ze=Ke.getBoundingClientRect().height;return Ne(Ze),x(mt=>[{toastId:h.id,height:Ze,position:h.position},...mt]),()=>x(mt=>mt.filter(At=>At.toastId!==h.id))}},[x,h.id]),ce.useLayoutEffect(()=>{if(!z)return;const Ke=Se.current,Ze=Ke.style.height;Ke.style.height="auto";const mt=Ke.getBoundingClientRect().height;Ke.style.height=Ze,Ne(mt),x(At=>At.find(cn=>cn.toastId===h.id)?At.map(cn=>cn.toastId===h.id?{...cn,height:mt}:cn):[{toastId:h.id,height:mt,position:h.position},...At])},[z,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const Je=ce.useCallback(()=>{F(!0),me(nn.current),x(Ke=>Ke.filter(Ze=>Ze.toastId!==h.id)),setTimeout(()=>{C(h)},gge)},[h,C,x,nn]);ce.useEffect(()=>{if(h.promise&&Ae==="loading"||h.duration===1/0||h.type==="loading")return;let Ke;return k||v||je?(()=>{if(Qn.current<ut.current){const At=new Date().getTime()-ut.current;He.current=He.current-At}Qn.current=new Date().getTime()})():He.current!==1/0&&(ut.current=new Date().getTime(),Ke=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),Je()},He.current)),()=>clearTimeout(Ke)},[k,v,h,Ae,je,Je]),ce.useEffect(()=>{h.delete&&(Je(),h.onDismiss==null||h.onDismiss.call(h,h))},[Je,h.delete]);function St(){var Ke;if(Z?.loading){var Ze;return ce.createElement("div",{className:Ui(H?.loader,h==null||(Ze=h.classNames)==null?void 0:Ze.loader,"sonner-loader"),"data-visible":Ae==="loading"},Z.loading)}return ce.createElement(Xhe,{className:Ui(H?.loader,h==null||(Ke=h.classNames)==null?void 0:Ke.loader),visible:Ae==="loading"})}const ht=h.icon||Z?.[Ae]||Yhe(Ae);var Mt,rn;return ce.createElement("li",{tabIndex:0,ref:Se,className:Ui(P,_e,H?.toast,h==null||(t=h.classNames)==null?void 0:t.toast,H?.default,H?.[Ae],h==null||(n=h.classNames)==null?void 0:n[Ae]),"data-sonner-toast":"","data-rich-colors":(Mt=h.richColors)!=null?Mt:R,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":z,"data-promise":!!h.promise,"data-swiped":X,"data-removed":L,"data-visible":fe,"data-y-position":Ve,"data-x-position":Le,"data-index":E,"data-front":Pe,"data-swiping":W,"data-dismissible":Me,"data-type":Ae,"data-invert":Fe,"data-swipe-out":le,"data-swipe-direction":j,"data-expanded":!!(k||ae&&z),"data-testid":h.testId,style:{"--index":E,"--toasts-before":E,"--z-index":_.length-E,"--offset":`${L?oe:nn.current}px`,"--initial-height":ae?"auto":`${ie}px`,...A,...h.style},onDragEnd:()=>{ne(!1),te(null),ot.current=null},onPointerDown:Ke=>{Ke.button!==2&&(We||!Me||(ye.current=new Date,me(nn.current),Ke.target.setPointerCapture(Ke.pointerId),Ke.target.tagName!=="BUTTON"&&(ne(!0),ot.current={x:Ke.clientX,y:Ke.clientY})))},onPointerUp:()=>{var Ke,Ze,mt;if(le||!Me)return;ot.current=null;const At=Number(((Ke=Se.current)==null?void 0:Ke.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),er=Number(((Ze=Se.current)==null?void 0:Ze.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),cn=new Date().getTime()-((mt=ye.current)==null?void 0:mt.getTime()),Vn=re==="x"?At:er,$n=Math.abs(Vn)/cn;if(Math.abs(Vn)>=hge||$n>.11){me(nn.current),h.onDismiss==null||h.onDismiss.call(h,h),V(re==="x"?At>0?"right":"left":er>0?"down":"up"),Je(),ue(!0);return}else{var yn,pn;(yn=Se.current)==null||yn.style.setProperty("--swipe-amount-x","0px"),(pn=Se.current)==null||pn.style.setProperty("--swipe-amount-y","0px")}q(!1),ne(!1),te(null)},onPointerMove:Ke=>{var Ze,mt,At;if(!ot.current||!Me||((Ze=window.getSelection())==null?void 0:Ze.toString().length)>0)return;const cn=Ke.clientY-ot.current.y,Vn=Ke.clientX-ot.current.x;var $n;const yn=($n=e.swipeDirections)!=null?$n:bge(Q);!re&&(Math.abs(Vn)>1||Math.abs(cn)>1)&&te(Math.abs(Vn)>Math.abs(cn)?"x":"y");let pn={x:0,y:0};const oa=Qt=>1/(1.5+Math.abs(Qt)/20);if(re==="y"){if(yn.includes("top")||yn.includes("bottom"))if(yn.includes("top")&&cn<0||yn.includes("bottom")&&cn>0)pn.y=cn;else{const Qt=cn*oa(cn);pn.y=Math.abs(Qt)<Math.abs(cn)?Qt:cn}}else if(re==="x"&&(yn.includes("left")||yn.includes("right")))if(yn.includes("left")&&Vn<0||yn.includes("right")&&Vn>0)pn.x=Vn;else{const Qt=Vn*oa(Vn);pn.x=Math.abs(Qt)<Math.abs(Vn)?Qt:Vn}(Math.abs(pn.x)>0||Math.abs(pn.y)>0)&&q(!0),(mt=Se.current)==null||mt.style.setProperty("--swipe-amount-x",`${pn.x}px`),(At=Se.current)==null||At.style.setProperty("--swipe-amount-y",`${pn.y}px`)}},ct&&!h.jsx&&Ae!=="loading"?ce.createElement("button",{"aria-label":G,"data-disabled":We,"data-close-button":!0,onClick:We||!Me?()=>{}:()=>{Je(),h.onDismiss==null||h.onDismiss.call(h,h)},className:Ui(H?.closeButton,h==null||(a=h.classNames)==null?void 0:a.closeButton)},(rn=Z?.close)!=null?rn:nge):null,(Ae||h.icon||h.promise)&&h.icon!==null&&(Z?.[Ae]!==null||h.icon)?ce.createElement("div",{"data-icon":"",className:Ui(H?.icon,h==null||(r=h.classNames)==null?void 0:r.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||St():null,h.type!=="loading"?ht:null):null,ce.createElement("div",{"data-content":"",className:Ui(H?.content,h==null||(i=h.classNames)==null?void 0:i.content)},ce.createElement("div",{"data-title":"",className:Ui(H?.title,h==null||(s=h.classNames)==null?void 0:s.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?ce.createElement("div",{"data-description":"",className:Ui(B,rt,H?.description,h==null||(c=h.classNames)==null?void 0:c.description)},typeof h.description=="function"?h.description():h.description):null),ce.isValidElement(h.cancel)?h.cancel:h.cancel&&pb(h.cancel)?ce.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||O,onClick:Ke=>{pb(h.cancel)&&Me&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,Ke),Je())},className:Ui(H?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,ce.isValidElement(h.action)?h.action:h.action&&pb(h.action)?ce.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||M,onClick:Ke=>{pb(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,Ke),!Ke.defaultPrevented&&Je())},className:Ui(H?.actionButton,h==null||(d=h.classNames)==null?void 0:d.actionButton)},h.action.label):null)};function sz(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function yge(e,t){const n={};return[e,t].forEach((a,r)=>{const i=r===1,s=i?"--mobile-offset":"--offset",c=i?fge:dge;function u(d){["top","right","bottom","left"].forEach(m=>{n[`${s}-${m}`]=typeof d=="number"?`${d}px`:d})}typeof a=="number"||typeof a=="string"?u(a):typeof a=="object"?["top","right","bottom","left"].forEach(d=>{a[d]===void 0?n[`${s}-${d}`]=c:n[`${s}-${d}`]=typeof a[d]=="number"?`${a[d]}px`:a[d]}):u(c)}),n}const VG=ce.forwardRef(function(t,n){const{id:a,invert:r,position:i="bottom-right",hotkey:s=["altKey","KeyT"],expand:c,closeButton:u,className:d,offset:m,mobileOffset:h,theme:g="light",richColors:v,duration:x,style:S,visibleToasts:w=uge,toastOptions:E,dir:_=sz(),gap:k=mge,icons:C,containerAriaLabel:R="Notifications"}=t,[I,A]=ce.useState([]),O=ce.useMemo(()=>a?I.filter(z=>z.toasterId===a):I.filter(z=>!z.toasterId),[I,a]),M=ce.useMemo(()=>Array.from(new Set([i].concat(O.filter(z=>z.position).map(z=>z.position)))),[O,i]),[P,B]=ce.useState([]),[K,Q]=ce.useState(!1),[ee,ae]=ce.useState(!1),[H,Z]=ce.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),G=ce.useRef(null),re=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),te=ce.useRef(null),j=ce.useRef(!1),V=ce.useCallback(z=>{A($=>{var L;return(L=$.find(F=>F.id===z.id))!=null&&L.delete||ga.dismiss(z.id),$.filter(({id:F})=>F!==z.id)})},[]);return ce.useEffect(()=>ga.subscribe(z=>{if(z.dismiss){requestAnimationFrame(()=>{A($=>$.map(L=>L.id===z.id?{...L,delete:!0}:L))});return}setTimeout(()=>{F9.flushSync(()=>{A($=>{const L=$.findIndex(F=>F.id===z.id);return L!==-1?[...$.slice(0,L),{...$[L],...z},...$.slice(L+1)]:[z,...$]})})})}),[I]),ce.useEffect(()=>{if(g!=="system"){Z(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;const z=window.matchMedia("(prefers-color-scheme: dark)");try{z.addEventListener("change",({matches:$})=>{Z($?"dark":"light")})}catch{z.addListener(({matches:L})=>{try{Z(L?"dark":"light")}catch(F){console.error(F)}})}},[g]),ce.useEffect(()=>{I.length<=1&&Q(!1)},[I]),ce.useEffect(()=>{const z=$=>{var L;if(s.every(ne=>$[ne]||$.code===ne)){var W;Q(!0),(W=G.current)==null||W.focus()}$.code==="Escape"&&(document.activeElement===G.current||(L=G.current)!=null&&L.contains(document.activeElement))&&Q(!1)};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[s]),ce.useEffect(()=>{if(G.current)return()=>{te.current&&(te.current.focus({preventScroll:!0}),te.current=null,j.current=!1)}},[G.current]),ce.createElement("section",{ref:n,"aria-label":`${R} ${re}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((z,$)=>{var L;const[F,W]=z.split("-");return O.length?ce.createElement("ol",{key:z,dir:_==="auto"?sz():_,tabIndex:-1,ref:G,className:d,"data-sonner-toaster":!0,"data-sonner-theme":H,"data-y-position":F,"data-x-position":W,style:{"--front-toast-height":`${((L=P[0])==null?void 0:L.height)||0}px`,"--width":`${pge}px`,"--gap":`${k}px`,...S,...yge(m,h)},onBlur:ne=>{j.current&&!ne.currentTarget.contains(ne.relatedTarget)&&(j.current=!1,te.current&&(te.current.focus({preventScroll:!0}),te.current=null))},onFocus:ne=>{ne.target instanceof HTMLElement&&ne.target.dataset.dismissible==="false"||j.current||(j.current=!0,te.current=ne.relatedTarget)},onMouseEnter:()=>Q(!0),onMouseMove:()=>Q(!0),onMouseLeave:()=>{ee||Q(!1)},onDragEnd:()=>Q(!1),onPointerDown:ne=>{ne.target instanceof HTMLElement&&ne.target.dataset.dismissible==="false"||ae(!0)},onPointerUp:()=>ae(!1)},O.filter(ne=>!ne.position&&$===0||ne.position===z).map((ne,le)=>{var ue,X;return ce.createElement(vge,{key:ne.id,icons:C,index:le,toast:ne,defaultRichColors:v,duration:(ue=E?.duration)!=null?ue:x,className:E?.className,descriptionClassName:E?.descriptionClassName,invert:r,visibleToasts:w,closeButton:(X=E?.closeButton)!=null?X:u,interacting:ee,position:z,style:E?.style,unstyled:E?.unstyled,classNames:E?.classNames,cancelButtonStyle:E?.cancelButtonStyle,actionButtonStyle:E?.actionButtonStyle,closeButtonAriaLabel:E?.closeButtonAriaLabel,removeToast:V,toasts:O.filter(q=>q.position==ne.position),heights:P.filter(q=>q.position==ne.position),setHeights:B,expandByDefault:c,gap:k,expanded:K,swipeDirections:t.swipeDirections})})):null}))}),lz=Object.freeze(Object.defineProperty({__proto__:null,Toaster:VG,toast:Xt},Symbol.toStringTag,{value:"Module"}));var Qy="Dialog",[GG]=Ii(Qy),[wge,Oi]=GG(Qy),WG=e=>{const{__scopeDialog:t,children:n,open:a,defaultOpen:r,onOpenChange:i,modal:s=!0}=e,c=y.useRef(null),u=y.useRef(null),[d,m]=Po({prop:a,defaultProp:r??!1,onChange:i,caller:Qy});return f.jsx(wge,{scope:t,triggerRef:c,contentRef:u,contentId:$r(),titleId:$r(),descriptionId:$r(),open:d,onOpenChange:m,onOpenToggle:y.useCallback(()=>m(h=>!h),[m]),modal:s,children:n})};WG.displayName=Qy;var KG="DialogTrigger",ZG=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(KG,n),i=Jt(t,r.triggerRef);return f.jsx(Et.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":iC(r.open),...a,ref:i,onClick:Ge(e.onClick,r.onOpenToggle)})});ZG.displayName=KG;var rC="DialogPortal",[Sge,YG]=GG(rC,{forceMount:void 0}),qG=e=>{const{__scopeDialog:t,forceMount:n,children:a,container:r}=e,i=Oi(rC,t);return f.jsx(Sge,{scope:t,forceMount:n,children:y.Children.map(a,s=>f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:s})}))})};qG.displayName=rC;var Iv="DialogOverlay",XG=y.forwardRef((e,t)=>{const n=YG(Iv,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Iv,e.__scopeDialog);return i.modal?f.jsx(Ua,{present:a||i.open,children:f.jsx(_ge,{...r,ref:t})}):null});XG.displayName=Iv;var xge=Vl("DialogOverlay.RemoveScroll"),_ge=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(Iv,n);return f.jsx(Om,{as:xge,allowPinchZoom:!0,shards:[r.contentRef],children:f.jsx(Et.div,{"data-state":iC(r.open),...a,ref:t,style:{pointerEvents:"auto",...a.style}})})}),Kl="DialogContent",JG=y.forwardRef((e,t)=>{const n=YG(Kl,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Kl,e.__scopeDialog);return f.jsx(Ua,{present:a||i.open,children:i.modal?f.jsx(Ege,{...r,ref:t}):f.jsx(kge,{...r,ref:t})})});JG.displayName=Kl;var Ege=y.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=y.useRef(null),r=Jt(t,n.contentRef,a);return y.useEffect(()=>{const i=a.current;if(i)return By(i)},[]),f.jsx(QG,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ge(e.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ge(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&i.preventDefault()}),onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault())})}),kge=y.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=y.useRef(!1),r=y.useRef(!1);return f.jsx(QG,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(a.current||n.triggerRef.current?.focus(),i.preventDefault()),a.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(a.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=i.target;n.triggerRef.current?.contains(s)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),QG=y.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:a,onOpenAutoFocus:r,onCloseAutoFocus:i,...s}=e,c=Oi(Kl,n),u=y.useRef(null),d=Jt(t,u);return jy(),f.jsxs(f.Fragment,{children:[f.jsx(Cm,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:r,onUnmountAutoFocus:i,children:f.jsx(Dd,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":iC(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),f.jsxs(f.Fragment,{children:[f.jsx(Tge,{titleId:c.titleId}),f.jsx(Cge,{contentRef:u,descriptionId:c.descriptionId})]})]})}),aC="DialogTitle",e7=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(aC,n);return f.jsx(Et.h2,{id:r.titleId,...a,ref:t})});e7.displayName=aC;var t7="DialogDescription",n7=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(t7,n);return f.jsx(Et.p,{id:r.descriptionId,...a,ref:t})});n7.displayName=t7;var r7="DialogClose",a7=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(r7,n);return f.jsx(Et.button,{type:"button",...a,ref:t,onClick:Ge(e.onClick,()=>r.onOpenChange(!1))})});a7.displayName=r7;function iC(e){return e?"open":"closed"}var i7="DialogTitleWarning",[tNe,o7]=pce(i7,{contentName:Kl,titleName:aC,docsSlug:"dialog"}),Tge=({titleId:e})=>{const t=o7(i7),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
93
|
+
`)},rfe=0,Yc=[];function afe(e){var t=y.useRef([]),n=y.useRef([0,0]),a=y.useRef(),r=y.useState(rfe++)[0],i=y.useState(E8)[0],s=y.useRef(e);y.useEffect(function(){s.current=e},[e]),y.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var S=kde([e.lockRef.current],(e.shards||[]).map(YU),!0).filter(Boolean);return S.forEach(function(w){return w.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),S.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var c=y.useCallback(function(S,w){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!s.current.allowPinchZoom;var E=lb(S),_=n.current,k="deltaX"in S?S.deltaX:_[0]-E[0],C="deltaY"in S?S.deltaY:_[1]-E[1],R,I=S.target,A=Math.abs(k)>Math.abs(C)?"h":"v";if("touches"in S&&A==="h"&&I.type==="range")return!1;var O=window.getSelection(),M=O&&O.anchorNode,P=M?M===I||M.contains(I):!1;if(P)return!1;var B=KU(A,I);if(!B)return!0;if(B?R=A:(R=A==="v"?"h":"v",B=KU(A,I)),!B)return!1;if(!a.current&&"changedTouches"in S&&(k||C)&&(a.current=R),!R)return!0;var K=a.current||R;return efe(K,w,S,K==="h"?k:C)},[]),u=y.useCallback(function(S){var w=S;if(!(!Yc.length||Yc[Yc.length-1]!==i)){var E="deltaY"in w?ZU(w):lb(w),_=t.current.filter(function(R){return R.name===w.type&&(R.target===w.target||w.target===R.shadowParent)&&tfe(R.delta,E)})[0];if(_&&_.should){w.cancelable&&w.preventDefault();return}if(!_){var k=(s.current.shards||[]).map(YU).filter(Boolean).filter(function(R){return R.contains(w.target)}),C=k.length>0?c(w,k[0]):!s.current.noIsolation;C&&w.cancelable&&w.preventDefault()}}},[]),d=y.useCallback(function(S,w,E,_){var k={name:S,delta:w,target:E,should:_,shadowParent:ife(E)};t.current.push(k),setTimeout(function(){t.current=t.current.filter(function(C){return C!==k})},1)},[]),m=y.useCallback(function(S){n.current=lb(S),a.current=void 0},[]),h=y.useCallback(function(S){d(S.type,ZU(S),S.target,c(S,e.lockRef.current))},[]),g=y.useCallback(function(S){d(S.type,lb(S),S.target,c(S,e.lockRef.current))},[]);y.useEffect(function(){return Yc.push(i),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,Zc),document.addEventListener("touchmove",u,Zc),document.addEventListener("touchstart",m,Zc),function(){Yc=Yc.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,Zc),document.removeEventListener("touchmove",u,Zc),document.removeEventListener("touchstart",m,Zc)}},[]);var v=e.removeScrollBar,x=e.inert;return y.createElement(y.Fragment,null,x?y.createElement(i,{styles:nfe(r)}):null,v?y.createElement(Kde,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function ife(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ofe=jde(_8,afe);var Om=y.forwardRef(function(e,t){return y.createElement(Hy,Fi({},e,{ref:t,sideCar:ofe}))});Om.classNames=Hy.classNames;var V_=["Enter"," "],sfe=["ArrowDown","PageUp","Home"],C8=["ArrowUp","PageDown","End"],lfe=[...sfe,...C8],cfe={ltr:[...V_,"ArrowRight"],rtl:[...V_,"ArrowLeft"]},ufe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Dm="Menu",[zp,dfe,ffe]=CN(Dm),[nc,R8]=Ii(Dm,[ffe,Zs,h8]),Vy=Zs(),A8=h8(),[pfe,rc]=nc(Dm),[mfe,jm]=nc(Dm),I8=e=>{const{__scopeMenu:t,open:n=!1,children:a,dir:r,onOpenChange:i,modal:s=!0}=e,c=Vy(t),[u,d]=y.useState(null),m=y.useRef(!1),h=Zi(i),g=RN(r);return y.useEffect(()=>{const v=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.jsx(Uy,{...c,children:f.jsx(pfe,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:d,children:f.jsx(mfe,{scope:t,onClose:y.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:s,children:a})})})};I8.displayName=Dm;var hfe="MenuAnchor",UN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Vy(n);return f.jsx(Am,{...r,...a,ref:t})});UN.displayName=hfe;var zN="MenuPortal",[gfe,O8]=nc(zN,{forceMount:void 0}),D8=e=>{const{__scopeMenu:t,forceMount:n,children:a,container:r}=e,i=rc(zN,t);return f.jsx(gfe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};D8.displayName=zN;var Qa="MenuContent",[bfe,FN]=nc(Qa),j8=y.forwardRef((e,t)=>{const n=O8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:s.modal?f.jsx(vfe,{...r,ref:t}):f.jsx(yfe,{...r,ref:t})})})})}),vfe=y.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu),a=y.useRef(null),r=Jt(t,a);return y.useEffect(()=>{const i=a.current;if(i)return By(i)},[]),f.jsx(BN,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),yfe=y.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu);return f.jsx(BN,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),wfe=Vl("MenuContent.ScrollLock"),BN=y.forwardRef((e,t)=>{const{__scopeMenu:n,loop:a=!1,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,disableOutsideScroll:x,...S}=e,w=rc(Qa,n),E=jm(Qa,n),_=Vy(n),k=A8(n),C=dfe(n),[R,I]=y.useState(null),A=y.useRef(null),O=Jt(t,A,w.onContentChange),M=y.useRef(0),P=y.useRef(""),B=y.useRef(0),K=y.useRef(null),Q=y.useRef("right"),ee=y.useRef(0),ae=x?Om:y.Fragment,H=x?{as:wfe,allowPinchZoom:!0}:void 0,Z=re=>{const te=P.current+re,j=C().filter(W=>!W.disabled),V=document.activeElement,z=j.find(W=>W.ref.current===V)?.textValue,$=j.map(W=>W.textValue),L=Ofe($,te,z),F=j.find(W=>W.textValue===L)?.ref.current;(function W(ne){P.current=ne,window.clearTimeout(M.current),ne!==""&&(M.current=window.setTimeout(()=>W(""),1e3))})(te),F&&setTimeout(()=>F.focus())};y.useEffect(()=>()=>window.clearTimeout(M.current),[]),jy();const G=y.useCallback(re=>Q.current===K.current?.side&&jfe(re,K.current?.area),[]);return f.jsx(bfe,{scope:n,searchRef:P,onItemEnter:y.useCallback(re=>{G(re)&&re.preventDefault()},[G]),onItemLeave:y.useCallback(re=>{G(re)||(A.current?.focus(),I(null))},[G]),onTriggerLeave:y.useCallback(re=>{G(re)&&re.preventDefault()},[G]),pointerGraceTimerRef:B,onPointerGraceIntentChange:y.useCallback(re=>{K.current=re},[]),children:f.jsx(ae,{...H,children:f.jsx(Cm,{asChild:!0,trapped:r,onMountAutoFocus:Ge(i,re=>{re.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,children:f.jsx(wde,{asChild:!0,...k,dir:E.dir,orientation:"vertical",loop:a,currentTabStopId:R,onCurrentTabStopIdChange:I,onEntryFocus:Ge(u,re=>{E.isUsingKeyboardRef.current||re.preventDefault()}),preventScrollOnEntryFocus:!0,children:f.jsx(zy,{role:"menu","aria-orientation":"vertical","data-state":q8(w.open),"data-radix-menu-content":"",dir:E.dir,..._,...S,ref:O,style:{outline:"none",...S.style},onKeyDown:Ge(S.onKeyDown,re=>{const j=re.target.closest("[data-radix-menu-content]")===re.currentTarget,V=re.ctrlKey||re.altKey||re.metaKey,z=re.key.length===1;j&&(re.key==="Tab"&&re.preventDefault(),!V&&z&&Z(re.key));const $=A.current;if(re.target!==$||!lfe.includes(re.key))return;re.preventDefault();const F=C().filter(W=>!W.disabled).map(W=>W.ref.current);C8.includes(re.key)&&F.reverse(),Afe(F)}),onBlur:Ge(e.onBlur,re=>{re.currentTarget.contains(re.target)||(window.clearTimeout(M.current),P.current="")}),onPointerMove:Ge(e.onPointerMove,Fp(re=>{const te=re.target,j=ee.current!==re.clientX;if(re.currentTarget.contains(te)&&j){const V=re.clientX>ee.current?"right":"left";Q.current=V,ee.current=re.clientX}}))})})})})})})});j8.displayName=Qa;var Sfe="MenuGroup",HN=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(Et.div,{role:"group",...a,ref:t})});HN.displayName=Sfe;var xfe="MenuLabel",$8=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(Et.div,{...a,ref:t})});$8.displayName=xfe;var Nv="MenuItem",qU="menu.itemSelect",Gy=y.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:a,...r}=e,i=y.useRef(null),s=jm(Nv,e.__scopeMenu),c=FN(Nv,e.__scopeMenu),u=Jt(t,i),d=y.useRef(!1),m=()=>{const h=i.current;if(!n&&h){const g=new CustomEvent(qU,{bubbles:!0,cancelable:!0});h.addEventListener(qU,v=>a?.(v),{once:!0}),H9(h,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.jsx(L8,{...r,ref:u,disabled:n,onClick:Ge(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),d.current=!0},onPointerUp:Ge(e.onPointerUp,h=>{d.current||h.currentTarget?.click()}),onKeyDown:Ge(e.onKeyDown,h=>{const g=c.searchRef.current!=="";n||g&&h.key===" "||V_.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Gy.displayName=Nv;var L8=y.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:a=!1,textValue:r,...i}=e,s=FN(Nv,n),c=A8(n),u=y.useRef(null),d=Jt(t,u),[m,h]=y.useState(!1),[g,v]=y.useState("");return y.useEffect(()=>{const x=u.current;x&&v((x.textContent??"").trim())},[i.children]),f.jsx(zp.ItemSlot,{scope:n,disabled:a,textValue:r??g,children:f.jsx(Sde,{asChild:!0,...c,focusable:!a,children:f.jsx(Et.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":a||void 0,"data-disabled":a?"":void 0,...i,ref:d,onPointerMove:Ge(e.onPointerMove,Fp(x=>{a?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ge(e.onPointerLeave,Fp(x=>s.onItemLeave(x))),onFocus:Ge(e.onFocus,()=>h(!0)),onBlur:Ge(e.onBlur,()=>h(!1))})})})}),_fe="MenuCheckboxItem",M8=y.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:a,...r}=e;return f.jsx(B8,{scope:e.__scopeMenu,checked:n,children:f.jsx(Gy,{role:"menuitemcheckbox","aria-checked":Cv(n)?"mixed":n,...r,ref:t,"data-state":GN(n),onSelect:Ge(r.onSelect,()=>a?.(Cv(n)?!0:!n),{checkForDefaultPrevented:!1})})})});M8.displayName=_fe;var P8="MenuRadioGroup",[Efe,kfe]=nc(P8,{value:void 0,onValueChange:()=>{}}),U8=y.forwardRef((e,t)=>{const{value:n,onValueChange:a,...r}=e,i=Zi(a);return f.jsx(Efe,{scope:e.__scopeMenu,value:n,onValueChange:i,children:f.jsx(HN,{...r,ref:t})})});U8.displayName=P8;var z8="MenuRadioItem",F8=y.forwardRef((e,t)=>{const{value:n,...a}=e,r=kfe(z8,e.__scopeMenu),i=n===r.value;return f.jsx(B8,{scope:e.__scopeMenu,checked:i,children:f.jsx(Gy,{role:"menuitemradio","aria-checked":i,...a,ref:t,"data-state":GN(i),onSelect:Ge(a.onSelect,()=>r.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});F8.displayName=z8;var VN="MenuItemIndicator",[B8,Tfe]=nc(VN,{checked:!1}),H8=y.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:a,...r}=e,i=Tfe(VN,n);return f.jsx(Ua,{present:a||Cv(i.checked)||i.checked===!0,children:f.jsx(Et.span,{...r,ref:t,"data-state":GN(i.checked)})})});H8.displayName=VN;var Nfe="MenuSeparator",V8=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(Et.div,{role:"separator","aria-orientation":"horizontal",...a,ref:t})});V8.displayName=Nfe;var Cfe="MenuArrow",G8=y.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Vy(n);return f.jsx(Fy,{...r,...a,ref:t})});G8.displayName=Cfe;var Rfe="MenuSub",[eNe,W8]=nc(Rfe),np="MenuSubTrigger",K8=y.forwardRef((e,t)=>{const n=rc(np,e.__scopeMenu),a=jm(np,e.__scopeMenu),r=W8(np,e.__scopeMenu),i=FN(np,e.__scopeMenu),s=y.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},m=y.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return y.useEffect(()=>m,[m]),y.useEffect(()=>{const h=c.current;return()=>{window.clearTimeout(h),u(null)}},[c,u]),f.jsx(UN,{asChild:!0,...d,children:f.jsx(L8,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":r.contentId,"data-state":q8(n.open),...e,ref:Ki(t,r.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ge(e.onPointerMove,Fp(h=>{i.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:Ge(e.onPointerLeave,Fp(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const v=n.content?.dataset.side,x=v==="right",S=x?-5:5,w=g[x?"left":"right"],E=g[x?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+S,y:h.clientY},{x:w,y:g.top},{x:E,y:g.top},{x:E,y:g.bottom},{x:w,y:g.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Ge(e.onKeyDown,h=>{const g=i.searchRef.current!=="";e.disabled||g&&h.key===" "||cfe[a.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});K8.displayName=np;var Z8="MenuSubContent",Y8=y.forwardRef((e,t)=>{const n=O8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu),c=W8(Z8,e.__scopeMenu),u=y.useRef(null),d=Jt(t,u);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:f.jsx(BN,{id:c.contentId,"aria-labelledby":c.triggerId,...r,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{s.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Ge(e.onFocusOutside,m=>{m.target!==c.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Ge(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:Ge(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=ufe[s.dir].includes(m.key);h&&g&&(i.onOpenChange(!1),c.trigger?.focus(),m.preventDefault())})})})})})});Y8.displayName=Z8;function q8(e){return e?"open":"closed"}function Cv(e){return e==="indeterminate"}function GN(e){return Cv(e)?"indeterminate":e?"checked":"unchecked"}function Afe(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Ife(e,t){return e.map((n,a)=>e[(t+a)%e.length])}function Ofe(e,t,n){const r=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=Ife(e,Math.max(i,0));r.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(r.toLowerCase()));return u!==n?u:void 0}function Dfe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function jfe(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Dfe(n,t)}function Fp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var $fe=I8,Lfe=UN,Mfe=D8,Pfe=j8,Ufe=HN,zfe=$8,Ffe=Gy,Bfe=M8,Hfe=U8,Vfe=F8,Gfe=H8,Wfe=V8,Kfe=G8,Zfe=K8,Yfe=Y8,Wy="DropdownMenu",[qfe]=Ii(Wy,[R8]),ia=R8(),[Xfe,X8]=qfe(Wy),J8=e=>{const{__scopeDropdownMenu:t,children:n,dir:a,open:r,defaultOpen:i,onOpenChange:s,modal:c=!0}=e,u=ia(t),d=y.useRef(null),[m,h]=Po({prop:r,defaultProp:i??!1,onChange:s,caller:Wy});return f.jsx(Xfe,{scope:t,triggerId:$r(),triggerRef:d,contentId:$r(),open:m,onOpenChange:h,onOpenToggle:y.useCallback(()=>h(g=>!g),[h]),modal:c,children:f.jsx($fe,{...u,open:m,onOpenChange:h,dir:a,modal:c,children:n})})};J8.displayName=Wy;var Q8="DropdownMenuTrigger",eG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:a=!1,...r}=e,i=X8(Q8,n),s=ia(n);return f.jsx(Lfe,{asChild:!0,...s,children:f.jsx(Et.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":a?"":void 0,disabled:a,...r,ref:Ki(t,i.triggerRef),onPointerDown:Ge(e.onPointerDown,c=>{!a&&c.button===0&&c.ctrlKey===!1&&(i.onOpenToggle(),i.open||c.preventDefault())}),onKeyDown:Ge(e.onKeyDown,c=>{a||(["Enter"," "].includes(c.key)&&i.onOpenToggle(),c.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});eG.displayName=Q8;var Jfe="DropdownMenuPortal",tG=e=>{const{__scopeDropdownMenu:t,...n}=e,a=ia(t);return f.jsx(Mfe,{...a,...n})};tG.displayName=Jfe;var nG="DropdownMenuContent",rG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=X8(nG,n),i=ia(n),s=y.useRef(!1);return f.jsx(Pfe,{id:r.contentId,"aria-labelledby":r.triggerId,...i,...a,ref:t,onCloseAutoFocus:Ge(e.onCloseAutoFocus,c=>{s.current||r.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:Ge(e.onInteractOutside,c=>{const u=c.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,m=u.button===2||d;(!r.modal||m)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});rG.displayName=nG;var Qfe="DropdownMenuGroup",epe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ufe,{...r,...a,ref:t})});epe.displayName=Qfe;var tpe="DropdownMenuLabel",aG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(zfe,{...r,...a,ref:t})});aG.displayName=tpe;var npe="DropdownMenuItem",iG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ffe,{...r,...a,ref:t})});iG.displayName=npe;var rpe="DropdownMenuCheckboxItem",oG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Bfe,{...r,...a,ref:t})});oG.displayName=rpe;var ape="DropdownMenuRadioGroup",ipe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Hfe,{...r,...a,ref:t})});ipe.displayName=ape;var ope="DropdownMenuRadioItem",sG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Vfe,{...r,...a,ref:t})});sG.displayName=ope;var spe="DropdownMenuItemIndicator",lpe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Gfe,{...r,...a,ref:t})});lpe.displayName=spe;var cpe="DropdownMenuSeparator",lG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Wfe,{...r,...a,ref:t})});lG.displayName=cpe;var upe="DropdownMenuArrow",dpe=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Kfe,{...r,...a,ref:t})});dpe.displayName=upe;var fpe="DropdownMenuSubTrigger",cG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Zfe,{...r,...a,ref:t})});cG.displayName=fpe;var ppe="DropdownMenuSubContent",uG=y.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Yfe,{...r,...a,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});uG.displayName=ppe;var mpe=J8,hpe=eG,gpe=tG,dG=rG,fG=aG,pG=iG,bpe=oG,vpe=sG,mG=lG,ype=cG,wpe=uG;const G_=mpe,W_=hpe;ype.displayName;wpe.displayName;function Rv({ref:e,className:t,sideOffset:n=4,...a}){return f.jsx(gpe,{children:f.jsx(dG,{ref:e,sideOffset:n,className:De("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})}Rv.displayName=dG.displayName;function Ao({ref:e,className:t,inset:n,...a}){return f.jsx(pG,{ref:e,className:De("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",t),...a})}Ao.displayName=pG.displayName;bpe.displayName;vpe.displayName;function K_({ref:e,className:t,inset:n,...a}){return f.jsx(fG,{ref:e,className:De("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...a})}K_.displayName=fG.displayName;function rp({ref:e,className:t,...n}){return f.jsx(mG,{ref:e,className:De("-mx-1 my-1 h-px bg-muted",t),...n})}rp.displayName=mG.displayName;var Spe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Wo=Spe.reduce((e,t)=>{const n=E9(`Primitive.${t}`),a=y.forwardRef((r,i)=>{const{asChild:s,...c}=r,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),f.jsx(u,{...c,ref:i})});return a.displayName=`Primitive.${t}`,{...e,[t]:a}},{}),xpe="Label",hG=y.forwardRef((e,t)=>f.jsx(Wo.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));hG.displayName=xpe;var _pe=hG;function Kt({className:e,...t}){return f.jsx(_pe,{"data-slot":"label",className:De("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Md({message:e,className:t="",vertical:n,noBorder:a}){return f.jsx("div",{className:De(`mt-2 rounded-md p-6 ${t}`,!a&&"border"),children:f.jsxs("p",{className:De("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[f.jsx("svg",{width:"40",height:"40",viewBox:"0 0 273 273",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:"flex-shrink-0",children:f.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:f.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[f.jsx("path",{d:"M49.953025,-2.10854389 C63.26892,-2.21867124 76.6185256,2.70621155 86.9019463,12.6653164 L86.9019463,12.6653164 L87.505627,13.2592944 C97.5154947,23.2654892 102.640454,36.3074513 102.880738,49.4222247 C103.08932,77.4533067 113.877287,105.391753 135.242867,126.757333 C156.613383,148.127849 184.559216,158.914875 212.568138,159.119313 L212.568138,159.119313 L213.212264,159.134159 C225.843948,159.517566 238.363557,164.434972 248.121998,173.886137 L248.121998,173.886137 L248.725621,174.480088 C258.982114,184.732164 264.11035,198.171134 264.11035,211.6101 C264.11035,225.04592 258.984514,238.481745 248.732867,248.732867 C238.592792,258.872942 225.336706,263.997882 212.046872,264.107794 C198.731075,264.21792 185.381569,259.293085 175.098248,249.334078 L175.098248,249.334078 L174.494602,248.740134 C163.75802,238.008189 158.640853,223.784027 159.143413,209.719372 C158.258245,182.640933 147.489786,155.83332 126.828333,135.171867 C106.351297,114.694831 79.8363505,103.934873 53.0237258,102.891841 L53.0237258,102.891841 L52.2811438,102.865674 C38.4791718,103.347421 24.5325234,98.4328111 13.8776628,88.1140866 L13.8776628,88.1140866 L13.2739843,87.5201168 C3.12895117,77.3789607 -1.9984796,64.1195994 -2.10841888,50.8264755 C-2.21854669,37.5105567 2.70635908,24.1609269 12.6655135,13.8774565 L12.6655135,13.8774565 L13.2594878,13.2737797 C23.4005926,3.12880025 36.659927,-1.99860507 49.953025,-2.10854389 Z"}),f.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),f.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function gG({className:e,color:t,children:n,grayscaled:a=!1}){const r=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return a?0:.2},[t,a]),i=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return a?.3:.4},[t,a]),s=y.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[2]||"0")}return Math.floor(Math.random()*360)},[t]),c=y.useMemo(()=>t||`oklch(${Math.min(i,1)} ${r} ${s})`,[s,r,i]),u=y.useMemo(()=>`oklch(${Math.min(i*2,1)} ${r} ${s})`,[s,r,i,t]),d=y.useMemo(()=>Math.floor(Math.random()*360),[s]),m=y.useMemo(()=>"1000%",[]);return f.jsx("section",{className:De("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:f.jsxs("div",{className:"isolate relative w-full h-full",children:[f.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${d}deg, ${c}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&f.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}function WN(e){const t=y.useRef({value:e,previous:e});return y.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Ky="Switch",[Epe]=Ii(Ky),[kpe,Tpe]=Epe(Ky),bG=y.forwardRef((e,t)=>{const{__scopeSwitch:n,name:a,checked:r,defaultChecked:i,required:s,disabled:c,value:u="on",onCheckedChange:d,form:m,...h}=e,[g,v]=y.useState(null),x=Jt(t,k=>v(k)),S=y.useRef(!1),w=g?m||!!g.closest("form"):!0,[E,_]=Po({prop:r,defaultProp:i??!1,onChange:d,caller:Ky});return f.jsxs(kpe,{scope:n,checked:E,disabled:c,children:[f.jsx(Et.button,{type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":SG(E),"data-disabled":c?"":void 0,disabled:c,value:u,...h,ref:x,onClick:Ge(e.onClick,k=>{_(C=>!C),w&&(S.current=k.isPropagationStopped(),S.current||k.stopPropagation())})}),w&&f.jsx(wG,{control:g,bubbles:!S.current,name:a,value:u,checked:E,required:s,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});bG.displayName=Ky;var vG="SwitchThumb",yG=y.forwardRef((e,t)=>{const{__scopeSwitch:n,...a}=e,r=Tpe(vG,n);return f.jsx(Et.span,{"data-state":SG(r.checked),"data-disabled":r.disabled?"":void 0,...a,ref:t})});yG.displayName=vG;var Npe="SwitchBubbleInput",wG=y.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:a=!0,...r},i)=>{const s=y.useRef(null),c=Jt(s,i),u=WN(n),d=LN(t);return y.useEffect(()=>{const m=s.current;if(!m)return;const h=window.HTMLInputElement.prototype,v=Object.getOwnPropertyDescriptor(h,"checked").set;if(u!==n&&v){const x=new Event("click",{bubbles:a});v.call(m,n),m.dispatchEvent(x)}},[u,n,a]),f.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...r,tabIndex:-1,ref:c,style:{...r.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});wG.displayName=Npe;function SG(e){return e?"checked":"unchecked"}var xG=bG,Cpe=yG;function Zy({ref:e,className:t,...n}){return f.jsx(xG,{className:De("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...n,ref:e,children:f.jsx(Cpe,{className:De("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})})}Zy.displayName=xG.displayName;var _G=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Rpe="VisuallyHidden",EG=y.forwardRef((e,t)=>f.jsx(Et.span,{...e,ref:t,style:{..._G,...e.style}}));EG.displayName=Rpe;var Ape=EG,[Yy]=Ii("Tooltip",[Zs]),qy=Zs(),kG="TooltipProvider",Ipe=700,Z_="tooltip.open",[Ope,KN]=Yy(kG),TG=e=>{const{__scopeTooltip:t,delayDuration:n=Ipe,skipDelayDuration:a=300,disableHoverableContent:r=!1,children:i}=e,s=y.useRef(!0),c=y.useRef(!1),u=y.useRef(0);return y.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),f.jsx(Ope,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:y.useCallback(()=>{window.clearTimeout(u.current),s.current=!1},[]),onClose:y.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>s.current=!0,a)},[a]),isPointerInTransitRef:c,onPointerInTransitChange:y.useCallback(d=>{c.current=d},[]),disableHoverableContent:r,children:i})};TG.displayName=kG;var Bp="Tooltip",[Dpe,$m]=Yy(Bp),NG=e=>{const{__scopeTooltip:t,children:n,open:a,defaultOpen:r,onOpenChange:i,disableHoverableContent:s,delayDuration:c}=e,u=KN(Bp,e.__scopeTooltip),d=qy(t),[m,h]=y.useState(null),g=$r(),v=y.useRef(0),x=s??u.disableHoverableContent,S=c??u.delayDuration,w=y.useRef(!1),[E,_]=Po({prop:a,defaultProp:r??!1,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(Z_))):u.onClose(),i?.(A)},caller:Bp}),k=y.useMemo(()=>E?w.current?"delayed-open":"instant-open":"closed",[E]),C=y.useCallback(()=>{window.clearTimeout(v.current),v.current=0,w.current=!1,_(!0)},[_]),R=y.useCallback(()=>{window.clearTimeout(v.current),v.current=0,_(!1)},[_]),I=y.useCallback(()=>{window.clearTimeout(v.current),v.current=window.setTimeout(()=>{w.current=!0,_(!0),v.current=0},S)},[S,_]);return y.useEffect(()=>()=>{v.current&&(window.clearTimeout(v.current),v.current=0)},[]),f.jsx(Uy,{...d,children:f.jsx(Dpe,{scope:t,contentId:g,open:E,stateAttribute:k,trigger:m,onTriggerChange:h,onTriggerEnter:y.useCallback(()=>{u.isOpenDelayedRef.current?I():C()},[u.isOpenDelayedRef,I,C]),onTriggerLeave:y.useCallback(()=>{x?R():(window.clearTimeout(v.current),v.current=0)},[R,x]),onOpen:C,onClose:R,disableHoverableContent:x,children:n})})};NG.displayName=Bp;var Y_="TooltipTrigger",CG=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=$m(Y_,n),i=KN(Y_,n),s=qy(n),c=y.useRef(null),u=Jt(t,c,r.onTriggerChange),d=y.useRef(!1),m=y.useRef(!1),h=y.useCallback(()=>d.current=!1,[]);return y.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),f.jsx(Am,{asChild:!0,...s,children:f.jsx(Et.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...a,ref:u,onPointerMove:Ge(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(r.onTriggerEnter(),m.current=!0)}),onPointerLeave:Ge(e.onPointerLeave,()=>{r.onTriggerLeave(),m.current=!1}),onPointerDown:Ge(e.onPointerDown,()=>{r.open&&r.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:Ge(e.onFocus,()=>{d.current||r.onOpen()}),onBlur:Ge(e.onBlur,r.onClose),onClick:Ge(e.onClick,r.onClose)})})});CG.displayName=Y_;var ZN="TooltipPortal",[jpe,$pe]=Yy(ZN,{forceMount:void 0}),RG=e=>{const{__scopeTooltip:t,forceMount:n,children:a,container:r}=e,i=$m(ZN,t);return f.jsx(jpe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};RG.displayName=ZN;var dd="TooltipContent",AG=y.forwardRef((e,t)=>{const n=$pe(dd,e.__scopeTooltip),{forceMount:a=n.forceMount,side:r="top",...i}=e,s=$m(dd,e.__scopeTooltip);return f.jsx(Ua,{present:a||s.open,children:s.disableHoverableContent?f.jsx(IG,{side:r,...i,ref:t}):f.jsx(Lpe,{side:r,...i,ref:t})})}),Lpe=y.forwardRef((e,t)=>{const n=$m(dd,e.__scopeTooltip),a=KN(dd,e.__scopeTooltip),r=y.useRef(null),i=Jt(t,r),[s,c]=y.useState(null),{trigger:u,onClose:d}=n,m=r.current,{onPointerInTransitChange:h}=a,g=y.useCallback(()=>{c(null),h(!1)},[h]),v=y.useCallback((x,S)=>{const w=x.currentTarget,E={x:x.clientX,y:x.clientY},_=zpe(E,w.getBoundingClientRect()),k=Fpe(E,_),C=Bpe(S.getBoundingClientRect()),R=Vpe([...k,...C]);c(R),h(!0)},[h]);return y.useEffect(()=>()=>g(),[g]),y.useEffect(()=>{if(u&&m){const x=w=>v(w,m),S=w=>v(w,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",S)}}},[u,m,v,g]),y.useEffect(()=>{if(s){const x=S=>{const w=S.target,E={x:S.clientX,y:S.clientY},_=u?.contains(w)||m?.contains(w),k=!Hpe(E,s);_?g():k&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,s,d,g]),f.jsx(IG,{...e,ref:i})}),[Mpe,Ppe]=Yy(Bp,{isInside:!1}),Upe=yce("TooltipContent"),IG=y.forwardRef((e,t)=>{const{__scopeTooltip:n,children:a,"aria-label":r,onEscapeKeyDown:i,onPointerDownOutside:s,...c}=e,u=$m(dd,n),d=qy(n),{onClose:m}=u;return y.useEffect(()=>(document.addEventListener(Z_,m),()=>document.removeEventListener(Z_,m)),[m]),y.useEffect(()=>{if(u.trigger){const h=g=>{g.target?.contains(u.trigger)&&m()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[u.trigger,m]),f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:f.jsxs(zy,{"data-state":u.stateAttribute,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[f.jsx(Upe,{children:a}),f.jsx(Mpe,{scope:n,isInside:!0,children:f.jsx(Ape,{id:u.contentId,role:"tooltip",children:r||a})})]})})});AG.displayName=dd;var OG="TooltipArrow",DG=y.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=qy(n);return Ppe(OG,n).isInside?null:f.jsx(Fy,{...r,...a,ref:t})});DG.displayName=OG;function zpe(e,t){const n=Math.abs(t.top-e.y),a=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,a,r,i)){case i:return"left";case r:return"right";case n:return"top";case a:return"bottom";default:throw new Error("unreachable")}}function Fpe(e,t,n=5){const a=[];switch(t){case"top":a.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":a.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":a.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":a.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return a}function Bpe(e){const{top:t,right:n,bottom:a,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:a},{x:r,y:a}]}function Hpe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function Vpe(e){const t=e.slice();return t.sort((n,a)=>n.x<a.x?-1:n.x>a.x?1:n.y<a.y?-1:n.y>a.y?1:0),Gpe(t)}function Gpe(e){if(e.length<=1)return e.slice();const t=[];for(let a=0;a<e.length;a++){const r=e[a];for(;t.length>=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let a=e.length-1;a>=0;a--){const r=e[a];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Wpe=TG,Kpe=NG,Zpe=CG,Ype=RG,qpe=AG,Xpe=DG;function YN({delayDuration:e=0,...t}){return f.jsx(Wpe,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Nt({...e}){return f.jsx(YN,{children:f.jsx(Kpe,{"data-slot":"tooltip",...e})})}function Ct({...e}){return f.jsx(Zpe,{"data-slot":"tooltip-trigger",...e})}function Rt({className:e,sideOffset:t=0,children:n,...a}){return f.jsx(Ype,{children:f.jsxs(qpe,{"data-slot":"tooltip-content",sideOffset:t,className:De("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...a,children:[n,f.jsx(Xpe,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class Jpe{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class XU{name="mcp_tool_execution";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId,success:t.success,duration:t.duration,error:t.error}}}class JU{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class QU{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class ez{name="mcp_chat_message";properties;constructor(t){this.properties={server_id:t.serverId,provider:t.provider,model:t.model,message_count:t.messageCount,tool_calls_count:t.toolCallsCount,success:t.success,execution_mode:t.executionMode,duration:t.duration,error:t.error}}}class Qpe{name="mcp_server_added";properties;constructor(t){this.properties={server_id:t.serverId,server_url:t.serverUrl,connection_type:t.connectionType,via_proxy:t.viaProxy}}}class eme{name="mcp_server_removed";properties;constructor(t){this.properties={server_id:t.serverId}}}class tme{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class nme{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function Sx(){try{return"0.13.2"}catch{return"0.0.0"}}var rme={};function xx(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class tz{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch{}}}function ws(e){return`mcp_inspector_telemetry_${e}`}class yr{static instance=null;POSTHOG_PROXY_URL="/inspector/api/tel/posthog";SCARF_PROXY_URL="/inspector/api/tel/scarf";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="inspector";constructor(){const t=xx(),n=this.isTelemetryDisabled();if(this._source=this.getStoredSource()||"inspector",n)this._posthogClient=null,this._scarfClient=null;else if(!t)this._posthogClient=null,this._scarfClient=null;else{try{this._posthogClient=new tz(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new tz(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(ws("disabled"))==="true"||typeof process<"u"&&rme?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(ws("source")):null}static getInstance(){return yr.instance||(yr.instance=new yr),yr.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(ws("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!xx())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(ws("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(ws("user_id"),n),this._currUserId=n}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(()=>{})}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}generateUserId(){const t=window.crypto;if(t){const n=new Uint8Array(16);t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;const a=Array.from(n).map(r=>r.toString(16).padStart(2,"0")).join("");return a.slice(0,8)+"-"+a.slice(8,12)+"-"+a.slice(12,16)+"-"+a.slice(16,20)+"-"+a.slice(20,32)}else return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=Math.random()*16|0;return(n==="x"?a:a&3|8).toString(16)})}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={event:t.name,user_id:this.userId,properties:{...t.properties,mcp_use_version:Sx(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=Sx(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,n.package="inspector",await this._scarfClient.logEvent(n)}catch{}}}async trackPackageDownload(t){if(this._scarfClient&&xx())try{const n=Sx();let a=!1,r=!1;const i=localStorage.getItem(ws("download_version"));if(i?n>i&&(a=!0,r=!1,localStorage.setItem(ws("download_version"),n)):(a=!0,r=!0,localStorage.setItem(ws("download_version"),n)),a){const s={...t||{}};s.mcp_use_version=n,s.user_id=this.userId,s.event="package_download",s.first_download=r,s.language="typescript",s.source=this._source,s.package="inspector",await this._scarfClient.logEvent(s)}}catch{}}async trackInspectorOpen(t){const n=new Jpe(t);await this.capture(n)}}const ame={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function ime({requestId:e,serverName:t,onViewDetails:n,onApprove:a,onDeny:r}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Sampling Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),n()},children:"View Details"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),a(ame)},children:"Approve"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),r()},children:"Deny"})]})]})}function ome({requestId:e,serverName:t,mode:n,message:a,url:r,onViewDetails:i,onOpenUrl:s,onCancel:c}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Elicitation Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["From ",t,": ",a]}),n==="url"&&r&&f.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono",children:r})]}),f.jsxs("div",{className:"flex gap-2 flex-wrap",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),i()},children:"View Details"}),n==="url"&&s&&f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),s()},children:"Open URL"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),c()},children:"Cancel"})]})]})}const cb=()=>{},ub=()=>{},db=()=>{},fb=()=>{},jG=y.createContext(null);function qN(){const e=y.use(jG);if(!e)throw new Error("useMcpContext must be used within a McpProvider");return e}function sme({url:e,name:t,proxyConfig:n,transportType:a,connectionId:r,onUpdate:i,onRemove:s}){const c=typeof window<"u"?new URL("/inspector/oauth/callback",window.location.origin).toString():"/inspector/oauth/callback";let u=e,d={};if(n?.proxyAddress){const $=new URL(n.proxyAddress),L=new URL(e);u=`${$.origin}${$.pathname}${L.pathname}${L.search}`,d["X-Target-URL"]=e}n?.customHeaders&&(d={...d,...n.customHeaders});const[m,h]=y.useState([]),g=y.useRef(0),[v,x]=y.useState([]),S=y.useRef(0),w=y.useMemo(()=>m.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[m]),E=y.useMemo(()=>v.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[v]),_=y.useRef(null),[k,C]=y.useState(!1),R=y.useRef(!1);y.useEffect(()=>{typeof window<"u"&&!R.current&&(R.current=!0,Jn(()=>import("./transport-wrapper-browser-BI4dDu3b.js"),[]).then($=>{_.current=$.wrapTransportForLogging,C(!0),console.log("[McpContext] Transport wrapper loaded")}).catch($=>{console.error("[McpContext] Failed to load transport wrapper:",$)}))},[]);const I=y.useMemo(()=>{if(!(!k||!_.current))return($,L)=>{const F=r;return console.log("[McpContext] Applying transport wrapper, serverId:",F,"from connector:",L),_.current($,F)}},[k,r]),A=`mcp-inspector-notifications-${r}`,O=500,[M,P]=y.useState([]);y.useEffect(()=>{try{const $=localStorage.getItem(A);if($){const L=JSON.parse($);Array.isArray(L)&&P(L)}}catch($){console.error("Failed to load notifications from localStorage:",$)}},[A]),y.useEffect(()=>{try{localStorage.setItem(A,JSON.stringify(M))}catch($){console.error("Failed to save notifications to localStorage:",$)}},[M,A]);const B=y.useCallback($=>{P(L=>L.map(F=>F.id===$?{...F,read:!0}:F))},[]),K=y.useCallback(()=>{P($=>$.map(L=>({...L,read:!0})))},[]),Q=y.useCallback(()=>{P([])},[]),ee=y.useCallback($=>{P(L=>{const F=[$,...L];return F.length>O?F.slice(0,O):F})},[]),ae=y.useCallback(($,L)=>{h(F=>{const W=F.find(ne=>ne.id===$);return W?(W.resolve(L),F.filter(ne=>ne.id!==$)):F})},[]),H=y.useCallback(($,L)=>{h(F=>{const W=F.find(ne=>ne.id===$);return W?(W.reject(new Error(L||"User rejected sampling request")),F.filter(ne=>ne.id!==$)):F})},[]),Z=y.useCallback(($,L)=>{x(F=>{const W=F.find(ne=>ne.id===$);return W?(W.resolve(L),F.filter(ne=>ne.id!==$)):F})},[]),G=y.useCallback(($,L)=>{x(F=>{const W=F.find(ne=>ne.id===$);return W?(W.reject(new Error(L||"User rejected elicitation request")),F.filter(ne=>ne.id!==$)):F})},[]),re=y.useCallback(async $=>new Promise((L,F)=>{const W=`sampling-${g.current++}`,ne={id:W,request:{params:$},timestamp:Date.now(),serverName:t,resolve:L,reject:F};h(le=>[...le,ne]),typeof window<"u"&&Jn(async()=>{const{toast:le}=await Promise.resolve().then(()=>lz);return{toast:le}},void 0).then(({toast:le})=>{const ue=le(f.jsx(ime,{requestId:W,serverName:t,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-sampling",{detail:{requestId:W}});window.dispatchEvent(X),le.dismiss(ue)},onApprove:X=>{h(q=>{const oe=q.find(me=>me.id===W);return oe?(oe.resolve(X),le.success("Sampling request approved"),q.filter(me=>me.id!==W)):q}),le.dismiss(ue)},onDeny:()=>{h(X=>{const q=X.find(oe=>oe.id===W);return q?(q.reject(new Error("User denied sampling request from toast")),le.error("Sampling request denied"),X.filter(oe=>oe.id!==W)):X}),le.dismiss(ue)}}),{duration:5e3})})}),[t]),te=y.useCallback(async $=>new Promise((L,F)=>{const W=`elicitation-${S.current++}`,ne={id:W,request:$,timestamp:Date.now(),serverName:t,resolve:L,reject:F};x(le=>[...le,ne]),typeof window<"u"&&Jn(async()=>{const{toast:le}=await Promise.resolve().then(()=>lz);return{toast:le}},void 0).then(({toast:le})=>{const ue=le(f.jsx(ome,{requestId:W,serverName:t,mode:$.mode||"form",message:$.message,url:$.mode==="url"?$.url:void 0,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-elicitation",{detail:{requestId:W}});window.dispatchEvent(X),le.dismiss(ue)},onOpenUrl:$.mode==="url"?()=>{window.open($.url,"_blank"),le.dismiss(ue)}:void 0,onCancel:()=>{x(X=>{const q=X.find(oe=>oe.id===W);return q?(q.reject(new Error("User cancelled elicitation request from toast")),le.error("Elicitation request cancelled"),X.filter(oe=>oe.id!==W)):X}),le.dismiss(ue)}}),{duration:5e3})})}),[t]),j=SN({url:u,callbackUrl:c,timeout:5e3,customHeaders:Object.keys(d).length>0?d:void 0,transportType:a||"http",preventAutoAuth:!0,useRedirectFlow:!0,enabled:k,wrapTransport:I,onNotification:$=>{ee({id:globalThis.crypto.randomUUID(),method:$.method,params:$.params,timestamp:Date.now(),read:!1})},samplingCallback:re,onElicitation:te}),V=y.useRef(i),z=y.useRef(null);return y.useEffect(()=>{V.current=i},[i]),y.useEffect(()=>{if(typeof queueMicrotask<"u")queueMicrotask(()=>{j.state==="ready"&&j.serverInfo&&console.log("[McpContext] Server info available:",j.serverInfo);const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:Q,pendingSamplingRequests:w,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))});else{const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:Q,pendingSamplingRequests:w,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))}},[e,t,a,n,d,r,j.state,j.tools,j.resources,j.prompts,j.error,j.authUrl,j.serverInfo,j.capabilities,j.client,M,B,K,Q,j.callTool,j.readResource,j.listPrompts,j.getPrompt,j.authenticate,j.retry,j.clearStorage,m,ae,H,E,Z,G]),null}function lme({children:e}){const[t,n]=y.useState([]),[a,r]=y.useState(!1),[i,s]=y.useState(!0),[c,u]=y.useState([]);y.useEffect(()=>{try{const w=localStorage.getItem("mcp-inspector-connections");if(w){const _=JSON.parse(w);Array.isArray(_)&&(u(_),n(_.map(k=>({id:k.id||k.url,url:k.url,name:k.name||"MCP Server",state:"discovering",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:k.proxyConfig?.customHeaders,transportType:k.transportType,proxyConfig:k.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}))))}const E=localStorage.getItem("mcp-inspector-auto-connect");E!==null&&s(E==="true")}catch(w){console.error("Failed to load connections from localStorage:",w)}finally{r(!0)}},[]),y.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-connections",JSON.stringify(c))},[c,a]),y.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-auto-connect",String(i))},[i,a]);const d=y.useCallback((w,E,_,k)=>{const C=c.find(A=>A.url===w),R=t.find(A=>A.url===w);if(C&&R){if(JSON.stringify(C.proxyConfig)!==JSON.stringify(_)&&_){u(O=>O.filter(M=>M.url!==w)),n(O=>O.filter(M=>M.url!==w)),setTimeout(()=>{const O={id:w,url:w,name:E||C.name||"MCP Server",proxyConfig:_,transportType:k||C.transportType};u(M=>[...M,O]),n(M=>[...M,{id:w,url:w,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k||C.transportType,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},10);return}return}if(C&&!R){(_||k)&&u(A=>A.map(O=>O.url===w?{...O,proxyConfig:_||O.proxyConfig,transportType:k||O.transportType,name:E||O.name}:O)),n(A=>[...A,{id:C.id||w,url:w,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders||C.proxyConfig?.customHeaders,transportType:k||C.transportType,proxyConfig:_||C.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}]);return}const I={id:w,url:w,name:E||"MCP Server",proxyConfig:_,transportType:k};u(A=>[...A,I]),n(A=>[...A,{id:w,url:w,name:E||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},[c,t]),m=y.useCallback(w=>{const E=t.find(k=>k.id===w);E&&(console.log(`[McpContext] Cleaning up connection: ${w}`),E.disconnect&&(console.log(`[McpContext] Disconnecting from server: ${w}`),E.disconnect()),E.clearStorage&&(console.log(`[McpContext] Clearing OAuth storage for connection: ${w}`),E.clearStorage())),u(k=>k.filter(C=>C.id!==w)),n(k=>k.filter(C=>C.id!==w));const _=localStorage.getItem("mcp-inspector-connections");if(_)try{const C=JSON.parse(_).filter(R=>(R.id||R.url)!==w);localStorage.setItem("mcp-inspector-connections",JSON.stringify(C))}catch(k){console.error("Failed to update localStorage on remove:",k)}yr.getInstance().capture(new eme({serverId:w}))},[t]),h=y.useCallback((w,E)=>{u(_=>_.map(k=>k.id===w||k.url===w?{...k,...E}:k)),n(_=>_.map(k=>k.id===w?{...k,...E}:k))},[]),g=y.useCallback(w=>{n(E=>{const _=E.findIndex(R=>R.id===w.id);if(_===-1)return E;const k=E[_];if(k.state===w.state&&k.tools===w.tools&&k.resources===w.resources&&k.prompts===w.prompts&&k.error===w.error&&k.serverInfo===w.serverInfo&&k.client===w.client&&k.notifications===w.notifications&&k.unreadNotificationCount===w.unreadNotificationCount&&k.pendingSamplingRequests.length===w.pendingSamplingRequests.length&&k.pendingElicitationRequests.length===w.pendingElicitationRequests.length)return E;const C=[...E];return C[_]=w,C})},[]),v=y.useCallback(w=>{console.log("Connect requested for:",w)},[]),x=y.useCallback(w=>{console.log("Disconnect requested for:",w)},[]),S=y.useMemo(()=>({connections:t,addConnection:d,removeConnection:m,updateConnectionConfig:h,autoConnect:i,setAutoConnect:s,connectServer:v,disconnectServer:x,configLoaded:a}),[t,d,m,h,i,v,x,a]);return f.jsxs(jG.Provider,{value:S,children:[e,a&&i&&c.map(w=>{const E=`${w.id||w.url}-${w.proxyConfig?.proxyAddress?"proxy":"direct"}`;return console.warn("[McpContext] Rendering McpConnectionWrapper with key:",E,"proxyConfig:",w.proxyConfig),f.jsx(sme,{url:w.url,name:w.name,proxyConfig:w.proxyConfig,transportType:w.transportType,connectionId:w.id||w.url,onUpdate:g,onRemove:()=>m(w.id||w.url)},E)})]})}const cme=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ume=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),nz=e=>{const t=ume(e);return t.charAt(0).toUpperCase()+t.slice(1)},$G=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),dme=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var fme={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const pme=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:s,...c},u)=>y.createElement("svg",{ref:u,...fme,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:$G("lucide",r),...!i&&!dme(c)&&{"aria-hidden":"true"},...c},[...s.map(([d,m])=>y.createElement(d,m)),...Array.isArray(i)?i:[i]]));const et=(e,t)=>{const n=y.forwardRef(({className:a,...r},i)=>y.createElement(pme,{ref:i,iconNode:t,className:$G(`lucide-${cme(nz(e))}`,`lucide-${e}`,a),...r}));return n.displayName=nz(e),n};const mme=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],hme=et("arrow-down-to-line",mme);const gme=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],bme=et("arrow-up-from-line",gme);const vme=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],yme=et("arrow-up",vme);const wme=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],XN=et("bell",wme);const Sme=[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]],LG=et("brush",Sme);const xme=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],_me=et("bug",xme);const Eme=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ra=et("check",Eme);const kme=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ac=et("chevron-down",kme);const Tme=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Xy=et("chevron-left",Tme);const Nme=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],MG=et("chevron-right",Nme);const Cme=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Rme=et("chevron-up",Cme);const Ame=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],Ime=et("chevrons-up-down",Ame);const Ome=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],rz=et("circle-minus",Ome);const Dme=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fd=et("clock",Dme);const jme=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],JN=et("code",jme);const $me=[["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}]],Lme=et("cog",$me);const Mme=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],Pme=et("command",Mme);const Ume=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Lr=et("copy",Ume);const zme=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Jy=et("database",zme);const Fme=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Lm=et("download",Fme);const Bme=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Hme=et("ellipsis-vertical",Bme);const Vme=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],q_=et("external-link",Vme);const Gme=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],PG=et("eye-off",Gme);const Wme=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],X_=et("eye",Wme);const Kme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Zme=et("file-code",Kme);const Yme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],qme=et("file-image",Yme);const Xme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],QN=et("file-text",Xme);const Jme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Qme=et("file",Jme);const ehe=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],the=et("folder-open",ehe);const nhe=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],rhe=et("globe",nhe);const ahe=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],ihe=et("grip-vertical",ahe);const ohe=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],UG=et("hash",ohe);const she=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Av=et("history",she);const lhe=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],zG=et("key",lhe);const che=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],zs=et("loader-circle",che);const uhe=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],eC=et("maximize-2",uhe);const dhe=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],tC=et("maximize",dhe);const fhe=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],phe=et("message-circle",fhe);const mhe=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Hp=et("message-square",mhe);const hhe=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],ghe=et("minimize",hhe);const bhe=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],az=et("monitor",bhe);const vhe=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],yhe=et("moon",vhe);const whe=[["path",{d:"M2 10h6V4",key:"zwrco"}],["path",{d:"m2 4 6 6",key:"ug085t"}],["path",{d:"M21 10V7a2 2 0 0 0-2-2h-7",key:"git5jr"}],["path",{d:"M3 14v2a2 2 0 0 0 2 2h3",key:"1f7fh3"}],["rect",{x:"12",y:"14",width:"10",height:"7",rx:"1",key:"1wjs3o"}]],She=et("picture-in-picture",whe);const xhe=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],FG=et("play",xhe);const _he=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],BG=et("plus",_he);const Ehe=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],iz=et("rotate-ccw",Ehe);const khe=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],nC=et("save",khe);const The=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Pd=et("search",The);const Nhe=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Che=et("send",Nhe);const Rhe=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Ahe=et("server",Rhe);const Ihe=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Eu=et("settings",Ihe);const Ohe=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Dhe=et("shield",Ohe);const jhe=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],$he=et("sparkles",jhe);const Lhe=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],HG=et("square-check-big",Lhe);const Mhe=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],Phe=et("square-pen",Mhe);const Uhe=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]],zhe=et("sun-dim",Uhe);const Fhe=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],_x=et("terminal",Fhe);const Bhe=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Fs=et("trash-2",Bhe);const Hhe=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Vhe=et("trash",Hhe);const Ghe=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Wl=et("wrench",Ghe);const Whe=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ji=et("x",Whe);const Khe=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Vp=et("zap",Khe);function Zhe(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const Yhe=e=>{switch(e){case"success":return Jhe;case"info":return ege;case"warning":return Qhe;case"error":return tge;default:return null}},qhe=Array(12).fill(0),Xhe=({visible:e,className:t})=>ce.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ce.createElement("div",{className:"sonner-spinner"},qhe.map((n,a)=>ce.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${a}`})))),Jhe=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Qhe=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),ege=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),tge=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),nge=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ce.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ce.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),rge=()=>{const[e,t]=ce.useState(document.hidden);return ce.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let J_=1;class age{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:a,...r}=t,i=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:J_++,s=this.toasts.find(u=>u.id===i),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),s?this.toasts=this.toasts.map(u=>u.id===i?(this.publish({...u,...t,id:i,title:a}),{...u,...t,id:i,dismissible:c,title:a}):u):this.addToast({title:a,...r,dismissible:c,id:i}),i},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(a=>a({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let a;n.loading!==void 0&&(a=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const r=Promise.resolve(t instanceof Function?t():t);let i=a!==void 0,s;const c=r.then(async d=>{if(s=["resolve",d],ce.isValidElement(d))i=!1,this.create({id:a,type:"default",message:d});else if(oge(d)&&!d.ok){i=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(d instanceof Error){i=!1;const h=typeof n.error=="function"?await n.error(d):n.error,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(n.success!==void 0){i=!1;const h=typeof n.success=="function"?await n.success(d):n.success,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:a,type:"success",description:g,...x})}}).catch(async d=>{if(s=["reject",d],n.error!==void 0){i=!1;const m=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description,v=typeof m=="object"&&!ce.isValidElement(m)?m:{message:m};this.create({id:a,type:"error",description:h,...v})}}).finally(()=>{i&&(this.dismiss(a),a=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,m)=>c.then(()=>s[0]==="reject"?m(s[1]):d(s[1])).catch(m));return typeof a!="string"&&typeof a!="number"?{unwrap:u}:Object.assign(a,{unwrap:u})},this.custom=(t,n)=>{const a=n?.id||J_++;return this.create({jsx:t(a),id:a,...n}),a},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ga=new age,ige=(e,t)=>{const n=t?.id||J_++;return ga.addToast({title:e,...t,id:n}),n},oge=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",sge=ige,lge=()=>ga.toasts,cge=()=>ga.getActiveToasts(),Xt=Object.assign(sge,{success:ga.success,info:ga.info,warning:ga.warning,error:ga.error,custom:ga.custom,message:ga.message,promise:ga.promise,dismiss:ga.dismiss,loading:ga.loading},{getHistory:lge,getToasts:cge});Zhe("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function pb(e){return e.label!==void 0}const uge=3,dge="24px",fge="16px",oz=4e3,pge=356,mge=14,hge=45,gge=200;function Ui(...e){return e.filter(Boolean).join(" ")}function bge(e){const[t,n]=e.split("-"),a=[];return t&&a.push(t),n&&a.push(n),a}const vge=e=>{var t,n,a,r,i,s,c,u,d;const{invert:m,toast:h,unstyled:g,interacting:v,setHeights:x,visibleToasts:S,heights:w,index:E,toasts:_,expanded:k,removeToast:C,defaultRichColors:R,closeButton:I,style:A,cancelButtonStyle:O,actionButtonStyle:M,className:P="",descriptionClassName:B="",duration:K,position:Q,gap:ee,expandByDefault:ae,classNames:H,icons:Z,closeButtonAriaLabel:G="Close toast"}=e,[re,te]=ce.useState(null),[j,V]=ce.useState(null),[z,$]=ce.useState(!1),[L,F]=ce.useState(!1),[W,ne]=ce.useState(!1),[le,ue]=ce.useState(!1),[X,q]=ce.useState(!1),[oe,me]=ce.useState(0),[ie,Ne]=ce.useState(0),He=ce.useRef(h.duration||K||oz),ye=ce.useRef(null),Se=ce.useRef(null),Pe=E===0,fe=E+1<=S,Ae=h.type,Me=h.dismissible!==!1,_e=h.className||"",rt=h.descriptionClassName||"",nt=ce.useMemo(()=>w.findIndex(Ke=>Ke.toastId===h.id)||0,[w,h.id]),ct=ce.useMemo(()=>{var Ke;return(Ke=h.closeButton)!=null?Ke:I},[h.closeButton,I]),bt=ce.useMemo(()=>h.duration||K||oz,[h.duration,K]),ut=ce.useRef(0),nn=ce.useRef(0),Qn=ce.useRef(0),ot=ce.useRef(null),[Ve,Le]=Q.split("-"),Ee=ce.useMemo(()=>w.reduce((Ke,Ze,mt)=>mt>=nt?Ke:Ke+Ze.height,0),[w,nt]),je=rge(),Fe=h.invert||m,We=Ae==="loading";nn.current=ce.useMemo(()=>nt*ee+Ee,[nt,Ee]),ce.useEffect(()=>{He.current=bt},[bt]),ce.useEffect(()=>{$(!0)},[]),ce.useEffect(()=>{const Ke=Se.current;if(Ke){const Ze=Ke.getBoundingClientRect().height;return Ne(Ze),x(mt=>[{toastId:h.id,height:Ze,position:h.position},...mt]),()=>x(mt=>mt.filter(At=>At.toastId!==h.id))}},[x,h.id]),ce.useLayoutEffect(()=>{if(!z)return;const Ke=Se.current,Ze=Ke.style.height;Ke.style.height="auto";const mt=Ke.getBoundingClientRect().height;Ke.style.height=Ze,Ne(mt),x(At=>At.find(cn=>cn.toastId===h.id)?At.map(cn=>cn.toastId===h.id?{...cn,height:mt}:cn):[{toastId:h.id,height:mt,position:h.position},...At])},[z,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const Je=ce.useCallback(()=>{F(!0),me(nn.current),x(Ke=>Ke.filter(Ze=>Ze.toastId!==h.id)),setTimeout(()=>{C(h)},gge)},[h,C,x,nn]);ce.useEffect(()=>{if(h.promise&&Ae==="loading"||h.duration===1/0||h.type==="loading")return;let Ke;return k||v||je?(()=>{if(Qn.current<ut.current){const At=new Date().getTime()-ut.current;He.current=He.current-At}Qn.current=new Date().getTime()})():He.current!==1/0&&(ut.current=new Date().getTime(),Ke=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),Je()},He.current)),()=>clearTimeout(Ke)},[k,v,h,Ae,je,Je]),ce.useEffect(()=>{h.delete&&(Je(),h.onDismiss==null||h.onDismiss.call(h,h))},[Je,h.delete]);function St(){var Ke;if(Z?.loading){var Ze;return ce.createElement("div",{className:Ui(H?.loader,h==null||(Ze=h.classNames)==null?void 0:Ze.loader,"sonner-loader"),"data-visible":Ae==="loading"},Z.loading)}return ce.createElement(Xhe,{className:Ui(H?.loader,h==null||(Ke=h.classNames)==null?void 0:Ke.loader),visible:Ae==="loading"})}const ht=h.icon||Z?.[Ae]||Yhe(Ae);var Mt,rn;return ce.createElement("li",{tabIndex:0,ref:Se,className:Ui(P,_e,H?.toast,h==null||(t=h.classNames)==null?void 0:t.toast,H?.default,H?.[Ae],h==null||(n=h.classNames)==null?void 0:n[Ae]),"data-sonner-toast":"","data-rich-colors":(Mt=h.richColors)!=null?Mt:R,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":z,"data-promise":!!h.promise,"data-swiped":X,"data-removed":L,"data-visible":fe,"data-y-position":Ve,"data-x-position":Le,"data-index":E,"data-front":Pe,"data-swiping":W,"data-dismissible":Me,"data-type":Ae,"data-invert":Fe,"data-swipe-out":le,"data-swipe-direction":j,"data-expanded":!!(k||ae&&z),"data-testid":h.testId,style:{"--index":E,"--toasts-before":E,"--z-index":_.length-E,"--offset":`${L?oe:nn.current}px`,"--initial-height":ae?"auto":`${ie}px`,...A,...h.style},onDragEnd:()=>{ne(!1),te(null),ot.current=null},onPointerDown:Ke=>{Ke.button!==2&&(We||!Me||(ye.current=new Date,me(nn.current),Ke.target.setPointerCapture(Ke.pointerId),Ke.target.tagName!=="BUTTON"&&(ne(!0),ot.current={x:Ke.clientX,y:Ke.clientY})))},onPointerUp:()=>{var Ke,Ze,mt;if(le||!Me)return;ot.current=null;const At=Number(((Ke=Se.current)==null?void 0:Ke.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),er=Number(((Ze=Se.current)==null?void 0:Ze.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),cn=new Date().getTime()-((mt=ye.current)==null?void 0:mt.getTime()),Vn=re==="x"?At:er,$n=Math.abs(Vn)/cn;if(Math.abs(Vn)>=hge||$n>.11){me(nn.current),h.onDismiss==null||h.onDismiss.call(h,h),V(re==="x"?At>0?"right":"left":er>0?"down":"up"),Je(),ue(!0);return}else{var yn,pn;(yn=Se.current)==null||yn.style.setProperty("--swipe-amount-x","0px"),(pn=Se.current)==null||pn.style.setProperty("--swipe-amount-y","0px")}q(!1),ne(!1),te(null)},onPointerMove:Ke=>{var Ze,mt,At;if(!ot.current||!Me||((Ze=window.getSelection())==null?void 0:Ze.toString().length)>0)return;const cn=Ke.clientY-ot.current.y,Vn=Ke.clientX-ot.current.x;var $n;const yn=($n=e.swipeDirections)!=null?$n:bge(Q);!re&&(Math.abs(Vn)>1||Math.abs(cn)>1)&&te(Math.abs(Vn)>Math.abs(cn)?"x":"y");let pn={x:0,y:0};const oa=Qt=>1/(1.5+Math.abs(Qt)/20);if(re==="y"){if(yn.includes("top")||yn.includes("bottom"))if(yn.includes("top")&&cn<0||yn.includes("bottom")&&cn>0)pn.y=cn;else{const Qt=cn*oa(cn);pn.y=Math.abs(Qt)<Math.abs(cn)?Qt:cn}}else if(re==="x"&&(yn.includes("left")||yn.includes("right")))if(yn.includes("left")&&Vn<0||yn.includes("right")&&Vn>0)pn.x=Vn;else{const Qt=Vn*oa(Vn);pn.x=Math.abs(Qt)<Math.abs(Vn)?Qt:Vn}(Math.abs(pn.x)>0||Math.abs(pn.y)>0)&&q(!0),(mt=Se.current)==null||mt.style.setProperty("--swipe-amount-x",`${pn.x}px`),(At=Se.current)==null||At.style.setProperty("--swipe-amount-y",`${pn.y}px`)}},ct&&!h.jsx&&Ae!=="loading"?ce.createElement("button",{"aria-label":G,"data-disabled":We,"data-close-button":!0,onClick:We||!Me?()=>{}:()=>{Je(),h.onDismiss==null||h.onDismiss.call(h,h)},className:Ui(H?.closeButton,h==null||(a=h.classNames)==null?void 0:a.closeButton)},(rn=Z?.close)!=null?rn:nge):null,(Ae||h.icon||h.promise)&&h.icon!==null&&(Z?.[Ae]!==null||h.icon)?ce.createElement("div",{"data-icon":"",className:Ui(H?.icon,h==null||(r=h.classNames)==null?void 0:r.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||St():null,h.type!=="loading"?ht:null):null,ce.createElement("div",{"data-content":"",className:Ui(H?.content,h==null||(i=h.classNames)==null?void 0:i.content)},ce.createElement("div",{"data-title":"",className:Ui(H?.title,h==null||(s=h.classNames)==null?void 0:s.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?ce.createElement("div",{"data-description":"",className:Ui(B,rt,H?.description,h==null||(c=h.classNames)==null?void 0:c.description)},typeof h.description=="function"?h.description():h.description):null),ce.isValidElement(h.cancel)?h.cancel:h.cancel&&pb(h.cancel)?ce.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||O,onClick:Ke=>{pb(h.cancel)&&Me&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,Ke),Je())},className:Ui(H?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,ce.isValidElement(h.action)?h.action:h.action&&pb(h.action)?ce.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||M,onClick:Ke=>{pb(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,Ke),!Ke.defaultPrevented&&Je())},className:Ui(H?.actionButton,h==null||(d=h.classNames)==null?void 0:d.actionButton)},h.action.label):null)};function sz(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function yge(e,t){const n={};return[e,t].forEach((a,r)=>{const i=r===1,s=i?"--mobile-offset":"--offset",c=i?fge:dge;function u(d){["top","right","bottom","left"].forEach(m=>{n[`${s}-${m}`]=typeof d=="number"?`${d}px`:d})}typeof a=="number"||typeof a=="string"?u(a):typeof a=="object"?["top","right","bottom","left"].forEach(d=>{a[d]===void 0?n[`${s}-${d}`]=c:n[`${s}-${d}`]=typeof a[d]=="number"?`${a[d]}px`:a[d]}):u(c)}),n}const VG=ce.forwardRef(function(t,n){const{id:a,invert:r,position:i="bottom-right",hotkey:s=["altKey","KeyT"],expand:c,closeButton:u,className:d,offset:m,mobileOffset:h,theme:g="light",richColors:v,duration:x,style:S,visibleToasts:w=uge,toastOptions:E,dir:_=sz(),gap:k=mge,icons:C,containerAriaLabel:R="Notifications"}=t,[I,A]=ce.useState([]),O=ce.useMemo(()=>a?I.filter(z=>z.toasterId===a):I.filter(z=>!z.toasterId),[I,a]),M=ce.useMemo(()=>Array.from(new Set([i].concat(O.filter(z=>z.position).map(z=>z.position)))),[O,i]),[P,B]=ce.useState([]),[K,Q]=ce.useState(!1),[ee,ae]=ce.useState(!1),[H,Z]=ce.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),G=ce.useRef(null),re=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),te=ce.useRef(null),j=ce.useRef(!1),V=ce.useCallback(z=>{A($=>{var L;return(L=$.find(F=>F.id===z.id))!=null&&L.delete||ga.dismiss(z.id),$.filter(({id:F})=>F!==z.id)})},[]);return ce.useEffect(()=>ga.subscribe(z=>{if(z.dismiss){requestAnimationFrame(()=>{A($=>$.map(L=>L.id===z.id?{...L,delete:!0}:L))});return}setTimeout(()=>{F9.flushSync(()=>{A($=>{const L=$.findIndex(F=>F.id===z.id);return L!==-1?[...$.slice(0,L),{...$[L],...z},...$.slice(L+1)]:[z,...$]})})})}),[I]),ce.useEffect(()=>{if(g!=="system"){Z(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;const z=window.matchMedia("(prefers-color-scheme: dark)");try{z.addEventListener("change",({matches:$})=>{Z($?"dark":"light")})}catch{z.addListener(({matches:L})=>{try{Z(L?"dark":"light")}catch(F){console.error(F)}})}},[g]),ce.useEffect(()=>{I.length<=1&&Q(!1)},[I]),ce.useEffect(()=>{const z=$=>{var L;if(s.every(ne=>$[ne]||$.code===ne)){var W;Q(!0),(W=G.current)==null||W.focus()}$.code==="Escape"&&(document.activeElement===G.current||(L=G.current)!=null&&L.contains(document.activeElement))&&Q(!1)};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[s]),ce.useEffect(()=>{if(G.current)return()=>{te.current&&(te.current.focus({preventScroll:!0}),te.current=null,j.current=!1)}},[G.current]),ce.createElement("section",{ref:n,"aria-label":`${R} ${re}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((z,$)=>{var L;const[F,W]=z.split("-");return O.length?ce.createElement("ol",{key:z,dir:_==="auto"?sz():_,tabIndex:-1,ref:G,className:d,"data-sonner-toaster":!0,"data-sonner-theme":H,"data-y-position":F,"data-x-position":W,style:{"--front-toast-height":`${((L=P[0])==null?void 0:L.height)||0}px`,"--width":`${pge}px`,"--gap":`${k}px`,...S,...yge(m,h)},onBlur:ne=>{j.current&&!ne.currentTarget.contains(ne.relatedTarget)&&(j.current=!1,te.current&&(te.current.focus({preventScroll:!0}),te.current=null))},onFocus:ne=>{ne.target instanceof HTMLElement&&ne.target.dataset.dismissible==="false"||j.current||(j.current=!0,te.current=ne.relatedTarget)},onMouseEnter:()=>Q(!0),onMouseMove:()=>Q(!0),onMouseLeave:()=>{ee||Q(!1)},onDragEnd:()=>Q(!1),onPointerDown:ne=>{ne.target instanceof HTMLElement&&ne.target.dataset.dismissible==="false"||ae(!0)},onPointerUp:()=>ae(!1)},O.filter(ne=>!ne.position&&$===0||ne.position===z).map((ne,le)=>{var ue,X;return ce.createElement(vge,{key:ne.id,icons:C,index:le,toast:ne,defaultRichColors:v,duration:(ue=E?.duration)!=null?ue:x,className:E?.className,descriptionClassName:E?.descriptionClassName,invert:r,visibleToasts:w,closeButton:(X=E?.closeButton)!=null?X:u,interacting:ee,position:z,style:E?.style,unstyled:E?.unstyled,classNames:E?.classNames,cancelButtonStyle:E?.cancelButtonStyle,actionButtonStyle:E?.actionButtonStyle,closeButtonAriaLabel:E?.closeButtonAriaLabel,removeToast:V,toasts:O.filter(q=>q.position==ne.position),heights:P.filter(q=>q.position==ne.position),setHeights:B,expandByDefault:c,gap:k,expanded:K,swipeDirections:t.swipeDirections})})):null}))}),lz=Object.freeze(Object.defineProperty({__proto__:null,Toaster:VG,toast:Xt},Symbol.toStringTag,{value:"Module"}));var Qy="Dialog",[GG]=Ii(Qy),[wge,Oi]=GG(Qy),WG=e=>{const{__scopeDialog:t,children:n,open:a,defaultOpen:r,onOpenChange:i,modal:s=!0}=e,c=y.useRef(null),u=y.useRef(null),[d,m]=Po({prop:a,defaultProp:r??!1,onChange:i,caller:Qy});return f.jsx(wge,{scope:t,triggerRef:c,contentRef:u,contentId:$r(),titleId:$r(),descriptionId:$r(),open:d,onOpenChange:m,onOpenToggle:y.useCallback(()=>m(h=>!h),[m]),modal:s,children:n})};WG.displayName=Qy;var KG="DialogTrigger",ZG=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(KG,n),i=Jt(t,r.triggerRef);return f.jsx(Et.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":iC(r.open),...a,ref:i,onClick:Ge(e.onClick,r.onOpenToggle)})});ZG.displayName=KG;var rC="DialogPortal",[Sge,YG]=GG(rC,{forceMount:void 0}),qG=e=>{const{__scopeDialog:t,forceMount:n,children:a,container:r}=e,i=Oi(rC,t);return f.jsx(Sge,{scope:t,forceMount:n,children:y.Children.map(a,s=>f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:s})}))})};qG.displayName=rC;var Iv="DialogOverlay",XG=y.forwardRef((e,t)=>{const n=YG(Iv,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Iv,e.__scopeDialog);return i.modal?f.jsx(Ua,{present:a||i.open,children:f.jsx(_ge,{...r,ref:t})}):null});XG.displayName=Iv;var xge=Vl("DialogOverlay.RemoveScroll"),_ge=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(Iv,n);return f.jsx(Om,{as:xge,allowPinchZoom:!0,shards:[r.contentRef],children:f.jsx(Et.div,{"data-state":iC(r.open),...a,ref:t,style:{pointerEvents:"auto",...a.style}})})}),Kl="DialogContent",JG=y.forwardRef((e,t)=>{const n=YG(Kl,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Kl,e.__scopeDialog);return f.jsx(Ua,{present:a||i.open,children:i.modal?f.jsx(Ege,{...r,ref:t}):f.jsx(kge,{...r,ref:t})})});JG.displayName=Kl;var Ege=y.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=y.useRef(null),r=Jt(t,n.contentRef,a);return y.useEffect(()=>{const i=a.current;if(i)return By(i)},[]),f.jsx(QG,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ge(e.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ge(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&i.preventDefault()}),onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault())})}),kge=y.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=y.useRef(!1),r=y.useRef(!1);return f.jsx(QG,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(a.current||n.triggerRef.current?.focus(),i.preventDefault()),a.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(a.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=i.target;n.triggerRef.current?.contains(s)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),QG=y.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:a,onOpenAutoFocus:r,onCloseAutoFocus:i,...s}=e,c=Oi(Kl,n),u=y.useRef(null),d=Jt(t,u);return jy(),f.jsxs(f.Fragment,{children:[f.jsx(Cm,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:r,onUnmountAutoFocus:i,children:f.jsx(Dd,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":iC(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),f.jsxs(f.Fragment,{children:[f.jsx(Tge,{titleId:c.titleId}),f.jsx(Cge,{contentRef:u,descriptionId:c.descriptionId})]})]})}),aC="DialogTitle",e7=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(aC,n);return f.jsx(Et.h2,{id:r.titleId,...a,ref:t})});e7.displayName=aC;var t7="DialogDescription",n7=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(t7,n);return f.jsx(Et.p,{id:r.descriptionId,...a,ref:t})});n7.displayName=t7;var r7="DialogClose",a7=y.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(r7,n);return f.jsx(Et.button,{type:"button",...a,ref:t,onClick:Ge(e.onClick,()=>r.onOpenChange(!1))})});a7.displayName=r7;function iC(e){return e?"open":"closed"}var i7="DialogTitleWarning",[tNe,o7]=pce(i7,{contentName:Kl,titleName:aC,docsSlug:"dialog"}),Tge=({titleId:e})=>{const t=o7(i7),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
94
94
|
|
|
95
95
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
96
96
|
|
|
@@ -1657,7 +1657,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1657
1657
|
<\/script>
|
|
1658
1658
|
</body>
|
|
1659
1659
|
</html>`,fY=1,b2=2,pY=3,v2=4,mY=5,y2=Symbol.for("quilt.threads.serialize"),gke=Symbol.for("quilt.threads.transferable");class bke extends AbortController{constructor(...t){super();const n=t.find(a=>a.aborted);if(n)this.abort(n.reason);else{const a=i=>this.abort(i.target.reason),r={signal:this.signal};for(const i of t)i.addEventListener("abort",a,r)}}}class w2 extends Error{constructor(){super("You attempted to call a function on a closed thread.")}}let vke="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function hY(e=21){let t="",n=crypto.getRandomValues(new Uint8Array(e));for(let a=0;a<e;a++)t+=vke[63&n[a]];return t}var sp,iu,lp,Yb,ek,gY;class yke{constructor(){hi(this,ek),hi(this,sp,new Map),hi(this,iu,new Map),hi(this,lp,new Map),hi(this,Yb,new WeakMap)}get(t){return Pn(this,iu).get(t)}release(t){const n=Pn(this,iu).get(t);return n&&(Pn(this,iu).delete(t),Pn(this,sp).delete(n)),!!n}serialize(t){let n=Pn(this,sp).get(t);return n==null&&(n=hY(),Pn(this,sp).set(t,n),Pn(this,iu).set(n,t)),n}deserialize(t,n){var a,r;let i=(a=Pn(this,lp).get(t))==null?void 0:a.deref();return i||(i=(...s)=>{if(!Pn(this,lp).has(t))throw new Error("You attempted to call a function that was already revoked.");return n.call((c,u,d)=>{n.messages.send([pY,c,t,u],d)},s)},(r=Rr(this,ek,gY).call(this,n))==null||r.register(i,t),Pn(this,lp).set(t,new WeakRef(i)),i)}}sp=new WeakMap,iu=new WeakMap,lp=new WeakMap,Yb=new WeakMap,ek=new WeakSet,gY=function(e){let t=Pn(this,Yb).get(e);if(!(typeof FinalizationRegistry>"u"))return t||(t=new FinalizationRegistry(n=>{e.messages.send([mY,n])}),Pn(this,Yb).set(e,t)),t};function wke(e){return e!=null&&(Symbol.asyncIterator in e||Symbol.iterator in e)&&typeof e.next=="function"}function S2(e){if(e==null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t==null||t===Object.prototype}const Xx="_@f",x2="_@i";var Np,Cp,Ya,qb,Es;class Ske{constructor(t){hi(this,Ya),hi(this,Np),hi(this,Cp),JE(this,Np,t?.serialize),JE(this,Cp,t?.deserialize)}serialize(t,n,a){return Rr(this,Ya,qb).call(this,t,n,a)}deserialize(t,n){return Rr(this,Ya,Es).call(this,t,n)}}Np=new WeakMap,Cp=new WeakMap,Ya=new WeakSet,qb=function(e,t,n,a=new Map,r=!1){if(e==null)return e;if(a.has(e))return a.get(e);if(a.set(e,void 0),typeof e=="object"){if(Pn(this,Np)&&!r){const c=Pn(this,Np).call(this,e,u=>Rr(this,Ya,qb).call(this,u,t,n,a,!0),t,n);if(c!==void 0)return a.set(e,c),c}if(e[gke])return n?.push(e),a.set(e,e),e;const i=c=>Rr(this,Ya,qb).call(this,c,t,n,a);if(typeof e[y2]=="function"){const c=e[y2]({serialize:i});return a.set(e,c),c}if(Array.isArray(e)){const c=e.map(u=>i(u));return a.set(e,c),c}if(e instanceof Map){const c=[...e.entries()].map(([d,m])=>[i(d),i(m)]),u=new Map(c);return a.set(e,u),u}if(e instanceof Set){const c=[...e].map(d=>i(d)),u=new Set(c);return a.set(e,u),u}const s=wke(e);if(S2(e)||s){const c={};for(const u of Object.keys(e))c[u]=i(e[u]);return s&&(c.next??(c.next=i(e.next.bind(e))),c.return??(c.return=i(e.return.bind(e))),c.throw??(c.throw=i(e.throw.bind(e))),c[x2]=!0),a.set(e,c),c}}if(typeof e=="function"){const i=t.functions.serialize(e,t,n),s={[Xx]:i};return a.set(e,s),s}return a.set(e,e),e},Es=function(e,t,n=!1){if(e==null)return e;if(typeof e=="object"){if(Pn(this,Cp)&&!n){const r=Pn(this,Cp).call(this,e,i=>Rr(this,Ya,Es).call(this,i,t,!0),t);if(r!==void 0)return r}if(e==null)return e;if(Array.isArray(e))return e.map(r=>Rr(this,Ya,Es).call(this,r,t));if(e instanceof Map)return new Map([...e].map(([r,i])=>[Rr(this,Ya,Es).call(this,r,t),Rr(this,Ya,Es).call(this,i,t)]));if(e instanceof Set)return new Set([...e].map(r=>Rr(this,Ya,Es).call(this,r,t)));if(Xx in e)return t.functions.deserialize(e[Xx],t);if(!S2(e))return e;const a={};for(const r of Object.keys(e))r===x2?a[Symbol.asyncIterator]=()=>a:a[r]=Rr(this,Ya,Es).call(this,e[r],t);return a}return e};var ou,jl,ks,tk,bY,nk,vY;class xke{constructor(t,{imports:n,exports:a,functions:r=new yke,serialization:i=new Ske,signal:s}={}){hi(this,ks),hi(this,ou),hi(this,jl,new Map);var c,u,d,m;this.messages=t,JE(this,ou,s?new bke(s):new AbortController),this.exports=a??{},this.imports=_ke(Rr(this,ks,bY).bind(this),n),this.functions=r,this.serialization=i,(u=(c=this.functions).start)==null||u.call(c,this),(m=(d=this.serialization).start)==null||m.call(d,this),this.signal.addEventListener("abort",()=>{for(const h of Pn(this,jl).keys())Rr(this,ks,nk).call(this,h,void 0,new w2);Pn(this,jl).clear()},{once:!0}),t.listen(async h=>{if(!(Array.isArray(h)&&typeof h[0]=="number"))return;const g=h;switch(g[0]){case fY:{const[,v,x,S]=g,w=this.exports[x]??(()=>{throw new Error(`No '${x}' method is exported from this thread`)});await Rr(this,ks,tk).call(this,w,S,(E,_,k)=>{this.messages.send([b2,v,E,_],k)});break}case pY:{const[,v,x,S]=g,w=this.functions.get(x,this)??Eke;await Rr(this,ks,tk).call(this,w,S,(E,_,k)=>{this.messages.send([v2,v,E,_],k)});break}case b2:case v2:{Rr(this,ks,nk).call(this,...g.slice(1));break}case mY:{const v=g[1];this.functions.release(v,this);break}}},{signal:this.signal})}get signal(){return Pn(this,ou).signal}get closed(){return Pn(this,ou).signal.aborted}close(){Pn(this,ou).abort()}call(t,n){if(this.closed)return Promise.reject(new w2);const a=[],r=this.serialization.serialize(n,this,a),i=hY(),s=Rr(this,ks,vY).call(this,i);return t(i,r,a),s}}ou=new WeakMap,jl=new WeakMap,ks=new WeakSet,tk=async function(e,t,n){try{const a=this.functions.call?await this.functions.call(e,t,this):await e(...this.serialization.deserialize(t,this)),r=[],i=this.serialization.serialize(a,this,r);n(i,void 0,r)}catch(a){n(void 0,this.serialization.serialize(a,this))}},bY=function(e){return(...t)=>{try{if(typeof e!="string"&&typeof e!="number")throw new Error(`Can’t call a symbol method on a thread: ${e.toString()}`);return this.call((n,a,r)=>{this.messages.send([fY,n,e,a],r)},t)}catch(n){return Promise.reject(n)}}},nk=function(...e){const t=e[0],n=Pn(this,jl).get(t);n&&(n(...e),Pn(this,jl).delete(t))},vY=function(e){const t=new Promise((n,a)=>{Pn(this,jl).set(e,(r,i,s)=>{s==null?n(this.serialization.deserialize(i,this)):a(this.serialization.deserialize(s,this))})});return Object.defineProperty(t,Symbol.asyncIterator,{async*value(){const n=await t;Object.defineProperty(n,Symbol.asyncIterator,{value:()=>n}),yield*n}}),t};function _ke(e,t){let n;if(t==null){if(typeof Proxy!="function")throw new Error("You must pass an array of callable methods in environments without Proxies.");const a=new Map;n=new Proxy({},{get(r,i){if(a.has(i))return a.get(i);const s=e(i);return a.set(i,s),s}})}else{n={};for(const a of t)Object.defineProperty(n,a,{value:e(a),writable:!1,configurable:!0,enumerable:!0})}return n}function Eke(){throw new Error("You attempted to call a function that is not stored. It may have already been released.")}const kke="quilt.threads.ping",_2="quilt.threads.pong";function Tke(e,{targetOrigin:t="*"}={}){let n=!1;const a=function(i,s){e.postMessage(i,t,s)},r=new Promise(i=>{const s=new AbortController;globalThis.window.addEventListener("message",c=>{c.source===e&&c.data===_2&&(n=!0,s.abort(),i())},{signal:s.signal}),s.signal.addEventListener("abort",()=>i(),{once:!0}),a(kke)});return{send(i,s){return n?a(i,s):r.then(()=>{if(n)return a(i,s)})},listen(i,{signal:s}){self.addEventListener("message",c=>{c.source===e&&c.data!==_2&&i(c.data)},{signal:s})}}}class Nke extends xke{constructor(t,{targetOrigin:n="*",...a}={}){super(Tke(t.contentWindow,{targetOrigin:n}),a),this.iframe=t}}const yY=ce.forwardRef(({content:e,children:t,...n},a)=>f.jsx("span",{ref:a,...n,children:e||t}));yY.displayName="UIText";const wY=ce.forwardRef(({label:e,onPress:t,onClick:n,children:a,...r},i)=>f.jsx("button",{ref:i,onClick:s=>{t&&t(),n&&n(s)},style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},...r,children:e||a}));wY.displayName="UIButton";const SY=ce.forwardRef(({direction:e="vertical",spacing:t="8",align:n="stretch",justify:a="flex-start",children:r,...i},s)=>f.jsx("div",{ref:s,style:{display:"flex",flexDirection:e==="horizontal"?"row":"column",gap:`${t}px`,alignItems:n,justifyContent:a},...i,children:r}));SY.displayName="UIStack";const xY=ce.forwardRef(({src:e,alt:t,width:n,height:a,children:r,...i},s)=>f.jsx("img",{ref:s,src:e,alt:t,width:n,height:a,style:{maxWidth:"100%",height:"auto",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.1)"},...i}));xY.displayName="UIImage";const wD={name:"basic",elements:[{tagName:"ui-text",component:yY,propMapping:{content:"content"},eventMapping:{}},{tagName:"ui-button",component:wY,propMapping:{label:"label"},eventMapping:{press:"onPress"}},{tagName:"ui-stack",component:SY,propMapping:{direction:"direction",spacing:"spacing",align:"align",justify:"justify"},eventMapping:{}},{tagName:"ui-image",component:xY,propMapping:{src:"src",alt:"alt",width:"width",height:"height"},eventMapping:{}}]},Cke=({receiver:e})=>{const t=y.useRef(null);return y.useEffect(()=>{if(t.current)return e.connect(t.current),()=>{e.disconnect()}},[e]),f.jsx("div",{ref:t,"data-testid":"standard-dom-renderer-container"})},Rke=({resource:e,library:t,remoteElements:n=[],onUIAction:a})=>{const r=y.useRef(null),i=y.useRef(null),[s,c]=y.useState(null),u=y.useMemo(()=>(e.mimeType||"").includes("framework=react")?"react":"webcomponents",[e.mimeType]),d=`${t?.name}-${u}`,{receiver:m,components:h}=y.useMemo(()=>{switch(u){case"react":{const v=new oke,x=t||wD,S=new Map;return x&&x.elements.forEach(w=>{const E=fke(w.component);S.set(w.tagName,E)}),{receiver:v,components:S}}case"webcomponents":default:return{receiver:new ske,components:null}}},[e,t,n]);y.useEffect(()=>{function v(x){var S;if(r.current&&x.source===r.current.contentWindow){const w=x.data;if(!w)return;(S=a?.(w))==null||S.catch(E=>{console.error("Error handling UI action result in RemoteDOMResourceRenderer:",E)})}}return window.addEventListener("message",v),()=>window.removeEventListener("message",v)},[a]),y.useEffect(()=>{const v=i.current;return i.current=null,()=>{v?.close()}},[d]);const g=()=>{const v=r.current;if(!v||i.current)return;const x=new Nke(v);i.current=x;const{code:S,error:w}=XEe(e);if(w){c(w);return}if(S&&m!=null&&m.connection){const E={code:S,remoteElements:n,useReactRenderer:u==="react",componentLibrary:t?.name};x.imports.render(E,m.connection).catch(_=>console.error("Error calling remote render:",_))}};return s?f.jsx("p",{className:"text-red-500",children:s}):f.jsxs(f.Fragment,{children:[f.jsx("iframe",{ref:r,srcDoc:hke,sandbox:"allow-scripts",style:{display:"none"},title:"Remote DOM Sandbox",onLoad:g},d),u==="react"&&h?f.jsx(mke,{receiver:m,components:h}):f.jsx(Cke,{receiver:m})]})};function Ake(e){var t;if(e.contentType)return e.contentType;if(e.mimeType==="text/html")return"rawHtml";if(e.mimeType==="text/uri-list")return"externalUrl";if((t=e.mimeType)!=null&&t.startsWith("application/vnd.mcp-ui.remote-dom"))return"remoteDom"}const SD=e=>{const{resource:t,onUIAction:n,supportedContentTypes:a,htmlProps:r,remoteDomProps:i}=e,s=Ake(t);if(a&&s&&!a.includes(s))return f.jsxs("p",{className:"text-red-500",children:["Unsupported content type: ",s,"."]});switch(s){case"rawHtml":case"externalUrl":return f.jsx(oY,{resource:t,onUIAction:n,...r});case"remoteDom":return f.jsx(Rke,{resource:t,onUIAction:n,library:i?.library||wD,...i});default:return f.jsx("p",{className:"text-red-500",children:"Unsupported resource type."})}};SD.displayName="UIResourceRenderer";const Ike={tagName:"ui-button",remoteAttributes:["label"],remoteEvents:["click","press"]},Oke={tagName:"ui-text",remoteAttributes:["content"]},Dke={tagName:"ui-stack",remoteAttributes:["direction","spacing","align","justify"]},jke={tagName:"ui-image",remoteAttributes:["src","alt","width","height"]},$ke=y.memo(({resource:e})=>{const t=async n=>(n.type==="tool"||n.type==="prompt"||(n.type==="link"?n.payload.url&&window.open(n.payload.url,"_blank"):n.type==="intent"||n.type),{status:"Action received"});return e.uri?.startsWith("ui://")?f.jsx("div",{className:"my-4 p-0 border h-[350px] rounded-2xl border-zinc-200 overflow-hidden bg-card",children:f.jsx(SD,{resource:e,onUIAction:t,htmlProps:{style:{maxWidth:"100%",height:"100%",overflow:"auto"},autoResizeIframe:!0,sandboxPermissions:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}})}):null});function E2({toolName:e,toolArgs:t,result:n,serverId:a,readResource:r,toolMeta:i}){const[s,c]=y.useState(null);y.useEffect(()=>{console.log("[ToolResultRenderer] Rendering:",{toolName:e,hasToolMeta:!!i,outputTemplate:i?.["openai/outputTemplate"],hasResult:!!n,hasServerId:!!a,hasReadResource:!!r})},[e,i,n,a,r]);const u=y.useMemo(()=>{if(typeof n=="string")try{return JSON.parse(n)}catch(v){return console.error("[ToolResultRenderer] Failed to parse result:",v),n}return n},[n]),d=y.useMemo(()=>!!i?.["openai/outputTemplate"],[i]),m=y.useMemo(()=>!!(u?.content&&Array.isArray(u.content)&&u.content.some(v=>v.type==="resource"&&v.resource?.uri?.startsWith("ui://")&&v.resource?.mimeType==="text/html+skybridge")),[u]),h=y.useMemo(()=>m&&u.content.find(x=>x.type==="resource"&&x.resource?.uri?.startsWith("ui://")&&x.resource?.mimeType==="text/html+skybridge")?.resource||null,[m,u]);if(y.useEffect(()=>{if(h){c(h);return}if(d&&i&&r){const v=i["openai/outputTemplate"];console.log("[ToolResultRenderer] Fetching resource for Apps SDK tool:",v),r(v).then(x=>{console.log("[ToolResultRenderer] Resource fetched:",x),x?.contents&&Array.isArray(x.contents)&&x.contents.length>0?c(x.contents[0]):console.warn("[ToolResultRenderer] No contents in fetched resource:",x)}).catch(x=>{console.error("[ToolResultRenderer] Failed to fetch resource:",x)})}},[h,d,i,r]),(d||m)&&s&&a&&r)return f.jsx(hD,{componentUrl:s.uri,toolName:e,toolArgs:t,toolResult:u,serverId:a,readResource:r,noWrapper:!0,className:"my-4",showConsole:!1});if((d||m)&&!s)return f.jsx("div",{className:"flex items-center justify-center w-full h-[200px] rounded border",children:f.jsx(ki,{className:"size-5"})});if(d&&(!a||!r))return console.error("[ToolResultRenderer] Apps SDK tool but missing serverId or readResource:",{toolName:e,hasServerId:!!a,hasReadResource:!!r}),f.jsx("div",{className:"my-4 p-4 bg-red-50/30 dark:bg-red-950/20 border border-red-200/50 dark:border-red-800/50 rounded-lg",children:f.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:"Cannot render widget: Missing required props (serverId or readResource)"})});const g=[];if(u?.content&&Array.isArray(u.content))for(const v of u.content)v.type==="resource"&&v.resource?.uri?.startsWith("ui://")&&v.resource?.mimeType!=="text/html+skybridge"&&g.push(v.resource);return g.length>0?f.jsx(f.Fragment,{children:g.map(v=>f.jsx($ke,{resource:v},`${e}-mcp-ui-${v.uri}`))}):(console.log("[ToolResultRenderer] Not rendering (no UI resources found):",{toolName:e,isAppsSdkTool:d,hasAppsSdkComponent:m,hasResourceData:!!s,contentLength:u?.content?.length}),null)}function Lke({content:e,timestamp:t}){return!e||e.length===0?null:f.jsx("div",{className:"flex items-start gap-3 justify-end group/user-message",children:f.jsxs("div",{className:"flex-1 min-w-0 flex flex-col items-end",children:[f.jsx("div",{className:"bg-zinc-200 dark:bg-zinc-800 text-primary rounded-3xl px-4 py-2 max-w-[80%] break-words",children:f.jsx("p",{className:"text-base leading-7 font-sans text-start break-words",children:e})}),t&&f.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:new Date(t).toLocaleTimeString()})]})})}const Mke=y.memo(({messages:e,isLoading:t,serverId:n,readResource:a,tools:r})=>{const i=y.useRef(null),s=d=>r?.find(h=>h.name===d)?._meta;y.useEffect(()=>{e.length>0&&i.current&&i.current.scrollIntoView({behavior:t?"auto":"smooth",block:"start"})},[e.length,t]);const c=t&&(()=>{if(e.length===0)return!0;const d=e[e.length-1];if(d.role==="user")return!0;if(d.role==="assistant"){const m=typeof d.content=="string"?d.content:Array.isArray(d.content)?d.content.map(g=>typeof g=="string"?g:g.text||JSON.stringify(g)).join(""):JSON.stringify(d.content);return!(m&&m.trim().length>0)}return!1})(),u=d=>{if(!t)return!1;const m=e[e.length-1];return d.id===m.id&&m.role==="assistant"};return f.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto px-2",children:[e.map(d=>{const m=typeof d.content=="string"?d.content:Array.isArray(d.content)?d.content.map(h=>typeof h=="string"?h:h.text||JSON.stringify(h)).join(""):JSON.stringify(d.content);return d.role==="user"?f.jsx(Lke,{content:m,timestamp:d.timestamp},d.id):d.role==="assistant"?f.jsx("div",{className:"space-y-4",children:d.parts&&d.parts.length>0?d.parts.map((h,g)=>{const v=h.type==="text"?`${d.id}-text-${g}-${h.text?.slice(0,20)}`:`${d.id}-tool-${h.toolInvocation?.toolName}-${g}`;return h.type==="text"?f.jsx(s2,{content:h.text||"",timestamp:g===d.parts.length-1?d.timestamp:void 0,_isStreaming:u(d)},v):h.type==="tool-invocation"&&h.toolInvocation?f.jsxs("div",{children:[f.jsx(l2,{toolName:h.toolInvocation.toolName,args:h.toolInvocation.args,result:h.toolInvocation.result,state:h.toolInvocation.result?"result":"call"}),h.toolInvocation.result&&f.jsx(E2,{toolName:h.toolInvocation.toolName,toolArgs:h.toolInvocation.args,result:h.toolInvocation.result,serverId:n,readResource:a,toolMeta:s(h.toolInvocation.toolName)})]},v):null}):f.jsxs(f.Fragment,{children:[f.jsx(s2,{content:m,timestamp:d.timestamp,_isStreaming:u(d)}),d.toolCalls&&d.toolCalls.length>0&&f.jsx("div",{className:"space-y-2",children:d.toolCalls.map(h=>{const g=`${d.id}-${h.toolName}-${JSON.stringify(h.args).slice(0,50)}`;return f.jsxs("div",{children:[f.jsx(l2,{toolName:h.toolName,args:h.args,result:h.result,state:h.result?"result":"call"}),h.result&&f.jsx(E2,{toolName:h.toolName,toolArgs:h.args,result:h.result,serverId:n,readResource:a,toolMeta:s(h.toolName)})]},g)})})]})},d.id):null}),c&&f.jsx("div",{className:"flex items-start gap-3",children:f.jsx("div",{className:"flex-1",children:f.jsx("div",{className:"rounded-lg p-4 max-w-fit",children:f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("span",{className:"text-sm",children:f.jsx(nxe,{duration:2,spread:1,children:"Thinking..."})})})})})}),f.jsx("div",{ref:i})]})});function _Y(e){let t=0;for(let n=0;n<e.length;n++){const a=e.charCodeAt(n);t=(t<<5)-t+a,t=t&t}return Math.abs(t).toString(16)}function Pke({mcpServerUrl:e,llmConfig:t,authConfig:n,isConnected:a}){const[r,i]=y.useState([]),[s,c]=y.useState(!1),u=y.useCallback(async m=>{if(!m.trim()||!t||!a)return;const h={id:`user-${Date.now()}`,role:"user",content:m.trim(),timestamp:Date.now()};i(g=>[...g,h]),c(!0);try{let g=n;if(n?.type==="oauth")try{const C="mcp:auth",R=_Y(e),I=`${C}_${R}_tokens`,A=localStorage.getItem(I);if(A){const O=JSON.parse(A);g={...n,oauthTokens:O}}else console.warn("No OAuth tokens found in localStorage for key:",I)}catch(C){console.warn("Failed to retrieve OAuth tokens:",C)}const v=await fetch("/inspector/api/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServerUrl:e,llmConfig:t,authConfig:g,messages:[...r,h].map(C=>({role:C.role,content:C.content}))})});if(!v.ok)throw new Error(`HTTP error! status: ${v.status}`);const x=`assistant-${Date.now()}`;let S="";const w=[];i(C=>[...C,{id:x,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]);const E=v.body?.getReader(),_=new TextDecoder;if(!E)throw new Error("No response body");let k="";for(;;){const{done:C,value:R}=await E.read();if(C)break;k+=_.decode(R,{stream:!0});const I=k.split(`
|
|
1660
|
-
`);k=I.pop()||"";for(const A of I)if(A.trim()&&A.startsWith("data: "))try{const O=JSON.parse(A.slice(6));if(console.log("[Client received event]",O.type,O.toolName||O.content?.slice?.(0,30)),O.type==="message")console.log("[Message started]",O.id);else if(O.type==="text"){S+=O.content;const M=w[w.length-1];M&&M.type==="text"?M.text=S:w.push({type:"text",text:S}),console.log("[Parts after text]",w.length,"parts, text length:",S.length),i(P=>P.map(B=>B.id===x?{...B,parts:[...w]}:B))}else if(O.type==="tool-call")S&&(S=""),w.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",w.length,"parts, tool:",O.toolName),i(M=>M.map(P=>P.id===x?{...P,parts:[...w]}:P));else if(O.type==="tool-result"){const M=w.find(P=>P.type==="tool-invocation"&&P.toolInvocation?.toolName===O.toolName&&!P.toolInvocation?.result);M&&M.toolInvocation?(M.toolInvocation.result=O.result,M.toolInvocation.state="result",console.log("[Parts after tool-result]",w.length,"parts, updated:",O.toolName),i(P=>P.map(B=>B.id===x?{...B,parts:[...w]}:B))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",w.length),i(M=>M.map(P=>P.id===x?{...P,parts:[...w],content:""}:P));else if(O.type==="error")throw new Error(O.message||"Streaming error")}catch(O){console.error("Failed to parse streaming event:",O,A)}}}catch(g){let v="Unknown error occurred";if(g instanceof Error){v=g.message;const S=g;S.status&&(v=`HTTP ${S.status}: ${v}`),(S.code===401||v.includes("401")||v.includes("Unauthorized"))&&(v="Authentication failed (401). Check your Authorization header in the connection settings.")}const x={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${v}`,timestamp:Date.now()};i(S=>[...S,x])}finally{c(!1)}},[t,a,e,r,n]),d=y.useCallback(()=>{i([])},[]);return{messages:r,isLoading:s,sendMessage:u,clearMessages:d}}function Uke({connection:e,llmConfig:t,isConnected:n,readResource:a}){const[r,i]=y.useState([]),[s,c]=y.useState(!1),u=y.useRef(null),d=y.useRef(null),m=y.useRef(null),h=y.useCallback(async v=>{if(!v.trim()||!t||!n)return;const x={id:`user-${Date.now()}`,role:"user",content:v.trim(),timestamp:Date.now()};i(E=>[...E,x]),c(!0),u.current=new AbortController;const S=Date.now();let w=0;try{const E=`assistant-${Date.now()}`;let _="";const k=[];if(i(C=>[...C,{id:E,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]),!m.current||m.current.provider!==t.provider||m.current.model!==t.model||m.current.apiKey!==t.apiKey){let C;if(t.provider==="openai"){const{ChatOpenAI:R}=await Jn(async()=>{const{ChatOpenAI:I}=await import("./index-DclCkKwz.js");return{ChatOpenAI:I}},__vite__mapDeps([6,7,8,2,9,10,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:R}=await Jn(async()=>{const{ChatAnthropic:I}=await import("./index-CCasFtk_.js");return{ChatAnthropic:I}},__vite__mapDeps([12,8,7,2,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:R}=await Jn(async()=>{const{ChatGoogleGenerativeAI:I}=await import("./index-DznD3Siw.js");return{ChatGoogleGenerativeAI:I}},__vite__mapDeps([13,8,7,2,10]));C=new R({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:C,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!d.current||d.current.llm!==m.current.instance){const{MCPAgent:C}=await Jn(async()=>{const{MCPAgent:R}=await import("./browser-CjAOLOLG.js");return{MCPAgent:R}},__vite__mapDeps([14,4,5,3,11,7,8,2,10,9]));d.current=new C({llm:m.current.instance,client:e.client,memoryEnabled:!0,systemPrompt:"You are a helpful assistant with access to MCP tools, prompts, and resources. Help users interact with the MCP server."}),await d.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",d.current.conversationHistory?.length);for await(const C of d.current.streamEvents(v,10,!1,void 0)){if(u.current?.signal.aborted)break;if(C.event==="on_chat_model_stream"&&C.data?.chunk?.text){const R=C.data.chunk.text;if(typeof R=="string"&&R.length>0){_+=R;const I=k[k.length-1];I&&I.type==="text"?I.text=_:k.push({type:"text",text:_}),i(A=>A.map(O=>O.id===E?{...O,parts:[...k]}:O))}}else if(C.event==="on_tool_start"){_&&(_="");let R={};C.data?.input?R=C.data.input:C.data?.tool_input?R=C.data.tool_input:C.data&&(R=C.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:C.name,eventData:C.data,extractedArgs:R}),w++,k.push({type:"tool-invocation",toolInvocation:{toolName:C.name||"unknown",args:R,state:"pending"}}),i(I=>I.map(A=>A.id===E?{...A,parts:[...k]}:A))}else if(C.event==="on_tool_end"){const R=k.find(I=>I.type==="tool-invocation"&&I.toolInvocation?.toolName===C.name&&!I.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:C.name,hasToolPart:!!R,output:C.data?.output}),R&&R.toolInvocation){let I=C.data?.output;if(I?.kwargs?.content&&typeof I.kwargs.content=="string")try{I=JSON.parse(I.kwargs.content)}catch(O){console.warn("[useChatMessagesClientSide] Failed to parse kwargs.content:",O),I=I.kwargs.content}else if(I?.content&&typeof I.content=="string")try{I=JSON.parse(I.content)}catch{I=I.content}R.toolInvocation.result=I,R.toolInvocation.state="result";const A=I?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:C.name,hasMeta:!!I?._meta,hasStructuredContent:!!I?.structuredContent,appsSdkUri:A}),A&&typeof A=="string"&&a){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",A);try{const O=await a(A);console.log("[useChatMessagesClientSide] Resource fetched:",O);const M=I?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const P=O.contents.map(K=>({type:"resource",resource:K}));console.log("[useChatMessagesClientSide] Created MCP resources:",P);const B={...I,content:[...I.content||[],...P],structuredContent:M};R.toolInvocation.result=B,console.log("[useChatMessagesClientSide] Updated result with resources")}else console.warn("[useChatMessagesClientSide] No contents in resourceData:",O)}catch(O){console.error("Failed to fetch Apps SDK resource:",O)}}i(O=>O.map(M=>M.id===E?{...M,parts:[...k]}:M))}}}i(C=>C.map(R=>R.id===E?{...R,parts:[...k],content:""}:R)),t&&yr.getInstance().capture(new ez({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:w,success:!0,executionMode:"client-side",duration:Date.now()-S})).catch(()=>{})}catch(E){console.error("Client-side agent error:",E);let _="Unknown error occurred";if(E instanceof Error){_=E.message;const C=E;C.status&&(_=`HTTP ${C.status}: ${_}`),(C.code===401||_.includes("401")||_.includes("Unauthorized"))&&(_="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&yr.getInstance().capture(new ez({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:w,success:!1,executionMode:"client-side",duration:Date.now()-S,error:_})).catch(()=>{});const k={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${_}`,timestamp:Date.now()};i(C=>[...C,k])}finally{c(!1),u.current=null}},[e,t,n,r,a]),g=y.useCallback(()=>{i([]),d.current&&d.current.clearConversationHistory()},[]);return{messages:r,isLoading:s,sendMessage:h,clearMessages:g}}const k2={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function EY({mcpServerUrl:e}){const[t,n]=y.useState(null),[a,r]=y.useState(null),[i,s]=y.useState(!1),[c,u]=y.useState("openai"),[d,m]=y.useState(""),[h,g]=y.useState(k2.openai),v=y.useCallback(()=>{const M=localStorage.getItem("mcp-inspector-api-keys");if(M)try{return JSON.parse(M)}catch(P){return console.error("Failed to load API keys:",P),{}}return{}},[]),x=y.useCallback(M=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(M))},[]),[S,w]=y.useState("none"),[E,_]=y.useState(""),[k,C]=y.useState(""),[R,I]=y.useState("");y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-llm-config"),P=v();if(M)try{const B=JSON.parse(M);n(B),u(B.provider),m(P[B.provider]||B.apiKey||""),g(B.model)}catch(B){console.error("Failed to load LLM config:",B)}},[v]),y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-auth-config");if(M)try{const P=JSON.parse(M);r(P),w(P.type),P.username&&_(P.username),P.password&&C(P.password),P.token&&I(P.token)}catch(P){console.error("Failed to load auth config:",P)}else try{const P="mcp:auth",B=_Y(e),K=`${P}_${B}_tokens`;localStorage.getItem(K)&&(r({type:"oauth"}),w("oauth"))}catch(P){console.error("Failed to check for OAuth tokens:",P)}},[e]),y.useEffect(()=>{g(k2[c]);const M=v();m(M[c]||"")},[c,v]);const A=y.useCallback(()=>{if(!d.trim())return;const M=v();M[c]=d,x(M);const P={provider:c,apiKey:d,model:h},B={type:S,...S==="basic"&&{username:E.trim(),password:k.trim()},...S==="bearer"&&{token:R.trim()}};n(P),r(B),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(P)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(B)),s(!1)},[c,d,h,S,E,k,R,v,x]),O=y.useCallback(()=>{n(null),r(null);const M=v();delete M[c],x(M),m(""),_(""),C(""),I(""),w("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[c,v,x]);return{llmConfig:t,authConfig:a,configDialogOpen:i,setConfigDialogOpen:s,tempProvider:c,setTempProvider:u,tempApiKey:d,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:S,saveLLMConfig:A,clearConfig:O}}function zke({connection:e,isConnected:t,useClientSide:n=!0,readResource:a}){const[r,i]=y.useState(""),s=y.useRef(null),{llmConfig:c,authConfig:u,configDialogOpen:d,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:v,setTempApiKey:x,tempModel:S,setTempModel:w,saveLLMConfig:E,clearConfig:_}=EY({mcpServerUrl:e.url}),k={connection:e,llmConfig:c,isConnected:t,readResource:a},C=Pke({mcpServerUrl:e.url,llmConfig:c,authConfig:u,isConnected:t}),R=Uke(k),{messages:I,isLoading:A,sendMessage:O,clearMessages:M}=n?R:C;xK({onNewChat:M}),y.useEffect(()=>{c&&I.length===0&&s.current&&s.current.focus()},[c,I.length]),y.useEffect(()=>{!A&&I.length>0&&s.current&&s.current.focus()},[A,I.length]);const P=y.useCallback(()=>{r.trim()&&(O(r),i(""))},[r,O]),B=y.useCallback(Q=>{Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),P())},[P]),K=y.useCallback(()=>{_(),M()},[_,M]);return c&&I.length===0?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"absolute top-4 right-4 z-10",children:f.jsx(CE,{open:d,onOpenChange:m,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSave:E,onClear:K,showClearButton:!0,buttonLabel:"Change API Key"})}),f.jsx(exe,{mcpServerUrl:e.url,inputValue:r,isConnected:t,isLoading:A,textareaRef:s,llmConfig:c,onInputChange:i,onKeyDown:B,onSubmit:Q=>{Q.preventDefault(),P()},onConfigDialogOpenChange:m})]}):f.jsxs("div",{className:"flex flex-col h-full relative",children:[f.jsx(XSe,{llmConfig:c,hasMessages:I.length>0,configDialogOpen:d,onConfigDialogOpenChange:m,onClearChat:M,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSaveConfig:E,onClearConfig:K}),f.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:c?f.jsx(Mke,{messages:I,isLoading:A,serverId:e.url,readResource:a,tools:e.tools}):f.jsx(txe,{onConfigureClick:()=>m(!0)})}),c&&f.jsx(JSe,{inputValue:r,isConnected:t,isLoading:A,textareaRef:s,onInputChange:i,onKeyDown:B,onSendMessage:P})]})}const kw=y.createContext(null);kw.displayName="PanelGroupContext";const Zn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},xD=10,Ul=y.useLayoutEffect,T2=kd.useId,Fke=typeof T2=="function"?T2:()=>null;let Bke=0;function _D(e=null){const t=Fke(),n=y.useRef(e||t||null);return n.current===null&&(n.current=""+Bke++),e??n.current}function kY({children:e,className:t="",collapsedSize:n,collapsible:a,defaultSize:r,forwardedRef:i,id:s,maxSize:c,minSize:u,onCollapse:d,onExpand:m,onResize:h,order:g,style:v,tagName:x="div",...S}){const w=y.useContext(kw);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:E,expandPanel:_,getPanelSize:k,getPanelStyle:C,groupId:R,isPanelCollapsed:I,reevaluatePanelConstraints:A,registerPanel:O,resizePanel:M,unregisterPanel:P}=w,B=_D(s),K=y.useRef({callbacks:{onCollapse:d,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:a,defaultSize:r,maxSize:c,minSize:u},id:B,idIsFromProps:s!==void 0,order:g});y.useRef({didLogMissingDefaultSizeWarning:!1}),Ul(()=>{const{callbacks:ee,constraints:ae}=K.current,H={...ae};K.current.id=B,K.current.idIsFromProps=s!==void 0,K.current.order=g,ee.onCollapse=d,ee.onExpand=m,ee.onResize=h,ae.collapsedSize=n,ae.collapsible=a,ae.defaultSize=r,ae.maxSize=c,ae.minSize=u,(H.collapsedSize!==ae.collapsedSize||H.collapsible!==ae.collapsible||H.maxSize!==ae.maxSize||H.minSize!==ae.minSize)&&A(K.current,H)}),Ul(()=>{const ee=K.current;return O(ee),()=>{P(ee)}},[g,B,O,P]),y.useImperativeHandle(i,()=>({collapse:()=>{E(K.current)},expand:ee=>{_(K.current,ee)},getId(){return B},getSize(){return k(K.current)},isCollapsed(){return I(K.current)},isExpanded(){return!I(K.current)},resize:ee=>{M(K.current,ee)}}),[E,_,k,I,B,M]);const Q=C(K.current,r);return y.createElement(x,{...S,children:e,className:t,id:B,style:{...Q,...v},[Zn.groupId]:R,[Zn.panel]:"",[Zn.panelCollapsible]:a||void 0,[Zn.panelId]:B,[Zn.panelSize]:parseFloat(""+Q.flexGrow).toFixed(1)})}const TY=y.forwardRef((e,t)=>y.createElement(kY,{...e,forwardedRef:t}));kY.displayName="Panel";TY.displayName="forwardRef(Panel)";let rk=null,Xb=-1,Rs=null;function Hke(e,t,n){const a=(t&IY)!==0,r=(t&OY)!==0,i=(t&DY)!==0,s=(t&jY)!==0;if(t){if(a)return i?"se-resize":s?"ne-resize":"e-resize";if(r)return i?"sw-resize":s?"nw-resize":"w-resize";if(i)return"s-resize";if(s)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function Vke(){Rs!==null&&(document.head.removeChild(Rs),rk=null,Rs=null,Xb=-1)}function Jx(e,t,n){var a,r;const i=Hke(e,t);if(rk!==i){if(rk=i,Rs===null&&(Rs=document.createElement("style"),document.head.appendChild(Rs)),Xb>=0){var s;(s=Rs.sheet)===null||s===void 0||s.removeRule(Xb)}Xb=(a=(r=Rs.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${i} !important;}`))!==null&&a!==void 0?a:-1}}function NY(e){return e.type==="keydown"}function CY(e){return e.type.startsWith("pointer")}function RY(e){return e.type.startsWith("mouse")}function Tw(e){if(CY(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(RY(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function Gke(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function Wke(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Kke(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:R2(e),b:R2(t)};let a;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),a=e;It(a,"Stacking order can only be calculated for elements with a common ancestor");const r={a:C2(N2(n.a)),b:C2(N2(n.b))};if(r.a===r.b){const i=a.childNodes,s={a:n.a.at(-1),b:n.b.at(-1)};let c=i.length;for(;c--;){const u=i[c];if(u===s.a)return 1;if(u===s.b)return-1}}return Math.sign(r.a-r.b)}const Zke=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function Yke(e){var t;const n=getComputedStyle((t=AY(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function qke(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||Yke(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||Zke.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function N2(e){let t=e.length;for(;t--;){const n=e[t];if(It(n,"Missing node"),qke(n))return n}return null}function C2(e){return e&&Number(getComputedStyle(e).zIndex)||0}function R2(e){const t=[];for(;e;)t.push(e),e=AY(e);return t}function AY(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const IY=1,OY=2,DY=4,jY=8,Xke=Gke()==="coarse";let wi=[],Cu=!1,As=new Map,Nw=new Map;const sm=new Set;function Jke(e,t,n,a,r){var i;const{ownerDocument:s}=t,c={direction:n,element:t,hitAreaMargins:a,setResizeHandlerState:r},u=(i=As.get(s))!==null&&i!==void 0?i:0;return As.set(s,u+1),sm.add(c),ey(),function(){var m;Nw.delete(e),sm.delete(c);const h=(m=As.get(s))!==null&&m!==void 0?m:1;if(As.set(s,h-1),ey(),h===1&&As.delete(s),wi.includes(c)){const g=wi.indexOf(c);g>=0&&wi.splice(g,1),Cw(),r("up",!0,null)}}}function Qke(e){const{target:t}=e,{x:n,y:a}=Tw(e);Cu=!0,ED({target:t,x:n,y:a}),ey(),wi.length>0&&(ty("down",e),Cw(),e.preventDefault(),$Y(t)||e.stopImmediatePropagation())}function Qx(e){const{x:t,y:n}=Tw(e);if(Cu&&e.type!=="pointerleave"&&e.buttons===0&&(Cu=!1,ty("up",e)),!Cu){const{target:a}=e;ED({target:a,x:t,y:n})}ty("move",e),Cw(),wi.length>0&&e.preventDefault()}function e_(e){const{target:t}=e,{x:n,y:a}=Tw(e);Nw.clear(),Cu=!1,wi.length>0&&(e.preventDefault(),$Y(t)||e.stopImmediatePropagation()),ty("up",e),ED({target:t,x:n,y:a}),Cw(),ey()}function $Y(e){let t=e;for(;t;){if(t.hasAttribute(Zn.resizeHandle))return!0;t=t.parentElement}return!1}function ED({target:e,x:t,y:n}){wi.splice(0);let a=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(a=e),sm.forEach(r=>{const{element:i,hitAreaMargins:s}=r,c=i.getBoundingClientRect(),{bottom:u,left:d,right:m,top:h}=c,g=Xke?s.coarse:s.fine;if(t>=d-g&&t<=m+g&&n>=h-g&&n<=u+g){if(a!==null&&document.contains(a)&&i!==a&&!i.contains(a)&&!a.contains(i)&&Kke(a,i)>0){let x=a,S=!1;for(;x&&!x.contains(i);){if(Wke(x.getBoundingClientRect(),c)){S=!0;break}x=x.parentElement}if(S)return}wi.push(r)}})}function t_(e,t){Nw.set(e,t)}function Cw(){let e=!1,t=!1;wi.forEach(a=>{const{direction:r}=a;r==="horizontal"?e=!0:t=!0});let n=0;Nw.forEach(a=>{n|=a}),e&&t?Jx("intersection",n):e?Jx("horizontal",n):t?Jx("vertical",n):Vke()}let n_;function ey(){var e;(e=n_)===null||e===void 0||e.abort(),n_=new AbortController;const t={capture:!0,signal:n_.signal};sm.size&&(Cu?(wi.length>0&&As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("contextmenu",e_,t),r.addEventListener("pointerleave",Qx,t),r.addEventListener("pointermove",Qx,t))}),As.forEach((n,a)=>{const{body:r}=a;r.addEventListener("pointerup",e_,t),r.addEventListener("pointercancel",e_,t)})):As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("pointerdown",Qke,t),r.addEventListener("pointermove",Qx,t))}))}function ty(e,t){sm.forEach(n=>{const{setResizeHandlerState:a}=n,r=wi.includes(n);a(e,r,t)})}function eTe(){const[e,t]=y.useState(0);return y.useCallback(()=>t(n=>n+1),[])}function It(e,t){if(!e)throw console.error(t),Error(t)}function Ql(e,t,n=xD){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function No(e,t,n=xD){return Ql(e,t,n)===0}function Da(e,t,n){return Ql(e,t,n)===0}function tTe(e,t,n){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++){const r=e[a],i=t[a];if(!Da(r,i,n))return!1}return!0}function wu({panelConstraints:e,panelIndex:t,size:n}){const a=e[t];It(a!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:r=0,collapsible:i,maxSize:s=100,minSize:c=0}=a;if(Ql(n,c)<0)if(i){const u=(r+c)/2;Ql(n,u)<0?n=r:n=c}else n=c;return n=Math.min(s,n),n=parseFloat(n.toFixed(xD)),n}function cp({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:a,prevLayout:r,trigger:i}){if(Da(e,0))return t;const s=[...t],[c,u]=a;It(c!=null,"Invalid first pivot index"),It(u!=null,"Invalid second pivot index");let d=0;if(i==="keyboard"){{const h=e<0?u:c,g=n[h];It(g,`Panel constraints not found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const w=t[h];if(It(w!=null,`Previous layout not found for panel index ${h}`),Da(w,v)){const E=S-w;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}{const h=e<0?c:u,g=n[h];It(g,`No panel constraints found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const w=t[h];if(It(w!=null,`Previous layout not found for panel index ${h}`),Da(w,S)){const E=w-v;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}}{const h=e<0?1:-1;let g=e<0?u:c,v=0;for(;;){const S=t[g];It(S!=null,`Previous layout not found for panel index ${g}`);const E=wu({panelConstraints:n,panelIndex:g,size:100})-S;if(v+=E,g+=h,g<0||g>=n.length)break}const x=Math.min(Math.abs(e),Math.abs(v));e=e<0?0-x:x}{let g=e<0?c:u;for(;g>=0&&g<n.length;){const v=Math.abs(e)-Math.abs(d),x=t[g];It(x!=null,`Previous layout not found for panel index ${g}`);const S=x-v,w=wu({panelConstraints:n,panelIndex:g,size:S});if(!Da(x,w)&&(d+=x-w,s[g]=w,d.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(tTe(r,s))return r;{const h=e<0?u:c,g=t[h];It(g!=null,`Previous layout not found for panel index ${h}`);const v=g+d,x=wu({panelConstraints:n,panelIndex:h,size:v});if(s[h]=x,!Da(x,v)){let S=v-x,E=e<0?u:c;for(;E>=0&&E<n.length;){const _=s[E];It(_!=null,`Previous layout not found for panel index ${E}`);const k=_+S,C=wu({panelConstraints:n,panelIndex:E,size:k});if(Da(_,C)||(S-=C-_,s[E]=C),Da(S,0))break;e>0?E--:E++}}}const m=s.reduce((h,g)=>g+h,0);return Da(m,100)?s:r}function nTe({layout:e,panelsArray:t,pivotIndices:n}){let a=0,r=100,i=0,s=0;const c=n[0];It(c!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:v}=h,{maxSize:x=100,minSize:S=0}=v;g===c?(a=S,r=x):(i+=S,s+=x)});const u=Math.min(r,100-i),d=Math.max(a,100-s),m=e[c];return{valueMax:u,valueMin:d,valueNow:m}}function lm(e,t=document){return Array.from(t.querySelectorAll(`[${Zn.resizeHandleId}][data-panel-group-id="${e}"]`))}function LY(e,t,n=document){const r=lm(e,n).findIndex(i=>i.getAttribute(Zn.resizeHandleId)===t);return r??null}function MY(e,t,n){const a=LY(e,t,n);return a!=null?[a,a+1]:[-1,-1]}function rTe(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function PY(e,t=document){if(rTe(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function Rw(e,t=document){const n=t.querySelector(`[${Zn.resizeHandleId}="${e}"]`);return n||null}function aTe(e,t,n,a=document){var r,i,s,c;const u=Rw(t,a),d=lm(e,a),m=u?d.indexOf(u):-1,h=(r=(i=n[m])===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:null,g=(s=(c=n[m+1])===null||c===void 0?void 0:c.id)!==null&&s!==void 0?s:null;return[h,g]}function iTe({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:a,panelDataArray:r,panelGroupElement:i,setLayout:s}){y.useRef({didWarnAboutMissingResizeHandle:!1}),Ul(()=>{if(!i)return;const c=lm(n,i);for(let u=0;u<r.length-1;u++){const{valueMax:d,valueMin:m,valueNow:h}=nTe({layout:a,panelsArray:r,pivotIndices:[u,u+1]}),g=c[u];if(g!=null){const v=r[u];It(v,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",v.id),g.setAttribute("aria-valuemax",""+Math.round(d)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{c.forEach((u,d)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,a,r,i]),y.useEffect(()=>{if(!i)return;const c=t.current;It(c,"Eager values not found");const{panelDataArray:u}=c,d=PY(n,i);It(d!=null,`No group found for id "${n}"`);const m=lm(n,i);It(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const v=g.getAttribute(Zn.resizeHandleId);It(v,"Resize handle element has no handle id attribute");const[x,S]=aTe(n,v,u,i);if(x==null||S==null)return()=>{};const w=E=>{if(!E.defaultPrevented)switch(E.key){case"Enter":{E.preventDefault();const _=u.findIndex(k=>k.id===x);if(_>=0){const k=u[_];It(k,`No panel data found for index ${_}`);const C=a[_],{collapsedSize:R=0,collapsible:I,minSize:A=0}=k.constraints;if(C!=null&&I){const O=cp({delta:Da(C,R)?A-R:R-C,initialLayout:a,panelConstraints:u.map(M=>M.constraints),pivotIndices:MY(n,v,i),prevLayout:a,trigger:"keyboard"});a!==O&&s(O)}}break}}};return g.addEventListener("keydown",w),()=>{g.removeEventListener("keydown",w)}});return()=>{h.forEach(g=>g())}},[i,e,t,n,a,r,s])}function A2(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function UY(e,t){const n=e==="horizontal",{x:a,y:r}=Tw(t);return n?a:r}function oTe(e,t,n,a,r){const i=n==="horizontal",s=Rw(t,r);It(s,`No resize handle element found for id "${t}"`);const c=s.getAttribute(Zn.groupId);It(c,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=a;const d=UY(n,e),m=PY(c,r);It(m,`No group element found for id "${c}"`);const h=m.getBoundingClientRect(),g=i?h.width:h.height;return(d-u)/g*100}function sTe(e,t,n,a,r,i){if(NY(e)){const s=n==="horizontal";let c=0;e.shiftKey?c=100:r!=null?c=r:c=10;let u=0;switch(e.key){case"ArrowDown":u=s?0:c;break;case"ArrowLeft":u=s?-c:0;break;case"ArrowRight":u=s?c:0;break;case"ArrowUp":u=s?0:-c;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return a==null?0:oTe(e,t,n,a,i)}function lTe({panelDataArray:e}){const t=Array(e.length),n=e.map(i=>i.constraints);let a=0,r=100;for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;c!=null&&(a++,t[i]=c,r-=c)}for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;if(c!=null)continue;const u=e.length-a,d=r/u;a++,t[i]=d,r-=d}return t}function Xc(e,t,n){t.forEach((a,r)=>{const i=e[r];It(i,`Panel data not found for index ${r}`);const{callbacks:s,constraints:c,id:u}=i,{collapsedSize:d=0,collapsible:m}=c,h=n[u];if(h==null||a!==h){n[u]=a;const{onCollapse:g,onExpand:v,onResize:x}=s;x&&x(a,h),m&&(g||v)&&(v&&(h==null||No(h,d))&&!No(a,d)&&v(),g&&(h==null||!No(h,d))&&No(a,d)&&g())}})}function Eb(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function cTe({defaultSize:e,dragState:t,layout:n,panelData:a,panelIndex:r,precision:i=3}){const s=n[r];let c;return s==null?c=e!=null?e.toFixed(i):"1":a.length===1?c="1":c=s.toFixed(i),{flexBasis:0,flexGrow:c,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function uTe(e,t=10){let n=null;return(...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function I2(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function zY(e){return`react-resizable-panels:${e}`}function FY(e){return e.map(t=>{const{constraints:n,id:a,idIsFromProps:r,order:i}=t;return r?a:i?`${i}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function BY(e,t){try{const n=zY(e),a=t.getItem(n);if(a){const r=JSON.parse(a);if(typeof r=="object"&&r!=null)return r}}catch{}return null}function dTe(e,t,n){var a,r;const i=(a=BY(e,n))!==null&&a!==void 0?a:{},s=FY(t);return(r=i[s])!==null&&r!==void 0?r:null}function fTe(e,t,n,a,r){var i;const s=zY(e),c=FY(t),u=(i=BY(e,r))!==null&&i!==void 0?i:{};u[c]={expandToSizes:Object.fromEntries(n.entries()),layout:a};try{r.setItem(s,JSON.stringify(u))}catch(d){console.error(d)}}function O2({layout:e,panelConstraints:t}){const n=[...e],a=n.reduce((i,s)=>i+s,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(i=>`${i}%`).join(", ")}`);if(!Da(a,100)&&n.length>0)for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=100/a*s;n[i]=c}let r=0;for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=wu({panelConstraints:t,panelIndex:i,size:s});s!=c&&(r+=s-c,n[i]=c)}if(!Da(r,0))for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=s+r,u=wu({panelConstraints:t,panelIndex:i,size:c});if(s!==u&&(r-=u-s,n[i]=u,Da(r,0)))break}return n}const pTe=100,up={getItem:e=>(I2(up),up.getItem(e)),setItem:(e,t)=>{I2(up),up.setItem(e,t)}},D2={};function HY({autoSaveId:e=null,children:t,className:n="",direction:a,forwardedRef:r,id:i=null,onLayout:s=null,keyboardResizeBy:c=null,storage:u=up,style:d,tagName:m="div",...h}){const g=_D(i),v=y.useRef(null),[x,S]=y.useState(null),[w,E]=y.useState([]),_=eTe(),k=y.useRef({}),C=y.useRef(new Map),R=y.useRef(0),I=y.useRef({autoSaveId:e,direction:a,dragState:x,id:g,keyboardResizeBy:c,onLayout:s,storage:u}),A=y.useRef({layout:w,panelDataArray:[],panelDataArrayChanged:!1});y.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),y.useImperativeHandle(r,()=>({getId:()=>I.current.id,getLayout:()=>{const{layout:z}=A.current;return z},setLayout:z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current,W=O2({layout:z,panelConstraints:F.map(ne=>ne.constraints)});A2(L,W)||(E(W),A.current.layout=W,$&&$(W),Xc(F,W,k.current))}}),[]),Ul(()=>{I.current.autoSaveId=e,I.current.direction=a,I.current.dragState=x,I.current.id=g,I.current.onLayout=s,I.current.storage=u}),iTe({committedValuesRef:I,eagerValuesRef:A,groupId:g,layout:w,panelDataArray:A.current.panelDataArray,setLayout:E,panelGroupElement:v.current}),y.useEffect(()=>{const{panelDataArray:z}=A.current;if(e){if(w.length===0||w.length!==z.length)return;let $=D2[e];$==null&&($=uTe(fTe,pTe),D2[e]=$);const L=[...z],F=new Map(C.current);$(e,L,F,w,u)}},[e,w,u]),y.useEffect(()=>{});const O=y.useCallback(z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current;if(z.constraints.collapsible){const W=F.map(X=>X.constraints),{collapsedSize:ne=0,panelSize:le,pivotIndices:ue}=_l(F,z,L);if(It(le!=null,`Panel size not found for panel "${z.id}"`),!No(le,ne)){C.current.set(z.id,le);const q=su(F,z)===F.length-1?le-ne:ne-le,oe=cp({delta:q,initialLayout:L,panelConstraints:W,pivotIndices:ue,prevLayout:L,trigger:"imperative-api"});Eb(L,oe)||(E(oe),A.current.layout=oe,$&&$(oe),Xc(F,oe,k.current))}}},[]),M=y.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current;if(z.constraints.collapsible){const ne=W.map(me=>me.constraints),{collapsedSize:le=0,panelSize:ue=0,minSize:X=0,pivotIndices:q}=_l(W,z,F),oe=$??X;if(No(ue,le)){const me=C.current.get(z.id),ie=me!=null&&me>=oe?me:oe,He=su(W,z)===W.length-1?ue-ie:ie-ue,ye=cp({delta:He,initialLayout:F,panelConstraints:ne,pivotIndices:q,prevLayout:F,trigger:"imperative-api"});Eb(F,ye)||(E(ye),A.current.layout=ye,L&&L(ye),Xc(W,ye,k.current))}}},[]),P=y.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{panelSize:F}=_l(L,z,$);return It(F!=null,`Panel size not found for panel "${z.id}"`),F},[]),B=y.useCallback((z,$)=>{const{panelDataArray:L}=A.current,F=su(L,z);return cTe({defaultSize:$,dragState:x,layout:w,panelData:L,panelIndex:F})},[x,w]),K=y.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:ne}=_l(L,z,$);return It(ne!=null,`Panel size not found for panel "${z.id}"`),W===!0&&No(ne,F)},[]),Q=y.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:ne}=_l(L,z,$);return It(ne!=null,`Panel size not found for panel "${z.id}"`),!W||Ql(ne,F)>0},[]),ee=y.useCallback(z=>{const{panelDataArray:$}=A.current;$.push(z),$.sort((L,F)=>{const W=L.order,ne=F.order;return W==null&&ne==null?0:W==null?-1:ne==null?1:W-ne}),A.current.panelDataArrayChanged=!0,_()},[_]);Ul(()=>{if(A.current.panelDataArrayChanged){A.current.panelDataArrayChanged=!1;const{autoSaveId:z,onLayout:$,storage:L}=I.current,{layout:F,panelDataArray:W}=A.current;let ne=null;if(z){const ue=dTe(z,W,L);ue&&(C.current=new Map(Object.entries(ue.expandToSizes)),ne=ue.layout)}ne==null&&(ne=lTe({panelDataArray:W}));const le=O2({layout:ne,panelConstraints:W.map(ue=>ue.constraints)});A2(F,le)||(E(le),A.current.layout=le,$&&$(le),Xc(W,le,k.current))}}),Ul(()=>{const z=A.current;return()=>{z.layout=[]}},[]);const ae=y.useCallback(z=>{let $=!1;const L=v.current;return L&&window.getComputedStyle(L,null).getPropertyValue("direction")==="rtl"&&($=!0),function(W){W.preventDefault();const ne=v.current;if(!ne)return()=>null;const{direction:le,dragState:ue,id:X,keyboardResizeBy:q,onLayout:oe}=I.current,{layout:me,panelDataArray:ie}=A.current,{initialLayout:Ne}=ue??{},He=MY(X,z,ne);let ye=sTe(W,z,le,ue,q,ne);const Se=le==="horizontal";Se&&$&&(ye=-ye);const Pe=ie.map(Me=>Me.constraints),fe=cp({delta:ye,initialLayout:Ne??me,panelConstraints:Pe,pivotIndices:He,prevLayout:me,trigger:NY(W)?"keyboard":"mouse-or-touch"}),Ae=!Eb(me,fe);(CY(W)||RY(W))&&R.current!=ye&&(R.current=ye,!Ae&&ye!==0?Se?t_(z,ye<0?IY:OY):t_(z,ye<0?DY:jY):t_(z,0)),Ae&&(E(fe),A.current.layout=fe,oe&&oe(fe),Xc(ie,fe,k.current))}},[]),H=y.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current,ne=W.map(me=>me.constraints),{panelSize:le,pivotIndices:ue}=_l(W,z,F);It(le!=null,`Panel size not found for panel "${z.id}"`);const q=su(W,z)===W.length-1?le-$:$-le,oe=cp({delta:q,initialLayout:F,panelConstraints:ne,pivotIndices:ue,prevLayout:F,trigger:"imperative-api"});Eb(F,oe)||(E(oe),A.current.layout=oe,L&&L(oe),Xc(W,oe,k.current))},[]),Z=y.useCallback((z,$)=>{const{layout:L,panelDataArray:F}=A.current,{collapsedSize:W=0,collapsible:ne}=$,{collapsedSize:le=0,collapsible:ue,maxSize:X=100,minSize:q=0}=z.constraints,{panelSize:oe}=_l(F,z,L);oe!=null&&(ne&&ue&&No(oe,W)?No(W,le)||H(z,le):oe<q?H(z,q):oe>X&&H(z,X))},[H]),G=y.useCallback((z,$)=>{const{direction:L}=I.current,{layout:F}=A.current;if(!v.current)return;const W=Rw(z,v.current);It(W,`Drag handle element not found for id "${z}"`);const ne=UY(L,$);S({dragHandleId:z,dragHandleRect:W.getBoundingClientRect(),initialCursorPosition:ne,initialLayout:F})},[]),re=y.useCallback(()=>{S(null)},[]),te=y.useCallback(z=>{const{panelDataArray:$}=A.current,L=su($,z);L>=0&&($.splice(L,1),delete k.current[z.id],A.current.panelDataArrayChanged=!0,_())},[_]),j=y.useMemo(()=>({collapsePanel:O,direction:a,dragState:x,expandPanel:M,getPanelSize:P,getPanelStyle:B,groupId:g,isPanelCollapsed:K,isPanelExpanded:Q,reevaluatePanelConstraints:Z,registerPanel:ee,registerResizeHandle:ae,resizePanel:H,startDragging:G,stopDragging:re,unregisterPanel:te,panelGroupElement:v.current}),[O,x,a,M,P,B,g,K,Q,Z,ee,ae,H,G,re,te]),V={display:"flex",flexDirection:a==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return y.createElement(kw.Provider,{value:j},y.createElement(m,{...h,children:t,className:n,id:i,ref:v,style:{...V,...d},[Zn.group]:"",[Zn.groupDirection]:a,[Zn.groupId]:g}))}const VY=y.forwardRef((e,t)=>y.createElement(HY,{...e,forwardedRef:t}));HY.displayName="PanelGroup";VY.displayName="forwardRef(PanelGroup)";function su(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function _l(e,t,n){const a=su(e,t),i=a===e.length-1?[a-1,a]:[a,a+1],s=n[a];return{...t.constraints,panelSize:s,pivotIndices:i}}function mTe({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:a}){y.useEffect(()=>{if(e||n==null||a==null)return;const r=Rw(t,a);if(r==null)return;const i=s=>{if(!s.defaultPrevented)switch(s.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{s.preventDefault(),n(s);break}case"F6":{s.preventDefault();const c=r.getAttribute(Zn.groupId);It(c,`No group element found for id "${c}"`);const u=lm(c,a),d=LY(c,t,a);It(d!==null,`No resize element found for id "${t}"`);const m=s.shiftKey?d>0?d-1:u.length-1:d+1<u.length?d+1:0;u[m].focus();break}}};return r.addEventListener("keydown",i),()=>{r.removeEventListener("keydown",i)}},[a,e,t,n])}function GY({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:a,id:r,onBlur:i,onClick:s,onDragging:c,onFocus:u,onPointerDown:d,onPointerUp:m,style:h={},tabIndex:g=0,tagName:v="div",...x}){var S,w;const E=y.useRef(null),_=y.useRef({onClick:s,onDragging:c,onPointerDown:d,onPointerUp:m});y.useEffect(()=>{_.current.onClick=s,_.current.onDragging=c,_.current.onPointerDown=d,_.current.onPointerUp=m});const k=y.useContext(kw);if(k===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:C,groupId:R,registerResizeHandle:I,startDragging:A,stopDragging:O,panelGroupElement:M}=k,P=_D(r),[B,K]=y.useState("inactive"),[Q,ee]=y.useState(!1),[ae,H]=y.useState(null),Z=y.useRef({state:B});Ul(()=>{Z.current.state=B}),y.useEffect(()=>{if(n)H(null);else{const j=I(P);H(()=>j)}},[n,P,I]);const G=(S=a?.coarse)!==null&&S!==void 0?S:15,re=(w=a?.fine)!==null&&w!==void 0?w:5;y.useEffect(()=>{if(n||ae==null)return;const j=E.current;It(j,"Element ref not attached");let V=!1;return Jke(P,j,C,{coarse:G,fine:re},($,L,F)=>{if(!L){K("inactive");return}switch($){case"down":{K("drag"),V=!1,It(F,'Expected event to be defined for "down" action'),A(P,F);const{onDragging:W,onPointerDown:ne}=_.current;W?.(!0),ne?.();break}case"move":{const{state:W}=Z.current;V=!0,W!=="drag"&&K("hover"),It(F,'Expected event to be defined for "move" action'),ae(F);break}case"up":{K("hover"),O();const{onClick:W,onDragging:ne,onPointerUp:le}=_.current;ne?.(!1),le?.(),V||W?.();break}}})},[G,C,n,re,I,P,ae,A,O]),mTe({disabled:n,handleId:P,resizeHandler:ae,panelGroupElement:M});const te={touchAction:"none",userSelect:"none"};return y.createElement(v,{...x,children:e,className:t,id:r,onBlur:()=>{ee(!1),i?.()},onFocus:()=>{ee(!0),u?.()},ref:E,role:"separator",style:{...te,...h},tabIndex:g,[Zn.groupDirection]:C,[Zn.groupId]:R,[Zn.resizeHandle]:"",[Zn.resizeHandleActive]:B==="drag"?"pointer":Q?"keyboard":void 0,[Zn.resizeHandleEnabled]:!n,[Zn.resizeHandleId]:P,[Zn.resizeHandleState]:B})}GY.displayName="PanelResizeHandle";function na({className:e,...t}){return f.jsx(VY,{"data-slot":"resizable-panel-group",className:De("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Rn({...e}){return f.jsx(TY,{"data-slot":"resizable-panel",...e})}function Si({withHandle:e,className:t,...n}){return f.jsx(GY,{"data-slot":"resizable-handle",className:De("bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&f.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:f.jsx(ihe,{className:"size-2.5"})})})}function eh({className:e,...t}){return f.jsx("kbd",{"data-slot":"kbd",className:De("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}function hTe({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onClearAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search notifications...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Clear all"})]})})]})}function Qs({id:e,isSelected:t,isFocused:n,icon:a,title:r,description:i,metadata:s,onClick:c,className:u}){return f.jsx("button",{id:e,type:"button",onClick:c,className:De("w-full text-left cursor-pointer p-2 sm:p-4 border-b dark:border-zinc-700 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors group",t&&"bg-zinc-50 dark:bg-zinc-800 border-l-4 border-l-zinc-500",n&&"ring-2 ring-zinc-500 dark:ring-zinc-400 ring-inset",u),children:f.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[a&&f.jsx("div",{className:"flex-shrink-0 mt-1",children:f.jsx("div",{className:De("p-2.5 rounded-full transition-colors",t?"bg-zinc-500 dark:bg-zinc-100/80 text-zinc-100 dark:text-zinc-900":"bg-gray-100 dark:bg-zinc-700 text-gray-600 dark:text-gray-400 group-hover:bg-gray-200 dark:group-hover:bg-zinc-600"),children:a})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"flex items-center gap-2 mb-1",children:f.jsx("h3",{className:De("font-medium truncate font-mono text-sm"),children:r})}),i&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:i})]})]})})}function gTe({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>f.jsx(Qs,{id:`notification-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.method,!s.read&&f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=r(s.timestamp),d=s.params&&Object.keys(s.params).length>0?Object.keys(s.params).length:0,m=d>0?` | ${d} param${d>1?"s":""}`:"";return u+m})(),onClick:()=>n(s)},s.id))})}function bTe({notification:e,previewMode:t,onTogglePreview:n,onCopy:a,onDownload:r,onFullscreen:i,isCopied:s=!1,onClose:c}){return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsxs($e,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?f.jsx(JN,{className:"h-4 w-4 mr-1"}):f.jsx(LG,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,children:s?f.jsx(ra,{className:"h-4 w-4"}):f.jsx(Lr,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:r,children:f.jsx(Lm,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:i,children:f.jsx(tC,{className:"h-4 w-4"})}),c&&f.jsx($e,{variant:"ghost",size:"sm",onClick:c,children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto",children:f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:{method:e.method,timestamp:e.timestamp,read:e.read,params:e.params},filename:`notification-${e.method.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(XN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function ny(e){const n=Date.now()-e,a=Math.floor(n/1e3),r=Math.floor(a/60),i=Math.floor(r/60),s=Math.floor(i/24);return a<60?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:s<7?`${s}d ago`:new Date(e).toLocaleDateString()}function vTe({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:a,clearNotifications:r,serverId:i,isConnected:s}){const[c,u]=y.useState(null),[d,m]=y.useState(""),[h,g]=y.useState(-1),[v,x]=y.useState(!0),[S,w]=y.useState(!1),[E,_]=y.useState(!0),[k,C]=y.useState(!1),R=y.useRef(null),I=y.useRef(null),A=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),y.useEffect(()=>{const Z=R.current;if(!Z)return;const G=()=>{Z.scrollTop>0&&(O.current=!0,x(!1))};return Z.addEventListener("scroll",G),()=>Z.removeEventListener("scroll",G)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),y.useEffect(()=>{c&&!c.read&&n(c.id)},[c,n]),y.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=y.useCallback(()=>{d.trim()||w(!1)},[d]),P=y.useMemo(()=>{if(!d.trim())return e;const Z=d.toLowerCase();return e.filter(G=>G.method.toLowerCase().includes(Z)||JSON.stringify(G.params||{}).toLowerCase().includes(Z))},[e,d]);y.useEffect(()=>{g(-1)},[d]),y.useEffect(()=>{const Z=G=>{const re=G.target;if(re.tagName==="INPUT"||re.tagName==="TEXTAREA"||re.contentEditable==="true"||G.metaKey||G.ctrlKey||G.altKey)return;const j=P;if(G.key==="ArrowDown")G.preventDefault(),g(V=>{const z=V+1;return z>=j.length?0:z});else if(G.key==="ArrowUp")G.preventDefault(),g(V=>{const z=V-1;return z<0?j.length-1:z});else if(G.key==="Enter"&&h>=0){G.preventDefault();const V=P[h];V&&B(V)}};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[h,P]),y.useEffect(()=>{if(h>=0){const Z=`notification-${P[h]?.id}`,G=document.getElementById(Z);G&&G.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=y.useCallback(Z=>{u(Z)},[]),K=y.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(r(),u(null))},[r]),Q=y.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(Z){console.error("[NotificationsTab] Failed to copy notification:",Z)}},[c]),ee=y.useCallback(()=>{if(c)try{const Z=new globalThis.Blob([JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)],{type:"application/json"}),G=URL.createObjectURL(Z),re=document.createElement("a");re.href=G,re.download=`notification-${Date.now()}.json`,document.body.appendChild(re),re.click(),document.body.removeChild(re),URL.revokeObjectURL(G)}catch(Z){console.error("[NotificationsTab] Failed to download notification:",Z)}},[c]),ae=y.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(Z){console.error("[NotificationsTab] Failed to toggle fullscreen:",Z)}},[]),H=c?{method:c.method,params:c.params,timestamp:c.timestamp,read:c.read,formatRelativeTime:ny}:null;return s?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(hTe,{isSearchExpanded:S,searchQuery:d,filteredNotificationsCount:P.length,notificationsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onClearAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(gTe,{notifications:P,selectedNotification:c,onNotificationSelect:B,focusedIndex:h,formatRelativeTime:ny,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(bTe,{notification:H,previewMode:E,onTogglePreview:()=>_(!E),onCopy:Q,onDownload:ee,onFullscreen:ae,onClose:()=>u(null),isCopied:k})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(XN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function WY({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:a,secondaryTabTitle:r,primaryCount:i,secondaryCount:s,secondaryIcon:c,primaryIcon:u,searchPlaceholder:d="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:v,searchInputRef:x,primaryTabName:S}){const w=e===S;return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?f.jsx(En,{ref:x,placeholder:d,value:n,onChange:E=>h(E.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:w?a:r}),w&&f.jsxs(f.Fragment,{children:[f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:i}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})]})}),f.jsxs($e,{variant:"ghost",size:"sm",onClick:v,className:"gap-2 flex-shrink-0",children:[w?f.jsx(c,{}):f.jsx(u,{}),f.jsx("span",{className:"hidden sm:inline",children:w?r:a}),w&&s>0&&f.jsx(Sr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:s})]})]})}function j2({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Hp,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((r,i)=>f.jsx(Qs,{id:`prompt-${r.name}`,isSelected:t?.name===r.name,isFocused:a===i,icon:f.jsx(Hp,{className:"h-4 w-4"}),title:r.name,description:r.description,metadata:r.arguments&&r.arguments.length>0&&f.jsxs(Sr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[r.arguments.length," args"]}),onClick:()=>n(r)},r.name))})}function $2({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:a,savedPromptsCount:r,onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d}){return f.jsx(WY,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:a,secondaryCount:r,primaryIcon:Hp,secondaryIcon:fd,searchPlaceholder:"Search prompts...",onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d})}function L2({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:a,focusedIndex:r}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(fd,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),f.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((i,s)=>f.jsx(Qs,{id:`saved-prompt-${i.id}`,isSelected:t?.id===i.id,isFocused:r===s,icon:f.jsx(fd,{className:"h-4 w-4"}),title:i.name,description:`${i.promptName} - ${new Date(i.savedAt).toLocaleString()}`,onClick:()=>n(i)},i.id))})}function yTe({selectedPrompt:e,promptArgs:t,onArgChange:n}){const a=e?.arguments||[];if(!(a.length>0))return f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const i=s=>{const c=s.name,u=t[c],d=typeof u=="string"?u:JSON.stringify(u);return s.type==="boolean"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx("input",{id:c,type:"checkbox",checked:!!u,onChange:m=>n(c,m.target.checked),className:"rounded","aria-label":`Toggle ${c}`}),f.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:s.description})]})]},c):s.type==="number"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,type:"number",value:Number(u)||0,onChange:m=>n(c,Number(m.target.value)),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):s.type==="array"||s.type==="object"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(Xl,{id:c,value:d,onChange:m=>{try{const h=JSON.parse(m.target.value);n(c,h)}catch{n(c,m.target.value)}},placeholder:s.description||`Enter ${c} as JSON`,className:"font-mono text-sm min-h-[100px]"}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,value:d,onChange:m=>n(c,m.target.value),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c)};return f.jsx("div",{className:"space-y-4",children:a.map(s=>i(s))})}function M2({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:a,onArgChange:r,onExecute:i,onSave:s}){return y.useEffect(()=>{const c=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&a&&(u.preventDefault(),i())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[e,n,a,i]),e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[f.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsx($e,{onClick:i,disabled:n||!a,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):f.jsxs(f.Fragment,{children:[f.jsx(FG,{className:"h-4 w-4 sm:mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Execute"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})}),f.jsxs($e,{variant:"outline",onClick:s,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[f.jsx(nC,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),f.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:f.jsx(yTe,{selectedPrompt:e,promptArgs:t,onArgChange:r})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a prompt from the list to view its details and execute it"})]})}function wTe(e){return"isError"in e&&!e.isError?null:"error"in e&&e.error?e.error:"isError"in e&&e.isError?"An error occurred":null}function P2({results:e,copiedResult:t,onCopy:n}){return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:e.length>0?f.jsx("div",{className:"space-y-4 flex-1 h-full",children:e.map((a,r)=>{const i=a.error||wTe(a.result);return f.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[f.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(a.timestamp).toLocaleTimeString()})]}),a.duration!==void 0&&f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[a.duration,"ms"]})]}),f.jsx("div",{className:"flex gap-2 ml-auto",children:f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>n(r,a.result),className:"h-6 px-2",children:t===r?f.jsx(ra,{className:"h-4 w-4"}):f.jsx(Lr,{className:"h-4 w-4"})})})]}),i?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:i})]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:a.result,filename:`prompt-result-${a.promptName}-${Date.now()}.json`})})]},r)})}):f.jsx("div",{className:"flex items-center justify-center h-full",children:f.jsx("div",{className:"text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})})}function kD({serverIds:e,onCountChange:t,onClearRef:n}={}){const[a,r]=y.useState([]),i=y.useRef(null),[s,c]=y.useState(new Set),[u]=y.useState(""),d=v=>{c(x=>{const S=new Set(x);return S.has(v)?S.delete(v):S.add(v),S})},m=async()=>{r([]),c(new Set),t?.(0);try{const v=new URLSearchParams;e&&e.length>0&&v.set("serverIds",e.join(","));const x=await fetch(`/inspector/api/rpc/log?${v.toString()}`,{method:"DELETE"});x.ok||console.warn("[RPC Logger] Failed to clear server buffer:",x.status)}catch(v){console.warn("[RPC Logger] Error clearing server buffer:",v)}},h=y.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);y.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),y.useEffect(()=>{t?.(a.length)},[a.length,t]),y.useEffect(()=>{let v=null;try{const x=new URLSearchParams;x.set("replay","50"),x.set("_t",Date.now().toString()),e&&e.length>0&&x.set("serverIds",e.join(","));const S=`/inspector/api/rpc/stream?${x.toString()}`;console.log("[RPC Logger] Connecting to SSE stream:",S),v=new globalThis.EventSource(S),v.onopen=()=>{console.log("[RPC Logger] SSE connection opened")},v.onmessage=w=>{try{const E=JSON.parse(w.data);if(!E||E.type!=="rpc")return;const{serverId:_,direction:k,message:C,timestamp:R}=E,I=C,A=typeof I?.method=="string"?I.method:I?.result!==void 0?"result":I?.error!==void 0?"error":"unknown",O={id:`${R??Date.now()}-${Math.random().toString(36).slice(2)}`,serverId:typeof _=="string"?_:"unknown",direction:typeof k=="string"?k.toUpperCase():"",method:A,timestamp:R??new Date().toISOString(),payload:C};console.log("[RPC Logger] Received RPC event:",{method:A,direction:k,serverId:_}),r(M=>{const P=[O,...M].slice(0,1e3);return t?.(P.length),P})}catch(E){console.error("[RPC Logger] Error parsing SSE message:",E)}},v.onerror=w=>{console.error("[RPC Logger] SSE connection error:",w);try{v?.close()}catch{}}}catch(x){console.error("[RPC Logger] Failed to create SSE connection:",x)}return()=>{try{v?.close(),console.log("[RPC Logger] SSE connection closed")}catch{}}},[h]);const g=y.useMemo(()=>{let v=a;if(e&&e.length>0){const x=new Set(e);v=v.filter(S=>x.has(S.serverId))}if(u.trim()){const x=u.toLowerCase();v=v.filter(S=>S.serverId.toLowerCase().includes(x)||S.method.toLowerCase().includes(x)||S.direction.toLowerCase().includes(x)||JSON.stringify(S.payload).toLowerCase().includes(x))}return v=[...v].sort((x,S)=>new Date(S.timestamp).getTime()-new Date(x.timestamp).getTime()),v},[a,u,e]);return f.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:f.jsx("div",{ref:i,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?f.jsxs("div",{className:"text-center py-8",children:[f.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),f.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(v=>{const x=s.has(v.id);return f.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[f.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>d(v.id),children:[f.jsx("div",{className:"flex-shrink-0",children:x?f.jsx(ac,{className:"h-3 w-3 text-muted-foreground transition-transform"}):f.jsx(MG,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),f.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[f.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(v.timestamp).toLocaleTimeString()}),f.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${v.direction==="RECEIVE"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-green-500/10 text-green-600 dark:text-green-400"}`,title:v.direction==="RECEIVE"?"Incoming":"Outgoing",children:v.direction==="RECEIVE"?f.jsx(hme,{className:"h-3 w-3"}):f.jsx(bme,{className:"h-3 w-3"})}),f.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:v.method})]})]}),x&&f.jsx("div",{className:"border-t bg-muted/20",children:f.jsx("div",{className:"p-3",children:f.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:f.jsx(Xn,{data:v.payload})})})})]},v.id)})})})}const U2="mcp-inspector-saved-prompts";function KY({ref:e,prompts:t,callPrompt:n,serverId:a,isConnected:r}){const[i,s]=y.useState(null),[c,u]=y.useState(null),{selectedPromptName:d,setSelectedPromptName:m}=ic(),[h,g]=y.useState({}),[v,x]=y.useState([]),[S,w]=y.useState(!1),[E,_]=y.useState(null),[k,C]=y.useState(""),[R,I]=y.useState("prompts"),[A,O]=y.useState([]),[M,P]=y.useState(!1),[B,K]=y.useState(""),[Q,ee]=y.useState(!1),[ae,H]=y.useState(-1),Z=y.useRef(null),[G,re]=y.useState(!1),[te,j]=y.useState("list"),[V,z]=y.useState(0),[$,L]=y.useState(!0),F=y.useRef(null),W=y.useRef(null);y.useEffect(()=>{const ye=()=>{re(window.innerWidth<1024)};return ye(),window.addEventListener("resize",ye),()=>window.removeEventListener("resize",ye)},[]),y.useEffect(()=>{j(i?"detail":"list")},[i]),y.useEffect(()=>{G&&v.length>0&&!S&&j("response")},[v,S,G]),y.useImperativeHandle(e,()=>({focusSearch:()=>{ee(!0),setTimeout(()=>{Z.current&&Z.current.focus()},0)},blurSearch:()=>{C(""),ee(!1),Z.current&&Z.current.blur()}})),y.useEffect(()=>{try{const ye=localStorage.getItem(U2);if(ye){const Se=JSON.parse(ye);O(Se)}}catch(ye){console.error("[PromptsTab] Failed to load saved prompts:",ye)}},[]);const ne=y.useCallback(ye=>{try{localStorage.setItem(U2,JSON.stringify(ye))}catch(Se){console.error("[PromptsTab] Failed to save prompts:",Se)}},[]);y.useEffect(()=>{Q&&Z.current&&Z.current.focus()},[Q]);const le=y.useCallback(()=>{k.trim()||ee(!1)},[k]),ue=y.useMemo(()=>{if(!k.trim())return t;const ye=k.toLowerCase();return t.filter(Se=>Se.name.toLowerCase().includes(ye)||Se.description?.toLowerCase().includes(ye))},[t,k]),X=y.useCallback(ye=>{s(ye);const Se={};ye.arguments&&ye.arguments.forEach(Pe=>{Pe.default!==void 0?Se[Pe.name]=Pe.default:Pe.type==="string"?Se[Pe.name]="":Pe.type==="number"?Se[Pe.name]=0:Pe.type==="boolean"?Se[Pe.name]=!1:Pe.type==="array"?Se[Pe.name]=[]:Pe.type==="object"&&(Se[Pe.name]={})}),g(Se)},[]),q=y.useCallback(ye=>{const Se=t.find(Pe=>Pe.name===ye.promptName);Se&&(s(Se),g(ye.args),u(ye))},[t]);y.useEffect(()=>{H(-1)},[k,R]),y.useEffect(()=>{const ye=Se=>{const Pe=Se.target;if(Pe.tagName==="INPUT"||Pe.tagName==="TEXTAREA"||Pe.contentEditable==="true"||Se.metaKey||Se.ctrlKey||Se.altKey)return;const Ae=R==="prompts"?ue:A;if(Se.key==="ArrowDown")Se.preventDefault(),H(Me=>{const _e=Me+1;return _e>=Ae.length?0:_e});else if(Se.key==="ArrowUp")Se.preventDefault(),H(Me=>{const _e=Me-1;return _e<0?Ae.length-1:_e});else if(Se.key==="Enter"&&ae>=0)if(Se.preventDefault(),R==="prompts"){const Me=ue[ae];Me&&X(Me)}else{const Me=A[ae];Me&&q(Me)}};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[ae,ue,A,R,X,q]),y.useEffect(()=>{if(ae>=0){const ye=R==="prompts"?`prompt-${ue[ae]?.name}`:`saved-prompt-${A[ae]?.id}`,Se=document.getElementById(ye);Se&&Se.scrollIntoView({behavior:"smooth",block:"nearest"})}},[ae,ue,A,R]),y.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:d,promptsCount:t.length,currentSelectedPrompt:i?.name}),d&&t.length>0){const ye=t.find(Se=>Se.name===d);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:d,promptFound:!!ye,promptName:ye?.name,shouldSelect:ye&&i?.name!==ye.name}),ye&&i?.name!==ye.name){console.warn("[PromptsTab] Selecting prompt:",ye.name),m(null);const Se=setTimeout(()=>{X(ye);const Pe=document.getElementById(`prompt-${ye.name}`);Pe&&(console.warn("[PromptsTab] Scrolling to prompt element"),Pe.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(Se)}}},[d,t,i,X,m]);const oe=y.useCallback((ye,Se)=>{g(Pe=>({...Pe,[ye]:Se}))},[]),me=y.useCallback(async()=>{if(!i||S)return;w(!0);const ye=Date.now();try{const Se=await n(i.name,h),Pe=Date.now()-ye;yr.getInstance().capture(new QU({promptName:i.name,serverId:a,success:!0})).catch(()=>{}),x(Ae=>[{promptName:i.name,args:h,result:Se,timestamp:ye,duration:Pe},...Ae])}catch(Se){yr.getInstance().capture(new QU({promptName:i.name,serverId:a,success:!1,error:Se instanceof Error?Se.message:"Unknown error"})).catch(()=>{});const fe={promptName:i.name,args:h,result:null,error:Se instanceof Error?Se.message:String(Se),timestamp:ye,duration:Date.now()-ye};x(Ae=>[fe,...Ae])}finally{w(!1)}},[i,h,S,n,a]),ie=y.useCallback(async(ye,Se)=>{try{await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),_(ye),setTimeout(()=>_(null),2e3)}catch(Pe){console.error("[PromptsTab] Failed to copy result:",Pe)}},[]),Ne=y.useCallback(()=>{i&&(K(""),P(!0))},[i]),He=y.useCallback(ye=>{ne(A.filter(Se=>Se.id!==ye)),c?.id===ye&&u(null)},[A,ne,c]);return G?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[te!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{te==="response"?j("detail"):(s(null),j("list"))},className:"p-0 h-8 w-8",children:f.jsx(Xy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{s(null),j("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Prompts"}),te!=="list"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{te==="response"&&j("detail")},className:te==="detail"?"text-foreground hover:underline":te==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),te==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(aw,{initial:!1,mode:"popLayout",children:[te==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx($2,{activeTab:R,isSearchExpanded:Q,searchQuery:k,filteredPromptsCount:ue.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:C,onSearchBlur:le,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(j2,{prompts:ue,selectedPrompt:i,onPromptSelect:X,focusedIndex:ae}):f.jsx(L2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:He,focusedIndex:ae})]},"list"),te==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(M2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:oe,onExecute:me,onSave:Ne})},"detail"),te==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(P2,{results:v,copiedResult:E,onCopy:ie})},"response")]})})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:33,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx($2,{activeTab:R,isSearchExpanded:Q,searchQuery:k,filteredPromptsCount:ue.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:C,onSearchBlur:le,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(j2,{prompts:ue,selectedPrompt:i,onPromptSelect:X,focusedIndex:ae}):f.jsx(L2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:He,focusedIndex:ae})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:F,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>L(!0),onExpand:()=>L(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:ye=>{ye.preventDefault(),ye.stopPropagation(),$?(F.current?.resize(25),L(!1)):(F.current?.resize(5),L(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),V>0&&f.jsx(Sr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:V}),V>0&&!$&&f.jsx($e,{variant:"ghost",size:"sm",onClick:ye=>{ye.preventDefault(),ye.stopPropagation(),W.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${$?"rotate-180":""}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${$?"hidden":""}`,children:f.jsx(kD,{serverIds:[a],onCountChange:z,onClearRef:W})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{defaultSize:40,children:f.jsx(M2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:oe,onExecute:me,onSave:Ne})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:50,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(P2,{results:v,copiedResult:E,onCopy:ie})})})]})})]})}KY.displayName="PromptsTab";function Ru(e){if(!e?.mimeType)return!1;const t=e.mimeType.toLowerCase();return t==="text/html"||t==="text/html+skybridge"||t==="text/uri-list"||t.startsWith("application/vnd.mcp-ui.remote-dom")}function STe(e){return{uri:e.uri,mimeType:e.mimeType,text:e.text,blob:e.blob}}function ZY({resource:e,onUIAction:t,className:n}){const a=async i=>t?.(i),r=STe(e);return f.jsx("div",{className:n,children:f.jsx(SD,{resource:r,onUIAction:a,htmlProps:{autoResizeIframe:{width:!0,height:!0},style:{width:"100%",minHeight:"200px"},sandboxPermissions:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"},remoteDomProps:{remoteElements:[Oke,Ike,Dke,jke],library:wD}})})}function xTe(e){if("error"in e&&e.error)return e.error;if(!("isError"in e&&e.isError))return null;if("contents"in e&&Array.isArray(e.contents)){const t=e.contents.filter(n=>"text"in n).map(n=>n.text).filter(Boolean);if(t.length>0)return t.join(`
|
|
1660
|
+
`);k=I.pop()||"";for(const A of I)if(A.trim()&&A.startsWith("data: "))try{const O=JSON.parse(A.slice(6));if(console.log("[Client received event]",O.type,O.toolName||O.content?.slice?.(0,30)),O.type==="message")console.log("[Message started]",O.id);else if(O.type==="text"){S+=O.content;const M=w[w.length-1];M&&M.type==="text"?M.text=S:w.push({type:"text",text:S}),console.log("[Parts after text]",w.length,"parts, text length:",S.length),i(P=>P.map(B=>B.id===x?{...B,parts:[...w]}:B))}else if(O.type==="tool-call")S&&(S=""),w.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",w.length,"parts, tool:",O.toolName),i(M=>M.map(P=>P.id===x?{...P,parts:[...w]}:P));else if(O.type==="tool-result"){const M=w.find(P=>P.type==="tool-invocation"&&P.toolInvocation?.toolName===O.toolName&&!P.toolInvocation?.result);M&&M.toolInvocation?(M.toolInvocation.result=O.result,M.toolInvocation.state="result",console.log("[Parts after tool-result]",w.length,"parts, updated:",O.toolName),i(P=>P.map(B=>B.id===x?{...B,parts:[...w]}:B))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",w.length),i(M=>M.map(P=>P.id===x?{...P,parts:[...w],content:""}:P));else if(O.type==="error")throw new Error(O.message||"Streaming error")}catch(O){console.error("Failed to parse streaming event:",O,A)}}}catch(g){let v="Unknown error occurred";if(g instanceof Error){v=g.message;const S=g;S.status&&(v=`HTTP ${S.status}: ${v}`),(S.code===401||v.includes("401")||v.includes("Unauthorized"))&&(v="Authentication failed (401). Check your Authorization header in the connection settings.")}const x={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${v}`,timestamp:Date.now()};i(S=>[...S,x])}finally{c(!1)}},[t,a,e,r,n]),d=y.useCallback(()=>{i([])},[]);return{messages:r,isLoading:s,sendMessage:u,clearMessages:d}}function Uke({connection:e,llmConfig:t,isConnected:n,readResource:a}){const[r,i]=y.useState([]),[s,c]=y.useState(!1),u=y.useRef(null),d=y.useRef(null),m=y.useRef(null),h=y.useCallback(async v=>{if(!v.trim()||!t||!n)return;const x={id:`user-${Date.now()}`,role:"user",content:v.trim(),timestamp:Date.now()};i(E=>[...E,x]),c(!0),u.current=new AbortController;const S=Date.now();let w=0;try{const E=`assistant-${Date.now()}`;let _="";const k=[];if(i(C=>[...C,{id:E,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]),!m.current||m.current.provider!==t.provider||m.current.model!==t.model||m.current.apiKey!==t.apiKey){let C;if(t.provider==="openai"){const{ChatOpenAI:R}=await Jn(async()=>{const{ChatOpenAI:I}=await import("./index-B5kLR_Rv.js");return{ChatOpenAI:I}},__vite__mapDeps([6,7,8,2,9,10,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:R}=await Jn(async()=>{const{ChatAnthropic:I}=await import("./index-sQyTG4jp.js");return{ChatAnthropic:I}},__vite__mapDeps([12,8,7,2,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:R}=await Jn(async()=>{const{ChatGoogleGenerativeAI:I}=await import("./index-BYR-I2bf.js");return{ChatGoogleGenerativeAI:I}},__vite__mapDeps([13,8,7,2,10]));C=new R({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:C,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!d.current||d.current.llm!==m.current.instance){const{MCPAgent:C}=await Jn(async()=>{const{MCPAgent:R}=await import("./browser-DZ15LLaB.js");return{MCPAgent:R}},__vite__mapDeps([14,4,5,3,11,7,8,2,10,9]));d.current=new C({llm:m.current.instance,client:e.client,memoryEnabled:!0,systemPrompt:"You are a helpful assistant with access to MCP tools, prompts, and resources. Help users interact with the MCP server."}),await d.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",d.current.conversationHistory?.length);for await(const C of d.current.streamEvents(v,10,!1,void 0)){if(u.current?.signal.aborted)break;if(C.event==="on_chat_model_stream"&&C.data?.chunk?.text){const R=C.data.chunk.text;if(typeof R=="string"&&R.length>0){_+=R;const I=k[k.length-1];I&&I.type==="text"?I.text=_:k.push({type:"text",text:_}),i(A=>A.map(O=>O.id===E?{...O,parts:[...k]}:O))}}else if(C.event==="on_tool_start"){_&&(_="");let R={};C.data?.input?R=C.data.input:C.data?.tool_input?R=C.data.tool_input:C.data&&(R=C.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:C.name,eventData:C.data,extractedArgs:R}),w++,k.push({type:"tool-invocation",toolInvocation:{toolName:C.name||"unknown",args:R,state:"pending"}}),i(I=>I.map(A=>A.id===E?{...A,parts:[...k]}:A))}else if(C.event==="on_tool_end"){const R=k.find(I=>I.type==="tool-invocation"&&I.toolInvocation?.toolName===C.name&&!I.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:C.name,hasToolPart:!!R,output:C.data?.output}),R&&R.toolInvocation){let I=C.data?.output;if(I?.kwargs?.content&&typeof I.kwargs.content=="string")try{I=JSON.parse(I.kwargs.content)}catch(O){console.warn("[useChatMessagesClientSide] Failed to parse kwargs.content:",O),I=I.kwargs.content}else if(I?.content&&typeof I.content=="string")try{I=JSON.parse(I.content)}catch{I=I.content}R.toolInvocation.result=I,R.toolInvocation.state="result";const A=I?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:C.name,hasMeta:!!I?._meta,hasStructuredContent:!!I?.structuredContent,appsSdkUri:A}),A&&typeof A=="string"&&a){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",A);try{const O=await a(A);console.log("[useChatMessagesClientSide] Resource fetched:",O);const M=I?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const P=O.contents.map(K=>({type:"resource",resource:K}));console.log("[useChatMessagesClientSide] Created MCP resources:",P);const B={...I,content:[...I.content||[],...P],structuredContent:M};R.toolInvocation.result=B,console.log("[useChatMessagesClientSide] Updated result with resources")}else console.warn("[useChatMessagesClientSide] No contents in resourceData:",O)}catch(O){console.error("Failed to fetch Apps SDK resource:",O)}}i(O=>O.map(M=>M.id===E?{...M,parts:[...k]}:M))}}}i(C=>C.map(R=>R.id===E?{...R,parts:[...k],content:""}:R)),t&&yr.getInstance().capture(new ez({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:w,success:!0,executionMode:"client-side",duration:Date.now()-S})).catch(()=>{})}catch(E){console.error("Client-side agent error:",E);let _="Unknown error occurred";if(E instanceof Error){_=E.message;const C=E;C.status&&(_=`HTTP ${C.status}: ${_}`),(C.code===401||_.includes("401")||_.includes("Unauthorized"))&&(_="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&yr.getInstance().capture(new ez({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:w,success:!1,executionMode:"client-side",duration:Date.now()-S,error:_})).catch(()=>{});const k={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${_}`,timestamp:Date.now()};i(C=>[...C,k])}finally{c(!1),u.current=null}},[e,t,n,r,a]),g=y.useCallback(()=>{i([]),d.current&&d.current.clearConversationHistory()},[]);return{messages:r,isLoading:s,sendMessage:h,clearMessages:g}}const k2={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function EY({mcpServerUrl:e}){const[t,n]=y.useState(null),[a,r]=y.useState(null),[i,s]=y.useState(!1),[c,u]=y.useState("openai"),[d,m]=y.useState(""),[h,g]=y.useState(k2.openai),v=y.useCallback(()=>{const M=localStorage.getItem("mcp-inspector-api-keys");if(M)try{return JSON.parse(M)}catch(P){return console.error("Failed to load API keys:",P),{}}return{}},[]),x=y.useCallback(M=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(M))},[]),[S,w]=y.useState("none"),[E,_]=y.useState(""),[k,C]=y.useState(""),[R,I]=y.useState("");y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-llm-config"),P=v();if(M)try{const B=JSON.parse(M);n(B),u(B.provider),m(P[B.provider]||B.apiKey||""),g(B.model)}catch(B){console.error("Failed to load LLM config:",B)}},[v]),y.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-auth-config");if(M)try{const P=JSON.parse(M);r(P),w(P.type),P.username&&_(P.username),P.password&&C(P.password),P.token&&I(P.token)}catch(P){console.error("Failed to load auth config:",P)}else try{const P="mcp:auth",B=_Y(e),K=`${P}_${B}_tokens`;localStorage.getItem(K)&&(r({type:"oauth"}),w("oauth"))}catch(P){console.error("Failed to check for OAuth tokens:",P)}},[e]),y.useEffect(()=>{g(k2[c]);const M=v();m(M[c]||"")},[c,v]);const A=y.useCallback(()=>{if(!d.trim())return;const M=v();M[c]=d,x(M);const P={provider:c,apiKey:d,model:h},B={type:S,...S==="basic"&&{username:E.trim(),password:k.trim()},...S==="bearer"&&{token:R.trim()}};n(P),r(B),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(P)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(B)),s(!1)},[c,d,h,S,E,k,R,v,x]),O=y.useCallback(()=>{n(null),r(null);const M=v();delete M[c],x(M),m(""),_(""),C(""),I(""),w("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[c,v,x]);return{llmConfig:t,authConfig:a,configDialogOpen:i,setConfigDialogOpen:s,tempProvider:c,setTempProvider:u,tempApiKey:d,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:S,saveLLMConfig:A,clearConfig:O}}function zke({connection:e,isConnected:t,useClientSide:n=!0,readResource:a}){const[r,i]=y.useState(""),s=y.useRef(null),{llmConfig:c,authConfig:u,configDialogOpen:d,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:v,setTempApiKey:x,tempModel:S,setTempModel:w,saveLLMConfig:E,clearConfig:_}=EY({mcpServerUrl:e.url}),k={connection:e,llmConfig:c,isConnected:t,readResource:a},C=Pke({mcpServerUrl:e.url,llmConfig:c,authConfig:u,isConnected:t}),R=Uke(k),{messages:I,isLoading:A,sendMessage:O,clearMessages:M}=n?R:C;xK({onNewChat:M}),y.useEffect(()=>{c&&I.length===0&&s.current&&s.current.focus()},[c,I.length]),y.useEffect(()=>{!A&&I.length>0&&s.current&&s.current.focus()},[A,I.length]);const P=y.useCallback(()=>{r.trim()&&(O(r),i(""))},[r,O]),B=y.useCallback(Q=>{Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),P())},[P]),K=y.useCallback(()=>{_(),M()},[_,M]);return c&&I.length===0?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"absolute top-4 right-4 z-10",children:f.jsx(CE,{open:d,onOpenChange:m,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSave:E,onClear:K,showClearButton:!0,buttonLabel:"Change API Key"})}),f.jsx(exe,{mcpServerUrl:e.url,inputValue:r,isConnected:t,isLoading:A,textareaRef:s,llmConfig:c,onInputChange:i,onKeyDown:B,onSubmit:Q=>{Q.preventDefault(),P()},onConfigDialogOpenChange:m})]}):f.jsxs("div",{className:"flex flex-col h-full relative",children:[f.jsx(XSe,{llmConfig:c,hasMessages:I.length>0,configDialogOpen:d,onConfigDialogOpenChange:m,onClearChat:M,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSaveConfig:E,onClearConfig:K}),f.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:c?f.jsx(Mke,{messages:I,isLoading:A,serverId:e.url,readResource:a,tools:e.tools}):f.jsx(txe,{onConfigureClick:()=>m(!0)})}),c&&f.jsx(JSe,{inputValue:r,isConnected:t,isLoading:A,textareaRef:s,onInputChange:i,onKeyDown:B,onSendMessage:P})]})}const kw=y.createContext(null);kw.displayName="PanelGroupContext";const Zn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},xD=10,Ul=y.useLayoutEffect,T2=kd.useId,Fke=typeof T2=="function"?T2:()=>null;let Bke=0;function _D(e=null){const t=Fke(),n=y.useRef(e||t||null);return n.current===null&&(n.current=""+Bke++),e??n.current}function kY({children:e,className:t="",collapsedSize:n,collapsible:a,defaultSize:r,forwardedRef:i,id:s,maxSize:c,minSize:u,onCollapse:d,onExpand:m,onResize:h,order:g,style:v,tagName:x="div",...S}){const w=y.useContext(kw);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:E,expandPanel:_,getPanelSize:k,getPanelStyle:C,groupId:R,isPanelCollapsed:I,reevaluatePanelConstraints:A,registerPanel:O,resizePanel:M,unregisterPanel:P}=w,B=_D(s),K=y.useRef({callbacks:{onCollapse:d,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:a,defaultSize:r,maxSize:c,minSize:u},id:B,idIsFromProps:s!==void 0,order:g});y.useRef({didLogMissingDefaultSizeWarning:!1}),Ul(()=>{const{callbacks:ee,constraints:ae}=K.current,H={...ae};K.current.id=B,K.current.idIsFromProps=s!==void 0,K.current.order=g,ee.onCollapse=d,ee.onExpand=m,ee.onResize=h,ae.collapsedSize=n,ae.collapsible=a,ae.defaultSize=r,ae.maxSize=c,ae.minSize=u,(H.collapsedSize!==ae.collapsedSize||H.collapsible!==ae.collapsible||H.maxSize!==ae.maxSize||H.minSize!==ae.minSize)&&A(K.current,H)}),Ul(()=>{const ee=K.current;return O(ee),()=>{P(ee)}},[g,B,O,P]),y.useImperativeHandle(i,()=>({collapse:()=>{E(K.current)},expand:ee=>{_(K.current,ee)},getId(){return B},getSize(){return k(K.current)},isCollapsed(){return I(K.current)},isExpanded(){return!I(K.current)},resize:ee=>{M(K.current,ee)}}),[E,_,k,I,B,M]);const Q=C(K.current,r);return y.createElement(x,{...S,children:e,className:t,id:B,style:{...Q,...v},[Zn.groupId]:R,[Zn.panel]:"",[Zn.panelCollapsible]:a||void 0,[Zn.panelId]:B,[Zn.panelSize]:parseFloat(""+Q.flexGrow).toFixed(1)})}const TY=y.forwardRef((e,t)=>y.createElement(kY,{...e,forwardedRef:t}));kY.displayName="Panel";TY.displayName="forwardRef(Panel)";let rk=null,Xb=-1,Rs=null;function Hke(e,t,n){const a=(t&IY)!==0,r=(t&OY)!==0,i=(t&DY)!==0,s=(t&jY)!==0;if(t){if(a)return i?"se-resize":s?"ne-resize":"e-resize";if(r)return i?"sw-resize":s?"nw-resize":"w-resize";if(i)return"s-resize";if(s)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function Vke(){Rs!==null&&(document.head.removeChild(Rs),rk=null,Rs=null,Xb=-1)}function Jx(e,t,n){var a,r;const i=Hke(e,t);if(rk!==i){if(rk=i,Rs===null&&(Rs=document.createElement("style"),document.head.appendChild(Rs)),Xb>=0){var s;(s=Rs.sheet)===null||s===void 0||s.removeRule(Xb)}Xb=(a=(r=Rs.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${i} !important;}`))!==null&&a!==void 0?a:-1}}function NY(e){return e.type==="keydown"}function CY(e){return e.type.startsWith("pointer")}function RY(e){return e.type.startsWith("mouse")}function Tw(e){if(CY(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(RY(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function Gke(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function Wke(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Kke(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:R2(e),b:R2(t)};let a;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),a=e;It(a,"Stacking order can only be calculated for elements with a common ancestor");const r={a:C2(N2(n.a)),b:C2(N2(n.b))};if(r.a===r.b){const i=a.childNodes,s={a:n.a.at(-1),b:n.b.at(-1)};let c=i.length;for(;c--;){const u=i[c];if(u===s.a)return 1;if(u===s.b)return-1}}return Math.sign(r.a-r.b)}const Zke=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function Yke(e){var t;const n=getComputedStyle((t=AY(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function qke(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||Yke(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||Zke.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function N2(e){let t=e.length;for(;t--;){const n=e[t];if(It(n,"Missing node"),qke(n))return n}return null}function C2(e){return e&&Number(getComputedStyle(e).zIndex)||0}function R2(e){const t=[];for(;e;)t.push(e),e=AY(e);return t}function AY(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const IY=1,OY=2,DY=4,jY=8,Xke=Gke()==="coarse";let wi=[],Cu=!1,As=new Map,Nw=new Map;const sm=new Set;function Jke(e,t,n,a,r){var i;const{ownerDocument:s}=t,c={direction:n,element:t,hitAreaMargins:a,setResizeHandlerState:r},u=(i=As.get(s))!==null&&i!==void 0?i:0;return As.set(s,u+1),sm.add(c),ey(),function(){var m;Nw.delete(e),sm.delete(c);const h=(m=As.get(s))!==null&&m!==void 0?m:1;if(As.set(s,h-1),ey(),h===1&&As.delete(s),wi.includes(c)){const g=wi.indexOf(c);g>=0&&wi.splice(g,1),Cw(),r("up",!0,null)}}}function Qke(e){const{target:t}=e,{x:n,y:a}=Tw(e);Cu=!0,ED({target:t,x:n,y:a}),ey(),wi.length>0&&(ty("down",e),Cw(),e.preventDefault(),$Y(t)||e.stopImmediatePropagation())}function Qx(e){const{x:t,y:n}=Tw(e);if(Cu&&e.type!=="pointerleave"&&e.buttons===0&&(Cu=!1,ty("up",e)),!Cu){const{target:a}=e;ED({target:a,x:t,y:n})}ty("move",e),Cw(),wi.length>0&&e.preventDefault()}function e_(e){const{target:t}=e,{x:n,y:a}=Tw(e);Nw.clear(),Cu=!1,wi.length>0&&(e.preventDefault(),$Y(t)||e.stopImmediatePropagation()),ty("up",e),ED({target:t,x:n,y:a}),Cw(),ey()}function $Y(e){let t=e;for(;t;){if(t.hasAttribute(Zn.resizeHandle))return!0;t=t.parentElement}return!1}function ED({target:e,x:t,y:n}){wi.splice(0);let a=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(a=e),sm.forEach(r=>{const{element:i,hitAreaMargins:s}=r,c=i.getBoundingClientRect(),{bottom:u,left:d,right:m,top:h}=c,g=Xke?s.coarse:s.fine;if(t>=d-g&&t<=m+g&&n>=h-g&&n<=u+g){if(a!==null&&document.contains(a)&&i!==a&&!i.contains(a)&&!a.contains(i)&&Kke(a,i)>0){let x=a,S=!1;for(;x&&!x.contains(i);){if(Wke(x.getBoundingClientRect(),c)){S=!0;break}x=x.parentElement}if(S)return}wi.push(r)}})}function t_(e,t){Nw.set(e,t)}function Cw(){let e=!1,t=!1;wi.forEach(a=>{const{direction:r}=a;r==="horizontal"?e=!0:t=!0});let n=0;Nw.forEach(a=>{n|=a}),e&&t?Jx("intersection",n):e?Jx("horizontal",n):t?Jx("vertical",n):Vke()}let n_;function ey(){var e;(e=n_)===null||e===void 0||e.abort(),n_=new AbortController;const t={capture:!0,signal:n_.signal};sm.size&&(Cu?(wi.length>0&&As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("contextmenu",e_,t),r.addEventListener("pointerleave",Qx,t),r.addEventListener("pointermove",Qx,t))}),As.forEach((n,a)=>{const{body:r}=a;r.addEventListener("pointerup",e_,t),r.addEventListener("pointercancel",e_,t)})):As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("pointerdown",Qke,t),r.addEventListener("pointermove",Qx,t))}))}function ty(e,t){sm.forEach(n=>{const{setResizeHandlerState:a}=n,r=wi.includes(n);a(e,r,t)})}function eTe(){const[e,t]=y.useState(0);return y.useCallback(()=>t(n=>n+1),[])}function It(e,t){if(!e)throw console.error(t),Error(t)}function Ql(e,t,n=xD){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function No(e,t,n=xD){return Ql(e,t,n)===0}function Da(e,t,n){return Ql(e,t,n)===0}function tTe(e,t,n){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++){const r=e[a],i=t[a];if(!Da(r,i,n))return!1}return!0}function wu({panelConstraints:e,panelIndex:t,size:n}){const a=e[t];It(a!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:r=0,collapsible:i,maxSize:s=100,minSize:c=0}=a;if(Ql(n,c)<0)if(i){const u=(r+c)/2;Ql(n,u)<0?n=r:n=c}else n=c;return n=Math.min(s,n),n=parseFloat(n.toFixed(xD)),n}function cp({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:a,prevLayout:r,trigger:i}){if(Da(e,0))return t;const s=[...t],[c,u]=a;It(c!=null,"Invalid first pivot index"),It(u!=null,"Invalid second pivot index");let d=0;if(i==="keyboard"){{const h=e<0?u:c,g=n[h];It(g,`Panel constraints not found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const w=t[h];if(It(w!=null,`Previous layout not found for panel index ${h}`),Da(w,v)){const E=S-w;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}{const h=e<0?c:u,g=n[h];It(g,`No panel constraints found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const w=t[h];if(It(w!=null,`Previous layout not found for panel index ${h}`),Da(w,S)){const E=w-v;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}}{const h=e<0?1:-1;let g=e<0?u:c,v=0;for(;;){const S=t[g];It(S!=null,`Previous layout not found for panel index ${g}`);const E=wu({panelConstraints:n,panelIndex:g,size:100})-S;if(v+=E,g+=h,g<0||g>=n.length)break}const x=Math.min(Math.abs(e),Math.abs(v));e=e<0?0-x:x}{let g=e<0?c:u;for(;g>=0&&g<n.length;){const v=Math.abs(e)-Math.abs(d),x=t[g];It(x!=null,`Previous layout not found for panel index ${g}`);const S=x-v,w=wu({panelConstraints:n,panelIndex:g,size:S});if(!Da(x,w)&&(d+=x-w,s[g]=w,d.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(tTe(r,s))return r;{const h=e<0?u:c,g=t[h];It(g!=null,`Previous layout not found for panel index ${h}`);const v=g+d,x=wu({panelConstraints:n,panelIndex:h,size:v});if(s[h]=x,!Da(x,v)){let S=v-x,E=e<0?u:c;for(;E>=0&&E<n.length;){const _=s[E];It(_!=null,`Previous layout not found for panel index ${E}`);const k=_+S,C=wu({panelConstraints:n,panelIndex:E,size:k});if(Da(_,C)||(S-=C-_,s[E]=C),Da(S,0))break;e>0?E--:E++}}}const m=s.reduce((h,g)=>g+h,0);return Da(m,100)?s:r}function nTe({layout:e,panelsArray:t,pivotIndices:n}){let a=0,r=100,i=0,s=0;const c=n[0];It(c!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:v}=h,{maxSize:x=100,minSize:S=0}=v;g===c?(a=S,r=x):(i+=S,s+=x)});const u=Math.min(r,100-i),d=Math.max(a,100-s),m=e[c];return{valueMax:u,valueMin:d,valueNow:m}}function lm(e,t=document){return Array.from(t.querySelectorAll(`[${Zn.resizeHandleId}][data-panel-group-id="${e}"]`))}function LY(e,t,n=document){const r=lm(e,n).findIndex(i=>i.getAttribute(Zn.resizeHandleId)===t);return r??null}function MY(e,t,n){const a=LY(e,t,n);return a!=null?[a,a+1]:[-1,-1]}function rTe(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function PY(e,t=document){if(rTe(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function Rw(e,t=document){const n=t.querySelector(`[${Zn.resizeHandleId}="${e}"]`);return n||null}function aTe(e,t,n,a=document){var r,i,s,c;const u=Rw(t,a),d=lm(e,a),m=u?d.indexOf(u):-1,h=(r=(i=n[m])===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:null,g=(s=(c=n[m+1])===null||c===void 0?void 0:c.id)!==null&&s!==void 0?s:null;return[h,g]}function iTe({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:a,panelDataArray:r,panelGroupElement:i,setLayout:s}){y.useRef({didWarnAboutMissingResizeHandle:!1}),Ul(()=>{if(!i)return;const c=lm(n,i);for(let u=0;u<r.length-1;u++){const{valueMax:d,valueMin:m,valueNow:h}=nTe({layout:a,panelsArray:r,pivotIndices:[u,u+1]}),g=c[u];if(g!=null){const v=r[u];It(v,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",v.id),g.setAttribute("aria-valuemax",""+Math.round(d)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{c.forEach((u,d)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,a,r,i]),y.useEffect(()=>{if(!i)return;const c=t.current;It(c,"Eager values not found");const{panelDataArray:u}=c,d=PY(n,i);It(d!=null,`No group found for id "${n}"`);const m=lm(n,i);It(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const v=g.getAttribute(Zn.resizeHandleId);It(v,"Resize handle element has no handle id attribute");const[x,S]=aTe(n,v,u,i);if(x==null||S==null)return()=>{};const w=E=>{if(!E.defaultPrevented)switch(E.key){case"Enter":{E.preventDefault();const _=u.findIndex(k=>k.id===x);if(_>=0){const k=u[_];It(k,`No panel data found for index ${_}`);const C=a[_],{collapsedSize:R=0,collapsible:I,minSize:A=0}=k.constraints;if(C!=null&&I){const O=cp({delta:Da(C,R)?A-R:R-C,initialLayout:a,panelConstraints:u.map(M=>M.constraints),pivotIndices:MY(n,v,i),prevLayout:a,trigger:"keyboard"});a!==O&&s(O)}}break}}};return g.addEventListener("keydown",w),()=>{g.removeEventListener("keydown",w)}});return()=>{h.forEach(g=>g())}},[i,e,t,n,a,r,s])}function A2(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function UY(e,t){const n=e==="horizontal",{x:a,y:r}=Tw(t);return n?a:r}function oTe(e,t,n,a,r){const i=n==="horizontal",s=Rw(t,r);It(s,`No resize handle element found for id "${t}"`);const c=s.getAttribute(Zn.groupId);It(c,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=a;const d=UY(n,e),m=PY(c,r);It(m,`No group element found for id "${c}"`);const h=m.getBoundingClientRect(),g=i?h.width:h.height;return(d-u)/g*100}function sTe(e,t,n,a,r,i){if(NY(e)){const s=n==="horizontal";let c=0;e.shiftKey?c=100:r!=null?c=r:c=10;let u=0;switch(e.key){case"ArrowDown":u=s?0:c;break;case"ArrowLeft":u=s?-c:0;break;case"ArrowRight":u=s?c:0;break;case"ArrowUp":u=s?0:-c;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return a==null?0:oTe(e,t,n,a,i)}function lTe({panelDataArray:e}){const t=Array(e.length),n=e.map(i=>i.constraints);let a=0,r=100;for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;c!=null&&(a++,t[i]=c,r-=c)}for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;if(c!=null)continue;const u=e.length-a,d=r/u;a++,t[i]=d,r-=d}return t}function Xc(e,t,n){t.forEach((a,r)=>{const i=e[r];It(i,`Panel data not found for index ${r}`);const{callbacks:s,constraints:c,id:u}=i,{collapsedSize:d=0,collapsible:m}=c,h=n[u];if(h==null||a!==h){n[u]=a;const{onCollapse:g,onExpand:v,onResize:x}=s;x&&x(a,h),m&&(g||v)&&(v&&(h==null||No(h,d))&&!No(a,d)&&v(),g&&(h==null||!No(h,d))&&No(a,d)&&g())}})}function Eb(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function cTe({defaultSize:e,dragState:t,layout:n,panelData:a,panelIndex:r,precision:i=3}){const s=n[r];let c;return s==null?c=e!=null?e.toFixed(i):"1":a.length===1?c="1":c=s.toFixed(i),{flexBasis:0,flexGrow:c,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function uTe(e,t=10){let n=null;return(...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function I2(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function zY(e){return`react-resizable-panels:${e}`}function FY(e){return e.map(t=>{const{constraints:n,id:a,idIsFromProps:r,order:i}=t;return r?a:i?`${i}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function BY(e,t){try{const n=zY(e),a=t.getItem(n);if(a){const r=JSON.parse(a);if(typeof r=="object"&&r!=null)return r}}catch{}return null}function dTe(e,t,n){var a,r;const i=(a=BY(e,n))!==null&&a!==void 0?a:{},s=FY(t);return(r=i[s])!==null&&r!==void 0?r:null}function fTe(e,t,n,a,r){var i;const s=zY(e),c=FY(t),u=(i=BY(e,r))!==null&&i!==void 0?i:{};u[c]={expandToSizes:Object.fromEntries(n.entries()),layout:a};try{r.setItem(s,JSON.stringify(u))}catch(d){console.error(d)}}function O2({layout:e,panelConstraints:t}){const n=[...e],a=n.reduce((i,s)=>i+s,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(i=>`${i}%`).join(", ")}`);if(!Da(a,100)&&n.length>0)for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=100/a*s;n[i]=c}let r=0;for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=wu({panelConstraints:t,panelIndex:i,size:s});s!=c&&(r+=s-c,n[i]=c)}if(!Da(r,0))for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=s+r,u=wu({panelConstraints:t,panelIndex:i,size:c});if(s!==u&&(r-=u-s,n[i]=u,Da(r,0)))break}return n}const pTe=100,up={getItem:e=>(I2(up),up.getItem(e)),setItem:(e,t)=>{I2(up),up.setItem(e,t)}},D2={};function HY({autoSaveId:e=null,children:t,className:n="",direction:a,forwardedRef:r,id:i=null,onLayout:s=null,keyboardResizeBy:c=null,storage:u=up,style:d,tagName:m="div",...h}){const g=_D(i),v=y.useRef(null),[x,S]=y.useState(null),[w,E]=y.useState([]),_=eTe(),k=y.useRef({}),C=y.useRef(new Map),R=y.useRef(0),I=y.useRef({autoSaveId:e,direction:a,dragState:x,id:g,keyboardResizeBy:c,onLayout:s,storage:u}),A=y.useRef({layout:w,panelDataArray:[],panelDataArrayChanged:!1});y.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),y.useImperativeHandle(r,()=>({getId:()=>I.current.id,getLayout:()=>{const{layout:z}=A.current;return z},setLayout:z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current,W=O2({layout:z,panelConstraints:F.map(ne=>ne.constraints)});A2(L,W)||(E(W),A.current.layout=W,$&&$(W),Xc(F,W,k.current))}}),[]),Ul(()=>{I.current.autoSaveId=e,I.current.direction=a,I.current.dragState=x,I.current.id=g,I.current.onLayout=s,I.current.storage=u}),iTe({committedValuesRef:I,eagerValuesRef:A,groupId:g,layout:w,panelDataArray:A.current.panelDataArray,setLayout:E,panelGroupElement:v.current}),y.useEffect(()=>{const{panelDataArray:z}=A.current;if(e){if(w.length===0||w.length!==z.length)return;let $=D2[e];$==null&&($=uTe(fTe,pTe),D2[e]=$);const L=[...z],F=new Map(C.current);$(e,L,F,w,u)}},[e,w,u]),y.useEffect(()=>{});const O=y.useCallback(z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current;if(z.constraints.collapsible){const W=F.map(X=>X.constraints),{collapsedSize:ne=0,panelSize:le,pivotIndices:ue}=_l(F,z,L);if(It(le!=null,`Panel size not found for panel "${z.id}"`),!No(le,ne)){C.current.set(z.id,le);const q=su(F,z)===F.length-1?le-ne:ne-le,oe=cp({delta:q,initialLayout:L,panelConstraints:W,pivotIndices:ue,prevLayout:L,trigger:"imperative-api"});Eb(L,oe)||(E(oe),A.current.layout=oe,$&&$(oe),Xc(F,oe,k.current))}}},[]),M=y.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current;if(z.constraints.collapsible){const ne=W.map(me=>me.constraints),{collapsedSize:le=0,panelSize:ue=0,minSize:X=0,pivotIndices:q}=_l(W,z,F),oe=$??X;if(No(ue,le)){const me=C.current.get(z.id),ie=me!=null&&me>=oe?me:oe,He=su(W,z)===W.length-1?ue-ie:ie-ue,ye=cp({delta:He,initialLayout:F,panelConstraints:ne,pivotIndices:q,prevLayout:F,trigger:"imperative-api"});Eb(F,ye)||(E(ye),A.current.layout=ye,L&&L(ye),Xc(W,ye,k.current))}}},[]),P=y.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{panelSize:F}=_l(L,z,$);return It(F!=null,`Panel size not found for panel "${z.id}"`),F},[]),B=y.useCallback((z,$)=>{const{panelDataArray:L}=A.current,F=su(L,z);return cTe({defaultSize:$,dragState:x,layout:w,panelData:L,panelIndex:F})},[x,w]),K=y.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:ne}=_l(L,z,$);return It(ne!=null,`Panel size not found for panel "${z.id}"`),W===!0&&No(ne,F)},[]),Q=y.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:ne}=_l(L,z,$);return It(ne!=null,`Panel size not found for panel "${z.id}"`),!W||Ql(ne,F)>0},[]),ee=y.useCallback(z=>{const{panelDataArray:$}=A.current;$.push(z),$.sort((L,F)=>{const W=L.order,ne=F.order;return W==null&&ne==null?0:W==null?-1:ne==null?1:W-ne}),A.current.panelDataArrayChanged=!0,_()},[_]);Ul(()=>{if(A.current.panelDataArrayChanged){A.current.panelDataArrayChanged=!1;const{autoSaveId:z,onLayout:$,storage:L}=I.current,{layout:F,panelDataArray:W}=A.current;let ne=null;if(z){const ue=dTe(z,W,L);ue&&(C.current=new Map(Object.entries(ue.expandToSizes)),ne=ue.layout)}ne==null&&(ne=lTe({panelDataArray:W}));const le=O2({layout:ne,panelConstraints:W.map(ue=>ue.constraints)});A2(F,le)||(E(le),A.current.layout=le,$&&$(le),Xc(W,le,k.current))}}),Ul(()=>{const z=A.current;return()=>{z.layout=[]}},[]);const ae=y.useCallback(z=>{let $=!1;const L=v.current;return L&&window.getComputedStyle(L,null).getPropertyValue("direction")==="rtl"&&($=!0),function(W){W.preventDefault();const ne=v.current;if(!ne)return()=>null;const{direction:le,dragState:ue,id:X,keyboardResizeBy:q,onLayout:oe}=I.current,{layout:me,panelDataArray:ie}=A.current,{initialLayout:Ne}=ue??{},He=MY(X,z,ne);let ye=sTe(W,z,le,ue,q,ne);const Se=le==="horizontal";Se&&$&&(ye=-ye);const Pe=ie.map(Me=>Me.constraints),fe=cp({delta:ye,initialLayout:Ne??me,panelConstraints:Pe,pivotIndices:He,prevLayout:me,trigger:NY(W)?"keyboard":"mouse-or-touch"}),Ae=!Eb(me,fe);(CY(W)||RY(W))&&R.current!=ye&&(R.current=ye,!Ae&&ye!==0?Se?t_(z,ye<0?IY:OY):t_(z,ye<0?DY:jY):t_(z,0)),Ae&&(E(fe),A.current.layout=fe,oe&&oe(fe),Xc(ie,fe,k.current))}},[]),H=y.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current,ne=W.map(me=>me.constraints),{panelSize:le,pivotIndices:ue}=_l(W,z,F);It(le!=null,`Panel size not found for panel "${z.id}"`);const q=su(W,z)===W.length-1?le-$:$-le,oe=cp({delta:q,initialLayout:F,panelConstraints:ne,pivotIndices:ue,prevLayout:F,trigger:"imperative-api"});Eb(F,oe)||(E(oe),A.current.layout=oe,L&&L(oe),Xc(W,oe,k.current))},[]),Z=y.useCallback((z,$)=>{const{layout:L,panelDataArray:F}=A.current,{collapsedSize:W=0,collapsible:ne}=$,{collapsedSize:le=0,collapsible:ue,maxSize:X=100,minSize:q=0}=z.constraints,{panelSize:oe}=_l(F,z,L);oe!=null&&(ne&&ue&&No(oe,W)?No(W,le)||H(z,le):oe<q?H(z,q):oe>X&&H(z,X))},[H]),G=y.useCallback((z,$)=>{const{direction:L}=I.current,{layout:F}=A.current;if(!v.current)return;const W=Rw(z,v.current);It(W,`Drag handle element not found for id "${z}"`);const ne=UY(L,$);S({dragHandleId:z,dragHandleRect:W.getBoundingClientRect(),initialCursorPosition:ne,initialLayout:F})},[]),re=y.useCallback(()=>{S(null)},[]),te=y.useCallback(z=>{const{panelDataArray:$}=A.current,L=su($,z);L>=0&&($.splice(L,1),delete k.current[z.id],A.current.panelDataArrayChanged=!0,_())},[_]),j=y.useMemo(()=>({collapsePanel:O,direction:a,dragState:x,expandPanel:M,getPanelSize:P,getPanelStyle:B,groupId:g,isPanelCollapsed:K,isPanelExpanded:Q,reevaluatePanelConstraints:Z,registerPanel:ee,registerResizeHandle:ae,resizePanel:H,startDragging:G,stopDragging:re,unregisterPanel:te,panelGroupElement:v.current}),[O,x,a,M,P,B,g,K,Q,Z,ee,ae,H,G,re,te]),V={display:"flex",flexDirection:a==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return y.createElement(kw.Provider,{value:j},y.createElement(m,{...h,children:t,className:n,id:i,ref:v,style:{...V,...d},[Zn.group]:"",[Zn.groupDirection]:a,[Zn.groupId]:g}))}const VY=y.forwardRef((e,t)=>y.createElement(HY,{...e,forwardedRef:t}));HY.displayName="PanelGroup";VY.displayName="forwardRef(PanelGroup)";function su(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function _l(e,t,n){const a=su(e,t),i=a===e.length-1?[a-1,a]:[a,a+1],s=n[a];return{...t.constraints,panelSize:s,pivotIndices:i}}function mTe({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:a}){y.useEffect(()=>{if(e||n==null||a==null)return;const r=Rw(t,a);if(r==null)return;const i=s=>{if(!s.defaultPrevented)switch(s.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{s.preventDefault(),n(s);break}case"F6":{s.preventDefault();const c=r.getAttribute(Zn.groupId);It(c,`No group element found for id "${c}"`);const u=lm(c,a),d=LY(c,t,a);It(d!==null,`No resize element found for id "${t}"`);const m=s.shiftKey?d>0?d-1:u.length-1:d+1<u.length?d+1:0;u[m].focus();break}}};return r.addEventListener("keydown",i),()=>{r.removeEventListener("keydown",i)}},[a,e,t,n])}function GY({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:a,id:r,onBlur:i,onClick:s,onDragging:c,onFocus:u,onPointerDown:d,onPointerUp:m,style:h={},tabIndex:g=0,tagName:v="div",...x}){var S,w;const E=y.useRef(null),_=y.useRef({onClick:s,onDragging:c,onPointerDown:d,onPointerUp:m});y.useEffect(()=>{_.current.onClick=s,_.current.onDragging=c,_.current.onPointerDown=d,_.current.onPointerUp=m});const k=y.useContext(kw);if(k===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:C,groupId:R,registerResizeHandle:I,startDragging:A,stopDragging:O,panelGroupElement:M}=k,P=_D(r),[B,K]=y.useState("inactive"),[Q,ee]=y.useState(!1),[ae,H]=y.useState(null),Z=y.useRef({state:B});Ul(()=>{Z.current.state=B}),y.useEffect(()=>{if(n)H(null);else{const j=I(P);H(()=>j)}},[n,P,I]);const G=(S=a?.coarse)!==null&&S!==void 0?S:15,re=(w=a?.fine)!==null&&w!==void 0?w:5;y.useEffect(()=>{if(n||ae==null)return;const j=E.current;It(j,"Element ref not attached");let V=!1;return Jke(P,j,C,{coarse:G,fine:re},($,L,F)=>{if(!L){K("inactive");return}switch($){case"down":{K("drag"),V=!1,It(F,'Expected event to be defined for "down" action'),A(P,F);const{onDragging:W,onPointerDown:ne}=_.current;W?.(!0),ne?.();break}case"move":{const{state:W}=Z.current;V=!0,W!=="drag"&&K("hover"),It(F,'Expected event to be defined for "move" action'),ae(F);break}case"up":{K("hover"),O();const{onClick:W,onDragging:ne,onPointerUp:le}=_.current;ne?.(!1),le?.(),V||W?.();break}}})},[G,C,n,re,I,P,ae,A,O]),mTe({disabled:n,handleId:P,resizeHandler:ae,panelGroupElement:M});const te={touchAction:"none",userSelect:"none"};return y.createElement(v,{...x,children:e,className:t,id:r,onBlur:()=>{ee(!1),i?.()},onFocus:()=>{ee(!0),u?.()},ref:E,role:"separator",style:{...te,...h},tabIndex:g,[Zn.groupDirection]:C,[Zn.groupId]:R,[Zn.resizeHandle]:"",[Zn.resizeHandleActive]:B==="drag"?"pointer":Q?"keyboard":void 0,[Zn.resizeHandleEnabled]:!n,[Zn.resizeHandleId]:P,[Zn.resizeHandleState]:B})}GY.displayName="PanelResizeHandle";function na({className:e,...t}){return f.jsx(VY,{"data-slot":"resizable-panel-group",className:De("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Rn({...e}){return f.jsx(TY,{"data-slot":"resizable-panel",...e})}function Si({withHandle:e,className:t,...n}){return f.jsx(GY,{"data-slot":"resizable-handle",className:De("bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&f.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:f.jsx(ihe,{className:"size-2.5"})})})}function eh({className:e,...t}){return f.jsx("kbd",{"data-slot":"kbd",className:De("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}function hTe({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onClearAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search notifications...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Clear all"})]})})]})}function Qs({id:e,isSelected:t,isFocused:n,icon:a,title:r,description:i,metadata:s,onClick:c,className:u}){return f.jsx("button",{id:e,type:"button",onClick:c,className:De("w-full text-left cursor-pointer p-2 sm:p-4 border-b dark:border-zinc-700 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors group",t&&"bg-zinc-50 dark:bg-zinc-800 border-l-4 border-l-zinc-500",n&&"ring-2 ring-zinc-500 dark:ring-zinc-400 ring-inset",u),children:f.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[a&&f.jsx("div",{className:"flex-shrink-0 mt-1",children:f.jsx("div",{className:De("p-2.5 rounded-full transition-colors",t?"bg-zinc-500 dark:bg-zinc-100/80 text-zinc-100 dark:text-zinc-900":"bg-gray-100 dark:bg-zinc-700 text-gray-600 dark:text-gray-400 group-hover:bg-gray-200 dark:group-hover:bg-zinc-600"),children:a})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"flex items-center gap-2 mb-1",children:f.jsx("h3",{className:De("font-medium truncate font-mono text-sm"),children:r})}),i&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:i})]})]})})}function gTe({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>f.jsx(Qs,{id:`notification-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.method,!s.read&&f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=r(s.timestamp),d=s.params&&Object.keys(s.params).length>0?Object.keys(s.params).length:0,m=d>0?` | ${d} param${d>1?"s":""}`:"";return u+m})(),onClick:()=>n(s)},s.id))})}function bTe({notification:e,previewMode:t,onTogglePreview:n,onCopy:a,onDownload:r,onFullscreen:i,isCopied:s=!1,onClose:c}){return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsxs($e,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?f.jsx(JN,{className:"h-4 w-4 mr-1"}):f.jsx(LG,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,children:s?f.jsx(ra,{className:"h-4 w-4"}):f.jsx(Lr,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:r,children:f.jsx(Lm,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:i,children:f.jsx(tC,{className:"h-4 w-4"})}),c&&f.jsx($e,{variant:"ghost",size:"sm",onClick:c,children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto",children:f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:{method:e.method,timestamp:e.timestamp,read:e.read,params:e.params},filename:`notification-${e.method.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(XN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function ny(e){const n=Date.now()-e,a=Math.floor(n/1e3),r=Math.floor(a/60),i=Math.floor(r/60),s=Math.floor(i/24);return a<60?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:s<7?`${s}d ago`:new Date(e).toLocaleDateString()}function vTe({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:a,clearNotifications:r,serverId:i,isConnected:s}){const[c,u]=y.useState(null),[d,m]=y.useState(""),[h,g]=y.useState(-1),[v,x]=y.useState(!0),[S,w]=y.useState(!1),[E,_]=y.useState(!0),[k,C]=y.useState(!1),R=y.useRef(null),I=y.useRef(null),A=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),y.useEffect(()=>{const Z=R.current;if(!Z)return;const G=()=>{Z.scrollTop>0&&(O.current=!0,x(!1))};return Z.addEventListener("scroll",G),()=>Z.removeEventListener("scroll",G)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),y.useEffect(()=>{c&&!c.read&&n(c.id)},[c,n]),y.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=y.useCallback(()=>{d.trim()||w(!1)},[d]),P=y.useMemo(()=>{if(!d.trim())return e;const Z=d.toLowerCase();return e.filter(G=>G.method.toLowerCase().includes(Z)||JSON.stringify(G.params||{}).toLowerCase().includes(Z))},[e,d]);y.useEffect(()=>{g(-1)},[d]),y.useEffect(()=>{const Z=G=>{const re=G.target;if(re.tagName==="INPUT"||re.tagName==="TEXTAREA"||re.contentEditable==="true"||G.metaKey||G.ctrlKey||G.altKey)return;const j=P;if(G.key==="ArrowDown")G.preventDefault(),g(V=>{const z=V+1;return z>=j.length?0:z});else if(G.key==="ArrowUp")G.preventDefault(),g(V=>{const z=V-1;return z<0?j.length-1:z});else if(G.key==="Enter"&&h>=0){G.preventDefault();const V=P[h];V&&B(V)}};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[h,P]),y.useEffect(()=>{if(h>=0){const Z=`notification-${P[h]?.id}`,G=document.getElementById(Z);G&&G.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=y.useCallback(Z=>{u(Z)},[]),K=y.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(r(),u(null))},[r]),Q=y.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(Z){console.error("[NotificationsTab] Failed to copy notification:",Z)}},[c]),ee=y.useCallback(()=>{if(c)try{const Z=new globalThis.Blob([JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)],{type:"application/json"}),G=URL.createObjectURL(Z),re=document.createElement("a");re.href=G,re.download=`notification-${Date.now()}.json`,document.body.appendChild(re),re.click(),document.body.removeChild(re),URL.revokeObjectURL(G)}catch(Z){console.error("[NotificationsTab] Failed to download notification:",Z)}},[c]),ae=y.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(Z){console.error("[NotificationsTab] Failed to toggle fullscreen:",Z)}},[]),H=c?{method:c.method,params:c.params,timestamp:c.timestamp,read:c.read,formatRelativeTime:ny}:null;return s?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(hTe,{isSearchExpanded:S,searchQuery:d,filteredNotificationsCount:P.length,notificationsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onClearAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(gTe,{notifications:P,selectedNotification:c,onNotificationSelect:B,focusedIndex:h,formatRelativeTime:ny,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(bTe,{notification:H,previewMode:E,onTogglePreview:()=>_(!E),onCopy:Q,onDownload:ee,onFullscreen:ae,onClose:()=>u(null),isCopied:k})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(XN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function WY({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:a,secondaryTabTitle:r,primaryCount:i,secondaryCount:s,secondaryIcon:c,primaryIcon:u,searchPlaceholder:d="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:v,searchInputRef:x,primaryTabName:S}){const w=e===S;return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?f.jsx(En,{ref:x,placeholder:d,value:n,onChange:E=>h(E.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:w?a:r}),w&&f.jsxs(f.Fragment,{children:[f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:i}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})]})}),f.jsxs($e,{variant:"ghost",size:"sm",onClick:v,className:"gap-2 flex-shrink-0",children:[w?f.jsx(c,{}):f.jsx(u,{}),f.jsx("span",{className:"hidden sm:inline",children:w?r:a}),w&&s>0&&f.jsx(Sr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:s})]})]})}function j2({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Hp,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((r,i)=>f.jsx(Qs,{id:`prompt-${r.name}`,isSelected:t?.name===r.name,isFocused:a===i,icon:f.jsx(Hp,{className:"h-4 w-4"}),title:r.name,description:r.description,metadata:r.arguments&&r.arguments.length>0&&f.jsxs(Sr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[r.arguments.length," args"]}),onClick:()=>n(r)},r.name))})}function $2({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:a,savedPromptsCount:r,onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d}){return f.jsx(WY,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:a,secondaryCount:r,primaryIcon:Hp,secondaryIcon:fd,searchPlaceholder:"Search prompts...",onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d})}function L2({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:a,focusedIndex:r}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(fd,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),f.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((i,s)=>f.jsx(Qs,{id:`saved-prompt-${i.id}`,isSelected:t?.id===i.id,isFocused:r===s,icon:f.jsx(fd,{className:"h-4 w-4"}),title:i.name,description:`${i.promptName} - ${new Date(i.savedAt).toLocaleString()}`,onClick:()=>n(i)},i.id))})}function yTe({selectedPrompt:e,promptArgs:t,onArgChange:n}){const a=e?.arguments||[];if(!(a.length>0))return f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const i=s=>{const c=s.name,u=t[c],d=typeof u=="string"?u:JSON.stringify(u);return s.type==="boolean"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx("input",{id:c,type:"checkbox",checked:!!u,onChange:m=>n(c,m.target.checked),className:"rounded","aria-label":`Toggle ${c}`}),f.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:s.description})]})]},c):s.type==="number"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,type:"number",value:Number(u)||0,onChange:m=>n(c,Number(m.target.value)),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):s.type==="array"||s.type==="object"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(Xl,{id:c,value:d,onChange:m=>{try{const h=JSON.parse(m.target.value);n(c,h)}catch{n(c,m.target.value)}},placeholder:s.description||`Enter ${c} as JSON`,className:"font-mono text-sm min-h-[100px]"}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,value:d,onChange:m=>n(c,m.target.value),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c)};return f.jsx("div",{className:"space-y-4",children:a.map(s=>i(s))})}function M2({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:a,onArgChange:r,onExecute:i,onSave:s}){return y.useEffect(()=>{const c=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&a&&(u.preventDefault(),i())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[e,n,a,i]),e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[f.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsx($e,{onClick:i,disabled:n||!a,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):f.jsxs(f.Fragment,{children:[f.jsx(FG,{className:"h-4 w-4 sm:mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Execute"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})}),f.jsxs($e,{variant:"outline",onClick:s,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[f.jsx(nC,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),f.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:f.jsx(yTe,{selectedPrompt:e,promptArgs:t,onArgChange:r})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a prompt from the list to view its details and execute it"})]})}function wTe(e){return"isError"in e&&!e.isError?null:"error"in e&&e.error?e.error:"isError"in e&&e.isError?"An error occurred":null}function P2({results:e,copiedResult:t,onCopy:n}){return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:e.length>0?f.jsx("div",{className:"space-y-4 flex-1 h-full",children:e.map((a,r)=>{const i=a.error||wTe(a.result);return f.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[f.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(a.timestamp).toLocaleTimeString()})]}),a.duration!==void 0&&f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[a.duration,"ms"]})]}),f.jsx("div",{className:"flex gap-2 ml-auto",children:f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>n(r,a.result),className:"h-6 px-2",children:t===r?f.jsx(ra,{className:"h-4 w-4"}):f.jsx(Lr,{className:"h-4 w-4"})})})]}),i?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:i})]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:a.result,filename:`prompt-result-${a.promptName}-${Date.now()}.json`})})]},r)})}):f.jsx("div",{className:"flex items-center justify-center h-full",children:f.jsx("div",{className:"text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})})}function kD({serverIds:e,onCountChange:t,onClearRef:n}={}){const[a,r]=y.useState([]),i=y.useRef(null),[s,c]=y.useState(new Set),[u]=y.useState(""),d=v=>{c(x=>{const S=new Set(x);return S.has(v)?S.delete(v):S.add(v),S})},m=async()=>{r([]),c(new Set),t?.(0);try{const v=new URLSearchParams;e&&e.length>0&&v.set("serverIds",e.join(","));const x=await fetch(`/inspector/api/rpc/log?${v.toString()}`,{method:"DELETE"});x.ok||console.warn("[RPC Logger] Failed to clear server buffer:",x.status)}catch(v){console.warn("[RPC Logger] Error clearing server buffer:",v)}},h=y.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);y.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),y.useEffect(()=>{t?.(a.length)},[a.length,t]),y.useEffect(()=>{let v=null;try{const x=new URLSearchParams;x.set("replay","50"),x.set("_t",Date.now().toString()),e&&e.length>0&&x.set("serverIds",e.join(","));const S=`/inspector/api/rpc/stream?${x.toString()}`;console.log("[RPC Logger] Connecting to SSE stream:",S),v=new globalThis.EventSource(S),v.onopen=()=>{console.log("[RPC Logger] SSE connection opened")},v.onmessage=w=>{try{const E=JSON.parse(w.data);if(!E||E.type!=="rpc")return;const{serverId:_,direction:k,message:C,timestamp:R}=E,I=C,A=typeof I?.method=="string"?I.method:I?.result!==void 0?"result":I?.error!==void 0?"error":"unknown",O={id:`${R??Date.now()}-${Math.random().toString(36).slice(2)}`,serverId:typeof _=="string"?_:"unknown",direction:typeof k=="string"?k.toUpperCase():"",method:A,timestamp:R??new Date().toISOString(),payload:C};console.log("[RPC Logger] Received RPC event:",{method:A,direction:k,serverId:_}),r(M=>{const P=[O,...M].slice(0,1e3);return t?.(P.length),P})}catch(E){console.error("[RPC Logger] Error parsing SSE message:",E)}},v.onerror=w=>{console.error("[RPC Logger] SSE connection error:",w);try{v?.close()}catch{}}}catch(x){console.error("[RPC Logger] Failed to create SSE connection:",x)}return()=>{try{v?.close(),console.log("[RPC Logger] SSE connection closed")}catch{}}},[h]);const g=y.useMemo(()=>{let v=a;if(e&&e.length>0){const x=new Set(e);v=v.filter(S=>x.has(S.serverId))}if(u.trim()){const x=u.toLowerCase();v=v.filter(S=>S.serverId.toLowerCase().includes(x)||S.method.toLowerCase().includes(x)||S.direction.toLowerCase().includes(x)||JSON.stringify(S.payload).toLowerCase().includes(x))}return v=[...v].sort((x,S)=>new Date(S.timestamp).getTime()-new Date(x.timestamp).getTime()),v},[a,u,e]);return f.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:f.jsx("div",{ref:i,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?f.jsxs("div",{className:"text-center py-8",children:[f.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),f.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(v=>{const x=s.has(v.id);return f.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[f.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>d(v.id),children:[f.jsx("div",{className:"flex-shrink-0",children:x?f.jsx(ac,{className:"h-3 w-3 text-muted-foreground transition-transform"}):f.jsx(MG,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),f.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[f.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(v.timestamp).toLocaleTimeString()}),f.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${v.direction==="RECEIVE"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-green-500/10 text-green-600 dark:text-green-400"}`,title:v.direction==="RECEIVE"?"Incoming":"Outgoing",children:v.direction==="RECEIVE"?f.jsx(hme,{className:"h-3 w-3"}):f.jsx(bme,{className:"h-3 w-3"})}),f.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:v.method})]})]}),x&&f.jsx("div",{className:"border-t bg-muted/20",children:f.jsx("div",{className:"p-3",children:f.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:f.jsx(Xn,{data:v.payload})})})})]},v.id)})})})}const U2="mcp-inspector-saved-prompts";function KY({ref:e,prompts:t,callPrompt:n,serverId:a,isConnected:r}){const[i,s]=y.useState(null),[c,u]=y.useState(null),{selectedPromptName:d,setSelectedPromptName:m}=ic(),[h,g]=y.useState({}),[v,x]=y.useState([]),[S,w]=y.useState(!1),[E,_]=y.useState(null),[k,C]=y.useState(""),[R,I]=y.useState("prompts"),[A,O]=y.useState([]),[M,P]=y.useState(!1),[B,K]=y.useState(""),[Q,ee]=y.useState(!1),[ae,H]=y.useState(-1),Z=y.useRef(null),[G,re]=y.useState(!1),[te,j]=y.useState("list"),[V,z]=y.useState(0),[$,L]=y.useState(!0),F=y.useRef(null),W=y.useRef(null);y.useEffect(()=>{const ye=()=>{re(window.innerWidth<1024)};return ye(),window.addEventListener("resize",ye),()=>window.removeEventListener("resize",ye)},[]),y.useEffect(()=>{j(i?"detail":"list")},[i]),y.useEffect(()=>{G&&v.length>0&&!S&&j("response")},[v,S,G]),y.useImperativeHandle(e,()=>({focusSearch:()=>{ee(!0),setTimeout(()=>{Z.current&&Z.current.focus()},0)},blurSearch:()=>{C(""),ee(!1),Z.current&&Z.current.blur()}})),y.useEffect(()=>{try{const ye=localStorage.getItem(U2);if(ye){const Se=JSON.parse(ye);O(Se)}}catch(ye){console.error("[PromptsTab] Failed to load saved prompts:",ye)}},[]);const ne=y.useCallback(ye=>{try{localStorage.setItem(U2,JSON.stringify(ye))}catch(Se){console.error("[PromptsTab] Failed to save prompts:",Se)}},[]);y.useEffect(()=>{Q&&Z.current&&Z.current.focus()},[Q]);const le=y.useCallback(()=>{k.trim()||ee(!1)},[k]),ue=y.useMemo(()=>{if(!k.trim())return t;const ye=k.toLowerCase();return t.filter(Se=>Se.name.toLowerCase().includes(ye)||Se.description?.toLowerCase().includes(ye))},[t,k]),X=y.useCallback(ye=>{s(ye);const Se={};ye.arguments&&ye.arguments.forEach(Pe=>{Pe.default!==void 0?Se[Pe.name]=Pe.default:Pe.type==="string"?Se[Pe.name]="":Pe.type==="number"?Se[Pe.name]=0:Pe.type==="boolean"?Se[Pe.name]=!1:Pe.type==="array"?Se[Pe.name]=[]:Pe.type==="object"&&(Se[Pe.name]={})}),g(Se)},[]),q=y.useCallback(ye=>{const Se=t.find(Pe=>Pe.name===ye.promptName);Se&&(s(Se),g(ye.args),u(ye))},[t]);y.useEffect(()=>{H(-1)},[k,R]),y.useEffect(()=>{const ye=Se=>{const Pe=Se.target;if(Pe.tagName==="INPUT"||Pe.tagName==="TEXTAREA"||Pe.contentEditable==="true"||Se.metaKey||Se.ctrlKey||Se.altKey)return;const Ae=R==="prompts"?ue:A;if(Se.key==="ArrowDown")Se.preventDefault(),H(Me=>{const _e=Me+1;return _e>=Ae.length?0:_e});else if(Se.key==="ArrowUp")Se.preventDefault(),H(Me=>{const _e=Me-1;return _e<0?Ae.length-1:_e});else if(Se.key==="Enter"&&ae>=0)if(Se.preventDefault(),R==="prompts"){const Me=ue[ae];Me&&X(Me)}else{const Me=A[ae];Me&&q(Me)}};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[ae,ue,A,R,X,q]),y.useEffect(()=>{if(ae>=0){const ye=R==="prompts"?`prompt-${ue[ae]?.name}`:`saved-prompt-${A[ae]?.id}`,Se=document.getElementById(ye);Se&&Se.scrollIntoView({behavior:"smooth",block:"nearest"})}},[ae,ue,A,R]),y.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:d,promptsCount:t.length,currentSelectedPrompt:i?.name}),d&&t.length>0){const ye=t.find(Se=>Se.name===d);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:d,promptFound:!!ye,promptName:ye?.name,shouldSelect:ye&&i?.name!==ye.name}),ye&&i?.name!==ye.name){console.warn("[PromptsTab] Selecting prompt:",ye.name),m(null);const Se=setTimeout(()=>{X(ye);const Pe=document.getElementById(`prompt-${ye.name}`);Pe&&(console.warn("[PromptsTab] Scrolling to prompt element"),Pe.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(Se)}}},[d,t,i,X,m]);const oe=y.useCallback((ye,Se)=>{g(Pe=>({...Pe,[ye]:Se}))},[]),me=y.useCallback(async()=>{if(!i||S)return;w(!0);const ye=Date.now();try{const Se=await n(i.name,h),Pe=Date.now()-ye;yr.getInstance().capture(new QU({promptName:i.name,serverId:a,success:!0})).catch(()=>{}),x(Ae=>[{promptName:i.name,args:h,result:Se,timestamp:ye,duration:Pe},...Ae])}catch(Se){yr.getInstance().capture(new QU({promptName:i.name,serverId:a,success:!1,error:Se instanceof Error?Se.message:"Unknown error"})).catch(()=>{});const fe={promptName:i.name,args:h,result:null,error:Se instanceof Error?Se.message:String(Se),timestamp:ye,duration:Date.now()-ye};x(Ae=>[fe,...Ae])}finally{w(!1)}},[i,h,S,n,a]),ie=y.useCallback(async(ye,Se)=>{try{await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),_(ye),setTimeout(()=>_(null),2e3)}catch(Pe){console.error("[PromptsTab] Failed to copy result:",Pe)}},[]),Ne=y.useCallback(()=>{i&&(K(""),P(!0))},[i]),He=y.useCallback(ye=>{ne(A.filter(Se=>Se.id!==ye)),c?.id===ye&&u(null)},[A,ne,c]);return G?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[te!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{te==="response"?j("detail"):(s(null),j("list"))},className:"p-0 h-8 w-8",children:f.jsx(Xy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{s(null),j("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Prompts"}),te!=="list"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{te==="response"&&j("detail")},className:te==="detail"?"text-foreground hover:underline":te==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),te==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(aw,{initial:!1,mode:"popLayout",children:[te==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx($2,{activeTab:R,isSearchExpanded:Q,searchQuery:k,filteredPromptsCount:ue.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:C,onSearchBlur:le,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(j2,{prompts:ue,selectedPrompt:i,onPromptSelect:X,focusedIndex:ae}):f.jsx(L2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:He,focusedIndex:ae})]},"list"),te==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(M2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:oe,onExecute:me,onSave:Ne})},"detail"),te==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(P2,{results:v,copiedResult:E,onCopy:ie})},"response")]})})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:33,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx($2,{activeTab:R,isSearchExpanded:Q,searchQuery:k,filteredPromptsCount:ue.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:C,onSearchBlur:le,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(j2,{prompts:ue,selectedPrompt:i,onPromptSelect:X,focusedIndex:ae}):f.jsx(L2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:He,focusedIndex:ae})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:F,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>L(!0),onExpand:()=>L(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:ye=>{ye.preventDefault(),ye.stopPropagation(),$?(F.current?.resize(25),L(!1)):(F.current?.resize(5),L(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),V>0&&f.jsx(Sr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:V}),V>0&&!$&&f.jsx($e,{variant:"ghost",size:"sm",onClick:ye=>{ye.preventDefault(),ye.stopPropagation(),W.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${$?"rotate-180":""}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${$?"hidden":""}`,children:f.jsx(kD,{serverIds:[a],onCountChange:z,onClearRef:W})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{defaultSize:40,children:f.jsx(M2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:oe,onExecute:me,onSave:Ne})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:50,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(P2,{results:v,copiedResult:E,onCopy:ie})})})]})})]})}KY.displayName="PromptsTab";function Ru(e){if(!e?.mimeType)return!1;const t=e.mimeType.toLowerCase();return t==="text/html"||t==="text/html+skybridge"||t==="text/uri-list"||t.startsWith("application/vnd.mcp-ui.remote-dom")}function STe(e){return{uri:e.uri,mimeType:e.mimeType,text:e.text,blob:e.blob}}function ZY({resource:e,onUIAction:t,className:n}){const a=async i=>t?.(i),r=STe(e);return f.jsx("div",{className:n,children:f.jsx(SD,{resource:r,onUIAction:a,htmlProps:{autoResizeIframe:{width:!0,height:!0},style:{width:"100%",minHeight:"200px"},sandboxPermissions:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"},remoteDomProps:{remoteElements:[Oke,Ike,Dke,jke],library:wD}})})}function xTe(e){if("error"in e&&e.error)return e.error;if(!("isError"in e&&e.isError))return null;if("contents"in e&&Array.isArray(e.contents)){const t=e.contents.filter(n=>"text"in n).map(n=>n.text).filter(Boolean);if(t.length>0)return t.join(`
|
|
1661
1661
|
`)}return"An error occurred"}function z2({result:e,isLoading:t,previewMode:n,serverId:a,readResource:r,onTogglePreview:i,onCopy:s,onDownload:c,onFullscreen:u,isCopied:d=!1}){let m=[],h;if(e?.resourceAnnotations&&(m=Object.keys(e.resourceAnnotations).filter(w=>w.startsWith("openai/")),h=e.resourceAnnotations["openai/outputTemplate"]),e?.result?.contents?.[0]?._meta){const w=e.result.contents[0]._meta,E=Object.keys(w).filter(_=>_.startsWith("openai/"));E.length>0&&(m=[...m,...E]),!h&&w["openai/outputTemplate"]&&(h=w["openai/outputTemplate"]),!h&&e.uri&&e.uri.startsWith("ui://widget/")&&(h=e.uri)}const g=!!(m.length>0&&h&&typeof h=="string"&&a&&r);if(t)return f.jsx("div",{className:"flex absolute left-0 top-0 items-center justify-center w-full h-full",children:f.jsx(ki,{className:"size-5"})});if(!e)return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a resource to view its contents"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a resource from the list to see its data"})]});const v=e.error||xTe(e.result);if(v)return f.jsx("div",{className:"p-4",children:f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:v})]})});const x=e?.result?.contents&&Array.isArray(e.result.contents)&&e.result.contents.some(w=>w.mimeType&&Ru(w)),S=x?e.result.contents.filter(w=>w.mimeType&&Ru(w)):[];return f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),(()=>{const w=e?.duration??e.result?.duration??e.result?.metrics?.durationMs;return w!==void 0?f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[w,"ms"]})]}):null})(),x&&f.jsx(Sr,{variant:"outline",className:"text-xs bg-purple-50 dark:bg-purple-900/20 border-none border-purple-200 dark:border-purple-800/50 text-purple-600 dark:text-purple-400",children:"MCP UI"}),g&&f.jsx(Sr,{variant:"outline",className:"text-xs bg-blue-50 dark:bg-blue-900/20 border-none border-blue-200 dark:border-blue-800/50 text-blue-600 dark:text-blue-400",children:"OpenAI Widget"})]}),f.jsxs("div",{className:"flex items-center gap-1",children:[(x||g)&&f.jsxs($e,{variant:"ghost",size:"sm",onClick:i,className:n?"":"text-purple-600 dark:text-purple-400",children:[n?f.jsx(JN,{className:"h-4 w-4 mr-1"}):f.jsx(LG,{className:"h-4 w-4 mr-1"}),n?"JSON":g?"Component":"Preview"]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:s,children:d?f.jsx(ra,{className:"h-4 w-4"}):f.jsx(Lr,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:c,children:f.jsx(Lm,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:u,children:f.jsx(tC,{className:"h-4 w-4"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto",children:g&&a&&r&&h?n?f.jsx("div",{className:"flex-1 h-full",children:f.jsx(hD,{componentUrl:h,toolName:e.uri,toolArgs:{},toolResult:e.result,serverId:a,readResource:r,className:"w-full h-full relative flex p-4"})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})}):x?n?f.jsxs("div",{className:"space-y-0 h-full",children:[S.map((w,E)=>f.jsx("div",{className:"mx-0 size-full",children:f.jsx("div",{className:"w-full h-full",children:f.jsx(ZY,{resource:w,className:"w-full h-full"})})},`mcp-ui-${w.uri||`resource-${Date.now()}-${Math.random()}`}`)),(()=>{if(e.result.contents&&Array.isArray(e.result.contents)){const w=e.result.contents.filter(E=>!(E.mimeType&&Ru(E)));if(w.length>0)return f.jsx("div",{className:"px-4",children:f.jsx(Xn,{data:w,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-non-ui-${Date.now()}.json`})})}return null})()]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-mcp-ui-${Date.now()}.json`})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]})}function _Te(e,t){if(!e&&!t)return f.jsx(Qme,{className:"h-5 w-5"});const n=(e||t||"").toLowerCase();return n.includes("image")?f.jsx(qme,{className:"h-5 w-5"}):n.includes("json")||n.includes("javascript")||n.includes("typescript")?f.jsx(Zme,{className:"h-5 w-5"}):n.includes("html")||n.includes("xml")?f.jsx(rhe,{className:"h-5 w-5"}):n.includes("database")||n.includes("sql")?f.jsx(Jy,{className:"h-5 w-5"}):f.jsx(QN,{className:"h-5 w-5"})}function F2({resources:e,selectedResource:t,onResourceSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Jy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No resources available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((r,i)=>{const s=_Te(r.mimeType,r.uri),c=[r.description,r.mimeType&&f.jsx("span",{className:"font-mono",children:r.mimeType},"mime")].filter(Boolean);return f.jsx(Qs,{id:`resource-${r.uri}`,isSelected:t?.uri===r.uri,isFocused:a===i,icon:s,title:r.name,description:c.length>0?f.jsxs("span",{className:"flex flex-col gap-1",children:[r.description&&f.jsx("span",{children:r.description}),r.mimeType&&f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-500 font-mono",children:r.mimeType})]}):void 0,onClick:()=>n(r)},r.uri)})})}function B2({isSearchExpanded:e,searchQuery:t,filteredResourcesCount:n,onSearchExpand:a,onSearchChange:r,onSearchBlur:i,searchInputRef:s}){return f.jsx("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:s,placeholder:"Search resources...",value:t,onChange:c=>r(c.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Resources"}),f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})})})}function YY({ref:e,resources:t,readResource:n,serverId:a,isConnected:r}){const[i,s]=y.useState(null),{selectedResourceUri:c,setSelectedResourceUri:u}=ic(),[d,m]=y.useState(null),[h,g]=y.useState(!1),[v,x]=y.useState(""),[S]=y.useState("resources"),[w,E]=y.useState(!0),[_,k]=y.useState(!1),[C,R]=y.useState(-1),[I,A]=y.useState(!1),O=y.useRef(null),M=y.useRef(null),[P,B]=y.useState(!1),[K,Q]=y.useState("list"),[ee,ae]=y.useState(0),[H,Z]=y.useState(!0),G=y.useRef(null),re=y.useRef(null);y.useEffect(()=>{const F=()=>{B(window.innerWidth<1024)};return F(),window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[]),y.useEffect(()=>{Q(i?"detail":"list")},[i]),y.useImperativeHandle(e,()=>({focusSearch:()=>{k(!0),setTimeout(()=>{O.current&&O.current.focus()},0)},blurSearch:()=>{x(""),k(!1),O.current&&O.current.blur()}})),y.useEffect(()=>{_&&O.current&&O.current.focus()},[_]);const te=y.useCallback(()=>{v.trim()||k(!1)},[v]),j=y.useMemo(()=>{if(!v)return t;const F=v.toLowerCase();return t.filter(W=>W.name.toLowerCase().includes(F)||W.description?.toLowerCase().includes(F)||W.uri.toLowerCase().includes(F))},[t,v]),V=y.useCallback(async F=>{if(s(F),r){g(!0);const W=Date.now();try{const ne=await n(F.uri);yr.getInstance().capture(new JU({resourceUri:F.uri,serverId:a,success:!0})).catch(()=>{}),m({uri:F.uri,result:ne,timestamp:W,resourceAnnotations:F.annotations})}catch(ne){yr.getInstance().capture(new JU({resourceUri:F.uri,serverId:a,success:!1,error:ne instanceof Error?ne.message:"Unknown error"})).catch(()=>{}),m({uri:F.uri,result:null,error:ne instanceof Error?ne.message:"Unknown error",timestamp:W,resourceAnnotations:F.annotations})}finally{g(!1)}}},[n,a,r]);y.useEffect(()=>{R(-1)},[v,S]),y.useEffect(()=>{const F=W=>{const ne=W.target;if(ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.contentEditable==="true"||W.metaKey||W.ctrlKey||W.altKey)return;const ue=j;if(W.key==="ArrowDown")W.preventDefault(),R(X=>{const q=X+1;return q>=ue.length?0:q});else if(W.key==="ArrowUp")W.preventDefault(),R(X=>{const q=X-1;return q<0?ue.length-1:q});else if(W.key==="Enter"&&C>=0){W.preventDefault();const X=j[C];X&&V(X)}};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[C,j,V]),y.useEffect(()=>{if(C>=0){const F=`resource-${j[C]?.uri}`,W=document.getElementById(F);W&&W.scrollIntoView({behavior:"smooth",block:"nearest"})}},[C,j]),y.useEffect(()=>{if(c&&t.length>0){const F=t.find(W=>W.uri===c);F&&i?.uri!==F.uri&&(u(null),setTimeout(()=>{V(F);const W=document.getElementById(`resource-${F.uri}`);W&&W.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[c,t,i,V,u]);const z=y.useCallback(async()=>{if(d)try{await navigator.clipboard.writeText(JSON.stringify(d.result,null,2)),A(!0),setTimeout(()=>A(!1),2e3)}catch(F){console.error("[ResourcesTab] Failed to copy result:",F)}},[d]),$=y.useCallback(()=>{if(d)try{const F=new globalThis.Blob([JSON.stringify(d.result,null,2)],{type:"application/json"}),W=URL.createObjectURL(F),ne=document.createElement("a");ne.href=W,ne.download=`resource-${Date.now()}.json`,document.body.appendChild(ne),ne.click(),document.body.removeChild(ne),URL.revokeObjectURL(W)}catch(F){console.error("[ResourcesTab] Failed to download result:",F)}},[d]),L=y.useCallback(async()=>{if(M.current)try{document.fullscreenElement?await document.exitFullscreen():await M.current.requestFullscreen()}catch(F){console.error("[ResourcesTab] Failed to toggle fullscreen:",F)}},[]);return P?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[K!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{s(null),Q("list")},className:"p-0 h-8 w-8",children:f.jsx(Xy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{s(null),Q("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Resources"}),K==="detail"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Content"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(aw,{initial:!1,mode:"popLayout",children:[K==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(B2,{activeTab:S,isSearchExpanded:_,searchQuery:v,filteredResourcesCount:j.length,onSearchExpand:()=>k(!0),onSearchChange:x,onSearchBlur:te,onTabSwitch:()=>{},searchInputRef:O}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(F2,{resources:j,selectedResource:i,onResourceSelect:V,focusedIndex:C})})]},"list"),K==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-white dark:bg-zinc-900 z-10",children:f.jsx("div",{ref:M,className:"h-full",children:f.jsx(z2,{result:d,isLoading:h,previewMode:w,serverId:a,readResource:n,onTogglePreview:()=>E(!w),onCopy:z,onDownload:$,onFullscreen:L,isCopied:I})})},"detail")]})})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:25,children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(B2,{activeTab:S,isSearchExpanded:_,searchQuery:v,filteredResourcesCount:j.length,onSearchExpand:()=>k(!0),onSearchChange:x,onSearchBlur:te,onTabSwitch:()=>{},searchInputRef:O}),f.jsx(F2,{resources:j,selectedResource:i,onResourceSelect:V,focusedIndex:C})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:G,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>Z(!0),onExpand:()=>Z(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:F=>{F.preventDefault(),F.stopPropagation(),H?(G.current?.resize(25),Z(!1)):(G.current?.resize(5),Z(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),ee>0&&f.jsx(Sr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:ee}),ee>0&&!H&&f.jsx($e,{variant:"ghost",size:"sm",onClick:F=>{F.preventDefault(),F.stopPropagation(),re.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${H?"":"rotate-180"}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${H?"hidden":""}`,children:f.jsx(kD,{serverIds:[a],onCountChange:ae,onClearRef:re})})]})]})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:50,children:f.jsx(na,{direction:"vertical",children:f.jsx(Rn,{defaultSize:70,children:f.jsx("div",{ref:M,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(z2,{result:d,isLoading:h,previewMode:w,serverId:a,readResource:n,onTogglePreview:()=>E(!w),onCopy:z,onDownload:$,onFullscreen:L,isCopied:I})})})})})]})}YY.displayName="ResourcesTab";function H2({savedRequests:e,selectedRequest:t,onLoadRequest:n,onDeleteRequest:a,focusedIndex:r}){if(e.length===0)return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Jy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"No saved requests yet"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Execute a tool and click Save to store requests"})]});const i=(s,c)=>{s.stopPropagation(),c()};return f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((s,c)=>f.jsxs("div",{className:"relative group",children:[f.jsx(Qs,{id:`saved-${s.id}`,isSelected:t?.id===s.id,isFocused:r===c,icon:f.jsx(Av,{className:"h-4 w-4"}),title:s.name,description:s.toolName,metadata:f.jsx("div",{className:"flex flex-col gap-1",children:f.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:new Date(s.savedAt).toLocaleString()})}),onClick:()=>n(s)}),f.jsx("div",{className:"absolute top-1/2 right-2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"secondary",size:"sm",onClick:u=>i(u,()=>a(s.id)),className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Delete saved request"})})]})})]},s.id))})}function V2({isOpen:e,requestName:t,defaultPlaceholder:n,onRequestNameChange:a,onSave:r,onCancel:i}){return e?f.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:i,children:f.jsxs("div",{className:"bg-white dark:bg-zinc-800 rounded-lg p-6 w-[400px] shadow-xl border border-gray-200 dark:border-zinc-700",onClick:s=>s.stopPropagation(),children:[f.jsx("h3",{className:"text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100",children:"Save Request"}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx(Kt,{htmlFor:"request-name",children:"Request Name (optional)"}),f.jsx(En,{id:"request-name",value:t,onChange:s=>a(s.target.value),placeholder:n,className:"mt-2",onKeyDown:s=>{s.key==="Enter"&&r()},autoFocus:!0})]}),f.jsxs("div",{className:"flex justify-end gap-2",children:[f.jsx($e,{variant:"outline",onClick:i,children:"Cancel"}),f.jsxs($e,{onClick:r,children:[f.jsx(nC,{className:"h-4 w-4 mr-2"}),"Save"]})]})]})]})}):null}function qY(e,t){if(!e?.$ref)return e;const n=e.$ref;if(n.startsWith("#/")){const a=n.substring(2).split("/");let r=t;for(const i of a)if(r&&typeof r=="object"&&i in r)r=r[i];else return console.warn(`Could not resolve $ref: ${n}`),e;return r}return e}function ETe(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){const n=e.anyOf.find(a=>a.type!=="null");if(n)return{...qY(n,t),nullable:!0}}return e}function kTe(e){return Array.isArray(e.enum)?e.enum:null}function G2({selectedTool:e,toolArgs:t,onArgChange:n}){const a=e?.inputSchema?.properties||{},r=e?.inputSchema?.required||[];return Object.keys(a).length>0?f.jsx("div",{className:"space-y-4",children:Object.entries(a).map(([s,c])=>{const u=e?.inputSchema||{};let d=ETe(c,u);d=qY(d,u);const m=kTe(d),h=d.type==="string"&&m!==null,g=d;g.required=r.includes(s);const v=t[s];let x="";return v!=null&&(typeof v=="string"?x=v:typeof v=="object"&&v!==null?x=JSON.stringify(v,null,2):x=String(v)),g.type==="object"||g.type==="array"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g?.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(Xl,{id:s,value:x,onChange:w=>n(s,w.target.value),placeholder:g?.description||`Enter ${s}`,className:"min-h-[100px]"}),g?.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s):h&&m?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsxs(Oo,{value:String(t[s]||""),onValueChange:w=>n(s,w),children:[f.jsx(jo,{id:s,className:"w-full",children:f.jsx(Do,{placeholder:g.description||"Select an option"})}),f.jsx($o,{children:m.map((w,E)=>f.jsx(Ir,{value:w,children:g.enumNames?.[E]||w},w))})]}),g.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s):f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g?.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:s,value:x,onChange:w=>n(s,w.target.value),placeholder:g?.description||`Enter ${s}`}),g?.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s)})}):f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No parameters required"})}function W2({selectedTool:e,toolArgs:t,isExecuting:n,isConnected:a,onArgChange:r,onExecute:i,onSave:s,onCancel:c}){const[u,d]=y.useState(!1),[m,h]=y.useState(()=>{if(typeof window<"u"){const S=localStorage.getItem("mcp-inspector-show-tool-metadata");return S?JSON.parse(S):!1}return!1}),[g,v]=y.useState(!1);y.useEffect(()=>{typeof window<"u"&&localStorage.setItem("mcp-inspector-show-tool-metadata",JSON.stringify(m))},[m]);const x=()=>{if(!e)return;const S={name:e.name,description:e.description||"",_meta:e._meta};navigator.clipboard.writeText(JSON.stringify(S,null,2)),v(!0),setTimeout(()=>v(!1),2e3)};return y.useEffect(()=>{const S=w=>{(w.metaKey||w.ctrlKey)&&w.key==="Enter"&&e&&!n&&a&&(w.preventDefault(),i()),w.key==="Escape"&&n&&c&&(w.preventDefault(),c())};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[e,n,a,i,c]),e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"flex-shrink-0 p-3 sm:p-5 pt-3 sm:pt-4 pb-4 sm:pr-4",children:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[f.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs($e,{variant:m?"default":"outline",onClick:()=>h(!m),disabled:n,size:"sm",className:"lg:size-default gap-2",title:"Toggle tool metadata",children:[f.jsx(JN,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Metadata"})]})}),f.jsx(Rt,{children:f.jsx("p",{children:"Show tool definition metadata"})})]}),f.jsxs($e,{variant:"outline",onClick:s,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[f.jsx(nC,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Save"})]}),n&&c?f.jsxs(Nt,{open:u?void 0:!1,children:[f.jsx(Ct,{asChild:!0,children:f.jsx("div",{onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),className:"relative",children:f.jsx($e,{onClick:c,variant:u?"destructive":"default",size:"sm",className:"lg:size-default gap-2 transition-all",children:u?f.jsxs(f.Fragment,{children:[f.jsx(Ji,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Cancel"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border border-current p-1 rounded-full ml-2",children:"Esc"})]}):f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]})})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Hover to cancel (or press Esc)"})})]}):f.jsx($e,{onClick:i,disabled:n||!a,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):f.jsxs(f.Fragment,{children:[f.jsx(FG,{className:"h-4 w-4 sm:mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Execute"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})})]})]}),e.description&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),m?f.jsxs("div",{className:"flex-1 overflow-hidden flex gap-4 px-3 sm:px-6 pb-4",children:[f.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:f.jsx(G2,{selectedTool:e,toolArgs:t,onArgChange:r})}),f.jsxs("div",{className:"w-2/5 flex flex-col bg-zinc-50 dark:bg-zinc-900/50 rounded border border-zinc-200 dark:border-zinc-800 overflow-hidden",children:[f.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-zinc-200 dark:border-zinc-800 flex-shrink-0",children:[f.jsx("h4",{className:"text-sm font-medium",children:"Tool Definition"}),f.jsx($e,{variant:"ghost",size:"sm",onClick:x,className:"h-7 w-7 p-0",title:"Copy metadata",children:g?f.jsx(ra,{className:"h-3.5 w-3.5 text-green-600"}):f.jsx(Lr,{className:"h-3.5 w-3.5"})})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-3",children:f.jsx("pre",{className:"text-xs font-mono text-zinc-700 dark:text-zinc-300 whitespace-pre-wrap break-words",children:JSON.stringify({name:e.name,description:e.description||"(no description)",_meta:e._meta||null},null,2)})})]})]}):f.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:f.jsx(G2,{selectedTool:e,toolArgs:t,onArgChange:r})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a tool to get started"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a tool from the list to view its details and execute it"})]})}function K2(e){const n=Date.now()-e,a=Math.floor(n/1e3),r=Math.floor(a/60),i=Math.floor(r/60),s=Math.floor(i/24);return a<10?"now":a<60?`${a}s ago`:r<60?`${r}m ago`:i<24?`${i}h ago`:`${s}d ago`}function TTe(e){if(!e?.isError)return null;if(e.content&&Array.isArray(e.content)){const t=e.content.filter(n=>n.type==="text").map(n=>n.text).filter(Boolean);if(t.length>0)return t.join(`
|
|
1662
1662
|
`)}return"An error occurred"}function NTe(e){try{return JSON.parse(e),!0}catch{return!1}}function CTe({content:e}){return!Array.isArray(e)||e.length===0?f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No content"}):f.jsx("div",{className:"space-y-4",children:e.map((t,n)=>{if(t.type==="text"){const a=t.text||"";if(NTe(a))try{const r=JSON.parse(a);return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Text Content (JSON)"}),f.jsx(Xn,{data:r,filename:`content-${n}.json`})]},n)}catch{}return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Text Content"}),f.jsx("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 font-mono text-sm whitespace-pre-wrap break-words",children:a})]},n)}if(t.type==="image")return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Image Content"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3",children:[f.jsx("img",{src:`data:${t.mimeType||"image/png"};base64,${t.data}`,alt:"Result",className:"max-w-full rounded"}),t.annotations&&f.jsx("div",{className:"mt-2 text-xs text-gray-500 dark:text-gray-400",children:f.jsx(Xn,{data:t.annotations,filename:`image-annotations-${n}.json`})})]})]},n);if(t.type==="audio")return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Audio Content"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3",children:[f.jsx("audio",{controls:!0,src:`data:${t.mimeType||"audio/wav"};base64,${t.data}`,className:"w-full"}),t.annotations&&f.jsx("div",{className:"mt-2 text-xs text-gray-500 dark:text-gray-400",children:f.jsx(Xn,{data:t.annotations,filename:`audio-annotations-${n}.json`})})]})]},n);if(t.type==="resource_link")return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Resource Link"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 space-y-2",children:[f.jsxs("div",{className:"font-mono text-sm break-all",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"URI:"})," ",t.uri]}),t.name&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"Name:"})," ",t.name]}),t.description&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"Description:"})," ",t.description]}),t.mimeType&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"MIME Type:"})," ",t.mimeType]}),t.annotations&&f.jsxs("div",{className:"mt-2",children:[f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Annotations:"}),f.jsx(Xn,{data:t.annotations,filename:`resource-link-annotations-${n}.json`})]})]})]},n);if(t.type==="resource"){const a=t.resource||{};return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Embedded Resource"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 space-y-2",children:[f.jsxs("div",{className:"font-mono text-sm break-all",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"URI:"})," ",a.uri]}),a.mimeType&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"MIME Type:"})," ",a.mimeType]}),a.text&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Content:"}),f.jsx("div",{className:"bg-white dark:bg-black rounded p-2 font-mono text-sm whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:a.text})]}),a.blob&&f.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:["[Binary content: ",a.blob.length||0," bytes]"]}),a.annotations&&f.jsxs("div",{className:"mt-2",children:[f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Annotations:"}),f.jsx(Xn,{data:a.annotations,filename:`resource-annotations-${n}.json`})]})]})]},n)}return f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:["Unknown Content Type: ",t.type||"N/A"]}),f.jsx(Xn,{data:t,filename:`content-${n}.json`})]},n)})})}function Z2({results:e,copiedResult:t,previewMode:n,serverId:a,readResource:r,onCopy:i,onTogglePreview:s,onMaximize:c,isMaximized:u=!1}){const[d,m]=y.useState(0),[h,g]=y.useState(""),[v,x]=y.useState(!0),S=e[0],w=S?e.filter(ee=>ee.toolName===S.toolName):[],E=w[d]||w[0],_=e.findIndex(ee=>ee===E);y.useEffect(()=>{w.length>0&&d>=w.length&&m(0)},[w.length,d]),y.useEffect(()=>{const ee=()=>{E&&g(K2(E.timestamp))};ee();const ae=setInterval(ee,1e3);return()=>clearInterval(ae)},[E]);const k=y.useMemo(()=>E?.args,[E?.timestamp,d]),C=y.useMemo(()=>E?.result,[E?.timestamp,d]),R=y.useCallback(ee=>r(ee),[r]);if(e.length===0)return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:f.jsx("div",{className:"flex items-center justify-center h-full",children:f.jsx("div",{className:"text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})});const I=E.toolMeta?.["openai/outputTemplate"],A=!!(I&&typeof I=="string"&&E.appsSdkResource),O=I,M=E.result?.content||[],P=M.filter(ee=>ee.type==="resource"&&Ru(ee.resource)),B=P.length>0,K=!!(M&&M.length>0||E.result?.structuredContent),Q=!B&&!A&&K;return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:f.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[f.jsxs("div",{className:`flex items-center gap-2 px-4 pt-2 ${B||A||Q?"border-b border-gray-200 dark:border-zinc-600 pb-2":""}`,children:[f.jsx("h3",{className:"text-sm font-medium hidden sm:block",children:"Response"}),E.duration!==void 0&&f.jsxs("div",{className:"hidden sm:flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[E.duration,"ms"]})]}),A&&f.jsxs("div",{className:"flex items-center gap-4 sm:ml-4",children:[f.jsxs("span",{className:"hidden sm:inline text-xs text-gray-500 dark:text-gray-400",children:["URI: ",O||"No URI"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Component"}),f.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw JSON"})]})]}),B&&!A&&f.jsxs("div",{className:"flex items-center gap-4 sm:ml-4",children:[f.jsxs("span",{className:"hidden sm:inline text-xs text-gray-500 dark:text-gray-400",children:["URI: ",P[0]?.resource?.uri||"No URI"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Preview"}),f.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"JSON"})]})]}),Q&&f.jsxs("div",{className:"flex items-center gap-2 sm:ml-4",children:[f.jsx("button",{onClick:()=>x(!0),className:`text-xs font-medium ${v?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Formatted"}),f.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),f.jsx("button",{onClick:()=>x(!1),className:`text-xs font-medium ${v?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw"})]}),f.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[(A||B)&&c&&f.jsx($e,{variant:"ghost",size:"sm",onClick:c,title:u?"Restore":"Maximize",children:u?f.jsx(ghe,{className:"h-4 w-4"}):f.jsx(tC,{className:"h-4 w-4"})}),w.length>1&&f.jsxs(Oo,{value:d.toString(),onValueChange:ee=>m(parseInt(ee)),children:[f.jsx(jo,{size:"sm",className:"w-[140px] h-8 text-xs",children:f.jsx(Do,{children:f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Av,{className:"h-3 w-3"}),f.jsx("span",{children:h})]})})}),f.jsx($o,{children:w.map((ee,ae)=>f.jsx(Ir,{value:ae.toString(),children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Av,{className:"h-3 w-3"}),f.jsx("span",{children:K2(ee.timestamp)}),f.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",new Date(ee.timestamp).toLocaleTimeString(),")"]})]})},ae))})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>i(_,E.result),children:t===_?f.jsx(ra,{className:"h-4 w-4"}):f.jsx(Lr,{className:"h-4 w-4"})})]})]}),(()=>{const ee=E.error||TTe(E.result);return ee?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:ee})]}):(()=>{if(A){const ae=E.appsSdkResource;return ae.isLoading?f.jsx(f.Fragment,{}):ae.error?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Resource Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:ae.error})]}):n?f.jsx("div",{className:"flex-1",children:f.jsx(hD,{componentUrl:O,toolName:E.toolName,toolArgs:k,toolResult:C,serverId:a,readResource:R,className:"w-full h-full relative p-4"})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:E.result,filename:`tool-result-${E.toolName}-${Date.now()}.json`})})}if(B)return n?f.jsxs("div",{className:"space-y-0 h-full",children:[P.map((ae,H)=>f.jsx("div",{className:"mx-0 size-full",children:f.jsx(ZY,{resource:ae.resource,onUIAction:Z=>{},className:"w-full h-full relative"})},H)),M.filter(ae=>!(ae.type==="resource"&&Ru(ae.resource))).length>0&&f.jsx("div",{className:"px-4",children:f.jsx(Xn,{data:M.filter(ae=>!(ae.type==="resource"&&Ru(ae.resource))),filename:`tool-result-${E.toolName}-non-ui-${Date.now()}.json`})})]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:E.result,filename:`tool-result-${E.toolName}-mcp-ui-${Date.now()}.json`})});if(Q&&v){const ae=E.result?.structuredContent;return f.jsxs("div",{className:"px-4 pt-4 space-y-4",children:[ae&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Structured Content"}),f.jsx(Xn,{data:ae,filename:`structured-content-${E.toolName}-${Date.now()}.json`})]}),M&&M.length>0&&f.jsx(CTe,{content:M}),!ae&&(!M||M.length===0)&&f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No content to display"})]})}return f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:E.result,filename:`tool-result-${E.toolName}-${Date.now()}.json`})})})()})()]})})})}function Y2({tools:e,selectedTool:t,onToolSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Wl,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No tools available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((r,i)=>f.jsx(Qs,{id:`tool-${r.name}`,isSelected:t?.name===r.name,isFocused:a===i,icon:f.jsx(Wl,{className:"h-4 w-4"}),title:r.name,description:r.description,metadata:r.inputSchema?.properties&&f.jsxs(Sr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[Object.keys(r.inputSchema.properties).length," params"]}),onClick:()=>n(r)},r.name))})}function q2({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredToolsCount:a,savedRequestsCount:r,onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d}){return f.jsx(WY,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"tools",secondaryTabName:"saved",primaryTabTitle:"Tools",secondaryTabTitle:"Saved",primaryCount:a,secondaryCount:r,primaryIcon:Wl,secondaryIcon:Jy,searchPlaceholder:"Search tools...",onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d})}const X2="mcp-inspector-saved-requests";function XY({ref:e,tools:t,callTool:n,readResource:a,serverId:r,isConnected:i}){const[s,c]=y.useState(null),[u,d]=y.useState(null),{selectedToolName:m,setSelectedToolName:h}=ic(),[g,v]=y.useState({}),[x,S]=y.useState([]),[w,E]=y.useState(!1),[_,k]=y.useState(null),[C,R]=y.useState(null),[I,A]=y.useState(""),[O,M]=y.useState("tools"),[P,B]=y.useState([]),[K,Q]=y.useState(!1),[ee,ae]=y.useState(""),[H,Z]=y.useState(!0),[G,re]=y.useState(!1),[te,j]=y.useState(-1),V=y.useRef(null),[z,$]=y.useState(!1),[L,F]=y.useState("list"),[W,ne]=y.useState(!1),[le,ue]=y.useState(0),[X,q]=y.useState(!0),[oe,me]=y.useState(void 0),ie=y.useRef(null),Ne=y.useRef(null),He=y.useRef(null),ye=y.useRef(null),Se=y.useRef(null);y.useEffect(()=>{const Ee=()=>{$(window.innerWidth<1024)};return Ee(),window.addEventListener("resize",Ee),()=>window.removeEventListener("resize",Ee)},[]),y.useEffect(()=>{F(s?"detail":"list")},[s]),y.useEffect(()=>{z&&x.length>0&&!w&&F("response")},[x,w,z]),y.useImperativeHandle(e,()=>({focusSearch:()=>{re(!0),setTimeout(()=>{V.current&&V.current.focus()},0)},blurSearch:()=>{A(""),re(!1),V.current&&V.current.blur()}})),y.useEffect(()=>{try{const Ee=localStorage.getItem(X2);Ee&&B(JSON.parse(Ee))}catch(Ee){console.error("[ToolsTab] Failed to load saved requests:",Ee)}},[]);const Pe=y.useCallback(Ee=>{try{localStorage.setItem(X2,JSON.stringify(Ee)),B(Ee)}catch(je){console.error("[ToolsTab] Failed to save requests:",je)}},[]),fe=y.useMemo(()=>{if(!I.trim())return t;const Ee=I.toLowerCase();return t.filter(je=>je.name.toLowerCase().includes(Ee)||je.description?.toLowerCase().includes(Ee))},[t,I]),Ae=y.useCallback(Ee=>{c(Ee);const je={};Ee.inputSchema?.properties&&Object.entries(Ee.inputSchema.properties).forEach(([Fe,We])=>{const Je=We;Je.default!==void 0?je[Fe]=Je.default:Je.type==="string"?je[Fe]="":Je.type==="number"?je[Fe]=0:Je.type==="boolean"?je[Fe]=!1:Je.type==="array"?je[Fe]="[]":Je.type==="object"&&(je[Fe]="{}")}),v(je)},[]),Me=y.useCallback(Ee=>{const je=t.find(Fe=>Fe.name===Ee.toolName);je&&(c(je),v(Ee.args),d(Ee))},[t]);y.useEffect(()=>{G&&V.current&&V.current.focus()},[G]);const _e=y.useCallback(()=>{I.trim()||re(!1)},[I]);y.useEffect(()=>{O!=="tools"&&re(!1)},[O]),y.useEffect(()=>{j(-1)},[I,O]),y.useEffect(()=>{const Ee=je=>{const Fe=je.target;if(Fe.tagName==="INPUT"||Fe.tagName==="TEXTAREA"||Fe.contentEditable==="true"||je.metaKey||je.ctrlKey||je.altKey)return;const Je=O==="tools"?fe:P;if(je.key==="ArrowDown")je.preventDefault(),j(St=>{const ht=St+1;return ht>=Je.length?0:ht});else if(je.key==="ArrowUp")je.preventDefault(),j(St=>{const ht=St-1;return ht<0?Je.length-1:ht});else if(je.key==="Enter"&&te>=0)if(je.preventDefault(),O==="tools"){const St=fe[te];St&&Ae(St)}else{const St=P[te];St&&Me(St)}};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[te,fe,P,O,Ae,Me]),y.useEffect(()=>{if(te>=0){const Ee=O==="tools"?`tool-${fe[te]?.name}`:`saved-${P[te]?.id}`,je=document.getElementById(Ee);je&&je.scrollIntoView({behavior:"smooth",block:"nearest"})}},[te,fe,P,O]),y.useEffect(()=>{if(m&&t.length>0){const Ee=t.find(je=>je.name===m);if(Ee&&s?.name!==Ee.name){h(null);const je=setTimeout(()=>{Ae(Ee);const Fe=document.getElementById(`tool-${Ee.name}`);Fe&&Fe.scrollIntoView({behavior:"smooth",block:"nearest"})},100);return()=>clearTimeout(je)}}},[m,t,s,Ae,h]);const rt=y.useCallback((Ee,je)=>{v(Fe=>{const We={...Fe};if(s?.inputSchema?.properties?.[Ee]){const St=s.inputSchema.properties[Ee].type;if(St==="object"||St==="array")We[Ee]=je;else if(St==="string")We[Ee]=je;else try{We[Ee]=JSON.parse(je)}catch{We[Ee]=je}}else We[Ee]=je;return We})},[s]),nt=y.useCallback(async()=>{if(!s||w)return;const Ee=new AbortController;R(Ee),E(!0);const je=Date.now();try{const Fe={...g};s.inputSchema?.properties&&Object.entries(s.inputSchema.properties).forEach(([Ke,Ze])=>{const At=Ze.type,er=Fe[Ke];if((At==="object"||At==="array")&&typeof er=="string")try{Fe[Ke]=JSON.parse(er)}catch{}});const We=await n(s.name,Fe,{timeout:6e5,resetTimeoutOnProgress:!0,signal:Ee.signal}),Je=Date.now()-je;yr.getInstance().capture(new XU({toolName:s.name,serverId:r,success:!0,duration:Je})).catch(()=>{});const ht=s?._meta||s?.metadata,Mt=ht?.["openai/outputTemplate"];let rn;if(Mt&&typeof Mt=="string"){const Ke={toolName:s.name,args:g,result:We,timestamp:je,duration:Je,toolMeta:ht,appsSdkResource:{uri:Mt,resourceData:null,isLoading:!0}};S([Ke]);try{const Ze=await a(Mt);let mt=null;if(We?.structuredContent)mt=We.structuredContent;else if(Array.isArray(We)&&We[0]){const At=We[0];At.output?.value?.structuredContent?mt=At.output.value.structuredContent:At.structuredContent?mt=At.structuredContent:At.output?.value&&(mt=At.output.value)}mt||(mt=We),rn={uri:Mt,resourceData:{...Ze,structuredContent:mt},isLoading:!1}}catch(Ze){rn={uri:Mt,resourceData:null,isLoading:!1,error:Ze instanceof Error?Ze.message:String(Ze)}}S(Ze=>Ze.map((mt,At)=>At===0?{...mt,appsSdkResource:rn}:mt))}else S(Ke=>[{toolName:s.name,args:g,result:We,timestamp:je,duration:Je,toolMeta:ht},...Ke])}catch(Fe){const We=Date.now()-je;yr.getInstance().capture(new XU({toolName:s.name,serverId:r,success:!1,duration:We,error:Fe instanceof Error?Fe.message:String(Fe)})).catch(()=>{});const St=s?._meta||s?.metadata,ht={toolName:s.name,args:g,result:null,error:Fe instanceof Error?Fe.message:String(Fe),timestamp:je,duration:We,toolMeta:St},Mt=St?.["openai/outputTemplate"];S(Mt?[ht]:rn=>[ht,...rn])}finally{E(!1)}},[s,g,w,n,a,r]),ct=y.useCallback(async(Ee,je)=>{try{await navigator.clipboard.writeText(JSON.stringify(je,null,2)),k(Ee),setTimeout(()=>k(null),2e3)}catch(Fe){console.error("[ToolsTab] Failed to copy result:",Fe)}},[]),bt=y.useCallback(Ee=>{S(je=>je.filter((Fe,We)=>We!==Ee))},[]),ut=y.useMemo(()=>s?x.filter(Ee=>Ee.toolName===s.name):[],[x,s]),nn=y.useCallback(Ee=>{const je=ut[Ee];if(je){const Fe=window.open("","_blank","width=800,height=600");Fe&&(Fe.document.write(`
|
|
1663
1663
|
<html>
|
|
@@ -1673,4 +1673,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1673
1673
|
<pre>${JSON.stringify(je.result,null,2)}</pre>
|
|
1674
1674
|
</body>
|
|
1675
1675
|
</html>
|
|
1676
|
-
`),Fe.document.close())}},[x]),Qn=y.useCallback(()=>{W?(ie.current&&ie.current.expand(),Ne.current&&Ne.current.expand(),ne(!1)):(ie.current&&ie.current.collapse(),Ne.current&&Ne.current.collapse(),ne(!0))},[W]),ot=y.useCallback(()=>{s&&(ae(""),Q(!0))},[s]),Ve=y.useCallback(()=>{if(!s)return;const Ee={id:`${Date.now()}-${Math.random()}`,name:ee.trim()||`${s.name} - ${new Date().toLocaleString()}`,toolName:s.name,args:g,savedAt:Date.now(),serverId:s._serverId,serverName:s._serverName};Pe([...P,Ee]),yr.getInstance().capture(new nme({toolName:s.name,serverId:r})).catch(()=>{}),Q(!1),ae("")},[s,ee,g,P,Pe,r]),Le=y.useCallback(Ee=>{Pe(P.filter(je=>je.id!==Ee)),u?.id===Ee&&d(null)},[P,Pe,u]);return z?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[L!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{L==="response"?F("detail"):(c(null),F("list"))},className:"p-0 h-8 w-8",children:f.jsx(Xy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{c(null),F("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),L==="detail"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{F("response")},className:L==="detail"?"text-foreground hover:underline":L==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),L==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(aw,{initial:!1,mode:"popLayout",children:[L==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(q2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:_e,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Y2,{tools:fe,selectedTool:s,onToolSelect:Ae,focusedIndex:te}):f.jsx(H2,{savedRequests:P,selectedRequest:u,onLoadRequest:Me,onDeleteRequest:Le,focusedIndex:te})]},"list"),L==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(W2,{selectedTool:s,toolArgs:g,isExecuting:w,isConnected:i,onArgChange:rt,onExecute:nt,onSave:ot})},"detail"),L==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(Z2,{results:ut,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ct,onDelete:bt,onFullscreen:nn,onTogglePreview:()=>Z(!H)})},"response")]})}),f.jsx(V2,{isOpen:K,requestName:ee,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Ve,onCancel:()=>Q(!1)})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{ref:ie,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(q2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:_e,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Y2,{tools:fe,selectedTool:s,onToolSelect:Ae,focusedIndex:te}):f.jsx(H2,{savedRequests:P,selectedRequest:u,onLoadRequest:Me,onDeleteRequest:Le,focusedIndex:te})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:ye,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>{q(!0)},onExpand:()=>{q(!1)},className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation(),X?(ye.current?.resize(25),q(!1)):(ye.current?.resize(5),q(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),le>0&&f.jsx(Sr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:le}),le>0&&!X&&f.jsx($e,{variant:"ghost",size:"sm",onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation(),Se.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${X?"":"rotate-180"}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${X?"hidden":""}`,children:f.jsx(kD,{serverIds:[r],onCountChange:ue,onClearRef:Se})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{ref:Ne,defaultSize:40,collapsible:!0,children:f.jsx(W2,{selectedTool:s,toolArgs:g,isExecuting:w,isConnected:i,onArgChange:rt,onExecute:nt,onSave:ot,onCancel:()=>{C&&C.abort()}})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{ref:He,defaultSize:60,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(Z2,{results:ut,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ct,onDelete:bt,onFullscreen:nn,onTogglePreview:()=>Z(!H),onMaximize:Qn,isMaximized:W})})})]})}),f.jsx(V2,{isOpen:K,requestName:ee,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Ve,onCancel:()=>Q(!1)})]})}XY.displayName="ToolsTab";function RTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onRejectAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Reject all"})]})})]})}function ATe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.params?.messages?.length||0,d=s.request.params?.maxTokens;return f.jsx(Qs,{id:`sampling-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=r(s.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),d&&h.push(`max ${d} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function ITe({llmConfig:e}){const t=y.useRef(null);return{generateResponse:y.useCallback(async({request:a})=>{if(!e)throw new Error("LLM config is not available");const r=a.params||{},i=r.maxTokens,s=r.temperature;r.modelPreferences;const c=r.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!r,messagesCount:c.length,messages:c,params:r}),c.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:d,AIMessage:m}=await Jn(async()=>{const{HumanMessage:x,AIMessage:S}=await import("./index-QOx227bY.js").then(w=>w.bI);return{HumanMessage:x,AIMessage:S}},[]);for(const x of c){if(!x||!x.role){console.warn("Skipping invalid message:",x);continue}const S=Array.isArray(x.content)?x.content[0]:x.content;if(!S){console.warn("Skipping message with no content:",x);continue}S.type==="text"&&S.text?x.role==="user"?u.push(new d(S.text)):x.role==="assistant"&&u.push(new m(S.text)):console.warn("Skipping message with unsupported content type:",S)}if(u.length===0)throw new Error("No valid messages could be converted. Please ensure messages have 'text' content type.");if(!t.current||t.current.provider!==e.provider||t.current.model!==e.model||t.current.apiKey!==e.apiKey){let x;const S={model:e.model,apiKey:e.apiKey};if(i!==void 0&&(S.maxTokens=i),s!==void 0?S.temperature=s:e.temperature!==void 0&&(S.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:w}=await Jn(async()=>{const{ChatOpenAI:E}=await import("./index-DclCkKwz.js");return{ChatOpenAI:E}},__vite__mapDeps([6,7,8,2,9,10,11]));x=new w(S)}else if(e.provider==="anthropic"){const{ChatAnthropic:w}=await Jn(async()=>{const{ChatAnthropic:E}=await import("./index-CCasFtk_.js");return{ChatAnthropic:E}},__vite__mapDeps([12,8,7,2,11]));x=new w(S)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:w}=await Jn(async()=>{const{ChatGoogleGenerativeAI:E}=await import("./index-DznD3Siw.js");return{ChatGoogleGenerativeAI:E}},__vite__mapDeps([13,8,7,2,10]));x=new w(S)}else throw new Error(`Unsupported LLM provider: ${e.provider}`);t.current={instance:x,provider:e.provider,model:e.model,apiKey:e.apiKey}}const h=await t.current.instance.invoke(u);return{role:"assistant",content:{type:"text",text:h.content||h.text||""},model:e.model,stopReason:"endTurn"}},[e]),isAvailable:e!==null}}function OTe({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d,llmConfig:m}){const[h,g]=y.useState("manual"),[v,x]=y.useState("stub-model"),[S,w]=y.useState("endTurn"),[E,_]=y.useState("assistant"),[k,C]=y.useState("text"),[R,I]=y.useState("positive"),[A,O]=y.useState(""),[M,P]=y.useState("image/png"),[B,K]=y.useState(!1),[Q,ee]=y.useState(null),{generateResponse:ae,isAvailable:H}=ITe({llmConfig:m});y.useEffect(()=>{e&&(x("stub-model"),w("endTurn"),_("assistant"),C("text"),I("positive"),O(""),P("image/png"),ee(null))},[e?.id]);const Z=async()=>{if(!(!e||!H)){K(!0),ee(null);try{const j=await ae({request:e.request});x(j.model||m?.model||"stub-model"),w(j.stopReason||"endTurn"),_(j.role||"assistant");const V=Array.isArray(j.content)?j.content[0]:j.content;V.type==="text"?(C("text"),I(V.text||"")):V.type==="image"&&(C("image"),O(V.data||""),P(V.mimeType||"image/png"))}catch(j){const V=j instanceof Error?j.message:"Failed to generate response";ee(V),Xt.error("LLM Generation Failed",{description:V})}finally{K(!1)}}},G=y.useMemo(()=>{const j={model:v,stopReason:S,role:E,content:{type:k}};return k==="text"?j.content.text=R:k==="image"&&(j.content.data=A,j.content.mimeType=M),j},[v,S,E,k,R,A,M]),re=()=>{if(!e)return;const j=uN.safeParse(G);if(!j.success){Xt.error("Invalid response",{description:`Validation failed: ${j.error.message}`});return}t(e.id,j.data),a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(V=>{const z=Xt(V.createElement("div",{className:"space-y-3"},V.createElement("div",null,V.createElement("strong",null,"Sampling Response Sent"),V.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),V.createElement("div",{className:"flex gap-2"},V.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const $=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent($),Xt.dismiss(z)}},"View Tool Result"))),{duration:5e3})})},te=()=>{e&&(n(e.id,"User rejected sampling request"),a())};return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx(Lr,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(eC,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request})})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Kt,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),f.jsxs(Oo,{value:h,onValueChange:j=>g(j),children:[f.jsx(jo,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:f.jsx(Do,{})}),f.jsxs($o,{children:[f.jsx(Ir,{value:"manual",children:"Manual"}),f.jsx(Ir,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&f.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[H?f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx($e,{onClick:Z,disabled:B,size:"sm",className:"flex items-center gap-2",children:B?f.jsxs(f.Fragment,{children:[f.jsx(zs,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):f.jsxs(f.Fragment,{children:[f.jsx($he,{className:"h-4 w-4"}),"Generate with LLM"]})}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),Q&&f.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:Q})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`model-${e.id}`,children:"Model"}),f.jsx(En,{id:`model-${e.id}`,value:v,onChange:j=>x(j.target.value),placeholder:"stub-model",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),f.jsx(En,{id:`stopReason-${e.id}`,value:S,onChange:j=>w(j.target.value),placeholder:"endTurn",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`role-${e.id}`,children:"Role"}),f.jsxs(Oo,{value:E,onValueChange:j=>_(j),disabled:h==="llm"&&B,children:[f.jsx(jo,{id:`role-${e.id}`,children:f.jsx(Do,{})}),f.jsxs($o,{children:[f.jsx(Ir,{value:"assistant",children:"assistant"}),f.jsx(Ir,{value:"user",children:"user"})]})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),f.jsxs(Oo,{value:k,onValueChange:j=>C(j),disabled:h==="llm"&&B,children:[f.jsx(jo,{id:`contentType-${e.id}`,children:f.jsx(Do,{})}),f.jsxs($o,{children:[f.jsx(Ir,{value:"text",children:"text"}),f.jsx(Ir,{value:"image",children:"image"})]})]})]}),k==="text"&&f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`text-${e.id}`,children:"Text Content"}),f.jsx(Xl,{id:`text-${e.id}`,value:R,onChange:j=>I(j.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&B})]}),k==="image"&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),f.jsx(Xl,{id:`imageData-${e.id}`,value:A,onChange:j=>O(j.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),f.jsx(En,{id:`mimeType-${e.id}`,value:M,onChange:j=>P(j.target.value),placeholder:"image/png",disabled:h==="llm"&&B})]})]})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:re,className:"flex-1",disabled:h==="llm"&&B,children:"Approve"}),f.jsx($e,{onClick:te,variant:"outline",className:"flex-1",disabled:h==="llm"&&B,children:"Reject"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}function DTe({pendingRequests:e,onApprove:t,onReject:n,serverId:a,isConnected:r,mcpServerUrl:i}){const{selectedSamplingRequestId:s,setSelectedSamplingRequestId:c}=ic(),{llmConfig:u}=EY({mcpServerUrl:i}),[d,m]=y.useState(null),[h,g]=y.useState(""),[v,x]=y.useState(-1),[S,w]=y.useState(!0),[E,_]=y.useState(!1),[k,C]=y.useState(!0),[R,I]=y.useState(!1),A=y.useRef(null),O=y.useRef(null),M=y.useRef(null),P=y.useRef(!1);y.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:s,pendingRequestsCount:e.length,currentSelectedId:d?.id}),s&&e.length>0){const G=e.find(re=>re.id===s);console.log("[SamplingTab] Found request for auto-selection:",!!G,G?.id),G&&(console.log("[SamplingTab] Auto-selecting request:",G.id),c(null),m(G),setTimeout(()=>{const re=document.getElementById(`sampling-request-${G.id}`);console.log("[SamplingTab] Scrolling to element:",!!re),re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[s,e,c]),y.useEffect(()=>{const G=re=>{const j=re.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",j);const V=e.find(z=>z.id===j);V&&(console.log("[SamplingTab] Selecting request from event:",j),m(V),setTimeout(()=>{const z=document.getElementById(`sampling-request-${j}`);z&&z.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",G),()=>window.removeEventListener("navigate-to-sampling",G)},[e]),y.useEffect(()=>{S&&e.length>0&&A.current&&!P.current&&(A.current.scrollTop=0)},[e.length,S]),y.useEffect(()=>{const G=A.current;if(!G)return;const re=()=>{G.scrollTop>0&&(P.current=!0,w(!1))};return G.addEventListener("scroll",re),()=>G.removeEventListener("scroll",re)},[]),y.useEffect(()=>{e.length===0&&(P.current=!1,w(!0))},[e.length]),y.useEffect(()=>{E&&M.current&&M.current.focus()},[E]);const B=y.useCallback(()=>{h.trim()||_(!1)},[h]),K=y.useMemo(()=>{if(!h.trim())return e;const G=h.toLowerCase();return e.filter(re=>re.serverName.toLowerCase().includes(G)||JSON.stringify(re.request||{}).toLowerCase().includes(G))},[e,h]);y.useEffect(()=>{x(-1)},[h]),y.useEffect(()=>{const G=re=>{const te=re.target;if(te.tagName==="INPUT"||te.tagName==="TEXTAREA"||te.contentEditable==="true"||re.metaKey||re.ctrlKey||re.altKey)return;const V=K;if(re.key==="ArrowDown")re.preventDefault(),x(z=>{const $=z+1;return $>=V.length?0:$});else if(re.key==="ArrowUp")re.preventDefault(),x(z=>{const $=z-1;return $<0?V.length-1:$});else if(re.key==="Enter"&&v>=0){re.preventDefault();const z=K[v];z&&Q(z)}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[v,K]),y.useEffect(()=>{if(v>=0){const G=`sampling-request-${K[v]?.id}`,re=document.getElementById(G);re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})}},[v,K]);const Q=y.useCallback(G=>{m(G)},[]),ee=y.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(G=>{n(G.id,"User rejected all requests")}),m(null))},[e,n]),ae=y.useCallback(async()=>{if(d)try{await navigator.clipboard.writeText(JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)),I(!0),setTimeout(()=>I(!1),2e3)}catch(G){console.error("[SamplingTab] Failed to copy request:",G)}},[d]),H=y.useCallback(()=>{if(d)try{const G=new globalThis.Blob([JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)],{type:"application/json"}),re=URL.createObjectURL(G),te=document.createElement("a");te.href=re,te.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(te),te.click(),document.body.removeChild(te),URL.revokeObjectURL(re)}catch(G){console.error("[SamplingTab] Failed to download request:",G)}},[d]),Z=y.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(G){console.error("[SamplingTab] Failed to toggle fullscreen:",G)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(RTe,{isSearchExpanded:E,searchQuery:h,filteredRequestsCount:K.length,requestsCount:e.length,onSearchExpand:()=>_(!0),onSearchChange:g,onSearchBlur:B,onRejectAll:ee,searchInputRef:M}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(ATe,{requests:K,selectedRequest:d,onRequestSelect:Q,focusedIndex:v,formatRelativeTime:ny,listRef:A})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(OTe,{request:d,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:k,onTogglePreview:()=>C(!k),isCopied:R,onCopy:ae,onDownload:H,onFullscreen:Z,llmConfig:u})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(UG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function jTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onCancelAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Cancel all"})]})})]})}function $Te({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.mode||"form",d=u==="form"&&"requestedSchema"in s.request&&s.request.requestedSchema;return f.jsx(Qs,{id:`elicitation-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx(Sr,{variant:"outline",className:u==="url"?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:u})]}),description:(()=>{const m=r(s.timestamp),h=[];d&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function LTe({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d}){const[m,h]=y.useState({}),[g,v]=y.useState(!1),x=e?.request.mode||"form",S=x==="form",w=x==="url";y.useEffect(()=>{if(e&&S&&"requestedSchema"in e.request){const A=e.request.requestedSchema,O={};if(A?.type==="object"&&A.properties)for(const[M,P]of Object.entries(A.properties)){const B=P;B.default!==void 0?O[M]=B.default:B.type==="boolean"?O[M]=!1:B.type==="number"||B.type==="integer"?O[M]=0:O[M]=""}h(O)}v(!1)},[e?.id,S]);const E=(A,O)=>{h(M=>({...M,[A]:O}))},_=()=>{if(e){if(S){if("requestedSchema"in e.request){const A=e.request.requestedSchema;if(A?.required){const O=A.required.filter(M=>m[M]===void 0||m[M]===""||m[M]===null);if(O.length>0){Xt.error("Missing required fields",{description:`Please fill in: ${O.join(", ")}`});return}}}t(e.id,{action:"accept",data:m})}else w&&t(e.id,{action:"accept"});a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(A=>{const O=Xt(A.createElement("div",{className:"space-y-3"},A.createElement("div",null,A.createElement("strong",null,"Elicitation Response Sent"),A.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),A.createElement("div",{className:"flex gap-2"},A.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const M=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(M),Xt.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},k=()=>{e&&(t(e.id,{action:"decline"}),a())},C=()=>{e&&(n(e.id,"User cancelled elicitation request"),a())},R=()=>{e&&w&&"url"in e.request&&(window.open(e.request.url,"_blank"),v(!0))},I=y.useMemo(()=>{if(!e||!S||!("requestedSchema"in e.request))return null;const A=e.request.requestedSchema;if(!A||A.type!=="object"||!A.properties)return f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=A.properties,M=A.required||[];return f.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([P,B])=>{const K=B,Q=M.includes(P),ee=K.type||"string",ae=K.title||P,H=K.description;return f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:`field-${P}`,children:[ae,Q&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),H&&f.jsx("p",{className:"text-xs text-muted-foreground",children:H}),ee==="boolean"?f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx(im,{id:`field-${P}`,checked:m[P]||!1,onCheckedChange:Z=>E(P,Z)}),f.jsx(Kt,{htmlFor:`field-${P}`,className:"text-sm font-normal cursor-pointer",children:K.title||P})]}):ee==="number"||ee==="integer"?f.jsx(En,{id:`field-${P}`,type:"number",value:m[P]||"",onChange:Z=>E(P,ee==="integer"?parseInt(Z.target.value,10):parseFloat(Z.target.value)),placeholder:K.default?.toString()||""}):K.enum?f.jsxs("select",{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:[f.jsx("option",{value:"",children:"Select..."}),K.enum.map(Z=>f.jsx("option",{value:Z,children:Z},Z))]}):ee==="string"&&(K.format==="textarea"||K.maxLength>100)?f.jsx(Xl,{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||"",rows:4}):f.jsx(En,{id:`field-${P}`,type:"text",value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||""})]},P)})})},[e,m,S]);return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx(Sr,{variant:"outline",className:w?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:x}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx(Lr,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(eC,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),f.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),w&&"url"in e.request&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),f.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[f.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),f.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[f.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),f.jsxs($e,{size:"sm",variant:"outline",onClick:R,className:"flex items-center gap-2",children:[f.jsx(q_,{className:"h-4 w-4"}),"Open URL"]})]}),f.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[f.jsx(im,{id:"url-completed",checked:g,onCheckedChange:A=>v(!!A)}),f.jsx(Kt,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),S&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),I]}),S&&"requestedSchema"in e.request&&e.request.requestedSchema&&f.jsxs("details",{className:"space-y-2",children:[f.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request.requestedSchema})})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:_,className:"flex-1",children:"Accept"}),f.jsx($e,{onClick:k,variant:"outline",className:"flex-1",children:"Decline"}),f.jsx($e,{onClick:C,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function MTe({pendingRequests:e=[],onApprove:t,onReject:n,serverId:a,isConnected:r}){const{selectedElicitationRequestId:i,setSelectedElicitationRequestId:s}=ic(),[c,u]=y.useState(null),[d,m]=y.useState(""),[h,g]=y.useState(-1),[v,x]=y.useState(!0),[S,w]=y.useState(!1),[E,_]=y.useState(!0),[k,C]=y.useState(!1),R=y.useRef(null),I=y.useRef(null),A=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:i,pendingRequestsCount:e.length,currentSelectedId:c?.id}),i&&e.length>0){const H=e.find(Z=>Z.id===i);console.log("[ElicitationTab] Found request for auto-selection:",!!H,H?.id),H&&(console.log("[ElicitationTab] Auto-selecting request:",H.id),s(null),u(H),setTimeout(()=>{const Z=document.getElementById(`elicitation-request-${H.id}`);console.log("[ElicitationTab] Scrolling to element:",!!Z),Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,s]),y.useEffect(()=>{const H=Z=>{const re=Z.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",re);const te=e.find(j=>j.id===re);te&&(console.log("[ElicitationTab] Selecting request from event:",re),u(te),setTimeout(()=>{const j=document.getElementById(`elicitation-request-${re}`);j&&j.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",H),()=>window.removeEventListener("navigate-to-elicitation",H)},[e]),y.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),y.useEffect(()=>{const H=R.current;if(!H)return;const Z=()=>{H.scrollTop>0&&(O.current=!0,x(!1))};return H.addEventListener("scroll",Z),()=>H.removeEventListener("scroll",Z)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),y.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=y.useCallback(()=>{d.trim()||w(!1)},[d]),P=y.useMemo(()=>{if(!d.trim())return e;const H=d.toLowerCase();return e.filter(Z=>Z.serverName.toLowerCase().includes(H)||Z.request.message.toLowerCase().includes(H)||JSON.stringify(Z.request||{}).toLowerCase().includes(H))},[e,d]);y.useEffect(()=>{g(-1)},[d]),y.useEffect(()=>{const H=Z=>{const G=Z.target;if(G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.contentEditable==="true"||Z.metaKey||Z.ctrlKey||Z.altKey)return;const te=P;if(Z.key==="ArrowDown")Z.preventDefault(),g(j=>{const V=j+1;return V>=te.length?0:V});else if(Z.key==="ArrowUp")Z.preventDefault(),g(j=>{const V=j-1;return V<0?te.length-1:V});else if(Z.key==="Enter"&&h>=0){Z.preventDefault();const j=P[h];j&&B(j)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,P]),y.useEffect(()=>{if(h>=0){const H=`elicitation-request-${P[h]?.id}`,Z=document.getElementById(H);Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=y.useCallback(H=>{u(H)},[]),K=y.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(H=>{n(H.id,"User cancelled all requests")}),u(null))},[e,n]),Q=y.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(H){console.error("[ElicitationTab] Failed to copy request:",H)}},[c]),ee=y.useCallback(()=>{if(c)try{const H=new globalThis.Blob([JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)],{type:"application/json"}),Z=URL.createObjectURL(H),G=document.createElement("a");G.href=Z,G.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(G),G.click(),document.body.removeChild(G),URL.revokeObjectURL(Z)}catch(H){console.error("[ElicitationTab] Failed to download request:",H)}},[c]),ae=y.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(H){console.error("[ElicitationTab] Failed to toggle fullscreen:",H)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(jTe,{isSearchExpanded:S,searchQuery:d,filteredRequestsCount:P.length,requestsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onCancelAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx($Te,{requests:P,selectedRequest:c,onRequestSelect:B,focusedIndex:h,formatRelativeTime:ny,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(LTe,{request:c,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:E,onTogglePreview:()=>_(!E),isCopied:k,onCopy:Q,onDownload:ee,onFullscreen:ae})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(HG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function PTe({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:a,resourcesSearchRef:r,children:i}){return e?f.jsxs(f.Fragment,{children:[f.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:f.jsx(XY,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:f.jsx(KY,{ref:a,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:f.jsx(YY,{ref:r,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:f.jsx(zke,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),f.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:f.jsx(DTe,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),f.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:f.jsx(MTe,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:f.jsx(vTe,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state==="ready"})}),t!=="tools"&&t!=="prompts"&&t!=="resources"&&t!=="chat"&&t!=="sampling"&&t!=="elicitation"&&t!=="notifications"&&f.jsx(f.Fragment,{children:i})]}):f.jsx(f.Fragment,{children:i})}function J2({className:e}){return f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[f.jsx("path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"}),f.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const JY=y.createContext(void 0);function QY(){const e=y.use(JY);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const eq=y.createContext(void 0);function UTe(){return y.use(eq)}function ak({ref:e,children:t,defaultValue:n,value:a,onValueChange:r,className:i,collapsed:s,onCollapsedChange:c,...u}){const[d,m]=y.useState(n||""),h=a!==void 0,g=s!==void 0,[v,x]=y.useState(!1),S=y.useCallback(k=>{h||m(k),r?.(k)},[h,r]),w=h?a:d,E=g?s:v,_=y.useCallback(k=>{g||x(k),c?.(k)},[g,c]);return f.jsx(JY,{value:{activeValue:w,handleValueChange:S,collapsed:E,handleCollapsedChange:_},children:f.jsx("div",{ref:e,className:De("flex flex-col gap-2",i),...u,children:t})})}ak.displayName="Tabs";function ik({ref:e,children:t,className:n,variant:a="default",collapsible:r=!1,...i}){const{activeValue:s,collapsed:c,handleCollapsedChange:u}=QY(),[d,m]=y.useState({width:0,left:0}),h=y.useRef(null),g=y.useRef(null),v=y.useRef(null),x=y.useCallback(()=>{const E=h.current;if(!E)return;const _=E.querySelector("div:first-child");if(!_)return;const k=_.querySelector(`button[data-tab-value="${s}"]`);if(k&&s){const C=_.getBoundingClientRect(),R=k.getBoundingClientRect();m({width:R.width,left:R.left-C.left})}else m({width:0,left:0})},[s]),S=y.useCallback(()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(x,16)},[x]);y.useEffect(()=>{const E=setTimeout(x,10);return()=>clearTimeout(E)},[x,c]),y.useEffect(()=>{const E=h.current;if(!E)return;g.current=new ResizeObserver(()=>{S()}),g.current.observe(E);const _=E.querySelector("div:first-child");return _&&_.querySelectorAll("button[data-tab-value]").forEach(C=>{g.current&&g.current.observe(C)}),()=>{g.current&&g.current.disconnect(),v.current&&clearTimeout(v.current)}},[S]),y.useEffect(()=>{const E=()=>{S()};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[S]);const w=y.useRef(null);return y.useEffect(()=>{w.current&&(w.current.style.width=`${d.width}px`,w.current.style.left=`${d.left}px`)},[d]),f.jsx(eq,{value:{variant:a,collapsed:c,handleCollapsedChange:u},children:f.jsx("div",{ref:h,className:De("relative flex items-center bg-none gap-1",a==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",a==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...i,children:f.jsxs("div",{role:"tablist",className:"flex-1 flex items-center relative",children:[t,f.jsx("span",{ref:w,className:De("absolute transition-all duration-500 ease-in-out z-0",a==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600",a==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white")})]})})})}ik.displayName="TabsList";const zTe=({children:e,title:t,collapsed:n})=>!t||!n?e:f.jsx(YN,{children:f.jsxs(Nt,{children:[f.jsx(Ct,{children:e}),f.jsx(Rt,{children:t})]})}),ok=y.forwardRef(({children:e,value:t,className:n,disabled:a,icon:r,title:i,...s},c)=>{const{activeValue:u,handleValueChange:d,collapsed:m}=QY(),g=UTe()?.variant||"default",v=u===t,x=m&&i?i:void 0;return f.jsx(zTe,{title:i,collapsed:m,children:f.jsxs("button",{ref:c,disabled:a,onClick:()=>d(t),"data-tab-value":t,"data-tab-active":v,role:"tab","aria-selected":v?"true":"false",title:x,className:De("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-500 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer",g==="default"&&"py-2.5",g==="default"&&"rounded-md px-4",g==="underline"&&"px-6 py-3 border-b-2 border-transparent",v&&"text-foreground",!v&&"text-muted-foreground hover:text-foreground",n),...s,children:[r&&f.jsx(r,{className:De("h-4 w-4 transition-all duration-500 ease-in-out",!m&&"mr-2",m&&"mr-0!")}),f.jsx("span",{className:De("transition-all duration-500 ease-in-out overflow-hidden",m?"w-0 opacity-0":"w-auto opacity-100"),children:e})]})})});ok.displayName="TabsTrigger";function Q2({className:e}){const{theme:t,setTheme:n}=_w(),a=y.useRef(null),[r,i]=y.useState(!1);y.useEffect(()=>{i(!0)},[]);const s=()=>t==="system"?"light":t==="light"?"dark":"system",c=()=>t==="system"?f.jsx(az,{className:"size-4"}):t==="light"?f.jsx(zhe,{className:"size-5"}):f.jsx(yhe,{className:"size-4"}),u=()=>t==="system"?"Switch to light mode":t==="light"?"Switch to dark mode":"Switch to system mode",d=async()=>{if(!a.current)return;const m=s();if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{Od.flushSync(()=>{n(m)})}).ready;const{top:h,left:g,width:v,height:x}=a.current.getBoundingClientRect(),S=h+x/2,w=g+v/2,E=window.innerWidth-g,_=window.innerHeight-h,k=Math.hypot(Math.max(g,E),Math.max(h,_));document.documentElement.animate({clipPath:[`circle(0px at ${w}px ${S}px)`,`circle(${k}px at ${w}px ${S}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(m)};return r?f.jsx("button",{ref:a,onClick:d,className:De(e),"aria-label":u(),title:`Current: ${t==="system"?"Auto":t==="light"?"Light":"Dark"}`,children:c()}):f.jsx("button",{ref:a,className:De(e),"aria-label":"Toggle theme",children:f.jsx(az,{className:"size-4"})})}function eF({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[a,r]=y.useState(!1),i=.2,s=.7,c=.6,u=4,d=i+s+c,m=0,h=i/d,g=(i+s)/d,v=1;return f.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:De("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[f.jsx("div",{className:"relative",children:f.jsxs(ya.svg,{viewBox:"0 0 303 303",initial:"rest",animate:a?"hover":"rest",className:De("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[f.jsxs(ya.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:d,times:[m,h,g,v],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z"}),f.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),f.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),f.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx(FTe,{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z",times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(tF,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(tF,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d})]})]})}),t==="expanded"&&f.jsxs("div",{className:"font-ubuntu flex flex-col items-start -space-y-1 mr-3",children:[f.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),f.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function FTe({d:e,times:t,total:n}){const{T0:a,T1:r,T2:i,T3:s}=t;return f.jsx(ya.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[a,r,i,s],ease:"easeInOut"}}}})}function tF({cx:e,cy:t,r:n,times:a,total:r}){const{T0:i,T1:s,T2:c,T3:u}=a;return f.jsx(ya.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:r,times:[i,s,c,u],ease:"easeInOut"}}}})}function tq({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:a="3s",borderRadius:r="100px",background:i,className:s,children:c,...u}){const{resolvedTheme:d}=_w(),m=d==="dark"?"#000000":"#ffffff",h=d==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,v=i||h;return f.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":r,"--speed":a,"--cut":n,"--bg":v},className:De("group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]","transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px",d==="dark"?"border-black/10 text-black":"border-white/10 text-white",s),ref:e,...u,children:[f.jsx("div",{className:De("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:f.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:f.jsx("div",{className:"animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]"})})}),c,f.jsx("div",{className:De("absolute inset-0 size-full","rounded-2xl px-4 py-1.5 text-sm font-medium","transform-gpu transition-all duration-300 ease-in-out",d==="dark"?"shadow-[inset_0_-8px_10px_#0000001f] group-hover:shadow-[inset_0_-6px_10px_#0000003f] group-active:shadow-[inset_0_-10px_10px_#0000003f]":"shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]")}),f.jsx("div",{className:De("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}tq.displayName="ShimmerButton";function nF({status:e}){const t=i=>{switch(i){case"ready":return{color:"bg-emerald-500",ringColor:"ring-emerald-500",tooltip:"Connected"};case"failed":return{color:"bg-red-500",ringColor:"ring-red-500",tooltip:"Failed"};default:return{color:"bg-yellow-500",ringColor:"ring-yellow-500",tooltip:i}}},{color:n,ringColor:a,tooltip:r}=t(e);return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:`absolute w-2 h-2 rounded-full ${a} animate-ping`}),f.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),f.jsx(Rt,{children:f.jsx("p",{children:r})})]})}function rF({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:a,mobileMode:r=!1}){const i=Rd(),s=c=>{const u=e.find(d=>d.id===c);if(!u||u.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}n(c)};return r?f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(G_,{children:[f.jsx(W_,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5",children:[t?f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md"}):f.jsx(Ahe,{className:"h-5 w-5"}),f.jsx(ac,{className:"h-4 w-4"})]})}),f.jsxs(Rv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(K_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ao,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(nF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ao,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})}):f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(G_,{children:[f.jsx(W_,{asChild:!0,children:f.jsxs(tq,{className:De("min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200",!t&&"pl-4",t&&"pr-10"),children:[t&&f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md",className:"mr-2"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("span",{className:"truncate",children:t?t.name:"Select server to inspect"}),t&&f.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:c=>{c.stopPropagation()},className:"w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors",title:"Click to copy error message","aria-label":"Copy error message to clipboard"})}),f.jsx(Rt,{children:f.jsx("p",{className:"max-w-xs",children:t.error})})]}):f.jsx("div",{className:`w-2 h-2 rounded-full ${t.state==="ready"?"bg-emerald-600 animate-status-pulse":t.state==="failed"?"bg-rose-600 animate-status-pulse-red":"bg-yellow-500 animate-status-pulse-yellow"}`})})]})]})}),t&&f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{type:"button",onClick:()=>{a(t.id)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"Edit connection settings",children:f.jsx(Eu,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Edit connection settings"})})]}),f.jsxs(Rv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(K_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ao,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(nF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ao,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})})}const aF=[{id:"tools",label:"Tools",icon:Wl},{id:"prompts",label:"Prompts",icon:Hp},{id:"resources",label:"Resources",icon:the},{id:"sampling",label:"Sampling",icon:UG},{id:"elicitation",label:"Elicitation",icon:HG},{id:"notifications",label:"Notifications",icon:XN},{id:"chat",label:"Chat",icon:phe}];function iF(e,t){return e==="tools"?t.tools.length:e==="prompts"?t.prompts.length:e==="resources"?t.resources.length:e==="sampling"?t.pendingSamplingRequests?.length||0:e==="elicitation"?t.pendingElicitationRequests?.length||0:e==="notifications"?t.unreadNotificationCount:0}function BTe({collapsed:e,onToggle:t}){return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:t,className:De("shrink-0 p-1.5 rounded-md transition-all duration-500 ease-in-out cursor-pointer","text-muted-foreground hover:text-foreground","hover:bg-zinc-100 dark:hover:bg-zinc-800","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),"aria-label":e?"Expand tabs":"Collapse tabs",type:"button",children:e?f.jsx(MG,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"}):f.jsx(Xy,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"})})}),f.jsx(Rt,{children:f.jsx("p",{children:e?"Expand tabs":"Collapse tabs"})})]})}function HTe({connections:e,selectedServer:t,activeTab:n,onServerSelect:a,onTabChange:r,onCommandPaletteOpen:i,onOpenConnectionOptions:s}){const{tunnelUrl:c}=ic(),u=t&&c,[d,m]=y.useState(!1),[h,g]=y.useState(!1),v=async()=>{if(c)try{await navigator.clipboard.writeText(`${c}/mcp`),m(!0),Xt.success("Tunnel URL copied to clipboard"),setTimeout(()=>m(!1),2e3)}catch{Xt.error("Failed to copy URL")}};return f.jsxs("header",{className:"w-full mx-auto",children:[f.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("div",{className:"flex-1 flex justify-start",children:f.jsx(rF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s,mobileMode:!0})}),f.jsx("div",{className:"flex-shrink-0 flex justify-center",children:f.jsx("div",{className:"scale-150",children:f.jsx(eF,{state:"collapsed"})})}),f.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:f.jsx(J2,{className:"h-4 w-4"})})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(Q2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})]})]}),t&&f.jsx("div",{className:"w-full",children:f.jsx(ak,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ik,{className:"w-full justify-center",children:aF.map(x=>{const S=iF(x.id,t);return f.jsxs(ok,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 flex-1 flex-row gap-2 relative",h&&"pl-2"),children:[S>0&&f.jsx("span",{className:De(n===x.id?"dark:bg-black":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 rounded-full font-medium"),children:S}),f.jsx("span",{className:"sr-only",children:x.label})]},x.id)})})})})]}),f.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[f.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[f.jsx(rF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s}),t&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(ak,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ik,{className:"overflow-x-auto",collapsible:!0,children:aF.map(x=>{const S=iF(x.id,t),w=S>0?`${x.label} (${S})`:x.label;return f.jsx(ok,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",h&&"pl-4"),title:w,children:f.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[x.label,S>0&&f.jsx("span",{className:De(n===x.id?" dark:bg-black ":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-xs px-2 py-0.5 rounded-full font-medium"),children:S})]})})})})}),f.jsx(BTe,{collapsed:h,onToggle:()=>g(!h)})]}),u&&f.jsxs(ZK,{children:[f.jsx(YK,{asChild:!0,children:f.jsxs("button",{className:"flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-500/10 to-pink-500/10 dark:from-purple-500/20 dark:to-pink-500/20 border border-purple-500/30 dark:border-purple-500/40 rounded-full hover:from-purple-500/20 hover:to-pink-500/20 dark:hover:from-purple-500/30 dark:hover:to-pink-500/30 transition-colors cursor-pointer",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),f.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),f.jsx(KC,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),f.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[f.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[c,"/mcp"]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:v,children:d?f.jsx(ra,{className:"size-3.5 text-green-600"}):f.jsx(Lr,{className:"size-3.5"})})]})]}),f.jsxs("div",{children:[f.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),f.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"1."}),f.jsxs("span",{children:["Enable"," ",f.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"2."}),f.jsxs("span",{children:["In"," ",f.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",f.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"3."}),f.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),f.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{children:f.jsx(Q2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})}),f.jsx(Rt,{children:f.jsx("p",{children:"Toggle theme"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:i,children:[f.jsx(Pme,{className:"size-4"}),f.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),f.jsx(Rt,{children:f.jsx("p",{children:"Command Palette"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[f.jsx(J2,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Github"})]})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(eF,{state:"expanded"})]})]})]})}function VTe({children:e}){const t=Rd(),n=Go(),{connections:a,addConnection:r,removeConnection:i,updateConnectionConfig:s,configLoaded:c}=qN(),{selectedServerId:u,setSelectedServerId:d,activeTab:m,setActiveTab:h,navigateToItem:g,setTunnelUrl:v}=ic(),[x,S]=y.useState(!1),[w,E]=y.useState(null),_=aSe();y.useEffect(()=>{const Z=new URLSearchParams(n.search).get("tunnelUrl");v(Z)},[n.search,v]),y.useEffect(()=>{const H=re=>{const j=re.detail.requestId;u&&g(u,"sampling",j)},Z=re=>{const j=re.detail.requestId;u&&g(u,"elicitation",j)},G=re=>{const j=re.detail.toolName;u&&j?g(u,"tools",j):u&&h("tools")};return window.addEventListener("navigate-to-sampling",H),window.addEventListener("navigate-to-elicitation",Z),window.addEventListener("navigate-to-tool-result",G),()=>{window.removeEventListener("navigate-to-sampling",H),window.removeEventListener("navigate-to-elicitation",Z),window.removeEventListener("navigate-to-tool-result",G)}},[u,h,g]);const k=y.useRef(null),C=y.useRef(null),R=y.useRef(null),{isAutoConnecting:I}=rSe({connections:a,addConnection:r,removeConnection:i,configLoaded:c}),A=y.useCallback(H=>{yr.getInstance().capture(new tme({trigger:H})).catch(()=>{}),S(!0)},[]),O=H=>{const Z=a.find(j=>j.id===H);if(!Z||Z.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}d(H);const re=new URLSearchParams(n.search).get("tunnelUrl"),te=re?`/?server=${encodeURIComponent(H)}&tunnelUrl=${encodeURIComponent(re)}`:`/?server=${encodeURIComponent(H)}`;t(te)},M=y.useCallback(H=>{E(H)},[]),P=y.useCallback(H=>{w&&(H.url!==w?(i(w),r(H.url,H.name,H.proxyConfig,H.transportType)):s(w,{name:H.name,proxyConfig:H.proxyConfig,transportType:H.transportType}),E(null),Xt.success("Connection settings updated"))},[w,i,r,s]),B=(H,Z,G)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:H,itemName:Z,serverId:G}),G){const re=a.find(z=>z.id===G);if(console.warn("[Layout] Server lookup:",{serverId:G,serverFound:!!re,serverState:re?.state}),!re||re.state!=="ready"){console.warn("[Layout] Server not ready, showing error"),Xt.error("Server is not connected and cannot be inspected");return}console.warn("[Layout] Calling navigateToItem:",{serverId:G,tab:H,itemName:Z}),g(G,H,Z);const j=new URLSearchParams(n.search).get("tunnelUrl"),V=j?`/?server=${encodeURIComponent(G)}&tunnelUrl=${encodeURIComponent(j)}`:`/?server=${encodeURIComponent(G)}`;console.warn("[Layout] Navigating to:",V),t(V)}else console.warn("[Layout] No serverId, just updating tab to:",H),h(H)},K=a.find(H=>H.id===u),Q=K?K.tools.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.tools.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),ee=K?K.prompts.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.prompts.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),ae=K?K.resources.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.resources.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]);return y.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server"),G=Z?decodeURIComponent(Z):null;G!==u&&d(G)},[n.search,u,d]),y.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server");if(!Z)return;const G=decodeURIComponent(Z),re=a.find(te=>te.id===G);if(!re){const te=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(te)}if(re.state==="failed"){const te=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(te)}},[n.search,t,a]),xK({onCommandPalette:()=>A("keyboard"),onToolsTab:()=>{K&&h("tools")},onPromptsTab:()=>{K&&h("prompts")},onResourcesTab:()=>{K&&h("resources")},onChatTab:()=>{K&&h("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{m==="tools"&&k.current?k.current.focusSearch():m==="prompts"&&C.current?C.current.focusSearch():m==="resources"&&R.current&&R.current.focusSearch()},onBlurSearch:()=>{m==="tools"&&k.current?k.current.blurSearch():m==="prompts"&&C.current?C.current.blurSearch():m==="resources"&&R.current&&R.current.blurSearch()}}),I?f.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(ki,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})}):f.jsx(YN,{children:f.jsxs("div",{className:"h-screen bg-[#f3f3f3] dark:bg-black flex flex-col px-2 py-2 sm:px-4 sm:py-4 gap-2 sm:gap-4",children:[f.jsx(HTe,{connections:a,selectedServer:K,activeTab:m,onServerSelect:O,onTabChange:h,onCommandPaletteOpen:()=>A("button"),onOpenConnectionOptions:M}),f.jsx("main",{className:"flex-1 w-full mx-auto bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 p-0 overflow-auto",children:f.jsx(PTe,{selectedServer:K,activeTab:m,toolsSearchRef:k,promptsSearchRef:C,resourcesSearchRef:R,children:e})}),f.jsx(ISe,{isOpen:x,onOpenChange:S,tools:Q,prompts:ee,resources:ae,savedRequests:_,connections:a,onNavigate:B,onServerSelect:O}),f.jsx(P7,{connection:w&&a.find(H=>H.id===w)||null,open:w!==null,onOpenChange:H=>{H||E(null)},onConnect:P})]})})}function GTe(){const[e,t]=y.useState("processing"),[n,a]=y.useState("");return y.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),yN().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(r=>{console.error("[OAuthCallback] Authorization failed:",r),t("error"),a(r instanceof Error?r.message:String(r))})},[]),e==="processing"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(zs,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),f.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var WTe=(e,t,n,a,r,i,s,c)=>{let u=document.documentElement,d=["light","dark"];function m(v){(Array.isArray(e)?e:[e]).forEach(x=>{let S=x==="class",w=S&&i?r.map(E=>i[E]||E):r;S?(u.classList.remove(...w),u.classList.add(i&&i[v]?i[v]:v)):u.setAttribute(x,v)}),h(v)}function h(v){c&&d.includes(v)&&(u.style.colorScheme=v)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(a)m(a);else try{let v=localStorage.getItem(t)||n,x=s&&v==="system"?g():v;m(x)}catch{}},KTe=y.createContext(void 0),ZTe={setTheme:e=>{},themes:[]},YTe=()=>{var e;return(e=y.useContext(KTe))!=null?e:ZTe};y.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:a,enableColorScheme:r,defaultTheme:i,value:s,themes:c,nonce:u,scriptProps:d})=>{let m=JSON.stringify([n,t,i,e,c,s,a,r]).slice(1,-1);return y.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${WTe.toString()})(${m})`}})});function qTe({...e}){const{theme:t="system"}=YTe();return f.jsx(VG,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function XTe(){return f.jsx(yEe,{children:f.jsx(lme,{children:f.jsxs(nSe,{children:[f.jsx(ole,{basename:"/inspector",children:f.jsxs(Mse,{children:[f.jsx($_,{path:"/oauth/callback",element:f.jsx(GTe,{})}),f.jsx($_,{path:"/",element:f.jsx(VTe,{children:f.jsx(tSe,{})})})]})}),f.jsx(qTe,{position:"top-center"})]})})})}const oF=new URLSearchParams(window.location.search);if(oF.has("code")||oF.has("error"))try{yN()}catch(e){console.error("[inspector] OAuth callback error:",e)}const sF=document.getElementById("root");sF?Goe.createRoot(sF).render(f.jsx(XTe,{})):console.error("[inspector] Root element not found");export{TB as $,IF as A,jF as B,M6 as C,kB as D,Eoe as E,Qb as F,Ce as G,Coe as H,koe as I,Rb as J,YP as K,Eo as L,_oe as M,Toe as N,Ll as O,sv as P,Ot as Q,ce as R,d6 as S,zi as T,yF as U,AJ as V,Db as W,dF as X,Roe as Y,Lne as Z,Be as _,Jn as a,vJ as a0,yN as a1,OJ as a2,kd as b,ry as c,od as d,MT as e,Rne as f,QTe as g,gne as h,Sy as i,sd as j,B5 as k,Cb as l,i_ as m,ov as n,Jf as o,BF as p,zT as q,y as r,Op as s,lu as t,id as u,vi as v,o_ as w,ni as x,P6 as y,VB as z};
|
|
1676
|
+
`),Fe.document.close())}},[x]),Qn=y.useCallback(()=>{W?(ie.current&&ie.current.expand(),Ne.current&&Ne.current.expand(),ne(!1)):(ie.current&&ie.current.collapse(),Ne.current&&Ne.current.collapse(),ne(!0))},[W]),ot=y.useCallback(()=>{s&&(ae(""),Q(!0))},[s]),Ve=y.useCallback(()=>{if(!s)return;const Ee={id:`${Date.now()}-${Math.random()}`,name:ee.trim()||`${s.name} - ${new Date().toLocaleString()}`,toolName:s.name,args:g,savedAt:Date.now(),serverId:s._serverId,serverName:s._serverName};Pe([...P,Ee]),yr.getInstance().capture(new nme({toolName:s.name,serverId:r})).catch(()=>{}),Q(!1),ae("")},[s,ee,g,P,Pe,r]),Le=y.useCallback(Ee=>{Pe(P.filter(je=>je.id!==Ee)),u?.id===Ee&&d(null)},[P,Pe,u]);return z?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[L!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{L==="response"?F("detail"):(c(null),F("list"))},className:"p-0 h-8 w-8",children:f.jsx(Xy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{c(null),F("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),L==="detail"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{F("response")},className:L==="detail"?"text-foreground hover:underline":L==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),L==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(aw,{initial:!1,mode:"popLayout",children:[L==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(q2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:_e,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Y2,{tools:fe,selectedTool:s,onToolSelect:Ae,focusedIndex:te}):f.jsx(H2,{savedRequests:P,selectedRequest:u,onLoadRequest:Me,onDeleteRequest:Le,focusedIndex:te})]},"list"),L==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(W2,{selectedTool:s,toolArgs:g,isExecuting:w,isConnected:i,onArgChange:rt,onExecute:nt,onSave:ot})},"detail"),L==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(Z2,{results:ut,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ct,onDelete:bt,onFullscreen:nn,onTogglePreview:()=>Z(!H)})},"response")]})}),f.jsx(V2,{isOpen:K,requestName:ee,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Ve,onCancel:()=>Q(!1)})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{ref:ie,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(q2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:_e,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Y2,{tools:fe,selectedTool:s,onToolSelect:Ae,focusedIndex:te}):f.jsx(H2,{savedRequests:P,selectedRequest:u,onLoadRequest:Me,onDeleteRequest:Le,focusedIndex:te})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:ye,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>{q(!0)},onExpand:()=>{q(!1)},className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation(),X?(ye.current?.resize(25),q(!1)):(ye.current?.resize(5),q(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),le>0&&f.jsx(Sr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:le}),le>0&&!X&&f.jsx($e,{variant:"ghost",size:"sm",onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation(),Se.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${X?"":"rotate-180"}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${X?"hidden":""}`,children:f.jsx(kD,{serverIds:[r],onCountChange:ue,onClearRef:Se})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{ref:Ne,defaultSize:40,collapsible:!0,children:f.jsx(W2,{selectedTool:s,toolArgs:g,isExecuting:w,isConnected:i,onArgChange:rt,onExecute:nt,onSave:ot,onCancel:()=>{C&&C.abort()}})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{ref:He,defaultSize:60,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(Z2,{results:ut,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ct,onDelete:bt,onFullscreen:nn,onTogglePreview:()=>Z(!H),onMaximize:Qn,isMaximized:W})})})]})}),f.jsx(V2,{isOpen:K,requestName:ee,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Ve,onCancel:()=>Q(!1)})]})}XY.displayName="ToolsTab";function RTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onRejectAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Reject all"})]})})]})}function ATe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.params?.messages?.length||0,d=s.request.params?.maxTokens;return f.jsx(Qs,{id:`sampling-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=r(s.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),d&&h.push(`max ${d} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function ITe({llmConfig:e}){const t=y.useRef(null);return{generateResponse:y.useCallback(async({request:a})=>{if(!e)throw new Error("LLM config is not available");const r=a.params||{},i=r.maxTokens,s=r.temperature;r.modelPreferences;const c=r.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!r,messagesCount:c.length,messages:c,params:r}),c.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:d,AIMessage:m}=await Jn(async()=>{const{HumanMessage:x,AIMessage:S}=await import("./index-CR9w_74S.js").then(w=>w.bI);return{HumanMessage:x,AIMessage:S}},[]);for(const x of c){if(!x||!x.role){console.warn("Skipping invalid message:",x);continue}const S=Array.isArray(x.content)?x.content[0]:x.content;if(!S){console.warn("Skipping message with no content:",x);continue}S.type==="text"&&S.text?x.role==="user"?u.push(new d(S.text)):x.role==="assistant"&&u.push(new m(S.text)):console.warn("Skipping message with unsupported content type:",S)}if(u.length===0)throw new Error("No valid messages could be converted. Please ensure messages have 'text' content type.");if(!t.current||t.current.provider!==e.provider||t.current.model!==e.model||t.current.apiKey!==e.apiKey){let x;const S={model:e.model,apiKey:e.apiKey};if(i!==void 0&&(S.maxTokens=i),s!==void 0?S.temperature=s:e.temperature!==void 0&&(S.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:w}=await Jn(async()=>{const{ChatOpenAI:E}=await import("./index-B5kLR_Rv.js");return{ChatOpenAI:E}},__vite__mapDeps([6,7,8,2,9,10,11]));x=new w(S)}else if(e.provider==="anthropic"){const{ChatAnthropic:w}=await Jn(async()=>{const{ChatAnthropic:E}=await import("./index-sQyTG4jp.js");return{ChatAnthropic:E}},__vite__mapDeps([12,8,7,2,11]));x=new w(S)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:w}=await Jn(async()=>{const{ChatGoogleGenerativeAI:E}=await import("./index-BYR-I2bf.js");return{ChatGoogleGenerativeAI:E}},__vite__mapDeps([13,8,7,2,10]));x=new w(S)}else throw new Error(`Unsupported LLM provider: ${e.provider}`);t.current={instance:x,provider:e.provider,model:e.model,apiKey:e.apiKey}}const h=await t.current.instance.invoke(u);return{role:"assistant",content:{type:"text",text:h.content||h.text||""},model:e.model,stopReason:"endTurn"}},[e]),isAvailable:e!==null}}function OTe({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d,llmConfig:m}){const[h,g]=y.useState("manual"),[v,x]=y.useState("stub-model"),[S,w]=y.useState("endTurn"),[E,_]=y.useState("assistant"),[k,C]=y.useState("text"),[R,I]=y.useState("positive"),[A,O]=y.useState(""),[M,P]=y.useState("image/png"),[B,K]=y.useState(!1),[Q,ee]=y.useState(null),{generateResponse:ae,isAvailable:H}=ITe({llmConfig:m});y.useEffect(()=>{e&&(x("stub-model"),w("endTurn"),_("assistant"),C("text"),I("positive"),O(""),P("image/png"),ee(null))},[e?.id]);const Z=async()=>{if(!(!e||!H)){K(!0),ee(null);try{const j=await ae({request:e.request});x(j.model||m?.model||"stub-model"),w(j.stopReason||"endTurn"),_(j.role||"assistant");const V=Array.isArray(j.content)?j.content[0]:j.content;V.type==="text"?(C("text"),I(V.text||"")):V.type==="image"&&(C("image"),O(V.data||""),P(V.mimeType||"image/png"))}catch(j){const V=j instanceof Error?j.message:"Failed to generate response";ee(V),Xt.error("LLM Generation Failed",{description:V})}finally{K(!1)}}},G=y.useMemo(()=>{const j={model:v,stopReason:S,role:E,content:{type:k}};return k==="text"?j.content.text=R:k==="image"&&(j.content.data=A,j.content.mimeType=M),j},[v,S,E,k,R,A,M]),re=()=>{if(!e)return;const j=uN.safeParse(G);if(!j.success){Xt.error("Invalid response",{description:`Validation failed: ${j.error.message}`});return}t(e.id,j.data),a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(V=>{const z=Xt(V.createElement("div",{className:"space-y-3"},V.createElement("div",null,V.createElement("strong",null,"Sampling Response Sent"),V.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),V.createElement("div",{className:"flex gap-2"},V.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const $=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent($),Xt.dismiss(z)}},"View Tool Result"))),{duration:5e3})})},te=()=>{e&&(n(e.id,"User rejected sampling request"),a())};return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx(Lr,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(eC,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request})})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Kt,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),f.jsxs(Oo,{value:h,onValueChange:j=>g(j),children:[f.jsx(jo,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:f.jsx(Do,{})}),f.jsxs($o,{children:[f.jsx(Ir,{value:"manual",children:"Manual"}),f.jsx(Ir,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&f.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[H?f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx($e,{onClick:Z,disabled:B,size:"sm",className:"flex items-center gap-2",children:B?f.jsxs(f.Fragment,{children:[f.jsx(zs,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):f.jsxs(f.Fragment,{children:[f.jsx($he,{className:"h-4 w-4"}),"Generate with LLM"]})}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),Q&&f.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:Q})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`model-${e.id}`,children:"Model"}),f.jsx(En,{id:`model-${e.id}`,value:v,onChange:j=>x(j.target.value),placeholder:"stub-model",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),f.jsx(En,{id:`stopReason-${e.id}`,value:S,onChange:j=>w(j.target.value),placeholder:"endTurn",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`role-${e.id}`,children:"Role"}),f.jsxs(Oo,{value:E,onValueChange:j=>_(j),disabled:h==="llm"&&B,children:[f.jsx(jo,{id:`role-${e.id}`,children:f.jsx(Do,{})}),f.jsxs($o,{children:[f.jsx(Ir,{value:"assistant",children:"assistant"}),f.jsx(Ir,{value:"user",children:"user"})]})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),f.jsxs(Oo,{value:k,onValueChange:j=>C(j),disabled:h==="llm"&&B,children:[f.jsx(jo,{id:`contentType-${e.id}`,children:f.jsx(Do,{})}),f.jsxs($o,{children:[f.jsx(Ir,{value:"text",children:"text"}),f.jsx(Ir,{value:"image",children:"image"})]})]})]}),k==="text"&&f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`text-${e.id}`,children:"Text Content"}),f.jsx(Xl,{id:`text-${e.id}`,value:R,onChange:j=>I(j.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&B})]}),k==="image"&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),f.jsx(Xl,{id:`imageData-${e.id}`,value:A,onChange:j=>O(j.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),f.jsx(En,{id:`mimeType-${e.id}`,value:M,onChange:j=>P(j.target.value),placeholder:"image/png",disabled:h==="llm"&&B})]})]})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:re,className:"flex-1",disabled:h==="llm"&&B,children:"Approve"}),f.jsx($e,{onClick:te,variant:"outline",className:"flex-1",disabled:h==="llm"&&B,children:"Reject"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}function DTe({pendingRequests:e,onApprove:t,onReject:n,serverId:a,isConnected:r,mcpServerUrl:i}){const{selectedSamplingRequestId:s,setSelectedSamplingRequestId:c}=ic(),{llmConfig:u}=EY({mcpServerUrl:i}),[d,m]=y.useState(null),[h,g]=y.useState(""),[v,x]=y.useState(-1),[S,w]=y.useState(!0),[E,_]=y.useState(!1),[k,C]=y.useState(!0),[R,I]=y.useState(!1),A=y.useRef(null),O=y.useRef(null),M=y.useRef(null),P=y.useRef(!1);y.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:s,pendingRequestsCount:e.length,currentSelectedId:d?.id}),s&&e.length>0){const G=e.find(re=>re.id===s);console.log("[SamplingTab] Found request for auto-selection:",!!G,G?.id),G&&(console.log("[SamplingTab] Auto-selecting request:",G.id),c(null),m(G),setTimeout(()=>{const re=document.getElementById(`sampling-request-${G.id}`);console.log("[SamplingTab] Scrolling to element:",!!re),re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[s,e,c]),y.useEffect(()=>{const G=re=>{const j=re.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",j);const V=e.find(z=>z.id===j);V&&(console.log("[SamplingTab] Selecting request from event:",j),m(V),setTimeout(()=>{const z=document.getElementById(`sampling-request-${j}`);z&&z.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",G),()=>window.removeEventListener("navigate-to-sampling",G)},[e]),y.useEffect(()=>{S&&e.length>0&&A.current&&!P.current&&(A.current.scrollTop=0)},[e.length,S]),y.useEffect(()=>{const G=A.current;if(!G)return;const re=()=>{G.scrollTop>0&&(P.current=!0,w(!1))};return G.addEventListener("scroll",re),()=>G.removeEventListener("scroll",re)},[]),y.useEffect(()=>{e.length===0&&(P.current=!1,w(!0))},[e.length]),y.useEffect(()=>{E&&M.current&&M.current.focus()},[E]);const B=y.useCallback(()=>{h.trim()||_(!1)},[h]),K=y.useMemo(()=>{if(!h.trim())return e;const G=h.toLowerCase();return e.filter(re=>re.serverName.toLowerCase().includes(G)||JSON.stringify(re.request||{}).toLowerCase().includes(G))},[e,h]);y.useEffect(()=>{x(-1)},[h]),y.useEffect(()=>{const G=re=>{const te=re.target;if(te.tagName==="INPUT"||te.tagName==="TEXTAREA"||te.contentEditable==="true"||re.metaKey||re.ctrlKey||re.altKey)return;const V=K;if(re.key==="ArrowDown")re.preventDefault(),x(z=>{const $=z+1;return $>=V.length?0:$});else if(re.key==="ArrowUp")re.preventDefault(),x(z=>{const $=z-1;return $<0?V.length-1:$});else if(re.key==="Enter"&&v>=0){re.preventDefault();const z=K[v];z&&Q(z)}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[v,K]),y.useEffect(()=>{if(v>=0){const G=`sampling-request-${K[v]?.id}`,re=document.getElementById(G);re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})}},[v,K]);const Q=y.useCallback(G=>{m(G)},[]),ee=y.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(G=>{n(G.id,"User rejected all requests")}),m(null))},[e,n]),ae=y.useCallback(async()=>{if(d)try{await navigator.clipboard.writeText(JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)),I(!0),setTimeout(()=>I(!1),2e3)}catch(G){console.error("[SamplingTab] Failed to copy request:",G)}},[d]),H=y.useCallback(()=>{if(d)try{const G=new globalThis.Blob([JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)],{type:"application/json"}),re=URL.createObjectURL(G),te=document.createElement("a");te.href=re,te.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(te),te.click(),document.body.removeChild(te),URL.revokeObjectURL(re)}catch(G){console.error("[SamplingTab] Failed to download request:",G)}},[d]),Z=y.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(G){console.error("[SamplingTab] Failed to toggle fullscreen:",G)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(RTe,{isSearchExpanded:E,searchQuery:h,filteredRequestsCount:K.length,requestsCount:e.length,onSearchExpand:()=>_(!0),onSearchChange:g,onSearchBlur:B,onRejectAll:ee,searchInputRef:M}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(ATe,{requests:K,selectedRequest:d,onRequestSelect:Q,focusedIndex:v,formatRelativeTime:ny,listRef:A})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(OTe,{request:d,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:k,onTogglePreview:()=>C(!k),isCopied:R,onCopy:ae,onDownload:H,onFullscreen:Z,llmConfig:u})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(UG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function jTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onCancelAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),f.jsx(Sr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Cancel all"})]})})]})}function $Te({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.mode||"form",d=u==="form"&&"requestedSchema"in s.request&&s.request.requestedSchema;return f.jsx(Qs,{id:`elicitation-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx(Sr,{variant:"outline",className:u==="url"?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:u})]}),description:(()=>{const m=r(s.timestamp),h=[];d&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function LTe({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d}){const[m,h]=y.useState({}),[g,v]=y.useState(!1),x=e?.request.mode||"form",S=x==="form",w=x==="url";y.useEffect(()=>{if(e&&S&&"requestedSchema"in e.request){const A=e.request.requestedSchema,O={};if(A?.type==="object"&&A.properties)for(const[M,P]of Object.entries(A.properties)){const B=P;B.default!==void 0?O[M]=B.default:B.type==="boolean"?O[M]=!1:B.type==="number"||B.type==="integer"?O[M]=0:O[M]=""}h(O)}v(!1)},[e?.id,S]);const E=(A,O)=>{h(M=>({...M,[A]:O}))},_=()=>{if(e){if(S){if("requestedSchema"in e.request){const A=e.request.requestedSchema;if(A?.required){const O=A.required.filter(M=>m[M]===void 0||m[M]===""||m[M]===null);if(O.length>0){Xt.error("Missing required fields",{description:`Please fill in: ${O.join(", ")}`});return}}}t(e.id,{action:"accept",data:m})}else w&&t(e.id,{action:"accept"});a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(A=>{const O=Xt(A.createElement("div",{className:"space-y-3"},A.createElement("div",null,A.createElement("strong",null,"Elicitation Response Sent"),A.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),A.createElement("div",{className:"flex gap-2"},A.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const M=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(M),Xt.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},k=()=>{e&&(t(e.id,{action:"decline"}),a())},C=()=>{e&&(n(e.id,"User cancelled elicitation request"),a())},R=()=>{e&&w&&"url"in e.request&&(window.open(e.request.url,"_blank"),v(!0))},I=y.useMemo(()=>{if(!e||!S||!("requestedSchema"in e.request))return null;const A=e.request.requestedSchema;if(!A||A.type!=="object"||!A.properties)return f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=A.properties,M=A.required||[];return f.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([P,B])=>{const K=B,Q=M.includes(P),ee=K.type||"string",ae=K.title||P,H=K.description;return f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:`field-${P}`,children:[ae,Q&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),H&&f.jsx("p",{className:"text-xs text-muted-foreground",children:H}),ee==="boolean"?f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx(im,{id:`field-${P}`,checked:m[P]||!1,onCheckedChange:Z=>E(P,Z)}),f.jsx(Kt,{htmlFor:`field-${P}`,className:"text-sm font-normal cursor-pointer",children:K.title||P})]}):ee==="number"||ee==="integer"?f.jsx(En,{id:`field-${P}`,type:"number",value:m[P]||"",onChange:Z=>E(P,ee==="integer"?parseInt(Z.target.value,10):parseFloat(Z.target.value)),placeholder:K.default?.toString()||""}):K.enum?f.jsxs("select",{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:[f.jsx("option",{value:"",children:"Select..."}),K.enum.map(Z=>f.jsx("option",{value:Z,children:Z},Z))]}):ee==="string"&&(K.format==="textarea"||K.maxLength>100)?f.jsx(Xl,{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||"",rows:4}):f.jsx(En,{id:`field-${P}`,type:"text",value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||""})]},P)})})},[e,m,S]);return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx(Sr,{variant:"outline",className:w?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:x}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx(Lr,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(eC,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),f.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),w&&"url"in e.request&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),f.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[f.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),f.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[f.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),f.jsxs($e,{size:"sm",variant:"outline",onClick:R,className:"flex items-center gap-2",children:[f.jsx(q_,{className:"h-4 w-4"}),"Open URL"]})]}),f.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[f.jsx(im,{id:"url-completed",checked:g,onCheckedChange:A=>v(!!A)}),f.jsx(Kt,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),S&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),I]}),S&&"requestedSchema"in e.request&&e.request.requestedSchema&&f.jsxs("details",{className:"space-y-2",children:[f.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request.requestedSchema})})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:_,className:"flex-1",children:"Accept"}),f.jsx($e,{onClick:k,variant:"outline",className:"flex-1",children:"Decline"}),f.jsx($e,{onClick:C,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function MTe({pendingRequests:e=[],onApprove:t,onReject:n,serverId:a,isConnected:r}){const{selectedElicitationRequestId:i,setSelectedElicitationRequestId:s}=ic(),[c,u]=y.useState(null),[d,m]=y.useState(""),[h,g]=y.useState(-1),[v,x]=y.useState(!0),[S,w]=y.useState(!1),[E,_]=y.useState(!0),[k,C]=y.useState(!1),R=y.useRef(null),I=y.useRef(null),A=y.useRef(null),O=y.useRef(!1);y.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:i,pendingRequestsCount:e.length,currentSelectedId:c?.id}),i&&e.length>0){const H=e.find(Z=>Z.id===i);console.log("[ElicitationTab] Found request for auto-selection:",!!H,H?.id),H&&(console.log("[ElicitationTab] Auto-selecting request:",H.id),s(null),u(H),setTimeout(()=>{const Z=document.getElementById(`elicitation-request-${H.id}`);console.log("[ElicitationTab] Scrolling to element:",!!Z),Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,s]),y.useEffect(()=>{const H=Z=>{const re=Z.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",re);const te=e.find(j=>j.id===re);te&&(console.log("[ElicitationTab] Selecting request from event:",re),u(te),setTimeout(()=>{const j=document.getElementById(`elicitation-request-${re}`);j&&j.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",H),()=>window.removeEventListener("navigate-to-elicitation",H)},[e]),y.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),y.useEffect(()=>{const H=R.current;if(!H)return;const Z=()=>{H.scrollTop>0&&(O.current=!0,x(!1))};return H.addEventListener("scroll",Z),()=>H.removeEventListener("scroll",Z)},[]),y.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),y.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=y.useCallback(()=>{d.trim()||w(!1)},[d]),P=y.useMemo(()=>{if(!d.trim())return e;const H=d.toLowerCase();return e.filter(Z=>Z.serverName.toLowerCase().includes(H)||Z.request.message.toLowerCase().includes(H)||JSON.stringify(Z.request||{}).toLowerCase().includes(H))},[e,d]);y.useEffect(()=>{g(-1)},[d]),y.useEffect(()=>{const H=Z=>{const G=Z.target;if(G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.contentEditable==="true"||Z.metaKey||Z.ctrlKey||Z.altKey)return;const te=P;if(Z.key==="ArrowDown")Z.preventDefault(),g(j=>{const V=j+1;return V>=te.length?0:V});else if(Z.key==="ArrowUp")Z.preventDefault(),g(j=>{const V=j-1;return V<0?te.length-1:V});else if(Z.key==="Enter"&&h>=0){Z.preventDefault();const j=P[h];j&&B(j)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,P]),y.useEffect(()=>{if(h>=0){const H=`elicitation-request-${P[h]?.id}`,Z=document.getElementById(H);Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=y.useCallback(H=>{u(H)},[]),K=y.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(H=>{n(H.id,"User cancelled all requests")}),u(null))},[e,n]),Q=y.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(H){console.error("[ElicitationTab] Failed to copy request:",H)}},[c]),ee=y.useCallback(()=>{if(c)try{const H=new globalThis.Blob([JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)],{type:"application/json"}),Z=URL.createObjectURL(H),G=document.createElement("a");G.href=Z,G.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(G),G.click(),document.body.removeChild(G),URL.revokeObjectURL(Z)}catch(H){console.error("[ElicitationTab] Failed to download request:",H)}},[c]),ae=y.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(H){console.error("[ElicitationTab] Failed to toggle fullscreen:",H)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(jTe,{isSearchExpanded:S,searchQuery:d,filteredRequestsCount:P.length,requestsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:M,onCancelAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx($Te,{requests:P,selectedRequest:c,onRequestSelect:B,focusedIndex:h,formatRelativeTime:ny,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(LTe,{request:c,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:E,onTogglePreview:()=>_(!E),isCopied:k,onCopy:Q,onDownload:ee,onFullscreen:ae})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(HG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function PTe({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:a,resourcesSearchRef:r,children:i}){return e?f.jsxs(f.Fragment,{children:[f.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:f.jsx(XY,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:f.jsx(KY,{ref:a,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:f.jsx(YY,{ref:r,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:f.jsx(zke,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),f.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:f.jsx(DTe,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),f.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:f.jsx(MTe,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:f.jsx(vTe,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state==="ready"})}),t!=="tools"&&t!=="prompts"&&t!=="resources"&&t!=="chat"&&t!=="sampling"&&t!=="elicitation"&&t!=="notifications"&&f.jsx(f.Fragment,{children:i})]}):f.jsx(f.Fragment,{children:i})}function J2({className:e}){return f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[f.jsx("path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"}),f.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const JY=y.createContext(void 0);function QY(){const e=y.use(JY);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const eq=y.createContext(void 0);function UTe(){return y.use(eq)}function ak({ref:e,children:t,defaultValue:n,value:a,onValueChange:r,className:i,collapsed:s,onCollapsedChange:c,...u}){const[d,m]=y.useState(n||""),h=a!==void 0,g=s!==void 0,[v,x]=y.useState(!1),S=y.useCallback(k=>{h||m(k),r?.(k)},[h,r]),w=h?a:d,E=g?s:v,_=y.useCallback(k=>{g||x(k),c?.(k)},[g,c]);return f.jsx(JY,{value:{activeValue:w,handleValueChange:S,collapsed:E,handleCollapsedChange:_},children:f.jsx("div",{ref:e,className:De("flex flex-col gap-2",i),...u,children:t})})}ak.displayName="Tabs";function ik({ref:e,children:t,className:n,variant:a="default",collapsible:r=!1,...i}){const{activeValue:s,collapsed:c,handleCollapsedChange:u}=QY(),[d,m]=y.useState({width:0,left:0}),h=y.useRef(null),g=y.useRef(null),v=y.useRef(null),x=y.useCallback(()=>{const E=h.current;if(!E)return;const _=E.querySelector("div:first-child");if(!_)return;const k=_.querySelector(`button[data-tab-value="${s}"]`);if(k&&s){const C=_.getBoundingClientRect(),R=k.getBoundingClientRect();m({width:R.width,left:R.left-C.left})}else m({width:0,left:0})},[s]),S=y.useCallback(()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(x,16)},[x]);y.useEffect(()=>{const E=setTimeout(x,10);return()=>clearTimeout(E)},[x,c]),y.useEffect(()=>{const E=h.current;if(!E)return;g.current=new ResizeObserver(()=>{S()}),g.current.observe(E);const _=E.querySelector("div:first-child");return _&&_.querySelectorAll("button[data-tab-value]").forEach(C=>{g.current&&g.current.observe(C)}),()=>{g.current&&g.current.disconnect(),v.current&&clearTimeout(v.current)}},[S]),y.useEffect(()=>{const E=()=>{S()};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[S]);const w=y.useRef(null);return y.useEffect(()=>{w.current&&(w.current.style.width=`${d.width}px`,w.current.style.left=`${d.left}px`)},[d]),f.jsx(eq,{value:{variant:a,collapsed:c,handleCollapsedChange:u},children:f.jsx("div",{ref:h,className:De("relative flex items-center bg-none gap-1",a==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",a==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...i,children:f.jsxs("div",{role:"tablist",className:"flex-1 flex items-center relative",children:[t,f.jsx("span",{ref:w,className:De("absolute transition-all duration-500 ease-in-out z-0",a==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600",a==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white")})]})})})}ik.displayName="TabsList";const zTe=({children:e,title:t,collapsed:n})=>!t||!n?e:f.jsx(YN,{children:f.jsxs(Nt,{children:[f.jsx(Ct,{children:e}),f.jsx(Rt,{children:t})]})}),ok=y.forwardRef(({children:e,value:t,className:n,disabled:a,icon:r,title:i,...s},c)=>{const{activeValue:u,handleValueChange:d,collapsed:m}=QY(),g=UTe()?.variant||"default",v=u===t,x=m&&i?i:void 0;return f.jsx(zTe,{title:i,collapsed:m,children:f.jsxs("button",{ref:c,disabled:a,onClick:()=>d(t),"data-tab-value":t,"data-tab-active":v,role:"tab","aria-selected":v?"true":"false",title:x,className:De("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-500 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer",g==="default"&&"py-2.5",g==="default"&&"rounded-md px-4",g==="underline"&&"px-6 py-3 border-b-2 border-transparent",v&&"text-foreground",!v&&"text-muted-foreground hover:text-foreground",n),...s,children:[r&&f.jsx(r,{className:De("h-4 w-4 transition-all duration-500 ease-in-out",!m&&"mr-2",m&&"mr-0!")}),f.jsx("span",{className:De("transition-all duration-500 ease-in-out overflow-hidden",m?"w-0 opacity-0":"w-auto opacity-100"),children:e})]})})});ok.displayName="TabsTrigger";function Q2({className:e}){const{theme:t,setTheme:n}=_w(),a=y.useRef(null),[r,i]=y.useState(!1);y.useEffect(()=>{i(!0)},[]);const s=()=>t==="system"?"light":t==="light"?"dark":"system",c=()=>t==="system"?f.jsx(az,{className:"size-4"}):t==="light"?f.jsx(zhe,{className:"size-5"}):f.jsx(yhe,{className:"size-4"}),u=()=>t==="system"?"Switch to light mode":t==="light"?"Switch to dark mode":"Switch to system mode",d=async()=>{if(!a.current)return;const m=s();if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{Od.flushSync(()=>{n(m)})}).ready;const{top:h,left:g,width:v,height:x}=a.current.getBoundingClientRect(),S=h+x/2,w=g+v/2,E=window.innerWidth-g,_=window.innerHeight-h,k=Math.hypot(Math.max(g,E),Math.max(h,_));document.documentElement.animate({clipPath:[`circle(0px at ${w}px ${S}px)`,`circle(${k}px at ${w}px ${S}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(m)};return r?f.jsx("button",{ref:a,onClick:d,className:De(e),"aria-label":u(),title:`Current: ${t==="system"?"Auto":t==="light"?"Light":"Dark"}`,children:c()}):f.jsx("button",{ref:a,className:De(e),"aria-label":"Toggle theme",children:f.jsx(az,{className:"size-4"})})}function eF({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[a,r]=y.useState(!1),i=.2,s=.7,c=.6,u=4,d=i+s+c,m=0,h=i/d,g=(i+s)/d,v=1;return f.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:De("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[f.jsx("div",{className:"relative",children:f.jsxs(ya.svg,{viewBox:"0 0 303 303",initial:"rest",animate:a?"hover":"rest",className:De("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[f.jsxs(ya.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:d,times:[m,h,g,v],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z"}),f.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),f.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),f.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx(FTe,{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z",times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(tF,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(tF,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d})]})]})}),t==="expanded"&&f.jsxs("div",{className:"font-ubuntu flex flex-col items-start -space-y-1 mr-3",children:[f.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),f.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function FTe({d:e,times:t,total:n}){const{T0:a,T1:r,T2:i,T3:s}=t;return f.jsx(ya.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[a,r,i,s],ease:"easeInOut"}}}})}function tF({cx:e,cy:t,r:n,times:a,total:r}){const{T0:i,T1:s,T2:c,T3:u}=a;return f.jsx(ya.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:r,times:[i,s,c,u],ease:"easeInOut"}}}})}function tq({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:a="3s",borderRadius:r="100px",background:i,className:s,children:c,...u}){const{resolvedTheme:d}=_w(),m=d==="dark"?"#000000":"#ffffff",h=d==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,v=i||h;return f.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":r,"--speed":a,"--cut":n,"--bg":v},className:De("group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]","transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px",d==="dark"?"border-black/10 text-black":"border-white/10 text-white",s),ref:e,...u,children:[f.jsx("div",{className:De("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:f.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:f.jsx("div",{className:"animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]"})})}),c,f.jsx("div",{className:De("absolute inset-0 size-full","rounded-2xl px-4 py-1.5 text-sm font-medium","transform-gpu transition-all duration-300 ease-in-out",d==="dark"?"shadow-[inset_0_-8px_10px_#0000001f] group-hover:shadow-[inset_0_-6px_10px_#0000003f] group-active:shadow-[inset_0_-10px_10px_#0000003f]":"shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]")}),f.jsx("div",{className:De("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}tq.displayName="ShimmerButton";function nF({status:e}){const t=i=>{switch(i){case"ready":return{color:"bg-emerald-500",ringColor:"ring-emerald-500",tooltip:"Connected"};case"failed":return{color:"bg-red-500",ringColor:"ring-red-500",tooltip:"Failed"};default:return{color:"bg-yellow-500",ringColor:"ring-yellow-500",tooltip:i}}},{color:n,ringColor:a,tooltip:r}=t(e);return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:`absolute w-2 h-2 rounded-full ${a} animate-ping`}),f.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),f.jsx(Rt,{children:f.jsx("p",{children:r})})]})}function rF({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:a,mobileMode:r=!1}){const i=Rd(),s=c=>{const u=e.find(d=>d.id===c);if(!u||u.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}n(c)};return r?f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(G_,{children:[f.jsx(W_,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5",children:[t?f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md"}):f.jsx(Ahe,{className:"h-5 w-5"}),f.jsx(ac,{className:"h-4 w-4"})]})}),f.jsxs(Rv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(K_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ao,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(nF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ao,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})}):f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(G_,{children:[f.jsx(W_,{asChild:!0,children:f.jsxs(tq,{className:De("min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200",!t&&"pl-4",t&&"pr-10"),children:[t&&f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md",className:"mr-2"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("span",{className:"truncate",children:t?t.name:"Select server to inspect"}),t&&f.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:c=>{c.stopPropagation()},className:"w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors",title:"Click to copy error message","aria-label":"Copy error message to clipboard"})}),f.jsx(Rt,{children:f.jsx("p",{className:"max-w-xs",children:t.error})})]}):f.jsx("div",{className:`w-2 h-2 rounded-full ${t.state==="ready"?"bg-emerald-600 animate-status-pulse":t.state==="failed"?"bg-rose-600 animate-status-pulse-red":"bg-yellow-500 animate-status-pulse-yellow"}`})})]})]})}),t&&f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{type:"button",onClick:()=>{a(t.id)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"Edit connection settings",children:f.jsx(Eu,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Edit connection settings"})})]}),f.jsxs(Rv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(K_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ao,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(nF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ao,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})})}const aF=[{id:"tools",label:"Tools",icon:Wl},{id:"prompts",label:"Prompts",icon:Hp},{id:"resources",label:"Resources",icon:the},{id:"sampling",label:"Sampling",icon:UG},{id:"elicitation",label:"Elicitation",icon:HG},{id:"notifications",label:"Notifications",icon:XN},{id:"chat",label:"Chat",icon:phe}];function iF(e,t){return e==="tools"?t.tools.length:e==="prompts"?t.prompts.length:e==="resources"?t.resources.length:e==="sampling"?t.pendingSamplingRequests?.length||0:e==="elicitation"?t.pendingElicitationRequests?.length||0:e==="notifications"?t.unreadNotificationCount:0}function BTe({collapsed:e,onToggle:t}){return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:t,className:De("shrink-0 p-1.5 rounded-md transition-all duration-500 ease-in-out cursor-pointer","text-muted-foreground hover:text-foreground","hover:bg-zinc-100 dark:hover:bg-zinc-800","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),"aria-label":e?"Expand tabs":"Collapse tabs",type:"button",children:e?f.jsx(MG,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"}):f.jsx(Xy,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"})})}),f.jsx(Rt,{children:f.jsx("p",{children:e?"Expand tabs":"Collapse tabs"})})]})}function HTe({connections:e,selectedServer:t,activeTab:n,onServerSelect:a,onTabChange:r,onCommandPaletteOpen:i,onOpenConnectionOptions:s}){const{tunnelUrl:c}=ic(),u=t&&c,[d,m]=y.useState(!1),[h,g]=y.useState(!1),v=async()=>{if(c)try{await navigator.clipboard.writeText(`${c}/mcp`),m(!0),Xt.success("Tunnel URL copied to clipboard"),setTimeout(()=>m(!1),2e3)}catch{Xt.error("Failed to copy URL")}};return f.jsxs("header",{className:"w-full mx-auto",children:[f.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("div",{className:"flex-1 flex justify-start",children:f.jsx(rF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s,mobileMode:!0})}),f.jsx("div",{className:"flex-shrink-0 flex justify-center",children:f.jsx("div",{className:"scale-150",children:f.jsx(eF,{state:"collapsed"})})}),f.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:f.jsx(J2,{className:"h-4 w-4"})})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(Q2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})]})]}),t&&f.jsx("div",{className:"w-full",children:f.jsx(ak,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ik,{className:"w-full justify-center",children:aF.map(x=>{const S=iF(x.id,t);return f.jsxs(ok,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 flex-1 flex-row gap-2 relative",h&&"pl-2"),children:[S>0&&f.jsx("span",{className:De(n===x.id?"dark:bg-black":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 rounded-full font-medium"),children:S}),f.jsx("span",{className:"sr-only",children:x.label})]},x.id)})})})})]}),f.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[f.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[f.jsx(rF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s}),t&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(ak,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ik,{className:"overflow-x-auto",collapsible:!0,children:aF.map(x=>{const S=iF(x.id,t),w=S>0?`${x.label} (${S})`:x.label;return f.jsx(ok,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",h&&"pl-4"),title:w,children:f.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[x.label,S>0&&f.jsx("span",{className:De(n===x.id?" dark:bg-black ":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-xs px-2 py-0.5 rounded-full font-medium"),children:S})]})})})})}),f.jsx(BTe,{collapsed:h,onToggle:()=>g(!h)})]}),u&&f.jsxs(ZK,{children:[f.jsx(YK,{asChild:!0,children:f.jsxs("button",{className:"flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-500/10 to-pink-500/10 dark:from-purple-500/20 dark:to-pink-500/20 border border-purple-500/30 dark:border-purple-500/40 rounded-full hover:from-purple-500/20 hover:to-pink-500/20 dark:hover:from-purple-500/30 dark:hover:to-pink-500/30 transition-colors cursor-pointer",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),f.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),f.jsx(KC,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),f.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[f.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[c,"/mcp"]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:v,children:d?f.jsx(ra,{className:"size-3.5 text-green-600"}):f.jsx(Lr,{className:"size-3.5"})})]})]}),f.jsxs("div",{children:[f.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),f.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"1."}),f.jsxs("span",{children:["Enable"," ",f.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"2."}),f.jsxs("span",{children:["In"," ",f.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",f.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"3."}),f.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),f.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{children:f.jsx(Q2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})}),f.jsx(Rt,{children:f.jsx("p",{children:"Toggle theme"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:i,children:[f.jsx(Pme,{className:"size-4"}),f.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),f.jsx(Rt,{children:f.jsx("p",{children:"Command Palette"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[f.jsx(J2,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Github"})]})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(eF,{state:"expanded"})]})]})]})}function VTe({children:e}){const t=Rd(),n=Go(),{connections:a,addConnection:r,removeConnection:i,updateConnectionConfig:s,configLoaded:c}=qN(),{selectedServerId:u,setSelectedServerId:d,activeTab:m,setActiveTab:h,navigateToItem:g,setTunnelUrl:v}=ic(),[x,S]=y.useState(!1),[w,E]=y.useState(null),_=aSe();y.useEffect(()=>{const Z=new URLSearchParams(n.search).get("tunnelUrl");v(Z)},[n.search,v]),y.useEffect(()=>{const H=re=>{const j=re.detail.requestId;u&&g(u,"sampling",j)},Z=re=>{const j=re.detail.requestId;u&&g(u,"elicitation",j)},G=re=>{const j=re.detail.toolName;u&&j?g(u,"tools",j):u&&h("tools")};return window.addEventListener("navigate-to-sampling",H),window.addEventListener("navigate-to-elicitation",Z),window.addEventListener("navigate-to-tool-result",G),()=>{window.removeEventListener("navigate-to-sampling",H),window.removeEventListener("navigate-to-elicitation",Z),window.removeEventListener("navigate-to-tool-result",G)}},[u,h,g]);const k=y.useRef(null),C=y.useRef(null),R=y.useRef(null),{isAutoConnecting:I}=rSe({connections:a,addConnection:r,removeConnection:i,configLoaded:c}),A=y.useCallback(H=>{yr.getInstance().capture(new tme({trigger:H})).catch(()=>{}),S(!0)},[]),O=H=>{const Z=a.find(j=>j.id===H);if(!Z||Z.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}d(H);const re=new URLSearchParams(n.search).get("tunnelUrl"),te=re?`/?server=${encodeURIComponent(H)}&tunnelUrl=${encodeURIComponent(re)}`:`/?server=${encodeURIComponent(H)}`;t(te)},M=y.useCallback(H=>{E(H)},[]),P=y.useCallback(H=>{w&&(H.url!==w?(i(w),r(H.url,H.name,H.proxyConfig,H.transportType)):s(w,{name:H.name,proxyConfig:H.proxyConfig,transportType:H.transportType}),E(null),Xt.success("Connection settings updated"))},[w,i,r,s]),B=(H,Z,G)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:H,itemName:Z,serverId:G}),G){const re=a.find(z=>z.id===G);if(console.warn("[Layout] Server lookup:",{serverId:G,serverFound:!!re,serverState:re?.state}),!re||re.state!=="ready"){console.warn("[Layout] Server not ready, showing error"),Xt.error("Server is not connected and cannot be inspected");return}console.warn("[Layout] Calling navigateToItem:",{serverId:G,tab:H,itemName:Z}),g(G,H,Z);const j=new URLSearchParams(n.search).get("tunnelUrl"),V=j?`/?server=${encodeURIComponent(G)}&tunnelUrl=${encodeURIComponent(j)}`:`/?server=${encodeURIComponent(G)}`;console.warn("[Layout] Navigating to:",V),t(V)}else console.warn("[Layout] No serverId, just updating tab to:",H),h(H)},K=a.find(H=>H.id===u),Q=K?K.tools.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.tools.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),ee=K?K.prompts.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.prompts.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),ae=K?K.resources.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.resources.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]);return y.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server"),G=Z?decodeURIComponent(Z):null;G!==u&&d(G)},[n.search,u,d]),y.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server");if(!Z)return;const G=decodeURIComponent(Z),re=a.find(te=>te.id===G);if(!re){const te=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(te)}if(re.state==="failed"){const te=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(te)}},[n.search,t,a]),xK({onCommandPalette:()=>A("keyboard"),onToolsTab:()=>{K&&h("tools")},onPromptsTab:()=>{K&&h("prompts")},onResourcesTab:()=>{K&&h("resources")},onChatTab:()=>{K&&h("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{m==="tools"&&k.current?k.current.focusSearch():m==="prompts"&&C.current?C.current.focusSearch():m==="resources"&&R.current&&R.current.focusSearch()},onBlurSearch:()=>{m==="tools"&&k.current?k.current.blurSearch():m==="prompts"&&C.current?C.current.blurSearch():m==="resources"&&R.current&&R.current.blurSearch()}}),I?f.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(ki,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})}):f.jsx(YN,{children:f.jsxs("div",{className:"h-screen bg-[#f3f3f3] dark:bg-black flex flex-col px-2 py-2 sm:px-4 sm:py-4 gap-2 sm:gap-4",children:[f.jsx(HTe,{connections:a,selectedServer:K,activeTab:m,onServerSelect:O,onTabChange:h,onCommandPaletteOpen:()=>A("button"),onOpenConnectionOptions:M}),f.jsx("main",{className:"flex-1 w-full mx-auto bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 p-0 overflow-auto",children:f.jsx(PTe,{selectedServer:K,activeTab:m,toolsSearchRef:k,promptsSearchRef:C,resourcesSearchRef:R,children:e})}),f.jsx(ISe,{isOpen:x,onOpenChange:S,tools:Q,prompts:ee,resources:ae,savedRequests:_,connections:a,onNavigate:B,onServerSelect:O}),f.jsx(P7,{connection:w&&a.find(H=>H.id===w)||null,open:w!==null,onOpenChange:H=>{H||E(null)},onConnect:P})]})})}function GTe(){const[e,t]=y.useState("processing"),[n,a]=y.useState("");return y.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),yN().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(r=>{console.error("[OAuthCallback] Authorization failed:",r),t("error"),a(r instanceof Error?r.message:String(r))})},[]),e==="processing"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(zs,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),f.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var WTe=(e,t,n,a,r,i,s,c)=>{let u=document.documentElement,d=["light","dark"];function m(v){(Array.isArray(e)?e:[e]).forEach(x=>{let S=x==="class",w=S&&i?r.map(E=>i[E]||E):r;S?(u.classList.remove(...w),u.classList.add(i&&i[v]?i[v]:v)):u.setAttribute(x,v)}),h(v)}function h(v){c&&d.includes(v)&&(u.style.colorScheme=v)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(a)m(a);else try{let v=localStorage.getItem(t)||n,x=s&&v==="system"?g():v;m(x)}catch{}},KTe=y.createContext(void 0),ZTe={setTheme:e=>{},themes:[]},YTe=()=>{var e;return(e=y.useContext(KTe))!=null?e:ZTe};y.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:a,enableColorScheme:r,defaultTheme:i,value:s,themes:c,nonce:u,scriptProps:d})=>{let m=JSON.stringify([n,t,i,e,c,s,a,r]).slice(1,-1);return y.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${WTe.toString()})(${m})`}})});function qTe({...e}){const{theme:t="system"}=YTe();return f.jsx(VG,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function XTe(){return f.jsx(yEe,{children:f.jsx(lme,{children:f.jsxs(nSe,{children:[f.jsx(ole,{basename:"/inspector",children:f.jsxs(Mse,{children:[f.jsx($_,{path:"/oauth/callback",element:f.jsx(GTe,{})}),f.jsx($_,{path:"/",element:f.jsx(VTe,{children:f.jsx(tSe,{})})})]})}),f.jsx(qTe,{position:"top-center"})]})})})}const oF=new URLSearchParams(window.location.search);if(oF.has("code")||oF.has("error"))try{yN()}catch(e){console.error("[inspector] OAuth callback error:",e)}const sF=document.getElementById("root");sF?Goe.createRoot(sF).render(f.jsx(XTe,{})):console.error("[inspector] Root element not found");export{TB as $,IF as A,jF as B,M6 as C,kB as D,Eoe as E,Qb as F,Ce as G,Coe as H,koe as I,Rb as J,YP as K,Eo as L,_oe as M,Toe as N,Ll as O,sv as P,Ot as Q,ce as R,d6 as S,zi as T,yF as U,AJ as V,Db as W,dF as X,Roe as Y,Lne as Z,Be as _,Jn as a,vJ as a0,yN as a1,OJ as a2,kd as b,ry as c,od as d,MT as e,Rne as f,QTe as g,gne as h,Sy as i,sd as j,B5 as k,Cb as l,i_ as m,ov as n,Jf as o,BF as p,zT as q,y as r,Op as s,lu as t,id as u,vi as v,o_ as w,ni as x,P6 as y,VB as z};
|