@mcp-use/inspector 20.0.0-beta.42 → 20.0.0-beta.44

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.
Binary file
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- var pn=Object.create;var Pt=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var mn=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,wn=Object.prototype.hasOwnProperty;var re=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mn(t))!wn.call(e,o)&&o!==r&&Pt(e,o,{get:()=>t[o],enumerable:!(n=hn(t,o))||n.enumerable});return e};var xn=(e,t,r)=>(r=e!=null?pn(gn(e)):{},yn(t||!e||!e.__esModule?Pt(r,"default",{value:e,enumerable:!0}):r,e));var Ar=re((gc,Pr)=>{"use strict";Pr.exports=class{constructor(t={}){this.points=t.points,this.duration=t.duration,this.blockDuration=t.blockDuration,this.execEvenly=t.execEvenly,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs,this.keyPrefix=t.keyPrefix}get points(){return this._points}set points(t){if(Number.isFinite(t))this._points=t;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(t){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)this._duration=t;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(t){this._blockDuration=typeof t>"u"?0:t}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(t){this._execEvenly=typeof t>"u"?!1:!!t}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(t){this._execEvenlyMinDelayMs=t}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(t){if(typeof t>"u"&&(t="rlflx"),typeof t!="string")throw new Error("keyPrefix must be string");this._keyPrefix=t}_getKeySecDuration(t={}){return t&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return this.keyPrefix.length>0?t.substring(this.keyPrefix.length+1):t}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 Cr=re((yc,_r)=>{"use strict";_r.exports=class{constructor(t,r,n=null){this.value=t,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(t){this._value=parseInt(t,10)}get expiresAt(){return this._expiresAt}set expiresAt(t){t instanceof Date?this._expiresAt=t.getTime():this._expiresAt=t}get timeoutId(){return this._timeoutId}set timeoutId(t){this._timeoutId=t}}});var ht=re((bc,Or)=>{"use strict";Or.exports=class{constructor(t,r,n,o){this.remainingPoints=typeof t>"u"?0:t,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(t){return this._msBeforeNext=t,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(t){return this._remainingPoints=t,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(t){return this._consumedPoints=t,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(t){this._isFirstInDuration=!!t}_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 Mr=re((Rc,Ir)=>{"use strict";var Tr=Cr(),mt=ht();Ir.exports=class{constructor(){this._storage=new Map}incrby(t,r,n){let o=this._storage.get(t);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new mt(0,s,o.value,!1)):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){let o=n*1e3,s=this._storage.get(t);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new Tr(r,o>0?Date.now()+o:null);return this._storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(t)},o),i.timeoutId.unref&&i.timeoutId.unref()),new mt(0,o===0?-1:o,i.value,!0)}get(t){let r=this._storage.get(t);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new mt(0,n,r.value,!1)}return null}delete(t){let r=this._storage.get(t);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(t),!0):!1}_restoreRecord(t,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(t);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new Tr(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var Nr=re((Ec,kr)=>{"use strict";var $o=Ar(),Bo=Mr(),Lr=ht(),gt=class extends $o{constructor(t={}){super(t),this._memoryStorage=new Bo}consume(t,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(t),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(t,r=1,n={}){let o=this.getKey(t);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(t,r=1,n={}){let o=this.getKey(t);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(t,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(t),o,r),Promise.resolve(new Lr(0,n===0?-1:n,o))}set(t,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(t),r,n),Promise.resolve(new Lr(0,o===0?-1:o,r))}get(t){let r=this._memoryStorage.get(this.getKey(t));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(t){return Promise.resolve(this._memoryStorage.delete(this.getKey(t)))}dump(){let t=[];for(let[r,n]of this._memoryStorage._storage)t.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:t}}restore(t,r=!1){if(!t||typeof t!="object"||t.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(t.storage))return n;for(let s of t.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}};kr.exports=gt});import{createServer as bn}from"http";import{Http2ServerRequest as Ot,constants as vn}from"http2";import{Http2ServerRequest as Ne}from"http2";import{Readable as At}from"stream";import Ln from"crypto";var F=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},Rn=e=>e instanceof F?e:new F(e.message,{cause:e}),En=global.Request,ne=class extends En{constructor(e,t){typeof e=="object"&&Y in e&&(e=e[Y]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},Sn=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},Tt=Symbol("wrapBodyStream"),Pn=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new ne(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[Tt]){let i;s.body=new ReadableStream({async pull(a){try{i||=At.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=At.toWeb(n);return new ne(t,s)},Y=Symbol("getRequestCache"),An=Symbol("requestCache"),pe=Symbol("incomingKey"),he=Symbol("urlKey"),_n=Symbol("headersKey"),X=Symbol("abortControllerKey"),Cn=Symbol("getAbortController"),me={get method(){return this[pe].method||"GET"},get url(){return this[he]},get headers(){return this[_n]||=Sn(this[pe])},[Cn](){return this[Y](),this[X]},[Y](){return this[X]||=new AbortController,this[An]||=Pn(this.method,this[he],this.headers,this[pe],this[X])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(me,e,{get(){return this[Y]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(me,e,{value:function(){return this[Y]()[e]()}})});Object.setPrototypeOf(me,ne.prototype);var On=(e,t)=>{let r=Object.create(me);r[pe]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof Ne)throw new F("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[he]=a.href}catch(a){throw new F("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof Ne?e.authority:e.headers.host)||t;if(!o)throw new F("Missing host header");let s;if(e instanceof Ne){if(s=e.scheme,!(s==="http"||s==="https"))throw new F("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new F("Invalid host header");return r[he]=i.href,r},_t=Symbol("responseCache"),G=Symbol("getResponseCache"),q=Symbol("cache"),je=global.Response,oe=class It{#t;#e;[G](){return delete this[q],this[_t]||=new je(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof It){let o=r[_t];if(o){this.#e=o,this[G]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[q]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[q];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[G]().headers}get status(){return this[q]?.[0]??this[G]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(oe.prototype,e,{get(){return this[G]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(oe.prototype,e,{value:function(){return this[G]()[e]()}})});Object.setPrototypeOf(oe,je);Object.setPrototypeOf(oe.prototype,je.prototype);async function Tn(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Mt(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function In(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Mt(e.getReader(),t)}var De=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},Mn="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=Ln);var $e=Symbol("outgoingEnded"),Ct=Symbol("incomingDraining"),kn=500,Nn=64*1024*1024,Ue=e=>{let t=e;if(e.destroyed||t[Ct])return;if(t[Ct]=!0,e instanceof Ot){try{e.stream?.close?.(vn.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,kn);s.unref?.();let i=a=>{r+=a.length,r>Nn&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Un=()=>new Response(null,{status:400}),Lt=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),He=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},kt=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Nt=async(e,t)=>{let[r,n,o]=e[q],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=De(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=De(i)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(kt(t),await In(n,t)?.catch(i=>He(i,t))),t[$e]?.()},Dn=e=>typeof e.then=="function",Hn=async(e,t,r={})=>{if(Dn(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(Lt);if(q in e)return Nt(e,t);let n=De(e.headers);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await Tn(a).catch(f=>{console.error(f),i=!0});if(!u){if(l===1){await new Promise(f=>setTimeout(f)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&kt(t),await Mt(o,t,a))}else n[Mn]||(t.writeHead(e.status,n),t.end());t[$e]?.()},jn=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==ne&&(Object.defineProperty(global,"Request",{value:ne}),Object.defineProperty(global,"Response",{value:oe})),async(n,o)=>{let s,i;try{i=On(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[Tt]=!0,n.on("end",()=>{a=!0}),n instanceof Ot&&(o[$e]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Ue(n)})})}),o.on("finish",()=>{a||Ue(n)})),o.on("close",()=>{i[X]&&(n.errored?i[X].abort(n.errored.toString()):o.writableFinished||i[X].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Ue(n)})})}),s=e(i,{incoming:n,outgoing:o}),q in s)return Nt(s,o)}catch(a){if(s)return He(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:Rn(a)),!s)return}else i?s=Lt(a):s=Un()}try{return await Hn(s,o,t)}catch(a){return He(a,o)}}},$n=e=>{let t=e.fetch,r=jn(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||bn)(e.serverOptions||{},r)},Ut=(e,t)=>{let r=$n(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var Be=(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(f){if(f instanceof Error&&t)n.error=f,c=await t(f,n),l=!0;else throw f}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Dt=Symbol();var Ht=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(e instanceof ge?e.raw.headers:e.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?Bn(e,{all:r,dot:n}):{}};async function Bn(e,t){let r=await e.formData();return r?Fn(r,t):{}}function Fn(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?qn(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(zn(r,n,o),delete r[n])}),r}var qn=(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},zn=(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 qe=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},jt=e=>{let{groups:t,path:r}=Wn(e),n=qe(r);return Kn(n,t)},Wn=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Kn=(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},we={},$t=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return we[n]||(r[2]?we[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:we[n]=[e,r[1],!0]),we[n]}return null},ye=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Vn=e=>ye(e,decodeURI),ze=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 Vn(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Bt=e=>{let t=ze(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},D=(e,t,...r)=>(r.length&&(t=D(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),xe=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)},Fe=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?ye(e,We):e):e,Ft=(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 Fe(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={};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=Fe(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=Fe(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},qt=Ft,zt=(e,t)=>Ft(e,t,!0),We=decodeURIComponent;var Wt=e=>ye(e,We),ge=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r,this.#t={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Wt(r):r}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Wt(n):n)}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return qt(this.url,e)}queries(e){return zt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Ht(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.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Dt](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Kt={Stringify:1,BeforeStream:2,Stream:3},Gn=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Ke=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=>Ke(c,t,!1,n,o))).then(()=>o[0]));return r?Gn(await i,s):i};var Xn="text/plain; charset=UTF-8",Ve=(e,t)=>({"Content-Type":e,...t}),se=(e,t)=>new Response(e,t),Ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#t=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.#e??=new ge(this.#t,this.#f,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||=se(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=se(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=se(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 se(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,Ve(Xn,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,Ve("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,Ve("text/html; charset=UTF-8",r));return typeof e=="object"?Ke(e,Kt.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??=()=>se(),this.#l(this))};var v="ALL",Vt="all",Gt=["get","post","put","delete","options","patch"],be="Can not add a route since the matcher is already built.",ve=class extends Error{};var Xt="__COMPOSED_HANDLER";var Yn=e=>e.text("404 Not Found",404),Yt=(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)},Jt=class Qt{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Gt,Vt].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}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??ze:Bt}#e(){let t=new Qt({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Yn;errorHandler=Yt;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Yt?s=o.handler:(s=async(i,a)=>(await Be([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Xt]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=D(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=D(this._basePath,t),l=c==="/"?0:c.length;return u=>{let f=new URL(u.url);return f.pathname=this.getPath(u).slice(l)||"/",new Request(f,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,D(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=D(this._basePath,r);let s={basePath:o!==void 0?D(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 Ge(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=Be(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${D("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var Re=[];function Xe(e,t){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(e,t)}var Ee="[^/]+",ie=".*",ae="(?:|/.*)",z=Symbol(),Jn=new Set(".\\+*[^]$()");function Qn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===ie||e===ae?1:t===ie||t===ae?-1:e===Ee?1:t===Ee?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Zt=class Ye{#t;#e;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#t!==void 0)throw z;if(s)return;this.#t=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",ie]:["","",Ee]:i==="/*"?["","",ae]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],f=c[2]||Ee;if(u&&c[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))))throw z;if(l=this.#r[f],!l){if(Object.keys(this.#r).some(p=>p!==ie&&p!==ae))throw z;if(s)return;l=this.#r[f]=new Ye,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!==ie&&u!==ae))throw z;if(s)return;l=this.#r[i]=new Ye}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Qn).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:Jn.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 er=class{#t={varIndex:0};#e=new Zt;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.#e.insert(s,t,n,this.#t,r),n}buildRegExp(){let e=this.#e.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 Zn=[/^$/,[],Object.create(null)],tr=Object.create(null);function rr(e){return tr[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function eo(){tr=Object.create(null)}function to(e){let t=new er,r=[];if(e.length===0)return Zn;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[f,p])=>l?1:f?-1:u.length-p.length),o=Object.create(null);for(let l=0,u=-1,f=n.length;l<f;l++){let[p,h,w]=n[l];p?o[h]=[w.map(([g])=>[g,Object.create(null)]),Re]:u++;let y;try{y=t.insert(h,u,p)}catch(g){throw g===z?new ve(h):g}p||(r[u]=w.map(([g,d])=>{let m=Object.create(null);for(d-=1;d>=0;d--){let[b,T]=y[d];m[b]=T}return[g,m]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let f=0,p=r[l].length;f<p;f++){let h=r[l][f]?.[1];if(!h)continue;let w=Object.keys(h);for(let y=0,g=w.length;y<g;y++)h[w[y]]=a[h[w[y]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function J(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(rr(r).test(t))return[...e[r]]}}var Se=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[v]:Object.create(null)},this.#e={[v]:Object.create(null)}}add(e,t,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(be);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[v]).forEach(c=>{a[e][c]=[...a[v][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=rr(t);e===v?Object.keys(n).forEach(c=>{n[c][t]||=J(n[c],t)||J(n[v],t)||[]}):n[e][t]||=J(n[e],t)||J(n[v],t)||[],Object.keys(n).forEach(c=>{(e===v||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===v||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=xe(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===v||e===u)&&(o[u][l]||=[...J(n[u],l)||J(n[v],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=Xe;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,eo(),e}#r(e){let t=[],r=e===v;return[this.#t,this.#e].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!==v&&t.push(...Object.keys(n[v]).map(s=>[s,n[v][s]]))}),r?to(t):null}};var Je=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(be);this.#e.push([e,t,r])}match(e,t){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(e,t)}catch(c){if(c instanceof ve)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 ce=Object.create(null),ro=e=>{for(let t in e)return!0;return!1},nr=class or{#t;#e;#r;#s=0;#o=ce;constructor(t,r,n){if(this.#e=n||Object.create(null),this.#t=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=jt(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],f=$t(l,u),p=Array.isArray(f)?f[0]:l;if(p in o.#e){o=o.#e[p],f&&i.push(f[1]);continue}o.#e[p]=new or,f&&(o.#r.push(f),i.push(f[1])),o=o.#e[p]}return o.#t.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.#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),t.push(l),o!==ce||s&&s!==ce))for(let f=0,p=l.possibleKeys.length;f<p;f++){let h=l.possibleKeys[f],w=u[l.score];l.params[h]=s?.[h]&&!w?s[h]:o[h]??s?.[h],u[l.score]=!0}}}search(t,r){let n=[];this.#o=ce;let s=[this],i=qe(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let f=i[u],p=u===c-1,h=[];for(let y=0,g=s.length;y<g;y++){let d=s[y],m=d.#e[f];m&&(m.#o=d.#o,p?(m.#e["*"]&&this.#n(n,m.#e["*"],t,d.#o),this.#n(n,m,t,d.#o)):h.push(m));for(let b=0,T=d.#r.length;b<T;b++){let I=d.#r[b],E=d.#o===ce?{}:{...d.#o};if(I==="*"){let P=d.#e["*"];P&&(this.#n(n,P,t,d.#o),P.#o=E,h.push(P));continue}let[S,A,R]=I;if(!f&&!(R instanceof RegExp))continue;let x=d.#e[S];if(R instanceof RegExp){if(l===null){l=new Array(c);let j=r[0]==="/"?1:0;for(let $=0;$<c;$++)l[$]=j,j+=i[$].length+1}let P=r.substring(l[u]),M=R.exec(P);if(M){if(E[A]=M[0],this.#n(n,x,t,d.#o,E),ro(x.#e)){x.#o=E;let j=M[0].match(/\//)?.length??0;(a[j]||=[]).push(x)}continue}}(R===!0||R.test(f))&&(E[A]=f,p?(this.#n(n,x,t,E,d.#o),x.#e["*"]&&this.#n(n,x.#e["*"],t,E,d.#o)):(x.#o=E,h.push(x)))}}let w=a.shift();s=w?h.concat(w):h}return n.length>1&&n.sort((u,f)=>u.score-f.score),[n.map(({handler:u,params:f})=>[u,f])]}};var Qe=class{name="TrieRouter";#t;constructor(){this.#t=new nr}add(e,t,r){let n=xe(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(e,n[o],r);return}this.#t.insert(e,t,r)}match(e,t){return this.#t.search(e,t)}};var Ze=class extends Jt{constructor(e={}){super(e),this.router=e.router??new Je({routers:[new Se,new Qe]})}};var Pe=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 f=s.req.header("Access-Control-Request-Headers");f&&(u=f.split(/\s*,\s*/))}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 vr from"process";import Rr from"path";import{fileURLToPath as No}from"url";import Uo from"child_process";import Do,{constants as Ho}from"fs/promises";import{promisify as ho}from"util";import mo from"child_process";import ot,{constants as dr}from"fs/promises";import ar from"process";import ao from"os";import co from"fs";import so from"fs";import sr from"fs";var et;function no(){try{return sr.statSync("/.dockerenv"),!0}catch{return!1}}function oo(){try{return sr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function tt(){return et===void 0&&(et=no()||oo()),et}var rt,io=()=>{try{return so.statSync("/run/.containerenv"),!0}catch{return!1}};function Q(){return rt===void 0&&(rt=io()||tt()),rt}var ir=()=>{if(ar.platform!=="linux")return!1;if(ao.release().toLowerCase().includes("microsoft"))return!Q();try{return co.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Q():!1}catch{return!1}},k=ar.env.__IS_WSL_TEST__?ir:ir();import cr from"process";import{Buffer as lo}from"buffer";import{promisify as uo}from"util";import fo from"child_process";import xa,{constants as ba}from"fs/promises";var po=uo(fo.execFile),nt=()=>`${cr.env.SYSTEMROOT||cr.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 po(r??nt(),[...O.argumentsPrefix,o],{encoding:"utf8",...n})};O.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];O.encodeCommand=e=>lo.from(e,"utf16le").toString("base64");O.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function lr(e){for(let t of e.split(`
3
- `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var go=ho(mo.execFile),wo=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await ot.access(r,dr.F_OK),n=!0}catch{}if(!n)return e;let o=await ot.readFile(r,{encoding:"utf8"}),s=lr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),yo=async()=>`${await wo()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ae=k?yo:nt,ur,fr=async()=>(ur??=(async()=>{try{let e=await Ae();return await ot.access(e,dr.X_OK),!0}catch{return!1}})(),ur),pr=async()=>{let e=await Ae(),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()},hr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await go("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function W(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 To}from"util";import ut from"process";import{execFile as Io}from"child_process";import{promisify as xo}from"util";import bo from"process";import{execFile as vo}from"child_process";var Ro=xo(vo);async function st(){if(bo.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await Ro("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 Eo from"process";import{promisify as So}from"util";import{execFile as Po,execFileSync as ja}from"child_process";var Ao=So(Po);async function mr(e,{humanReadableOutput:t=!0,signal:r}={}){if(Eo.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Ao("osascript",["-e",e,n],o);return s.trim()}async function it(e){return mr(`tell application "Finder" to set app_path to application file id "${e}" as string
4
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as _o}from"util";import{execFile as Co}from"child_process";var Oo=_o(Co),_e={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"}},ct=new Map(Object.entries(_e)),at=class extends Error{};async function lt(e=Oo){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 at(`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 _e[n]??_e[i]??_e[a]??{name:n,id:n}}var Mo=To(Io),Lo=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function dt(){if(ut.platform==="darwin"){let e=await st();return{name:await it(e),id:e}}if(ut.platform==="linux"){let{stdout:e}=await Mo("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Lo(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(ut.platform==="win32")return lt();throw new Error("Only macOS, Linux, and Windows are supported")}import ft from"process";var ko=!!(ft.env.SSH_CONNECTION||ft.env.SSH_CLIENT||ft.env.SSH_TTY),gr=ko;var Ce=Symbol("fallbackAttempt"),pt=import.meta.url?Rr.dirname(No(import.meta.url)):"",wr=Rr.join(pt,"xdg-open"),{platform:Z,arch:yr}=vr,xr=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")},Oe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[Ce]===!0;if(delete e[Ce],Array.isArray(e.app))return xr(e.app,l=>Oe({...e,app:l,[Ce]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return xr(r,l=>Oe({...e,app:{name:l,arguments:n},[Ce]:!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"},f;if(k){let p=await pr();f=ct.get(p)??{}}else f=await dt();if(f.id in l){let p=l[f.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 Oe({...e,app:{name:ee[p],arguments:n}})}throw new Error(`${f.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(k&&!Q()&&!gr&&!r&&(a=await fr()),Z==="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(Z==="win32"||a){o=await Ae(),s.push(...O.argumentsPrefix),k||(i.windowsVerbatimArguments=!0),k&&e.target&&(e.target=await hr(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=!pt||pt==="/",u=!1;try{await Do.access(wr,Ho.X_OK),u=!0}catch{}o=vr.versions.electron??(Z==="android"||l||!u)?"xdg-open":wr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}Z==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Uo.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",f=>{if(!e.allowNonzeroExitCode&&f!==0){u(new Error(`Exited with code ${f}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",f=>{if(c.off("error",u),f!==0){u(new Error(`Exited with code ${f}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},jo=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Oe({...t,target:e})};function br(e){if(typeof e=="string"||Array.isArray(e))return e;let{[yr]:t}=e;if(!t)throw new Error(`${yr} is not supported`);return t}function le({[Z]:e},{wsl:t}={}){if(t&&k)return br(t);if(!e)throw new Error(`${Z} is not supported`);return br(e)}var ee={browser:"browser",browserPrivate:"browserPrivate"};W(ee,"chrome",()=>le({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"]}}));W(ee,"brave",()=>le({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"]}}));W(ee,"firefox",()=>le({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));W(ee,"edge",()=>le({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));W(ee,"safari",()=>le({darwin:"Safari"}));var Er=jo;function Sr(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Ur,readFileSync as zo}from"fs";import U from"path";import{fileURLToPath as Wo}from"url";import{gunzipSync as Ko}from"zlib";var N=xn(Nr(),1);function te(e,t){return e.header("Retry-After",String(Fo(t))),e.json({error:"Too Many Requests"},429)}function Fo(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 Vo={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Go(){let e=U.dirname(Wo(import.meta.url));for(let t of[U.resolve(e,"app"),U.resolve(e,"../app"),U.resolve(e,"../../dist/app")])if(Ur(U.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Dr(e,t="/inspector/assets"){let r=Go(),n=new Map,o=new N.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return te(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=U.resolve(r,l),f=r.endsWith(U.sep)?r:`${r}${U.sep}`;if(!u.startsWith(f)||!Ur(u))return i.notFound();let p=U.extname(c),h=l.endsWith(".gz"),w=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),y=zo(u),g=h&&!w?n.get(u)??Xo(n,u,y):y,d=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(d,200,{"Content-Type":Vo[p]??"application/octet-stream",...h&&w?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Xo(e,t,r){let n=Ko(r);return e.set(t,n),n}var Hr={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.42",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"}},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_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} 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","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.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","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":"workspace:*",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},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":"^1.19.13","@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.12","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":"^7.12.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",zod:"^4.2.0"}};var Jo=Hr.version;function Te(){return Jo}var jr=Te(),Qo=`<!doctype html>
2
+ var pn=Object.create;var Pt=Object.defineProperty;var hn=Object.getOwnPropertyDescriptor;var mn=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,wn=Object.prototype.hasOwnProperty;var re=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var yn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mn(t))!wn.call(e,o)&&o!==r&&Pt(e,o,{get:()=>t[o],enumerable:!(n=hn(t,o))||n.enumerable});return e};var xn=(e,t,r)=>(r=e!=null?pn(gn(e)):{},yn(t||!e||!e.__esModule?Pt(r,"default",{value:e,enumerable:!0}):r,e));var Ar=re((yc,Pr)=>{"use strict";Pr.exports=class{constructor(t={}){this.points=t.points,this.duration=t.duration,this.blockDuration=t.blockDuration,this.execEvenly=t.execEvenly,this.execEvenlyMinDelayMs=t.execEvenlyMinDelayMs,this.keyPrefix=t.keyPrefix}get points(){return this._points}set points(t){if(Number.isFinite(t))this._points=t;else throw new Error("points must be set and must be a finite number")}get duration(){return this._duration}set duration(t){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)this._duration=t;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(t){this._blockDuration=typeof t>"u"?0:t}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(t){this._execEvenly=typeof t>"u"?!1:!!t}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs===void 0?this._getExecEvenlyMinDelayMsDefault():this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(t){this._execEvenlyMinDelayMs=t}_getExecEvenlyMinDelayMsDefault(){return this.points>0?Math.ceil(this.msDuration/this.points):0}get keyPrefix(){return this._keyPrefix}set keyPrefix(t){if(typeof t>"u"&&(t="rlflx"),typeof t!="string")throw new Error("keyPrefix must be string");this._keyPrefix=t}_getKeySecDuration(t={}){return t&&t.customDuration>=0?t.customDuration:this.duration}getKey(t){return this.keyPrefix.length>0?`${this.keyPrefix}:${t}`:t}parseKey(t){return this.keyPrefix.length>0?t.substring(this.keyPrefix.length+1):t}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 Cr=re((bc,_r)=>{"use strict";_r.exports=class{constructor(t,r,n=null){this.value=t,this.expiresAt=r,this.timeoutId=n}get value(){return this._value}set value(t){this._value=parseInt(t,10)}get expiresAt(){return this._expiresAt}set expiresAt(t){t instanceof Date?this._expiresAt=t.getTime():this._expiresAt=t}get timeoutId(){return this._timeoutId}set timeoutId(t){this._timeoutId=t}}});var ht=re((Rc,Or)=>{"use strict";Or.exports=class{constructor(t,r,n,o){this.remainingPoints=typeof t>"u"?0:t,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(t){return this._msBeforeNext=t,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(t){return this._remainingPoints=t,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(t){return this._consumedPoints=t,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(t){this._isFirstInDuration=!!t}_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 Ir=re((Sc,Lr)=>{"use strict";var Tr=Cr(),mt=ht();Lr.exports=class{constructor(){this._storage=new Map}incrby(t,r,n){let o=this._storage.get(t);if(o){let s=o.expiresAt?o.expiresAt-Date.now():-1;return!o.expiresAt||s>0?(o.value=o.value+r,new mt(0,s,o.value,!1)):this.set(t,r,n)}return this.set(t,r,n)}set(t,r,n){let o=n*1e3,s=this._storage.get(t);s&&s.timeoutId&&clearTimeout(s.timeoutId);let i=new Tr(r,o>0?Date.now()+o:null);return this._storage.set(t,i),o>0&&(i.timeoutId=setTimeout(()=>{this._storage.delete(t)},o),i.timeoutId.unref&&i.timeoutId.unref()),new mt(0,o===0?-1:o,i.value,!0)}get(t){let r=this._storage.get(t);if(r){let n=r.expiresAt?r.expiresAt-Date.now():-1;return new mt(0,n,r.value,!1)}return null}delete(t){let r=this._storage.get(t);return r?(r.timeoutId&&clearTimeout(r.timeoutId),this._storage.delete(t),!0):!1}_restoreRecord(t,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(t);a&&a.timeoutId&&clearTimeout(a.timeoutId);let c=new Tr(r,n);this._storage.set(t,c),i>0&&(c.timeoutId=setTimeout(()=>{this._storage.delete(t)},i),c.timeoutId.unref&&c.timeoutId.unref())}}});var Ur=re((Pc,kr)=>{"use strict";var $o=Ar(),Bo=Ir(),Mr=ht(),gt=class extends $o{constructor(t={}){super(t),this._memoryStorage=new Bo}consume(t,r=1,n={}){return new Promise((o,s)=>{let i=this.getKey(t),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(t,r=1,n={}){let o=this.getKey(t);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(t,r=1,n={}){let o=this.getKey(t);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(t,r){let n=r*1e3,o=this.points+1;return this._memoryStorage.set(this.getKey(t),o,r),Promise.resolve(new Mr(0,n===0?-1:n,o))}set(t,r,n){let o=(n>=0?n:this.duration)*1e3;return this._memoryStorage.set(this.getKey(t),r,n),Promise.resolve(new Mr(0,o===0?-1:o,r))}get(t){let r=this._memoryStorage.get(this.getKey(t));return r!==null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),Promise.resolve(r)}delete(t){return Promise.resolve(this._memoryStorage.delete(this.getKey(t)))}dump(){let t=[];for(let[r,n]of this._memoryStorage._storage)t.push({key:this.parseKey(r),value:n.value,expiresAt:n.expiresAt});return{version:1,dumpedAt:Date.now(),storage:t}}restore(t,r=!1){if(!t||typeof t!="object"||t.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(t.storage))return n;for(let s of t.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}};kr.exports=gt});import{createServer as bn}from"http";import{Http2ServerRequest as Ot,constants as vn}from"http2";import{Http2ServerRequest as Ue}from"http2";import{Readable as At}from"stream";import Mn from"crypto";var F=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},Rn=e=>e instanceof F?e:new F(e.message,{cause:e}),En=global.Request,ne=class extends En{constructor(e,t){typeof e=="object"&&Y in e&&(e=e[Y]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},Sn=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},Tt=Symbol("wrapBodyStream"),Pn=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new ne(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[Tt]){let i;s.body=new ReadableStream({async pull(a){try{i||=At.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=At.toWeb(n);return new ne(t,s)},Y=Symbol("getRequestCache"),An=Symbol("requestCache"),pe=Symbol("incomingKey"),he=Symbol("urlKey"),_n=Symbol("headersKey"),X=Symbol("abortControllerKey"),Cn=Symbol("getAbortController"),me={get method(){return this[pe].method||"GET"},get url(){return this[he]},get headers(){return this[_n]||=Sn(this[pe])},[Cn](){return this[Y](),this[X]},[Y](){return this[X]||=new AbortController,this[An]||=Pn(this.method,this[he],this.headers,this[pe],this[X])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(me,e,{get(){return this[Y]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(me,e,{value:function(){return this[Y]()[e]()}})});Object.setPrototypeOf(me,ne.prototype);var On=(e,t)=>{let r=Object.create(me);r[pe]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof Ue)throw new F("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[he]=a.href}catch(a){throw new F("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof Ue?e.authority:e.headers.host)||t;if(!o)throw new F("Missing host header");let s;if(e instanceof Ue){if(s=e.scheme,!(s==="http"||s==="https"))throw new F("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new F("Invalid host header");return r[he]=i.href,r},_t=Symbol("responseCache"),G=Symbol("getResponseCache"),q=Symbol("cache"),je=global.Response,oe=class Lt{#t;#e;[G](){return delete this[q],this[_t]||=new je(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof Lt){let o=r[_t];if(o){this.#e=o,this[G]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[q]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[q];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[G]().headers}get status(){return this[q]?.[0]??this[G]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(oe.prototype,e,{get(){return this[G]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(oe.prototype,e,{value:function(){return this[G]()[e]()}})});Object.setPrototypeOf(oe,je);Object.setPrototypeOf(oe.prototype,je.prototype);async function Tn(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function It(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function Ln(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:It(e.getReader(),t)}var De=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},In="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=Mn);var $e=Symbol("outgoingEnded"),Ct=Symbol("incomingDraining"),kn=500,Un=64*1024*1024,Ne=e=>{let t=e;if(e.destroyed||t[Ct])return;if(t[Ct]=!0,e instanceof Ot){try{e.stream?.close?.(vn.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,kn);s.unref?.();let i=a=>{r+=a.length,r>Un&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},Nn=()=>new Response(null,{status:400}),Mt=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),He=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},kt=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Ut=async(e,t)=>{let[r,n,o]=e[q],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=De(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=De(i)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(kt(t),await Ln(n,t)?.catch(i=>He(i,t))),t[$e]?.()},Dn=e=>typeof e.then=="function",Hn=async(e,t,r={})=>{if(Dn(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(Mt);if(q in e)return Ut(e,t);let n=De(e.headers);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await Tn(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&kt(t),await It(o,t,a))}else n[In]||(t.writeHead(e.status,n),t.end());t[$e]?.()},jn=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==ne&&(Object.defineProperty(global,"Request",{value:ne}),Object.defineProperty(global,"Response",{value:oe})),async(n,o)=>{let s,i;try{i=On(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[Tt]=!0,n.on("end",()=>{a=!0}),n instanceof Ot&&(o[$e]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Ne(n)})})}),o.on("finish",()=>{a||Ne(n)})),o.on("close",()=>{i[X]&&(n.errored?i[X].abort(n.errored.toString()):o.writableFinished||i[X].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Ne(n)})})}),s=e(i,{incoming:n,outgoing:o}),q in s)return Ut(s,o)}catch(a){if(s)return He(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:Rn(a)),!s)return}else i?s=Mt(a):s=Nn()}try{return await Hn(s,o,t)}catch(a){return He(a,o)}}},$n=e=>{let t=e.fetch,r=jn(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||bn)(e.serverOptions||{},r)},Nt=(e,t)=>{let r=$n(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var Be=(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 Dt=Symbol();var Ht=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(e instanceof ge?e.raw.headers:e.headers).get("Content-Type");return s?.startsWith("multipart/form-data")||s?.startsWith("application/x-www-form-urlencoded")?Bn(e,{all:r,dot:n}):{}};async function Bn(e,t){let r=await e.formData();return r?Fn(r,t):{}}function Fn(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?qn(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(zn(r,n,o),delete r[n])}),r}var qn=(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},zn=(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 qe=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},jt=e=>{let{groups:t,path:r}=Wn(e),n=qe(r);return Kn(n,t)},Wn=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Kn=(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},we={},$t=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return we[n]||(r[2]?we[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:we[n]=[e,r[1],!0]),we[n]}return null},ye=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Vn=e=>ye(e,decodeURI),ze=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 Vn(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var Bt=e=>{let t=ze(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},D=(e,t,...r)=>(r.length&&(t=D(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),xe=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)},Fe=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?ye(e,We):e):e,Ft=(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 Fe(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={};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=Fe(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=Fe(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},qt=Ft,zt=(e,t)=>Ft(e,t,!0),We=decodeURIComponent;var Wt=e=>ye(e,We),ge=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r,this.#t={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Wt(r):r}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Wt(n):n)}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return qt(this.url,e)}queries(e){return zt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Ht(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.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Dt](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Kt={Stringify:1,BeforeStream:2,Stream:3},Gn=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Ke=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=>Ke(c,t,!1,n,o))).then(()=>o[0]));return r?Gn(await i,s):i};var Xn="text/plain; charset=UTF-8",Ve=(e,t)=>({"Content-Type":e,...t}),se=(e,t)=>new Response(e,t),Ge=class{#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#t=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.#e??=new ge(this.#t,this.#f,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||=se(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=se(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=se(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 se(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,Ve(Xn,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,Ve("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,Ve("text/html; charset=UTF-8",r));return typeof e=="object"?Ke(e,Kt.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??=()=>se(),this.#l(this))};var v="ALL",Vt="all",Gt=["get","post","put","delete","options","patch"],be="Can not add a route since the matcher is already built.",ve=class extends Error{};var Xt="__COMPOSED_HANDLER";var Yn=e=>e.text("404 Not Found",404),Yt=(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)},Jt=class Qt{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Gt,Vt].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}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??ze:Bt}#e(){let t=new Qt({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Yn;errorHandler=Yt;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Yt?s=o.handler:(s=async(i,a)=>(await Be([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[Xt]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=D(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=D(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(v,D(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=D(this._basePath,r);let s={basePath:o!==void 0?D(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 Ge(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=Be(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${D("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var Re=[];function Xe(e,t){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(e,t)}var Ee="[^/]+",ie=".*",ae="(?:|/.*)",z=Symbol(),Jn=new Set(".\\+*[^]$()");function Qn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===ie||e===ae?1:t===ie||t===ae?-1:e===Ee?1:t===Ee?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Zt=class Ye{#t;#e;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#t!==void 0)throw z;if(s)return;this.#t=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",ie]:["","",Ee]:i==="/*"?["","",ae]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||Ee;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw z;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(p=>p!==ie&&p!==ae))throw z;if(s)return;l=this.#r[d]=new Ye,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!==ie&&u!==ae))throw z;if(s)return;l=this.#r[i]=new Ye}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Qn).map(n=>{let o=this.#r[n];return(typeof o.#e=="number"?`(${n})@${o.#e}`:Jn.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 er=class{#t={varIndex:0};#e=new Zt;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.#e.insert(s,t,n,this.#t,r),n}buildRegExp(){let e=this.#e.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 Zn=[/^$/,[],Object.create(null)],tr=Object.create(null);function rr(e){return tr[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function eo(){tr=Object.create(null)}function to(e){let t=new er,r=[];if(e.length===0)return Zn;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,h,w]=n[l];p?o[h]=[w.map(([g])=>[g,Object.create(null)]),Re]:u++;let y;try{y=t.insert(h,u,p)}catch(g){throw g===z?new ve(h):g}p||(r[u]=w.map(([g,f])=>{let m=Object.create(null);for(f-=1;f>=0;f--){let[b,T]=y[f];m[b]=T}return[g,m]}))}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 h=r[l][d]?.[1];if(!h)continue;let w=Object.keys(h);for(let y=0,g=w.length;y<g;y++)h[w[y]]=a[h[w[y]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function J(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(rr(r).test(t))return[...e[r]]}}var Se=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[v]:Object.create(null)},this.#e={[v]:Object.create(null)}}add(e,t,r){let n=this.#t,o=this.#e;if(!n||!o)throw new Error(be);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[v]).forEach(c=>{a[e][c]=[...a[v][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=rr(t);e===v?Object.keys(n).forEach(c=>{n[c][t]||=J(n[c],t)||J(n[v],t)||[]}):n[e][t]||=J(n[e],t)||J(n[v],t)||[],Object.keys(n).forEach(c=>{(e===v||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===v||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=xe(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===v||e===u)&&(o[u][l]||=[...J(n[u],l)||J(n[v],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=Xe;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,eo(),e}#r(e){let t=[],r=e===v;return[this.#t,this.#e].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!==v&&t.push(...Object.keys(n[v]).map(s=>[s,n[v][s]]))}),r?to(t):null}};var Je=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(be);this.#e.push([e,t,r])}match(e,t){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(e,t)}catch(c){if(c instanceof ve)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 ce=Object.create(null),ro=e=>{for(let t in e)return!0;return!1},nr=class or{#t;#e;#r;#s=0;#o=ce;constructor(t,r,n){if(this.#e=n||Object.create(null),this.#t=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=jt(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],d=$t(l,u),p=Array.isArray(d)?d[0]:l;if(p in o.#e){o=o.#e[p],d&&i.push(d[1]);continue}o.#e[p]=new or,d&&(o.#r.push(d),i.push(d[1])),o=o.#e[p]}return o.#t.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.#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),t.push(l),o!==ce||s&&s!==ce))for(let d=0,p=l.possibleKeys.length;d<p;d++){let h=l.possibleKeys[d],w=u[l.score];l.params[h]=s?.[h]&&!w?s[h]:o[h]??s?.[h],u[l.score]=!0}}}search(t,r){let n=[];this.#o=ce;let s=[this],i=qe(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],p=u===c-1,h=[];for(let y=0,g=s.length;y<g;y++){let f=s[y],m=f.#e[d];m&&(m.#o=f.#o,p?(m.#e["*"]&&this.#n(n,m.#e["*"],t,f.#o),this.#n(n,m,t,f.#o)):h.push(m));for(let b=0,T=f.#r.length;b<T;b++){let L=f.#r[b],E=f.#o===ce?{}:{...f.#o};if(L==="*"){let P=f.#e["*"];P&&(this.#n(n,P,t,f.#o),P.#o=E,h.push(P));continue}let[S,A,R]=L;if(!d&&!(R instanceof RegExp))continue;let x=f.#e[S];if(R instanceof RegExp){if(l===null){l=new Array(c);let j=r[0]==="/"?1:0;for(let $=0;$<c;$++)l[$]=j,j+=i[$].length+1}let P=r.substring(l[u]),I=R.exec(P);if(I){if(E[A]=I[0],this.#n(n,x,t,f.#o,E),ro(x.#e)){x.#o=E;let j=I[0].match(/\//)?.length??0;(a[j]||=[]).push(x)}continue}}(R===!0||R.test(d))&&(E[A]=d,p?(this.#n(n,x,t,E,f.#o),x.#e["*"]&&this.#n(n,x.#e["*"],t,E,f.#o)):(x.#o=E,h.push(x)))}}let w=a.shift();s=w?h.concat(w):h}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var Qe=class{name="TrieRouter";#t;constructor(){this.#t=new nr}add(e,t,r){let n=xe(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#t.insert(e,n[o],r);return}this.#t.insert(e,t,r)}match(e,t){return this.#t.search(e,t)}};var Ze=class extends Jt{constructor(e={}){super(e),this.router=e.router??new Je({routers:[new Se,new Qe]})}};var Pe=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(/\s*,\s*/))}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 vr from"process";import Rr from"path";import{fileURLToPath as Uo}from"url";import No from"child_process";import Do,{constants as Ho}from"fs/promises";import{promisify as ho}from"util";import mo from"child_process";import ot,{constants as dr}from"fs/promises";import ar from"process";import ao from"os";import co from"fs";import so from"fs";import sr from"fs";var et;function no(){try{return sr.statSync("/.dockerenv"),!0}catch{return!1}}function oo(){try{return sr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function tt(){return et===void 0&&(et=no()||oo()),et}var rt,io=()=>{try{return so.statSync("/run/.containerenv"),!0}catch{return!1}};function Q(){return rt===void 0&&(rt=io()||tt()),rt}var ir=()=>{if(ar.platform!=="linux")return!1;if(ao.release().toLowerCase().includes("microsoft"))return!Q();try{return co.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Q():!1}catch{return!1}},k=ar.env.__IS_WSL_TEST__?ir:ir();import cr from"process";import{Buffer as lo}from"buffer";import{promisify as uo}from"util";import fo from"child_process";import va,{constants as Ra}from"fs/promises";var po=uo(fo.execFile),nt=()=>`${cr.env.SYSTEMROOT||cr.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 po(r??nt(),[...O.argumentsPrefix,o],{encoding:"utf8",...n})};O.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];O.encodeCommand=e=>lo.from(e,"utf16le").toString("base64");O.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function lr(e){for(let t of e.split(`
3
+ `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var go=ho(mo.execFile),wo=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await ot.access(r,dr.F_OK),n=!0}catch{}if(!n)return e;let o=await ot.readFile(r,{encoding:"utf8"}),s=lr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),yo=async()=>`${await wo()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ae=k?yo:nt,ur,fr=async()=>(ur??=(async()=>{try{let e=await Ae();return await ot.access(e,dr.X_OK),!0}catch{return!1}})(),ur),pr=async()=>{let e=await Ae(),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()},hr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await go("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function W(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 To}from"util";import ut from"process";import{execFile as Lo}from"child_process";import{promisify as xo}from"util";import bo from"process";import{execFile as vo}from"child_process";var Ro=xo(vo);async function st(){if(bo.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await Ro("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 Eo from"process";import{promisify as So}from"util";import{execFile as Po,execFileSync as Ba}from"child_process";var Ao=So(Po);async function mr(e,{humanReadableOutput:t=!0,signal:r}={}){if(Eo.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Ao("osascript",["-e",e,n],o);return s.trim()}async function it(e){return mr(`tell application "Finder" to set app_path to application file id "${e}" as string
4
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as _o}from"util";import{execFile as Co}from"child_process";var Oo=_o(Co),_e={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"}},ct=new Map(Object.entries(_e)),at=class extends Error{};async function lt(e=Oo){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 at(`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 _e[n]??_e[i]??_e[a]??{name:n,id:n}}var Io=To(Lo),Mo=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function dt(){if(ut.platform==="darwin"){let e=await st();return{name:await it(e),id:e}}if(ut.platform==="linux"){let{stdout:e}=await Io("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Mo(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(ut.platform==="win32")return lt();throw new Error("Only macOS, Linux, and Windows are supported")}import ft from"process";var ko=!!(ft.env.SSH_CONNECTION||ft.env.SSH_CLIENT||ft.env.SSH_TTY),gr=ko;var Ce=Symbol("fallbackAttempt"),pt=import.meta.url?Rr.dirname(Uo(import.meta.url)):"",wr=Rr.join(pt,"xdg-open"),{platform:Z,arch:yr}=vr,xr=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")},Oe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[Ce]===!0;if(delete e[Ce],Array.isArray(e.app))return xr(e.app,l=>Oe({...e,app:l,[Ce]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return xr(r,l=>Oe({...e,app:{name:l,arguments:n},[Ce]:!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(k){let p=await pr();d=ct.get(p)??{}}else d=await dt();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 Oe({...e,app:{name:ee[p],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(k&&!Q()&&!gr&&!r&&(a=await fr()),Z==="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(Z==="win32"||a){o=await Ae(),s.push(...O.argumentsPrefix),k||(i.windowsVerbatimArguments=!0),k&&e.target&&(e.target=await hr(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=!pt||pt==="/",u=!1;try{await Do.access(wr,Ho.X_OK),u=!0}catch{}o=vr.versions.electron??(Z==="android"||l||!u)?"xdg-open":wr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}Z==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=No.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)})}))},jo=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Oe({...t,target:e})};function br(e){if(typeof e=="string"||Array.isArray(e))return e;let{[yr]:t}=e;if(!t)throw new Error(`${yr} is not supported`);return t}function le({[Z]:e},{wsl:t}={}){if(t&&k)return br(t);if(!e)throw new Error(`${Z} is not supported`);return br(e)}var ee={browser:"browser",browserPrivate:"browserPrivate"};W(ee,"chrome",()=>le({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"]}}));W(ee,"brave",()=>le({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"]}}));W(ee,"firefox",()=>le({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));W(ee,"edge",()=>le({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));W(ee,"safari",()=>le({darwin:"Safari"}));var Er=jo;function Sr(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as Nr,readFileSync as zo}from"fs";import N from"path";import{fileURLToPath as Wo}from"url";import{gunzipSync as Ko}from"zlib";var U=xn(Ur(),1);function te(e,t){return e.header("Retry-After",String(Fo(t))),e.json({error:"Too Many Requests"},429)}function Fo(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 Vo={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Go(){let e=N.dirname(Wo(import.meta.url));for(let t of[N.resolve(e,"app"),N.resolve(e,"../app"),N.resolve(e,"../../dist/app")])if(Nr(N.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function Dr(e,t="/inspector/assets"){let r=Go(),n=new Map,o=new U.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return te(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=N.resolve(r,l),d=r.endsWith(N.sep)?r:`${r}${N.sep}`;if(!u.startsWith(d)||!Nr(u))return i.notFound();let p=N.extname(c),h=l.endsWith(".gz"),w=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),y=zo(u),g=h&&!w?n.get(u)??Xo(n,u,y):y,f=g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength);return i.body(f,200,{"Content-Type":Vo[p]??"application/octet-stream",...h&&w?{"Content-Encoding":"gzip"}:{},...h?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Xo(e,t,r){let n=Ko(r);return e.set(t,n),n}var Hr={name:"@mcp-use/inspector",type:"module",version:"20.0.0-beta.44",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"}},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_MANUFACT_CHAT_URL=${VITE_MANUFACT_CHAT_URL:-http://localhost:8000/api/v1/inspector/chat/stream} 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","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.0-alpha.0","@mcp-use/client":"^2.0.0-alpha.0","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":"workspace:*",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},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":"^1.19.13","@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.12","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":"^7.12.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",zod:"^4.2.0"}};var Jo=Hr.version;function Te(){return Jo}import{buildSandboxProxyBlobHtml as Qo}from"@mcp-use/client/react";var jr=Te();function Zo(e){let t=e.hostname==="localhost"?"127.0.0.1":e.hostname==="127.0.0.1"||e.hostname==="::1"?"localhost":void 0;if(!t)return;let r=new URL(e.origin);return r.hostname=t,r.origin}var es=`<!doctype html>
5
5
  <html lang="en"><head><meta charset="utf-8"><title>Signed in</title><meta name="robots" content="noindex"><style>html,body{margin:0;height:100%;display:flex;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#4b5563;background:#fff}</style></head>
6
6
  <body><div>Signed in. You can close this window.</div>
7
7
  <script>try{if(window.opener&&!window.opener.closed)window.opener.postMessage({type:"manufact:oauth-complete"},"*")}catch(e){}try{window.close()}catch(e){}</script>
8
- </body></html>`;function Zo(e,t,r){let n=[];e?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(e.basePath)};</script>`),e?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),e?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(e.sandboxOrigin)};</script>`),e?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(e.proxyUrl)};</script>`),e?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(e.inspectorMode)};</script>`),e?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(e.manufactChatUrl)};</script>`),e?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
8
+ </body></html>`;function ts(e,t,r){let n=[];e?.basePath!==void 0&&n.push(`<script>window.__MCP_BASE_PATH__ = ${JSON.stringify(e.basePath)};</script>`),e?.devMode&&n.push("<script>window.__MCP_DEV_MODE__ = true;</script>"),e?.sandboxOrigin&&n.push(`<script>window.__MCP_SANDBOX_ORIGIN__ = ${JSON.stringify(e.sandboxOrigin)};</script>`),e?.proxyUrl!==void 0&&n.push(`<script>window.__MCP_PROXY_URL__ = ${JSON.stringify(e.proxyUrl)};</script>`),e?.inspectorMode&&n.push(`<script>window.__MCP_INSPECTOR_MODE__ = ${JSON.stringify(e.inspectorMode)};</script>`),e?.manufactChatUrl&&n.push(`<script>window.__MANUFACT_CHAT_URL__ = ${JSON.stringify(e.manufactChatUrl)};</script>`),e?.disableTelemetry&&n.push('<script>window.__MCP_USE_ANONYMIZED_TELEMETRY__ = false;try{localStorage.setItem("MCP_USE_ANONYMIZED_TELEMETRY","false");}catch(e){}</script>'),process.env.MCP_USE_DEV_CLI==="1"&&n.push("<script>window.__MCP_DEV_CLI__ = true;</script>");let o=n.join(`
9
9
  `);return`<!doctype html>
10
10
  <html lang="en">
11
11
  <head>
@@ -97,9 +97,9 @@ tell application "System Events" to get value of property list item "CFBundleNam
97
97
  </div>
98
98
  <script type="module" src="${r.jsUrl}"></script>
99
99
  </body>
100
- </html>`}function $r(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(jr),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...t,basePath:t?.basePath??r,proxyUrl:t?.proxyUrl!==void 0?t.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:t?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>u.html(Zo(a,r,s));Dr(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(Qo)),e.get(i("/inspector"),c),e.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");e.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),e.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&t?.rootRedirect!==!1&&e.get("/",u=>{let f=new URL(u.req.url);return u.redirect(`${i("/inspector")}${f.search}`)})}function es(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function Br(){let{navigator:e}=globalThis,t="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(t)).env??{})}catch{return!1}})():!es())}var ts=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},rs=e=>{let t=Date.now()-e;return ts([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},ns=async e=>{if(await Br())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function Fr(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await ns(o)} ${s}`;e(i)}var qr=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Fr(e,"<--",o,i);let a=Date.now();await n(),await Fr(e,"-->",o,i,r.res.status,rs(a))};import{lookup as os}from"dns/promises";import{Buffer as ss}from"buffer";import{isIP as is}from"net";var as=new Set(["accept","authorization","content-type","dpop"]),cs=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),ls=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Yr=600*1e3,us=100,ds=1440*60*1e3,fs=500;function vt(e,t={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:f,rateLimiter:p=new N.default({points:120,duration:60})}=t,h=new Set(n.map(bt)),w=new Map,y=new Map,g=async(d,m)=>{try{await p.consume(d.req)}catch(b){return te(d,b)}return m()};e.use(`${r}/*`,async(d,m)=>{let b=d.req.header("Origin");if(b&&!vs(b,d,h))return d.json({error:"Origin not allowed"},403);if(d.req.method==="OPTIONS")return Rs(b);await m(),b&&nn(d.res.headers,b)}),e.use(`${r}/*`,g),e.get(`${r}/metadata`,async d=>{if(!await Xr(d,u))return d.json({error:"Unauthorized"},401);let m=await V(d.req.query("serverUrl"),o);if("error"in m)return d.json({error:m.error},400);let b=m.url;if(f&&!await f(b.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let T=await V(d.req.query("url"),o);if("error"in T)return d.json({error:T.error},400);let I=T.url,E=L(b),S=Vr(w,E),A=zr(b,I,S);if(!A&&S.authorizationServers.size===0)try{await Wr(b,S,o,s,a),w.set(E,S),A=zr(b,I,S)}catch{}if(!A)return d.json({error:"Metadata target is not bound to this MCP server"},403);try{wt(l,`GET ${I}`);let R=await Ie(I,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(Le(R.status))return d.json({error:"OAuth metadata redirects are not allowed"},502);let x=await Me(R,a);if(!R.ok)return d.body(x,R.status,{"Content-Type":R.headers.get("content-type")??"application/json"});let P=xt(x);return A.type==="protected-resource"?await Zr(P,b,S,o):await en(P,A.issuer,S,o),S.updatedAt=Date.now(),w.set(E,S),Gr(w),d.body(x,200,{"Content-Type":R.headers.get("content-type")??"application/json"})}catch(R){return yt(d,R,l)}}),e.post(`${r}/proxy`,async d=>{if(!await Xr(d,u))return d.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await xs(d.req.raw,i))}catch(x){return d.json({error:x instanceof H?"Request body too large":"Invalid JSON request body"},x instanceof H?413:400)}let b=await V(m.serverUrl,o);if("error"in b)return d.json({error:b.error},400);let T=b.url;if(f&&!await f(T.toString(),d))return d.json({error:"MCP server URL not allowed"},403);let I=await V(m.url,o);if("error"in I)return d.json({error:I.error},400);let E=I.url;if(m.method!==void 0&&m.method!=="POST")return d.json({error:"Only OAuth endpoint POST is allowed"},405);let S=L(T),A=Vr(w,S);if(A.endpoints.size===0)try{await Wr(T,A,o,s,a),w.set(S,A),Gr(w)}catch(x){return yt(d,x,l)}let R=A.endpoints.get(L(E));if(!R)return d.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let x=ps(m.headers),P=ms(m.body,x);if(R==="registration"){let fn=bt(d.req.header("Origin")??new URL(d.req.url).origin);P=bs(P,x,new URL(c,fn).toString())}else P=ws({body:P,headers:x,bindingKey:S,clients:y});if(new TextEncoder().encode(P??"").byteLength>i)return d.json({error:"OAuth request body too large"},413);wt(l,`POST ${R} ${E}`);let M=await Ie(E,{method:"POST",headers:x,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(Le(M.status))return d.json({error:"OAuth endpoint redirects are not allowed"},502);let j=await Me(M,a),$=hs(M.headers),dn=M.headers.get("content-type")??"",B=j;if(dn.includes("json"))try{B=JSON.parse(j)}catch{}return R==="registration"&&M.ok&&B&&typeof B=="object"&&!Array.isArray(B)&&(B=gs({responseBody:B,binding:A,bindingKey:S,clients:y})),d.json({status:M.status,statusText:M.statusText,headers:$,body:B})}catch(x){return yt(d,x,l)}}),wt(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function V(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=Es(r.hostname);if(r.protocol!=="https:"&&!(t&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return t?{url:r}:{error:"Loopback URL not allowed"};if(Ss(r.hostname))return{error:"Local network URL not allowed"};try{let o=is(r.hostname)?[r.hostname]:(await os(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!on(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Rt(e,t=!1){return!("error"in await V(e,t))}function zr(e,t,r){let n=L(t);if(Jr(e).some(o=>L(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Qr(new URL(o)).some(s=>L(s)===n))return{type:"authorization-server",issuer:o}}function Jr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),new URL("/.well-known/oauth-protected-resource",e.origin)]}function Qr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-authorization-server${t}`,e.origin),new URL(`/.well-known/openid-configuration${t}`,e.origin),new URL(`${t||""}/.well-known/openid-configuration`,e.origin)]}async function Zr(e,t,r,n){if(typeof e.resource!="string"||L(new URL(e.resource))!==L(t))throw new _("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new _("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of e.authorization_servers){let i=await V(s,n);if("error"in i)throw new _(`Unsafe authorization server: ${i.error}`);o.add(L(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function en(e,t,r,n){if(typeof e.issuer!="string"||L(new URL(e.issuer))!==t)throw new _("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(e.token_endpoint_auth_methods_supported)?e.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of ls){let i=e[o];if(i===void 0)continue;let a=await V(i,n);if("error"in a)throw new _(`Unsafe ${o}: ${a.error}`);r.endpoints.set(L(a.url),s)}}async function Wr(e,t,r,n,o){for(let s of Jr(e)){let i=await Ie(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Le(i.status))throw new _("OAuth metadata redirects are not allowed");if(i.ok){await Zr(xt(await Me(i,o)),e,t,r);break}}if(t.authorizationServers.size===0)throw new _("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of Qr(new URL(s))){let c=await Ie(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Le(c.status))throw new _("OAuth metadata redirects are not allowed");if(c.ok){await en(xt(await Me(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0)throw new _("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Ie(e,t){return fetch(e,t)}function ps(e){let t=new Headers;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();as.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function hs(e){let t={};return e.forEach((r,n)=>{cs.has(n.toLowerCase())&&(t[n]=r)}),t}function ms(e,t){if(e==null)return;if(typeof e=="string"){if(!t.has("content-type"))try{JSON.parse(e),t.set("content-type","application/json")}catch{t.set("content-type","application/x-www-form-urlencoded")}return e}if((t.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof e=="object"&&!Array.isArray(e)){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.append(o,String(s));return n.toString()}return t.has("content-type")||t.set("content-type","application/json"),JSON.stringify(e)}function tn(e,t){return`${e}\0${t}`}function gs(e){let{responseBody:t,binding:r,bindingKey:n,clients:o}=e,s=t.client_id,i=t.client_secret;if(typeof s!="string"||typeof i!="string")return t;let a=t.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=t.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+ds;for(ys(o),o.set(tn(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>fs;){let p=o.keys().next().value;if(!p)break;o.delete(p)}let f={...t};return delete f.client_secret,delete f.client_secret_expires_at,f.token_endpoint_auth_method="none",f}function ws(e){let{body:t,headers:r,bindingKey:n,clients:o}=e;if(!t||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return t;let s=new URLSearchParams(t),i=s.get("client_id");if(!i)return t;let a=tn(n,i),c=o.get(a);if(!c)return t;if(c.expiresAt<=Date.now())return o.delete(a),t;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=ss.from(`${Kr(i)}:${Kr(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Kr(e){return new URLSearchParams({value:e}).toString().slice(6)}function ys(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function xs(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new H;return rn(e.body,t)}async function Me(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new H;return rn(e.body,t)}async function rn(e,t){if(!e)return"";let r=e.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>t)throw await r.cancel(),new H;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function xt(e){let t;try{t=JSON.parse(e)}catch{throw new _("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new _("OAuth metadata is not an object");return t}function Vr(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Yr?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Gr(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Yr&&e.delete(r);for(;e.size>us;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function L(e){let t=new URL(e);return t.hash="",(t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80")&&(t.port=""),t.toString().replace(/\/$/,"")}function bs(e,t,r){if(!e||!(t.get("content-type")??"").includes("json"))return e;try{let o=JSON.parse(e);return!o||typeof o!="object"||Array.isArray(o)?e:JSON.stringify({...o,redirect_uris:[r]})}catch{return e}}function bt(e){let t=new URL(e);if(t.pathname!=="/"||t.search||t.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${e}`);return t.origin}function vs(e,t,r){try{let n=bt(e);if(n===new URL(t.req.url).origin||r.has(n))return!0;let o=new URL(n),i=t.req.header("x-forwarded-host")?.split(",")[0]?.trim()||t.req.header("host");if(!i||o.host!==i)return!1;let a=t.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Rs(e){let t=new Headers;return e&&nn(t,e),t.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),t.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:t})}function nn(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Xr(e,t){return t?t(e):!0}function Le(e){return e>=300&&e<400}function Es(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function Ss(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function on(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?on(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let t=e.split(".").map(Number);if(t.length!==4||t.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=t;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function wt(e,t){e&&console.log(`[OAuth BFF] ${t}`)}function yt(e,t,r){let n=t instanceof Error?t.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),t instanceof H?e.json({error:"Upstream response too large"},502):t instanceof _?e.json({error:t.message},502):t instanceof DOMException&&t.name==="TimeoutError"?e.json({error:"OAuth upstream timed out"},504):e.json({error:"OAuth upstream request failed"},502)}var H=class extends Error{},_=class extends Error{};var Ps=3;function As(e,t){return e.includes("text/event-stream")&&!t}function Et(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.rateLimiter??new N.default({points:120,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return te(i,c)}return a()};e.use(`${r}/*`,Pe({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&e.use(`${r}/*`,qr()),e.use(`${r}/*`,s),e.all(`${r}/*`,async i=>{try{if(t.authenticate&&!await t.authenticate(i))return i.json({error:"Unauthorized"},401);let a=i.req.header("X-Target-URL");if(!a)return i.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Rt(a,t.allowLoopback??!1))return i.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(a,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(a)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let c=i.req.method,l={},u=i.req.header();for(let[y,g]of Object.entries(u)){let d=y.toLowerCase();!d.startsWith("x-proxy-")&&!d.startsWith("x-target-")&&!d.startsWith("x-mcp-")&&!d.startsWith("x-forwarded-")&&!d.startsWith("cf-")&&d!=="x-original-host"&&d!=="host"&&d!=="origin"&&d!=="referer"&&d!=="cookie"&&d!=="proxy-authorization"&&d!=="accept-encoding"&&d!=="cdn-loop"&&!d.startsWith("sec-fetch-")&&(l[y]=g)}l["Accept-Encoding"]="identity";let f=c!=="GET"&&c!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,p=a,h=c,w=f;for(let y=0;;y+=1){let g=await fetch(p,{method:h,headers:l,body:w,redirect:"manual"}),d=g.headers.get("location");if(!(g.status>=300&&g.status<400&&d))return _s(g);if(y>=Ps)return i.json({error:"Too many upstream redirects"},502);let m=new URL(d,p);if(!await Rt(m.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(m.toString(),i))return i.json({error:"Redirect target is not allowed"},403);m.origin!==new URL(p).origin&&(ke(l,"authorization"),ke(l,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&h==="POST")&&(h="GET",w=void 0,ke(l,"content-type"),ke(l,"content-length")),p=m.toString()}}catch(a){let c=a instanceof Error?a.message:"Unknown error",l=i.req.header("X-Target-URL");return a instanceof Error&&(a.message.includes("ECONNREFUSED")||a.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${l||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",c,`
100
+ </html>`}function $r(e,t,r=""){let n=`${r}/inspector/assets`,o=encodeURIComponent(jr),s={jsUrl:`${n}/inspector.js?v=${o}`,cssUrl:`${n}/inspector.css?v=${o}`},i=u=>`${r}${u}`,a={...t,basePath:t?.basePath??r,proxyUrl:t?.proxyUrl!==void 0?t.proxyUrl:i("/inspector/api/proxy"),disableTelemetry:t?.disableTelemetry??process.env.MCP_USE_ANONYMIZED_TELEMETRY==="false"},c=u=>{let d=new URL(u.req.url),p={...a,sandboxOrigin:a.sandboxOrigin??Zo(d)??null};return u.html(ts(p,r,s))};Dr(e,n),e.get(i("/inspector/oauth-popup-closed.html"),u=>u.html(es)),e.get(i("/inspector/sandbox"),u=>u.html(Qo(new URL(u.req.url).search))),e.get(i("/inspector"),c),e.get(`${i("/inspector")}/`,c);let l=i("/inspector/api/");e.get(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),e.post(i("/inspector/*"),u=>u.req.path.startsWith(l)?u.notFound():c(u)),r===""&&t?.rootRedirect!==!1&&e.get("/",u=>{let d=new URL(u.req.url);return u.redirect(`${i("/inspector")}${d.search}`)})}function rs(){let{process:e,Deno:t}=globalThis;return!(typeof t?.noColor=="boolean"?t.noColor:e!==void 0?"NO_COLOR"in e?.env:!1)}async function Br(){let{navigator:e}=globalThis,t="cloudflare:workers";return!(e!==void 0&&e.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import(t)).env??{})}catch{return!1}})():!rs())}var ns=e=>{let[t,r]=[",","."];return e.map(o=>o.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+t)).join(r)},os=e=>{let t=Date.now()-e;return ns([t<1e3?t+"ms":Math.round(t/1e3)+"s"])},ss=async e=>{if(await Br())switch(e/100|0){case 5:return`\x1B[31m${e}\x1B[0m`;case 4:return`\x1B[33m${e}\x1B[0m`;case 3:return`\x1B[36m${e}\x1B[0m`;case 2:return`\x1B[32m${e}\x1B[0m`}return`${e}`};async function Fr(e,t,r,n,o=0,s){let i=t==="<--"?`${t} ${r} ${n}`:`${t} ${r} ${n} ${await ss(o)} ${s}`;e(i)}var qr=(e=console.log)=>async function(r,n){let{method:o,url:s}=r.req,i=s.slice(s.indexOf("/",8));await Fr(e,"<--",o,i);let a=Date.now();await n(),await Fr(e,"-->",o,i,r.res.status,os(a))};import{lookup as is}from"dns/promises";import{Buffer as as}from"buffer";import{isIP as cs}from"net";var ls=new Set(["accept","authorization","content-type","dpop"]),us=new Set(["cache-control","content-type","dpop-nonce","expires","pragma","retry-after","www-authenticate"]),ds=[["registration_endpoint","registration"],["token_endpoint","token"],["revocation_endpoint","revocation"],["introspection_endpoint","introspection"]],Yr=600*1e3,fs=100,ps=1440*60*1e3,hs=500;function vt(e,t={}){let{basePath:r="/oauth",allowedOrigins:n=[],allowLoopback:o=!1,timeoutMs:s=1e4,maxRequestBodyBytes:i=64*1024,maxResponseBodyBytes:a=1024*1024,callbackPath:c="/oauth/callback",enableLogging:l=!0,authenticate:u,validateServerUrl:d,rateLimiter:p=new U.default({points:120,duration:60})}=t,h=new Set(n.map(bt)),w=new Map,y=new Map,g=async(f,m)=>{try{await p.consume(f.req)}catch(b){return te(f,b)}return m()};e.use(`${r}/*`,async(f,m)=>{let b=f.req.header("Origin");if(b&&!Es(b,f,h))return f.json({error:"Origin not allowed"},403);if(f.req.method==="OPTIONS")return Ss(b);await m(),b&&nn(f.res.headers,b)}),e.use(`${r}/*`,g),e.get(`${r}/metadata`,async f=>{if(!await Xr(f,u))return f.json({error:"Unauthorized"},401);let m=await V(f.req.query("serverUrl"),o);if("error"in m)return f.json({error:m.error},400);let b=m.url;if(d&&!await d(b.toString(),f))return f.json({error:"MCP server URL not allowed"},403);let T=await V(f.req.query("url"),o);if("error"in T)return f.json({error:T.error},400);let L=T.url,E=M(b),S=Vr(w,E),A=zr(b,L,S);if(!A&&S.authorizationServers.size===0)try{await Wr(b,S,o,s,a),w.set(E,S),A=zr(b,L,S)}catch{}if(!A)return f.json({error:"Metadata target is not bound to this MCP server"},403);try{wt(l,`GET ${L}`);let R=await Le(L,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(s)});if(Me(R.status))return f.json({error:"OAuth metadata redirects are not allowed"},502);let x=await Ie(R,a);if(!R.ok)return f.body(x,R.status,{"Content-Type":R.headers.get("content-type")??"application/json"});let P=xt(x);return A.type==="protected-resource"?await Zr(P,b,S,o):await en(P,A.issuer,S,o),S.updatedAt=Date.now(),w.set(E,S),Gr(w),f.body(x,200,{"Content-Type":R.headers.get("content-type")??"application/json"})}catch(R){return yt(f,R,l)}}),e.post(`${r}/proxy`,async f=>{if(!await Xr(f,u))return f.json({error:"Unauthorized"},401);let m;try{m=JSON.parse(await vs(f.req.raw,i))}catch(x){return f.json({error:x instanceof H?"Request body too large":"Invalid JSON request body"},x instanceof H?413:400)}let b=await V(m.serverUrl,o);if("error"in b)return f.json({error:b.error},400);let T=b.url;if(d&&!await d(T.toString(),f))return f.json({error:"MCP server URL not allowed"},403);let L=await V(m.url,o);if("error"in L)return f.json({error:L.error},400);let E=L.url;if(m.method!==void 0&&m.method!=="POST")return f.json({error:"Only OAuth endpoint POST is allowed"},405);let S=M(T),A=Vr(w,S);if(A.endpoints.size===0)try{await Wr(T,A,o,s,a),w.set(S,A),Gr(w)}catch(x){return yt(f,x,l)}let R=A.endpoints.get(M(E));if(!R)return f.json({error:"OAuth endpoint is not bound to this MCP server"},403);try{let x=ms(m.headers),P=ws(m.body,x);if(R==="registration"){let fn=bt(f.req.header("Origin")??new URL(f.req.url).origin);P=Rs(P,x,new URL(c,fn).toString())}else P=xs({body:P,headers:x,bindingKey:S,clients:y});if(new TextEncoder().encode(P??"").byteLength>i)return f.json({error:"OAuth request body too large"},413);wt(l,`POST ${R} ${E}`);let I=await Le(E,{method:"POST",headers:x,body:P,redirect:"manual",signal:AbortSignal.timeout(s)});if(Me(I.status))return f.json({error:"OAuth endpoint redirects are not allowed"},502);let j=await Ie(I,a),$=gs(I.headers),dn=I.headers.get("content-type")??"",B=j;if(dn.includes("json"))try{B=JSON.parse(j)}catch{}return R==="registration"&&I.ok&&B&&typeof B=="object"&&!Array.isArray(B)&&(B=ys({responseBody:B,binding:A,bindingKey:S,clients:y})),f.json({status:I.status,statusText:I.statusText,headers:$,body:B})}catch(x){return yt(f,x,l)}}),wt(l,`Mounted at ${r}/metadata and ${r}/proxy`)}async function V(e,t){if(typeof e!="string"||!e)return{error:"Missing or invalid URL"};let r;try{r=new URL(e)}catch{return{error:"Invalid URL"}}if(r.username||r.password||r.hash)return{error:"URL credentials and fragments are not allowed"};let n=Ps(r.hostname);if(r.protocol!=="https:"&&!(t&&n&&r.protocol==="http:"))return{error:"HTTPS is required"};if(n)return t?{url:r}:{error:"Loopback URL not allowed"};if(As(r.hostname))return{error:"Local network URL not allowed"};try{let o=cs(r.hostname)?[r.hostname]:(await is(r.hostname,{all:!0,verbatim:!0})).map(({address:s})=>s);if(o.length===0||o.some(s=>!on(s)))return{error:"Private or non-routable URL not allowed"}}catch{return{error:"URL hostname could not be resolved"}}return{url:r}}async function Rt(e,t=!1){return!("error"in await V(e,t))}function zr(e,t,r){let n=M(t);if(Jr(e).some(o=>M(o)===n))return{type:"protected-resource"};for(let o of r.authorizationServers)if(Qr(new URL(o)).some(s=>M(s)===n))return{type:"authorization-server",issuer:o}}function Jr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-protected-resource${t}`,e.origin),new URL("/.well-known/oauth-protected-resource",e.origin)]}function Qr(e){let t=e.pathname==="/"?"":e.pathname;return[new URL(`/.well-known/oauth-authorization-server${t}`,e.origin),new URL(`/.well-known/openid-configuration${t}`,e.origin),new URL(`${t||""}/.well-known/openid-configuration`,e.origin)]}async function Zr(e,t,r,n){if(typeof e.resource!="string"||M(new URL(e.resource))!==M(t))throw new _("Protected-resource metadata does not match serverUrl");if(!Array.isArray(e.authorization_servers)||e.authorization_servers.length===0)throw new _("Protected-resource metadata has no authorization servers");let o=new Set;for(let s of e.authorization_servers){let i=await V(s,n);if("error"in i)throw new _(`Unsafe authorization server: ${i.error}`);o.add(M(i.url))}r.authorizationServers=o,r.endpoints.clear(),r.tokenEndpointAuthMethods.clear()}async function en(e,t,r,n){if(typeof e.issuer!="string"||M(new URL(e.issuer))!==t)throw new _("Authorization-server metadata issuer mismatch");r.endpoints.clear(),r.tokenEndpointAuthMethods=new Set(Array.isArray(e.token_endpoint_auth_methods_supported)?e.token_endpoint_auth_methods_supported.filter(o=>typeof o=="string"):[]);for(let[o,s]of ds){let i=e[o];if(i===void 0)continue;let a=await V(i,n);if("error"in a)throw new _(`Unsafe ${o}: ${a.error}`);r.endpoints.set(M(a.url),s)}}async function Wr(e,t,r,n,o){for(let s of Jr(e)){let i=await Le(s,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Me(i.status))throw new _("OAuth metadata redirects are not allowed");if(i.ok){await Zr(xt(await Ie(i,o)),e,t,r);break}}if(t.authorizationServers.size===0)throw new _("Protected-resource metadata could not be discovered");for(let s of t.authorizationServers){let i=!1;for(let a of Qr(new URL(s))){let c=await Le(a,{method:"GET",headers:{Accept:"application/json"},redirect:"manual",signal:AbortSignal.timeout(n)});if(Me(c.status))throw new _("OAuth metadata redirects are not allowed");if(c.ok){await en(xt(await Ie(c,o)),s,t,r),i=!0;break}}if(i)break}if(t.endpoints.size===0)throw new _("Authorization-server metadata could not be discovered");t.updatedAt=Date.now()}async function Le(e,t){return fetch(e,t)}function ms(e){let t=new Headers;if(!e||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();ls.has(o)&&typeof n=="string"&&t.set(o,n)}return t}function gs(e){let t={};return e.forEach((r,n)=>{us.has(n.toLowerCase())&&(t[n]=r)}),t}function ws(e,t){if(e==null)return;if(typeof e=="string"){if(!t.has("content-type"))try{JSON.parse(e),t.set("content-type","application/json")}catch{t.set("content-type","application/x-www-form-urlencoded")}return e}if((t.get("content-type")??"").includes("application/x-www-form-urlencoded")&&typeof e=="object"&&!Array.isArray(e)){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.append(o,String(s));return n.toString()}return t.has("content-type")||t.set("content-type","application/json"),JSON.stringify(e)}function tn(e,t){return`${e}\0${t}`}function ys(e){let{responseBody:t,binding:r,bindingKey:n,clients:o}=e,s=t.client_id,i=t.client_secret;if(typeof s!="string"||typeof i!="string")return t;let a=t.token_endpoint_auth_method,c=a==="client_secret_post"||a==="client_secret_basic"?a:r.tokenEndpointAuthMethods.has("client_secret_basic")?"client_secret_basic":"client_secret_post",l=t.client_secret_expires_at,u=l===0?Number.POSITIVE_INFINITY:typeof l=="number"&&l>0?l*1e3:Date.now()+ps;for(bs(o),o.set(tn(n,s),{clientSecret:i,authMethod:c,expiresAt:u});o.size>hs;){let p=o.keys().next().value;if(!p)break;o.delete(p)}let d={...t};return delete d.client_secret,delete d.client_secret_expires_at,d.token_endpoint_auth_method="none",d}function xs(e){let{body:t,headers:r,bindingKey:n,clients:o}=e;if(!t||!(r.get("content-type")??"").includes("application/x-www-form-urlencoded"))return t;let s=new URLSearchParams(t),i=s.get("client_id");if(!i)return t;let a=tn(n,i),c=o.get(a);if(!c)return t;if(c.expiresAt<=Date.now())return o.delete(a),t;if(s.delete("client_secret"),c.authMethod==="client_secret_basic"){let l=as.from(`${Kr(i)}:${Kr(c.clientSecret)}`,"utf8").toString("base64");r.set("authorization",`Basic ${l}`)}else r.delete("authorization"),s.set("client_id",i),s.set("client_secret",c.clientSecret);return s.toString()}function Kr(e){return new URLSearchParams({value:e}).toString().slice(6)}function bs(e){let t=Date.now();for(let[r,n]of e)n.expiresAt<=t&&e.delete(r)}async function vs(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new H;return rn(e.body,t)}async function Ie(e,t){let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw await e.body?.cancel(),new H;return rn(e.body,t)}async function rn(e,t){if(!e)return"";let r=e.getReader(),n=[],o=0;for(;;){let{done:a,value:c}=await r.read();if(a)break;if(o+=c.byteLength,o>t)throw await r.cancel(),new H;n.push(c)}let s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.byteLength;return new TextDecoder().decode(s)}function xt(e){let t;try{t=JSON.parse(e)}catch{throw new _("OAuth metadata is not valid JSON")}if(!t||typeof t!="object"||Array.isArray(t))throw new _("OAuth metadata is not an object");return t}function Vr(e,t){let r=e.get(t);return r&&Date.now()-r.updatedAt<=Yr?r:(e.delete(t),{authorizationServers:new Set,endpoints:new Map,tokenEndpointAuthMethods:new Set,updatedAt:Date.now()})}function Gr(e){let t=Date.now();for(let[r,n]of e)t-n.updatedAt>Yr&&e.delete(r);for(;e.size>fs;){let r=e.keys().next().value;if(!r)break;e.delete(r)}}function M(e){let t=new URL(e);return t.hash="",(t.protocol==="https:"&&t.port==="443"||t.protocol==="http:"&&t.port==="80")&&(t.port=""),t.toString().replace(/\/$/,"")}function Rs(e,t,r){if(!e||!(t.get("content-type")??"").includes("json"))return e;try{let o=JSON.parse(e);return!o||typeof o!="object"||Array.isArray(o)?e:JSON.stringify({...o,redirect_uris:[r]})}catch{return e}}function bt(e){let t=new URL(e);if(t.pathname!=="/"||t.search||t.hash)throw new Error(`OAuth proxy allowed origin must be an origin: ${e}`);return t.origin}function Es(e,t,r){try{let n=bt(e);if(n===new URL(t.req.url).origin||r.has(n))return!0;let o=new URL(n),i=t.req.header("x-forwarded-host")?.split(",")[0]?.trim()||t.req.header("host");if(!i||o.host!==i)return!1;let a=t.req.header("x-forwarded-proto")?.split(",")[0]?.trim();return!a||`${a}:`===o.protocol}catch{return!1}}function Ss(e){let t=new Headers;return e&&nn(t,e),t.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.set("Access-Control-Allow-Headers","Accept, Authorization, Content-Type"),t.set("Access-Control-Max-Age","600"),new Response(null,{status:204,headers:t})}function nn(e,t){e.set("Access-Control-Allow-Origin",t),e.append("Vary","Origin")}async function Xr(e,t){return t?t(e):!0}function Me(e){return e>=300&&e<400}function Ps(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}function As(e){let t=e.toLowerCase();return t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa")}function on(e){if(e.includes(":")){let s=e.toLowerCase();return s.startsWith("::ffff:")?on(s.slice(7)):!(s==="::"||s==="::1"||s.startsWith("fc")||s.startsWith("fd")||/^fe[89ab]/.test(s)||s.startsWith("ff")||s.startsWith("2001:db8:"))}let t=e.split(".").map(Number);if(t.length!==4||t.some(s=>!Number.isInteger(s)))return!1;let[r,n,o]=t;return!(r===0||r===10||r===127||r===100&&n>=64&&n<=127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&o===0||r===192&&n===0&&o===2||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&o===100||r===203&&n===0&&o===113||r>=224)}function wt(e,t){e&&console.log(`[OAuth BFF] ${t}`)}function yt(e,t,r){let n=t instanceof Error?t.message:"Unknown error";return r&&console.error("[OAuth BFF]",n),t instanceof H?e.json({error:"Upstream response too large"},502):t instanceof _?e.json({error:t.message},502):t instanceof DOMException&&t.name==="TimeoutError"?e.json({error:"OAuth upstream timed out"},504):e.json({error:"OAuth upstream request failed"},502)}var H=class extends Error{},_=class extends Error{};var _s=3;function Cs(e,t){return e.includes("text/event-stream")&&!t}function Et(e,t={}){let r=t.path||"/mcp/proxy",n=t.enableLogging!==!1,o=t.rateLimiter??new U.default({points:120,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return te(i,c)}return a()};e.use(`${r}/*`,Pe({origin:"*",allowHeaders:["Authorization","Content-Type","Accept","X-Target-URL","X-MCP-Target","Mcp-Session-Id","mcp-session-id","mcp-protocol-version","X-Server-Id","X-Requested-With"],exposeHeaders:["*"]})),n&&e.use(`${r}/*`,qr()),e.use(`${r}/*`,s),e.all(`${r}/*`,async i=>{try{if(t.authenticate&&!await t.authenticate(i))return i.json({error:"Unauthorized"},401);let a=i.req.header("X-Target-URL");if(!a)return i.json({error:"X-Target-URL header is required",usage:"Set X-Target-URL header to the MCP server URL you want to proxy to"},400);if(!await Rt(a,t.allowLoopback??!1))return i.json({error:"Invalid target URL",details:"Target is not allowed by the proxy network policy"},403);if(t.validateRequest&&!await t.validateRequest(a,i))return i.json({error:"Invalid target URL",details:"The requested target URL is not allowed"},403);try{new URL(a)}catch{return i.json({error:"Invalid target URL format",details:"The X-Target-URL must be a valid HTTP/HTTPS URL"},400)}let c=i.req.method,l={},u=i.req.header();for(let[y,g]of Object.entries(u)){let f=y.toLowerCase();!f.startsWith("x-proxy-")&&!f.startsWith("x-target-")&&!f.startsWith("x-mcp-")&&!f.startsWith("x-forwarded-")&&!f.startsWith("cf-")&&f!=="x-original-host"&&f!=="host"&&f!=="origin"&&f!=="referer"&&f!=="cookie"&&f!=="proxy-authorization"&&f!=="accept-encoding"&&f!=="cdn-loop"&&!f.startsWith("sec-fetch-")&&(l[y]=g)}l["Accept-Encoding"]="identity";let d=c!=="GET"&&c!=="HEAD"?new Uint8Array(await i.req.arrayBuffer()).slice():void 0,p=a,h=c,w=d;for(let y=0;;y+=1){let g=await fetch(p,{method:h,headers:l,body:w,redirect:"manual"}),f=g.headers.get("location");if(!(g.status>=300&&g.status<400&&f))return Os(g);if(y>=_s)return i.json({error:"Too many upstream redirects"},502);let m=new URL(f,p);if(!await Rt(m.toString(),t.allowLoopback??!1)||t.validateRequest&&!await t.validateRequest(m.toString(),i))return i.json({error:"Redirect target is not allowed"},403);m.origin!==new URL(p).origin&&(ke(l,"authorization"),ke(l,"proxy-authorization")),(g.status===303||(g.status===301||g.status===302)&&h==="POST")&&(h="GET",w=void 0,ke(l,"content-type"),ke(l,"content-length")),p=m.toString()}}catch(a){let c=a instanceof Error?a.message:"Unknown error",l=i.req.header("X-Target-URL");return a instanceof Error&&(a.message.includes("ECONNREFUSED")||a.message.includes("fetch failed"))?console.warn(`[MCP Proxy] Connection refused to ${l||"unknown target"} - server may not be running`):console.error("[MCP Proxy] Request failed:",c,`
101
101
  Target URL:`,l||"unknown",`
102
- Error:`,a),i.json({error:"Proxy request failed",details:c,targetUrl:l||"unknown"},500)}})}function ke(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function _s(e){let t={};if(e.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(t[s]=o)}),As(e.headers.get("content-type")||"",e.headers.get("content-length")))return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t});if([204,205,304].includes(e.status))return new Response(null,{status:e.status,statusText:e.statusText,headers:t});let n=await e.arrayBuffer();return t["Content-Length"]=String(n.byteLength),new Response(n,{status:e.status,statusText:e.statusText,headers:t})}function sn(e,t,r=""){let n=a=>`${r}${a}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1,i=new N.default({points:120,duration:60});if(e.get(n("/inspector/health"),a=>a.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Et(e,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i}),s&&vt(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:t?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:i}),t?.autoConnectUrl!==void 0){let a=t.autoConnectUrl;e.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:a??null}))}}function an(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function cn(e=8080,t=100){let r=await import("net");for(let n=e;n<e+t;n++)try{return await new Promise((o,s)=>{let i=r.createServer();i.listen(n,()=>{i.close(()=>o())}),i.on("error",a=>s(a))}),n}catch{continue}throw new Error(`No available port found after trying ${t} ports starting from ${e}`)}function St(e){if(!(e instanceof Error))return`UnknownError (${typeof e})`;let t=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(e.name)?e.name:"Error",r=e.code,n=typeof r=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(r)?r:void 0;return n?`${t} (${n})`:t}var C=process.argv.slice(2),de,ln=8080,un=!1;for(let e=0;e<C.length;e++)if(C[e]==="--url"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=C[e+1];an(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),de=t,e++}else if(C[e]==="--port"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(C[e+1],10);(Number.isNaN(t)||t<1||t>65535)&&(console.error("Error: Port must be a number between 1 and 65535."),process.exit(1)),ln=t,e++}else C[e]==="--no-open"?un=!0:C[e]==="--version"||C[e]==="-v"?(console.log(Te()),process.exit(0)):C[e]==="--help"||C[e]==="-h"?(console.log(`
102
+ Error:`,a),i.json({error:"Proxy request failed",details:c,targetUrl:l||"unknown"},500)}})}function ke(e,t){for(let r of Object.keys(e))r.toLowerCase()===t&&delete e[r]}async function Os(e){let t={};if(e.headers.forEach((o,s)=>{let i=s.toLowerCase();i!=="content-encoding"&&i!=="transfer-encoding"&&i!=="content-length"&&i!=="set-cookie"&&(t[s]=o)}),Cs(e.headers.get("content-type")||"",e.headers.get("content-length")))return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t});if([204,205,304].includes(e.status))return new Response(null,{status:e.status,statusText:e.statusText,headers:t});let n=await e.arrayBuffer();return t["Content-Length"]=String(n.byteLength),new Response(n,{status:e.status,statusText:e.statusText,headers:t})}function sn(e,t,r=""){let n=a=>`${r}${a}`,o=t?.oauthProxyAllowLoopback??!1,s=t?.oauth!==!1,i=new U.default({points:120,duration:60});if(e.get(n("/inspector/health"),a=>a.json({status:"ok",protocol:"mcp-use-inspector-preview",version:1,capabilities:["view-preview"]})),Et(e,{path:n("/inspector/api/proxy"),allowLoopback:o,rateLimiter:i}),s&&vt(e,{basePath:n("/inspector/api/oauth"),callbackPath:n("/inspector/oauth/callback"),enableLogging:!0,allowedOrigins:t?.oauthProxyAllowedOrigins??[],allowLoopback:o,rateLimiter:i}),t?.autoConnectUrl!==void 0){let a=t.autoConnectUrl;e.get(n("/inspector/config.json"),c=>c.json({autoConnectUrl:a??null}))}}function an(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}async function cn(e=8080,t=100){let r=await import("net");for(let n=e;n<e+t;n++)try{return await new Promise((o,s)=>{let i=r.createServer();i.listen(n,()=>{i.close(()=>o())}),i.on("error",a=>s(a))}),n}catch{continue}throw new Error(`No available port found after trying ${t} ports starting from ${e}`)}function St(e){if(!(e instanceof Error))return`UnknownError (${typeof e})`;let t=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(e.name)?e.name:"Error",r=e.code,n=typeof r=="string"&&/^[A-Z][A-Z0-9_]{0,31}$/.test(r)?r:void 0;return n?`${t} (${n})`:t}var C=process.argv.slice(2),de,ln=8080,un=!1;for(let e=0;e<C.length;e++)if(C[e]==="--url"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --url requires a value"),process.exit(1));let t=C[e+1];an(t)||(console.error("Error: Invalid URL format."),console.error("URL must start with http://, https://, ws://, or wss://"),process.exit(1)),de=t,e++}else if(C[e]==="--port"){(e+1>=C.length||C[e+1].startsWith("-"))&&(console.error("Error: --port requires a value"),process.exit(1));let t=Number.parseInt(C[e+1],10);(Number.isNaN(t)||t<1||t>65535)&&(console.error("Error: Port must be a number between 1 and 65535."),process.exit(1)),ln=t,e++}else C[e]==="--no-open"?un=!0:C[e]==="--version"||C[e]==="-v"?(console.log(Te()),process.exit(0)):C[e]==="--help"||C[e]==="-h"?(console.log(`
103
103
  MCP Inspector - Inspect and debug MCP servers
104
104
 
105
105
  Usage:
@@ -116,4 +116,4 @@ Examples:
116
116
  npx @mcp-use/inspector --url http://localhost:3000/mcp
117
117
  npx @mcp-use/inspector --url http://localhost:3000/mcp --port 9000
118
118
  npx @mcp-use/inspector
119
- `),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var fe=new Ze;fe.use("*",Pe({origin:"*",exposeHeaders:["*"]}));sn(fe,{autoConnectUrl:de,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:!0});$r(fe,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Cs(){try{let e=await cn(ln);if(Ut({fetch:fe.fetch,port:e}),console.log(`MCP Inspector started at http://localhost:${e}/inspector`),de&&console.log("Auto-connect configured."),!un){let t=new URL(`http://localhost:${e}/inspector`);de&&t.searchParams.set("autoConnect",de);try{await Er(t.toString()),console.log("Browser opened.")}catch(r){console.log(`Browser could not be opened automatically. Open ${t.toString()} manually.`),console.error(`Browser open error: ${St(r)}`)}}return{port:e,fetch:fe.fetch}}catch(e){console.error(`Failed to start server (StartupError): ${St(e)}`),process.exit(1)}}Cs();
119
+ `),process.exit(0)):(console.error("Error: Unknown option."),console.error("Run with --help to see available options."),process.exit(1));var fe=new Ze;fe.use("*",Pe({origin:"*",exposeHeaders:["*"]}));sn(fe,{autoConnectUrl:de,oauthProxyAllowedOrigins:[],oauthProxyAllowLoopback:!0});$r(fe,{inspectorMode:"standalone",manufactChatUrl:process.env.MANUFACT_CHAT_URL});async function Ts(){try{let e=await cn(ln);if(Nt({fetch:fe.fetch,port:e}),console.log(`MCP Inspector started at http://localhost:${e}/inspector`),de&&console.log("Auto-connect configured."),!un){let t=new URL(`http://localhost:${e}/inspector`);de&&t.searchParams.set("autoConnect",de);try{await Er(t.toString()),console.log("Browser opened.")}catch(r){console.log(`Browser could not be opened automatically. Open ${t.toString()} manually.`),console.error(`Browser open error: ${St(r)}`)}}return{port:e,fetch:fe.fetch}}catch(e){console.error(`Failed to start server (StartupError): ${St(e)}`),process.exit(1)}}Ts();
@@ -1,9 +1,9 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { Tool, Resource, Prompt, McpServer, ElicitRequestFormParams, ElicitRequestURLParams, GetPromptResult, ElicitResult } from '@mcp-use/client/react';
3
3
  export { ViewRenderer, getViewResourceUri, isViewTool } from '@mcp-use/client/react';
4
+ import { ProviderName, McpConnectionLike } from '@mcp-use/agent';
4
5
  import * as react from 'react';
5
6
  import react__default, { ReactNode, RefObject } from 'react';
6
- import { ProviderName } from '@mcp-use/agent';
7
7
 
8
8
  interface AddToClientDropdownProps {
9
9
  serverConfig: {
@@ -242,46 +242,6 @@ type MessageContentBlock = {
242
242
  [key: string]: unknown;
243
243
  };
244
244
 
245
- interface ToolResultRendererProps {
246
- toolName: string;
247
- toolArgs: Record<string, unknown>;
248
- result: any;
249
- serverId?: string;
250
- readResource?: (uri: string) => Promise<any>;
251
- toolMeta?: Record<string, any>;
252
- onSendFollowUp?: (content: MessageContentBlock[]) => Promise<void>;
253
- modelContextScope?: string;
254
- partialToolArgs?: Record<string, unknown>;
255
- cancelled?: boolean;
256
- }
257
- declare function ToolResultRenderer({ toolName, toolArgs, result, serverId, readResource, toolMeta, onSendFollowUp, modelContextScope, partialToolArgs, cancelled, }: ToolResultRendererProps): react_jsx_runtime.JSX.Element | null;
258
-
259
- type Theme = "light" | "dark" | "system";
260
- interface ThemeProviderProps {
261
- children: ReactNode;
262
- defaultTheme?: Theme;
263
- storageKey?: string;
264
- forcedTheme?: Theme;
265
- }
266
- declare function ThemeProvider({ children, defaultTheme, storageKey, forcedTheme, }: ThemeProviderProps): react_jsx_runtime.JSX.Element;
267
-
268
- interface WidgetModelContext {
269
- content?: Array<{
270
- type: "text";
271
- text: string;
272
- }>;
273
- structuredContent?: Record<string, unknown>;
274
- }
275
-
276
- /**
277
- * Provider for widget debugging context
278
- *
279
- * Manages widget debug state following the same pattern as InspectorProvider
280
- */
281
- declare function WidgetDebugProvider({ children }: {
282
- children: ReactNode;
283
- }): react_jsx_runtime.JSX.Element;
284
-
285
245
  interface MessageAttachment {
286
246
  type: "image" | "file";
287
247
  data: string;
@@ -367,6 +327,47 @@ interface MCPConfig {
367
327
  }
368
328
  type StreamProtocol = "sse" | "data-stream";
369
329
 
330
+ interface ToolResultRendererProps {
331
+ toolName: string;
332
+ toolArgs: Record<string, unknown>;
333
+ result: any;
334
+ serverId?: string;
335
+ readResource?: (uri: string) => Promise<any>;
336
+ toolMeta?: Record<string, any>;
337
+ onSendFollowUp?: (content: MessageContentBlock[]) => Promise<void>;
338
+ modelContextScope?: string;
339
+ llmConfig?: LLMConfig | null;
340
+ partialToolArgs?: Record<string, unknown>;
341
+ cancelled?: boolean;
342
+ }
343
+ declare function ToolResultRenderer({ toolName, toolArgs, result, serverId, readResource, toolMeta, onSendFollowUp, modelContextScope, llmConfig, partialToolArgs, cancelled, }: ToolResultRendererProps): react_jsx_runtime.JSX.Element | null;
344
+
345
+ type Theme = "light" | "dark" | "system";
346
+ interface ThemeProviderProps {
347
+ children: ReactNode;
348
+ defaultTheme?: Theme;
349
+ storageKey?: string;
350
+ forcedTheme?: Theme;
351
+ }
352
+ declare function ThemeProvider({ children, defaultTheme, storageKey, forcedTheme, }: ThemeProviderProps): react_jsx_runtime.JSX.Element;
353
+
354
+ interface WidgetModelContext {
355
+ content?: Array<{
356
+ type: "text";
357
+ text: string;
358
+ }>;
359
+ structuredContent?: Record<string, unknown>;
360
+ }
361
+
362
+ /**
363
+ * Provider for widget debugging context
364
+ *
365
+ * Manages widget debug state following the same pattern as InspectorProvider
366
+ */
367
+ declare function WidgetDebugProvider({ children }: {
368
+ children: ReactNode;
369
+ }): react_jsx_runtime.JSX.Element;
370
+
370
371
  type TabType = "tools" | "prompts" | "resources" | "chat" | "sampling" | "elicitation" | "notifications" | "server-metadata" | "connection-settings";
371
372
  /**
372
373
  * Configuration injected by a host application when the inspector runs in
@@ -845,8 +846,9 @@ interface MessageListProps {
845
846
  /** Trace events used to derive per-message token counts on hover. */
846
847
  traceEvents?: InspectorTraceEvent[];
847
848
  modelContextScope?: string;
849
+ llmConfig?: LLMConfig | null;
848
850
  }
849
- declare const MessageList: react.MemoExoticComponent<({ messages, isLoading, serverId, readResource, tools, sendMessage, messagesEndRef, traceEvents, modelContextScope, }: MessageListProps) => react_jsx_runtime.JSX.Element>;
851
+ declare const MessageList: react.MemoExoticComponent<({ messages, isLoading, serverId, readResource, tools, sendMessage, messagesEndRef, traceEvents, modelContextScope, llmConfig, }: MessageListProps) => react_jsx_runtime.JSX.Element>;
850
852
 
851
853
  interface ChatHeaderProps {
852
854
  llmConfig: LLMConfig | null;
@@ -1164,10 +1166,11 @@ interface UseChatMessagesClientSideProps {
1164
1166
  readResource?: (uri: string) => Promise<any>;
1165
1167
  widgetModelContexts?: Map<string, WidgetModelContext | undefined>;
1166
1168
  disabledTools?: Set<string>;
1169
+ appToolConnections?: McpConnectionLike[];
1167
1170
  initialMessages?: Message$1[];
1168
1171
  systemPrompt?: string;
1169
1172
  }
1170
- declare function useChatMessagesClientSide({ connection, llmConfig, isConnected, readResource, widgetModelContexts, disabledTools, initialMessages, systemPrompt, }: UseChatMessagesClientSideProps): {
1173
+ declare function useChatMessagesClientSide({ connection, llmConfig, isConnected, readResource, widgetModelContexts, disabledTools, appToolConnections, initialMessages, systemPrompt, }: UseChatMessagesClientSideProps): {
1171
1174
  messages: Message$1[];
1172
1175
  isLoading: boolean;
1173
1176
  attachments: MessageAttachment[];
@@ -1263,7 +1266,7 @@ declare function useConfig({ mcpServerUrl }: UseConfigProps): {
1263
1266
  setTempModel: react.Dispatch<react.SetStateAction<string>>;
1264
1267
  tempBaseUrl: string;
1265
1268
  setTempBaseUrl: react.Dispatch<react.SetStateAction<string>>;
1266
- tempAuthType: "none" | "oauth" | "basic" | "bearer";
1269
+ tempAuthType: "none" | "basic" | "bearer" | "oauth";
1267
1270
  saveLLMConfig: () => boolean;
1268
1271
  clearConfig: () => void;
1269
1272
  };