@mcp-use/inspector 20.2.5-canary.1 → 20.2.5
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/dist/app/inspector.js.gz +0 -0
- package/dist/cli.js +1 -1
- package/dist/client/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/package.json +6 -5
package/dist/app/inspector.js.gz
CHANGED
|
Binary file
|
package/dist/cli.js
CHANGED
|
@@ -5,7 +5,7 @@ ${n.join(`\r
|
|
|
5
5
|
\r
|
|
6
6
|
`)},Bo=e=>{let t=e.socket.encrypted?"https":"http",r=new URL(e.url??"/",`${t}://${e.headers.host??"localhost"}`),n=new Headers;for(let o in e.headers){let s=e.headers[o];s&&n.append(o,Array.isArray(s)?s[0]:s)}return new Request(r,{headers:n})},Ho=e=>{let{server:t,fetchCallback:r,wss:n}=e,o=new Map;n.on("connection",(a,c)=>{let l=o.get(c);l&&(l.resolve(a),o.delete(c))});let s=a=>{let c=o.get(a);c&&(o.delete(a),c.reject(new Error("WebSocket handshake aborted")))},i=(a,c)=>new Promise((l,u)=>{o.set(a,{resolve:l,reject:u,connectionSymbol:c})});t.on("upgrade",async(a,c,l)=>{if(a.headers.upgrade?.toLowerCase()!=="websocket")return;let u={incoming:a,outgoing:void 0,wss:n,[ur]:i},d=400,p;try{let y=await r(Bo(a),u);y instanceof Response&&(d=y.status,p=y.headers)}catch{t.listenerCount("upgrade")===1&&Jt(c,500);return}let m=o.get(a);if(!m||m.connectionSymbol!==u[lr]){s(a),t.listenerCount("upgrade")===1&&Jt(c,d,p);return}let g=y=>{dr(y,p)},h=()=>s(a);c.once("close",h),n.on("headers",g);try{n.handleUpgrade(a,c,l,y=>{c.off("close",h),n.emit("connection",y,a)})}finally{n.off("headers",g)}}),t.on("close",()=>{n.close()})},Hi=Wt(async(e,t,r)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=e.env,o=n[ur];if(!o||!n.incoming)return new Response(null,{status:500});let s=Uo();return n[lr]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,p)=>{a.push([d,p])};i.on("message",c);let l={binaryType:"arraybuffer",close(d,p){i.close(d,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,p){i.send(d,{compress:p?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),l)}catch(d){(r?.onError??console.error)(d)}let u=(d,p)=>{let m=Array.isArray(d)?d:[d];for(let g of m)try{t?.onMessage?.(new MessageEvent("message",{data:p?g instanceof ArrayBuffer?g:g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength):typeof g=="string"?g:Buffer.from(g).toString("utf-8")}),l)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let d of a)u(...d);i.on("message",(d,p)=>{u(d,p)}),i.on("close",(d,p)=>{try{t?.onClose?.(new Do("close",{code:d,reason:p.toString()}),l)}catch(m){(r?.onError??console.error)(m)}}),i.on("error",d=>{try{t?.onError?.(new No("error",{error:d}),l)}catch(p){(r?.onError??console.error)(p)}})})(),new Response}),$o=e=>{let t=e.fetch,r=Io(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),n=(e.createServer||ro)(e.serverOptions||{},r);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw new Error("WebSocket server must be created with { noServer: true } option");Ho({server:n,fetchCallback:t,wss:e.websocket.server})}return n},fr=(e,t)=>{let r=$o(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var nt=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var pr=Symbol();var hr=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Oe=e=>"headers"in e,gr=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(Oe(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?Fo(e,{all:r,dot:n}):{}};async function Fo(e,t){if(!Oe(e)&&e.bodyCache.formData)return mr(await e.bodyCache.formData,t);let r=Oe(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=hr(n,r.get("Content-Type")||"");Oe(e)||(e.bodyCache.formData=o);let s=await o;return s?mr(s,t):{}}function mr(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?Wo(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(zo(r,n,o),delete r[n])}),r}var Wo=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},zo=(e,t,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var st=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},yr=e=>{let{groups:t,path:r}=qo(e),n=st(r);return Ko(n,t)},qo=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Ko=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},Te={},wr=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Te[n]||(r[2]?Te[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Te[n]=[e,r[1],!0]),Te[n]}return null},Le=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Vo=e=>Le(e,decodeURI),it=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return Vo(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var br=e=>{let t=it(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},K=(e,t,...r)=>(r.length&&(t=K(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ke=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ot=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?Le(e,at):e):e,vr=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return ot(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(n=/[%+]/.test(e),!n)return}let o=Object.create(null);n??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let i=e.indexOf("&",s+1),a=e.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=e.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ot(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=ot(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},xr=vr,Er=(e,t)=>vr(e,t,!0),at=decodeURIComponent;var Sr=e=>Le(e,at),Rr=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Sr(r):r}#s(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Sr(n):n)}return e}#o(e){return this.#t[1]?this.#t[1][e]:e}query(e){return xr(this.url,e)}queries(e){return Er(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return gr(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let o=Object.keys(t)[0];return o?t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[pr](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};var Pr={Stringify:1,BeforeStream:2,Stream:3},Go=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var ct=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>ct(c,t,!1,n,o))).then(()=>o[0]));return r?Go(await i,s):i};var Yo="text/plain; charset=UTF-8",lt=(e,t)=>({"Content-Type":e,...t}),me=(e,t)=>new Response(e,t),ut=class{#e;#t;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#e=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new Rr(this.#e,this.#f,this.#d),this.#t}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=me(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=me(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#n=me(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let s=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof t=="number"?t:t?.status??this.#s;return me(e,{status:o,headers:n})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,lt(Yo,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,lt("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,lt("text/html; charset=UTF-8",r));return typeof e=="object"?ct(e,Pr.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>me(),this.#l(this))};var x="ALL",Ar="all",Cr=["get","post","put","delete","options","patch"],Me="Can not add a route since the matcher is already built.",Ie=class extends Error{};var _r="__COMPOSED_HANDLER";var Xo=e=>e.text("404 Not Found",404),Or=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Tr=class Lr{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Cr,Ar].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#e=i:this.#s(s,this.#e,i),a.forEach(c=>{this.#s(s,this.#e,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#e=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#e,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#e=s:(this.#e="*",i.unshift(s)),i.forEach(a=>{this.#s(x,this.#e,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??it:br}#t(){let t=new Lr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Xo;errorHandler=Or;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Or?s=o.handler:(s=async(i,a)=>(await nt([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[_r]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=K(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=K(this._basePath,t),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(x,K(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=K(this._basePath,r);let s={basePath:o!==void 0?K(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new ut(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=nt(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${K("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var De=[];function dt(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[x],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],De];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var Ne="[^/]+",ge=".*",ye="(?:|/.*)",J=Symbol(),Jo=new Set(".\\+*[^]$()");function Qo(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===ge||e===ye?1:t===ge||t===ye?-1:e===Ne?1:t===Ne?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var kr=class ft{#e;#t;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#e!==void 0)throw J;if(s)return;this.#e=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",ge]:["","",Ne]:i==="/*"?["","",ye]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||Ne;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw J;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(p=>p!==ge&&p!==ye))throw J;if(s)return;l=this.#r[d]=new ft,u!==""&&(l.#t=o.varIndex++)}!s&&u!==""&&n.push([u,l.#t])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==ge&&u!==ye))throw J;if(s)return;l=this.#r[i]=new ft}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Qo).map(n=>{let o=this.#r[n];return(typeof o.#t=="number"?`(${n})@${o.#t}`:Jo.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Mr=class{#e={varIndex:0};#t=new kr;insert(e,t,r){let n=[],o=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#t.insert(s,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var Zo=[/^$/,[],Object.create(null)],Ir=Object.create(null);function Dr(e){return Ir[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function es(){Ir=Object.create(null)}function ts(e){let t=new Mr,r=[];if(e.length===0)return Zo;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,p])=>l?1:d?-1:u.length-p.length),o=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[p,m,g]=n[l];p?o[m]=[g.map(([y])=>[y,Object.create(null)]),De]:u++;let h;try{h=t.insert(m,u,p)}catch(y){throw y===J?new Ie(m):y}p||(r[u]=g.map(([y,f])=>{let w=Object.create(null);for(f-=1;f>=0;f--){let[v,L]=h[f];w[v]=L}return[y,w]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,p=r[l].length;d<p;d++){let m=r[l][d]?.[1];if(!m)continue;let g=Object.keys(m);for(let h=0,y=g.length;h<y;h++)m[g[h]]=a[m[g[h]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function se(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(Dr(r).test(t))return[...e[r]]}}var Ue=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[x]:Object.create(null)},this.#t={[x]:Object.create(null)}}add(e,t,r){let n=this.#e,o=this.#t;if(!n||!o)throw new Error(Me);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[x]).forEach(c=>{a[e][c]=[...a[x][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Dr(t);e===x?Object.keys(n).forEach(c=>{n[c][t]||=se(n[c],t)||se(n[x],t)||[]}):n[e][t]||=se(n[e],t)||se(n[x],t)||[],Object.keys(n).forEach(c=>{(e===x||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===x||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=ke(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===x||e===u)&&(o[u][l]||=[...se(n[u],l)||se(n[x],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=dt;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t)}),this.#e=this.#t=void 0,es(),e}#r(e){let t=[],r=e===x;return[this.#e,this.#t].forEach(n=>{let o=n[e]?Object.keys(n[e]).map(s=>[s,n[e][s]]):[];o.length!==0?(r||=!0,t.push(...o)):e!==x&&t.push(...Object.keys(n[x]).map(s=>[s,n[x][s]]))}),r?ts(t):null}};var pt=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(Me);this.#t.push([e,t,r])}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof Ie)continue;throw c}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var we=Object.create(null),rs=e=>{for(let t in e)return!0;return!1},Nr=class Ur{#e;#t;#r;#s=0;#o=we;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#e=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=yr(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],d=wr(l,u),p=Array.isArray(d)?d[0]:l;if(p in o.#t){o=o.#t[p],d&&i.push(d[1]);continue}o.#t[p]=new Ur,d&&(o.#r.push(d),i.push(d[1])),o=o.#t[p]}return o.#e.push({[t]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(t,r,n,o,s){for(let i=0,a=r.#e.length;i<a;i++){let c=r.#e[i],l=c[n]||c[x],u={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),o!==we||s&&s!==we))for(let d=0,p=l.possibleKeys.length;d<p;d++){let m=l.possibleKeys[d],g=u[l.score];l.params[m]=s?.[m]&&!g?s[m]:o[m]??s?.[m],u[l.score]=!0}}}search(t,r){let n=[];this.#o=we;let s=[this],i=st(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],p=u===c-1,m=[];for(let h=0,y=s.length;h<y;h++){let f=s[h],w=f.#t[d];w&&(w.#o=f.#o,p?(w.#t["*"]&&this.#n(n,w.#t["*"],t,f.#o),this.#n(n,w,t,f.#o)):m.push(w));for(let v=0,L=f.#r.length;v<L;v++){let k=f.#r[v],S=f.#o===we?{}:{...f.#o};if(k==="*"){let R=f.#t["*"];R&&(this.#n(n,R,t,f.#o),R.#o=S,m.push(R));continue}let[P,A,E]=k;if(!d&&!(E instanceof RegExp))continue;let b=f.#t[P];if(E instanceof RegExp){if(l===null){l=new Array(c);let G=r[0]==="/"?1:0;for(let Y=0;Y<c;Y++)l[Y]=G,G+=i[Y].length+1}let R=r.substring(l[u]),T=E.exec(R);if(T){if(S[A]=T[0],this.#n(n,b,t,f.#o,S),T[0].length===R.length&&b.#t["*"]&&this.#n(n,b.#t["*"],t,f.#o,S),rs(b.#t)){b.#o=S;let G=T[0].match(/\//)?.length??0;(a[G]||=[]).push(b)}continue}}(E===!0||E.test(d))&&(S[A]=d,p?(this.#n(n,b,t,S,f.#o),b.#t["*"]&&this.#n(n,b.#t["*"],t,S,f.#o)):(b.#o=S,m.push(b)))}}let g=a.shift();s=g?m.concat(g):m}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var ht=class{name="TrieRouter";#e;constructor(){this.#e=new Nr}add(e,t,r){let n=ke(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#e.insert(e,n[o],r);return}this.#e.insert(e,t,r)}match(e,t){return this.#e.search(e,t)}};var mt=class extends Tr{constructor(e={}){super(e),this.router=e.router??new pt({routers:[new Ue,new ht]})}};var je=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...e},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(t.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(t.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),t.credentials&&a("Access-Control-Allow-Credentials","true"),t.exposeHeaders?.length&&a("Access-Control-Expose-Headers",t.exposeHeaders.join(",")),s.req.method==="OPTIONS"){t.origin!=="*"&&a("Vary","Origin"),t.maxAge!=null&&a("Access-Control-Max-Age",t.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=t.allowHeaders;if(!u?.length){let d=s.req.header("Access-Control-Request-Headers");d&&(u=d.split(",").map(p=>p.trim()))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),t.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};import en from"process";import tn from"path";import{fileURLToPath as Is}from"url";import Ds from"child_process";import Ns,{constants as Us}from"fs/promises";import{promisify as ps}from"util";import hs from"child_process";import vt,{constants as zr}from"fs/promises";import Hr from"process";import as from"os";import cs from"fs";import ss from"fs";import jr from"fs";var gt;function ns(){try{return jr.statSync("/.dockerenv"),!0}catch{return!1}}function os(){try{return jr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function yt(){return gt===void 0&&(gt=ns()||os()),gt}var wt,is=()=>{try{return ss.statSync("/run/.containerenv"),!0}catch{return!1}};function ie(){return wt===void 0&&(wt=is()||yt()),wt}var Br=()=>{if(Hr.platform!=="linux")return!1;if(as.release().toLowerCase().includes("microsoft"))return!ie();try{return cs.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!ie():!1}catch{return!1}},H=Hr.env.__IS_WSL_TEST__?Br:Br();import $r from"process";import{Buffer as ls}from"buffer";import{promisify as us}from"util";import ds from"child_process";import Lc,{constants as kc}from"fs/promises";var fs=us(ds.execFile),bt=()=>`${$r.env.SYSTEMROOT||$r.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var O=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=O.encodeCommand(e);return fs(r??bt(),[...O.argumentsPrefix,o],{encoding:"utf8",...n})};O.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];O.encodeCommand=e=>ls.from(e,"utf16le").toString("base64");O.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Fr(e){for(let t of e.split(`
|
|
7
7
|
`)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var ms=ps(hs.execFile),gs=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await vt.access(r,zr.F_OK),n=!0}catch{}if(!n)return e;let o=await vt.readFile(r,{encoding:"utf8"}),s=Fr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),ys=async()=>`${await gs()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Be=H?ys:bt,Wr,qr=async()=>(Wr??=(async()=>{try{let e=await Be();return await vt.access(e,zr.X_OK),!0}catch{return!1}})(),Wr),Kr=async()=>{let e=await Be(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await O(t,{powerShellPath:e});return r.trim()},Vr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await ms("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function Q(e,t,r){let n=o=>Object.defineProperty(e,t,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let o=r();return n(o),o},set(o){n(o)}}),e}import{promisify as Os}from"util";import At from"process";import{execFile as Ts}from"child_process";import{promisify as ws}from"util";import bs from"process";import{execFile as vs}from"child_process";var xs=ws(vs);async function xt(){if(bs.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await xs("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}import Es from"process";import{promisify as Ss}from"util";import{execFile as Rs,execFileSync as Jc}from"child_process";var Ps=Ss(Rs);async function Gr(e,{humanReadableOutput:t=!0,signal:r}={}){if(Es.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Ps("osascript",["-e",e,n],o);return s.trim()}async function Et(e){return Gr(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
8
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as As}from"util";import{execFile as Cs}from"child_process";var _s=As(Cs),He={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Rt=new Map(Object.entries(He)),St=class extends Error{};async function Pt(e=_s){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new St(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return He[n]??He[i]??He[a]??{name:n,id:n}}var Ls=Os(Ts),ks=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function Ct(){if(At.platform==="darwin"){let e=await xt();return{name:await Et(e),id:e}}if(At.platform==="linux"){let{stdout:e}=await Ls("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:ks(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(At.platform==="win32")return Pt();throw new Error("Only macOS, Linux, and Windows are supported")}import _t from"process";var Ms=!!(_t.env.SSH_CONNECTION||_t.env.SSH_CLIENT||_t.env.SSH_TTY),Yr=Ms;var $e=Symbol("fallbackAttempt"),Ot=import.meta.url?tn.dirname(Is(import.meta.url)):"",Xr=tn.join(Ot,"xdg-open"),{platform:ae,arch:Jr}=en,Qr=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Fe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[$e]===!0;if(delete e[$e],Array.isArray(e.app))return Qr(e.app,l=>Fe({...e,app:l,[$e]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return Qr(r,l=>Fe({...e,app:{name:l,arguments:n},[$e]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(H){let p=await Kr();d=Rt.get(p)??{}}else d=await Ct();if(d.id in l){let p=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(p==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[p])}return Fe({...e,app:{name:ce[p],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(H&&!ie()&&!Yr&&!r&&(a=await qr()),ae==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(ae==="win32"||a){o=await Be(),s.push(...O.argumentsPrefix),H||(i.windowsVerbatimArguments=!0),H&&e.target&&(e.target=await Vr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(O.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(O.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>O.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=O.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Ot||Ot==="/",u=!1;try{await Ns.access(Xr,Us.X_OK),u=!0}catch{}o=en.versions.electron??(ae==="android"||l||!u)?"xdg-open":Xr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}ae==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Ds.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},js=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Fe({...t,target:e})};function Zr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[Jr]:t}=e;if(!t)throw new Error(`${Jr} is not supported`);return t}function be({[ae]:e},{wsl:t}={}){if(t&&H)return Zr(t);if(!e)throw new Error(`${ae} is not supported`);return Zr(e)}var ce={browser:"browser",browserPrivate:"browserPrivate"};Q(ce,"chrome",()=>be({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Q(ce,"brave",()=>be({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Q(ce,"firefox",()=>be({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Q(ce,"edge",()=>be({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Q(ce,"safari",()=>be({darwin:"Safari"}));var rn=js;function nn(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as gn,readFileSync as Ws}from"fs";import F from"path";import{fileURLToPath as zs}from"url";import{gunzipSync as qs}from"zlib";var $=eo(mn(),1);function le(e,t){return e.header("Retry-After",String($s(t))),e.json({error:"Too Many Requests"},429)}function $s(e){return e&&typeof e=="object"&&"msBeforeNext"in e&&typeof e.msBeforeNext=="number"&&Number.isFinite(e.msBeforeNext)?Math.max(1,Math.ceil(e.msBeforeNext/1e3)):60}var Ks={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Vs(){let e=F.dirname(zs(import.meta.url));for(let t of[F.resolve(e,"app"),F.resolve(e,"../app"),F.resolve(e,"../../dist/app")])if(gn(F.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function yn(e,t="/inspector/assets"){let r=Vs(),n=new Map,o=new $.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return le(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=F.resolve(r,l),d=r.endsWith(F.sep)?r:`${r}${F.sep}`;if(!u.startsWith(d)||!gn(u))return i.notFound();let p=F.extname(c),m=l.endsWith(".gz"),g=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),h=Ws(u),y=m&&!g?n.get(u)??Gs(n,u,h):h,f=y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength);return i.body(f,200,{"Content-Type":Ks[p]??"application/octet-stream",...m&&g?{"Content-Encoding":"gzip"}:{},...m?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Gs(e,t,r){let n=qs(r);return e.set(t,n),n}var wn={name:"@mcp-use/inspector",type:"module",version:"20.2.5-canary.1",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"},"./client/styles.css":{default:"./dist/client/styles.css"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.7 || ^2.0.8-canary.0","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"^2.2.5-canary.0",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34",jsdom:"^27.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var Xs=wn.version;function We(){return Xs}var Js=`<!doctype html>
|
|
8
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as As}from"util";import{execFile as Cs}from"child_process";var _s=As(Cs),He={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Rt=new Map(Object.entries(He)),St=class extends Error{};async function Pt(e=_s){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new St(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return He[n]??He[i]??He[a]??{name:n,id:n}}var Ls=Os(Ts),ks=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function Ct(){if(At.platform==="darwin"){let e=await xt();return{name:await Et(e),id:e}}if(At.platform==="linux"){let{stdout:e}=await Ls("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:ks(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(At.platform==="win32")return Pt();throw new Error("Only macOS, Linux, and Windows are supported")}import _t from"process";var Ms=!!(_t.env.SSH_CONNECTION||_t.env.SSH_CLIENT||_t.env.SSH_TTY),Yr=Ms;var $e=Symbol("fallbackAttempt"),Ot=import.meta.url?tn.dirname(Is(import.meta.url)):"",Xr=tn.join(Ot,"xdg-open"),{platform:ae,arch:Jr}=en,Qr=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Fe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[$e]===!0;if(delete e[$e],Array.isArray(e.app))return Qr(e.app,l=>Fe({...e,app:l,[$e]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return Qr(r,l=>Fe({...e,app:{name:l,arguments:n},[$e]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(H){let p=await Kr();d=Rt.get(p)??{}}else d=await Ct();if(d.id in l){let p=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(p==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[p])}return Fe({...e,app:{name:ce[p],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(H&&!ie()&&!Yr&&!r&&(a=await qr()),ae==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(ae==="win32"||a){o=await Be(),s.push(...O.argumentsPrefix),H||(i.windowsVerbatimArguments=!0),H&&e.target&&(e.target=await Vr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(O.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(O.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>O.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=O.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Ot||Ot==="/",u=!1;try{await Ns.access(Xr,Us.X_OK),u=!0}catch{}o=en.versions.electron??(ae==="android"||l||!u)?"xdg-open":Xr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}ae==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Ds.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},js=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Fe({...t,target:e})};function Zr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[Jr]:t}=e;if(!t)throw new Error(`${Jr} is not supported`);return t}function be({[ae]:e},{wsl:t}={}){if(t&&H)return Zr(t);if(!e)throw new Error(`${ae} is not supported`);return Zr(e)}var ce={browser:"browser",browserPrivate:"browserPrivate"};Q(ce,"chrome",()=>be({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Q(ce,"brave",()=>be({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Q(ce,"firefox",()=>be({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Q(ce,"edge",()=>be({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Q(ce,"safari",()=>be({darwin:"Safari"}));var rn=js;function nn(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as gn,readFileSync as Ws}from"fs";import F from"path";import{fileURLToPath as zs}from"url";import{gunzipSync as qs}from"zlib";var $=eo(mn(),1);function le(e,t){return e.header("Retry-After",String($s(t))),e.json({error:"Too Many Requests"},429)}function $s(e){return e&&typeof e=="object"&&"msBeforeNext"in e&&typeof e.msBeforeNext=="number"&&Number.isFinite(e.msBeforeNext)?Math.max(1,Math.ceil(e.msBeforeNext/1e3)):60}var Ks={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Vs(){let e=F.dirname(zs(import.meta.url));for(let t of[F.resolve(e,"app"),F.resolve(e,"../app"),F.resolve(e,"../../dist/app")])if(gn(F.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function yn(e,t="/inspector/assets"){let r=Vs(),n=new Map,o=new $.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return le(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=F.resolve(r,l),d=r.endsWith(F.sep)?r:`${r}${F.sep}`;if(!u.startsWith(d)||!gn(u))return i.notFound();let p=F.extname(c),m=l.endsWith(".gz"),g=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),h=Ws(u),y=m&&!g?n.get(u)??Gs(n,u,h):h,f=y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength);return i.body(f,200,{"Content-Type":Ks[p]??"application/octet-stream",...m&&g?{"Content-Encoding":"gzip"}:{},...m?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Gs(e,t,r){let n=qs(r);return e.set(t,n),n}var wn={name:"@mcp-use/inspector",type:"module",version:"20.2.5",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"},"./client/styles.css":{default:"./dist/client/styles.css"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs",test:"vitest run","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.7 || ^2.0.8","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"^2.2.4 || ^2.2.5 || ^2.3.0",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34",jsdom:"^27.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var Xs=wn.version;function We(){return Xs}var Js=`<!doctype html>
|
|
9
9
|
<html>
|
|
10
10
|
<head>
|
|
11
11
|
<meta charset="utf-8" />
|
package/dist/client/index.js
CHANGED
|
@@ -201,7 +201,7 @@ void main(){
|
|
|
201
201
|
}`;function MN(e){return[parseInt(e.slice(1,3),16)/255,parseInt(e.slice(3,5),16)/255,parseInt(e.slice(5,7),16)/255,1]}function El({className:e,colors:t=["#e0eaff","#f9ffbd","#dedede","#ffffff"],distortion:n=.8,swirl:o=.1,grainMixer:r=0,grainOverlay:s=.2,speed:a=1}){let i=uu(null),c=uu(null),l=uu({colors:t,distortion:n,swirl:o,grainMixer:r,grainOverlay:s,speed:a});return l.current={colors:t,distortion:n,swirl:o,grainMixer:r,grainOverlay:s,speed:a},TN(()=>{let u=i.current,p=c.current;if(!u||!p)return;let d=u.getContext("webgl2");if(!d)return;let g=(B,G)=>{let U=d.createShader(B);return U?(d.shaderSource(U,G),d.compileShader(U),d.getShaderParameter(U,d.COMPILE_STATUS)?U:(console.error(d.getShaderInfoLog(U)),null)):null},m=g(d.VERTEX_SHADER,PN),y=g(d.FRAGMENT_SHADER,RN);if(!m||!y)return;let f=d.createProgram();if(!f)return;if(d.attachShader(f,m),d.attachShader(f,y),d.linkProgram(f),!d.getProgramParameter(f,d.LINK_STATUS)){console.error(d.getProgramInfoLog(f));return}d.useProgram(f);let v=d.getAttribLocation(f,"a_position"),C=d.createBuffer();d.bindBuffer(d.ARRAY_BUFFER,C),d.bufferData(d.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),d.STATIC_DRAW),d.enableVertexAttribArray(v),d.vertexAttribPointer(v,2,d.FLOAT,!1,0,0);let b=d.getUniformLocation(f,"u_time"),h=d.getUniformLocation(f,"u_resolution"),N=[0,1,2,3].map(B=>d.getUniformLocation(f,`u_colors[${B}]`)),P=d.getUniformLocation(f,"u_colorsCount"),M=d.getUniformLocation(f,"u_distortion"),R=d.getUniformLocation(f,"u_swirl"),x=d.getUniformLocation(f,"u_grainMixer"),E=d.getUniformLocation(f,"u_grainOverlay"),w=0,k=performance.now(),T=0,A=()=>{let B=Math.min(2,window.devicePixelRatio||1);u.width=Math.floor(p.clientWidth*B),u.height=Math.floor(p.clientHeight*B),d.viewport(0,0,u.width,u.height)},I=B=>{if(document.hidden){k=B,T=requestAnimationFrame(I);return}let{colors:G,distortion:U,swirl:q,grainMixer:K,grainOverlay:H,speed:W}=l.current,oe=B-k;k=B,w+=oe*W;let j=G.map(MN);d.uniform1f(b,w*.001),d.uniform2f(h,u.width,u.height);for(let z=0;z<4;z++){let $=N[z];$&&d.uniform4fv($,j[z]??[1,1,1,1])}d.uniform1f(P,j.length),d.uniform1f(M,U),d.uniform1f(R,q),d.uniform1f(x,K),d.uniform1f(E,H),d.drawArrays(d.TRIANGLES,0,6),T=requestAnimationFrame(I)};A();let J=new ResizeObserver(A);return J.observe(p),T=requestAnimationFrame(I),()=>{cancelAnimationFrame(T),J.disconnect()}},[]),vh("div",{ref:c,className:e,children:vh("canvas",{ref:i,className:"h-full w-full","aria-hidden":!0})})}var IN=["#e0eaff","#f9ffbd","#dedede","#ffffff"],EN=["#27272a","#9a9448","#3f3f46","#18181b"];function Al(e){return e==="dark"?EN:IN}import{useCallback as AN,useState as LN}from"react";import{Play as DN,Square as _N}from"lucide-react";import{jsx as Is,jsxs as BN}from"react/jsx-runtime";var bh="mcp-inspector-chat-mesh-animation-paused";function ON(e){try{return localStorage.getItem(e)==="true"}catch{return!1}}function yh(e){let[t,n]=LN(()=>ON(e)),o=AN(()=>{n(r=>{let s=!r;try{localStorage.setItem(e,s?"true":"false")}catch{}return s})},[e]);return{paused:t,toggle:o}}var zN="z-50 flex h-7 w-7 cursor-pointer items-center justify-center rounded-full border border-zinc-500/60 bg-transparent text-zinc-600 transition-colors hover:border-zinc-500 hover:text-zinc-800 dark:border-zinc-500/50 dark:text-zinc-400 dark:hover:border-zinc-400 dark:hover:text-zinc-200";function xh({paused:e,onToggle:t,className:n}){return BN(Re,{children:[Is(Te,{render:Is("button",{type:"button",onClick:t,"aria-label":e?"Resume animation":"Pause animation",className:S(zN,n),children:e?Is(DN,{className:"ml-px h-3 w-3",fill:"currentColor"}):Is(_N,{className:"h-2.5 w-2.5",fill:"currentColor"})}),nativeButton:!0}),Is(Pe,{side:"left",children:Is("p",{children:e?"Resume animation":"Pause animation"})})]})}import{jsx as Da,jsxs as Sh}from"react/jsx-runtime";var FN=.54,$N=.4,Ch="linear-gradient(to top, black 0%, black 12%, rgba(0,0,0,0.55) 38%, transparent 100%)";function Nh({className:e,children:t,shaderPhase:n="hidden",onShaderFadeComplete:o,meshAnimationPaused:r=!1,...s}){let a=UN(null),[i,c]=HN(!1),{resolvedTheme:l}=lo(),u=Al(l),p=l==="dark",{paused:d,toggle:g}=yh(bh),m=d||r;wh(()=>{let C=window.requestAnimationFrame(()=>c(!0));return()=>window.cancelAnimationFrame(C)},[]),wh(()=>{n==="fading"&&!i&&o?.()},[n,i,o]);let y=n!=="hidden",f=n==="visible"&&i,v=C=>{C.propertyName==="opacity"&&n==="fading"&&o?.()};return Sh("div",{ref:a,className:S("relative flex min-h-0 flex-1 flex-col overflow-hidden bg-background",e),...s,children:[y&&Da("div",{className:S("pointer-events-none absolute inset-x-0 bottom-0 z-0 transition-opacity duration-500",f?"opacity-100":"opacity-0"),style:{height:`${FN*100}%`},"aria-hidden":!0,onTransitionEnd:v,children:Sh("div",{className:S("absolute inset-0",i?p?"opacity-90":"opacity-75":"opacity-0"),style:{maskImage:Ch,WebkitMaskImage:Ch},children:[Da("div",{className:"absolute inset-0 bg-[#edf2ff] dark:hidden"}),Da(El,{className:"absolute inset-0 h-full w-full",colors:[...u],distortion:.8,swirl:.1,grainMixer:0,grainOverlay:p?.12:.3,speed:m?0:$N})]})}),y&&Da(xh,{paused:d,onToggle:g,className:"absolute bottom-3 right-3 sm:bottom-5 sm:right-5"}),Da("div",{className:"relative z-10 flex min-h-0 flex-1 flex-col",children:t})]})}function kh(e){return e?e.apiKey==="server-managed"||e.baseUrl?.includes("/inspector/llm")===!0:!1}function _a(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes("failed to fetch")||t.includes("networkerror")||t.includes("network request failed")||t.includes("load failed")}function mu(e,t){if(!t)return e>=502&&e<=504?{kind:"cloud_unavailable"}:null;if(e===402)return{kind:"credits_exhausted",billingUrl:typeof t.upgradeUrl=="string"?t.upgradeUrl:typeof t.billingUrl=="string"?t.billingUrl:void 0,message:typeof t.message=="string"?t.message:"You've used your included free plan credits."};if(e===429){if(t.loginRequired&&t.loginUrl)return{kind:"login_required",loginUrl:String(t.loginUrl)};if(t.creditsExhausted)return{kind:"credits_exhausted",billingUrl:typeof t.billingUrl=="string"?t.billingUrl:void 0,message:typeof t.message=="string"?t.message:"You've used your included free plan credits."};if(t.error==="free_org_rate_limited"||typeof t.reason=="string")return{kind:"credits_exhausted",message:typeof t.message=="string"?t.message:"You've reached your included chat quota for this workspace."}}return e>=502&&e<=504?{kind:"cloud_unavailable"}:null}function VN(e){let t=e.match(/^OpenAI request failed \((\d+) /);if(!t)return null;let n=Number(t[1]),o=e.indexOf("{");if(o===-1)return null;try{let r=JSON.parse(e.slice(o));if(r&&typeof r=="object"&&!Array.isArray(r))return{status:n,body:r}}catch{}return null}function Th(e){if(e instanceof Error&&e.name==="LlmRequestError"){let t=e.status??0,n=e.body,o=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return mu(t,o)}if(e instanceof Error){let t=VN(e.message);if(t)return mu(t.status,t.body)}return _a(e)?{kind:"cloud_unavailable"}:null}function Ph(e,t){return mu(e,t)}import{ChevronDown as jN,Key as qN}from"lucide-react";import{jsx as $n,jsxs as pu}from"react/jsx-runtime";var WN="https://cdn.mcp-use.com/mcpuse_logo_circle_dark.svg";function Rh({symbolSize:e=14,className:t,textClassName:n}){return pu("span",{className:S("inline-flex items-center gap-1.5 text-black dark:text-white",t),children:[$n(KN,{size:e}),$n("span",{className:S("font-medium leading-none text-current [font-family:var(--font-family-outfit)]",n),children:"Manufact"})]})}function KN({size:e=14,className:t}){return pu("svg",{width:e,height:e,viewBox:"0 0 480 480","aria-hidden":!0,className:S("block shrink-0",t),children:[$n("path",{d:"M101.7 0 C157.9 0 203.4 45.7 203.4 102.1 C203.4 126.6 202.1 152.1 212.2 174.3 L219.8 191 C233.8 221.8 258.5 246.4 289.2 260.5 L303.5 267 C326.5 277.5 353 275.8 378.3 275.8 C434.5 275.8 480 321.5 480 377.9 C480 434.3 434.5 480 378.3 480 C322.1 480 276.6 434.3 276.6 377.9 C276.6 354.2 277.7 329.6 267.8 308 L259.8 290.3 C245.7 259.5 221 234.8 190.2 220.7 L173 212.9 C151 202.9 125.8 204.2 101.7 204.2 C45.5 204.2 0 158.5 0 102.1 C0 45.7 45.5 0 101.7 0 Z",fill:"currentColor"}),$n("circle",{cx:"96.4",cy:"383.6",r:"96.4",fill:"currentColor"}),$n("circle",{cx:"383.6",cy:"96.4",r:"96.4",fill:"currentColor"})]})}var JN='<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" fill="#94A3B8" stroke="#94A3B8"><g><path fill="none" d="M3 248.945C18 248.945 76 236 106 219C136 202 136 202 198 158C276.497 102.293 332 120.945 423 120.945" stroke-width="90"/><path d="M511 121.5L357.25 210.268L357.25 32.7324L511 121.5Z"/><path fill="none" d="M0 249C15 249 73 261.945 103 278.945C133 295.945 133 295.945 195 339.945C273.497 395.652 329 377 420 377" stroke-width="90"/><path d="M508 376.445L354.25 287.678L354.25 465.213L508 376.445Z"/></g></svg>',GN=`data:image/svg+xml,${encodeURIComponent(JN)}`,YN={openai:"OpenAI",anthropic:"Anthropic",google:"Google"};function XN(e){let t=e.split("/")[0]?.toLowerCase();return t==="openai"||t==="anthropic"||t==="google"?t:"openrouter"}function Oa(e,t){let n=e.trim(),o=YN[t];if(o){let s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${s}\\s*:\\s*`,"i"),i=n.replace(a,"").trim();if(i.length>0)return i}let r=n.indexOf(": ");return r>0&&r<48?n.slice(r+2).trim():n}function Mh({provider:e,model:t,displayName:n,mode:o="byok",className:r,...s}){let a=n??t,i=o==="managed"&&e==="openai-compatible"?XN(t):e;return pu("button",{type:"button",className:S("inline-flex items-center gap-1.5 min-w-0 border-0 bg-transparent p-1","font-mono text-[11px] text-muted-foreground cursor-pointer","hover:text-foreground transition-colors","rounded-md outline-none focus-visible:ring-1 focus-visible:ring-ring",r),...s,children:[o==="managed"?$n("img",{src:WN,alt:"Manufact",className:"h-3.5 w-3.5 shrink-0 rounded-full object-cover"}):$n(qN,{className:"size-3 shrink-0 opacity-70","aria-hidden":!0}),$n(eo,{provider:i,className:"shrink-0"}),$n("span",{className:"whitespace-nowrap",children:a}),$n(jN,{className:"size-3 shrink-0 opacity-60","aria-hidden":!0})]})}function jt(e){switch(e){case"openai":return"OpenAI";case"openai-compatible":return"OpenAI Compatible";case"anthropic":return"Anthropic";case"google":return"Google";case"openrouter":return"OpenRouter";case"ollama":return"Ollama";default:return e}}function QN(e,t){switch(e){case"openai":case"anthropic":case"google":return sa(`${e}.png`);case"ollama":return sa(`${t==="dark"?"ollama_dark":"ollama_light"}.png`);case"openrouter":return GN;case"openai-compatible":return null;default:return null}}function eo({provider:e,className:t}){let{resolvedTheme:n}=lo();if(e==="openai-compatible")return null;let o=QN(e,n);if(o){let r=e==="ollama"?"h-3.5 w-3.5 object-contain":"h-4 w-4 rounded-full object-cover";return $n("img",{src:o,alt:jt(e),className:S(r,t)})}return $n("div",{"aria-label":jt(e),className:S("flex h-4 w-4 items-center justify-center rounded-full bg-neutral-900 text-[9px] font-semibold text-white dark:bg-neutral-100 dark:text-neutral-900",t),children:jt(e).charAt(0)})}import{useCallback as Ll,useEffect as ZN,useSyncExternalStore as ek}from"react";var yu="openid profile email offline_access",Eh="mcp-inspector:manufact-auth",tk="manufact:session-changed",za={loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null},qr=new Map,vu=new Set,fu=new Map,gu=new Map,Ah=null,hu=!1;typeof window<"u"&&window.addEventListener("message",e=>{if(e.data?.type!=="manufact:invalidate-oauth-client")return;for(let n of qr.keys())Vn()?.removeItem(xn(n,"client"));let t=Ah;!t||hu||(hu=!0,Bh(t,{isRetry:!0}).finally(()=>{hu=!1}))});function nk(e){let t=qr.get(e);if(t)return t;let n={...za,loaded:!1};return qr.set(e,n),n}function Vn(){return typeof window>"u"?null:window.localStorage}function Ol(e){return new URL(e).origin}function ok(e,t){let n=new URL(e),o=new URL(t),r=new Set(["localhost","127.0.0.1"]);return r.has(n.hostname)&&r.has(o.hostname)?n.origin===o.origin:(n.hostname==="manufact.com"||n.hostname.endsWith(".manufact.com"))&&(o.hostname==="manufact.com"||o.hostname.endsWith(".manufact.com"))}function Lh(e){let t=window.__MANUFACT_LOGIN_URL__;if(t)return new URL(t).origin;let n=new URL(e);return n.hostname==="localhost"||n.hostname==="127.0.0.1"?`${n.protocol}//${n.hostname}:3000`:`${n.protocol}//manufact.com`}function rk(e){return`${Lh(e)}/auth/embedded-sign-out`}function xn(e,t){return`${Eh}:${t}:${e}`}function sk(e){return Vn()?.getItem(xn(e,"skip-session"))==="1"}function _l(e,t){let n=xn(e,"skip-session");t?Vn()?.setItem(n,"1"):Vn()?.removeItem(n)}function ak(e){return`${Eh}:state:${e}`}function Es(e){let t=Vn()?.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return Vn()?.removeItem(e),null}}function xu(e,t){Vn()?.setItem(e,JSON.stringify(t))}function fo(e,t){qr.set(e,{...qr.get(e)??za,...t}),vu.forEach(n=>n()),window.dispatchEvent(new CustomEvent(tk))}function Dh(e){let t="";return e.forEach(n=>{t+=String.fromCharCode(n)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function bu(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),Dh(t)}async function _h(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Dh(new Uint8Array(t))}async function zl(e){let t=await fetch(`${e}/api/auth/.well-known/openid-configuration`);if(!t.ok)throw new Error("Manufact OAuth discovery failed");return await t.json()}function Oh(){return`${window.location.origin}${Fo()}/auth/callback`}function Ih(e){return e==="localhost"||e==="127.0.0.1"}function ik(e){try{let t=new URL(e).hostname,n=typeof window<"u"?new URL(window.location.href).hostname:"";return Ih(t)&&Ih(n)}catch{return!1}}async function lk(e,t,n){let o=new URL(`${e}/api/auth/oauth2/authorize`);o.searchParams.set("response_type","code"),o.searchParams.set("client_id",t),o.searchParams.set("redirect_uri",n),o.searchParams.set("scope",yu),o.searchParams.set("code_challenge",await _h(bu(32))),o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("state","client-probe"),o.searchParams.set("prompt","none");try{let r=await fetch(o.toString(),{method:"GET",redirect:"manual",credentials:"include"}),s=r.headers.get("location")??"";return s.includes("/auth/error")&&s.includes("invalid_client")?!1:r.status>=300&&r.status<400||r.type==="opaqueredirect"?!!s&&!s.includes("/auth/error"):!0}catch{return!1}}async function ck(e,t){let n=Oh(),o=xn(e,"client"),r=Es(o),s=ik(e);if(!s&&r?.client_id&&r.redirect_uri===n){if(await lk(e,r.client_id,n))return r;Vn()?.removeItem(o)}else s&&r?.client_id&&Vn()?.removeItem(o);if(!t.registration_endpoint)throw new Error("Manufact OAuth registration is unavailable");let a=await fetch(t.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"mcp-use Inspector",redirect_uris:[n],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",scope:yu})});if(!a.ok)throw new Error("Could not register Inspector with Manufact");let i=await a.json();if(!i.client_id)throw new Error("Manufact returned no OAuth client ID");let c={...i,redirect_uri:n};return xu(o,c),c}async function dk(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t)}),o=await n.json().catch(()=>({}));if(!n.ok||!o.access_token)throw new Error(o.error_description??"Manufact token exchange failed");return{access_token:o.access_token,refresh_token:o.refresh_token,token_type:o.token_type,expires_at:Date.now()+(o.expires_in??3600)*1e3}}async function uk(e,t){if(!t.refresh_token)return null;let n=gu.get(e);if(n)return n;let o=(async()=>{try{let r=await zl(e),s=Es(xn(e,"client"));if(!s?.client_id)return null;let a=await dk(r.token_endpoint,{grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:s.client_id}),i={...a,refresh_token:a.refresh_token??t.refresh_token};return xu(xn(e,"tokens"),i),i}catch{return Vn()?.removeItem(xn(e,"tokens")),null}finally{gu.delete(e)}})();return gu.set(e,o),o}async function mk(e){let t=Es(xn(e,"tokens"));return t?.access_token?t.expires_at>Date.now()+3e4?t:uk(e,t):null}async function pk(e,t){let n=await zl(e);if(!n.userinfo_endpoint)return null;let o=await fetch(n.userinfo_endpoint,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok)return null;let r=await o.json();return r.sub?{id:r.sub,name:r.name,email:r.email,image:r.picture}:null}async function zh(e){try{let t=await fetch(`${e}/api/auth/get-session`,{credentials:"include"});return t.ok?(await t.json())?.user??null:null}catch{return null}}async function Dl(e){let t=fu.get(e);if(t)return t;qr.set(e,{...qr.get(e)??za,loaded:!1});let n=(async()=>{try{let o=typeof window<"u"?window.location.href:e,r=ok(o,e),s=sk(e),a=await mk(e),i=a?await pk(e,a.access_token):null;if(i&&a){_l(e,!1),fo(e,{loaded:!0,accessToken:a.access_token,user:i,mode:"oauth"});return}a&&!i&&Vn()?.removeItem(xn(e,"tokens"));let c=r&&!s?await zh(e):null;if(c){fo(e,{loaded:!0,accessToken:null,user:c,mode:"session"});return}fo(e,{loaded:!0,accessToken:null,user:null,mode:null})}catch{fo(e,{loaded:!0,accessToken:null,user:null,mode:null})}})().finally(()=>fu.delete(e));return fu.set(e,n),n}async function Bh(e,t){let n=Ol(e);Ah=e,_l(n,!1);let o=window.open("","manufact-oauth","width=600,height=700,resizable=yes,scrollbars=yes");if(!o)throw new Error("Allow popups to sign in with Manufact");fo(n,{authorizing:!0});try{let r=await zl(n),s=await ck(n,r),a=bu(64),i=bu(),c=Oh();xu(ak(i),{authOrigin:n,clientId:s.client_id,redirectUri:c,codeVerifier:a,expiresAt:Date.now()+600*1e3});let l=new URL(r.authorization_endpoint);l.searchParams.set("response_type","code"),l.searchParams.set("client_id",s.client_id),l.searchParams.set("redirect_uri",c),l.searchParams.set("scope",yu),l.searchParams.set("state",i),l.searchParams.set("code_challenge",await _h(a)),l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("prompt","consent"),o.location.href=l.toString();let u=window.setInterval(()=>{o.closed&&(window.clearInterval(u),Dl(n).finally(()=>fo(n,{authorizing:!1})))},500)}catch(r){throw o.close(),fo(n,{authorizing:!1}),r}}function fk(e){let t=Ol(e);Vn()?.removeItem(xn(t,"tokens")),fo(t,{loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null})}async function gk(e){let t=Es(xn(e,"tokens")),n=Es(xn(e,"client")),o=t?.refresh_token??t?.access_token;if(!n?.client_id||!o)return null;try{let s=(await zl(e)).revocation_endpoint??`${e}/api/auth/oauth2/revoke`;return(await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n.client_id,token:o,token_type_hint:t?.refresh_token?"refresh_token":"access_token"})})).status}catch{return-1}}async function hk(e){let t=Lh(e),n=window.open(rk(e),"manufact-sign-out","width=420,height=320");return n?new Promise(o=>{let r=!1,s=l=>{r||(r=!0,window.clearTimeout(a),window.clearInterval(c),window.removeEventListener("message",i),o(l))},a=window.setTimeout(()=>{s({attempted:!0,signOutOk:!1,signOutStatus:null})},3e4),i=l=>{l.origin===t&&l.data?.type==="manufact:sign-out-complete"&&s({attempted:!0,signOutOk:!0,signOutStatus:200})},c=window.setInterval(()=>{n.closed&&zh(e).then(l=>{s({attempted:!0,signOutOk:!l,signOutStatus:l?401:200})})},500);window.addEventListener("message",i)}):{attempted:!0,signOutOk:!1,signOutStatus:null}}async function vk(e,t){let n=Ol(e),o=!!Es(xn(n,"tokens"))?.access_token;t==="oauth"||o?(await gk(n),_l(n,!0)):t==="session"&&(await hk(n),_l(n,!1)),fk(e)}function Uh(e){let t=e?Ol(e):null,n=Ll(s=>(vu.add(s),()=>vu.delete(s)),[]),o=Ll(()=>t?nk(t):za,[t]),r=ek(n,o,()=>za);return ZN(()=>{if(!t)return;Dl(t);let s=i=>{i.origin===window.location.origin&&i.data?.type==="manufact:oauth-complete"&&i.data.authOrigin===t&&Dl(t).finally(()=>fo(t,{authorizing:!1}))},a=i=>{i.key!==xn(t,"tokens")||!i.newValue||Dl(t).finally(()=>fo(t,{authorizing:!1}))};return window.addEventListener("message",s),window.addEventListener("storage",a),()=>{window.removeEventListener("message",s),window.removeEventListener("storage",a)}},[t]),{...r,authorize:Ll(async()=>{e&&await Bh(e)},[e]),logout:Ll(async()=>{e&&await vk(e,r.mode)},[e,r.mode])}}function Hh(e){return Uh(e)}import{useEffect as bk}from"react";function Fh(e){bk(()=>{let t=n=>{let o=n.target,r=o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.contentEditable==="true";if((n.metaKey||n.ctrlKey)&&n.key==="k"){n.preventDefault(),e.onCommandPalette?.();return}if((n.metaKey||n.ctrlKey)&&n.key==="o"&&e.onNewChat){n.preventDefault(),e.onNewChat();return}if(n.key==="Escape"){n.preventDefault(),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),e.onBlurSearch?.();return}if(!r&&!(n.metaKey||n.ctrlKey||n.altKey||n.shiftKey))switch(n.key.toLowerCase()){case"t":n.preventDefault(),e.onToolsTab?.();break;case"p":n.preventDefault(),e.onPromptsTab?.();break;case"r":n.preventDefault(),e.onResourcesTab?.();break;case"c":n.preventDefault(),e.onChatTab?.();break;case"h":n.preventDefault(),e.onHome?.();break;case"f":n.preventDefault(),e.onFocusSearch?.();break;default:break}};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[e])}import{Copy as Jk,Download as Gk,SquarePen as Yk}from"lucide-react";import{Check as Kh,ChevronsUpDown as Jh,Eye as Mk,EyeOff as Ik,Key as Ek,Loader2 as Gh}from"lucide-react";import{useEffect as Mu,useRef as Ak,useState as Kr}from"react";import{Tabs as Su}from"@base-ui/react/tabs";import{AnimatePresence as Nu,motion as Bl}from"motion/react";import{createContext as Ck,forwardRef as Pu,useCallback as Cu,useContext as Sk,useEffect as ku,useRef as Ul,useState as Nk}from"react";import{useCallback as As,useEffect as wu,useRef as Ls,useState as $h}from"react";function Vh(e,t){let n=e.getBoundingClientRect(),o=t==="x"?e.offsetWidth:e.offsetHeight,r=t==="x"?n.width:n.height;return o>0?r/o:1}function yk(e,t){let n=e.getBoundingClientRect(),o=Vh(e,"x"),r=Vh(e,"y"),s=[];return t.forEach((a,i)=>{let c=a.getBoundingClientRect();s[i]={top:(c.top-n.top)/r+e.scrollTop,left:(c.left-n.left)/o+e.scrollLeft,width:a.offsetWidth,height:a.offsetHeight}}),s}function xk(e,t,n,o){let r=o==="x"?t:n,s=null,a=1/0,i=null;return e.forEach((c,l)=>{let u=c.getBoundingClientRect(),p=o==="x"?u.left:u.top,d=o==="x"?u.right:u.bottom;r>=p&&r<=d&&(i=l);let g=(p+d)/2,m=Math.abs(r-g);m<a&&(a=m,s=l)}),i??s}function wk(e,t){if(e.length!==t.length)return!0;for(let n=0;n<t.length;n++){let o=e[n],r=t[n];if(o!==r&&(!o||!r||o.top!==r.top||o.left!==r.left||o.width!==r.width||o.height!==r.height))return!0}return!1}function jh(e,t={}){let{axis:n="y"}=t,o=Ls(new Map),[r,s]=$h(null),[a,i]=$h([]),c=Ls([]),l=Ls(0),u=Ls(null),p=Ls(null),d=Ls(null),g=As(()=>{let b=e.current;if(!b)return;let h=yk(b,o.current);wk(c.current,h)&&(c.current=h,i(h))},[e]),m=As((b,h)=>{s(xk(o.current,b,h,n))},[n]),y=As((b,h)=>{h?o.current.set(b,h):o.current.delete(b),p.current!==null&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{p.current=null,g()})},[g]),f=As(b=>{d.current={x:b.clientX,y:b.clientY},u.current!==null&&cancelAnimationFrame(u.current),u.current=requestAnimationFrame(()=>{u.current=null,g(),m(b.clientX,b.clientY)})},[g,m]),v=As(()=>{l.current+=1},[]),C=As(()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),d.current=null,s(null)},[]);return wu(()=>{let b=e.current;if(!b||typeof ResizeObserver>"u")return;let h=new ResizeObserver(()=>{p.current!==null&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{p.current=null,g()})});return h.observe(b),()=>h.disconnect()},[e,g]),wu(()=>{let b=e.current;if(!b)return;let h=()=>{g();let N=d.current;N&&m(N.x,N.y)};return b.addEventListener("scroll",h,{capture:!0,passive:!0}),()=>b.removeEventListener("scroll",h,{capture:!0})},[e,g,m]),wu(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),p.current!==null&&cancelAnimationFrame(p.current)},[]),{activeIndex:r,setActiveIndex:s,itemRects:a,sessionRef:l,handlers:{onMouseMove:f,onMouseEnter:v,onMouseLeave:C},registerItem:y,measureItems:g}}import{jsx as Mn,jsxs as Tu}from"react/jsx-runtime";var qh=Ck(null);function kk(){let e=Sk(qh);if(!e)throw new Error("useTabsSubtle must be used within a TabsSubtle");return e}var Ba=Pu(({children:e,selectedIndex:t,onSelect:n,idPrefix:o,activeLabel:r=!1,className:s,...a},i)=>{let c=Ul(null),l=Ul(!1),u=Nt(),{activeIndex:p,setActiveIndex:d,itemRects:g,handlers:m,registerItem:y,measureItems:f}=jh(c,{axis:"x"}),v=Ul(new Map),C=Cu((k,T)=>{y(k,T),T?v.current.set(k,T):v.current.delete(k)},[y]);ku(()=>{f()},[f,e]),ku(()=>{let k=v.current;if(k.size===0)return;let T=new ResizeObserver(()=>f());return k.forEach(A=>T.observe(A)),()=>T.disconnect()},[f,e]);let b=Cu(k=>{l.current=!0,m.onMouseMove(k)},[m]),h=Cu(()=>{l.current=!1,m.onMouseLeave()},[m]),[N,P]=Nk(null),M=g[t],R=p!==null?g[p]:null,x=N!==null?g[N]:null,E=p===t,w=p!==null&&!E;return Mn(qh.Provider,{value:{registerTab:C,hoveredIndex:p,selectedIndex:t,idPrefix:o,activeLabel:r},children:Mn(Su.Root,{value:t,onValueChange:k=>{typeof k=="number"&&n(k)},render:Tu(Su.List,{activateOnFocus:!1,ref:k=>{c.current=k,typeof i=="function"?i(k):i&&(i.current=k)},onMouseMove:b,onMouseLeave:h,onFocus:k=>{let T=k.target.closest("[data-proximity-index]")?.getAttribute("data-proximity-index");if(T!=null){let A=Number(T);d(A),P(k.target.matches(":focus-visible")?A:null)}},onBlur:k=>{c.current?.contains(k.relatedTarget)||(P(null),!l.current&&d(null))},className:S("relative flex items-center gap-0.5 select-none overflow-x-auto max-w-full -mx-1 px-1 -my-1 py-1",s),...a,children:[M&&Mn(Bl.div,{className:S("absolute bg-accent pointer-events-none",u.bg),initial:!1,animate:{left:M.left,width:M.width,top:M.top,height:M.height,opacity:w?.8:1},transition:{...ae.moderate,opacity:{duration:.08}}}),Mn(Nu,{children:R&&!E&&M&&Mn(Bl.div,{className:S("absolute bg-accent pointer-events-none",u.bg),initial:{left:M.left,width:M.width,top:M.top,height:M.height,opacity:0},animate:{left:R.left,width:R.width,top:R.top,height:R.height,opacity:.4},exit:!l.current&&M?{left:M.left,width:M.width,top:M.top,height:M.height,opacity:0,transition:{...ae.moderate,opacity:{duration:.06}}}:{opacity:0,transition:ae.fast.exit},transition:{...ae.fast,opacity:{duration:.08}}})}),Mn(Nu,{children:x&&Mn(Bl.div,{className:S("absolute pointer-events-none z-20 border border-[color:var(--focus-ring,#6B97FF)]",u.focusRing),initial:!1,animate:{left:x.left-2,top:x.top-2,width:x.width+4,height:x.height+4},exit:{opacity:0,transition:ae.fast.exit},transition:{...ae.fast,opacity:{duration:.08}}})}),e]})})})});Ba.displayName="TabsSubtle";var Wr=Pu(({icon:e,label:t,index:n,className:o,...r},s)=>{let a=Ul(null),i=Nt(),{registerTab:c,hoveredIndex:l,selectedIndex:u,idPrefix:p,activeLabel:d}=kk();ku(()=>(c(n,a.current),()=>c(n,null)),[n,c]);let g=u===n,m=l===n||g,y=d&&!!e,f=!y||g,v=Tu("span",{className:"inline-grid",children:[Mn("span",{className:"col-start-1 row-start-1 invisible [text-box:trim-both_cap_alphabetic]",style:{fontVariationSettings:Pt.semibold},"aria-hidden":"true",children:t}),Mn("span",{className:S("col-start-1 row-start-1 transition-[color,font-variation-settings] duration-80 [text-box:trim-both_cap_alphabetic]",m?"text-foreground":"text-muted-foreground"),style:{fontVariationSettings:g?Pt.semibold:Pt.normal},children:t})]});return Tu(Su.Tab,{ref:C=>{let b=C;a.current=b,typeof s=="function"?s(b):s&&(s.current=b)},value:n,"data-proximity-index":n,id:p?`${p}-tab-${n}`:void 0,"aria-controls":p?`${p}-panel-${n}`:void 0,"aria-label":y&&!f?t:void 0,className:S("relative z-10 flex items-center px-2 cursor-pointer bg-transparent border-none outline-none text-xs",y?"h-7":"h-7 gap-1.5",i.bg,o),...r,children:[e&&Mn(e,{size:14,strokeWidth:m?2:1.5,className:S("shrink-0 transition-[color,stroke-width] duration-80",m?"text-foreground":"text-muted-foreground")}),y?Mn(Nu,{children:f&&Mn(Bl.span,{className:"overflow-hidden",initial:{width:0,opacity:0,marginLeft:0},animate:{width:"auto",opacity:1,marginLeft:6},exit:{width:0,opacity:0,marginLeft:0},transition:{...ae.fast,opacity:{duration:.06}},children:v},"label")}):v]})});Wr.displayName="TabsSubtleItem";var Tk=Pu(({index:e,selectedIndex:t,idPrefix:n,children:o,className:r,...s},a)=>{let i=t===e;return Mn("div",{ref:a,id:`${n}-panel-${e}`,role:"tabpanel","aria-labelledby":`${n}-tab-${e}`,hidden:!i,tabIndex:-1,className:S("outline-none",r),...s,children:i&&o})});Tk.displayName="TabsSubtlePanel";import*as _t from"react";import{jsx as ir,jsxs as Rk}from"react/jsx-runtime";var Wh=_t.createContext(null);function Ru(){let e=_t.useContext(Wh);if(!e)throw new Error("Command components must be used within <Command>");return e}function Pk(e,t){return t?e.toLowerCase().includes(t.toLowerCase()):!0}var Hl=_t.forwardRef(({className:e,...t},n)=>{let[o,r]=_t.useState(""),[s,a]=_t.useState(null),[i,c]=_t.useState(0),l=_t.useCallback(()=>(c(u=>u+1),()=>c(u=>Math.max(0,u-1))),[]);return ir(Wh.Provider,{value:{search:o,setSearch:r,activeValue:s,setActiveValue:a,visibleCount:i,registerVisible:l},children:ir("div",{ref:n,className:S("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})})});Hl.displayName="Command";var Fl=_t.forwardRef(({className:e,...t},n)=>{let{search:o,setSearch:r}=Ru();return ir("div",{className:"flex items-center border-b px-3",children:ir("input",{ref:n,value:o,onChange:s=>r(s.target.value),className:S("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})})});Fl.displayName="CommandInput";var $l=_t.forwardRef(({className:e,...t},n)=>ir("div",{ref:n,className:S("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));$l.displayName="CommandList";var Vl=_t.forwardRef(({className:e,...t},n)=>{let{visibleCount:o}=Ru();return o>0?null:ir("div",{ref:n,className:S("py-6 text-center text-sm",e),...t})});Vl.displayName="CommandEmpty";var jl=_t.forwardRef(({className:e,heading:t,children:n,...o},r)=>Rk("div",{ref:r,className:S("overflow-hidden p-1 text-foreground [&_[data-command-group-heading]]:px-2 [&_[data-command-group-heading]]:py-1.5 [&_[data-command-group-heading]]:text-xs [&_[data-command-group-heading]]:font-medium [&_[data-command-group-heading]]:text-muted-foreground",e),...o,children:[t?ir("div",{"data-command-group-heading":"",children:t}):null,n]}));jl.displayName="CommandGroup";var ql=_t.forwardRef(({className:e,value:t,keywords:n,onSelect:o,disabled:r,onClick:s,...a},i)=>{let{search:c,activeValue:l,setActiveValue:u,registerVisible:p}=Ru(),d=Array.isArray(n)?n.join(" "):n,g=d?`${t} ${d}`:t,m=Pk(g,c),y=l===t;return _t.useLayoutEffect(()=>{if(m)return p()},[m,p]),_t.useEffect(()=>{m&&l===null&&!r&&u(t)},[m,l,r,u,t]),m?ir("div",{ref:i,role:"option","aria-selected":y,"data-selected":y,"data-disabled":r,className:S("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),onMouseEnter:()=>!r&&u(t),onClick:f=>{s?.(f),r||o?.(t)},...a}):null});ql.displayName="CommandItem";import{buildOllamaApiUrl as Lk,normalizeOllamaBaseUrl as Dk,OllamaCorsError as _k}from"@mcp-use/agent";import{Fragment as Kk,jsx as ee,jsxs as Ue}from"react/jsx-runtime";var Iu="mcp-inspector-models-cache",Ok=1440*60*1e3;function Yh(){try{let e=localStorage.getItem(Iu);if(e)return JSON.parse(e)}catch(e){console.error("Failed to load models cache:",e)}return{}}function zk(e,t){try{let n=Yh();n[e]={models:t,timestamp:Date.now()},localStorage.setItem(Iu,JSON.stringify(n))}catch(n){console.error("Failed to save models cache:",n)}}function Bk(e){try{let t=Yh(),n=t[e];if(n){if(Date.now()-n.timestamp<Ok)return n.models;delete t[e],localStorage.setItem(Iu,JSON.stringify(t))}}catch(t){console.error("Failed to get cached models:",t)}return null}function Uk(e,t){if(!Po(e)||!t?.trim())return e;let n=e==="ollama"?Dk(t):t.trim().toLowerCase();return`${e}:${n}`}var Hk="chat-config-source";function Ua(e){return e==="openai"||e==="anthropic"||e==="google"?e:"openrouter"}async function Fk(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);let o;try{o=await fetch(`${e}/models`,{headers:n})}catch{throw new Error("Failed to reach the server. Check the URL is correct and that CORS is enabled on the server.")}if(!o.ok)throw new Error(`Failed to fetch models: ${o.statusText}`);if(!(o.headers.get("content-type")??"").includes("application/json"))throw new Error("Invalid URL \u2014 response was not JSON");let s=await o.json();if(!Array.isArray(s?.data))throw new Error("Unexpected response format \u2014 expected { data: [...] } from the OpenAI-compatible endpoint");return s.data.map(a=>({id:a.id}))}async function $k(e){let t=await fetch("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch OpenAI models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id}))}async function Vk(e){let t=await fetch("https://api.anthropic.com/v1/models",{headers:{"x-api-key":e,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"}});if(!t.ok)throw new Error(`Failed to fetch Anthropic models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id,displayName:o.display_name}))}async function jk(e){let t=await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${e}`);if(!t.ok)throw new Error(`Failed to fetch Google models: ${t.statusText}`);return((await t.json()).models||[]).map(o=>({id:o.name,displayName:o.displayName}))}async function qk(e){let t=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch OpenRouter models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id,displayName:o.name}))}async function Wk(e,t){let n;try{n=await fetch(Lk(e,"/api/tags"),{headers:{...t.trim()?{Authorization:`Bearer ${t.trim()}`}:{}}})}catch(r){throw new _k(r)}if(!n.ok)throw new Error(`Failed to fetch Ollama models: ${n.statusText}`);return((await n.json()).models||[]).map(r=>({id:r.model||r.name||""}))}function Ha({open:e,onOpenChange:t,tempProvider:n,tempModel:o,tempApiKey:r,tempBaseUrl:s,onProviderChange:a,onModelChange:i,onApiKeyChange:c,onBaseUrlChange:l,onSave:u,onClear:p,showClearButton:d=!1,buttonLabel:g="Configure API Key",hostedInspector:m=!1,freeTierInfo:y,managedCloudInfo:f,useManagedCloud:v=!1,onSaveManagedCloud:C}){let{resolvedTheme:b}=lo(),h=Al(b),N=b==="dark",[P,M]=Kr([]),[R,x]=Kr(!1),[E,w]=Kr(null),[k,T]=Kr(!1),[A,I]=Kr(!1),[J,B]=Kr(!1),[G,U]=Kr(v?0:1),q=Uk(n,s),K=!!(m||y||f),H=!!(f&&G===0);Mu(()=>{e&&U(v?0:1)},[e,v]),Mu(()=>{let Z=Ur(n),Y=Po(n);if(H||!e||!n||Z&&!r.trim()||Y&&!s.trim()){M([]),w(null);return}let le=setTimeout(async()=>{let De=Bk(q);if(De){M(De),w(null);return}x(!0),w(null);try{let We=[];n==="openai-compatible"?We=await Fk(s,r):n==="openai"?We=await $k(r):n==="anthropic"?We=await Vk(r):n==="google"?We=await jk(r):n==="openrouter"?We=await qk(r):n==="ollama"&&(We=await Wk(s,r)),zk(q,We),M(We)}catch(We){w(We instanceof Error?We.message:"Failed to fetch models. Please check your API key."),M([])}finally{x(!1)}},500);return()=>clearTimeout(le)},[r,s,n,e,q,H]);let W=Ak(null);Mu(()=>{if(!e||H){e||(W.current=null);return}let Z=W.current;Z!==null&&Z!==n&&i(""),W.current=n},[n,e,i,H]);let oe=Po(n),j=!Ur(n),z=e&&(!Ur(n)||!!r.trim())&&(!oe||!!s.trim()),$=j?"API Key (optional)":"API Key",ie=j?n==="ollama"?"Leave empty for local Ollama":"Enter your API key (optional)":"Enter your API key",fe=n==="openai-compatible"?"http://localhost:11434/v1":tr(n),ue=n==="openai-compatible"?"Base URL of your OpenAI-compatible API. Local servers must have CORS enabled.":null,xe=n==="ollama"?"Optional for local Ollama. Stored locally and never sent to our servers.":"Your API key is stored locally and never sent to our servers.",re=f?f.models.reduce((Z,Y)=>(Z[Y.provider]||(Z[Y.provider]=[]),Z[Y.provider].push(Y),Z),{}):{},Se=f?.models.find(Z=>Z.id===f.selectedModelId),Ne=Object.keys(re),pe=Se?.provider??Ne[0]??"",He=pe?re[pe]??[]:[],Ye=!!p&&d&&(!f||G===1),qe=()=>{if(H&&C){C();return}u()},xt=H?!!(f?.isLoading||!f?.selectedModelId||f?.models.length===0):Ur(n)&&!r.trim()||oe&&!s.trim()||!o.trim();return ee(Sn,{open:e,onOpenChange:t,children:Ue(gn,{className:"max-w-md","data-testid":"chat-config-dialog",children:[Ue(sn,{children:[ee(nn,{children:K?"Configure Chat":"LLM Provider Configuration"}),ee(bo,{children:f?"Pick a Manufact cloud model or bring your own API key.":y?"Chat requires an LLM. You can chat for free if you have a Manufact account, or you can use your own API key (not sent to Manufact).":"Configure your LLM provider and API key to start chatting with the MCP server"})]}),Ue("div",{className:"space-y-4",children:[y&&Ue("button",{type:"button",onClick:y.onLoginClick,"data-testid":"chat-config-sign-in-card",className:"relative w-full cursor-pointer overflow-hidden rounded-2xl border-0 text-left transition-opacity hover:opacity-95 active:opacity-90",children:[ee("div",{className:"absolute inset-0 bg-[#edf2ff] dark:bg-background","aria-hidden":!0}),ee("div",{className:"absolute inset-0 dark:opacity-90",children:ee(El,{className:"absolute inset-0 h-full w-full",colors:[...h],grainOverlay:N?.1:.15})}),Ue("div",{className:"relative flex items-center justify-between gap-4 px-4 py-3.5",children:[Ue("div",{className:"text-sm font-medium text-foreground",children:[ee("p",{children:"Chat for free with a"}),Ue("p",{className:"mt-1 flex items-center gap-1.5",children:[ee(Rh,{symbolSize:14,textClassName:"text-sm"}),"account"]})]}),ee(L,{size:"sm",render:ee("span",{"aria-hidden":"true"}),nativeButton:!1,tabIndex:-1,className:"pointer-events-none shrink-0",children:"Sign in"})]})]}),f&&ee("div",{className:"flex justify-center",children:Ue(Ba,{selectedIndex:G,onSelect:U,idPrefix:Hk,className:"w-fit",children:[ee(Wr,{index:0,label:"Manufact cloud"}),ee(Wr,{index:1,label:"API key"})]})}),Ue("div",{className:S("space-y-2",f&&"!mt-2"),children:[ee(ut,{children:"Provider"}),H?Ue(Dn,{value:pe,onValueChange:Z=>{let Y=f?.models.find(_=>_.provider===Z);Y&&f?.onModelChange(Y.id)},children:[ee(Gn,{className:"rounded-md",leading:pe?ee(eo,{provider:Ua(pe),className:"shrink-0"}):void 0,children:ee(Kn,{})}),ee(Jn,{children:Ne.map(Z=>ee(on,{value:Z,label:jt(Ua(Z)),children:Ue("div",{className:"flex items-center gap-2",children:[ee(eo,{provider:Ua(Z)}),ee("span",{children:jt(Ua(Z))})]})},Z))})]}):Ue(Dn,{value:n,onValueChange:Z=>a(Z),children:[ee(Gn,{className:"rounded-md",leading:ee(eo,{provider:n,className:"shrink-0"}),children:ee(Kn,{})}),Ue(Jn,{children:[ee(on,{value:"openai",label:jt("openai"),children:Ue("div",{className:"flex items-center gap-2",children:[ee(eo,{provider:"openai"}),ee("span",{children:jt("openai")})]})}),ee(on,{value:"anthropic",label:jt("anthropic"),children:Ue("div",{className:"flex items-center gap-2",children:[ee(eo,{provider:"anthropic"}),ee("span",{children:jt("anthropic")})]})}),ee(on,{value:"google",label:jt("google"),children:Ue("div",{className:"flex items-center gap-2",children:[ee(eo,{provider:"google"}),ee("span",{children:jt("google")})]})}),ee(on,{value:"ollama",label:jt("ollama"),children:Ue("div",{className:"flex items-center gap-2",children:[ee(eo,{provider:"ollama"}),ee("span",{children:jt("ollama")})]})}),ee(on,{value:"openrouter",label:jt("openrouter"),children:Ue("div",{className:"flex items-center gap-2",children:[ee(eo,{provider:"openrouter"}),ee("span",{children:jt("openrouter")})]})}),ee(on,{value:"openai-compatible",label:jt("openai-compatible"),children:ee("div",{className:"flex items-center gap-2",children:ee("span",{children:jt("openai-compatible")})})})]})]})]}),!H&&oe&&Ue("div",{className:"space-y-2",children:[ee(ut,{children:"Base URL"}),ee(nt,{value:s,onChange:Z=>l(Z.target.value),placeholder:fe,"data-testid":"chat-config-base-url-input"}),ue&&ee("p",{className:"text-xs text-muted-foreground",children:ue})]}),!H&&Ue("div",{className:"space-y-2",children:[ee(ut,{children:$}),Ue("div",{className:"relative",children:[ee(nt,{type:J?"text":"password",value:r,onChange:Z=>c(Z.target.value),placeholder:ie,className:"pr-10","data-testid":"chat-config-api-key-input"}),ee(L,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>B(!J),children:J?ee(Ik,{className:"h-4 w-4 text-muted-foreground"}):ee(Mk,{className:"h-4 w-4 text-muted-foreground"})})]}),ee("p",{className:"text-xs text-muted-foreground",children:xe})]}),H?Ue("div",{className:"space-y-2",children:[ee(ut,{children:"Model"}),f?.isLoading?Ue("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[ee(Gh,{className:"h-4 w-4 animate-spin"}),ee("span",{children:"Loading models\u2026"})]}):He.length>0?Ue(Go,{open:A,modal:!0,onOpenChange:I,children:[ee(Yo,{render:Ue(L,{variant:"outline",role:"combobox","aria-expanded":A,className:"w-full justify-between rounded-md","data-testid":"chat-config-cloud-model-select",children:[ee("span",{className:"inline-flex min-w-0 items-center gap-2 truncate",children:Se?Ue(Kk,{children:[ee(eo,{provider:Ua(Se.provider),className:"shrink-0"}),ee("span",{className:"truncate",children:Oa(Se.name,Se.provider)})]}):"Select a model\u2026"}),ee(Jh,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]}),nativeButton:!0}),ee(Xo,{className:"w-full p-0",align:"start",children:Ue(Hl,{children:[ee(Fl,{placeholder:"Search models\u2026",className:"h-9"}),Ue($l,{children:[ee(Vl,{children:"No model found."}),ee(jl,{children:He.map(Z=>Ue(ql,{value:Z.id,keywords:[Z.name,Z.id,Z.provider],onSelect:Y=>{f?.onModelChange(Y),I(!1)},children:[Oa(Z.name,Z.provider),ee(Kh,{className:S("ml-auto h-4 w-4",f?.selectedModelId===Z.id?"opacity-100":"opacity-0")})]},Z.id))})]})]})})]}):ee("p",{className:"text-sm text-muted-foreground",children:"Cloud models unavailable \u2014 try again or use your own key."})]}):z&&Ue("div",{className:"space-y-2",children:[ee(ut,{children:"Model"}),R?Ue("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[ee(Gh,{className:"h-4 w-4 animate-spin"}),ee("span",{children:"Loading models..."})]}):E?ee("div",{className:"text-sm text-destructive",children:E}):P.length>0?Ue(Go,{open:k,modal:!0,onOpenChange:T,children:[ee(Yo,{render:Ue(L,{variant:"outline",role:"combobox","aria-expanded":k,className:"w-full justify-between rounded-md","data-testid":"chat-config-model-select",children:[ee("span",{className:"truncate",children:o&&(P.find(Z=>Z.id===o)?.displayName||P.find(Z=>Z.id===o)?.id)||"Select a model..."}),ee(Jh,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]}),nativeButton:!0}),ee(Xo,{className:"w-full p-0",align:"start",children:Ue(Hl,{children:[ee(Fl,{placeholder:"Search models...",className:"h-9"}),Ue($l,{children:[ee(Vl,{children:"No model found."}),ee(jl,{children:P.map(Z=>Ue(ql,{value:Z.id,keywords:Z.displayName,onSelect:Y=>{i(Y===o?"":Y),T(!1)},children:[Z.displayName||Z.id,ee(Kh,{className:S("ml-auto h-4 w-4",o===Z.id?"opacity-100":"opacity-0")})]},Z.id))})]})]})})]}):ee(nt,{value:o,onChange:Z=>i(Z.target.value),placeholder:"Enter model name manually","data-testid":"chat-config-model-input"})]}),Ue("div",{className:"flex justify-between",children:[Ye&&ee(L,{variant:"outline",onClick:p,children:"Clear Config"}),Ue(L,{onClick:qe,disabled:xt,className:Ye?"ml-auto":"","data-testid":"chat-config-save-button",children:[ee(Ek,{className:"h-4 w-4 mr-2"}),"Save Configuration"]})]})]})]})})}var Eu="rounded-full bg-background/80 backdrop-blur-md supports-[backdrop-filter]:bg-background/60 dark:bg-zinc-950/75 dark:supports-[backdrop-filter]:bg-zinc-950/55",Au=S(Eu,"w-fit"),Wl=S(Eu,"h-9 gap-1.5 px-3");import{jsx as Ot,jsxs as go}from"react/jsx-runtime";var Xk="chat-view";function Lu({llmConfig:e,hasMessages:t,configDialogOpen:n,onConfigDialogOpenChange:o,onClearChat:r,tempProvider:s,tempModel:a,tempApiKey:i,tempBaseUrl:c,onProviderChange:l,onModelChange:u,onApiKeyChange:p,onBaseUrlChange:d,onSaveConfig:g,onClearConfig:m,hideConfigButton:y,hostedInspector:f,freeTierInfo:v,managedCloudInfo:C,useManagedCloud:b,onSaveManagedCloud:h,showClearButton:N,clearButtonLabel:P,hideTitle:M,clearButtonHideIcon:R,clearButtonHideShortcut:x,clearButtonVariant:E,hideClearButton:w,onCopyChat:k,onExportChat:T,activeChatId:A,chatTitle:I,showViewToggle:J,viewIndex:B=0,onViewIndexChange:G,elevatedHeader:U}){return go("div",{className:S("relative flex w-full items-center gap-2 overflow-visible",_o,U?"pointer-events-none absolute top-0 right-0 z-50":"absolute top-0 right-0 z-10"),children:[Ot("div",{className:S("flex min-w-0 flex-1 items-center",U&&"pointer-events-auto"),children:!M&&Ot("h2",{className:S(Oo,Au),children:A?Ot(Ea,{chatId:A,title:I??sr},A):sr})}),J&&G&&Ot("div",{className:S("absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 overflow-visible px-1",U&&"pointer-events-auto"),children:go(Ba,{selectedIndex:B,onSelect:G,idPrefix:Xk,className:"shrink-0 overflow-visible","data-testid":"chat-view-tabs",children:[Ot(Wr,{label:"Conv",index:0}),Ot(Wr,{label:"Raw",index:1})]})}),go("div",{className:S("ml-auto flex shrink-0 items-center gap-2",U&&"pointer-events-auto"),children:[!w&&t&&go("div",{className:"flex items-center gap-1",children:[k&&go(L,{"data-testid":"chat-copy-button",variant:"ghost",size:"sm",className:Wl,onClick:k,children:[Ot(Jk,{className:"h-4 w-4"}),Ot("span",{className:"hidden sm:inline",children:"Copy"})]}),T&&go(Cr,{children:[Ot(Ho,{render:go(L,{"data-testid":"chat-export-button",variant:"ghost",size:"sm",className:Wl,children:[Ot(Gk,{className:"h-4 w-4"}),Ot("span",{className:"hidden sm:inline",children:"Export"})]}),nativeButton:!0}),go(Sr,{align:"end",children:[Ot(Ln,{"data-testid":"chat-export-json",onClick:()=>T("json"),children:"Export as JSON"}),Ot(Ln,{"data-testid":"chat-export-markdown",onClick:()=>T("markdown"),children:"Export as Markdown"})]})]}),Ot("div",{className:"w-px h-4 bg-border mx-1"}),go(Re,{children:[Ot(Te,{render:go(L,{variant:E??"default",size:"default",className:`p-2 cursor-pointer ${x?"sm:px-3":"sm:pr-1 sm:pl-3"}`,onClick:r,children:[!R&&Ot(Yk,{className:"h-4 w-4 sm:mr-2"}),Ot("span",{className:"hidden sm:inline",children:P??"New Chat"}),!x&&Ot("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:"\u2318O"})]}),nativeButton:!0}),Ot(Pe,{children:Ot("p",{children:P??"New Chat"})})]})]}),(!y||f||v||C)&&Ot(Ha,{open:n,onOpenChange:o,tempProvider:s,tempModel:a,tempApiKey:i,tempBaseUrl:c,onProviderChange:l,onModelChange:u,onApiKeyChange:p,onBaseUrlChange:d,onSave:g,onClear:m,showClearButton:N??(!!e&&!v&&!C),buttonLabel:e?"Change API Key":"Configure API Key",hostedInspector:f,freeTierInfo:v,managedCloudInfo:C,useManagedCloud:b,onSaveManagedCloud:h})]})]})}import{ArrowUp as DT,Loader2 as _T}from"lucide-react";import{Image as tT,Paperclip as nT,X as oT}from"lucide-react";import{useRef as rT}from"react";import{Wrench as Qk}from"lucide-react";import{useCallback as Xh,useMemo as Zk,useState as eT}from"react";import{jsx as Eo,jsxs as lr}from"react/jsx-runtime";function Qh({tools:e,disabledTools:t,onDisabledToolsChange:n,disabled:o}){let[r,s]=eT(!1),a=e.length-t.size,i=t.size===0,c=t.size>0&&t.size<e.length,l=Xh(d=>{let g=new Set(t);g.has(d)?g.delete(d):g.add(d),n(g)},[t,n]),u=Xh(()=>{n(i?new Set(e.map(d=>d.name)):new Set)},[i,e,n]),p=Zk(()=>[...e].sort((d,g)=>d.name.localeCompare(g.name)),[e]);return e.length===0?null:lr(Go,{open:r,onOpenChange:s,children:[lr(Re,{children:[Eo(Te,{render:Eo(Yo,{render:lr(L,{variant:"ghost",size:"sm",disabled:o,className:S("h-auto gap-1 rounded-full px-2 py-2",c?"text-amber-500 dark:text-amber-400":"text-muted-foreground hover:text-foreground"),type:"button","data-testid":"chat-tool-selector",children:[Eo(Qk,{className:"h-4 w-4 shrink-0"}),c&&Eo("span",{className:"flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-500 px-1 text-[9px] font-bold leading-none text-white",children:a})]}),nativeButton:!0}),nativeButton:!0}),Eo(Pe,{side:"top",children:lr("p",{children:["Tools (",a,"/",e.length,")"]})})]}),lr(Xo,{className:"w-72 gap-0 p-0",align:"start",side:"top",sideOffset:8,children:[lr("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[lr("span",{className:"text-xs font-medium text-muted-foreground",children:["Allowed Tools (",a,"/",e.length,")"]}),Eo(L,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:u,type:"button",children:i?"Disable All":"Enable All"})]}),Eo("div",{className:"max-h-64 overflow-y-auto",children:p.map(d=>{let g=!t.has(d.name);return lr("button",{type:"button",className:"flex items-center gap-2.5 w-full px-3 py-1.5 text-left hover:bg-accent/50 transition-colors cursor-pointer",onClick:()=>l(d.name),children:[Eo(Ta,{checked:g,className:"pointer-events-none",tabIndex:-1}),Eo("span",{className:"min-w-0 flex-1 truncate text-sm font-mono",children:d.name})]},d.name)})})]})]})}import{jsx as In,jsxs as Fa}from"react/jsx-runtime";function Zh({variant:e="default",inputValue:t,isConnected:n,isLoading:o,textareaRef:r,attachments:s,placeholder:a="Ask a question",className:i,showAttachButton:c=!0,tools:l,disabledTools:u,onDisabledToolsChange:p,onInputChange:d,onKeyDown:g,onKeyUp:m,onClick:y,onAttachmentAdd:f,onAttachmentRemove:v,inlineControls:C,trailingControls:b}){let h=Nt(),N=rT(null),P=e==="fullscreen",M=x=>{let E=x.target.files;if(E&&E.length>0)for(let w=0;w<E.length;w++)f(E[w]);N.current&&(N.current.value="")},R=s.length>0;return Fa("div",{className:"relative w-full","data-chat-input-variant":e,children:[!P&&R&&In("div",{className:"absolute top-0 left-0 right-0 z-20 p-3 flex gap-2 flex-wrap",children:s.map((x,E)=>Fa("div",{className:"relative group bg-zinc-100/90 dark:bg-zinc-900/90 backdrop-blur-sm rounded-lg p-2 flex items-center gap-2 border border-zinc-200 dark:border-zinc-700","data-testid":`chat-attachment-${E}`,children:[In(tT,{className:"h-4 w-4 text-muted-foreground shrink-0"}),Fa("div",{className:"flex flex-col min-w-0",children:[In("span",{className:"text-xs font-medium truncate max-w-[150px]",children:x.name||"Image"}),x.size&&In("span",{className:"text-xs text-muted-foreground",children:Gf(x.size)})]}),In("button",{onClick:()=>v(E),className:"shrink-0 p-1 rounded-full hover:bg-zinc-200 dark:hover:bg-zinc-800 transition-colors",title:"Remove attachment",type:"button","data-testid":`chat-attachment-remove-${E}`,children:In(oT,{className:"h-3 w-3"})})]},E))}),In(io,{ref:r,value:t,onChange:x=>d(x.target.value),onKeyDown:g,onKeyUp:m,onClick:y,placeholder:n?a:"Server not connected",className:S(P?"field-sizing-fixed h-11 min-h-11 max-h-11 resize-none overflow-hidden py-2.5 pl-4 pr-12":"p-4 min-h-[150px] max-h-[300px]",h.container,!P&&R&&"pt-20",i),rows:P?1:void 0,disabled:!n||o,"data-testid":"chat-input"}),In("input",{ref:N,type:"file",accept:"image/*",multiple:!0,onChange:M,className:"hidden","aria-label":"Upload images"}),P?b?In("div",{className:"absolute right-1.5 top-1/2 flex -translate-y-1/2 items-center",children:b}):null:Fa("div",{className:"absolute inset-x-0 bottom-0 flex items-center justify-between gap-2 p-3",children:[Fa("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:[c&&In(L,{variant:"ghost",size:"sm",onClick:()=>N.current?.click(),disabled:!n||o,className:"h-auto w-auto aspect-square rounded-full p-2 text-muted-foreground hover:text-foreground",title:"Attach images",type:"button","data-testid":"chat-attach-button",children:In(nT,{className:"h-4 w-4"})}),l&&l.length>0&&u&&p&&In(Qh,{tools:l,disabledTools:u,onDisabledToolsChange:p,disabled:!n||o}),C]}),b?In("div",{className:"flex shrink-0 items-center gap-1.5",children:b}):null]})]})}import{MessageSquare as sT,X as aT}from"lucide-react";import{jsx as $a,jsxs as iT}from"react/jsx-runtime";function ev({promptResults:e,onDeletePromptResult:t,offsetForSkills:n=!1}){return $a("div",{className:`absolute ${n?"top-12":"top-4"} left-4 right-4 flex gap-2 overflow-x-auto z-20 flex-nowrap`,style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:e.map(({promptName:o},r)=>iT(L,{type:"button",className:"flex items-center gap-2 bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 dark:bg-zinc-700 rounded-lg border border-zinc-200 dark:border-zinc-300 font-medium hover:bg-zinc-300 dark:hover:bg-zinc-600",children:[$a(sT,{className:"h-3.5 w-3.5 shrink-0"}),$a("span",{className:"truncate",title:o,children:o}),$a("span",{className:"ml-1 h-4 w-4 rounded-full bg-zinc-400 dark:bg-zinc-600 hover:bg-zinc-500 dark:hover:bg-zinc-500 flex items-center justify-center cursor-pointer shrink-0 transition-colors",onClick:s=>{s.stopPropagation(),t(r)},title:"Remove prompt",role:"button",tabIndex:0,children:$a(aT,{className:"h-2.5 w-2.5 text-white"})})]},r))})}import{MessageSquare as lT}from"lucide-react";import{useEffect as cT}from"react";import{jsx as cr,jsxs as Kl}from"react/jsx-runtime";function tv({isOpen:e,focusedIndex:t,prompts:n,selectedPrompt:o,onPromptSelect:r}){return e?(cT(()=>{if(t>=0){let s=document.getElementById(`prompt-suggestion-${t}`);s&&s.scrollIntoView({behavior:"smooth",block:"nearest"})}},[t]),cr("div",{className:"absolute bottom-full left-0 right-0 max-w-3xl w-full max-h-[300px] overflow-y-auto rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 shadow-lg z-30 flex flex-col gap-2 mb-1","data-testid":"chat-prompts-dropdown",children:Kl("div",{className:"p-2",children:[n.length>0&&cr("div",{className:"text-xs font-medium text-zinc-900 dark:text-zinc-100 mb-2",children:"Prompts"}),n.map((s,a)=>Kl(Re,{children:[cr(Te,{render:Kl(L,{id:`prompt-suggestion-${a}`,type:"button",variant:"ghost",className:S("w-full flex items-center px-3 py-2 rounded-md hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors text-left justify-start",t===a&&"bg-zinc-200 dark:bg-zinc-700"),onClick:()=>r(s),"data-testid":`chat-prompt-option-${a}`,children:[cr("div",{className:"flex items-center justify-center shrink-0",children:cr(lT,{className:"h-4 w-4 text-zinc-600 dark:text-zinc-400"})}),cr("div",{className:"flex-1 min-w-0",children:Kl("div",{className:"text-sm font-medium text-zinc-900 dark:text-zinc-100 flex items-center gap-2",children:[s.name,o?.name===s.name&&cr(kn,{className:"size-3 text-zinc-600 dark:text-zinc-400"})]})})]}),nativeButton:!0}),cr(Pe,{children:s.description})]},a))]})})):null}import{motion as PT}from"motion/react";import{useMemo as gv,useState as hv}from"react";import{ExternalLink as TT}from"lucide-react";import{toast as vv}from"sonner";import{forwardRef as bT,useCallback as wn,useEffect as to,useId as yT,useMemo as ja,useRef as Ao,useState as Jr}from"react";import{AnimatePresence as Os,motion as ho}from"motion/react";import{RadioGroup as xT}from"@base-ui/react/radio-group";import{Radio as wT}from"@base-ui/react/radio";import{CheckboxGroup as CT}from"@base-ui/react/checkbox-group";import{Checkbox as ST}from"@base-ui/react/checkbox";import{Field as Bu}from"@base-ui/react/field";import{useEffect as zu,useLayoutEffect as dT,useRef as Du,useState as uT}from"react";import{AnimatePresence as mT,motion as pT}from"motion/react";import{jsx as ov}from"react/jsx-runtime";var fT=typeof window<"u"?dT:zu,Ds=ae.moderate,Va=.07,gT=(Ds.duration+Va)*1e3+80,hT=Ds.duration*1e3+80;function _u(e,t){let n=t.filter(s=>s.start>=e.start&&s.end<=e.end).sort((s,a)=>s.start-a.start);if(n.length!==2)return null;let[o,r]=n;return r.start===o.end+2?{up:o,lo:r,gap:o.end+1}:null}function vT(e,t,n,o){let r=n[e],s=n[t];if(!r||!s)return null;if(o==="y")return{top:r.top,left:Math.min(r.left,s.left),width:Math.max(r.width,s.width),height:s.top+s.height-r.top};let a=Math.min(r.left,s.left),i=Math.max(r.left+r.width,s.left+s.width);return{top:Math.min(r.top,s.top),left:a,width:i-a,height:Math.max(r.height,s.height)}}function rv(e,t){return t==="y"?e.top+e.height/2:e.left+e.width/2}function Jl(e,t){return t==="y"?[e,e,0,0]:[e,0,0,e]}function dr(e,t){return t==="y"?[0,0,e,e]:[0,e,e,0]}function Ou(e){return[e,e,e,e]}function nv(e,t,n,o,r){let s=rv(n,o);if(o==="y"){let i=t.top+t.height;e.height=s-e.top,e.radii=Jl(r,o),e.instant=!0,t.top=s,t.height=i-s,t.radii=dr(r,o),t.instant=!0,t.enterFrom={top:s,left:t.left,width:t.width,height:i-s,radii:dr(r,o)};return}let a=t.left+t.width;e.width=s-e.left,e.radii=Jl(r,o),e.instant=!0,t.left=s,t.width=a-s,t.radii=dr(r,o),t.instant=!0,t.enterFrom={top:t.top,left:s,width:a-s,height:t.height,radii:dr(r,o)}}function sv(e,t,n,o="y"){let[r,s]=uT([]),a=Du([]),i=Du(0),c=Du(new Map),l=e.map(d=>`${d.id}:${d.start}-${d.end}`).join("|");fT(()=>{let d=a.current,g=e,m=[];for(let f of g){let v=_u(f,d);v&&(f.id===v.up.id||f.id===v.lo.id)&&m.push({tid:++i.current,kind:"merge",survivorId:f.id,otherId:f.id===v.up.id?v.lo.id:v.up.id,gapIndex:v.gap,phase:"converge"})}for(let f of d){let v=_u(f,g);v&&m.push({tid:++i.current,kind:"split",survivorId:v.up.id,otherId:v.lo.id,gapIndex:v.gap,phase:"splitIn"})}a.current=g.map(f=>({...f}));for(let f of m)c.current.set(f.tid,setTimeout(()=>{c.current.delete(f.tid),s(v=>v.some(C=>C.tid===f.tid)?v.flatMap(C=>C.tid!==f.tid?[C]:C.kind==="merge"?[{...C,phase:"commit"}]:[]):v)},f.kind==="merge"?gT:hT));let y=f=>f.kind==="merge"?g.some(v=>v.id===f.survivorId&&f.gapIndex>v.start&&f.gapIndex<v.end):g.some(v=>v.id===f.survivorId&&v.end===f.gapIndex-1)&&g.some(v=>v.id===f.otherId&&v.start===f.gapIndex+1);s(f=>{for(let v of f){if(y(v))continue;let C=c.current.get(v.tid);C!==void 0&&(clearTimeout(C),c.current.delete(v.tid))}return[...f.filter(y),...m]})},[l]),zu(()=>{let d=c.current;return()=>d.forEach(clearTimeout)},[]),zu(()=>{r.some(d=>d.phase==="splitIn"||d.phase==="commit")&&s(d=>d.flatMap(g=>g.phase==="commit"?[]:[{...g,phase:g.phase==="splitIn"?"diverge":g.phase}]))},[r]);let u=[];for(let d of e){let g=vT(d.start,d.end,t,o);g&&u.push({key:`sel-${d.id}`,...g,radii:Ou(n),instant:!1,exitInstant:!1,delayCorners:!1})}let p=new Map(u.map(d=>[d.key,d]));for(let d of r){let g=t[d.gapIndex],m=p.get(`sel-${d.survivorId}`);if(!g||!m)continue;let y=rv(g,o);if(d.kind==="merge"){if(d.phase==="commit"){m.instant=!0,o==="y"?u.push({key:`sel-${d.otherId}`,top:y,left:m.left,width:m.width,height:m.top+m.height-y,radii:dr(n,o),instant:!0,exitInstant:!0,delayCorners:!1,opacity:0}):u.push({key:`sel-${d.otherId}`,top:m.top,left:y,width:m.left+m.width-y,height:m.height,radii:dr(n,o),instant:!0,exitInstant:!0,delayCorners:!1,opacity:0});continue}let f=Math.min(Va+.03,Math.max(Va,Va+y/Math.max(o==="y"?g.height:g.width,1)*.002));if(o==="y"){let v=m.top+m.height;m.height=y-m.top,m.radii=Jl(n,o),m.delayCorners=!0,m.cornerDelay=f,u.push({key:`sel-${d.otherId}`,top:y,left:m.left,width:m.width,height:v-y,radii:dr(n,o),enterFrom:{top:y,left:m.left,width:m.width,height:v-y,radii:Ou(n)},instant:!1,exitInstant:!0,delayCorners:!0,cornerDelay:f})}else{let v=m.left+m.width;m.width=y-m.left,m.radii=Jl(n,o),m.delayCorners=!0,m.cornerDelay=f,u.push({key:`sel-${d.otherId}`,top:m.top,left:y,width:v-y,height:m.height,radii:dr(n,o),enterFrom:{top:m.top,left:y,width:v-y,height:m.height,radii:Ou(n)},instant:!1,exitInstant:!0,delayCorners:!0,cornerDelay:f})}}else if(d.phase==="splitIn"){let f=p.get(`sel-${d.otherId}`);if(!f)continue;nv(m,f,g,o,n)}}for(let d of a.current){let g=_u(d,e),m=g&&t[g.gap];if(!g||!m)continue;let y=p.get(`sel-${g.up.id}`),f=p.get(`sel-${g.lo.id}`);!y||!f||nv(y,f,m,o,n)}return u}function av({blocks:e,dimmed:t}){return ov(mT,{children:e.map(n=>{let o=n.delayCorners?{...Ds,delay:n.cornerDelay??Va}:Ds,r=n.opacity??(t?.8:1);return ov(pT.div,{"aria-hidden":!0,className:"absolute bg-active pointer-events-none",initial:n.enterFrom?{opacity:r,top:n.enterFrom.top,left:n.enterFrom.left,width:n.enterFrom.width,height:n.enterFrom.height,borderTopLeftRadius:n.enterFrom.radii[0],borderTopRightRadius:n.enterFrom.radii[1],borderBottomRightRadius:n.enterFrom.radii[2],borderBottomLeftRadius:n.enterFrom.radii[3]}:!1,animate:{top:n.top,left:n.left,width:n.width,height:n.height,borderTopLeftRadius:n.radii[0],borderTopRightRadius:n.radii[1],borderBottomRightRadius:n.radii[2],borderBottomLeftRadius:n.radii[3],opacity:r},exit:{opacity:0,transition:n.exitInstant?{duration:0}:Ds.exit},transition:n.instant?{duration:0}:{...Ds,borderTopLeftRadius:o,borderTopRightRadius:o,borderBottomRightRadius:o,borderBottomLeftRadius:o,opacity:{duration:.08}}},n.key)})})}import{Fragment as lv,jsx as me,jsxs as Zt}from"react/jsx-runtime";function NT(e,t){return e.id??`q-${t}`}function Gl(e,t){return e.id??`o-${t}`}var _s=[],Uu=bT(function({questions:t,currentIndex:n,defaultCurrentIndex:o=0,onCurrentIndexChange:r,answers:s,defaultAnswers:a,onAnswersChange:i,onComplete:c,onSkip:l,skipLabel:u="Skip",intro:p,onCancel:d,cancelLabel:g="Cancel",footerLeading:m,className:y,...f},v){let[C,b]=Jr(o),h=n!==void 0,N=h?n:C,P=wn(D=>{h||b(D),r?.(D)},[h,r]),[M,R]=Jr(a??{}),x=s!==void 0,E=x?s:M,w=Ao(E);to(()=>{w.current=E},[E]);let k=wn(D=>{let ne=D(w.current);return w.current=ne,x||R(ne),i?.(ne),ne},[x,i]),T=Nt(),A=br("arrow-left"),I=br("arrow-right"),J=ja(()=>function(ne){return me(A,{...ne,className:S(ne.className,"hidden sm:block")})},[A]),B=ja(()=>function(ne){return me(I,{...ne,className:S(ne.className,"hidden sm:block")})},[I]),[G]=Jr(()=>{if(typeof navigator>"u")return!1;let D=navigator,ne=D.userAgentData?.platform||D.platform||"";return/mac/i.test(ne)}),U=yT(),q=t.length,K=Math.max(0,Math.min(N,Math.max(0,q-1))),H=t[K],W=H?NT(H,K):"",oe=E[W],j=!!H?.multiSelect,z=H?.skippable!==!1,$=!!H?.freeText,ie=H?.freeTextMultiline!==!1,fe=!$&&!!H?.allowOther,ue=ja(()=>oe?.selectedIds??[],[oe]),xe=oe?.otherText??"",re=H?.options??[],Se=fe?re.length:-1,Ne=re.length+(fe?1:0),pe=Ao(null),He=!!H;to(()=>{if(!He)return;let D=pe.current;if(D)return _s.push(D),()=>{let ne=_s.indexOf(D);ne!==-1&&_s.splice(ne,1)}},[He]);let Ye=Ao(null),qe=Ao(null),xt=Ao(0),Z=Ao(new Map),{activeIndex:Y,setActiveIndex:_,itemRects:le,sessionRef:De,handlers:We,registerItem:wt,measureItems:dt}=xr(Ye);to(()=>{dt()},[dt,W,Ne,T]);let[Wt,zt]=Jr(!1);to(()=>{zt(!1)},[W]),to(()=>{let D=qe.current;if(!D)return;D.style.height="0px",D.style.height=`${D.scrollHeight}px`;let ne=parseFloat(window.getComputedStyle(D).lineHeight)||18;zt(D.scrollHeight>ne*1.5),dt()},[xe,dt,W]),to(()=>{$&&qe.current?.focus({preventScroll:!0})},[$,W]);let Ke=Ao(null),[En,mn]=Jr("auto");to(()=>{let D=Ke.current;if(!D)return;let ne=()=>mn(D.offsetHeight);ne();let Ie=new ResizeObserver(ne);return Ie.observe(D),()=>Ie.disconnect()},[]);let[Ct,pn]=Jr(null),[Cn,mt]=Jr(null);to(()=>{_(null),pn(null),mt(null)},[K,_]);let te=Ao(!1),Me=wn(()=>{Ye.current?.contains(document.activeElement)&&(te.current=!0)},[]);to(()=>{if(!te.current)return;te.current=!1,Ye.current?.querySelector('[data-proximity-index="0"]')?.focus()},[K]);let ke=wn(D=>{K>=q-1?c?.(D):(Me(),P(K+1))},[K,q,c,P,Me]),rt=wn(D=>{if(!H)return;let ne=w.current[W]?.otherText,Ie=k(gt=>({...gt,[W]:{questionId:W,selectedIds:[D],otherText:ne||void 0,skipped:!1}}));ke(Ie)},[H,W,k,ke]),bt=wn(D=>{H&&k(ne=>{let Ie=ne[W],gt=new Set(Ie?.selectedIds??[]);return gt.has(D)?gt.delete(D):gt.add(D),{...ne,[W]:{questionId:W,selectedIds:Array.from(gt),otherText:Ie?.otherText,skipped:!1}}})},[H,W,k]),en=wn(D=>{H&&k(ne=>({...ne,[W]:{questionId:W,selectedIds:D,otherText:ne[W]?.otherText,skipped:!1}}))},[H,W,k]),ce=wn(D=>{H&&(mt(null),k(ne=>({...ne,[W]:{questionId:W,selectedIds:ne[W]?.selectedIds??[],otherText:D,skipped:!1}})))},[H,W,k]),ve=wn(()=>{if(!H)return;let D=(w.current[W]?.otherText??"").trim();if(!D)return;if(H.freeText&&H.freeTextValidate){let Ie=H.freeTextValidate(D);if(Ie){mt(Ie);return}}mt(null);let ne=k(Ie=>({...Ie,[W]:{questionId:W,selectedIds:Ie[W]?.selectedIds??[],otherText:D,skipped:!1}}));ke(ne)},[H,W,k,ke]),st=wn(()=>{if(!H)return;let D=k(ne=>({...ne,[W]:{questionId:W,selectedIds:ne[W]?.selectedIds??[],otherText:ne[W]?.otherText,skipped:!0}}));l?.(W,K),ke(D)},[H,W,k,l,K,ke]),tt=wn(()=>{d?.()},[d]),O=wn(()=>{ke(E)},[ke,E]),X=wn(()=>{K>0&&(Me(),P(K-1))},[K,P,Me]);to(()=>{if(!H)return;let D=ne=>{if(ne.metaKey||ne.ctrlKey||ne.altKey)return;let Ie=ne.target;if(!Ie)return;let gt=Ie.tagName;if(gt==="INPUT"||gt==="TEXTAREA"||Ie.isContentEditable)return;let Et=pe.current;if(!Et||!Et.contains(Ie)&&(_s.some($t=>$t!==Et&&$t.contains(Ie))||_s[_s.length-1]!==Et))return;let St=ne.key;if(St<"1"||St>"9")return;let Tt=parseInt(St,10)-1;if(Tt>=0&&Tt<re.length){ne.preventDefault();let $t=Gl(re[Tt],Tt);j?bt($t):rt($t)}else Tt===re.length&&fe&&(ne.preventDefault(),qe.current?.focus())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[H,re,j,fe,rt,bt]);let Oe=D=>{Ye.current?.querySelector(`[data-proximity-index="${D}"]`)?.focus()},we=wn(D=>{_(D),fe&&D===Se?qe.current?.focus():Oe(D)},[fe,Se,_]),be=D=>{let ne=D.target,Ie=ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.isContentEditable;if(Ie&&D.key!=="ArrowDown"&&D.key!=="ArrowUp")return;if(Ie&&(D.key==="ArrowUp"||D.key==="ArrowDown")&&ne.tagName==="TEXTAREA"){let Et=ne;if(D.key==="ArrowUp"&&Et.selectionStart>0||D.key==="ArrowDown"&&Et.selectionEnd<Et.value.length)return}let gt=D.preventBaseUIHandler;if(D.key==="ArrowLeft"||D.key==="ArrowRight"){D.preventDefault(),D.stopPropagation(),gt?.(),D.key==="ArrowLeft"?K>0&&X():z&&q>1&&st();return}if(Ne!==0&&(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Home"||D.key==="End")){D.preventDefault(),D.stopPropagation(),gt?.();let Et;if(D.key==="Home")Et=0;else if(D.key==="End")Et=Ne-1;else{let St=Ie?Se:Y??-1;Et=D.key==="ArrowDown"?St+1:St-1,Et=(Et+Ne)%Ne}we(Et)}},ze=D=>{if(D.key!=="Enter"||!(G?D.metaKey:D.ctrlKey)||!(j||$))return;if(D.preventDefault(),$){xe.trim().length>0&&ve();return}(ue.length>0||xe.trim().length>0)&&O()};if(!H)return me("div",{ref:v,className:S("w-full max-w-[520px] p-5 bg-card border border-border",T.container,y),...f,children:me("p",{className:"text-[13px] text-muted-foreground",children:"No questions."})});let _e=Y!==null?le[Y]:null,Qe=Ct!==null&&!(fe&&Ct===Se)?le[Ct]:null,at=ja(()=>{let D=new Set;return re.forEach((ne,Ie)=>{ue.includes(Gl(ne,Ie))&&D.add(Ie)}),fe&&xe.length>0&&D.add(Se),D},[re,ue,fe,xe,Se]),kt=ja(()=>{let D=[],ne=[...at].sort((St,Tt)=>St-Tt);for(let St of ne){let Tt=D[D.length-1];Tt&&St===Tt.end+1?Tt.end=St:D.push({start:St,end:St})}let Ie=new Set,gt=new Map,Et=D.map(St=>{let Tt=null;for(let Kt=St.start;Kt<=St.end;Kt++){let it=Z.current.get(Kt);if(it!==void 0&&!Ie.has(it)){Tt=it;break}}let $t=Tt??++xt.current;Ie.add($t);for(let Kt=St.start;Kt<=St.end;Kt++)gt.set(Kt,$t);return{...St,id:$t}});return Z.current=gt,Et},[at]),es=Y!==null&&!at.has(Y),fr=sv(kt,le,T.bgRadius),fn=q>1&&K>0,tn=d!=null,pt=!tn&&q>1&&z,gr=j||$,si=fn||pt||gr||tn||m!=null,ai=re.findIndex((D,ne)=>ue.includes(Gl(D,ne))),Vs=Zt("div",{ref:Ye,role:j?"group":"radiogroup","aria-labelledby":`${U}-${W}-title`,onMouseEnter:We.onMouseEnter,onMouseMove:We.onMouseMove,onMouseLeave:We.onMouseLeave,onFocus:D=>{let ne=D.target.closest("[data-proximity-index]")?.getAttribute("data-proximity-index");if(ne!=null){let Ie=Number(ne);_(Ie),pn(D.target.matches(":focus-visible")?Ie:null)}},onBlur:D=>{Ye.current?.contains(D.relatedTarget)||(pn(null),_(null))},onKeyDown:be,className:"relative flex flex-col gap-0.5 -mx-3",children:[me(Os,{children:(()=>{if(!fe)return null;let D=le[Se],ne=Ct===Se&&xe.length===0;return!D||!ne?null:me(ho.div,{"aria-hidden":!0,className:S("absolute pointer-events-none bg-card ring-1 ring-inset ring-border",T.bg),initial:{opacity:0,top:D.top,left:D.left,width:D.width,height:D.height},animate:{opacity:1,top:D.top,left:D.left,width:D.width,height:D.height},exit:{opacity:0,transition:ae.fast.exit},transition:{...ae.fast,opacity:{duration:.08}}},"other-input")})()}),me(Os,{children:_e&&me(ho.div,{"aria-hidden":!0,className:S("absolute pointer-events-none bg-hover",T.bg),initial:{opacity:0,top:_e.top,left:_e.left,width:_e.width,height:_e.height},animate:{opacity:1,top:_e.top,left:_e.left,width:_e.width,height:_e.height},exit:{opacity:0,transition:ae.fast.exit},transition:{...ae.fast,opacity:{duration:.08}}},`hover-${De.current}`)}),me(av,{blocks:fr,dimmed:es}),me(Os,{children:Qe&&me(ho.div,{"aria-hidden":!0,className:S("absolute pointer-events-none border border-[color:var(--focus-ring,#6B97FF)] z-20",T.focusRing),initial:{opacity:0,top:Qe.top-2,left:Qe.left-2,width:Qe.width+4,height:Qe.height+4},animate:{opacity:1,top:Qe.top-2,left:Qe.left-2,width:Qe.width+4,height:Qe.height+4},exit:{opacity:0,transition:ae.fast.exit},transition:{...ae.fast,opacity:{duration:.08}}})}),re.map((D,ne)=>{let Ie=Gl(D,ne),gt=ue.includes(Ie),St=!j&&Y===ne;return me(iv,{index:ne,registerItem:wt,role:j?"checkbox":"radio",isSelected:gt,tabIndex:ne===ai||ai===-1&&ne===0?0:-1,onClick:()=>j?bt(Ie):rt(Ie),onKeyDown:Tt=>{(Tt.key===" "||Tt.key==="Enter")&&!Tt.metaKey&&!Tt.ctrlKey&&(Tt.preventDefault(),j?bt(Ie):rt(Ie))},shape:T,"aria-checked":gt,chipContent:ne+1,chipFilled:gt,isMulti:j,showArrow:St,bodyLayout:H.layout==="stacked"?"stacked":"inline",topAlign:H.layout==="stacked",chipPosition:H.chipPosition??"right",arrowIcon:me(I,{size:14,strokeWidth:2,className:"h-3.5 w-3.5"}),hiddenControl:j?me(ST.Root,{name:Ie,className:"sr-only",tabIndex:-1,"aria-hidden":!0}):me(wT.Root,{value:Ie,className:"sr-only",tabIndex:-1,"aria-hidden":!0}),children:H.layout==="stacked"?Zt(lv,{children:[Zt("span",{className:"inline-grid",children:[me("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:Pt.semibold},"aria-hidden":"true",children:D.title}),me("span",{className:"col-start-1 row-start-1 text-foreground transition-[color,font-variation-settings] duration-80",style:{fontVariationSettings:gt?Pt.semibold:Pt.medium},children:D.title})]}),D.description&&me("span",{className:"text-[12px] text-muted-foreground leading-snug",children:D.description})]}):Zt("span",{children:[Zt("span",{className:"inline-grid",children:[me("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:Pt.semibold},"aria-hidden":"true",children:D.title}),me("span",{className:"col-start-1 row-start-1 text-foreground transition-[color,font-variation-settings] duration-80",style:{fontVariationSettings:gt?Pt.semibold:Pt.medium},children:D.title})]}),D.description&&Zt(lv,{children:[" ",me("span",{className:"text-muted-foreground",children:D.description})]})]})},Ie)}),fe&&me(iv,{index:Se,registerItem:wt,role:null,isSelected:xe.length>0,tabIndex:-1,onClick:()=>qe.current?.focus(),shape:T,chipContent:Se+1,chipFilled:xe.length>0,isMulti:j,topAlign:Wt,chipPosition:H.chipPosition??"right",ariaLabel:H.otherPlaceholder??"Describe in your own words",showArrow:!j&&(Ct===Se||Y===Se)&&xe.trim().length>0,arrowIcon:me(I,{size:14,strokeWidth:2,className:"h-3.5 w-3.5"}),onArrowClick:!j&&xe.trim().length>0?ve:void 0,children:me("span",{className:"inline-grid w-full",children:me("textarea",{ref:qe,rows:1,value:xe,placeholder:H.otherPlaceholder??"Describe in your own words\u2026","aria-label":H.otherPlaceholder??"Describe in your own words",onChange:D=>ce(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.shiftKey||j||(D.preventDefault(),ve()))},onClick:D=>D.stopPropagation(),className:S("col-start-1 row-start-1 block w-full bg-transparent border-0 p-0 m-0 outline-none resize-none overflow-hidden text-[13px] leading-snug text-foreground placeholder:text-muted-foreground"),style:{fontVariationSettings:Pt.medium}})})})]});return Zt("div",{ref:D=>{pe.current=D,typeof v=="function"?v(D):v&&(v.current=D)},className:S("relative w-full max-w-[520px] overflow-hidden bg-card border border-border",T.container,y),...f,onKeyDown:D=>{f.onKeyDown?.(D),ze(D)},children:[me("div",{className:"flex items-center px-4 sm:px-5 pt-4 sm:pt-5 pb-2 text-[12px] text-muted-foreground",children:Zt("span",{children:["Question ",K+1," of ",q]})}),p!=null&&me("div",{className:"px-4 sm:px-5 pb-3 text-[13px] leading-snug text-muted-foreground",children:p}),Zt(Bu.Root,{invalid:Cn!==null,className:"contents",children:[me(ho.div,{animate:{height:En},initial:!1,transition:ae.slow,className:"overflow-hidden",children:me("div",{ref:Ke,className:S("px-4 sm:px-5",si?"pb-1":"pb-2.5 sm:pb-3"),children:Zt("div",{className:"flex flex-col gap-2",children:[me("h3",{id:`${U}-${W}-title`,className:"text-[16px] text-foreground leading-snug",style:{fontVariationSettings:Pt.semibold},children:H.title}),$?me("div",{onClick:()=>qe.current?.focus(),className:S("relative mt-1 -mx-3 px-3 py-2.5 cursor-text transition-colors",ie?"min-h-[76px]":"min-h-10",T.bg,xe.length>0?"bg-active":"hover:bg-hover focus-within:bg-card focus-within:ring-1 focus-within:ring-inset focus-within:ring-border"),children:me(Bu.Control,{value:xe,onValueChange:ce,render:me("textarea",{ref:qe,rows:1,placeholder:H.freeTextPlaceholder??"Type your answer\u2026","aria-labelledby":`${U}-${W}-title`,onKeyDown:D=>{D.key==="Enter"&&(D.shiftKey||D.metaKey||D.ctrlKey||ie||(D.preventDefault(),ve()))},className:"block w-full bg-transparent border-0 p-0 m-0 outline-none resize-none overflow-hidden text-[13px] leading-snug text-foreground placeholder:text-muted-foreground",style:{fontVariationSettings:Pt.medium}})})}):j?me(CT,{value:ue,onValueChange:en,render:Vs}):me(xT,{value:ue[0]??null,onValueChange:D=>{typeof D=="string"&&rt(D)},render:Vs})]},W)})}),si&&me("div",{className:"px-4 sm:px-5 pt-1 pb-2",children:Zt("div",{className:"flex items-center justify-between gap-2 -mx-2 sm:-mx-3",children:[Zt("div",{className:"relative flex flex-1 min-w-0 items-center gap-2",children:[m!=null&&me("div",{className:"shrink-0 px-2 sm:px-3",children:m}),me(Os,{mode:"popLayout",initial:!1,children:fn&&me(ho.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ae.fast,opacity:{duration:.1}},children:me(L,{variant:"ghost",size:"sm",leadingIcon:J,onClick:X,className:"pl-3 sm:pl-[6px]",children:"Back"})},"back")}),Cn&&me(Bu.Error,{match:!0,render:me(ho.p,{role:"alert",initial:{opacity:0,y:-2},animate:{opacity:1,y:0},transition:{...ae.fast,opacity:{duration:.12}},className:"min-w-0 px-2 sm:px-3 text-left text-[12px] leading-snug text-destructive"}),children:Cn},"ft-error")]}),me("div",{className:"relative flex items-center gap-2",children:Zt(Os,{mode:"popLayout",initial:!1,children:[tn&&me(ho.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ae.fast,opacity:{duration:.1}},children:me(L,{variant:"ghost",size:"sm",trailingIcon:B,onClick:tt,className:"pr-3 sm:pr-[6px]",children:g})},"cancel"),pt&&me(ho.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ae.fast,opacity:{duration:.1}},children:me(L,{variant:"ghost",size:"sm",trailingIcon:B,onClick:st,className:"pr-3 sm:pr-[6px]",children:u})},"skip"),gr&&me(ho.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ae.fast,opacity:{duration:.1}},children:me(L,{variant:"primary",size:"sm",onClick:$?ve:O,disabled:($||ue.length===0)&&xe.trim().length===0,className:"pr-3 sm:pr-[6px]",children:Zt("span",{className:"inline-flex items-center gap-1.5",children:[H.nextLabel??(K>=q-1?"Finish":"Continue"),me("span",{className:"hidden sm:contents",children:Zt(kT,{shape:T,tone:"inverted",children:[G?"\u2318":"\u2303","\u21B5"]})})]})})},"continue")]})})]})})]})]})});Uu.displayName="AskUserQuestions";function kT({children:e,tone:t="muted",shape:n}){return me("kbd",{"aria-hidden":!0,suppressHydrationWarning:!0,className:S("inline-flex items-center justify-center gap-0.5 px-1 min-w-[18px] h-[18px] text-[11px] leading-none font-sans tracking-wide",t==="inverted"?"bg-background/15 text-background":"bg-foreground/10 text-muted-foreground",n.bg),children:e})}function iv({index:e,registerItem:t,role:n,isSelected:o,tabIndex:r,onClick:s,onKeyDown:a,shape:i,chipContent:c,chipFilled:l,isMulti:u,ariaLabel:p,showArrow:d,arrowIcon:g,onArrowClick:m,bodyLayout:y="inline",topAlign:f=!1,chipPosition:v="right",hiddenControl:C,children:b,...h}){let N=Ao(null);to(()=>(t(e,N.current),()=>t(e,null)),[e,t]);let P=me(Os,{children:d&&me(ho.span,{"aria-hidden":!m,role:m?"button":void 0,onClick:m?x=>{x.stopPropagation(),m()}:void 0,className:S("absolute inset-0 inline-flex items-center justify-center bg-foreground text-background",i.bg,m&&"cursor-pointer"),initial:{opacity:0,scale:.6},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.6,transition:ae.fast.exit},transition:{...ae.fast,opacity:{duration:.08}},children:g})}),M=Zt("span",{className:S("shrink-0 w-7 h-7 relative inline-flex items-center justify-center",f&&(y==="stacked"?"-mt-[1px]":"-mt-[5px]")),children:[me("span",{"aria-hidden":!0,className:S("absolute inline-flex items-center justify-center w-5 h-5 text-[11px] transition-[opacity,font-variation-settings] duration-80",u&&i.bg,u?l?"bg-foreground text-background":"border border-border text-muted-foreground":l?"text-foreground":"text-muted-foreground",v==="right"&&d&&"opacity-0"),style:{fontVariationSettings:l?Pt.semibold:Pt.medium},children:c}),v==="right"&&P]}),R=v==="left"&&!u&&me("span",{className:S("shrink-0 w-7 h-7 relative inline-flex items-center justify-center",f&&(y==="stacked"?"-mt-[1px]":"-mt-[5px]")),children:P});return Zt("div",{ref:N,"data-proximity-index":e,"data-state":o?"checked":"unchecked",role:n??void 0,"aria-checked":n==="radio"||n==="checkbox"?!!h["aria-checked"]:void 0,"aria-label":p,tabIndex:r,onMouseDown:x=>{let E=x.target.closest('button:not([tabindex="-1"]), a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])');E&&E!==x.currentTarget||(x.preventDefault(),x.currentTarget.focus())},onClick:s,onKeyDown:a,className:S("relative z-10 flex cursor-pointer select-none outline-none",v==="left"?"gap-2":"gap-3",f?"items-start":"items-center",y==="stacked"?"min-h-14 py-2":"min-h-10 py-1.5",v==="left"?u?"pl-1.5 pr-3":"pl-1.5 pr-1.5":"pl-3 pr-1.5",i.item),children:[v==="left"&&M,me("span",{className:S("min-w-0 flex-1 text-[13px] leading-snug",y==="stacked"?"flex flex-col gap-0.5":"inline-flex items-center gap-0"),children:b}),v==="right"?M:R,C]})}function Yl(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.const=="string"&&(t.title===void 0||typeof t.title=="string")}function cv(e){let t=Array.isArray(e.oneOf)?e.oneOf.filter(Yl):[],n=Array.isArray(e.anyOf)?e.anyOf.filter(Yl):[];return t.length>0?t:n}function dv(e){let t=e.items&&typeof e.items=="object"?e.items:{},n=Array.isArray(t.anyOf)?t.anyOf.filter(Yl):[],o=Array.isArray(t.oneOf)?t.oneOf.filter(Yl):[];return n.length>0?n:o}function uv(e){if(e.mode==="url"&&"url"in e)return[{id:"__url_confirm__",title:"Confirm completion",layout:"stacked",options:[{id:"confirmed",title:"I've completed the required action",description:e.url}],skippable:!1,nextLabel:"Confirm"}];let t="requestedSchema"in e?e.requestedSchema:void 0;if(!t||t.type!=="object"||!t.properties)return[{id:"__freeform__",title:"Your response",freeText:!0,freeTextPlaceholder:"Type your response\u2026",skippable:!1}];let n=t.properties,o=t.required??[];return Object.entries(n).map(([r,s])=>{let a=s,i=o.includes(r),c=a.title||r,l=a.description,u=a.type||"string",p=cv(a),d=dv(a),g=Array.isArray(a.enum),m=u==="array"&&Array.isArray(a.items?.enum),y=u==="array"&&d.length>0,f={id:r,title:c,skippable:!i,layout:l&&l.length>60?"stacked":"inline"};if(u==="boolean")return{...f,options:[{id:"true",title:"Yes"},{id:"false",title:"No"}]};if(y||m){let v=y?d:a.items.enum.map(C=>({const:C,title:C}))??[];return{...f,multiSelect:!0,options:v.map(C=>({id:C.const,title:C.title||C.const}))}}if(p.length>0)return{...f,layout:"stacked",options:p.map(v=>({id:v.const,title:v.title||v.const}))};if(g){let v=a.enum,C=a.enumNames;return{...f,options:v.map((b,h)=>({id:b,title:C?.[h]||b}))}}return u==="number"||u==="integer"?{...f,freeText:!0,freeTextMultiline:!1,freeTextPlaceholder:a.default!==void 0?String(a.default):"Enter a number\u2026",freeTextValidate:v=>{let C=v.trim();if(!C)return i?"Required":null;let b=u==="integer"?parseInt(C,10):parseFloat(C);return Number.isNaN(b)?"Enter a valid number":null}}:u==="string"&&(a.format==="textarea"||(a.maxLength??0)>100)?{...f,freeText:!0,freeTextPlaceholder:a.default||"Type your answer\u2026"}:{...f,freeText:!0,freeTextMultiline:!1,freeTextPlaceholder:a.default!==void 0?String(a.default):"Type your answer\u2026",freeTextValidate:v=>!v.trim()&&i?"Required":null}})}function mv(e,t,n){if(n.mode==="url")return{};let o="requestedSchema"in n?n.requestedSchema:void 0,r=o?.type==="object"&&o.properties?o.properties:{},s={};for(let a of e){let i=a.id??"";if(i==="__freeform__"){let p=t[i]?.otherText?.trim();p&&(s.response=p);continue}let c=t[i];if(!c||c.skipped)continue;let u=r[i]?.type||"string";if(a.freeText){let p=c.otherText?.trim()??"";if(!p)continue;s[i]=u==="number"||u==="integer"?u==="integer"?parseInt(p,10):parseFloat(p):p;continue}if(a.multiSelect){s[i]=c.selectedIds;continue}if(u==="boolean"){s[i]=c.selectedIds[0]==="true";continue}c.selectedIds[0]!==void 0&&(s[i]=c.selectedIds[0])}return s}function pv(e,t,n){if(n.mode==="url")return[];let o="requestedSchema"in n?n.requestedSchema:void 0;return(o?.type==="object"?o.required??[]:[]).filter(s=>{let a=t[s];if(!a||a.skipped)return!0;let i=e.find(c=>c.id===s);return i?i.freeText?!a.otherText?.trim():(i.multiSelect,a.selectedIds.length===0):!0})}function fv(e,t){if(t.mode==="url")return{};let n="requestedSchema"in t?t.requestedSchema:void 0,o=n?.type==="object"&&n.properties?n.properties:{},r={};for(let s of e){let a=s.id;if(!a||a.startsWith("__"))continue;let i=o[a];if(!(!i||i.default===void 0)){if(s.freeText){r[a]={questionId:a,selectedIds:[],otherText:String(i.default),skipped:!1};continue}if(s.multiSelect&&Array.isArray(i.default)){r[a]={questionId:a,selectedIds:i.default.map(String),skipped:!1};continue}if(i.type==="boolean"){r[a]={questionId:a,selectedIds:[String(i.default)],skipped:!1};continue}r[a]={questionId:a,selectedIds:[String(i.default)],skipped:!1}}}return r}import{jsx as qa,jsxs as Xl}from"react/jsx-runtime";function bv({request:e,onApprove:t,onReject:n,testId:o="inline-elicitation",actionTestIdPrefix:r="inline-elicitation"}){let[s,a]=hv(!1),[i,c]=hv(""),l=gv(()=>uv(e.request),[e.request]),u=gv(()=>fv(l,e.request),[l,e.request]),d=(e.request.mode||"form")==="url",g=d&&"url"in e.request?e.request.url:void 0,m=(v,C)=>{a(!0),c(v),t(e.id,C)},y=v=>{if(s)return;if(d){if(!v.__url_confirm__?.selectedIds.includes("confirmed")){vv.error("Confirm you've completed the external action");return}m("accepted",{action:"accept"});return}let C=pv(l,v,e.request);if(C.length>0){vv.error("Missing required fields",{description:`Please fill in: ${C.join(", ")}`});return}m("accepted",{action:"accept",content:mv(l,v,e.request)})};if(s)return Xl("p",{className:"text-sm text-muted-foreground","data-testid":`${o}-responded`,children:["Elicitation ",i," \u2014 the tool will continue executing."]});let f=Xl("div",{className:"space-y-2",children:[qa("p",{className:"text-foreground/90",children:e.request.message}),d&&g&&Xl("div",{className:"flex items-center gap-2 rounded-md border bg-muted/40 p-2",children:[qa("code",{className:"flex-1 text-xs font-mono break-all",children:g}),Xl(L,{size:"sm",variant:"outline",onClick:()=>window.open(g,"_blank"),"data-testid":`${r}-open-url`,children:[qa(TT,{className:"h-3 w-3 mr-1"}),"Open"]})]})]});return qa(Uu,{questions:l,defaultAnswers:u,onComplete:y,intro:f,onCancel:()=>n(e.id,"User cancelled elicitation request"),cancelLabel:"Cancel",footerLeading:qa("button",{type:"button",className:"shrink-0 cursor-pointer text-[12px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",onClick:()=>m("declined",{action:"decline"}),"data-testid":`${r}-decline-button`,children:"Decline"}),className:"w-full max-w-none shadow-lg","data-testid":o})}import{jsx as Hu}from"react/jsx-runtime";function yv({requests:e,onApprove:t,onReject:n}){return e.length===0?null:Hu("div",{className:"mb-3 space-y-3 pointer-events-auto","data-testid":"floating-elicitation-stack",children:e.map(o=>Hu(PT.div,{initial:{opacity:0,y:12,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.98},transition:ae.moderate,children:Hu(bv,{request:o,onApprove:t,onReject:n})},o.id))})}import{Check as RT,Loader2 as MT,Settings2 as IT}from"lucide-react";import{useCallback as ET,useEffect as AT,useState as Fu}from"react";var Gr="You are a helpful assistant with access to MCP tools. Help users interact with the MCP server.";import{jsx as no,jsxs as Wa}from"react/jsx-runtime";function LT(e){let t=e?.trim();return t?t!==Gr:!1}function xv({value:e,onSave:t,disabled:n,isSaving:o=!1,compact:r=!1}){let[s,a]=Fu(!1),[i,c]=Fu(e??""),[l,u]=Fu(!1);AT(()=>{c(e??"")},[e]);let p=ET(async()=>{u(!0);try{await t(i),a(!1)}finally{u(!1)}},[i,t]),d=o||l,g=LT(e),m=Wa("button",{type:"button","data-testid":"chat-system-prompt-button",onClick:()=>a(!0),disabled:n,className:r?S("inline-flex h-auto w-auto aspect-square items-center justify-center rounded-full p-2 transition-colors disabled:pointer-events-none disabled:opacity-50",g?"text-amber-500 dark:text-amber-400":"text-muted-foreground hover:text-foreground"):S("inline-flex h-9 items-center justify-center gap-1.5 rounded-full border border-input bg-secondary px-3 text-sm font-medium shadow-xs transition-colors hover:bg-secondary/80 disabled:pointer-events-none disabled:opacity-50",g?"text-amber-600 dark:text-amber-400":"text-secondary-foreground"),children:[no(IT,{className:"h-4 w-4"}),!r&&no("span",{className:"hidden sm:inline",children:"System Prompt"})]});return Wa(Sn,{open:s,onOpenChange:a,children:[r?Wa(Re,{children:[no(Te,{render:m,nativeButton:!0}),no(Pe,{side:"top",children:no("p",{children:g?"Custom system prompt":"System Prompt"})})]}):m,Wa(gn,{className:"sm:max-w-xl",children:[no(sn,{children:no(nn,{children:"System Prompt"})}),no(io,{value:i,onChange:y=>c(y.target.value),placeholder:"Describe the assistant's behavior...",className:"min-h-[160px] text-sm"}),no(Ri,{children:Wa(L,{size:"sm",onClick:p,disabled:d||i===(e??""),className:"gap-1.5",children:[d?no(MT,{className:"h-3.5 w-3.5 animate-spin"}):no(RT,{className:"h-3.5 w-3.5"}),"Save"]})})]})]})}import{Fragment as wv,jsx as un,jsxs as Ql}from"react/jsx-runtime";function Ka({variant:e="default",inputValue:t,isConnected:n,isLoading:o,textareaRef:r,llmConfig:s,promptsDropdownOpen:a,promptFocusedIndex:i,prompts:c,selectedPrompt:l,promptResults:u,attachments:p,tools:d,disabledTools:g,onDisabledToolsChange:m,onInputChange:y,onKeyDown:f,onKeyUp:v,onClick:C,onSendMessage:b,onStopStreaming:h,onConfigDialogOpenChange:N,onPromptSelect:P,onDeletePromptResult:M,onAttachmentAdd:R,onAttachmentRemove:x,hideModelBadge:E,freeTierInfo:w,managedCloudInfo:k,modelBadgeMode:T="byok",modelDisplayName:A,followups:I=[],onFollowupSelect:J,pendingElicitationRequests:B,onApproveElicitation:G,onRejectElicitation:U,systemPromptProvider:q}){let K=e==="fullscreen",H=t.trim()||u.length>0||p.length>0,W=(B?.length??0)>0,oe=s&&(!E||w||k)?Ql(Re,{children:[un(Te,{render:un(Mh,{provider:s.provider,model:s.model,displayName:A,mode:T,className:"shrink-0",onClick:()=>N(!0)}),nativeButton:!0}),un(Pe,{children:un("p",{children:k||w?"Change model":"Change API Key"})})]}):null;return un("div",{className:S("w-full flex shrink-0 flex-col items-center px-2 pt-0 sm:px-4 text-foreground",K?"pb-4 sm:pb-4":"pb-2 sm:pb-2"),children:Ql("div",{className:S("relative w-full max-w-3xl",!K&&"backdrop-blur-xl"),children:[!K&&W&&G&&U&&un(yv,{requests:B,onApprove:G,onReject:U}),!K&&I.length>0&&un("div",{className:"mb-2 flex flex-wrap gap-2",children:I.map(j=>un(L,{type:"button",variant:"outline",size:"sm",className:"rounded-full",onClick:()=>J?.(j),disabled:o||!n,children:j},j))}),!K&&Ql(wv,{children:[un(tv,{isOpen:a,prompts:c,selectedPrompt:l,focusedIndex:i,onPromptSelect:P}),un(ev,{promptResults:u,onDeletePromptResult:M})]}),un(Zh,{variant:e,inputValue:t,isConnected:n,isLoading:o,textareaRef:r,attachments:p,placeholder:"Ask a question or request an action...",className:S("bg-white/80 dark:text-white dark:bg-black backdrop-blur-sm border-gray-200 dark:border-zinc-800",!K&&u.length>0&&"pt-16"),showAttachButton:!K,tools:K?void 0:d,disabledTools:K?void 0:g,onDisabledToolsChange:K?void 0:m,onInputChange:y,onKeyDown:f,onKeyUp:v,onClick:C,onAttachmentAdd:R,onAttachmentRemove:x,inlineControls:!K&&s&&q?un(xv,{compact:!0,value:q.prompt,onSave:q.savePrompt,disabled:!n||o||q.disabled,isSaving:q.isSaving}):null,trailingControls:Ql(wv,{children:[!K&&oe,un(L,{type:"button",size:"sm",className:S("h-8 w-8 rounded-full p-0",o&&"animate-spin",!H&&!o&&"bg-zinc-400"),disabled:!o&&(!H||!n||W),title:o?"Stop streaming":"Send",onClick:o?h:b,"data-testid":"chat-send-button",children:o?un(_T,{className:"h-3.5 w-3.5 animate-spin"}):un(DT,{className:"h-3.5 w-3.5"})})]})})]})})}import{AnimatePresence as OT,motion as zT,useInView as BT}from"motion/react";import{useRef as UT}from"react";import{jsx as Cv}from"react/jsx-runtime";function Sv({children:e,className:t,variant:n,duration:o=.4,delay:r=0,offset:s=6,direction:a="down",inView:i=!1,inViewMargin:c="-50px",blur:l="6px",...u}){let p=UT(null),d=BT(p,{once:!0,margin:c}),g=!i||d,m={hidden:{[a==="left"||a==="right"?"x":"y"]:a==="right"||a==="down"?-s:s,opacity:0,filter:`blur(${l})`},visible:{[a==="left"||a==="right"?"x":"y"]:0,opacity:1,filter:"blur(0px)"}},y=n||m;return Cv(OT,{children:Cv(zT.div,{ref:p,initial:"hidden",animate:g?"visible":"hidden",exit:"hidden",variants:y,transition:{delay:.04+r,duration:o,ease:"easeOut"},className:t,...u,children:e})})}import{jsx as Ja,jsxs as Zl}from"react/jsx-runtime";function $u({serverDisplayName:e,composerNotice:t,quickQuestions:n=[],onQuickQuestionSelect:o,...r}){return Ja("div",{className:"flex h-full flex-col items-center justify-center",children:Zl(Sv,{className:"w-full max-w-4xl mx-auto px-2 sm:px-4",children:[Zl("div",{className:"text-center mb-6 sm:mb-8",children:[Zl("h1",{className:"text-2xl sm:text-4xl font-light mb-2 dark:text-white","data-testid":"chat-landing-header",children:["Chat with ",e]}),Ja("p",{className:"mx-auto max-w-xl text-sm text-muted-foreground sm:text-base","data-testid":"chat-landing-description",children:"Chat, inspect traces, preview widgets, and more."})]}),Zl("div",{className:"space-y-6",children:[t,Ja(Ka,{...r}),n.length>0&&Ja("div",{className:"flex flex-wrap items-center justify-center gap-2 px-2",children:n.map(s=>Ja(L,{type:"button",variant:"outline",size:"sm",className:"rounded-full bg-white/70 dark:bg-black/50 text-gray-900 dark:text-white",onClick:()=>o?.(s),disabled:r.isLoading||!r.isConnected,children:s},s))})]})]})})}import{Key as HT,Settings as FT}from"lucide-react";import{jsx as ec,jsxs as Nv}from"react/jsx-runtime";function Vu({onConfigureClick:e}){return Nv("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[ec(HT,{className:"h-12 w-12 text-muted-foreground mb-4"}),ec("h3",{className:"text-lg font-semibold mb-2",children:"Configure Your LLM Provider"}),ec("p",{className:"text-sm text-muted-foreground mb-4 max-w-md",children:"To start chatting with the MCP server, you need to configure your LLM provider and API key. Your credentials are stored locally and used only for this chat."}),Nv(L,{onClick:e,"data-testid":"chat-configure-api-key-button",children:[ec(FT,{className:"h-4 w-4 mr-2"}),"Configure API Key"]})]})}import{motion as $T}from"motion/react";import{useMemo as VT}from"react";import{jsx as jT}from"react/jsx-runtime";function kv({children:e,as:t="p",className:n,duration:o=2,spread:r=2}){let s=$T.create(t),a=VT(()=>e.length*r,[e,r]);return jT(s,{className:S("relative inline-block bg-[length:250%_100%,auto] bg-clip-text","text-transparent [--base-color:#a1a1aa] [--base-gradient-color:#000]","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]","dark:[--base-color:#71717a] dark:[--base-gradient-color:#ffffff] dark:[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))]",n),initial:{backgroundPosition:"100% center"},animate:{backgroundPosition:"0% center"},transition:{repeat:1/0,duration:o,ease:"linear"},style:{"--spread":`${a}px`,backgroundImage:"var(--bg), linear-gradient(var(--base-color), var(--base-color))"},children:e})}import{memo as hP,useCallback as vP,useMemo as bP,useRef as Zu}from"react";import{memo as qT,useMemo as WT}from"react";import{jsx as Tv,jsxs as JT}from"react/jsx-runtime";function KT(e){let t=e.match(/```/g);return t&&t.length%2===1?`${e}
|
|
202
202
|
\`\`\``:e}var Pv=qT(function({content:t,isStreaming:n=!1}){let o=WT(()=>n?KT(t):t,[t,n]);return JT("div",{children:[Tv(Ts,{className:S("text-[14px] leading-relaxed text-foreground","[&_p]:mb-2 [&_p:last-child]:mb-0","[&_pre]:my-3 [&_ul]:mb-2 [&_ol]:mb-2"),content:o}),n?Tv("span",{className:"inline-block w-0.5 h-[1em] ml-0.5 -mt-1 align-middle bg-foreground/60 animate-pulse","aria-hidden":!0}):null]})});import{forwardRef as tP}from"react";import{motion as nP}from"motion/react";import{useEffect as GT,useState as YT}from"react";function Rv(){let[e,t]=YT(!1);return GT(()=>{if(typeof window>"u")return;let n=new AbortController,{signal:o}=n,r=()=>{let a="ontouchstart"in window||navigator.maxTouchPoints>0,i=window.matchMedia("(pointer: coarse)").matches;t(a&&i)};return window.matchMedia("(pointer: coarse)").addEventListener("change",r,{signal:o}),window.addEventListener("pointerdown",r,{signal:o}),r(),()=>n.abort()},[]),e}import{useEffect as XT,useState as QT}from"react";import{jsx as ur,jsxs as eP}from"react/jsx-runtime";function ZT({size:e}){return eP("svg",{width:Math.max(16,e*.35),height:Math.max(16,e*.35),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[ur("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"}),ur("path",{d:"M14 3v5h5"})]})}function Mv({file:e,size:t,className:n}){let o=Nt(),r=e.type.startsWith("image/"),[s,a]=QT(null);XT(()=>{if(!r){a(null);return}let c=URL.createObjectURL(e);return a(c),()=>URL.revokeObjectURL(c)},[r,e]);let i=r&&!s;return ur("div",{className:S("relative shrink-0 overflow-hidden bg-accent border border-border",o.bg,n),style:{width:t,height:t},children:s?ur("img",{src:s,alt:e.name,className:"absolute inset-0 w-full h-full object-cover"}):i?ur("div",{className:"absolute inset-0 flex items-center justify-center",children:ur("div",{className:"w-6 h-6 rounded-full border-2 border-border border-t-muted-foreground animate-spin","aria-label":"Loading preview",role:"status"})}):ur("div",{className:"absolute inset-0 flex items-center justify-center text-muted-foreground",role:"img","aria-label":e.name,children:ur(ZT,{size:t})})})}import{jsx as Ga,jsxs as Iv}from"react/jsx-runtime";var Ya=tP(({from:e,files:t,thumbnailSize:n=64,time:o,actions:r,children:s,className:a,...i},c)=>{let l=Nt(),u=e==="user",p=Rv(),d=u&&o!=null;return Iv(nP.div,{ref:c,layout:"position",initial:{opacity:0,y:8,scale:.96},animate:{opacity:1,y:0,scale:1},transition:ae.moderate,style:{transformOrigin:u?"bottom right":"bottom left"},className:S("group flex max-w-[80%] flex-col gap-1.5",u?"items-end self-end":"items-start self-start",a),...i,children:[t&&t.length>0&&Ga("div",{className:S("flex flex-wrap gap-1.5",u?"justify-end":"justify-start"),children:t.map((g,m)=>Ga(Mv,{file:g,size:n},`${g.name}-${g.size}-${g.lastModified}-${m}`))}),s!=null&&s!==""&&Ga("div",{className:S("py-2 text-[14px] whitespace-pre-wrap break-words",u?S(l.bg,"px-3.5 text-pretty bg-[color-mix(in_oklab,var(--accent),var(--background)_45%)] text-accent-foreground"):"text-foreground"),children:s}),(d||r!=null)&&Iv("div",{className:S("flex items-center gap-2 px-1 text-[12px] leading-none text-muted-foreground select-none",!p&&["opacity-0 pointer-events-none transition-opacity duration-150","group-hover:opacity-100 group-hover:pointer-events-auto","group-focus-within:opacity-100 group-focus-within:pointer-events-auto"]),children:[d&&Ga("span",{className:"tabular-nums",children:o}),r!=null&&Ga("span",{className:"flex items-center gap-0.5",children:r})]})]})});Ya.displayName="ChatMessage";import{Check as oP,Copy as rP}from"lucide-react";import{useState as sP}from"react";import{jsx as ju}from"react/jsx-runtime";function Ev({text:e}){let[t,n]=sP(!1);return ju("button",{type:"button",className:"text-muted-foreground hover:text-foreground flex items-center rounded p-0.5",onClick:async()=>{await ct(e),n(!0),setTimeout(()=>n(!1),2e3)},title:"Copy message content","data-testid":"copy-button",children:t?ju(oP,{className:"h-3.5 w-3.5"}):ju(rP,{className:"h-3.5 w-3.5"})})}import{Fragment as Dv,jsx as Lv,jsxs as _v}from"react/jsx-runtime";function Av(e,t){let n=e===1?"token":"tokens";return`${e.toLocaleString()} ${n} ${t}`}function tc({variant:e,copyText:t,inputTokens:n,outputTokens:o}){let r=!!t,s=e==="user"&&n!=null?Av(n,"in"):e==="assistant"&&o!=null?Av(o,"out"):null;if(!r&&!s)return null;let a=r?Lv(Ev,{text:t}):null,i=s?Lv("span",{className:"tabular-nums",title:e==="user"?"Input tokens":"Output tokens","data-testid":e==="user"?"message-input-tokens":"message-output-tokens",children:s}):null;return e==="user"?_v(Dv,{children:[i,a]}):_v(Dv,{children:[a,i]})}import{jsx as nc,jsxs as aP}from"react/jsx-runtime";function qu({content:e,timestamp:t,_isStreaming:n,outputTokens:o}){return!e||e.length===0?null:aP("div",{"data-testid":"chat-message-assistant",children:[nc(Ya,{from:"assistant",actions:nc(tc,{variant:"assistant",copyText:e,outputTokens:o}),"data-testid":"chat-message-content",children:nc(Pv,{content:e,isStreaming:n})}),t!=null&&nc("span",{className:"sr-only",children:new Date(t).toLocaleTimeString()})]})}import{Check as Ov,Copy as Wu,Loader2 as Ku,LockKeyhole as Ju,Wrench as zv,X as iP}from"lucide-react";import{jsx as et,jsxs as Ht}from"react/jsx-runtime";function Gu({toolName:e,args:t,result:n,state:o="result",partialArgs:r,onAuthenticate:s,isAuthenticating:a=!1,authorizationError:i,toolCallId:c}){let l=o==="call"&&r?r:t,u=()=>{switch(o){case"call":return et(Ku,{className:"h-4 w-4 animate-spin text-blue-500 dark:text-blue-400"});case"authorization-required":return et(Ju,{className:"h-4 w-4 text-amber-700 dark:text-amber-300"});case"result":return et(Ov,{className:"h-4 w-4 text-emerald-800 dark:text-emerald-400"});case"error":return et(iP,{className:"h-4 w-4 text-red-500 dark:text-red-400"});default:return et(Ov,{className:"h-4 w-4 text-emerald-800 dark:text-emerald-400"})}},p=()=>{switch(o){case"call":return" bg-blue-500/20 dark:bg-blue-500/20";case"authorization-required":return" bg-amber-400/30 dark:bg-amber-500/25";case"result":return" bg-emerald-500/20 dark:bg-emerald-500/20";case"error":return" bg-red-500/20 dark:bg-red-500/20";default:return" bg-emerald-500/20 dark:bg-emerald-500/20"}},d=g=>typeof g=="object"?ol(g).preview:String(g);return Ht("div",{className:"my-4 flex w-fit max-w-full flex-col items-start gap-2",children:[Ht(gs,{children:[et(Xi,{render:Ht("div",{className:S("flex max-w-min items-center gap-3 rounded-full border p-1 transition-colors cursor-pointer",o==="authorization-required"?"border-amber-400/70 bg-amber-50 hover:bg-amber-100 dark:border-amber-500/50 dark:bg-amber-950/40 dark:hover:bg-amber-950/60":"bg-card hover:bg-accent/50"),"data-testid":`chat-tool-call-${e}`,children:[et("div",{className:"w-8 h-8 rounded-full bg-zinc-100 dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 flex items-center justify-center shrink-0",children:et(zv,{className:"size-4 text-muted-foreground"})}),et("div",{className:"flex-1 min-w-0",children:et("div",{className:"flex items-center gap-2",children:Ht("span",{className:"text-sm font-medium truncate",children:[e,"(",Object.keys(l).length>0?Ht("span",{className:"bg-muted-foreground/20 rounded-full px-1.5 mx-1 py-0.5 text-xs",children:[Object.keys(l).length," args"]}):"",")"]})})}),et("div",{className:S("w-8 h-8 rounded-full flex items-center justify-center",p()),"data-testid":`chat-tool-call-status-${o}`,children:u()})]}),nativeButton:!1}),Ht(hs,{side:"right",className:"w-[400px] sm:w-[540px] p-4 overflow-y-auto","data-testid":"chat-tool-drawer",children:[Ht(Qi,{children:[Ht(Zi,{className:"flex items-center gap-2",children:[et(zv,{className:"h-5 w-5"}),"Tool Call Details"]}),Ht(Ef,{className:"flex items-center gap-2",children:[e," \u2014 ",o,o==="call"&&Ht("span",{className:"flex items-center gap-1 text-blue-500 dark:text-blue-400",children:[et(Ku,{className:"h-3 w-3 animate-spin"}),"streaming\u2026"]}),o==="authorization-required"&&Ht("span",{className:"flex items-center gap-1 text-amber-700 dark:text-amber-300",children:[et(Ju,{className:"h-3 w-3"}),"authentication required"]})]})]}),Ht("div",{className:"flex flex-col gap-6 py-4",children:[Ht("div",{children:[et("h3",{className:"text-sm font-medium mb-2",children:"Arguments"}),Ht("div",{className:"relative","data-testid":"chat-tool-drawer-args",children:[et("pre",{className:"text-xs bg-muted/50 rounded-lg p-3 overflow-x-auto border font-mono leading-relaxed max-h-48 whitespace-pre-wrap break-words",children:d(l)}),et(L,{variant:"ghost",size:"sm",onClick:()=>ct(d(l)),className:"absolute top-2 right-2 h-6 w-6 p-0 opacity-70 hover:opacity-100",title:"Copy arguments",children:et(Wu,{className:"h-3 w-3"})})]})]}),n&&Ht("div",{children:[et("h3",{className:"text-sm font-medium mb-2",children:"Result"}),et("div",{className:"relative","data-testid":"chat-tool-drawer-result",children:typeof n=="string"?Ht("div",{className:S("p-3 rounded-lg border text-sm leading-relaxed max-h-48 overflow-x-auto whitespace-pre-wrap break-words max-w-full",o==="error"?"bg-destructive/10 border-destructive/20 text-destructive-foreground":"bg-muted/30 border-border"),children:[n.startsWith("Error")?Ht("div",{className:"font-mono",children:[et("div",{className:"font-semibold text-destructive mb-1",children:"Error:"}),et("div",{className:"whitespace-pre-wrap break-words",children:n.replace(/^Error:\s*/,"")})]}):et("div",{className:"whitespace-pre-wrap font-mono break-words",children:n}),et(L,{variant:"ghost",size:"sm",onClick:()=>ct(n),className:"absolute top-2 right-2 h-6 w-6 p-0 opacity-70 hover:opacity-100",title:"Copy result",children:et(Wu,{className:"h-3 w-3"})})]}):Ht("div",{className:S("p-3 rounded-lg border text-sm leading-relaxed max-h-96 overflow-y-auto max-w-full",o==="error"?"bg-destructive/10 border-destructive/20 text-destructive-foreground":"bg-muted/30 border-border"),children:[et(Mt,{data:n,filename:`tool-call-${e}-result-${Date.now()}.json`}),et(L,{variant:"ghost",size:"sm",onClick:()=>ct(JSON.stringify(n,null,2)),className:"absolute top-2 right-2 h-6 w-6 p-0 opacity-70 hover:opacity-100",title:"Copy result",children:et(Wu,{className:"h-3 w-3"})})]})})]})]})]})]}),o==="authorization-required"&&c&&s&&Ht("div",{className:"flex flex-col items-start gap-1.5 pl-1",children:[Ht(L,{"data-testid":`chat-tool-authenticate-${c}`,size:"sm",onClick:()=>{s(c)},disabled:a,className:"bg-amber-600 text-white hover:bg-amber-700 focus-visible:ring-amber-600 dark:bg-amber-500 dark:text-amber-950 dark:hover:bg-amber-400",children:[a?et(Ku,{className:"size-3.5 animate-spin","aria-hidden":!0}):et(Ju,{className:"size-3.5","aria-hidden":!0}),a?"Authenticating\u2026":"Authenticate"]}),i&&et("p",{className:"max-w-sm text-xs text-red-700 dark:text-red-300",children:i})]})]})}import{useMemo as lP}from"react";import{jsx as Yu}from"react/jsx-runtime";function cP(e){let t=atob(e.data),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return new File([n],e.name||"attachment",{type:e.mimeType})}function Bv({content:e,timestamp:t,attachments:n,inputTokens:o}){let r=lP(()=>n?.map(cP),[n]);return(!e||e.length===0)&&(!n||n.length===0)?null:Yu("div",{"data-testid":"chat-message-user",className:"flex flex-col items-end",children:Yu(Ya,{from:"user",files:r,time:t?new Date(t).toLocaleTimeString():void 0,actions:e||o!=null?Yu(tc,{variant:"user",copyText:e||void 0,inputTokens:o}):void 0,"data-testid":"chat-message-content",children:e&&e.length>0?e:void 0})})}import{isViewTool as yP}from"@mcp-use/client/react";var mr={events:[],spans:[]};function rc(e){if(!e||typeof e!="object")return;let t=e,n=(...p)=>{for(let d of p)if(typeof t[d]=="number")return t[d]},o=n("inputTokens","input_tokens","promptTokens"),r=n("outputTokens","output_tokens","completionTokens"),s=n("cachedInputTokens","cache_read_input_tokens"),a=n("cacheCreationInputTokens","cache_creation_input_tokens"),i=n("reasoningTokens","thoughtsTokenCount"),l=(n("cache_read_input_tokens")??0)+(a??0),u=n("totalTokens","total_tokens")??(o!==void 0&&r!==void 0?o+r+l:void 0);if(!(o===void 0&&r===void 0&&u===void 0&&s===void 0&&a===void 0&&i===void 0))return{inputTokens:o,outputTokens:r,totalTokens:u,cachedInputTokens:s,cacheCreationInputTokens:a,reasoningTokens:i}}var dP=new Set(["apikey","authorization","accesstoken","refreshtoken","password","cookie","secret"]);function oc(e){return Array.isArray(e)?e.map(oc):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,n])=>[t,dP.has(t.toLowerCase().replace(/[_-]/g,""))?"[REDACTED]":oc(n)]))}function Uv(e,t=120){let n;try{n=JSON.stringify(e)}catch{n=String(e)}return n.length>t?`${n.slice(0,t)}\u2026`:n}function Yr(e){switch(e.type){case"request":return"LLM request";case"text-delta":return e.delta.trim()||"Text delta";case"tool-call-start":return e.toolName;case"tool-call-args":return Uv(e.args);case"tool-result":return Uv(e.result);case"usage":return`${e.usage.totalTokens??"?"} tokens`;case"error":return e.message;case"done":return"Completed";default:return e}}function Xu(e,t){let n=(o,r)=>o===void 0&&r===void 0?void 0:(o??0)+(r??0);return{inputTokens:n(e?.inputTokens,t.inputTokens),outputTokens:n(e?.outputTokens,t.outputTokens),totalTokens:n(e?.totalTokens,t.totalTokens),cachedInputTokens:n(e?.cachedInputTokens,t.cachedInputTokens),cacheCreationInputTokens:n(e?.cacheCreationInputTokens,t.cacheCreationInputTokens),reasoningTokens:n(e?.reasoningTokens,t.reasoningTokens)}}function sc(e,t){let n=e.spans.map(s=>({...s})),o=e.usage,r=[...n].reverse().find(s=>s.kind==="llm"&&s.status==="running");if(t.type==="request")n.push({id:`llm-${t.id}`,kind:"llm",name:"LLM",status:"running",startedAt:t.timestamp,preview:Yr(t)});else if((t.type==="text-delta"||t.type==="tool-call-start")&&!r)r={id:`llm-${t.id}`,kind:"llm",name:"LLM",status:"running",startedAt:t.timestamp,preview:t.type==="text-delta"?Yr(t):"LLM response"},n.push(r),t.type==="tool-call-start"&&n.push({id:t.toolCallId,kind:"tool",name:t.toolName,status:"running",startedAt:t.timestamp,preview:Yr(t)});else if(t.type==="tool-call-start")n.push({id:t.toolCallId,kind:"tool",name:t.toolName,status:"running",startedAt:t.timestamp,preview:Yr(t)});else if(t.type==="tool-call-args"){let s=n.find(a=>a.id===t.toolCallId);s&&(s.preview=Yr(t))}else if(t.type==="tool-result"){let s=t.toolCallId?n.find(a=>a.id===t.toolCallId):[...n].reverse().find(a=>a.kind==="tool"&&a.name===t.toolName&&a.status==="running");s&&(s.status=t.isError?"error":"success",s.endedAt=t.timestamp,s.preview=Yr(t))}else t.type==="usage"?(o=Xu(o,t.usage),r&&(r.usage=Xu(r.usage,t.usage))):(t.type==="error"||t.type==="done")&&r&&(r.status=t.type==="error"?"error":"success",r.endedAt=t.timestamp,r.preview=Yr(t));return{events:[...e.events,t],spans:n,usage:o}}function Qu(e,t){let n=[],o=null;for(let r of e)r.type==="request"?(o&&n.push(o),o={request:r,response:[]}):o&&o.response.push(r);return o&&n.push(o),{turns:n,tokenUsage:t??null}}function uP(e){let t;for(let n of e)n.type==="usage"&&(t=Xu(t,n.usage));return t}function mP(e){let t=[],n=0;for(;n<e.length;){if(e[n]?.role!=="user"){n++;continue}let o=e[n].id;n++;let r=null;for(;n<e.length&&e[n]?.role==="assistant";)r=e[n].id,n++;t.push({userId:o,assistantId:r})}return t}function Hv(e,t){let{turns:n}=Qu(t),o=mP(e),r=new Map,s=Math.min(n.length,o.length);for(let a=0;a<s;a++){let i=uP(n[a].response);if(!i)continue;let{userId:c,assistantId:l}=o[a];i.inputTokens!=null&&r.set(c,{...r.get(c),inputTokens:i.inputTokens}),l!=null&&i.outputTokens!=null&&r.set(l,{...r.get(l),outputTokens:i.outputTokens})}return r}var pP=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp","image/svg+xml"]);function fP(e){for(let t of e)if(t>10485760)throw new Error("ui/message image exceeds the 10 MB per-file limit");if(e.reduce((t,n)=>t+n,0)>20971520)throw new Error("ui/message images exceed the 20 MB total limit")}function gP(e){let t=e.replace(/\s/g,"");if(t.length===0||t.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("ui/message image data must be valid base64");let n=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-n}function Fv(e){if(e.length===0)throw new Error("ui/message requires at least one content block");let t=[],n=[];for(let[r,s]of e.entries()){if(s.type==="text"){if(typeof s.text!="string")throw new Error(`ui/message text block ${r} is invalid`);t.push(s.text);continue}if(s.type==="image"){if(typeof s.data!="string"||typeof s.mimeType!="string")throw new Error(`ui/message image block ${r} is invalid`);if(!pP.has(s.mimeType))throw new Error(`Unsupported ui/message image type: ${s.mimeType}`);let a=gP(s.data);fP([...n.map(i=>i.size??0),a]),n.push({type:"image",data:s.data,mimeType:s.mimeType,name:`widget-image-${n.length+1}`,size:a});continue}throw new Error(`Unsupported ui/message content block: ${s.type||"unknown"}`)}let o=t.join(`
|
|
203
203
|
`);if(!o.trim()&&n.length===0)throw new Error("ui/message must include text or an image");return{text:o,attachments:n}}import{Fragment as xP,jsx as qt,jsxs as ac}from"react/jsx-runtime";var Xa=hP(({messages:e,isLoading:t,serverId:n,readResource:o,tools:r,sendMessage:s,messagesEndRef:a,traceEvents:i=[],modelContextScope:c,llmConfig:l,renderToolResults:u=!0,onAuthenticateTool:p,authenticatingToolCallId:d,toolAuthorizationError:g})=>{let m=Zu(!1),y=Zu(t);y.current=t;let f=Zu(s);f.current=s;let v=bP(()=>Hv(e,i),[e,i]),C=w=>{let k=I=>I.replace(/-/g,"_"),T=k(w);return r?.find(I=>k(I.name)===T)?._meta},b=w=>{let k=C(w);return yP(k)},h=vP(async w=>{if(y.current||m.current)throw new Error("Chat is busy with another turn");let k=f.current;if(!k)throw new Error("Chat is not available on this host surface");let T=Fv(w);m.current=!0;try{await k(T.text,T.attachments.length>0?T.attachments:void 0)}finally{m.current=!1}},[]),N=t&&(()=>{if(e.length===0)return!0;let w=e[e.length-1];if(w.role==="user")return!0;if(w.role==="assistant"){if(w.parts&&w.parts.length>0)return!1;let k=typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.map(A=>typeof A=="string"?A:A.text||JSON.stringify(A)).join(""):JSON.stringify(w.content);return!(k&&k.trim().length>0)}return!1})(),P=e[e.length-1],M=t&&P?.role==="assistant",R=w=>{for(let k=w.length-1;k>=0;k--)if(w[k]?.type==="text")return k;return-1},x=(w,k,T)=>M&&w.id===P?.id&&k===R(T),E=w=>M&&w.id===P?.id;return ac("div",{className:"space-y-6 max-w-3xl mx-auto px-2",children:[e.map(w=>{let k=typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.map(T=>typeof T=="string"?T:T.text||JSON.stringify(T)).join(""):JSON.stringify(w.content);if(w.role==="user")return qt(Bv,{content:k,timestamp:w.timestamp,attachments:w.attachments,inputTokens:v.get(w.id)?.inputTokens},w.id);if(w.role==="assistant"){let T=v.get(w.id)?.outputTokens,A=w.parts&&w.parts.length>0?R(w.parts):-1;return qt("div",{className:"space-y-4",children:w.parts&&w.parts.length>0?w.parts.map((I,J)=>{let B=I.type==="text"?`${w.id}-text-${J}`:`${w.id}-tool-${I.toolInvocation?.toolCallId??`${I.toolInvocation?.toolName}-${J}`}`;return I.type==="text"?qt(qu,{content:I.text||"",timestamp:J===w.parts.length-1?w.timestamp:void 0,_isStreaming:x(w,J,w.parts),outputTokens:J===A?T:void 0},B):I.type==="tool-invocation"&&I.toolInvocation?ac("div",{children:[qt(Gu,{toolName:I.toolInvocation.toolName,toolCallId:I.toolInvocation.toolCallId,args:I.toolInvocation.args,result:I.toolInvocation.result,state:I.toolInvocation.state==="authorization-required"?"authorization-required":I.toolInvocation.state==="error"?"error":I.toolInvocation.state==="streaming"||I.toolInvocation.state==="pending"?"call":"result",partialArgs:I.toolInvocation.partialArgs,onAuthenticate:p,isAuthenticating:d===I.toolInvocation.toolCallId,authorizationError:I.toolInvocation.state==="authorization-required"?g:null}),u&&(I.toolInvocation.result||I.toolInvocation.state==="streaming"||b(I.toolInvocation.toolName))&&qt("div",{"data-tool-call-id":`${w.id}-${I.toolInvocation.toolName}-${J}`,children:qt(pl,{toolName:I.toolInvocation.toolName,toolArgs:I.toolInvocation.args,result:I.toolInvocation.result||null,serverId:n,readResource:o,toolMeta:C(I.toolInvocation.toolName),onSendFollowUp:h,modelContextScope:c,llmConfig:l,partialToolArgs:I.toolInvocation.partialArgs,cancelled:I.toolInvocation.state==="error"&&I.toolInvocation.result==="Cancelled by user"})})]},B):null}):ac(xP,{children:[qt(qu,{content:k,timestamp:w.timestamp,_isStreaming:E(w),outputTokens:T}),w.toolCalls&&w.toolCalls.length>0&&qt("div",{className:"space-y-2",children:w.toolCalls.map(I=>{let J=`${w.id}-${I.toolName}-${JSON.stringify(I.args).slice(0,50)}`;return ac("div",{children:[qt(Gu,{toolName:I.toolName,args:I.args,result:I.result,state:I.result?"result":"call"}),u&&(I.result||b(I.toolName))&&qt("div",{"data-tool-call-id":J,children:qt(pl,{toolName:I.toolName,toolArgs:I.args,result:I.result||null,serverId:n,readResource:o,toolMeta:C(I.toolName),onSendFollowUp:h,modelContextScope:c,llmConfig:l})})]},J)})})]})},w.id)}return null}),N&&qt("div",{className:"flex items-start gap-3",children:qt("div",{className:"flex-1",children:qt("div",{className:"rounded-lg p-4 max-w-fit",children:qt("div",{className:"flex items-center gap-2",children:qt("span",{className:"text-sm",children:qt(kv,{duration:2,spread:1,children:"Thinking..."})})})})})}),qt("div",{ref:a})]})});import{ArrowDown as wP}from"lucide-react";import{AnimatePresence as CP,motion as SP}from"motion/react";import{jsx as Qa}from"react/jsx-runtime";function $v({visible:e,onClick:t}){return Qa("div",{className:"pointer-events-none absolute bottom-2 left-0 right-0 z-30 flex justify-center",children:Qa(CP,{children:e&&Qa(SP.div,{initial:{opacity:0,y:8,scale:.96},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.96},transition:{duration:.18,ease:"easeOut"},children:Qa(L,{type:"button",variant:"secondary",className:"pointer-events-auto size-9 rounded-full border bg-background/95 p-0 shadow-lg backdrop-blur supports-[backdrop-filter]:bg-background/80",onClick:t,"aria-label":"Scroll to bottom",title:"Scroll to bottom","data-testid":"chat-scroll-to-bottom",children:Qa(wP,{className:"size-4"})})})})})}import{jsx as NP}from"react/jsx-runtime";function Vv({visible:e}){return NP("div",{"aria-hidden":!0,className:S("pointer-events-none absolute inset-x-0 top-0 z-[5] h-32 bg-[linear-gradient(to_bottom,var(--background)_0%,var(--background)_24%,transparent_46%)] transition-opacity duration-200 sm:h-36",e?"opacity-100":"opacity-0")})}import{useCallback as jv,useEffect as qv,useRef as em,useState as Wv}from"react";function Kv(e,{messageCount:t,isLoading:n,enabled:o=!0}){let r=em(null),[s,a]=Wv(!0),[i,c]=Wv(!1),l=em(!0),u=em({length:0,loading:!1}),p=64,d=8,g=t>0,m=o&&g&&!s,y=jv(()=>{let v=e.current;if(!v)return;let b=v.scrollHeight-(v.scrollTop+v.clientHeight)<=p;l.current=b,a(b),c(v.scrollTop>d)},[e]),f=jv(v=>{let C=e.current;C&&(C.scrollTo({top:C.scrollHeight,behavior:v}),l.current=!0,a(!0))},[e]);return qv(()=>{if(!o)return;let v=e.current;if(!v)return;y();let C=()=>y();v.addEventListener("scroll",C,{passive:!0});let b=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null;return b?.observe(v),()=>{v.removeEventListener("scroll",C),b?.disconnect()}},[o,y,t,e]),qv(()=>{if(!o||!g||!l.current)return;let v=u.current,C=t!==v.length,b=n!==v.loading;u.current={length:t,loading:n},!(!C&&!b)&&f(n?"auto":"smooth")},[o,g,n,t,f]),{messagesEndRef:r,showScrollToBottom:m,showTopFade:i,scrollToBottom:f}}import{ChevronDown as kP,ChevronUp as TP}from"lucide-react";import{useEffect as ic,useRef as Jv,useState as Gv}from"react";import{jsx as Za,jsxs as PP}from"react/jsx-runtime";function tm(){let[e,t]=Gv(!1);return ic(()=>{let n=document.documentElement,o=()=>t(n.hasAttribute("data-mcp-widget-fullscreen"));o();let r=new MutationObserver(o);return r.observe(n,{attributes:!0,attributeFilter:["data-mcp-widget-fullscreen"]}),()=>r.disconnect()},[]),e}function Yv({messages:e,isLoading:t}){let n=tm(),[o,r]=Gv(!1),s=Jv(null),a=e.reduce((c,l)=>l.role==="user"?l.id:c,null),i=Jv(a);return ic(()=>{n||r(!1)},[n]),ic(()=>{let c=i.current;i.current=a,n&&a!==null&&a!==c&&r(!0)},[n,a]),ic(()=>{o&&s.current?.scrollIntoView({block:"end"})},[o,e]),n?PP("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-2 px-2 pb-2 sm:px-4","data-testid":"fullscreen-chat-overlay",children:[o&&Za("section",{id:"fullscreen-chat-drawer",className:"max-h-[46vh] overflow-y-auto overscroll-contain rounded-2xl border border-border/80 bg-background/95 px-2 py-4 shadow-2xl backdrop-blur-xl sm:px-4","aria-label":"Current chat messages","data-testid":"fullscreen-chat-drawer",children:Za(Xa,{messages:e,isLoading:t,messagesEndRef:s,renderToolResults:!1})}),Za("button",{type:"button",className:"grid size-9 place-items-center self-center rounded-full border border-border/80 bg-background/95 text-foreground shadow-lg backdrop-blur-xl transition-colors hover:bg-muted","aria-label":o?"Hide chat messages":"Show chat messages","aria-expanded":o,"aria-controls":"fullscreen-chat-drawer",onClick:()=>r(c=>!c),"data-testid":"fullscreen-chat-drawer-toggle",children:o?Za(kP,{className:"size-4"}):Za(TP,{className:"size-4"})})]}):null}import{useCallback as jn,useState as EP}from"react";import{convertMessagesToProvider as RP}from"@mcp-use/agent";function lc(e){return RP(e)}var cc=e=>{let t=[];for(let n of e){if(n.error||n.result?.isError){let r={id:`prompt-error-${n.promptName}-${n.timestamp}`,role:"assistant",content:n.error||"Prompt execution failed",timestamp:n.timestamp};t.push(r);continue}let o=n.result;if(o&&"messages"in o&&Array.isArray(o.messages))for(let r of o.messages){let s="",a=[];if(typeof r.content=="string")s=r.content;else if(Array.isArray(r.content)){let c=[];for(let l of r.content)l.type==="text"&&l.text?c.push(l.text):l.type==="image"&&l.data?a.push({type:"image",data:l.data,mimeType:l.mimeType||"image/png"}):l.type==="resource"&&c.push(`[Resource: ${l.resource?.uri||"embedded"}]`);s=c.join(`
|
|
204
|
-
`)}else r.content&&typeof r.content=="object"&&(r.content.type==="text"&&r.content.text?s=r.content.text:r.content.type==="image"&&r.content.data?a.push({type:"image",data:r.content.data,mimeType:r.content.mimeType||"image/png"}):s=JSON.stringify(r.content));!s&&a.length===0&&(s="[no content]");let i={id:`prompt-${n.promptName}-${n.timestamp}-${t.length}`,role:r.role,content:s||"",timestamp:n.timestamp,attachments:a.length>0?a:void 0};t.push(i)}}return t};function dc(e){if(!e)return;let t=Xv(e);if(t)return t;let n=[],o=!1,r=!1;for(let a of e){if(o){r?r=!1:a==="\\"?r=!0:a==='"'&&(o=!1);continue}a==='"'?o=!0:a==="{"?n.push("}"):a==="["?n.push("]"):(a==="}"||a==="]")&&n[n.length-1]===a&&n.pop()}let s=e;return o&&r&&(s=s.slice(0,-1)),o&&(s+='"'),s+=[...n].reverse().join(""),Xv(s)}function Xv(e){try{let t=JSON.parse(e);return t!==null&&!Array.isArray(t)&&typeof t=="object"?t:void 0}catch{return}}function nm(e,t=[]){return{id:e,messages:t,attachments:[],isLoading:!1,trace:mr,managedChatNotice:null,pendingAuthorization:null,authenticatingToolCallId:null,toolAuthorizationError:null,mcpServerAuthRequired:null,persistedChatId:null,creation:null,runtime:{abortController:null,sendInProgress:!1,traceId:0,authorizationGate:null,pendingTurnResumed:!1}}}function Xr(){let e=globalThis.crypto?.randomUUID?.();if(
|
|
204
|
+
`)}else r.content&&typeof r.content=="object"&&(r.content.type==="text"&&r.content.text?s=r.content.text:r.content.type==="image"&&r.content.data?a.push({type:"image",data:r.content.data,mimeType:r.content.mimeType||"image/png"}):s=JSON.stringify(r.content));!s&&a.length===0&&(s="[no content]");let i={id:`prompt-${n.promptName}-${n.timestamp}-${t.length}`,role:r.role,content:s||"",timestamp:n.timestamp,attachments:a.length>0?a:void 0};t.push(i)}}return t};function dc(e){if(!e)return;let t=Xv(e);if(t)return t;let n=[],o=!1,r=!1;for(let a of e){if(o){r?r=!1:a==="\\"?r=!0:a==='"'&&(o=!1);continue}a==='"'?o=!0:a==="{"?n.push("}"):a==="["?n.push("]"):(a==="}"||a==="]")&&n[n.length-1]===a&&n.pop()}let s=e;return o&&r&&(s=s.slice(0,-1)),o&&(s+='"'),s+=[...n].reverse().join(""),Xv(s)}function Xv(e){try{let t=JSON.parse(e);return t!==null&&!Array.isArray(t)&&typeof t=="object"?t:void 0}catch{return}}function nm(e,t=[]){return{id:e,messages:t,attachments:[],isLoading:!1,trace:mr,managedChatNotice:null,pendingAuthorization:null,authenticatingToolCallId:null,toolAuthorizationError:null,mcpServerAuthRequired:null,persistedChatId:null,creation:null,runtime:{abortController:null,sendInProgress:!1,traceId:0,authorizationGate:null,pendingTurnResumed:!1}}}function Xr(){let e=globalThis.crypto,t=e?.randomUUID?.();if(t)return t;if(!e?.getRandomValues)throw new Error("Secure random generation is unavailable");let n=e.getRandomValues(new Uint8Array(16));return`chat-${Array.from(n,r=>r.toString(16).padStart(2,"0")).join("")}`}import{useCallback as om,useRef as MP,useSyncExternalStore as IP}from"react";function uc(e,t){return typeof t=="function"?t(e):t}var rm=class{constructor(){lt(this,"sessions",new Map);lt(this,"listeners",new Map)}get(t){let n=this.sessions.get(t);if(n)return n;let o=nm(t);return this.sessions.set(t,o),o}has(t){return this.sessions.has(t)}seed(t,n){let o=this.sessions.get(t);if(o)return o;let r=nm(t,n);return this.sessions.set(t,r),r}update(t,n){let o=this.get(t),r=typeof n=="function"?n(o):n;if(Object.keys(r).every(i=>Object.is(o[i],r[i])))return o;let a={...o,...r};this.sessions.set(t,a);for(let i of this.listeners.get(t)??[])i();return a}subscribe(t,n){let o=this.listeners.get(t);return o||(o=new Set,this.listeners.set(t,o)),o.add(n),()=>{o.delete(n),o.size===0&&this.listeners.delete(t)}}delete(t){this.sessions.delete(t)}findByPersistedChatId(t){for(let n of this.sessions.values())if((n.persistedChatId??n.id)===t)return n}};function zs(){let e=MP(null);return e.current||(e.current=new rm),e.current}function mc(e,t){let n=om(a=>e.subscribe(t,a),[e,t]),o=om(()=>e.get(t),[e,t]),r=IP(n,o,o),s=om(a=>e.update(t,a),[t,e]);return[r,s]}function sm({sessionStore:e,sessionId:t,onMessagesChange:n,mcpServerUrl:o,llmConfig:r,authConfig:s,mcpAuthTokens:a,isConnected:i,chatApiUrl:c,waitForChatApiUrl:l,widgetModelContexts:u,initialMessages:p,disabledTools:d,streamProtocol:g="sse",credentials:m,extraHeaders:y,body:f}){let v=zs(),C=e??v,[b]=EP(Xr),h=t??b;p?.length&&!C.has(h)&&C.seed(h,p);let[N,P]=mc(C,h),{messages:M,isLoading:R,attachments:x,managedChatNotice:E,mcpServerAuthRequired:w,runtime:k}=N,T=N.trace,A=jn(z=>{let $=C.update(h,ie=>({messages:uc(ie.messages,z)}));n?.(h,$.messages)},[h,n,C]),I=jn(z=>{let $={...z,id:`trace-${++k.traceId}`,timestamp:Date.now()};P(ie=>({trace:sc(ie.trace,$)}))},[k,P]),J=jn(async(z,$,ie,fe)=>{let ue=[...x,...ie??[]],xe=z.trim()||$.length>0||ue.length>0,re=pe=>{if(fe?.throwOnError)throw new Error(pe)};if(!xe){re("Chat message must include content");return}if(!r){re("Chat is not configured");return}if(!i){re("The MCP server is not connected");return}if(k.sendInProgress){re("Chat is busy with another turn");return}k.sendInProgress=!0;let Ne=[...cc($)];if(z.trim()||ue.length>0){let pe={id:`user-${Date.now()}`,role:"user",content:z.trim(),timestamp:Date.now(),attachments:ue.length>0?ue:void 0};Ne.push(pe)}A(pe=>[...pe,...Ne]),P({isLoading:!0,attachments:[]}),k.abortController=new AbortController;try{let pe=s,He=s?.type==="bearer"&&!!s.token,Ye=s?.type==="basic"&&!!(s.username||s.password);if(!He&&!Ye)if(a?.access_token)pe={type:"oauth",oauthTokens:a};else try{let ce="mcp:auth",ve=xl(o),st=`${ce}_${ve}_tokens`,tt=localStorage.getItem(st);if(tt){let O=JSON.parse(tt);O?.access_token&&(pe={type:"oauth",oauthTokens:O})}}catch(ce){console.warn("Failed to retrieve OAuth tokens:",ce)}let qe=[...M,...Ne],xt=kr(u??new Map),Z=Ji(xt),Y=[...Z?[Z]:[],...qe.map(ce=>({role:ce.role,content:ce.content||(ce.parts?.filter(ve=>ve.type==="text").map(ve=>ve.text).join("")??""),attachments:ce.attachments}))],_=c??(l?await l():void 0)??kp("chat/stream"),le=[...d??[]].sort(),De={disabledTools:le,...xt?{widgetModelContext:xt}:{}},We=f?f(Y,De):{mcpServerUrl:o,llmConfig:r,authConfig:pe,messages:Y,...le.length>0?{disabledTools:le}:{}},wt=f?oc(We):{mcpServerUrl:o,llmConfig:{provider:r.provider,model:r.model,temperature:r.temperature,baseUrl:r.baseUrl},messages:Y,...le.length>0?{disabledTools:le}:{}};I({type:"request",request:{url:_,protocol:g,envelope:wt,providerMessages:[...Z?[Z]:[],...lc(qe)]}});let dt=await fetch(_,{method:"POST",headers:{"Content-Type":"application/json",...y},signal:k.abortController.signal,...m?{credentials:m}:{},body:JSON.stringify(We)});if(!dt.ok){let ce=await dt.json().catch(()=>null);if(c){let ve=Ph(dt.status,ce);if(ve){if(P({managedChatNotice:ve}),fe?.throwOnError)throw new Error(`Chat request failed with HTTP ${dt.status}`);return}}if(dt.status===401&&ce?.error==="mcp_auth_required"){if(P({mcpServerAuthRequired:{mcpServerUrl:ce.mcpServerUrl??o,message:ce.message}}),fe?.throwOnError)throw new Error("The MCP server requires authentication");return}throw new Error(`HTTP error! status: ${dt.status}`)}fe?.onAccepted?.();let Wt=`assistant-${Date.now()}`,zt="",Ke=[];A(ce=>[...ce,{id:Wt,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]);let En=dt.body?.getReader(),mn=new TextDecoder;if(!En)throw new Error("No response body");let Ct=()=>{A(ce=>ce.map(ve=>ve.id===Wt?{...ve,parts:[...Ke]}:ve))},pn=()=>{A(ce=>ce.map(ve=>ve.id===Wt?{...ve,parts:[...Ke],content:""}:ve))},Cn=ce=>{zt+=ce;let ve=Ke[Ke.length-1];ve&&ve.type==="text"?ve.text=zt:Ke.push({type:"text",text:zt}),Ct()},mt=new Map,te=new Map,Me=(ce,ve)=>{zt&&(zt=""),!mt.has(ce)&&(Ke.push({type:"tool-invocation",toolInvocation:{toolCallId:ce,toolName:ve,args:{},state:"streaming",partialArgs:{}}}),mt.set(ce,Ke.length-1),te.set(ce,""),Ct())},ke=(ce,ve)=>{let st=mt.get(ce);if(st===void 0||!ve)return;let tt=(te.get(ce)??"")+ve;te.set(ce,tt);let O=dc(tt),X=Ke[st]?.toolInvocation;!O||!X||(X.partialArgs=O,Ct())},rt=(ce,ve,st)=>{zt&&(zt="");let tt=mt.get(ce),O=tt===void 0?void 0:Ke[tt]?.toolInvocation;O?(O.toolName=ve,O.args=st,O.state="pending",O.partialArgs=void 0):(Ke.push({type:"tool-invocation",toolInvocation:{toolCallId:ce,toolName:ve,args:st,state:"pending"}}),mt.set(ce,Ke.length-1)),te.delete(ce),Ct()},bt=(ce,ve)=>{let st;ce.by==="toolName"?st=Ke.find(tt=>tt.type==="tool-invocation"&&tt.toolInvocation?.toolName===ce.toolName&&!tt.toolInvocation?.result):st=Ke[ce.index],st?.toolInvocation&&(st.toolInvocation.result=ve,st.toolInvocation.state=ve?.isError?"error":"result",Ct())},en="";for(;;){if(k.abortController?.signal.aborted){await En.cancel();break}let{done:ce,value:ve}=await En.read();if(ce)break;en+=mn.decode(ve,{stream:!0});let st=en.split(`
|
|
205
205
|
`);en=st.pop()||"";for(let tt of st)if(tt.trim())try{if(g==="data-stream"){let O=tt.indexOf(":");if(O===-1)continue;let X=tt.slice(0,O),Oe=tt.slice(O+1),we;try{we=JSON.parse(Oe)}catch{continue}switch(X){case"0":{let be=typeof we=="string"?we:String(we);I({type:"text-delta",delta:be,raw:we}),Cn(be);break}case"b":{let be=we,ze=String(be.toolCallId??`tool-${Ke.length}`),_e=String(be.toolName??"");I({type:"tool-call-start",toolCallId:ze,toolName:_e,raw:we}),Me(ze,_e);break}case"c":{let be=we,ze=String(be.toolCallId??""),_e=String(be.argsTextDelta??be.argsDelta??"");ke(ze,_e);break}case"9":{let be=we,ze=be.args??{};if(typeof ze.input=="string"&&Object.keys(ze).length===1)try{let at=JSON.parse(ze.input);typeof at=="object"&&at!==null&&(ze=at)}catch{}let _e=String(be.toolCallId??`tool-${Ke.length}`),Qe=String(be.toolName??"");mt.has(_e)||I({type:"tool-call-start",toolCallId:_e,toolName:Qe,raw:we}),I({type:"tool-call-args",toolCallId:_e,toolName:Qe,args:ze,raw:we}),rt(_e,Qe,ze);break}case"a":{let be=we,ze=mt.get(be.toolCallId),_e=be.result,Qe=_e;if(Qe?.lc===1&&Qe?.type==="constructor"&&Qe?.kwargs?.content){let at=Qe.kwargs.content;if(typeof at=="string")try{_e=JSON.parse(at)}catch{_e=at}}ze!==void 0&&(I({type:"tool-result",toolCallId:String(be.toolCallId??""),toolName:Ke[ze]?.toolInvocation?.toolName??"Tool",result:_e,isError:!!(_e&&typeof _e=="object"&&_e.isError),raw:we}),bt({by:"index",index:ze},_e));break}case"d":{let ze=rc((we&&typeof we=="object"?we:void 0)?.usage);ze&&I({type:"usage",usage:ze,raw:we}),I({type:"done",raw:we}),pn();break}case"3":throw I({type:"error",message:typeof we=="string"?we:JSON.stringify(we),raw:we}),new Error(typeof we=="string"?we:JSON.stringify(we));default:break}}else{if(!tt.startsWith("data: "))continue;let O=JSON.parse(tt.slice(6));if(O.type!=="message"){if(O.type==="text")I({type:"text-delta",delta:O.content,raw:O}),Cn(O.content);else if(O.type==="tool-call-start"){let X=O.toolCallId??`tool-${Ke.length}`;I({type:"tool-call-start",toolCallId:X,toolName:O.toolName,raw:O}),Me(X,O.toolName)}else if(O.type==="tool-call-delta"||O.type==="tool-call-args-delta")ke(O.toolCallId,O.argsDelta??O.argsTextDelta??"");else if(O.type==="tool-call"){let X=O.toolCallId??`tool-${Ke.length}`;mt.has(X)||I({type:"tool-call-start",toolCallId:X,toolName:O.toolName,raw:O}),I({type:"tool-call-args",toolCallId:X,toolName:O.toolName,args:O.args,raw:O}),rt(X,O.toolName,O.args)}else if(O.type==="tool-result"){I({type:"tool-result",toolCallId:O.toolCallId,toolName:O.toolName,result:O.result,isError:O.isError??O.result?.isError,raw:O});let X=mt.get(O.toolCallId);bt(X===void 0?{by:"toolName",toolName:O.toolName}:{by:"index",index:X},O.result)}else if(O.type==="done"){let X=rc(O.usage);X&&I({type:"usage",usage:X,raw:O}),I({type:"done",raw:O}),pn()}else if(O.type==="usage"){let X=rc(O.usage??O);X&&I({type:"usage",usage:X,raw:O})}else if(O.type==="error")throw I({type:"error",message:O.message||"Streaming error",raw:O}),new Error(O.message||"Streaming error")}}}catch(O){if(O instanceof Error&&O.message!=="Streaming error")console.error("Failed to parse streaming event:",O,tt);else throw O}}if(k.abortController?.signal.aborted){for(let ce of Ke)ce.type==="tool-invocation"&&(ce.toolInvocation?.state==="pending"||ce.toolInvocation?.state==="streaming")&&(ce.toolInvocation.state="error",ce.toolInvocation.result="Cancelled by user");A(ce=>ce.map(ve=>ve.id===Wt?{...ve,parts:[...Ke],content:""}:ve))}}catch(pe){if(pe instanceof DOMException&&pe.name==="AbortError"){if(fe?.throwOnError)throw new Error("Chat turn was cancelled");return}if(c&&_a(pe)){if(P({managedChatNotice:{kind:"cloud_unavailable"}}),fe?.throwOnError)throw new Error("Chat service is unavailable");return}let He="Unknown error occurred";if(pe instanceof Error){He=pe.message;let qe=pe;qe.status&&(He=`HTTP ${qe.status}: ${He}`),(qe.code===401||He.includes("401")||He.includes("Unauthorized"))&&(He="Authentication failed (401). Check your Authorization header in the connection settings.")}let Ye={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${He}`,timestamp:Date.now()};if(A(qe=>[...qe,Ye]),fe?.throwOnError)throw new Error(He)}finally{P({isLoading:!1}),k.abortController=null,k.sendInProgress=!1}},[r,i,o,M,s,a,x,c,l,u,d,g,m,y,f,I,k,A,P]),B=jn(()=>{A([]),P({managedChatNotice:null,mcpServerAuthRequired:null,trace:mr})},[A,P]),G=jn(()=>{P({managedChatNotice:null})},[P]),U=jn(z=>{P({managedChatNotice:z})},[P]),q=jn(()=>P({trace:mr}),[P]),K=jn(()=>{P({mcpServerAuthRequired:null})},[P]),H=jn(()=>{k.abortController?.abort()},[k]),W=jn(async z=>{try{let $=await Cl(z);P(ie=>{let fe=[...ie.attachments,$];return wl(fe)?{attachments:fe}:(alert("Total attachment size exceeds 20MB limit"),{})})}catch($){$ instanceof Error?alert($.message):alert("Failed to add attachment")}},[P]),oe=jn(z=>{P($=>({attachments:$.attachments.filter((ie,fe)=>fe!==z)}))},[P]),j=jn(()=>{P({attachments:[]})},[P]);return{sessionId:h,messages:M,isLoading:R,attachments:x,managedChatNotice:E,mcpServerAuthRequired:w,sendMessage:J,clearMessages:B,clearManagedChatNotice:G,showManagedChatNotice:U,clearMcpServerAuthRequired:K,setMessages:A,stop:H,addAttachment:W,removeAttachment:oe,clearAttachments:j,clearTrace:q,traceEvents:T.events,tokenUsage:T.usage}}import{MCPAgent as HP,providerConfigFromOptions as FP}from"@mcp-use/agent";import{isOAuthInteractionRequired as $P}from"@mcp-use/client/react";import{useCallback as qn,useEffect as VP,useState as jP}from"react";var Bs="read_skill",Us="read_skill_resource";function Qv(e){return typeof e.frontmatter.name=="string"?e.frontmatter.name:e.uri}function AP(e){if(e.text!==void 0)return new TextEncoder().encode(e.text);let t=atob(e.blob??"");return Uint8Array.from(t,n=>n.charCodeAt(0))}function LP(e){let t=AP(e),n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}async function DP(e){let t=await crypto.subtle.digest("SHA-256",LP(e));return`sha256:${[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}`}async function _P(e){let t=e.skill.resources?.find(s=>s.uri===e.uri)?.digest;if(!t)throw new Error("Resource is not part of the skill manifest");let n=await e.readResource(e.uri),o=n.contents[0];if(!o||n.contents.length!==1||o.uri!==e.uri)throw new Error("resources/read returned an unexpected resource");if(await DP(o)!==t)throw new Error(`Skill resource digest mismatch for ${e.uri}`);return o}function Zv(e,t="connected MCP server"){return e.length===0?"":`
|
|
206
206
|
|
|
207
207
|
The connected MCP server advertises these optional skills:
|
package/dist/server/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Qt=Object.create;var ke=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var er=Object.getOwnPropertyNames;var tr=Object.getPrototypeOf,rr=Object.prototype.hasOwnProperty;var F=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var nr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of er(e))!rr.call(t,o)&&o!==r&&ke(t,o,{get:()=>e[o],enumerable:!(n=Zt(e,o))||n.enumerable});return t};var or=(t,e,r)=>(r=t!=null?Qt(tr(t)):{},nr(e||!t||!t.__esModule?ke(r,"default",{value:t,enumerable:!0}):r,t));var ct=F((Ko,at)=>{"use strict";at.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){if(Number.isFinite(e))this._points=e;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)this._duration=e;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=e}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return this.keyPrefix.length>0?e.substring(this.keyPrefix.length+1):e}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var ut=F((Go,lt)=>{"use strict";lt.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e,10)}get expiresAt(){return this._expiresAt}set expiresAt(e){e instanceof Date?this._expiresAt=e.getTime():this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Re=F((Xo,dt)=>{"use strict";dt.exports=class{constructor(e,r,n,o){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var ft=F((Zo,ht)=>{"use strict";var pt=ut(),Ee=Re();ht.exports=class{constructor(){this._storage=new Map}incrby(e,r,n){let o=this._storage.get(e);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new Ee(0,s,o.value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,s=this._storage.get(e);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new pt(r,o>0?Date.now()+o:null);return this._storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),i.timeoutId.unref&&i.timeoutId.unref()),new Ee(0,o===0?-1:o,i.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Ee(0,n,r.value,!1)}return null}delete(e){let r=this._storage.get(e);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(e),!0):!1}_restoreRecord(e,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(e);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new pt(r,n);this._storage.set(e,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var yt=F((es,gt)=>{"use strict";var xr=ct(),vr=ft(),mt=Re(),_e=class extends xr{constructor(e={}){super(e),this._memoryStorage=new vr}consume(e,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new mt(0,n===0?-1:n,o))}set(e,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new mt(0,o===0?-1:o,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}dump(){let e=[];for(let[r,n]of this._memoryStorage._storage)e.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:e}}restore(e,r=!1){if(!e||typeof e!="object"||e.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(e.storage))return n;for(let s of e.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};gt.exports=_e});var le=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(p){if(p instanceof Error&&e)n.error=p,c=await e(p,n),l=!0;else throw p}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var De=Symbol();var je=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Y=t=>"headers"in t,Ne=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,i=(Y(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?sr(t,{all:r,dot:n}):{}};async function sr(t,e){if(!Y(t)&&t.bodyCache.formData)return Ue(await t.bodyCache.formData,e);let r=Y(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=je(n,r.get("Content-Type")||"");Y(t)||(t.bodyCache.formData=o);let s=await o;return s?Ue(s,e):{}}function Ue(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?ir(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(ar(r,n,o),delete r[n])}),r}var ir=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},ar=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var de=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},He=t=>{let{groups:e,path:r}=cr(t),n=de(r);return lr(n,e)},cr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},lr=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},X={},$e=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return X[n]||(r[2]?X[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:X[n]=[t,r[1],!0]),X[n]}return null},Q=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},ur=t=>Q(t,decodeURI),pe=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return ur(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Be=t=>{let e=pe(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},k=(t,e,...r)=>(r.length&&(e=k(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Z=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ue=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?Q(t,he):t):t,qe=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return ue(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let o=Object.create(null);n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let i=t.indexOf("&",s+1),a=t.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=t.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ue(c)),s=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),n&&(l=ue(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return e?o[e]:o},ze=qe,Fe=(t,e)=>qe(t,e,!0),he=decodeURIComponent;var We=t=>Q(t,he),Ve=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?We(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?We(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return ze(this.url,t)}queries(t){return Fe(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e=Object.create(null);return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return Ne(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[De](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ke={Stringify:1,BeforeStream:2,Stream:3},dr=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var fe=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>fe(c,e,!1,n,o))).then(()=>o[0]));return r?dr(await i,s):i};var pr="text/plain; charset=UTF-8",me=(t,e)=>({"Content-Type":t,...e}),W=(t,e)=>new Response(t,e),ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Ve(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=W(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=W(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=W(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof e=="number"?e:e?.status??this.#s;return W(t,{status:o,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,me(pr,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,me("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,me("text/html; charset=UTF-8",r));return typeof t=="object"?fe(t,Ke.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>W(),this.#l(this))};var v="ALL",Je="all",Ge=["get","post","put","delete","options","patch"],ee="Can not add a route since the matcher is already built.",te=class extends Error{};var Ye="__COMPOSED_HANDLER";var hr=t=>t.text("404 Not Found",404),Xe=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Qe=class Ze{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ge,Je].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(v,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??pe:Be}#e(){let e=new Ze({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=hr;errorHandler=Xe;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===Xe?s=o.handler:(s=async(i,a)=>(await le([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Ye]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=k(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=k(this._basePath,e),l=c==="/"?0:c.length;return u=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(l)||"/",new Request(p,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(v,k(e,"*"),a),this}#s(e,r,n,o){e=e.toUpperCase(),r=k(this._basePath,r);let s={basePath:o!==void 0?k(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new ge(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=le(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${k("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var re=[];function ye(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[v],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],re];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var ne="[^/]+",V=".*",K="(?:|/.*)",H=Symbol(),fr=new Set(".\\+*[^]$()");function mr(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===V||t===K?1:e===V||e===K?-1:t===ne?1:e===ne?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var et=class we{#t;#e;#r=Object.create(null);insert(e,r,n,o,s){if(e.length===0){if(this.#t!==void 0)throw H;if(s)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",V]:["","",ne]:i==="/*"?["","",K]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],p=c[2]||ne;if(u&&c[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw H;if(l=this.#r[p],!l){if(Object.keys(this.#r).some(h=>h!==V&&h!==K))throw H;if(s)return;l=this.#r[p]=new we,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==V&&u!==K))throw H;if(s)return;l=this.#r[i]=new we}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(mr).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:fr.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var tt=class{#t={varIndex:0};#e=new et;insert(t,e,r){let n=[],o=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var gr=[/^$/,[],Object.create(null)],rt=Object.create(null);function nt(t){return rt[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function yr(){rt=Object.create(null)}function wr(t){let e=new tt,r=[];if(t.length===0)return gr;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[p,h])=>l?1:p?-1:u.length-h.length),o=Object.create(null);for(let l=0,u=-1,p=n.length;l<p;l++){let[h,f,w]=n[l];h?o[f]=[w.map(([g])=>[g,Object.create(null)]),re]:u++;let b;try{b=e.insert(f,u,h)}catch(g){throw g===H?new te(f):g}h||(r[u]=w.map(([g,d])=>{let m=Object.create(null);for(d-=1;d>=0;d--){let[x,O]=b[d];m[x]=O}return[g,m]}))}let[s,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let p=0,h=r[l].length;p<h;p++){let f=r[l][p]?.[1];if(!f)continue;let w=Object.keys(f);for(let b=0,g=w.length;b<g;b++)f[w[b]]=a[f[w[b]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function q(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(nt(r).test(e))return[...t[r]]}}var oe=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[v]:Object.create(null)},this.#e={[v]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(ee);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[v]).forEach(c=>{a[t][c]=[...a[v][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=nt(e);t===v?Object.keys(n).forEach(c=>{n[c][e]||=q(n[c],e)||q(n[v],e)||[]}):n[t][e]||=q(n[t],e)||q(n[v],e)||[],Object.keys(n).forEach(c=>{(t===v||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(t===v||t===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=Z(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(t===v||t===u)&&(o[u][l]||=[...q(n[u],l)||q(n[v],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=ye;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,yr(),t}#r(t){let e=[],r=t===v;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==v&&e.push(...Object.keys(n[v]).map(s=>[s,n[v][s]]))}),r?wr(e):null}};var be=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(ee);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof te)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var J=Object.create(null),br=t=>{for(let e in t)return!0;return!1},ot=class st{#t;#e;#r;#s=0;#o=J;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#s=++this.#s;let o=this,s=He(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],p=$e(l,u),h=Array.isArray(p)?p[0]:l;if(h in o.#e){o=o.#e[h],p&&i.push(p[1]);continue}o.#e[h]=new st,p&&(o.#r.push(p),i.push(p[1])),o=o.#e[h]}return o.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[v],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),o!==J||s&&s!==J))for(let p=0,h=l.possibleKeys.length;p<h;p++){let f=l.possibleKeys[p],w=u[l.score];l.params[f]=s?.[f]&&!w?s[f]:o[f]??s?.[f],u[l.score]=!0}}}search(e,r){let n=[];this.#o=J;let s=[this],i=de(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let p=i[u],h=u===c-1,f=[];for(let b=0,g=s.length;b<g;b++){let d=s[b],m=d.#e[p];m&&(m.#o=d.#o,h?(m.#e["*"]&&this.#n(n,m.#e["*"],e,d.#o),this.#n(n,m,e,d.#o)):f.push(m));for(let x=0,O=d.#r.length;x<O;x++){let L=d.#r[x],E=d.#o===J?{}:{...d.#o};if(L==="*"){let _=d.#e["*"];_&&(this.#n(n,_,e,d.#o),_.#o=E,f.push(_));continue}let[P,S,R]=L;if(!p&&!(R instanceof RegExp))continue;let y=d.#e[P];if(R instanceof RegExp){if(l===null){l=new Array(c);let j=r[0]==="/"?1:0;for(let U=0;U<c;U++)l[U]=j,j+=i[U].length+1}let _=r.substring(l[u]),C=R.exec(_);if(C){if(E[S]=C[0],this.#n(n,y,e,d.#o,E),C[0].length===_.length&&y.#e["*"]&&this.#n(n,y.#e["*"],e,d.#o,E),br(y.#e)){y.#o=E;let j=C[0].match(/\//)?.length??0;(a[j]||=[]).push(y)}continue}}(R===!0||R.test(p))&&(E[S]=p,h?(this.#n(n,y,e,E,d.#o),y.#e["*"]&&this.#n(n,y.#e["*"],e,E,d.#o)):(y.#o=E,f.push(y)))}}let w=a.shift();s=w?f.concat(w):f}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};var xe=class{name="TrieRouter";#t;constructor(){this.#t=new ot}add(t,e,r){let n=Z(e);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var ve=class extends Qe{constructor(t={}){super(t),this.router=t.router??new be({routers:[new oe,new xe]})}};import{Readable as pn}from"stream";function it(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as wt,readFileSync as _r}from"fs";import I from"path";import{fileURLToPath as Pr}from"url";import{gunzipSync as Sr}from"zlib";var M=or(yt(),1);function z(t,e){return t.header("Retry-After",String(Rr(e))),t.json({error:"Too Many Requests"},429)}function Rr(t){return t&&typeof t=="object"&&"msBeforeNext"in t&&typeof t.msBeforeNext=="number"&&Number.isFinite(t.msBeforeNext)?Math.max(1,Math.ceil(t.msBeforeNext/1e3)):60}var Ar={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Cr(){let t=I.dirname(Pr(import.meta.url));for(let e of[I.resolve(t,"app"),I.resolve(t,"../app"),I.resolve(t,"../../dist/app")])if(wt(I.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function bt(t,e="/inspector/assets"){let r=Cr(),n=new Map,o=new M.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return z(i,c)}return a()};t.use(`${e}/*`,s),t.get(`${e}/*`,async i=>{let a=i.req.path.slice(e.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=I.resolve(r,l),p=r.endsWith(I.sep)?r:`${r}${I.sep}`;if(!u.startsWith(p)||!wt(u))return i.notFound();let h=I.extname(c),f=l.endsWith(".gz"),w=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),b=_r(u),g=f&&!w?n.get(u)??Or(n,u,b):b,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(d,200,{"Content-Type":Ar[h]??"application/octet-stream",...f&&w?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Or(t,e,r){let n=Sr(r);return t.set(e,n),n}var xt={name:"@mcp-use/inspector",type:"module",version:"20.2.5-canary.1",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"},"./client/styles.css":{default:"./dist/client/styles.css"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.7 || ^2.0.8-canary.0","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"^2.2.5-canary.0",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34",jsdom:"^27.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var Tr=xt.version;function vt(){return Tr}var Mr=`<!doctype html>
|
|
1
|
+
var Qt=Object.create;var ke=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var er=Object.getOwnPropertyNames;var tr=Object.getPrototypeOf,rr=Object.prototype.hasOwnProperty;var F=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var nr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of er(e))!rr.call(t,o)&&o!==r&&ke(t,o,{get:()=>e[o],enumerable:!(n=Zt(e,o))||n.enumerable});return t};var or=(t,e,r)=>(r=t!=null?Qt(tr(t)):{},nr(e||!t||!t.__esModule?ke(r,"default",{value:t,enumerable:!0}):r,t));var ct=F((Ko,at)=>{"use strict";at.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){if(Number.isFinite(e))this._points=e;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)this._duration=e;else throw new Error("duration must be set and must be a finite, non-negative number")}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=e}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return this.keyPrefix.length>0?e.substring(this.keyPrefix.length+1):e}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var ut=F((Go,lt)=>{"use strict";lt.exports=class{constructor(e,r,n=null){this.value=e,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(e){this._value=parseInt(e,10)}get expiresAt(){return this._expiresAt}set expiresAt(e){e instanceof Date?this._expiresAt=e.getTime():this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Re=F((Xo,dt)=>{"use strict";dt.exports=class{constructor(e,r,n,o){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof r>"u"?0:r,this.consumedPoints=typeof n>"u"?0:n,this.isFirstInDuration=typeof o>"u"?!1:o}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var ft=F((Zo,ht)=>{"use strict";var pt=ut(),Ee=Re();ht.exports=class{constructor(){this._storage=new Map}incrby(e,r,n){let o=this._storage.get(e);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new Ee(0,s,o.value,!1)):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,s=this._storage.get(e);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new pt(r,o>0?Date.now()+o:null);return this._storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(e)},o),i.timeoutId.unref&&i.timeoutId.unref()),new Ee(0,o===0?-1:o,i.value,!0)}get(e){let r=this._storage.get(e);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new Ee(0,n,r.value,!1)}return null}delete(e){let r=this._storage.get(e);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(e),!0):!1}_restoreRecord(e,r,n){let o=Date.now(),s=n!==null;if(s&&!Number.isFinite(n)||s&&n<=o)return;let i=s?n-o:0,a=this._storage.get(e);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new pt(r,n);this._storage.set(e,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(e)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var yt=F((es,gt)=>{"use strict";var xr=ct(),vr=ft(),mt=Re(),_e=class extends xr{constructor(e={}){super(e),this._memoryStorage=new vr}consume(e,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(e),a=this._getKeySecDuration(n),c=this._memoryStorage.incrby(i,r,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+r&&(c=this._memoryStorage.set(i,c.consumedPoints,this.blockDuration)),s(c);else if(this.execEvenly&&this.points>0&&c.msBeforeNext>0&&!c.isFirstInDuration){let l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),c.msBeforeNext=Math.max(c.msBeforeNext-l,0),setTimeout(o,l,c)}else o(c)})}penalty(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}reward(e,r=1,n={}){let o=this.getKey(e);return new Promise(s=>{let i=this._getKeySecDuration(n),a=this._memoryStorage.incrby(o,-r,i);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),s(a)})}block(e,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(e),o,r),Promise.resolve(new mt(0,n===0?-1:n,o))}set(e,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),r,n),Promise.resolve(new mt(0,o===0?-1:o,r))}get(e){let r=this._memoryStorage.get(this.getKey(e));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}dump(){let e=[];for(let[r,n]of this._memoryStorage._storage)e.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:e}}restore(e,r=!1){if(!e||typeof e!="object"||e.version!==1)return;let n=r?{invalid:{count:0,keys:[]},expired:{count:0,keys:[]},restored:{count:0,keys:[]}}:{invalid:0,expired:0,restored:0},o=(s,i)=>{r?(n[s].count+=1,n[s].keys.push(i)):n[s]+=1};if(!Array.isArray(e.storage))return n;for(let s of e.storage){if(!s||typeof s!="object"){o("invalid","N/A");continue}let i=typeof s.key=="string"||typeof s.key=="number",a=Number.isFinite(s.value),c=s.expiresAt===null||Number.isFinite(s.expiresAt);if(!i||!a||!c){o("invalid",s.key);continue}if(s.expiresAt!==null&&s.expiresAt<=Date.now()){o("expired",s.key);continue}this._memoryStorage._restoreRecord(this.getKey(s.key),s.value,s.expiresAt),o("restored",s.key)}return n}};gt.exports=_e});var le=(t,e,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(t[a]?(u=t[a][0][0],n.req.routeIndex=a):u=a===t.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(p){if(p instanceof Error&&e)n.error=p,c=await e(p,n),l=!0;else throw p}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var De=Symbol();var je=(t,e)=>new Response(t,{headers:{"Content-Type":e.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Y=t=>"headers"in t,Ne=async(t,e=Object.create(null))=>{let{all:r=!1,dot:n=!1}=e,i=(Y(t)?t.headers:t.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?sr(t,{all:r,dot:n}):{}};async function sr(t,e){if(!Y(t)&&t.bodyCache.formData)return Ue(await t.bodyCache.formData,e);let r=Y(t)?t.headers:t.raw.headers,n=await t.arrayBuffer(),o=je(n,r.get("Content-Type")||"");Y(t)||(t.bodyCache.formData=o);let s=await o;return s?Ue(s,e):{}}function Ue(t,e){let r=Object.create(null);return t.forEach((n,o)=>{e.all||o.endsWith("[]")?ir(r,o,n):r[o]=n}),e.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(ar(r,n,o),delete r[n])}),r}var ir=(t,e,r)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(r):t[e]=[t[e],r]:e.endsWith("[]")?t[e]=[r]:t[e]=r},ar=(t,e,r)=>{if(/(?:^|\.)__proto__\./.test(e))return;let n=t,o=e.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var de=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},He=t=>{let{groups:e,path:r}=cr(t),n=de(r);return lr(n,e)},cr=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return e.push([o,r]),o}),{groups:e,path:t}},lr=(t,e)=>{for(let r=e.length-1;r>=0;r--){let[n]=e[r];for(let o=t.length-1;o>=0;o--)if(t[o].includes(n)){t[o]=t[o].replace(n,e[r][1]);break}}return t},X={},$e=(t,e)=>{if(t==="*")return"*";let r=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${t}#${e}`;return X[n]||(r[2]?X[n]=e&&e[0]!==":"&&e[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${e})`)]:[t,r[1],new RegExp(`^${r[2]}$`)]:X[n]=[t,r[1],!0]),X[n]}return null},Q=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return e(r)}catch{return r}})}},ur=t=>Q(t,decodeURI),pe=t=>{let e=t.url,r=e.indexOf("/",e.indexOf(":")+4),n=r;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o===37){let s=e.indexOf("?",n),i=e.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=e.slice(r,a);return ur(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return e.slice(r,n)};var Be=t=>{let e=pe(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},k=(t,e,...r)=>(r.length&&(e=k(e,...r)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),Z=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),r=[],n="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ue=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?Q(t,he):t):t,qe=(t,e,r)=>{let n;if(!r&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let a=t.charCodeAt(i+e.length+1);if(a===61){let c=i+e.length+2,l=t.indexOf("&",c);return ue(t.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=t.indexOf(`&${e}`,i+1)}if(n=/[%+]/.test(t),!n)return}let o=Object.create(null);n??=/[%+]/.test(t);let s=t.indexOf("?",8);for(;s!==-1;){let i=t.indexOf("&",s+1),a=t.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=t.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ue(c)),s=i,c==="")continue;let l;a===-1?l="":(l=t.slice(a+1,i===-1?void 0:i),n&&(l=ue(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return e?o[e]:o},ze=qe,Fe=(t,e)=>qe(t,e,!0),he=decodeURIComponent;var We=t=>Q(t,he),Ve=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",r=[[]]){this.raw=t,this.path=e,this.#e=r,this.#t={}}param(t){return t?this.#r(t):this.#s()}#r(t){let e=this.#e[0][this.routeIndex][1][t],r=this.#o(e);return r&&/\%/.test(r)?We(r):r}#s(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of e){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(t[r]=/\%/.test(n)?We(n):n)}return t}#o(t){return this.#e[1]?this.#e[1][t]:t}query(t){return ze(this.url,t)}queries(t){return Fe(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e=Object.create(null);return this.raw.headers.forEach((r,n)=>{e[n]=r}),e}async parseBody(t){return Ne(this,t)}#n=t=>{let{bodyCache:e,raw:r}=this,n=e[t];if(n)return n;let o=Object.keys(e)[0];return o?e[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[t]())):e[t]=r[t]()};json(){return this.#n("text").then(t=>JSON.parse(t))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(t=>new Uint8Array(t))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[De](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Ke={Stringify:1,BeforeStream:2,Stream:3},dr=(t,e)=>{let r=new String(t);return r.isEscaped=!0,r.callbacks=e,r};var fe=async(t,e,r,n,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let s=t.callbacks;if(!s?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let i=Promise.all(s.map(a=>a({phase:e,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>fe(c,e,!1,n,o))).then(()=>o[0]));return r?dr(await i,s):i};var pr="text/plain; charset=UTF-8",me=(t,e)=>({"Content-Type":t,...e}),W=(t,e)=>new Response(t,e),ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#p;constructor(t,e){this.#t=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#l=e.notFoundHandler,this.#p=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new Ve(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=W(null,{headers:this.#a??=new Headers})}set res(t){if(this.#n&&t){t=W(t.body,t);for(let[e,r]of this.#n.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let n=this.#n.headers.getSetCookie();t.headers.delete("set-cookie");for(let o of n)t.headers.append("set-cookie",o)}else t.headers.set(e,r)}this.#n=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#u=t;getLayout=()=>this.#u;setRenderer=t=>{this.#c=t};header=(t,e,r)=>{this.finalized&&(this.#n=W(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;e===void 0?n.delete(t):r?.append?n.append(t,e):n.set(t,e)};status=t=>{this.#s=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let s=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof e=="number"?e:e?.status??this.#s;return W(t,{status:o,headers:n})}newResponse=(...t)=>this.#i(...t);body=(t,e,r)=>this.#i(t,e,r);text=(t,e,r)=>!this.#a&&!this.#s&&!e&&!r&&!this.finalized?new Response(t):this.#i(t,e,me(pr,r));json=(t,e,r)=>this.#i(JSON.stringify(t),e,me("application/json",r));html=(t,e,r)=>{let n=o=>this.#i(o,e,me("text/html; charset=UTF-8",r));return typeof t=="object"?fe(t,Ke.Stringify,!1,{}).then(n):n(t)};redirect=(t,e)=>{let r=String(t);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,e??302)};notFound=()=>(this.#l??=()=>W(),this.#l(this))};var v="ALL",Je="all",Ge=["get","post","put","delete","options","patch"],ee="Can not add a route since the matcher is already built.",te=class extends Error{};var Ye="__COMPOSED_HANDLER";var hr=t=>t.text("404 Not Found",404),Xe=(t,e)=>{if("getResponse"in t){let r=t.getResponse();return e.newResponse(r.body,r)}return console.error(t),e.text("Internal Server Error",500)},Qe=class Ze{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ge,Je].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(v,this.#t,a)}),this);let{strict:n,...o}=e;Object.assign(this,o),this.getPath=n??!0?e.getPath??pe:Be}#e(){let e=new Ze({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=hr;errorHandler=Xe;route(e,r){let n=this.basePath(e);return r.routes.map(o=>{let s;r.errorHandler===Xe?s=o.handler:(s=async(i,a)=>(await le([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Ye]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(e){let r=this.#e();return r._basePath=k(this._basePath,e),r}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=k(this._basePath,e),l=c==="/"?0:c.length;return u=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(l)||"/",new Request(p,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(v,k(e,"*"),a),this}#s(e,r,n,o){e=e.toUpperCase(),r=k(this._basePath,r);let s={basePath:o!==void 0?k(this._basePath,o):this._basePath,path:r,method:e,handler:n};this.router.add(e,r,[n,s]),this.routes.push(s)}#o(e,r){if(e instanceof Error)return this.errorHandler(e,r);throw e}#n(e,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(e,r,n,"GET")))();let s=this.getPath(e,{env:n}),i=this.router.match(o,s),a=new ge(e,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=le(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(e,...r)=>this.#n(e,r[1],r[0],e.method);request=(e,r,n,o)=>e instanceof Request?this.fetch(r?new Request(e,r):e,n,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${k("/",e)}`,r),n,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#n(e.request,e,void 0,e.request.method))})}};var re=[];function ye(t,e){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[v],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],re];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(t,e)}var ne="[^/]+",V=".*",K="(?:|/.*)",H=Symbol(),fr=new Set(".\\+*[^]$()");function mr(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===V||t===K?1:e===V||e===K?-1:t===ne?1:e===ne?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var et=class we{#t;#e;#r=Object.create(null);insert(e,r,n,o,s){if(e.length===0){if(this.#t!==void 0)throw H;if(s)return;this.#t=r;return}let[i,...a]=e,c=i==="*"?a.length===0?["","",V]:["","",ne]:i==="/*"?["","",K]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],p=c[2]||ne;if(u&&c[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw H;if(l=this.#r[p],!l){if(Object.keys(this.#r).some(h=>h!==V&&h!==K))throw H;if(s)return;l=this.#r[p]=new we,u!==""&&(l.#e=o.varIndex++)}!s&&u!==""&&n.push([u,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==V&&u!==K))throw H;if(s)return;l=this.#r[i]=new we}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(mr).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:fr.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#t=="number"&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var tt=class{#t={varIndex:0};#e=new et;insert(t,e,r){let n=[],o=[];for(let i=0;;){let a=!1;if(t=t.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#e.insert(s,e,n,this.#t,r),n}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,r=[],n=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++e]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++e),"")),[new RegExp(`^${t}`),r,n]}};var gr=[/^$/,[],Object.create(null)],rt=Object.create(null);function nt(t){return rt[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function yr(){rt=Object.create(null)}function wr(t){let e=new tt,r=[];if(t.length===0)return gr;let n=t.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[p,h])=>l?1:p?-1:u.length-h.length),o=Object.create(null);for(let l=0,u=-1,p=n.length;l<p;l++){let[h,f,w]=n[l];h?o[f]=[w.map(([g])=>[g,Object.create(null)]),re]:u++;let b;try{b=e.insert(f,u,h)}catch(g){throw g===H?new te(f):g}h||(r[u]=w.map(([g,d])=>{let m=Object.create(null);for(d-=1;d>=0;d--){let[x,O]=b[d];m[x]=O}return[g,m]}))}let[s,i,a]=e.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let p=0,h=r[l].length;p<h;p++){let f=r[l][p]?.[1];if(!f)continue;let w=Object.keys(f);for(let b=0,g=w.length;b<g;b++)f[w[b]]=a[f[w[b]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function q(t,e){if(t){for(let r of Object.keys(t).sort((n,o)=>o.length-n.length))if(nt(r).test(e))return[...t[r]]}}var oe=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[v]:Object.create(null)},this.#e={[v]:Object.create(null)}}add(t,e,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(ee);n[t]||[n,o].forEach(a=>{a[t]=Object.create(null),Object.keys(a[v]).forEach(c=>{a[t][c]=[...a[v][c]]})}),e==="/*"&&(e="*");let s=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let a=nt(e);t===v?Object.keys(n).forEach(c=>{n[c][e]||=q(n[c],e)||q(n[v],e)||[]}):n[t][e]||=q(n[t],e)||q(n[v],e)||[],Object.keys(n).forEach(c=>{(t===v||t===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(t===v||t===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=Z(e)||[e];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(t===v||t===u)&&(o[u][l]||=[...q(n[u],l)||q(n[v],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=ye;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,yr(),t}#r(t){let e=[],r=t===v;return[this.#t,this.#e].forEach(n=>{let o=n[t]?Object.keys(n[t]).map(s=>[s,n[t][s]]):[];o.length!==0?(r||=!0,e.push(...o)):t!==v&&e.push(...Object.keys(n[v]).map(s=>[s,n[v][s]]))}),r?wr(e):null}};var be=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,r){if(!this.#e)throw new Error(ee);this.#e.push([t,e,r])}match(t,e){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(t,e)}catch(c){if(c instanceof te)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var J=Object.create(null),br=t=>{for(let e in t)return!0;return!1},ot=class st{#t;#e;#r;#s=0;#o=J;constructor(e,r,n){if(this.#e=n||Object.create(null),this.#t=[],e&&r){let o=Object.create(null);o[e]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(e,r,n){this.#s=++this.#s;let o=this,s=He(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],p=$e(l,u),h=Array.isArray(p)?p[0]:l;if(h in o.#e){o=o.#e[h],p&&i.push(p[1]);continue}o.#e[h]=new st,p&&(o.#r.push(p),i.push(p[1])),o=o.#e[h]}return o.#t.push({[e]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(e,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[v],u={};if(l!==void 0&&(l.params=Object.create(null),e.push(l),o!==J||s&&s!==J))for(let p=0,h=l.possibleKeys.length;p<h;p++){let f=l.possibleKeys[p],w=u[l.score];l.params[f]=s?.[f]&&!w?s[f]:o[f]??s?.[f],u[l.score]=!0}}}search(e,r){let n=[];this.#o=J;let s=[this],i=de(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let p=i[u],h=u===c-1,f=[];for(let b=0,g=s.length;b<g;b++){let d=s[b],m=d.#e[p];m&&(m.#o=d.#o,h?(m.#e["*"]&&this.#n(n,m.#e["*"],e,d.#o),this.#n(n,m,e,d.#o)):f.push(m));for(let x=0,O=d.#r.length;x<O;x++){let L=d.#r[x],E=d.#o===J?{}:{...d.#o};if(L==="*"){let _=d.#e["*"];_&&(this.#n(n,_,e,d.#o),_.#o=E,f.push(_));continue}let[P,S,R]=L;if(!p&&!(R instanceof RegExp))continue;let y=d.#e[P];if(R instanceof RegExp){if(l===null){l=new Array(c);let j=r[0]==="/"?1:0;for(let U=0;U<c;U++)l[U]=j,j+=i[U].length+1}let _=r.substring(l[u]),C=R.exec(_);if(C){if(E[S]=C[0],this.#n(n,y,e,d.#o,E),C[0].length===_.length&&y.#e["*"]&&this.#n(n,y.#e["*"],e,d.#o,E),br(y.#e)){y.#o=E;let j=C[0].match(/\//)?.length??0;(a[j]||=[]).push(y)}continue}}(R===!0||R.test(p))&&(E[S]=p,h?(this.#n(n,y,e,E,d.#o),y.#e["*"]&&this.#n(n,y.#e["*"],e,E,d.#o)):(y.#o=E,f.push(y)))}}let w=a.shift();s=w?f.concat(w):f}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};var xe=class{name="TrieRouter";#t;constructor(){this.#t=new ot}add(t,e,r){let n=Z(e);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(t,n[o],r);return}this.#t.insert(t,e,r)}match(t,e){return this.#t.search(t,e)}};var ve=class extends Qe{constructor(t={}){super(t),this.router=t.router??new be({routers:[new oe,new xe]})}};import{Readable as pn}from"stream";function it(t=""){return`<link rel="icon" type="image/svg+xml" href="${`${t.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as wt,readFileSync as _r}from"fs";import I from"path";import{fileURLToPath as Pr}from"url";import{gunzipSync as Sr}from"zlib";var M=or(yt(),1);function z(t,e){return t.header("Retry-After",String(Rr(e))),t.json({error:"Too Many Requests"},429)}function Rr(t){return t&&typeof t=="object"&&"msBeforeNext"in t&&typeof t.msBeforeNext=="number"&&Number.isFinite(t.msBeforeNext)?Math.max(1,Math.ceil(t.msBeforeNext/1e3)):60}var Ar={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Cr(){let t=I.dirname(Pr(import.meta.url));for(let e of[I.resolve(t,"app"),I.resolve(t,"../app"),I.resolve(t,"../../dist/app")])if(wt(I.join(e,"inspector.js.gz")))return e;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function bt(t,e="/inspector/assets"){let r=Cr(),n=new Map,o=new M.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return z(i,c)}return a()};t.use(`${e}/*`,s),t.get(`${e}/*`,async i=>{let a=i.req.path.slice(e.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=I.resolve(r,l),p=r.endsWith(I.sep)?r:`${r}${I.sep}`;if(!u.startsWith(p)||!wt(u))return i.notFound();let h=I.extname(c),f=l.endsWith(".gz"),w=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),b=_r(u),g=f&&!w?n.get(u)??Or(n,u,b):b,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(d,200,{"Content-Type":Ar[h]??"application/octet-stream",...f&&w?{"Content-Encoding":"gzip"}:{},...f?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Or(t,e,r){let n=Sr(r);return t.set(e,n),n}var xt={name:"@mcp-use/inspector",type:"module",version:"20.2.5",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"},"./client/styles.css":{default:"./dist/client/styles.css"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs",test:"vitest run","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.7 || ^2.0.8","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"^2.2.4 || ^2.2.5 || ^2.3.0",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34",jsdom:"^27.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var Tr=xt.version;function vt(){return Tr}var Mr=`<!doctype html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-use/inspector",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "20.2.5
|
|
4
|
+
"version": "20.2.5",
|
|
5
5
|
"description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
|
|
6
6
|
"author": "",
|
|
7
7
|
"license": "MIT",
|
|
@@ -46,14 +46,14 @@
|
|
|
46
46
|
},
|
|
47
47
|
"peerDependencies": {
|
|
48
48
|
"@base-ui/react": "^1.6.0",
|
|
49
|
-
"@mcp-use/agent": "^2.0.7 || ^2.0.8
|
|
49
|
+
"@mcp-use/agent": "^2.0.7 || ^2.0.8",
|
|
50
50
|
"@mcp-use/client": "^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5",
|
|
51
51
|
"class-variance-authority": "^0.7.1",
|
|
52
52
|
"clsx": "^2.1.1",
|
|
53
53
|
"express": "^4.21.2 || ^5.0.0",
|
|
54
54
|
"lucide-react": "^0.562.0",
|
|
55
55
|
"markdown-to-jsx": "^9.7.4",
|
|
56
|
-
"mcp-use": "^2.2.5
|
|
56
|
+
"mcp-use": "^2.2.4 || ^2.2.5 || ^2.3.0",
|
|
57
57
|
"motion": "^12.34.2",
|
|
58
58
|
"react": "^18.0.0 || ^19.0.0",
|
|
59
59
|
"react-dom": "^18.0.0 || ^19.0.0",
|
|
@@ -149,7 +149,7 @@
|
|
|
149
149
|
"wait-on": "^9.0.4",
|
|
150
150
|
"yaml": "^2.8.3",
|
|
151
151
|
"zod": "^4.2.0",
|
|
152
|
-
"@mcp-use/agent": "2.0.8
|
|
152
|
+
"@mcp-use/agent": "2.0.8",
|
|
153
153
|
"@mcp-use/client": "2.1.5"
|
|
154
154
|
},
|
|
155
155
|
"scripts": {
|
|
@@ -158,7 +158,7 @@
|
|
|
158
158
|
"dev:server": "VITE_DEV=true tsx watch src/server/server.ts",
|
|
159
159
|
"dev:standalone": "tsx watch src/server/server.ts",
|
|
160
160
|
"clean": "rimraf dist",
|
|
161
|
-
"build": "
|
|
161
|
+
"build": "pnpm run clean && pnpm run build:client-exports && pnpm run build:server && pnpm run build:app && pnpm run verify:package",
|
|
162
162
|
"build:app": "vite build --config vite.app.config.ts && node scripts/compress-app.mjs",
|
|
163
163
|
"watch:app": "vite build --watch --config vite.app.config.ts",
|
|
164
164
|
"preview:app": "vite preview --config vite.app.config.ts --host 127.0.0.1",
|
|
@@ -182,6 +182,7 @@
|
|
|
182
182
|
"test:e2e:codegen": "playwright codegen http://localhost:3000/inspector",
|
|
183
183
|
"test:e2e:report": "playwright show-report",
|
|
184
184
|
"test:e2e:python": "node tests/e2e/scripts/run-python-e2e.mjs",
|
|
185
|
+
"test": "vitest run",
|
|
185
186
|
"test:unit": "vitest run",
|
|
186
187
|
"test:unit:watch": "vitest",
|
|
187
188
|
"test:e2e:tunnel": "node tests/e2e/scripts/run-tunnel-test.mjs",
|