@easbot/mcp 0.2.23 → 0.2.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var chunk4DCCWUIJ_cjs=require('./chunks/chunk-4DCCWUIJ.cjs'),mcp_js=require('@modelcontextprotocol/sdk/server/mcp.js'),stdio_js=require('@modelcontextprotocol/sdk/server/stdio.js'),events=require('events'),d=require('zod/v4'),z=require('http'),streamableHttp_js=require('@modelcontextprotocol/sdk/server/streamableHttp.js'),index_js=require('@modelcontextprotocol/sdk/client/index.js'),stdio_js$1=require('@modelcontextprotocol/sdk/client/stdio.js'),streamableHttp_js$1=require('@modelcontextprotocol/sdk/client/streamableHttp.js'),sse_js=require('@modelcontextprotocol/sdk/client/sse.js'),types_js=require('@modelcontextprotocol/sdk/types.js'),auth_js=require('@modelcontextprotocol/sdk/client/auth.js'),utils=require('@easbot/utils'),v=require('zod');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var d__default=/*#__PURE__*/_interopDefault(d);var z__default=/*#__PURE__*/_interopDefault(z);var v__default=/*#__PURE__*/_interopDefault(v);var I={STDIO:"stdio",HTTP:"http"},l={STOPPED:"stopped",STARTING:"starting",RUNNING:"running",STOPPING:"stopping",ERROR:"error"};var N=chunk4DCCWUIJ_cjs.b.create({service:"tool-registry"}),b={REGISTERED:"mcp.tool.registered",UNREGISTERED:"mcp.tool.unregistered",CLEARED:"mcp.tool.cleared"},A=class extends events.EventEmitter{constructor(){super();chunk4DCCWUIJ_cjs.a(this,"tools",new Map);}register(e){if(!e.name||typeof e.name!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u65E0\u6548\uFF1A\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(this.tools.has(e.name)){N?.debug("tool already registered, skipping",{tool:e.name});return}this.tools.set(e.name,e),this.emit(b.REGISTERED,e);}unregister(e){return this.tools.has(e)?(this.tools.delete(e),this.emit(b.UNREGISTERED,e),true):false}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getTools(){return Array.from(this.tools.values()).map(({handler:e,...r})=>r)}has(e){return this.tools.has(e)}getSize(){return this.tools.size}clear(){this.tools.clear(),this.emit(b.CLEARED);}},C=new A;var S=chunk4DCCWUIJ_cjs.b.create({service:"mcp.server.stdio"}),R=class{constructor(t){chunk4DCCWUIJ_cjs.a(this,"config");chunk4DCCWUIJ_cjs.a(this,"server",null);chunk4DCCWUIJ_cjs.a(this,"info");chunk4DCCWUIJ_cjs.a(this,"isStarting",false);chunk4DCCWUIJ_cjs.a(this,"isStopping",false);chunk4DCCWUIJ_cjs.a(this,"toolEventCleanup",null);chunk4DCCWUIJ_cjs.a(this,"handleToolRegistered",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),S.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now(),enabled:t.enabled};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of C.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),S.info("tool loaded",{tool:t.name});}}subscribeToolEvents(){this.toolEventCleanup=()=>{C.off(b.REGISTERED,this.handleToolRegistered);},C.on(b.REGISTERED,this.handleToolRegistered);}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeToolEvents(){this.toolEventCleanup&&(this.toolEventCleanup(),this.toolEventCleanup=null);}convertToZodSchema(t){if(t instanceof d__default.default.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}if(e.type==="string")return d__default.default.string();if(e.type==="number")return d__default.default.number();if(e.type==="boolean")return d__default.default.boolean();if(e.type==="array"){let r=e.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}}return d__default.default.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d__default.default.string();case "number":return d__default.default.number();case "integer":return d__default.default.number().int();case "boolean":return d__default.default.boolean();case "null":return d__default.default.null();case "array":{let r=t.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}default:return d__default.default.unknown()}}async start(){if(this.isStarting){S.warn("server is already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){S.debug("server is already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{S.info("starting stdio mcp server",{id:this.info.id,name:this.info.name,command:this.config.command,args:this.config.args});let t=new stdio_js.StdioServerTransport;this.server=new mcp_js.McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeToolEvents(),await this.server.connect(t),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),S.info("stdio mcp server started successfully",{id:this.info.id,name:this.info.name,toolCount:C.getSize()});}catch(t){throw this.info.status=l.ERROR,S.error("failed to start stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){S.warn("server is already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){S.debug("server is not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{S.info("stopping stdio mcp server",{id:this.info.id,name:this.info.name}),this.unsubscribeToolEvents(),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,S.info("stdio mcp server stopped",{id:this.info.id,name:this.info.name});}catch(t){this.info.status=l.ERROR,S.error("error stopping stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){S.info("restarting stdio mcp server",{id:this.info.id}),await this.stop(),await this.start();}};function U(s){return new R(s)}async function Z(s){let t=new R(s);return await t.start(),t.createInstance()}var g=chunk4DCCWUIJ_cjs.b.create({service:"mcp.server.http"}),w=class{constructor(t){chunk4DCCWUIJ_cjs.a(this,"config");chunk4DCCWUIJ_cjs.a(this,"server",null);chunk4DCCWUIJ_cjs.a(this,"transport",null);chunk4DCCWUIJ_cjs.a(this,"httpServer",null);chunk4DCCWUIJ_cjs.a(this,"info");chunk4DCCWUIJ_cjs.a(this,"isStarting",false);chunk4DCCWUIJ_cjs.a(this,"isStopping",false);chunk4DCCWUIJ_cjs.a(this,"toolCleanup",null);chunk4DCCWUIJ_cjs.a(this,"handleTool",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now()};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of C.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool loaded",{tool:t.name});}}subscribeTools(){this.toolCleanup=()=>{C.off(b.REGISTERED,this.handleTool);},C.on(b.REGISTERED,this.handleTool);}convertToZodSchema(t){if(t instanceof d__default.default.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}if(e.type==="string")return d__default.default.string();if(e.type==="number")return d__default.default.number();if(e.type==="boolean")return d__default.default.boolean();if(e.type==="array"){let r=e.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}}return d__default.default.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d__default.default.string();case "number":return d__default.default.number();case "integer":return d__default.default.number().int();case "boolean":return d__default.default.boolean();case "null":return d__default.default.null();case "array":{let r=t.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}default:return d__default.default.unknown()}}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeTools(){this.toolCleanup&&(this.toolCleanup(),this.toolCleanup=null);}async start(){if(this.isStarting){g.warn("already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){g.debug("already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{g.info("starting",{id:this.info.id,name:this.info.name,url:this.config.url});let t;try{t=new URL(this.config.url);}catch{throw new Error(`\u65E0\u6548\u7684 URL: ${this.config.url}`)}let e=parseInt(t.port||"3000",10),r=t.hostname||"0.0.0.0";if(Number.isNaN(e)||e<1||e>65535)throw new Error(`\u65E0\u6548\u7684\u7AEF\u53E3\u53F7: ${t.port}`);this.transport=new streamableHttp_js.StreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID()}),this.server=new mcp_js.McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeTools(),await this.server.connect(this.transport),this.httpServer=z__default.default.createServer((n,o)=>{let m=n.headers.origin,f=(h,c,k)=>{o.writeHead(h,c),k?o.end(k):o.end();},i={"Access-Control-Allow-Origin":m||"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, mcpsessionid, mcp-protocol-version","Access-Control-Max-Age":"86400"};if(n.method==="OPTIONS"){f(204,i);return}if(n.method==="POST"){let h="";n.setEncoding("utf8"),n.on("data",c=>{h+=c;}),n.on("end",()=>{let c;if(h)try{c=JSON.parse(h);}catch{c=void 0;}this.transport&&this.transport.handleRequest(n,o,c);}),n.on("error",c=>{g.error("HTTP request error",{error:c.message}),f(500,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}}));});}else n.method==="GET"?this.transport&&this.transport.handleRequest(n,o,void 0):f(405,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32601,message:"Method not found"}}));}),this.httpServer.on("error",n=>{g.error("HTTP server error",{error:n.message}),this.info.status=l.ERROR;}),this.httpServer.on("clientError",(n,o)=>{g.warn("HTTP client error",{error:n.message}),o.writable&&o.end(`HTTP/1.1 400 Bad Request\r
1
+ 'use strict';var chunkDQPEZFOV_cjs=require('./chunks/chunk-DQPEZFOV.cjs'),mcp_js=require('@modelcontextprotocol/sdk/server/mcp.js'),stdio_js=require('@modelcontextprotocol/sdk/server/stdio.js'),events=require('events'),d=require('zod/v4'),z=require('http'),streamableHttp_js=require('@modelcontextprotocol/sdk/server/streamableHttp.js'),index_js=require('@modelcontextprotocol/sdk/client/index.js'),stdio_js$1=require('@modelcontextprotocol/sdk/client/stdio.js'),streamableHttp_js$1=require('@modelcontextprotocol/sdk/client/streamableHttp.js'),sse_js=require('@modelcontextprotocol/sdk/client/sse.js'),types_js=require('@modelcontextprotocol/sdk/types.js'),auth_js=require('@modelcontextprotocol/sdk/client/auth.js'),utils=require('@easbot/utils'),v=require('zod');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var d__default=/*#__PURE__*/_interopDefault(d);var z__default=/*#__PURE__*/_interopDefault(z);var v__default=/*#__PURE__*/_interopDefault(v);var I={STDIO:"stdio",HTTP:"http"},l={STOPPED:"stopped",STARTING:"starting",RUNNING:"running",STOPPING:"stopping",ERROR:"error"};var N=chunkDQPEZFOV_cjs.b.create({service:"tool-registry"}),b={REGISTERED:"mcp.tool.registered",UNREGISTERED:"mcp.tool.unregistered",CLEARED:"mcp.tool.cleared"},A=class extends events.EventEmitter{constructor(){super();chunkDQPEZFOV_cjs.a(this,"tools",new Map);}register(e){if(!e.name||typeof e.name!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u65E0\u6548\uFF1A\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(this.tools.has(e.name)){N?.debug("tool already registered, skipping",{tool:e.name});return}this.tools.set(e.name,e),this.emit(b.REGISTERED,e);}unregister(e){return this.tools.has(e)?(this.tools.delete(e),this.emit(b.UNREGISTERED,e),true):false}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getTools(){return Array.from(this.tools.values()).map(({handler:e,...r})=>r)}has(e){return this.tools.has(e)}getSize(){return this.tools.size}clear(){this.tools.clear(),this.emit(b.CLEARED);}},C=new A;var y=chunkDQPEZFOV_cjs.b.create({service:"mcp.server.stdio"}),R=class{constructor(t){chunkDQPEZFOV_cjs.a(this,"config");chunkDQPEZFOV_cjs.a(this,"server",null);chunkDQPEZFOV_cjs.a(this,"info");chunkDQPEZFOV_cjs.a(this,"isStarting",false);chunkDQPEZFOV_cjs.a(this,"isStopping",false);chunkDQPEZFOV_cjs.a(this,"toolEventCleanup",null);chunkDQPEZFOV_cjs.a(this,"handleToolRegistered",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),y.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now(),enabled:t.enabled};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of C.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),y.info("tool loaded",{tool:t.name});}}subscribeToolEvents(){this.toolEventCleanup=()=>{C.off(b.REGISTERED,this.handleToolRegistered);},C.on(b.REGISTERED,this.handleToolRegistered);}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeToolEvents(){this.toolEventCleanup&&(this.toolEventCleanup(),this.toolEventCleanup=null);}convertToZodSchema(t){if(t instanceof d__default.default.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}if(e.type==="string")return d__default.default.string();if(e.type==="number")return d__default.default.number();if(e.type==="boolean")return d__default.default.boolean();if(e.type==="array"){let r=e.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}}return d__default.default.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d__default.default.string();case "number":return d__default.default.number();case "integer":return d__default.default.number().int();case "boolean":return d__default.default.boolean();case "null":return d__default.default.null();case "array":{let r=t.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}default:return d__default.default.unknown()}}async start(){if(this.isStarting){y.warn("server is already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){y.debug("server is already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{y.info("starting stdio mcp server",{id:this.info.id,name:this.info.name,command:this.config.command,args:this.config.args});let t=new stdio_js.StdioServerTransport;this.server=new mcp_js.McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeToolEvents(),await this.server.connect(t),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),y.info("stdio mcp server started successfully",{id:this.info.id,name:this.info.name,toolCount:C.getSize()});}catch(t){throw this.info.status=l.ERROR,y.error("failed to start stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){y.warn("server is already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){y.debug("server is not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{y.info("stopping stdio mcp server",{id:this.info.id,name:this.info.name}),this.unsubscribeToolEvents(),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,y.info("stdio mcp server stopped",{id:this.info.id,name:this.info.name});}catch(t){this.info.status=l.ERROR,y.error("error stopping stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){y.info("restarting stdio mcp server",{id:this.info.id}),await this.stop(),await this.start();}};function U(s){return new R(s)}async function Z(s){let t=new R(s);return await t.start(),t.createInstance()}var g=chunkDQPEZFOV_cjs.b.create({service:"mcp.server.http"}),w=class{constructor(t){chunkDQPEZFOV_cjs.a(this,"config");chunkDQPEZFOV_cjs.a(this,"server",null);chunkDQPEZFOV_cjs.a(this,"transport",null);chunkDQPEZFOV_cjs.a(this,"httpServer",null);chunkDQPEZFOV_cjs.a(this,"info");chunkDQPEZFOV_cjs.a(this,"isStarting",false);chunkDQPEZFOV_cjs.a(this,"isStopping",false);chunkDQPEZFOV_cjs.a(this,"toolCleanup",null);chunkDQPEZFOV_cjs.a(this,"handleTool",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now()};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of C.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool loaded",{tool:t.name});}}subscribeTools(){this.toolCleanup=()=>{C.off(b.REGISTERED,this.handleTool);},C.on(b.REGISTERED,this.handleTool);}convertToZodSchema(t){if(t instanceof d__default.default.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}if(e.type==="string")return d__default.default.string();if(e.type==="number")return d__default.default.number();if(e.type==="boolean")return d__default.default.boolean();if(e.type==="array"){let r=e.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}}return d__default.default.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d__default.default.string();case "number":return d__default.default.number();case "integer":return d__default.default.number().int();case "boolean":return d__default.default.boolean();case "null":return d__default.default.null();case "array":{let r=t.items;return r?d__default.default.array(this.jsonSchemaToZod(r)):d__default.default.array(d__default.default.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d__default.default.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d__default.default.object(f)}default:return d__default.default.unknown()}}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeTools(){this.toolCleanup&&(this.toolCleanup(),this.toolCleanup=null);}async start(){if(this.isStarting){g.warn("already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){g.debug("already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{g.info("starting",{id:this.info.id,name:this.info.name,url:this.config.url});let t;try{t=new URL(this.config.url);}catch{throw new Error(`\u65E0\u6548\u7684 URL: ${this.config.url}`)}let e=parseInt(t.port||"3000",10),r=t.hostname||"0.0.0.0";if(Number.isNaN(e)||e<1||e>65535)throw new Error(`\u65E0\u6548\u7684\u7AEF\u53E3\u53F7: ${t.port}`);this.transport=new streamableHttp_js.StreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID()}),this.server=new mcp_js.McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeTools(),await this.server.connect(this.transport),this.httpServer=z__default.default.createServer((n,o)=>{let m=n.headers.origin,f=(h,c,k)=>{o.writeHead(h,c),k?o.end(k):o.end();},i={"Access-Control-Allow-Origin":m||"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, mcpsessionid, mcp-protocol-version","Access-Control-Max-Age":"86400"};if(n.method==="OPTIONS"){f(204,i);return}if(n.method==="POST"){let h="";n.setEncoding("utf8"),n.on("data",c=>{h+=c;}),n.on("end",()=>{let c;if(h)try{c=JSON.parse(h);}catch{c=void 0;}this.transport&&this.transport.handleRequest(n,o,c);}),n.on("error",c=>{g.error("HTTP request error",{error:c.message}),f(500,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}}));});}else n.method==="GET"?this.transport&&this.transport.handleRequest(n,o,void 0):f(405,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32601,message:"Method not found"}}));}),this.httpServer.on("error",n=>{g.error("HTTP server error",{error:n.message}),this.info.status=l.ERROR;}),this.httpServer.on("clientError",(n,o)=>{g.warn("HTTP client error",{error:n.message}),o.writable&&o.end(`HTTP/1.1 400 Bad Request\r
2
2
  \r
3
- `);}),this.httpServer.listen(e,r),g.info("HTTP server listening",{hostname:r,port:e}),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),g.info("started",{id:this.info.id,name:this.info.name,toolCount:C.getSize()});}catch(t){throw this.info.status=l.ERROR,g.error("failed to start",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){g.warn("already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){g.debug("not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{g.info("stopping",{id:this.info.id,name:this.info.name}),this.unsubscribeTools(),this.httpServer&&(await new Promise(t=>{this.httpServer.close(()=>t());}),this.httpServer=null),this.transport&&(await this.transport.close(),this.transport=null),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,g.info("stopped",{id:this.info.id});}catch(t){this.info.status=l.ERROR,g.error("failed to stop",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){g.info("restarting",{id:this.info.id}),await this.stop(),await this.start();}};function V(s){return new w(s)}async function F(s){let t=new w(s);return await t.start(),t.createInstance()}var H={version:"0.2.23"};function E(){return H.version}var O=chunk4DCCWUIJ_cjs.b.create({service:"mcp.server.factory"});function K(s){return s.type==="local"}function $(s){return s.type==="remote"}function J(s,t){if(!t.command)throw new Error(`MCP server ${s} has no command specified`);return {id:s,name:s,version:"1.0.0",transportType:I.STDIO,enabled:t.enabled,timeout:t.timeout,command:t.command,args:t.args?.length?t.args:void 0,env:t.env}}function W(s,t){return {id:s,name:s,version:"1.0.0",transportType:I.HTTP,enabled:t.enabled,timeout:t.timeout,url:t.url,headers:t.headers}}async function Q(s,t){if(O.debug("creating server from config",{name:s,type:t.type}),K(t)){let e=J(s,t),r=new R(e);return await r.start(),r.createInstance()}if($(t)){let e=W(s,t),r=new w(e);return await r.start(),r.createInstance()}throw new Error(`Unsupported MCP config type: ${t.type}`)}async function Zt(s){let t={};for(let[e,r]of Object.entries(s))try{let n=await Q(e,r);t[e]=n;}catch(n){O.error("failed to create server from config",{name:e,error:n instanceof Error?n.message:String(n)});}return t}var p=chunk4DCCWUIJ_cjs.b.create({service:"mcp.client"}),x=3e4,M=class{constructor(){chunk4DCCWUIJ_cjs.a(this,"id","");chunk4DCCWUIJ_cjs.a(this,"client",null);chunk4DCCWUIJ_cjs.a(this,"_info");chunk4DCCWUIJ_cjs.a(this,"notificationCleanup",null);chunk4DCCWUIJ_cjs.a(this,"pendingTransport",null);chunk4DCCWUIJ_cjs.a(this,"oauthState","");chunk4DCCWUIJ_cjs.a(this,"capturedRedirectUrl",null);chunk4DCCWUIJ_cjs.a(this,"oauthConfig");chunk4DCCWUIJ_cjs.a(this,"toolListChangedHandler",null);chunk4DCCWUIJ_cjs.a(this,"oauthProvider",null);this._info=this.createInitialInfo();}get info(){return {...this._info}}get status(){return this._info.status}get tools(){return [...this._info.tools]}get resources(){return [...this._info.resources]}get prompts(){return [...this._info.prompts]}get clientId(){return this.id}setToolListChangedHandler(t){this.toolListChangedHandler=t;}setOAuthProvider(t){this.oauthProvider=t;}async connect(t,e){p.info("connecting to MCP server",{id:t,type:e.type}),await this.disconnect(),this.id=t,this._info=this.createInitialInfo(),this._info.id=t,this._info.name=t;try{if(e.type==="remote"&&(this.oauthConfig=e.oauth===!1?void 0:e.oauth??{}),this.client=await this.createClient(e),!this.client)return;this._info.status={status:"connected"},this._info.connectedAt=Date.now(),await this.fetchCapabilities(),p.info("connected to MCP server",{id:t,toolCount:this._info.tools.length});}catch(r){let n=r instanceof Error?r.message:String(r);this._info.status={status:"failed",error:n},this._info.error=n,p.error("failed to connect to MCP server",{id:t,error:n});}}async startAuth(){if(!this.pendingTransport)throw new Error("No pending OAuth flow. Please connect to a server that requires authentication first.");return this.oauthState=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(t=>t.toString(16).padStart(2,"0")).join(""),this.oauthProvider&&await this.oauthProvider.saveState(this.oauthState),{authorizationUrl:this.capturedRedirectUrl?.toString()??"",state:this.oauthState}}async finishAuth(t){if(!this.pendingTransport)throw new Error("No pending OAuth flow.");try{await this.pendingTransport.finishAuth?.(t);}catch(e){throw p.error("failed to finish OAuth",{id:this.id,error:e}),e}this.pendingTransport=null,this.capturedRedirectUrl=null,p.info("OAuth completed, ready to reconnect",{id:this.id});}isAuthRequired(){return this._info.status.status==="needs_auth"}isClientRegistrationRequired(){return this._info.status.status==="needs_client_registration"}getPendingTransport(){return this.pendingTransport}getAuthorizationUrl(){return this.capturedRedirectUrl?.toString()??""}async disconnect(){this.notificationCleanup&&(this.notificationCleanup(),this.notificationCleanup=null),this.client&&(await this.client.close().catch(t=>{p.error("Failed to close MCP client",{id:this.id,error:t});}),this.client=null),this.pendingTransport=null,this.capturedRedirectUrl=null,this.toolListChangedHandler=null,this._info.status.status==="connected"&&(this._info.status={status:"disconnected"}),p.info("disconnected from MCP server",{id:this.id});}async listTools(){if(!this.client||this._info.status.status!=="connected")return {};let t={};for(let e of this._info.tools)t[e.name]={name:e.name,description:e.description,inputSchema:e.inputSchema};return t}async callTool(t,e,r){let n=Date.now();if(!this.client||this._info.status.status!=="connected")return {toolName:t,args:e,content:[],success:false,error:"Client not connected",duration:Date.now()-n};try{let o=await utils.withTimeout(this.client.callTool({name:t,arguments:e},types_js.CallToolResultSchema,{resetTimeoutOnProgress:!0,timeout:r}),r??x);return {toolName:t,args:e,content:o.content.map(m=>m.type==="text"?{type:"text",text:m.text}:m.type==="image"?{type:"image",data:m.data,mimeType:m.mimeType}:m.type==="resource"?{type:"resource",resource:m.resource}:{type:"text",text:String(m)}),success:!0,duration:Date.now()-n,metadata:o.metadata}}catch(o){return {toolName:t,args:e,content:[],success:false,error:o instanceof Error?o.message:String(o),duration:Date.now()-n}}}async listResources(){return [...this._info.resources]}async readResource(t){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for readResource",{id:this.id});return}return this.client.readResource({uri:t}).catch(e=>{p.error("failed to read resource",{id:this.id,uri:t,error:e.message});})}async listPrompts(){return [...this._info.prompts]}async getPrompt(t,e){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for getPrompt",{id:this.id});return}return this.client.getPrompt({name:t,arguments:e}).catch(r=>{p.error("failed to get prompt",{id:this.id,name:t,error:r.message});})}async refreshTools(){if(!(!this.client||this._info.status.status!=="connected"))try{let t=await utils.withTimeout(this.client.listTools(),x);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),p.info("tools refreshed",{id:this.id,count:this._info.tools.length});}catch(t){p.error("failed to refresh tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}}async createClient(t){return t.type==="local"?await this.createLocalClient(t):t.type==="remote"?await this.createRemoteClient(t):null}async fetchCapabilities(){if(this.client){try{let t=await utils.withTimeout(this.client.listTools(),x);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));}catch(t){p.debug("failed to get tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}try{let t=await utils.withTimeout(this.client.listResources(),5e3);this._info.resources=t.resources.map(e=>({name:e.name,uri:e.uri,description:e.description,mimeType:e.mimeType}));}catch{p.debug("failed to get resources",{id:this.id});}try{let t=await utils.withTimeout(this.client.listPrompts(),5e3);this._info.prompts=t.prompts.map(e=>({name:e.name,description:e.description,arguments:e.arguments?.map(r=>({name:r.name,description:r.description,required:r.required}))}));}catch{p.debug("failed to get prompts",{id:this.id});}}}async createLocalClient(t){let[e,...r]=t.command;if(!e)return this._info.status={status:"failed",error:"Command is empty"},null;let n=new stdio_js$1.StdioClientTransport({stderr:"pipe",command:e,args:r.length>0?r:void 0,cwd:t.cwd??process.cwd(),env:Object.fromEntries(Object.entries({...process.env,...t.environment}).filter(([,o])=>o!==void 0))});n.stderr?.on("data",o=>{p.info(`mcp stderr: ${o.toString()}`,{id:this.id});});try{let o=new index_js.Client({name:"easbot-mcp",version:E()});return await utils.withTimeout(o.connect(n),t.timeout??x),this.registerNotificationHandler(o),o}catch(o){let m=o instanceof Error?o.message:String(o);return this._info.status={status:"failed",error:m},p.error("local mcp startup failed",{id:this.id,command:[e,...r],error:m}),null}}async createRemoteClient(t){let e={headers:t.headers};if((t.transport||"streamable-http")==="sse"){p.info("using SSE transport",{id:this.id,url:t.url});let n=new sse_js.SSEClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}else {p.info("using StreamableHTTP transport",{id:this.id,url:t.url});let n=new streamableHttp_js$1.StreamableHTTPClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}}async connectWithTransport(t,e){try{let r=new index_js.Client({name:"easbot-mcp",version:E()});return await r.connect(t),this.registerNotificationHandler(r),r}catch(r){return this.handleConnectionError(r,t,e),null}}handleConnectionError(t,e,r){if(t instanceof auth_js.UnauthorizedError){let n=t instanceof Error?t.message:String(t);n.includes("registration")||n.includes("client_id")?this._info.status={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."}:(this._info.status={status:"needs_auth"},this.pendingTransport=e,this.capturedRedirectUrl=this.extractRedirectUrl(t));}else {let n=t instanceof Error?t.message:String(t);this._info.status={status:"failed",error:n};}p.error("remote mcp connection failed",{id:this.id,url:r.url,status:this._info.status});}extractRedirectUrl(t){let r=t.message.match(/https?:\/\/[^\s]+/);if(r)try{return new URL(r[0])}catch{return null}return null}registerNotificationHandler(t){let e=async()=>{p.info("tools list changed notification received",{id:this.id}),await this.refreshTools(),this.toolListChangedHandler&&await this.toolListChangedHandler();};t.setNotificationHandler(types_js.ToolListChangedNotificationSchema,e),this.notificationCleanup=()=>{t.removeNotificationHandler("notifications/tools/list_changed");};}createInitialInfo(){return {id:"",name:"",status:{status:"disconnected"},tools:[],resources:[],prompts:[]}}};function ot(){return new M}var ce=v__default.default.discriminatedUnion("status",[v__default.default.object({status:v__default.default.literal("connected")}).meta({ref:"MCPStatusConnected"}),v__default.default.object({status:v__default.default.literal("disconnected")}).meta({ref:"MCPStatusDisconnected"}),v__default.default.object({status:v__default.default.literal("failed"),error:v__default.default.string()}).meta({ref:"MCPStatusFailed"}),v__default.default.object({status:v__default.default.literal("needs_auth")}).meta({ref:"MCPStatusNeedsAuth"}),v__default.default.object({status:v__default.default.literal("needs_client_registration"),error:v__default.default.string()}).meta({ref:"MCPStatusNeedsClientRegistration"}),v__default.default.object({status:v__default.default.literal("disabled")}).meta({ref:"MCPStatusDisabled"})]);var he="@easbot/mcp";async function ge(s){let{Log:t}=await import('./chunks/log-WXSBDTHF.cjs'),e=false;await t.init({logDir:s.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:s.print??false,dev:s.dev??e,level:s.level??("INFO")});}exports.HttpServerAdapter=w;exports.MCPClient=M;exports.NAME=he;exports.ServerStatus=l;exports.ServerTransportType=I;exports.Status=ce;exports.StdioServerAdapter=R;exports.ToolRegistry=A;exports.ToolRegistryEvent=b;exports.createAndStartHttpServer=F;exports.createAndStartStdioServer=Z;exports.createHttpServer=V;exports.createMCPClient=ot;exports.createServerFromConfig=Q;exports.createServersFromConfigMap=Zt;exports.createStdioServer=U;exports.getVersion=E;exports.initLog=ge;exports.tools=C;
3
+ `);}),this.httpServer.listen(e,r),g.info("HTTP server listening",{hostname:r,port:e}),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),g.info("started",{id:this.info.id,name:this.info.name,toolCount:C.getSize()});}catch(t){throw this.info.status=l.ERROR,g.error("failed to start",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){g.warn("already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){g.debug("not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{g.info("stopping",{id:this.info.id,name:this.info.name}),this.unsubscribeTools(),this.httpServer&&(await new Promise(t=>{this.httpServer.close(()=>t());}),this.httpServer=null),this.transport&&(await this.transport.close(),this.transport=null),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,g.info("stopped",{id:this.info.id});}catch(t){this.info.status=l.ERROR,g.error("failed to stop",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){g.info("restarting",{id:this.info.id}),await this.stop(),await this.start();}};function V(s){return new w(s)}async function F(s){let t=new w(s);return await t.start(),t.createInstance()}var H={version:"0.2.25"};function E(){return H.version}var O=chunkDQPEZFOV_cjs.b.create({service:"mcp.server.factory"});function K(s){return s.type==="local"}function $(s){return s.type==="remote"}function J(s,t){if(!t.command)throw new Error(`MCP server ${s} has no command specified`);return {id:s,name:s,version:"1.0.0",transportType:I.STDIO,enabled:t.enabled,timeout:t.timeout,command:t.command,args:t.args?.length?t.args:void 0,env:t.env}}function W(s,t){return {id:s,name:s,version:"1.0.0",transportType:I.HTTP,enabled:t.enabled,timeout:t.timeout,url:t.url,headers:t.headers}}async function Q(s,t){if(O.debug("creating server from config",{name:s,type:t.type}),K(t)){let e=J(s,t),r=new R(e);return await r.start(),r.createInstance()}if($(t)){let e=W(s,t),r=new w(e);return await r.start(),r.createInstance()}throw new Error(`Unsupported MCP config type: ${t.type}`)}async function Zt(s){let t={};for(let[e,r]of Object.entries(s))try{let n=await Q(e,r);t[e]=n;}catch(n){O.error("failed to create server from config",{name:e,error:n instanceof Error?n.message:String(n)});}return t}var p=chunkDQPEZFOV_cjs.b.create({service:"mcp.client"}),x=3e4,M=class{constructor(){chunkDQPEZFOV_cjs.a(this,"id","");chunkDQPEZFOV_cjs.a(this,"client",null);chunkDQPEZFOV_cjs.a(this,"_info");chunkDQPEZFOV_cjs.a(this,"notificationCleanup",null);chunkDQPEZFOV_cjs.a(this,"pendingTransport",null);chunkDQPEZFOV_cjs.a(this,"oauthState","");chunkDQPEZFOV_cjs.a(this,"capturedRedirectUrl",null);chunkDQPEZFOV_cjs.a(this,"oauthConfig");chunkDQPEZFOV_cjs.a(this,"toolListChangedHandler",null);chunkDQPEZFOV_cjs.a(this,"oauthProvider",null);this._info=this.createInitialInfo();}get info(){return {...this._info}}get status(){return this._info.status}get tools(){return [...this._info.tools]}get resources(){return [...this._info.resources]}get prompts(){return [...this._info.prompts]}get clientId(){return this.id}setToolListChangedHandler(t){this.toolListChangedHandler=t;}setOAuthProvider(t){this.oauthProvider=t;}async connect(t,e){p.info("connecting to MCP server",{id:t,type:e.type}),await this.disconnect(),this.id=t,this._info=this.createInitialInfo(),this._info.id=t,this._info.name=t;try{if(e.type==="remote"&&(this.oauthConfig=e.oauth===!1?void 0:e.oauth??{}),this.client=await this.createClient(e),!this.client)return;this._info.status={status:"connected"},this._info.connectedAt=Date.now(),await this.fetchCapabilities(),p.info("connected to MCP server",{id:t,toolCount:this._info.tools.length});}catch(r){let n=r instanceof Error?r.message:String(r);this._info.status={status:"failed",error:n},this._info.error=n,p.error("failed to connect to MCP server",{id:t,error:n});}}async startAuth(){if(!this.pendingTransport)throw new Error("No pending OAuth flow. Please connect to a server that requires authentication first.");return this.oauthState=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(t=>t.toString(16).padStart(2,"0")).join(""),this.oauthProvider&&await this.oauthProvider.saveState(this.oauthState),{authorizationUrl:this.capturedRedirectUrl?.toString()??"",state:this.oauthState}}async finishAuth(t){if(!this.pendingTransport)throw new Error("No pending OAuth flow.");try{await this.pendingTransport.finishAuth?.(t);}catch(e){throw p.error("failed to finish OAuth",{id:this.id,error:e}),e}this.pendingTransport=null,this.capturedRedirectUrl=null,p.info("OAuth completed, ready to reconnect",{id:this.id});}isAuthRequired(){return this._info.status.status==="needs_auth"}isClientRegistrationRequired(){return this._info.status.status==="needs_client_registration"}getPendingTransport(){return this.pendingTransport}getAuthorizationUrl(){return this.capturedRedirectUrl?.toString()??""}async disconnect(){this.notificationCleanup&&(this.notificationCleanup(),this.notificationCleanup=null),this.client&&(await this.client.close().catch(t=>{p.error("Failed to close MCP client",{id:this.id,error:t});}),this.client=null),this.pendingTransport=null,this.capturedRedirectUrl=null,this.toolListChangedHandler=null,this._info.status.status==="connected"&&(this._info.status={status:"disconnected"}),p.info("disconnected from MCP server",{id:this.id});}async listTools(){if(!this.client||this._info.status.status!=="connected")return {};let t={};for(let e of this._info.tools)t[e.name]={name:e.name,description:e.description,inputSchema:e.inputSchema};return t}async callTool(t,e,r){let n=Date.now();if(!this.client||this._info.status.status!=="connected")return {toolName:t,args:e,content:[],success:false,error:"Client not connected",duration:Date.now()-n};try{let o=await utils.withTimeout(this.client.callTool({name:t,arguments:e},types_js.CallToolResultSchema,{resetTimeoutOnProgress:!0,timeout:r}),r??x);return {toolName:t,args:e,content:o.content.map(m=>m.type==="text"?{type:"text",text:m.text}:m.type==="image"?{type:"image",data:m.data,mimeType:m.mimeType}:m.type==="resource"?{type:"resource",resource:m.resource}:{type:"text",text:String(m)}),success:!0,duration:Date.now()-n,metadata:o.metadata}}catch(o){return {toolName:t,args:e,content:[],success:false,error:o instanceof Error?o.message:String(o),duration:Date.now()-n}}}async listResources(){return [...this._info.resources]}async readResource(t){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for readResource",{id:this.id});return}return this.client.readResource({uri:t}).catch(e=>{p.error("failed to read resource",{id:this.id,uri:t,error:e.message});})}async listPrompts(){return [...this._info.prompts]}async getPrompt(t,e){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for getPrompt",{id:this.id});return}return this.client.getPrompt({name:t,arguments:e}).catch(r=>{p.error("failed to get prompt",{id:this.id,name:t,error:r.message});})}async refreshTools(){if(!(!this.client||this._info.status.status!=="connected"))try{let t=await utils.withTimeout(this.client.listTools(),x);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),p.info("tools refreshed",{id:this.id,count:this._info.tools.length});}catch(t){p.error("failed to refresh tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}}async createClient(t){return t.type==="local"?await this.createLocalClient(t):t.type==="remote"?await this.createRemoteClient(t):null}async fetchCapabilities(){if(this.client){try{let t=await utils.withTimeout(this.client.listTools(),x);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));}catch(t){p.debug("failed to get tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}try{let t=await utils.withTimeout(this.client.listResources(),5e3);this._info.resources=t.resources.map(e=>({name:e.name,uri:e.uri,description:e.description,mimeType:e.mimeType}));}catch{p.debug("failed to get resources",{id:this.id});}try{let t=await utils.withTimeout(this.client.listPrompts(),5e3);this._info.prompts=t.prompts.map(e=>({name:e.name,description:e.description,arguments:e.arguments?.map(r=>({name:r.name,description:r.description,required:r.required}))}));}catch{p.debug("failed to get prompts",{id:this.id});}}}async createLocalClient(t){let[e,...r]=t.command;if(!e)return this._info.status={status:"failed",error:"Command is empty"},null;let n=new stdio_js$1.StdioClientTransport({stderr:"pipe",command:e,args:r.length>0?r:void 0,cwd:t.cwd??process.cwd(),env:Object.fromEntries(Object.entries({...process.env,...t.environment}).filter(([,o])=>o!==void 0))});n.stderr?.on("data",o=>{p.info(`mcp stderr: ${o.toString()}`,{id:this.id});});try{let o=new index_js.Client({name:"easbot-mcp",version:E()});return await utils.withTimeout(o.connect(n),t.timeout??x),this.registerNotificationHandler(o),o}catch(o){let m=o instanceof Error?o.message:String(o);return this._info.status={status:"failed",error:m},p.error("local mcp startup failed",{id:this.id,command:[e,...r],error:m}),null}}async createRemoteClient(t){let e={headers:t.headers};if((t.transport||"streamable-http")==="sse"){p.info("using SSE transport",{id:this.id,url:t.url});let n=new sse_js.SSEClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}else {p.info("using StreamableHTTP transport",{id:this.id,url:t.url});let n=new streamableHttp_js$1.StreamableHTTPClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}}async connectWithTransport(t,e){try{let r=new index_js.Client({name:"easbot-mcp",version:E()});return await r.connect(t),this.registerNotificationHandler(r),r}catch(r){return this.handleConnectionError(r,t,e),null}}handleConnectionError(t,e,r){if(t instanceof auth_js.UnauthorizedError){let n=t instanceof Error?t.message:String(t);n.includes("registration")||n.includes("client_id")?this._info.status={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."}:(this._info.status={status:"needs_auth"},this.pendingTransport=e,this.capturedRedirectUrl=this.extractRedirectUrl(t));}else {let n=t instanceof Error?t.message:String(t);this._info.status={status:"failed",error:n};}p.error("remote mcp connection failed",{id:this.id,url:r.url,status:this._info.status});}extractRedirectUrl(t){let r=t.message.match(/https?:\/\/[^\s]+/);if(r)try{return new URL(r[0])}catch{return null}return null}registerNotificationHandler(t){let e=async()=>{p.info("tools list changed notification received",{id:this.id}),await this.refreshTools(),this.toolListChangedHandler&&await this.toolListChangedHandler();};t.setNotificationHandler(types_js.ToolListChangedNotificationSchema,e),this.notificationCleanup=()=>{t.removeNotificationHandler("notifications/tools/list_changed");};}createInitialInfo(){return {id:"",name:"",status:{status:"disconnected"},tools:[],resources:[],prompts:[]}}};function ot(){return new M}var ce=v__default.default.discriminatedUnion("status",[v__default.default.object({status:v__default.default.literal("connected")}).meta({ref:"MCPStatusConnected"}),v__default.default.object({status:v__default.default.literal("disconnected")}).meta({ref:"MCPStatusDisconnected"}),v__default.default.object({status:v__default.default.literal("failed"),error:v__default.default.string()}).meta({ref:"MCPStatusFailed"}),v__default.default.object({status:v__default.default.literal("needs_auth")}).meta({ref:"MCPStatusNeedsAuth"}),v__default.default.object({status:v__default.default.literal("needs_client_registration"),error:v__default.default.string()}).meta({ref:"MCPStatusNeedsClientRegistration"}),v__default.default.object({status:v__default.default.literal("disabled")}).meta({ref:"MCPStatusDisabled"})]);var he="@easbot/mcp";async function ge(s){let{Log:t}=await import('./chunks/log-P5KGMDMW.cjs'),e=false;await t.init({logDir:s.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:s.print??false,dev:s.dev??e,level:s.level??("INFO")});}exports.HttpServerAdapter=w;exports.MCPClient=M;exports.NAME=he;exports.ServerStatus=l;exports.ServerTransportType=I;exports.Status=ce;exports.StdioServerAdapter=R;exports.ToolRegistry=A;exports.ToolRegistryEvent=b;exports.createAndStartHttpServer=F;exports.createAndStartStdioServer=Z;exports.createHttpServer=V;exports.createMCPClient=ot;exports.createServerFromConfig=Q;exports.createServersFromConfigMap=Zt;exports.createStdioServer=U;exports.getVersion=E;exports.initLog=ge;exports.tools=C;
package/dist/index.d.cts CHANGED
@@ -469,6 +469,7 @@ declare const tools: ToolRegistry;
469
469
  declare function getVersion(): string;
470
470
 
471
471
  declare const NAME = "@easbot/mcp";
472
+
472
473
  declare function initLog(options: {
473
474
  print: boolean;
474
475
  logDir: string;
package/dist/index.d.ts CHANGED
@@ -469,6 +469,7 @@ declare const tools: ToolRegistry;
469
469
  declare function getVersion(): string;
470
470
 
471
471
  declare const NAME = "@easbot/mcp";
472
+
472
473
  declare function initLog(options: {
473
474
  print: boolean;
474
475
  logDir: string;
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import {b as b$1,a}from'./chunks/chunk-PJM3ON7Z.mjs';import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {EventEmitter}from'events';import d from'zod/v4';import q from'http';import {StreamableHTTPServerTransport}from'@modelcontextprotocol/sdk/server/streamableHttp.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {SSEClientTransport}from'@modelcontextprotocol/sdk/client/sse.js';import {CallToolResultSchema,ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {UnauthorizedError}from'@modelcontextprotocol/sdk/client/auth.js';import {withTimeout}from'@easbot/utils';import v from'zod';var E={STDIO:"stdio",HTTP:"http"},l={STOPPED:"stopped",STARTING:"starting",RUNNING:"running",STOPPING:"stopping",ERROR:"error"};var D=b$1.create({service:"tool-registry"}),R={REGISTERED:"mcp.tool.registered",UNREGISTERED:"mcp.tool.unregistered",CLEARED:"mcp.tool.cleared"},k=class extends EventEmitter{constructor(){super();a(this,"tools",new Map);}register(e){if(!e.name||typeof e.name!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u65E0\u6548\uFF1A\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(this.tools.has(e.name)){D?.debug("tool already registered, skipping",{tool:e.name});return}this.tools.set(e.name,e),this.emit(R.REGISTERED,e);}unregister(e){return this.tools.has(e)?(this.tools.delete(e),this.emit(R.UNREGISTERED,e),true):false}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getTools(){return Array.from(this.tools.values()).map(({handler:e,...r})=>r)}has(e){return this.tools.has(e)}getSize(){return this.tools.size}clear(){this.tools.clear(),this.emit(R.CLEARED);}},b=new k;var S=b$1.create({service:"mcp.server.stdio"}),w=class{constructor(t){a(this,"config");a(this,"server",null);a(this,"info");a(this,"isStarting",false);a(this,"isStopping",false);a(this,"toolEventCleanup",null);a(this,"handleToolRegistered",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),S.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now(),enabled:t.enabled};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of b.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),S.info("tool loaded",{tool:t.name});}}subscribeToolEvents(){this.toolEventCleanup=()=>{b.off(R.REGISTERED,this.handleToolRegistered);},b.on(R.REGISTERED,this.handleToolRegistered);}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeToolEvents(){this.toolEventCleanup&&(this.toolEventCleanup(),this.toolEventCleanup=null);}convertToZodSchema(t){if(t instanceof d.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}if(e.type==="string")return d.string();if(e.type==="number")return d.number();if(e.type==="boolean")return d.boolean();if(e.type==="array"){let r=e.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}}return d.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d.string();case "number":return d.number();case "integer":return d.number().int();case "boolean":return d.boolean();case "null":return d.null();case "array":{let r=t.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}default:return d.unknown()}}async start(){if(this.isStarting){S.warn("server is already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){S.debug("server is already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{S.info("starting stdio mcp server",{id:this.info.id,name:this.info.name,command:this.config.command,args:this.config.args});let t=new StdioServerTransport;this.server=new McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeToolEvents(),await this.server.connect(t),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),S.info("stdio mcp server started successfully",{id:this.info.id,name:this.info.name,toolCount:b.getSize()});}catch(t){throw this.info.status=l.ERROR,S.error("failed to start stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){S.warn("server is already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){S.debug("server is not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{S.info("stopping stdio mcp server",{id:this.info.id,name:this.info.name}),this.unsubscribeToolEvents(),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,S.info("stdio mcp server stopped",{id:this.info.id,name:this.info.name});}catch(t){this.info.status=l.ERROR,S.error("error stopping stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){S.info("restarting stdio mcp server",{id:this.info.id}),await this.stop(),await this.start();}};function Z(s){return new w(s)}async function z(s){let t=new w(s);return await t.start(),t.createInstance()}var g=b$1.create({service:"mcp.server.http"}),P=class{constructor(t){a(this,"config");a(this,"server",null);a(this,"transport",null);a(this,"httpServer",null);a(this,"info");a(this,"isStarting",false);a(this,"isStopping",false);a(this,"toolCleanup",null);a(this,"handleTool",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now()};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of b.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool loaded",{tool:t.name});}}subscribeTools(){this.toolCleanup=()=>{b.off(R.REGISTERED,this.handleTool);},b.on(R.REGISTERED,this.handleTool);}convertToZodSchema(t){if(t instanceof d.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}if(e.type==="string")return d.string();if(e.type==="number")return d.number();if(e.type==="boolean")return d.boolean();if(e.type==="array"){let r=e.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}}return d.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d.string();case "number":return d.number();case "integer":return d.number().int();case "boolean":return d.boolean();case "null":return d.null();case "array":{let r=t.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}default:return d.unknown()}}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeTools(){this.toolCleanup&&(this.toolCleanup(),this.toolCleanup=null);}async start(){if(this.isStarting){g.warn("already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){g.debug("already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{g.info("starting",{id:this.info.id,name:this.info.name,url:this.config.url});let t;try{t=new URL(this.config.url);}catch{throw new Error(`\u65E0\u6548\u7684 URL: ${this.config.url}`)}let e=parseInt(t.port||"3000",10),r=t.hostname||"0.0.0.0";if(Number.isNaN(e)||e<1||e>65535)throw new Error(`\u65E0\u6548\u7684\u7AEF\u53E3\u53F7: ${t.port}`);this.transport=new StreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID()}),this.server=new McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeTools(),await this.server.connect(this.transport),this.httpServer=q.createServer((n,o)=>{let m=n.headers.origin,f=(h,c,H)=>{o.writeHead(h,c),H?o.end(H):o.end();},i={"Access-Control-Allow-Origin":m||"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, mcpsessionid, mcp-protocol-version","Access-Control-Max-Age":"86400"};if(n.method==="OPTIONS"){f(204,i);return}if(n.method==="POST"){let h="";n.setEncoding("utf8"),n.on("data",c=>{h+=c;}),n.on("end",()=>{let c;if(h)try{c=JSON.parse(h);}catch{c=void 0;}this.transport&&this.transport.handleRequest(n,o,c);}),n.on("error",c=>{g.error("HTTP request error",{error:c.message}),f(500,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}}));});}else n.method==="GET"?this.transport&&this.transport.handleRequest(n,o,void 0):f(405,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32601,message:"Method not found"}}));}),this.httpServer.on("error",n=>{g.error("HTTP server error",{error:n.message}),this.info.status=l.ERROR;}),this.httpServer.on("clientError",(n,o)=>{g.warn("HTTP client error",{error:n.message}),o.writable&&o.end(`HTTP/1.1 400 Bad Request\r
1
+ import {b as b$1,a}from'./chunks/chunk-VHCOYGSJ.mjs';import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {EventEmitter}from'events';import d from'zod/v4';import q from'http';import {StreamableHTTPServerTransport}from'@modelcontextprotocol/sdk/server/streamableHttp.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {SSEClientTransport}from'@modelcontextprotocol/sdk/client/sse.js';import {CallToolResultSchema,ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {UnauthorizedError}from'@modelcontextprotocol/sdk/client/auth.js';import {withTimeout}from'@easbot/utils';import v from'zod';var E={STDIO:"stdio",HTTP:"http"},l={STOPPED:"stopped",STARTING:"starting",RUNNING:"running",STOPPING:"stopping",ERROR:"error"};var D=b$1.create({service:"tool-registry"}),R={REGISTERED:"mcp.tool.registered",UNREGISTERED:"mcp.tool.unregistered",CLEARED:"mcp.tool.cleared"},k=class extends EventEmitter{constructor(){super();a(this,"tools",new Map);}register(e){if(!e.name||typeof e.name!="string")throw new Error("\u5DE5\u5177\u540D\u79F0\u65E0\u6548\uFF1A\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(this.tools.has(e.name)){D?.debug("tool already registered, skipping",{tool:e.name});return}this.tools.set(e.name,e),this.emit(R.REGISTERED,e);}unregister(e){return this.tools.has(e)?(this.tools.delete(e),this.emit(R.UNREGISTERED,e),true):false}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getTools(){return Array.from(this.tools.values()).map(({handler:e,...r})=>r)}has(e){return this.tools.has(e)}getSize(){return this.tools.size}clear(){this.tools.clear(),this.emit(R.CLEARED);}},b=new k;var y=b$1.create({service:"mcp.server.stdio"}),w=class{constructor(t){a(this,"config");a(this,"server",null);a(this,"info");a(this,"isStarting",false);a(this,"isStopping",false);a(this,"toolEventCleanup",null);a(this,"handleToolRegistered",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),y.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now(),enabled:t.enabled};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of b.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),y.info("tool loaded",{tool:t.name});}}subscribeToolEvents(){this.toolEventCleanup=()=>{b.off(R.REGISTERED,this.handleToolRegistered);},b.on(R.REGISTERED,this.handleToolRegistered);}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeToolEvents(){this.toolEventCleanup&&(this.toolEventCleanup(),this.toolEventCleanup=null);}convertToZodSchema(t){if(t instanceof d.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}if(e.type==="string")return d.string();if(e.type==="number")return d.number();if(e.type==="boolean")return d.boolean();if(e.type==="array"){let r=e.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}}return d.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d.string();case "number":return d.number();case "integer":return d.number().int();case "boolean":return d.boolean();case "null":return d.null();case "array":{let r=t.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}default:return d.unknown()}}async start(){if(this.isStarting){y.warn("server is already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){y.debug("server is already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{y.info("starting stdio mcp server",{id:this.info.id,name:this.info.name,command:this.config.command,args:this.config.args});let t=new StdioServerTransport;this.server=new McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeToolEvents(),await this.server.connect(t),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),y.info("stdio mcp server started successfully",{id:this.info.id,name:this.info.name,toolCount:b.getSize()});}catch(t){throw this.info.status=l.ERROR,y.error("failed to start stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){y.warn("server is already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){y.debug("server is not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{y.info("stopping stdio mcp server",{id:this.info.id,name:this.info.name}),this.unsubscribeToolEvents(),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,y.info("stdio mcp server stopped",{id:this.info.id,name:this.info.name});}catch(t){this.info.status=l.ERROR,y.error("error stopping stdio mcp server",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){y.info("restarting stdio mcp server",{id:this.info.id}),await this.stop(),await this.start();}};function Z(s){return new w(s)}async function z(s){let t=new w(s);return await t.start(),t.createInstance()}var g=b$1.create({service:"mcp.server.http"}),P=class{constructor(t){a(this,"config");a(this,"server",null);a(this,"transport",null);a(this,"httpServer",null);a(this,"info");a(this,"isStarting",false);a(this,"isStopping",false);a(this,"toolCleanup",null);a(this,"handleTool",t=>{if(this.server){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool registered",{tool:t.name});}});this.config=t,this.info={id:t.id,name:t.name,version:t.version,transportType:t.transportType,status:l.STOPPED,createdAt:Date.now(),lastActivityAt:Date.now()};}getInfo(){return this.info}getConfig(){return this.config}createInstance(){let t=this;return {info:this.info,get server(){return t.server},start:()=>this.start(),stop:()=>this.stop(),restart:()=>this.restart()}}loadTools(){if(this.server)for(let t of b.getAll()){let e=this.convertToZodSchema(t.inputSchema),r=this.adaptToolHandler(t.handler);this.server.registerTool(t.name,{description:t.description,inputSchema:e},r),g.info("tool loaded",{tool:t.name});}}subscribeTools(){this.toolCleanup=()=>{b.off(R.REGISTERED,this.handleTool);},b.on(R.REGISTERED,this.handleTool);}convertToZodSchema(t){if(t instanceof d.ZodType)return t;if(typeof t=="object"&&t!==null){let e=t;if(e.type==="object"){let r=e.properties||{},n=e.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}if(e.type==="string")return d.string();if(e.type==="number")return d.number();if(e.type==="boolean")return d.boolean();if(e.type==="array"){let r=e.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}}return d.unknown()}jsonSchemaToZod(t){switch(t.type){case "string":return d.string();case "number":return d.number();case "integer":return d.number().int();case "boolean":return d.boolean();case "null":return d.null();case "array":{let r=t.items;return r?d.array(this.jsonSchemaToZod(r)):d.array(d.unknown())}case "object":{let r=t.properties||{},n=t.required||[],o={};for(let[i,h]of Object.entries(r))o[i]=this.jsonSchemaToZod(h);if(Object.keys(r).filter(i=>!n.includes(i)).length===0)return d.object(o);let f={};for(let[i,h]of Object.entries(r)){let c=o[i];c&&(n.includes(i)?f[i]=c:f[i]=c.optional());}return d.object(f)}default:return d.unknown()}}adaptToolHandler(t){return async(e,r)=>{let n={signal:r.signal,sessionId:r.sessionId,requestId:r.requestId,taskId:r.taskId,_meta:r._meta,authInfo:r.authInfo?{type:"bearer",claims:{clientId:r.authInfo.clientId,scopes:r.authInfo.scopes}}:void 0};return t(e,n)}}unsubscribeTools(){this.toolCleanup&&(this.toolCleanup(),this.toolCleanup=null);}async start(){if(this.isStarting){g.warn("already starting",{id:this.info.id});return}if(this.info.status===l.RUNNING){g.debug("already running",{id:this.info.id});return}this.isStarting=true,this.info.status=l.STARTING;try{g.info("starting",{id:this.info.id,name:this.info.name,url:this.config.url});let t;try{t=new URL(this.config.url);}catch{throw new Error(`\u65E0\u6548\u7684 URL: ${this.config.url}`)}let e=parseInt(t.port||"3000",10),r=t.hostname||"0.0.0.0";if(Number.isNaN(e)||e<1||e>65535)throw new Error(`\u65E0\u6548\u7684\u7AEF\u53E3\u53F7: ${t.port}`);this.transport=new StreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID()}),this.server=new McpServer({name:this.config.name,version:this.config.version}),this.loadTools(),this.subscribeTools(),await this.server.connect(this.transport),this.httpServer=q.createServer((n,o)=>{let m=n.headers.origin,f=(h,c,H)=>{o.writeHead(h,c),H?o.end(H):o.end();},i={"Access-Control-Allow-Origin":m||"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, mcpsessionid, mcp-protocol-version","Access-Control-Max-Age":"86400"};if(n.method==="OPTIONS"){f(204,i);return}if(n.method==="POST"){let h="";n.setEncoding("utf8"),n.on("data",c=>{h+=c;}),n.on("end",()=>{let c;if(h)try{c=JSON.parse(h);}catch{c=void 0;}this.transport&&this.transport.handleRequest(n,o,c);}),n.on("error",c=>{g.error("HTTP request error",{error:c.message}),f(500,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}}));});}else n.method==="GET"?this.transport&&this.transport.handleRequest(n,o,void 0):f(405,i,JSON.stringify({jsonrpc:"2.0",error:{code:-32601,message:"Method not found"}}));}),this.httpServer.on("error",n=>{g.error("HTTP server error",{error:n.message}),this.info.status=l.ERROR;}),this.httpServer.on("clientError",(n,o)=>{g.warn("HTTP client error",{error:n.message}),o.writable&&o.end(`HTTP/1.1 400 Bad Request\r
2
2
  \r
3
- `);}),this.httpServer.listen(e,r),g.info("HTTP server listening",{hostname:r,port:e}),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),g.info("started",{id:this.info.id,name:this.info.name,toolCount:b.getSize()});}catch(t){throw this.info.status=l.ERROR,g.error("failed to start",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){g.warn("already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){g.debug("not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{g.info("stopping",{id:this.info.id,name:this.info.name}),this.unsubscribeTools(),this.httpServer&&(await new Promise(t=>{this.httpServer.close(()=>t());}),this.httpServer=null),this.transport&&(await this.transport.close(),this.transport=null),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,g.info("stopped",{id:this.info.id});}catch(t){this.info.status=l.ERROR,g.error("failed to stop",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){g.info("restarting",{id:this.info.id}),await this.stop(),await this.start();}};function F(s){return new P(s)}async function B(s){let t=new P(s);return await t.start(),t.createInstance()}var O={version:"0.2.23"};function x(){return O.version}var j=b$1.create({service:"mcp.server.factory"});function $(s){return s.type==="local"}function J(s){return s.type==="remote"}function W(s,t){if(!t.command)throw new Error(`MCP server ${s} has no command specified`);return {id:s,name:s,version:"1.0.0",transportType:E.STDIO,enabled:t.enabled,timeout:t.timeout,command:t.command,args:t.args?.length?t.args:void 0,env:t.env}}function Q(s,t){return {id:s,name:s,version:"1.0.0",transportType:E.HTTP,enabled:t.enabled,timeout:t.timeout,url:t.url,headers:t.headers}}async function X(s,t){if(j.debug("creating server from config",{name:s,type:t.type}),$(t)){let e=W(s,t),r=new w(e);return await r.start(),r.createInstance()}if(J(t)){let e=Q(s,t),r=new P(e);return await r.start(),r.createInstance()}throw new Error(`Unsupported MCP config type: ${t.type}`)}async function zt(s){let t={};for(let[e,r]of Object.entries(s))try{let n=await X(e,r);t[e]=n;}catch(n){j.error("failed to create server from config",{name:e,error:n instanceof Error?n.message:String(n)});}return t}var p=b$1.create({service:"mcp.client"}),M=3e4,A=class{constructor(){a(this,"id","");a(this,"client",null);a(this,"_info");a(this,"notificationCleanup",null);a(this,"pendingTransport",null);a(this,"oauthState","");a(this,"capturedRedirectUrl",null);a(this,"oauthConfig");a(this,"toolListChangedHandler",null);a(this,"oauthProvider",null);this._info=this.createInitialInfo();}get info(){return {...this._info}}get status(){return this._info.status}get tools(){return [...this._info.tools]}get resources(){return [...this._info.resources]}get prompts(){return [...this._info.prompts]}get clientId(){return this.id}setToolListChangedHandler(t){this.toolListChangedHandler=t;}setOAuthProvider(t){this.oauthProvider=t;}async connect(t,e){p.info("connecting to MCP server",{id:t,type:e.type}),await this.disconnect(),this.id=t,this._info=this.createInitialInfo(),this._info.id=t,this._info.name=t;try{if(e.type==="remote"&&(this.oauthConfig=e.oauth===!1?void 0:e.oauth??{}),this.client=await this.createClient(e),!this.client)return;this._info.status={status:"connected"},this._info.connectedAt=Date.now(),await this.fetchCapabilities(),p.info("connected to MCP server",{id:t,toolCount:this._info.tools.length});}catch(r){let n=r instanceof Error?r.message:String(r);this._info.status={status:"failed",error:n},this._info.error=n,p.error("failed to connect to MCP server",{id:t,error:n});}}async startAuth(){if(!this.pendingTransport)throw new Error("No pending OAuth flow. Please connect to a server that requires authentication first.");return this.oauthState=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(t=>t.toString(16).padStart(2,"0")).join(""),this.oauthProvider&&await this.oauthProvider.saveState(this.oauthState),{authorizationUrl:this.capturedRedirectUrl?.toString()??"",state:this.oauthState}}async finishAuth(t){if(!this.pendingTransport)throw new Error("No pending OAuth flow.");try{await this.pendingTransport.finishAuth?.(t);}catch(e){throw p.error("failed to finish OAuth",{id:this.id,error:e}),e}this.pendingTransport=null,this.capturedRedirectUrl=null,p.info("OAuth completed, ready to reconnect",{id:this.id});}isAuthRequired(){return this._info.status.status==="needs_auth"}isClientRegistrationRequired(){return this._info.status.status==="needs_client_registration"}getPendingTransport(){return this.pendingTransport}getAuthorizationUrl(){return this.capturedRedirectUrl?.toString()??""}async disconnect(){this.notificationCleanup&&(this.notificationCleanup(),this.notificationCleanup=null),this.client&&(await this.client.close().catch(t=>{p.error("Failed to close MCP client",{id:this.id,error:t});}),this.client=null),this.pendingTransport=null,this.capturedRedirectUrl=null,this.toolListChangedHandler=null,this._info.status.status==="connected"&&(this._info.status={status:"disconnected"}),p.info("disconnected from MCP server",{id:this.id});}async listTools(){if(!this.client||this._info.status.status!=="connected")return {};let t={};for(let e of this._info.tools)t[e.name]={name:e.name,description:e.description,inputSchema:e.inputSchema};return t}async callTool(t,e,r){let n=Date.now();if(!this.client||this._info.status.status!=="connected")return {toolName:t,args:e,content:[],success:false,error:"Client not connected",duration:Date.now()-n};try{let o=await withTimeout(this.client.callTool({name:t,arguments:e},CallToolResultSchema,{resetTimeoutOnProgress:!0,timeout:r}),r??M);return {toolName:t,args:e,content:o.content.map(m=>m.type==="text"?{type:"text",text:m.text}:m.type==="image"?{type:"image",data:m.data,mimeType:m.mimeType}:m.type==="resource"?{type:"resource",resource:m.resource}:{type:"text",text:String(m)}),success:!0,duration:Date.now()-n,metadata:o.metadata}}catch(o){return {toolName:t,args:e,content:[],success:false,error:o instanceof Error?o.message:String(o),duration:Date.now()-n}}}async listResources(){return [...this._info.resources]}async readResource(t){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for readResource",{id:this.id});return}return this.client.readResource({uri:t}).catch(e=>{p.error("failed to read resource",{id:this.id,uri:t,error:e.message});})}async listPrompts(){return [...this._info.prompts]}async getPrompt(t,e){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for getPrompt",{id:this.id});return}return this.client.getPrompt({name:t,arguments:e}).catch(r=>{p.error("failed to get prompt",{id:this.id,name:t,error:r.message});})}async refreshTools(){if(!(!this.client||this._info.status.status!=="connected"))try{let t=await withTimeout(this.client.listTools(),M);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),p.info("tools refreshed",{id:this.id,count:this._info.tools.length});}catch(t){p.error("failed to refresh tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}}async createClient(t){return t.type==="local"?await this.createLocalClient(t):t.type==="remote"?await this.createRemoteClient(t):null}async fetchCapabilities(){if(this.client){try{let t=await withTimeout(this.client.listTools(),M);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));}catch(t){p.debug("failed to get tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}try{let t=await withTimeout(this.client.listResources(),5e3);this._info.resources=t.resources.map(e=>({name:e.name,uri:e.uri,description:e.description,mimeType:e.mimeType}));}catch{p.debug("failed to get resources",{id:this.id});}try{let t=await withTimeout(this.client.listPrompts(),5e3);this._info.prompts=t.prompts.map(e=>({name:e.name,description:e.description,arguments:e.arguments?.map(r=>({name:r.name,description:r.description,required:r.required}))}));}catch{p.debug("failed to get prompts",{id:this.id});}}}async createLocalClient(t){let[e,...r]=t.command;if(!e)return this._info.status={status:"failed",error:"Command is empty"},null;let n=new StdioClientTransport({stderr:"pipe",command:e,args:r.length>0?r:void 0,cwd:t.cwd??process.cwd(),env:Object.fromEntries(Object.entries({...process.env,...t.environment}).filter(([,o])=>o!==void 0))});n.stderr?.on("data",o=>{p.info(`mcp stderr: ${o.toString()}`,{id:this.id});});try{let o=new Client({name:"easbot-mcp",version:x()});return await withTimeout(o.connect(n),t.timeout??M),this.registerNotificationHandler(o),o}catch(o){let m=o instanceof Error?o.message:String(o);return this._info.status={status:"failed",error:m},p.error("local mcp startup failed",{id:this.id,command:[e,...r],error:m}),null}}async createRemoteClient(t){let e={headers:t.headers};if((t.transport||"streamable-http")==="sse"){p.info("using SSE transport",{id:this.id,url:t.url});let n=new SSEClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}else {p.info("using StreamableHTTP transport",{id:this.id,url:t.url});let n=new StreamableHTTPClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}}async connectWithTransport(t,e){try{let r=new Client({name:"easbot-mcp",version:x()});return await r.connect(t),this.registerNotificationHandler(r),r}catch(r){return this.handleConnectionError(r,t,e),null}}handleConnectionError(t,e,r){if(t instanceof UnauthorizedError){let n=t instanceof Error?t.message:String(t);n.includes("registration")||n.includes("client_id")?this._info.status={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."}:(this._info.status={status:"needs_auth"},this.pendingTransport=e,this.capturedRedirectUrl=this.extractRedirectUrl(t));}else {let n=t instanceof Error?t.message:String(t);this._info.status={status:"failed",error:n};}p.error("remote mcp connection failed",{id:this.id,url:r.url,status:this._info.status});}extractRedirectUrl(t){let r=t.message.match(/https?:\/\/[^\s]+/);if(r)try{return new URL(r[0])}catch{return null}return null}registerNotificationHandler(t){let e=async()=>{p.info("tools list changed notification received",{id:this.id}),await this.refreshTools(),this.toolListChangedHandler&&await this.toolListChangedHandler();};t.setNotificationHandler(ToolListChangedNotificationSchema,e),this.notificationCleanup=()=>{t.removeNotificationHandler("notifications/tools/list_changed");};}createInitialInfo(){return {id:"",name:"",status:{status:"disconnected"},tools:[],resources:[],prompts:[]}}};function it(){return new A}var le=v.discriminatedUnion("status",[v.object({status:v.literal("connected")}).meta({ref:"MCPStatusConnected"}),v.object({status:v.literal("disconnected")}).meta({ref:"MCPStatusDisconnected"}),v.object({status:v.literal("failed"),error:v.string()}).meta({ref:"MCPStatusFailed"}),v.object({status:v.literal("needs_auth")}).meta({ref:"MCPStatusNeedsAuth"}),v.object({status:v.literal("needs_client_registration"),error:v.string()}).meta({ref:"MCPStatusNeedsClientRegistration"}),v.object({status:v.literal("disabled")}).meta({ref:"MCPStatusDisabled"})]);var ge="@easbot/mcp";async function ve(s){let{Log:t}=await import('./chunks/log-2GAL6FAC.mjs'),e=false;await t.init({logDir:s.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:s.print??false,dev:s.dev??e,level:s.level??("INFO")});}export{P as HttpServerAdapter,A as MCPClient,ge as NAME,l as ServerStatus,E as ServerTransportType,le as Status,w as StdioServerAdapter,k as ToolRegistry,R as ToolRegistryEvent,B as createAndStartHttpServer,z as createAndStartStdioServer,F as createHttpServer,it as createMCPClient,X as createServerFromConfig,zt as createServersFromConfigMap,Z as createStdioServer,x as getVersion,ve as initLog,b as tools};
3
+ `);}),this.httpServer.listen(e,r),g.info("HTTP server listening",{hostname:r,port:e}),this.info.status=l.RUNNING,this.info.lastActivityAt=Date.now(),g.info("started",{id:this.info.id,name:this.info.name,toolCount:b.getSize()});}catch(t){throw this.info.status=l.ERROR,g.error("failed to start",{id:this.info.id,error:t instanceof Error?t.message:String(t)}),t}finally{this.isStarting=false;}}async stop(){if(this.isStopping){g.warn("already stopping",{id:this.info.id});return}if(this.info.status!==l.RUNNING&&this.info.status!==l.ERROR){g.debug("not running",{id:this.info.id,status:this.info.status});return}this.isStopping=true,this.info.status=l.STOPPING;try{g.info("stopping",{id:this.info.id,name:this.info.name}),this.unsubscribeTools(),this.httpServer&&(await new Promise(t=>{this.httpServer.close(()=>t());}),this.httpServer=null),this.transport&&(await this.transport.close(),this.transport=null),this.server&&(await this.server.close(),this.server=null),this.info.status=l.STOPPED,g.info("stopped",{id:this.info.id});}catch(t){this.info.status=l.ERROR,g.error("failed to stop",{id:this.info.id,error:t instanceof Error?t.message:String(t)});}finally{this.isStopping=false;}}async restart(){g.info("restarting",{id:this.info.id}),await this.stop(),await this.start();}};function F(s){return new P(s)}async function B(s){let t=new P(s);return await t.start(),t.createInstance()}var O={version:"0.2.25"};function x(){return O.version}var j=b$1.create({service:"mcp.server.factory"});function $(s){return s.type==="local"}function J(s){return s.type==="remote"}function W(s,t){if(!t.command)throw new Error(`MCP server ${s} has no command specified`);return {id:s,name:s,version:"1.0.0",transportType:E.STDIO,enabled:t.enabled,timeout:t.timeout,command:t.command,args:t.args?.length?t.args:void 0,env:t.env}}function Q(s,t){return {id:s,name:s,version:"1.0.0",transportType:E.HTTP,enabled:t.enabled,timeout:t.timeout,url:t.url,headers:t.headers}}async function X(s,t){if(j.debug("creating server from config",{name:s,type:t.type}),$(t)){let e=W(s,t),r=new w(e);return await r.start(),r.createInstance()}if(J(t)){let e=Q(s,t),r=new P(e);return await r.start(),r.createInstance()}throw new Error(`Unsupported MCP config type: ${t.type}`)}async function zt(s){let t={};for(let[e,r]of Object.entries(s))try{let n=await X(e,r);t[e]=n;}catch(n){j.error("failed to create server from config",{name:e,error:n instanceof Error?n.message:String(n)});}return t}var p=b$1.create({service:"mcp.client"}),M=3e4,A=class{constructor(){a(this,"id","");a(this,"client",null);a(this,"_info");a(this,"notificationCleanup",null);a(this,"pendingTransport",null);a(this,"oauthState","");a(this,"capturedRedirectUrl",null);a(this,"oauthConfig");a(this,"toolListChangedHandler",null);a(this,"oauthProvider",null);this._info=this.createInitialInfo();}get info(){return {...this._info}}get status(){return this._info.status}get tools(){return [...this._info.tools]}get resources(){return [...this._info.resources]}get prompts(){return [...this._info.prompts]}get clientId(){return this.id}setToolListChangedHandler(t){this.toolListChangedHandler=t;}setOAuthProvider(t){this.oauthProvider=t;}async connect(t,e){p.info("connecting to MCP server",{id:t,type:e.type}),await this.disconnect(),this.id=t,this._info=this.createInitialInfo(),this._info.id=t,this._info.name=t;try{if(e.type==="remote"&&(this.oauthConfig=e.oauth===!1?void 0:e.oauth??{}),this.client=await this.createClient(e),!this.client)return;this._info.status={status:"connected"},this._info.connectedAt=Date.now(),await this.fetchCapabilities(),p.info("connected to MCP server",{id:t,toolCount:this._info.tools.length});}catch(r){let n=r instanceof Error?r.message:String(r);this._info.status={status:"failed",error:n},this._info.error=n,p.error("failed to connect to MCP server",{id:t,error:n});}}async startAuth(){if(!this.pendingTransport)throw new Error("No pending OAuth flow. Please connect to a server that requires authentication first.");return this.oauthState=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(t=>t.toString(16).padStart(2,"0")).join(""),this.oauthProvider&&await this.oauthProvider.saveState(this.oauthState),{authorizationUrl:this.capturedRedirectUrl?.toString()??"",state:this.oauthState}}async finishAuth(t){if(!this.pendingTransport)throw new Error("No pending OAuth flow.");try{await this.pendingTransport.finishAuth?.(t);}catch(e){throw p.error("failed to finish OAuth",{id:this.id,error:e}),e}this.pendingTransport=null,this.capturedRedirectUrl=null,p.info("OAuth completed, ready to reconnect",{id:this.id});}isAuthRequired(){return this._info.status.status==="needs_auth"}isClientRegistrationRequired(){return this._info.status.status==="needs_client_registration"}getPendingTransport(){return this.pendingTransport}getAuthorizationUrl(){return this.capturedRedirectUrl?.toString()??""}async disconnect(){this.notificationCleanup&&(this.notificationCleanup(),this.notificationCleanup=null),this.client&&(await this.client.close().catch(t=>{p.error("Failed to close MCP client",{id:this.id,error:t});}),this.client=null),this.pendingTransport=null,this.capturedRedirectUrl=null,this.toolListChangedHandler=null,this._info.status.status==="connected"&&(this._info.status={status:"disconnected"}),p.info("disconnected from MCP server",{id:this.id});}async listTools(){if(!this.client||this._info.status.status!=="connected")return {};let t={};for(let e of this._info.tools)t[e.name]={name:e.name,description:e.description,inputSchema:e.inputSchema};return t}async callTool(t,e,r){let n=Date.now();if(!this.client||this._info.status.status!=="connected")return {toolName:t,args:e,content:[],success:false,error:"Client not connected",duration:Date.now()-n};try{let o=await withTimeout(this.client.callTool({name:t,arguments:e},CallToolResultSchema,{resetTimeoutOnProgress:!0,timeout:r}),r??M);return {toolName:t,args:e,content:o.content.map(m=>m.type==="text"?{type:"text",text:m.text}:m.type==="image"?{type:"image",data:m.data,mimeType:m.mimeType}:m.type==="resource"?{type:"resource",resource:m.resource}:{type:"text",text:String(m)}),success:!0,duration:Date.now()-n,metadata:o.metadata}}catch(o){return {toolName:t,args:e,content:[],success:false,error:o instanceof Error?o.message:String(o),duration:Date.now()-n}}}async listResources(){return [...this._info.resources]}async readResource(t){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for readResource",{id:this.id});return}return this.client.readResource({uri:t}).catch(e=>{p.error("failed to read resource",{id:this.id,uri:t,error:e.message});})}async listPrompts(){return [...this._info.prompts]}async getPrompt(t,e){if(!this.client||this._info.status.status!=="connected"){p.warn("client not connected for getPrompt",{id:this.id});return}return this.client.getPrompt({name:t,arguments:e}).catch(r=>{p.error("failed to get prompt",{id:this.id,name:t,error:r.message});})}async refreshTools(){if(!(!this.client||this._info.status.status!=="connected"))try{let t=await withTimeout(this.client.listTools(),M);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),p.info("tools refreshed",{id:this.id,count:this._info.tools.length});}catch(t){p.error("failed to refresh tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}}async createClient(t){return t.type==="local"?await this.createLocalClient(t):t.type==="remote"?await this.createRemoteClient(t):null}async fetchCapabilities(){if(this.client){try{let t=await withTimeout(this.client.listTools(),M);this._info.tools=t.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));}catch(t){p.debug("failed to get tools",{id:this.id,error:t instanceof Error?t.message:String(t)});}try{let t=await withTimeout(this.client.listResources(),5e3);this._info.resources=t.resources.map(e=>({name:e.name,uri:e.uri,description:e.description,mimeType:e.mimeType}));}catch{p.debug("failed to get resources",{id:this.id});}try{let t=await withTimeout(this.client.listPrompts(),5e3);this._info.prompts=t.prompts.map(e=>({name:e.name,description:e.description,arguments:e.arguments?.map(r=>({name:r.name,description:r.description,required:r.required}))}));}catch{p.debug("failed to get prompts",{id:this.id});}}}async createLocalClient(t){let[e,...r]=t.command;if(!e)return this._info.status={status:"failed",error:"Command is empty"},null;let n=new StdioClientTransport({stderr:"pipe",command:e,args:r.length>0?r:void 0,cwd:t.cwd??process.cwd(),env:Object.fromEntries(Object.entries({...process.env,...t.environment}).filter(([,o])=>o!==void 0))});n.stderr?.on("data",o=>{p.info(`mcp stderr: ${o.toString()}`,{id:this.id});});try{let o=new Client({name:"easbot-mcp",version:x()});return await withTimeout(o.connect(n),t.timeout??M),this.registerNotificationHandler(o),o}catch(o){let m=o instanceof Error?o.message:String(o);return this._info.status={status:"failed",error:m},p.error("local mcp startup failed",{id:this.id,command:[e,...r],error:m}),null}}async createRemoteClient(t){let e={headers:t.headers};if((t.transport||"streamable-http")==="sse"){p.info("using SSE transport",{id:this.id,url:t.url});let n=new SSEClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}else {p.info("using StreamableHTTP transport",{id:this.id,url:t.url});let n=new StreamableHTTPClientTransport(new URL(t.url),{requestInit:e});return await this.connectWithTransport(n,t)}}async connectWithTransport(t,e){try{let r=new Client({name:"easbot-mcp",version:x()});return await r.connect(t),this.registerNotificationHandler(r),r}catch(r){return this.handleConnectionError(r,t,e),null}}handleConnectionError(t,e,r){if(t instanceof UnauthorizedError){let n=t instanceof Error?t.message:String(t);n.includes("registration")||n.includes("client_id")?this._info.status={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."}:(this._info.status={status:"needs_auth"},this.pendingTransport=e,this.capturedRedirectUrl=this.extractRedirectUrl(t));}else {let n=t instanceof Error?t.message:String(t);this._info.status={status:"failed",error:n};}p.error("remote mcp connection failed",{id:this.id,url:r.url,status:this._info.status});}extractRedirectUrl(t){let r=t.message.match(/https?:\/\/[^\s]+/);if(r)try{return new URL(r[0])}catch{return null}return null}registerNotificationHandler(t){let e=async()=>{p.info("tools list changed notification received",{id:this.id}),await this.refreshTools(),this.toolListChangedHandler&&await this.toolListChangedHandler();};t.setNotificationHandler(ToolListChangedNotificationSchema,e),this.notificationCleanup=()=>{t.removeNotificationHandler("notifications/tools/list_changed");};}createInitialInfo(){return {id:"",name:"",status:{status:"disconnected"},tools:[],resources:[],prompts:[]}}};function it(){return new A}var le=v.discriminatedUnion("status",[v.object({status:v.literal("connected")}).meta({ref:"MCPStatusConnected"}),v.object({status:v.literal("disconnected")}).meta({ref:"MCPStatusDisconnected"}),v.object({status:v.literal("failed"),error:v.string()}).meta({ref:"MCPStatusFailed"}),v.object({status:v.literal("needs_auth")}).meta({ref:"MCPStatusNeedsAuth"}),v.object({status:v.literal("needs_client_registration"),error:v.string()}).meta({ref:"MCPStatusNeedsClientRegistration"}),v.object({status:v.literal("disabled")}).meta({ref:"MCPStatusDisabled"})]);var ge="@easbot/mcp";async function ve(s){let{Log:t}=await import('./chunks/log-WIKXQDPJ.mjs'),e=false;await t.init({logDir:s.logDir??process.env.EASBOT_LOG_PATH??process.cwd(),print:s.print??false,dev:s.dev??e,level:s.level??("INFO")});}export{P as HttpServerAdapter,A as MCPClient,ge as NAME,l as ServerStatus,E as ServerTransportType,le as Status,w as StdioServerAdapter,k as ToolRegistry,R as ToolRegistryEvent,B as createAndStartHttpServer,z as createAndStartStdioServer,F as createHttpServer,it as createMCPClient,X as createServerFromConfig,zt as createServersFromConfigMap,Z as createStdioServer,x as getVersion,ve as initLog,b as tools};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/mcp",
3
- "version": "0.2.23",
3
+ "version": "0.2.25",
4
4
  "description": "MCP (Model Context Protocol) integration library for EASBOT ecosystem",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -44,8 +44,8 @@
44
44
  "ai": "^6.0.176",
45
45
  "zod": "^4.4.3",
46
46
  "@modelcontextprotocol/sdk": "^1.29.0",
47
- "@easbot/types": "0.2.23",
48
- "@easbot/utils": "0.2.23"
47
+ "@easbot/types": "0.2.25",
48
+ "@easbot/utils": "0.2.25"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@biomejs/biome": "^2.4.14",
@@ -1,7 +0,0 @@
1
- 'use strict';var qi=require('path'),lh=require('fs/promises'),Fn=require('fs'),fo=require('zod'),url=require('url'),events=require('events'),jr=require('stream'),string_decoder=require('string_decoder'),utils=require('@easbot/utils');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var qi__default=/*#__PURE__*/_interopDefault(qi);var lh__default=/*#__PURE__*/_interopDefault(lh);var Fn__namespace=/*#__PURE__*/_interopNamespace(Fn);var fo__default=/*#__PURE__*/_interopDefault(fo);var jr__default=/*#__PURE__*/_interopDefault(jr);var ph=Object.defineProperty;var Rs=e=>{throw TypeError(e)};var fh=(e,t,i)=>t in e?ph(e,t,{enumerable:true,configurable:true,writable:true,value:i}):e[t]=i;var p=(e,t,i)=>fh(e,typeof t!="symbol"?t+"":t,i),Ki=(e,t,i)=>t.has(e)||Rs("Cannot "+i);var r=(e,t,i)=>(Ki(e,t,"read from private field"),i?i.call(e):t.get(e)),m=(e,t,i)=>t.has(e)?Rs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),c=(e,t,i,s)=>(Ki(e,t,"write to private field"),t.set(e,i),i),g=(e,t,i)=>(Ki(e,t,"access private method"),i);var xi=(e,t,i,s)=>({set _(h){c(e,t,h);},get _(){return r(e,t,s)}});var yr=(e,t,i)=>{let s=e instanceof RegExp?Cs(e,i):e,h=t instanceof RegExp?Cs(t,i):t,n=s!==null&&h!=null&&gh(s,h,i);return n&&{start:n[0],end:n[1],pre:i.slice(0,n[0]),body:i.slice(n[0]+s.length,n[1]),post:i.slice(n[1]+h.length)}},Cs=(e,t)=>{let i=t.match(e);return i?i[0]:null},gh=(e,t,i)=>{let s,h,n,o,a,l=i.indexOf(e),u=i.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return [l,u];for(s=[],n=i.length;d>=0&&!a;){if(d===l)s.push(d),l=i.indexOf(e,d+1);else if(s.length===1){let f=s.pop();f!==void 0&&(a=[f,u]);}else h=s.pop(),h!==void 0&&h<n&&(n=h,o=u),u=i.indexOf(t,d+1);d=l<u&&l>=0?l:u;}s.length&&o!==void 0&&(a=[n,o]);}return a},br="\0SLASH"+Math.random()+"\0",Sr="\0OPEN"+Math.random()+"\0",bs="\0CLOSE"+Math.random()+"\0",vr="\0COMMA"+Math.random()+"\0",Er="\0PERIOD"+Math.random()+"\0",mh=new RegExp(br,"g"),wh=new RegExp(Sr,"g"),yh=new RegExp(bs,"g"),bh=new RegExp(vr,"g"),Sh=new RegExp(Er,"g"),vh=/\\\\/g,Eh=/\\{/g,xh=/\\}/g,kh=/\\,/g,Rh=/\\./g,Ch=1e5;function Yi(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function Oh(e){return e.replace(vh,br).replace(Eh,Sr).replace(xh,bs).replace(kh,vr).replace(Rh,Er)}function Ah(e){return e.replace(mh,"\\").replace(wh,"{").replace(yh,"}").replace(bh,",").replace(Sh,".")}function xr(e){if(!e)return [""];let t=[],i=yr("{","}",e);if(!i)return e.split(",");let{pre:s,body:h,post:n}=i,o=s.split(",");o[o.length-1]+="{"+h+"}";let a=xr(n);return n.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),t.push.apply(t,o),t}function Fh(e,t={}){if(!e)return [];let{max:i=Ch}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Je(Oh(e),i,true).map(Ah)}function Th(e){return "{"+e+"}"}function Lh(e){return /^-?0\d/.test(e)}function Mh(e,t){return e<=t}function Wh(e,t){return e>=t}function Je(e,t,i){let s=[],h=yr("{","}",e);if(!h)return [e];let n=h.pre,o=h.post.length?Je(h.post,t,false):[""];if(/\$$/.test(h.pre))for(let a=0;a<o.length&&a<t;a++){let l=n+"{"+h.body+"}"+o[a];s.push(l);}else {let a=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(h.body),l=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(h.body),u=a||l,d=h.body.indexOf(",")>=0;if(!u&&!d)return h.post.match(/,(?!,).*\}/)?(e=h.pre+"{"+h.body+bs+h.post,Je(e,t,true)):[e];let f;if(u)f=h.body.split(/\.\./);else if(f=xr(h.body),f.length===1&&f[0]!==void 0&&(f=Je(f[0],t,false).map(Th),f.length===1))return o.map(S=>h.pre+f[0]+S);let w;if(u&&f[0]!==void 0&&f[1]!==void 0){let S=Yi(f[0]),E=Yi(f[1]),b=Math.max(f[0].length,f[1].length),x=f.length===3&&f[2]!==void 0?Math.abs(Yi(f[2])):1,v=Mh;E<S&&(x*=-1,v=Wh);let R=f.some(Lh);w=[];for(let A=S;v(A,E);A+=x){let T;if(l)T=String.fromCharCode(A),T==="\\"&&(T="");else if(T=String(A),R){let L=b-T.length;if(L>0){let F=new Array(L+1).join("0");A<0?T="-"+F+T.slice(1):T=F+T;}}w.push(T);}}else {w=[];for(let S=0;S<f.length;S++)w.push.apply(w,Je(f[S],t,false));}for(let S=0;S<w.length;S++)for(let E=0;E<o.length&&s.length<t;E++){let b=n+w[S]+o[E];(!i||u||b)&&s.push(b);}}return s}var $i=e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},Ph={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},$e=e=>e.replace(/[[\]\\-]/g,"\\$&"),Dh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Os=e=>e.join(""),jh=(e,t)=>{let i=t;if(e.charAt(i)!=="[")throw new Error("not in a brace expression");let s=[],h=[],n=i+1,o=false,a=false,l=false,u=false,d=i,f="";t:for(;n<e.length;){let E=e.charAt(n);if((E==="!"||E==="^")&&n===i+1){u=true,n++;continue}if(E==="]"&&o&&!l){d=n+1;break}if(o=true,E==="\\"&&!l){l=true,n++;continue}if(E==="["&&!l){for(let[b,[x,v,R]]of Object.entries(Ph))if(e.startsWith(b,n)){if(f)return ["$.",false,e.length-i,true];n+=b.length,R?h.push(x):s.push(x),a=a||v;continue t}}if(l=false,f){E>f?s.push($e(f)+"-"+$e(E)):E===f&&s.push($e(E)),f="",n++;continue}if(e.startsWith("-]",n+1)){s.push($e(E+"-")),n+=2;continue}if(e.startsWith("-",n+1)){f=E,n+=2;continue}s.push($e(E)),n++;}if(d<n)return ["",false,0,false];if(!s.length&&!h.length)return ["$.",false,e.length-i,true];if(h.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!u){let E=s[0].length===2?s[0].slice(-1):s[0];return [Dh(E),false,d-i,false]}let w="["+(u?"^":"")+Os(s)+"]",S="["+(u?"":"^")+Os(h)+"]";return [s.length&&h.length?"("+w+"|"+S+")":s.length?w:S,a,d-i,true]},Ce=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=true}={})=>i?t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?e.replace(/\[([^\/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1"),Nh=new Set(["!","?","+","*","@"]),As=e=>Nh.has(e),zh="(?!(?:^|/)\\.\\.?(?:$|/))",ki="(?!\\.)",_h=new Set(["[","."]),$h=new Set(["..","."]),Bh=new Set("().*{}+?[]^$\\!"),Uh=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ss="[^/]",Fs=Ss+"*?",Ts=Ss+"+?",U,V,$t,P,_,Qt,ue,te,Pt,pe,Qe,ve,Rr,ne,X,Mi,hs,Cr,kr=(X=class{constructor(t,i,s={}){m(this,ve);p(this,"type");m(this,U);m(this,V);m(this,$t,false);m(this,P,[]);m(this,_);m(this,Qt);m(this,ue);m(this,te,false);m(this,Pt);m(this,pe);m(this,Qe,false);this.type=t,t&&c(this,V,true),c(this,_,i),c(this,U,r(this,_)?r(r(this,_),U):this),c(this,Pt,r(this,U)===this?s:r(r(this,U),Pt)),c(this,ue,r(this,U)===this?[]:r(r(this,U),ue)),t==="!"&&!r(r(this,U),te)&&r(this,ue).push(this),c(this,Qt,r(this,_)?r(r(this,_),P).length:0);}get hasMagic(){if(r(this,V)!==void 0)return r(this,V);for(let t of r(this,P))if(typeof t!="string"&&(t.type||t.hasMagic))return c(this,V,true);return r(this,V)}toString(){return r(this,pe)!==void 0?r(this,pe):this.type?c(this,pe,this.type+"("+r(this,P).map(t=>String(t)).join("|")+")"):c(this,pe,r(this,P).map(t=>String(t)).join(""))}push(...t){for(let i of t)if(i!==""){if(typeof i!="string"&&!(i instanceof X&&r(i,_)===this))throw new Error("invalid part: "+i);r(this,P).push(i);}}toJSON(){let t=this.type===null?r(this,P).slice().map(i=>typeof i=="string"?i:i.toJSON()):[this.type,...r(this,P).map(i=>i.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===r(this,U)||r(r(this,U),te)&&r(this,_)?.type==="!")&&t.push({}),t}isStart(){if(r(this,U)===this)return true;if(!r(this,_)?.isStart())return false;if(r(this,Qt)===0)return true;let t=r(this,_);for(let i=0;i<r(this,Qt);i++){let s=r(t,P)[i];if(!(s instanceof X&&s.type==="!"))return false}return true}isEnd(){if(r(this,U)===this||r(this,_)?.type==="!")return true;if(!r(this,_)?.isEnd())return false;if(!this.type)return r(this,_)?.isEnd();let t=r(this,_)?r(r(this,_),P).length:0;return r(this,Qt)===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this));}clone(t){let i=new X(this.type,t);for(let s of r(this,P))i.copyIn(s);return i}static fromGlob(t,i={}){var h;let s=new X(null,void 0,i);return g(h=X,ne,Mi).call(h,t,s,0,i),s}toMMPattern(){if(this!==r(this,U))return r(this,U).toMMPattern();let t=this.toString(),[i,s,h,n]=this.toRegExpSource();if(!(h||r(this,V)||r(this,Pt).nocase&&!r(this,Pt).nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return s;let o=(r(this,Pt).nocase?"i":"")+(n?"u":"");return Object.assign(new RegExp(`^${i}$`,o),{_src:i,_glob:t})}get options(){return r(this,Pt)}toRegExpSource(t){let i=t??!!r(this,Pt).dot;if(r(this,U)===this&&g(this,ve,Rr).call(this),!this.type){let l=this.isStart()&&this.isEnd()&&!r(this,P).some(w=>typeof w!="string"),u=r(this,P).map(w=>{var v;let[S,E,b,x]=typeof w=="string"?g(v=X,ne,Cr).call(v,w,r(this,V),l):w.toRegExpSource(t);return c(this,V,r(this,V)||b),c(this,$t,r(this,$t)||x),S}).join(""),d="";if(this.isStart()&&typeof r(this,P)[0]=="string"&&!(r(this,P).length===1&&$h.has(r(this,P)[0]))){let w=_h,S=i&&w.has(u.charAt(0))||u.startsWith("\\.")&&w.has(u.charAt(2))||u.startsWith("\\.\\.")&&w.has(u.charAt(4)),E=!i&&!t&&w.has(u.charAt(0));d=S?zh:E?ki:"";}let f="";return this.isEnd()&&r(r(this,U),te)&&r(this,_)?.type==="!"&&(f="(?:$|\\/)"),[d+u+f,Ce(u),c(this,V,!!r(this,V)),r(this,$t)]}let s=this.type==="*"||this.type==="+",h=this.type==="!"?"(?:(?!(?:":"(?:",n=g(this,ve,hs).call(this,i);if(this.isStart()&&this.isEnd()&&!n&&this.type!=="!"){let l=this.toString();return c(this,P,[l]),this.type=null,c(this,V,void 0),[l,Ce(this.toString()),false,false]}let o=!s||t||i||!ki?"":g(this,ve,hs).call(this,true);o===n&&(o=""),o&&(n=`(?:${n})(?:${o})*?`);let a="";if(this.type==="!"&&r(this,Qe))a=(this.isStart()&&!i?ki:"")+Ts;else {let l=this.type==="!"?"))"+(this.isStart()&&!i&&!t?ki:"")+Fs+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=h+n+l;}return [a,Ce(n),c(this,V,!!r(this,V)),r(this,$t)]}},U=new WeakMap,V=new WeakMap,$t=new WeakMap,P=new WeakMap,_=new WeakMap,Qt=new WeakMap,ue=new WeakMap,te=new WeakMap,Pt=new WeakMap,pe=new WeakMap,Qe=new WeakMap,ve=new WeakSet,Rr=function(){if(this!==r(this,U))throw new Error("should only call on root");if(r(this,te))return this;this.toString(),c(this,te,true);let t;for(;t=r(this,ue).pop();){if(t.type!=="!")continue;let i=t,s=r(i,_);for(;s;){for(let h=r(i,Qt)+1;!s.type&&h<r(s,P).length;h++)for(let n of r(t,P)){if(typeof n=="string")throw new Error("string part in extglob AST??");n.copyIn(r(s,P)[h]);}i=s,s=r(i,_);}}return this},ne=new WeakSet,Mi=function(t,i,s,h){var S,E;let n=false,o=false,a=-1,l=false;if(i.type===null){let b=s,x="";for(;b<t.length;){let v=t.charAt(b++);if(n||v==="\\"){n=!n,x+=v;continue}if(o){b===a+1?(v==="^"||v==="!")&&(l=true):v==="]"&&!(b===a+2&&l)&&(o=false),x+=v;continue}else if(v==="["){o=true,a=b,l=false,x+=v;continue}if(!h.noext&&As(v)&&t.charAt(b)==="("){i.push(x),x="";let R=new X(v,i);b=g(S=X,ne,Mi).call(S,t,R,b,h),i.push(R);continue}x+=v;}return i.push(x),b}let u=s+1,d=new X(null,i),f=[],w="";for(;u<t.length;){let b=t.charAt(u++);if(n||b==="\\"){n=!n,w+=b;continue}if(o){u===a+1?(b==="^"||b==="!")&&(l=true):b==="]"&&!(u===a+2&&l)&&(o=false),w+=b;continue}else if(b==="["){o=true,a=u,l=false,w+=b;continue}if(As(b)&&t.charAt(u)==="("){d.push(w),w="";let x=new X(b,d);d.push(x),u=g(E=X,ne,Mi).call(E,t,x,u,h);continue}if(b==="|"){d.push(w),w="",f.push(d),d=new X(null,i);continue}if(b===")")return w===""&&r(i,P).length===0&&c(i,Qe,true),d.push(w),w="",i.push(...f,d),u;w+=b;}return i.type=null,c(i,V,void 0),c(i,P,[t.substring(s-1)]),u},hs=function(t){return r(this,P).map(i=>{if(typeof i=="string")throw new Error("string type in extglob ast??");let[s,h,n,o]=i.toRegExpSource(t);return c(this,$t,r(this,$t)||o),s}).filter(i=>!(this.isStart()&&this.isEnd())||!!i).join("|")},Cr=function(t,i,s=false){let h=false,n="",o=false,a=false;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(h){h=false,n+=(Bh.has(u)?"\\":"")+u;continue}if(u==="*"){if(a)continue;a=true,n+=s&&/^[*]+$/.test(t)?Ts:Fs,i=true;continue}else a=false;if(u==="\\"){l===t.length-1?n+="\\\\":h=true;continue}if(u==="["){let[d,f,w,S]=jh(t,l);if(w){n+=d,o=o||f,l+=w-1,i=i||S;continue}}if(u==="?"){n+=Ss,i=true;continue}n+=Uh(u);}return [n,Ce(t),!!i,o]},m(X,ne),X),Or=(e,{windowsPathsNoEscape:t=false,magicalBraces:i=false}={})=>i?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),nt=(e,t,i={})=>($i(t),!i.nocomment&&t.charAt(0)==="#"?false:new oe(t,i).match(e)),Gh=/^\*+([^+@!?\*\[\(]*)$/,Ih=e=>t=>!t.startsWith(".")&&t.endsWith(e),Hh=e=>t=>t.endsWith(e),Jh=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),qh=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),Zh=/^\*+\.\*+$/,Vh=e=>!e.startsWith(".")&&e.includes("."),Kh=e=>e!=="."&&e!==".."&&e.includes("."),Yh=/^\.\*+$/,Xh=e=>e!=="."&&e!==".."&&e.startsWith("."),Qh=/^\*+$/,tn=e=>e.length!==0&&!e.startsWith("."),en=e=>e.length!==0&&e!=="."&&e!=="..",sn=/^\?+([^+@!?\*\[\(]*)?$/,rn=([e,t=""])=>{let i=Ar([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},hn=([e,t=""])=>{let i=Fr([e]);return t?(t=t.toLowerCase(),s=>i(s)&&s.toLowerCase().endsWith(t)):i},nn=([e,t=""])=>{let i=Fr([e]);return t?s=>i(s)&&s.endsWith(t):i},on=([e,t=""])=>{let i=Ar([e]);return t?s=>i(s)&&s.endsWith(t):i},Ar=([e])=>{let t=e.length;return i=>i.length===t&&!i.startsWith(".")},Fr=([e])=>{let t=e.length;return i=>i.length===t&&i!=="."&&i!==".."},Tr=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",Ls={win32:{sep:"\\"},posix:{sep:"/"}},an=Tr==="win32"?Ls.win32.sep:Ls.posix.sep;nt.sep=an;var ht=Symbol("globstar **");nt.GLOBSTAR=ht;var ln="[^/]",cn=ln+"*?",un="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",pn="(?:(?!(?:\\/|^)\\.).)*?",fn=(e,t={})=>i=>nt(i,e,t);nt.filter=fn;var mt=(e,t={})=>Object.assign({},e,t),dn=e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return nt;let t=nt;return Object.assign((i,s,h={})=>t(i,s,mt(e,h)),{Minimatch:class extends t.Minimatch{constructor(i,s={}){super(i,mt(e,s));}static defaults(i){return t.defaults(mt(e,i)).Minimatch}},AST:class extends t.AST{constructor(i,s,h={}){super(i,s,mt(e,h));}static fromGlob(i,s={}){return t.AST.fromGlob(i,mt(e,s))}},unescape:(i,s={})=>t.unescape(i,mt(e,s)),escape:(i,s={})=>t.escape(i,mt(e,s)),filter:(i,s={})=>t.filter(i,mt(e,s)),defaults:i=>t.defaults(mt(e,i)),makeRe:(i,s={})=>t.makeRe(i,mt(e,s)),braceExpand:(i,s={})=>t.braceExpand(i,mt(e,s)),match:(i,s,h={})=>t.match(i,s,mt(e,h)),sep:t.sep,GLOBSTAR:ht})};nt.defaults=dn;var Lr=(e,t={})=>($i(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:Fh(e,{max:t.braceExpandMax}));nt.braceExpand=Lr;var gn=(e,t={})=>new oe(e,t).makeRe();nt.makeRe=gn;var mn=(e,t,i={})=>{let s=new oe(t,i);return e=e.filter(h=>s.match(h)),s.options.nonull&&!e.length&&e.push(t),e};nt.match=mn;var Ms=/[?*]|[+@!]\(.*?\)|\[|\]/,wn=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),oe=class{constructor(e,t={}){p(this,"options");p(this,"set");p(this,"pattern");p(this,"windowsPathsNoEscape");p(this,"nonegate");p(this,"negate");p(this,"comment");p(this,"empty");p(this,"preserveMultipleSlashes");p(this,"partial");p(this,"globSet");p(this,"globParts");p(this,"nocase");p(this,"isWindows");p(this,"platform");p(this,"windowsNoMagicRoot");p(this,"regexp");$i(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Tr,this.isWindows=this.platform==="win32";let i="allowWindowsEscape";this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t[i]===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...h)=>console.error(...h)),this.debug(this.pattern,this.globSet);let i=this.globSet.map(h=>this.slashSplit(h));this.globParts=this.preprocess(i),this.debug(this.pattern,this.globParts);let s=this.globParts.map((h,n,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=h[0]===""&&h[1]===""&&(h[2]==="?"||!Ms.test(h[2]))&&!Ms.test(h[3]),l=/^[a-z]:/i.test(h[0]);if(a)return [...h.slice(0,4),...h.slice(4).map(u=>this.parse(u))];if(l)return [h[0],...h.slice(1).map(u=>this.parse(u))]}return h.map(a=>this.parse(a))});if(this.debug(this.pattern,s),this.set=s.filter(h=>h.indexOf(false)===-1),this.isWindows)for(let h=0;h<this.set.length;h++){let n=this.set[h];n[0]===""&&n[1]===""&&this.globParts[h][2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3])&&(n[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let i=0;i<e.length;i++)for(let s=0;s<e[i].length;s++)e[i][s]==="**"&&(e[i][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let i=-1;for(;(i=t.indexOf("**",i+1))!==-1;){let s=i;for(;t[s+1]==="**";)s++;s!==i&&t.splice(i,s-i);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((i,s)=>{let h=i[i.length-1];return s==="**"&&h==="**"?i:s===".."&&h&&h!==".."&&h!=="."&&h!=="**"?(i.pop(),i):(i.push(s),i)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let h=e[s];s===1&&h===""&&e[0]===""||(h==="."||h==="")&&(t=true,e.splice(s,1),s--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let i=0;for(;(i=e.indexOf("..",i+1))!==-1;){let s=e[i-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,e.splice(i-1,2),i-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let i of e){let s=-1;for(;(s=i.indexOf("**",s+1))!==-1;){let n=s;for(;i[n+1]==="**";)n++;n>s&&i.splice(s+1,n-s);let o=i[s+1],a=i[s+2],l=i[s+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;t=true,i.splice(s,1);let u=i.slice(0);u[s]="**",e.push(u),s--;}if(!this.preserveMultipleSlashes){for(let n=1;n<i.length-1;n++){let o=i[n];n===1&&o===""&&i[0]===""||(o==="."||o==="")&&(t=true,i.splice(n,1),n--);}i[0]==="."&&i.length===2&&(i[1]==="."||i[1]==="")&&(t=true,i.pop());}let h=0;for(;(h=i.indexOf("..",h+1))!==-1;){let n=i[h-1];if(n&&n!=="."&&n!==".."&&n!=="**"){t=true;let o=h===1&&i[h+1]==="**"?["."]:[];i.splice(h-1,2,...o),i.length===0&&i.push(""),h-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let i=t+1;i<e.length;i++){let s=this.partsMatch(e[t],e[i],!this.preserveMultipleSlashes);if(s){e[t]=[],e[i]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,i=false){let s=0,h=0,n=[],o="";for(;s<e.length&&h<t.length;)if(e[s]===t[h])n.push(o==="b"?t[h]:e[s]),s++,h++;else if(i&&e[s]==="**"&&t[h]===e[s+1])n.push(e[s]),s++;else if(i&&t[h]==="**"&&e[s]===t[h+1])n.push(t[h]),h++;else if(e[s]==="*"&&t[h]&&(this.options.dot||!t[h].startsWith("."))&&t[h]!=="**"){if(o==="b")return false;o="a",n.push(e[s]),s++,h++;}else if(t[h]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(o==="a")return false;o="b",n.push(t[h]),s++,h++;}else return false;return e.length===t.length&&n}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,i=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,i++;i&&(this.pattern=e.slice(i)),this.negate=t;}matchOne(e,t,i=false){let s=this.options;if(this.isWindows){let E=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),b=!E&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),x=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),v=!x&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),R=b?3:E?0:void 0,A=v?3:x?0:void 0;if(typeof R=="number"&&typeof A=="number"){let[T,L]=[e[R],t[A]];T.toLowerCase()===L.toLowerCase()&&(t[A]=T,A>R?t=t.slice(A):R>A&&(e=e.slice(R)));}}let{optimizationLevel:h=1}=this.options;h>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var n=0,o=0,a=e.length,l=t.length;n<a&&o<l;n++,o++){this.debug("matchOne loop");var u=t[o],d=e[n];if(this.debug(t,u,d),u===false)return false;if(u===ht){this.debug("GLOBSTAR",[t,u,d]);var f=n,w=o+1;if(w===l){for(this.debug("** at the end");n<a;n++)if(e[n]==="."||e[n]===".."||!s.dot&&e[n].charAt(0)===".")return false;return true}for(;f<a;){var S=e[f];if(this.debug(`
2
- globstar while`,e,f,t,w,S),this.matchOne(e.slice(f),t.slice(w),i))return this.debug("globstar found match!",f,a,S),true;if(S==="."||S===".."||!s.dot&&S.charAt(0)==="."){this.debug("dot detected!",e,f,t,w);break}this.debug("globstar swallow a segment, and continue"),f++;}return !!(i&&(this.debug(`
3
- >>> no match, partial?`,e,f,t,w),f===a))}let E;if(typeof u=="string"?(E=d===u,this.debug("string match",u,d,E)):(E=u.test(d),this.debug("pattern match",u,d,E)),!E)return false}if(n===a&&o===l)return true;if(n===a)return i;if(o===l)return n===a-1&&e[n]==="";throw new Error("wtf?")}braceExpand(){return Lr(this.pattern,this.options)}parse(e){$i(e);let t=this.options;if(e==="**")return ht;if(e==="")return "";let i,s=null;(i=e.match(Qh))?s=t.dot?en:tn:(i=e.match(Gh))?s=(t.nocase?t.dot?qh:Jh:t.dot?Hh:Ih)(i[1]):(i=e.match(sn))?s=(t.nocase?t.dot?hn:rn:t.dot?nn:on)(i):(i=e.match(Zh))?s=t.dot?Kh:Vh:(i=e.match(Yh))&&(s=Xh);let h=kr.fromGlob(e,this.options).toMMPattern();return s&&typeof h=="object"&&Reflect.defineProperty(h,"test",{value:s}),h}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,i=t.noglobstar?cn:t.dot?un:pn,s=new Set(t.nocase?["i"]:[]),h=e.map(a=>{let l=a.map(d=>{if(d instanceof RegExp)for(let f of d.flags.split(""))s.add(f);return typeof d=="string"?wn(d):d===ht?ht:d._src});l.forEach((d,f)=>{let w=l[f+1],S=l[f-1];d!==ht||S===ht||(S===void 0?w!==void 0&&w!==ht?l[f+1]="(?:\\/|"+i+"\\/)?"+w:l[f]=i:w===void 0?l[f-1]=S+"(?:\\/|\\/"+i+")?":w!==ht&&(l[f-1]=S+"(?:\\/|\\/"+i+"\\/)"+w,l[f+1]=ht));});let u=l.filter(d=>d!==ht);if(this.partial&&u.length>=1){let d=[];for(let f=1;f<=u.length;f++)d.push(u.slice(0,f).join("/"));return "(?:"+d.join("|")+")"}return u.join("/")}).join("|"),[n,o]=e.length>1?["(?:",")"]:["",""];h="^"+n+h+o+"$",this.partial&&(h="^(?:\\/|"+n+h.slice(1,-1)+o+")$"),this.negate&&(h="^(?!"+h+").+$");try{this.regexp=new RegExp(h,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let i=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let h=this.set;this.debug(this.pattern,"set",h);let n=s[s.length-1];if(!n)for(let o=s.length-2;!n&&o>=0;o--)n=s[o];for(let o=0;o<h.length;o++){let a=h[o],l=s;if(i.matchBase&&a.length===1&&(l=[n]),this.matchOne(l,a,t))return i.flipNegate?true:!this.negate}return i.flipNegate?false:this.negate}static defaults(e){return nt.defaults(e).Minimatch}};nt.AST=kr;nt.Minimatch=oe;nt.escape=Or;nt.unescape=Ce;var bn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Mr=new Set,ns=typeof process=="object"&&process?process:{},Wr=(e,t,i,s)=>{typeof ns.emitWarning=="function"?ns.emitWarning(e,t,i,s):console.error(`[${i}] ${t}: ${e}`);},Bi=globalThis.AbortController,Ws=globalThis.AbortSignal;if(typeof Bi>"u"){Ws=class{constructor(){p(this,"onabort");p(this,"_onabort",[]);p(this,"reason");p(this,"aborted",false);}addEventListener(i,s){this._onabort.push(s);}},Bi=class{constructor(){p(this,"signal",new Ws);t();}abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=true;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i);}}};let e=ns.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=false,Wr("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var Sn=e=>!Mr.has(e),Vt=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),Pr=e=>Vt(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?Wi:null:null,Wi=class extends Array{constructor(e){super(e),this.fill(0);}},Nt,Oe,vn=(Nt=class{constructor(t,i){p(this,"heap");p(this,"length");if(!r(Nt,Oe))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new i(t),this.length=0;}static create(t){let i=Pr(t);if(!i)return [];c(Nt,Oe,true);let s=new Nt(t,i);return c(Nt,Oe,false),s}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},Oe=new WeakMap,m(Nt,Oe,false),Nt),Zs,Vs,yt,ut,xt,fe,kt,Ae,Fe,Rt,G,Ct,$,D,O,it,pt,tt,K,Ot,Y,At,Ft,ft,dt,Tt,ee,st,Te,y,os,de,Bt,ti,gt,Dr,ge,Le,ei,Kt,Yt,as,Pi,Di,W,ls,qe,Xt,cs,Me,Ii=(Me=class{constructor(t){m(this,y);m(this,yt);m(this,ut);m(this,xt);m(this,fe);m(this,kt);m(this,Ae);m(this,Fe);m(this,Rt);p(this,"ttl");p(this,"ttlResolution");p(this,"ttlAutopurge");p(this,"updateAgeOnGet");p(this,"updateAgeOnHas");p(this,"allowStale");p(this,"noDisposeOnSet");p(this,"noUpdateTTL");p(this,"maxEntrySize");p(this,"sizeCalculation");p(this,"noDeleteOnFetchRejection");p(this,"noDeleteOnStaleGet");p(this,"allowStaleOnFetchAbort");p(this,"allowStaleOnFetchRejection");p(this,"ignoreFetchAbort");m(this,G);m(this,Ct);m(this,$);m(this,D);m(this,O);m(this,it);m(this,pt);m(this,tt);m(this,K);m(this,Ot);m(this,Y);m(this,At);m(this,Ft);m(this,ft);m(this,dt);m(this,Tt);m(this,ee);m(this,st);m(this,Te);m(this,de,()=>{});m(this,Bt,()=>{});m(this,ti,()=>{});m(this,gt,()=>false);m(this,ge,t=>{});m(this,Le,(t,i,s)=>{});m(this,ei,(t,i,s,h)=>{if(s||h)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});p(this,Zs,"LRUCache");let{max:i=0,ttl:s,ttlResolution:h=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:u,onInsert:d,disposeAfter:f,noDisposeOnSet:w,noUpdateTTL:S,maxSize:E=0,maxEntrySize:b=0,sizeCalculation:x,fetchMethod:v,memoMethod:R,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:L,allowStaleOnFetchAbort:F,ignoreFetchAbort:j,perf:N}=t;if(N!==void 0&&typeof N?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(c(this,Rt,N??bn),i!==0&&!Vt(i))throw new TypeError("max option must be a nonnegative integer");let B=i?Pr(i):Array;if(!B)throw new Error("invalid max value: "+i);if(c(this,yt,i),c(this,ut,E),this.maxEntrySize=b||r(this,ut),this.sizeCalculation=x,this.sizeCalculation){if(!r(this,ut)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(R!==void 0&&typeof R!="function")throw new TypeError("memoMethod must be a function if defined");if(c(this,Fe,R),v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(c(this,Ae,v),c(this,ee,!!v),c(this,$,new Map),c(this,D,new Array(i).fill(void 0)),c(this,O,new Array(i).fill(void 0)),c(this,it,new B(i)),c(this,pt,new B(i)),c(this,tt,0),c(this,K,0),c(this,Ot,vn.create(i)),c(this,G,0),c(this,Ct,0),typeof u=="function"&&c(this,xt,u),typeof d=="function"&&c(this,fe,d),typeof f=="function"?(c(this,kt,f),c(this,Y,[])):(c(this,kt,void 0),c(this,Y,void 0)),c(this,Tt,!!r(this,xt)),c(this,Te,!!r(this,fe)),c(this,st,!!r(this,kt)),this.noDisposeOnSet=!!w,this.noUpdateTTL=!!S,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!L,this.allowStaleOnFetchAbort=!!F,this.ignoreFetchAbort=!!j,this.maxEntrySize!==0){if(r(this,ut)!==0&&!Vt(r(this,ut)))throw new TypeError("maxSize must be a positive integer if specified");if(!Vt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");g(this,y,Dr).call(this);}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Vt(h)||h===0?h:1,this.ttlAutopurge=!!n,this.ttl=s||0,this.ttl){if(!Vt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");g(this,y,os).call(this);}if(r(this,yt)===0&&this.ttl===0&&r(this,ut)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!r(this,yt)&&!r(this,ut)){let M="LRU_CACHE_UNBOUNDED";Sn(M)&&(Mr.add(M),Wr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",M,Me));}}get perf(){return r(this,Rt)}static unsafeExposeInternals(t){return {starts:r(t,Ft),ttls:r(t,ft),autopurgeTimers:r(t,dt),sizes:r(t,At),keyMap:r(t,$),keyList:r(t,D),valList:r(t,O),next:r(t,it),prev:r(t,pt),get head(){return r(t,tt)},get tail(){return r(t,K)},free:r(t,Ot),isBackgroundFetch:i=>{var s;return g(s=t,y,W).call(s,i)},backgroundFetch:(i,s,h,n)=>{var o;return g(o=t,y,Di).call(o,i,s,h,n)},moveToTail:i=>{var s;return g(s=t,y,qe).call(s,i)},indexes:i=>{var s;return g(s=t,y,Kt).call(s,i)},rindexes:i=>{var s;return g(s=t,y,Yt).call(s,i)},isStale:i=>{var s;return r(s=t,gt).call(s,i)}}}get max(){return r(this,yt)}get maxSize(){return r(this,ut)}get calculatedSize(){return r(this,Ct)}get size(){return r(this,G)}get fetchMethod(){return r(this,Ae)}get memoMethod(){return r(this,Fe)}get dispose(){return r(this,xt)}get onInsert(){return r(this,fe)}get disposeAfter(){return r(this,kt)}getRemainingTTL(t){return r(this,$).has(t)?1/0:0}*entries(){for(let t of g(this,y,Kt).call(this))r(this,O)[t]!==void 0&&r(this,D)[t]!==void 0&&!g(this,y,W).call(this,r(this,O)[t])&&(yield [r(this,D)[t],r(this,O)[t]]);}*rentries(){for(let t of g(this,y,Yt).call(this))r(this,O)[t]!==void 0&&r(this,D)[t]!==void 0&&!g(this,y,W).call(this,r(this,O)[t])&&(yield [r(this,D)[t],r(this,O)[t]]);}*keys(){for(let t of g(this,y,Kt).call(this)){let i=r(this,D)[t];i!==void 0&&!g(this,y,W).call(this,r(this,O)[t])&&(yield i);}}*rkeys(){for(let t of g(this,y,Yt).call(this)){let i=r(this,D)[t];i!==void 0&&!g(this,y,W).call(this,r(this,O)[t])&&(yield i);}}*values(){for(let t of g(this,y,Kt).call(this))r(this,O)[t]!==void 0&&!g(this,y,W).call(this,r(this,O)[t])&&(yield r(this,O)[t]);}*rvalues(){for(let t of g(this,y,Yt).call(this))r(this,O)[t]!==void 0&&!g(this,y,W).call(this,r(this,O)[t])&&(yield r(this,O)[t]);}[(Vs=Symbol.iterator,Zs=Symbol.toStringTag,Vs)](){return this.entries()}find(t,i={}){for(let s of g(this,y,Kt).call(this)){let h=r(this,O)[s],n=g(this,y,W).call(this,h)?h.__staleWhileFetching:h;if(n!==void 0&&t(n,r(this,D)[s],this))return this.get(r(this,D)[s],i)}}forEach(t,i=this){for(let s of g(this,y,Kt).call(this)){let h=r(this,O)[s],n=g(this,y,W).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,D)[s],this);}}rforEach(t,i=this){for(let s of g(this,y,Yt).call(this)){let h=r(this,O)[s],n=g(this,y,W).call(this,h)?h.__staleWhileFetching:h;n!==void 0&&t.call(i,n,r(this,D)[s],this);}}purgeStale(){let t=false;for(let i of g(this,y,Yt).call(this,{allowStale:true}))r(this,gt).call(this,i)&&(g(this,y,Xt).call(this,r(this,D)[i],"expire"),t=true);return t}info(t){let i=r(this,$).get(t);if(i===void 0)return;let s=r(this,O)[i],h=g(this,y,W).call(this,s)?s.__staleWhileFetching:s;if(h===void 0)return;let n={value:h};if(r(this,ft)&&r(this,Ft)){let o=r(this,ft)[i],a=r(this,Ft)[i];if(o&&a){let l=o-(r(this,Rt).now()-a);n.ttl=l,n.start=Date.now();}}return r(this,At)&&(n.size=r(this,At)[i]),n}dump(){let t=[];for(let i of g(this,y,Kt).call(this,{allowStale:true})){let s=r(this,D)[i],h=r(this,O)[i],n=g(this,y,W).call(this,h)?h.__staleWhileFetching:h;if(n===void 0||s===void 0)continue;let o={value:n};if(r(this,ft)&&r(this,Ft)){o.ttl=r(this,ft)[i];let a=r(this,Rt).now()-r(this,Ft)[i];o.start=Math.floor(Date.now()-a);}r(this,At)&&(o.size=r(this,At)[i]),t.unshift([s,o]);}return t}load(t){this.clear();for(let[i,s]of t){if(s.start){let h=Date.now()-s.start;s.start=r(this,Rt).now()-h;}this.set(i,s.value,s);}}set(t,i,s={}){var w,S,E,b;if(i===void 0)return this.delete(t),this;let{ttl:h=this.ttl,start:n,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:u=this.noUpdateTTL}=s,d=r(this,ei).call(this,t,i,s.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),g(this,y,Xt).call(this,t,"set"),this;let f=r(this,G)===0?void 0:r(this,$).get(t);if(f===void 0)f=r(this,G)===0?r(this,K):r(this,Ot).length!==0?r(this,Ot).pop():r(this,G)===r(this,yt)?g(this,y,Pi).call(this,false):r(this,G),r(this,D)[f]=t,r(this,O)[f]=i,r(this,$).set(t,f),r(this,it)[r(this,K)]=f,r(this,pt)[f]=r(this,K),c(this,K,f),xi(this,G)._++,r(this,Le).call(this,f,d,l),l&&(l.set="add"),u=false,r(this,Te)&&((w=r(this,fe))==null||w.call(this,i,t,"add"));else {g(this,y,qe).call(this,f);let x=r(this,O)[f];if(i!==x){if(r(this,ee)&&g(this,y,W).call(this,x)){x.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:v}=x;v!==void 0&&!o&&(r(this,Tt)&&((S=r(this,xt))==null||S.call(this,v,t,"set")),r(this,st)&&r(this,Y)?.push([v,t,"set"]));}else o||(r(this,Tt)&&((E=r(this,xt))==null||E.call(this,x,t,"set")),r(this,st)&&r(this,Y)?.push([x,t,"set"]));if(r(this,ge).call(this,f),r(this,Le).call(this,f,d,l),r(this,O)[f]=i,l){l.set="replace";let v=x&&g(this,y,W).call(this,x)?x.__staleWhileFetching:x;v!==void 0&&(l.oldValue=v);}}else l&&(l.set="update");r(this,Te)&&this.onInsert?.(i,t,i===x?"update":"replace");}if(h!==0&&!r(this,ft)&&g(this,y,os).call(this),r(this,ft)&&(u||r(this,ti).call(this,f,h,n),l&&r(this,Bt).call(this,l,f)),!o&&r(this,st)&&r(this,Y)){let x=r(this,Y),v;for(;v=x?.shift();)(b=r(this,kt))==null||b.call(this,...v);}return this}pop(){var t;try{for(;r(this,G);){let i=r(this,O)[r(this,tt)];if(g(this,y,Pi).call(this,!0),g(this,y,W).call(this,i)){if(i.__staleWhileFetching)return i.__staleWhileFetching}else if(i!==void 0)return i}}finally{if(r(this,st)&&r(this,Y)){let i=r(this,Y),s;for(;s=i?.shift();)(t=r(this,kt))==null||t.call(this,...s);}}}has(t,i={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:h}=i,n=r(this,$).get(t);if(n!==void 0){let o=r(this,O)[n];if(g(this,y,W).call(this,o)&&o.__staleWhileFetching===void 0)return false;if(r(this,gt).call(this,n))h&&(h.has="stale",r(this,Bt).call(this,h,n));else return s&&r(this,de).call(this,n),h&&(h.has="hit",r(this,Bt).call(this,h,n)),true}else h&&(h.has="miss");return false}peek(t,i={}){let{allowStale:s=this.allowStale}=i,h=r(this,$).get(t);if(h===void 0||!s&&r(this,gt).call(this,h))return;let n=r(this,O)[h];return g(this,y,W).call(this,n)?n.__staleWhileFetching:n}async fetch(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:S=this.ignoreFetchAbort,allowStaleOnFetchAbort:E=this.allowStaleOnFetchAbort,context:b,forceRefresh:x=false,status:v,signal:R}=i;if(!r(this,ee))return v&&(v.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,status:v});let A={allowStale:s,updateAgeOnGet:h,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:u,noUpdateTTL:d,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:E,ignoreFetchAbort:S,status:v,signal:R},T=r(this,$).get(t);if(T===void 0){v&&(v.fetch="miss");let L=g(this,y,Di).call(this,t,T,A,b);return L.__returned=L}else {let L=r(this,O)[T];if(g(this,y,W).call(this,L)){let B=s&&L.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",B&&(v.returnedStale=true)),B?L.__staleWhileFetching:L.__returned=L}let F=r(this,gt).call(this,T);if(!x&&!F)return v&&(v.fetch="hit"),g(this,y,qe).call(this,T),h&&r(this,de).call(this,T),v&&r(this,Bt).call(this,v,T),L;let j=g(this,y,Di).call(this,t,T,A,b),N=j.__staleWhileFetching!==void 0&&s;return v&&(v.fetch=F?"stale":"refresh",N&&F&&(v.returnedStale=true)),N?j.__staleWhileFetching:j.__returned=j}}async forceFetch(t,i={}){let s=await this.fetch(t,i);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,i={}){let s=r(this,Fe);if(!s)throw new Error("no memoMethod provided to constructor");let{context:h,forceRefresh:n,...o}=i,a=this.get(t,o);if(!n&&a!==void 0)return a;let l=s(t,a,{options:o,context:h});return this.set(t,l,o),l}get(t,i={}){let{allowStale:s=this.allowStale,updateAgeOnGet:h=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=i,a=r(this,$).get(t);if(a!==void 0){let l=r(this,O)[a],u=g(this,y,W).call(this,l);return o&&r(this,Bt).call(this,o,a),r(this,gt).call(this,a)?(o&&(o.get="stale"),u?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),s?l.__staleWhileFetching:void 0):(n||g(this,y,Xt).call(this,t,"expire"),o&&s&&(o.returnedStale=true),s?l:void 0)):(o&&(o.get="hit"),u?l.__staleWhileFetching:(g(this,y,qe).call(this,a),h&&r(this,de).call(this,a),l))}else o&&(o.get="miss");}delete(t){return g(this,y,Xt).call(this,t,"delete")}clear(){return g(this,y,cs).call(this,"delete")}},yt=new WeakMap,ut=new WeakMap,xt=new WeakMap,fe=new WeakMap,kt=new WeakMap,Ae=new WeakMap,Fe=new WeakMap,Rt=new WeakMap,G=new WeakMap,Ct=new WeakMap,$=new WeakMap,D=new WeakMap,O=new WeakMap,it=new WeakMap,pt=new WeakMap,tt=new WeakMap,K=new WeakMap,Ot=new WeakMap,Y=new WeakMap,At=new WeakMap,Ft=new WeakMap,ft=new WeakMap,dt=new WeakMap,Tt=new WeakMap,ee=new WeakMap,st=new WeakMap,Te=new WeakMap,y=new WeakSet,os=function(){let t=new Wi(r(this,yt)),i=new Wi(r(this,yt));c(this,ft,t),c(this,Ft,i);let s=this.ttlAutopurge?new Array(r(this,yt)):void 0;c(this,dt,s),c(this,ti,(o,a,l=r(this,Rt).now())=>{if(i[o]=a!==0?l:0,t[o]=a,s?.[o]&&(clearTimeout(s[o]),s[o]=void 0),a!==0&&s){let u=setTimeout(()=>{r(this,gt).call(this,o)&&g(this,y,Xt).call(this,r(this,D)[o],"expire");},a+1);u.unref&&u.unref(),s[o]=u;}}),c(this,de,o=>{i[o]=t[o]!==0?r(this,Rt).now():0;}),c(this,Bt,(o,a)=>{if(t[a]){let l=t[a],u=i[a];if(!l||!u)return;o.ttl=l,o.start=u,o.now=h||n();let d=o.now-u;o.remainingTTL=l-d;}});let h=0,n=()=>{let o=r(this,Rt).now();if(this.ttlResolution>0){h=o;let a=setTimeout(()=>h=0,this.ttlResolution);a.unref&&a.unref();}return o};this.getRemainingTTL=o=>{let a=r(this,$).get(o);if(a===void 0)return 0;let l=t[a],u=i[a];if(!l||!u)return 1/0;let d=(h||n())-u;return l-d},c(this,gt,o=>{let a=i[o],l=t[o];return !!l&&!!a&&(h||n())-a>l});},de=new WeakMap,Bt=new WeakMap,ti=new WeakMap,gt=new WeakMap,Dr=function(){let t=new Wi(r(this,yt));c(this,Ct,0),c(this,At,t),c(this,ge,i=>{c(this,Ct,r(this,Ct)-t[i]),t[i]=0;}),c(this,ei,(i,s,h,n)=>{if(g(this,y,W).call(this,s))return 0;if(!Vt(h))if(n){if(typeof n!="function")throw new TypeError("sizeCalculation must be a function");if(h=n(s,i),!Vt(h))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return h}),c(this,Le,(i,s,h)=>{if(t[i]=s,r(this,ut)){let n=r(this,ut)-t[i];for(;r(this,Ct)>n;)g(this,y,Pi).call(this,true);}c(this,Ct,r(this,Ct)+t[i]),h&&(h.entrySize=s,h.totalCalculatedSize=r(this,Ct));});},ge=new WeakMap,Le=new WeakMap,ei=new WeakMap,Kt=function*({allowStale:t=this.allowStale}={}){if(r(this,G))for(let i=r(this,K);!(!g(this,y,as).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,tt)));)i=r(this,pt)[i];},Yt=function*({allowStale:t=this.allowStale}={}){if(r(this,G))for(let i=r(this,tt);!(!g(this,y,as).call(this,i)||((t||!r(this,gt).call(this,i))&&(yield i),i===r(this,K)));)i=r(this,it)[i];},as=function(t){return t!==void 0&&r(this,$).get(r(this,D)[t])===t},Pi=function(t){var n;let i=r(this,tt),s=r(this,D)[i],h=r(this,O)[i];return r(this,ee)&&g(this,y,W).call(this,h)?h.__abortController.abort(new Error("evicted")):(r(this,Tt)||r(this,st))&&(r(this,Tt)&&((n=r(this,xt))==null||n.call(this,h,s,"evict")),r(this,st)&&r(this,Y)?.push([h,s,"evict"])),r(this,ge).call(this,i),r(this,dt)?.[i]&&(clearTimeout(r(this,dt)[i]),r(this,dt)[i]=void 0),t&&(r(this,D)[i]=void 0,r(this,O)[i]=void 0,r(this,Ot).push(i)),r(this,G)===1?(c(this,tt,c(this,K,0)),r(this,Ot).length=0):c(this,tt,r(this,it)[i]),r(this,$).delete(s),xi(this,G)._--,i},Di=function(t,i,s,h){let n=i===void 0?void 0:r(this,O)[i];if(g(this,y,W).call(this,n))return n;let o=new Bi,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:h},u=(b,x=false)=>{let{aborted:v}=o.signal,R=s.ignoreFetchAbort&&b!==void 0,A=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&b!==void 0);if(s.status&&(v&&!x?(s.status.fetchAborted=true,s.status.fetchError=o.signal.reason,R&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),v&&!R&&!x)return f(o.signal.reason,A);let T=S,L=r(this,O)[i];return (L===S||R&&x&&L===void 0)&&(b===void 0?T.__staleWhileFetching!==void 0?r(this,O)[i]=T.__staleWhileFetching:g(this,y,Xt).call(this,t,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(t,b,l.options))),b},d=b=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=b),f(b,false)),f=(b,x)=>{let{aborted:v}=o.signal,R=v&&s.allowStaleOnFetchAbort,A=R||s.allowStaleOnFetchRejection,T=A||s.noDeleteOnFetchRejection,L=S;if(r(this,O)[i]===S&&(!T||!x&&L.__staleWhileFetching===void 0?g(this,y,Xt).call(this,t,"fetch"):R||(r(this,O)[i]=L.__staleWhileFetching)),A)return s.status&&L.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),L.__staleWhileFetching;if(L.__returned===L)throw b},w=(b,x)=>{var R;let v=(R=r(this,Ae))==null?void 0:R.call(this,t,n,l);v&&v instanceof Promise&&v.then(A=>b(A===void 0?void 0:A),x),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(b(void 0),s.allowStaleOnFetchAbort&&(b=A=>u(A,true)));});};s.status&&(s.status.fetchDispatched=true);let S=new Promise(w).then(u,d),E=Object.assign(S,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return i===void 0?(this.set(t,E,{...l.options,status:void 0}),i=r(this,$).get(t)):r(this,O)[i]=E,E},W=function(t){if(!r(this,ee))return false;let i=t;return !!i&&i instanceof Promise&&i.hasOwnProperty("__staleWhileFetching")&&i.__abortController instanceof Bi},ls=function(t,i){r(this,pt)[i]=t,r(this,it)[t]=i;},qe=function(t){t!==r(this,K)&&(t===r(this,tt)?c(this,tt,r(this,it)[t]):g(this,y,ls).call(this,r(this,pt)[t],r(this,it)[t]),g(this,y,ls).call(this,r(this,K),t),c(this,K,t));},Xt=function(t,i){var h,n;let s=false;if(r(this,G)!==0){let o=r(this,$).get(t);if(o!==void 0)if(r(this,dt)?.[o]&&(clearTimeout(r(this,dt)?.[o]),r(this,dt)[o]=void 0),s=true,r(this,G)===1)g(this,y,cs).call(this,i);else {r(this,ge).call(this,o);let a=r(this,O)[o];if(g(this,y,W).call(this,a)?a.__abortController.abort(new Error("deleted")):(r(this,Tt)||r(this,st))&&(r(this,Tt)&&((h=r(this,xt))==null||h.call(this,a,t,i)),r(this,st)&&r(this,Y)?.push([a,t,i])),r(this,$).delete(t),r(this,D)[o]=void 0,r(this,O)[o]=void 0,o===r(this,K))c(this,K,r(this,pt)[o]);else if(o===r(this,tt))c(this,tt,r(this,it)[o]);else {let l=r(this,pt)[o];r(this,it)[l]=r(this,it)[o];let u=r(this,it)[o];r(this,pt)[u]=r(this,pt)[o];}xi(this,G)._--,r(this,Ot).push(o);}}if(r(this,st)&&r(this,Y)?.length){let o=r(this,Y),a;for(;a=o?.shift();)(n=r(this,kt))==null||n.call(this,...a);}return s},cs=function(t){var i,s;for(let h of g(this,y,Yt).call(this,{allowStale:true})){let n=r(this,O)[h];if(g(this,y,W).call(this,n))n.__abortController.abort(new Error("deleted"));else {let o=r(this,D)[h];r(this,Tt)&&((i=r(this,xt))==null||i.call(this,n,o,t)),r(this,st)&&r(this,Y)?.push([n,o,t]);}}if(r(this,$).clear(),r(this,O).fill(void 0),r(this,D).fill(void 0),r(this,ft)&&r(this,Ft)){r(this,ft).fill(0),r(this,Ft).fill(0);for(let h of r(this,dt)??[])h!==void 0&&clearTimeout(h);r(this,dt)?.fill(void 0);}if(r(this,At)&&r(this,At).fill(0),c(this,tt,0),c(this,K,0),r(this,Ot).length=0,c(this,Ct,0),c(this,G,0),r(this,st)&&r(this,Y)){let h=r(this,Y),n;for(;n=h?.shift();)(s=r(this,kt))==null||s.call(this,...n);}},Me),Ps=typeof process=="object"&&process?process:{stdout:null,stderr:null},Dn=e=>!!e&&typeof e=="object"&&(e instanceof Ui||e instanceof jr__default.default||jn(e)||Nn(e)),jn=e=>!!e&&typeof e=="object"&&e instanceof events.EventEmitter&&typeof e.pipe=="function"&&e.pipe!==jr__default.default.Writable.prototype.pipe,Nn=e=>!!e&&typeof e=="object"&&e instanceof events.EventEmitter&&typeof e.write=="function"&&typeof e.end=="function",zt=Symbol("EOF"),_t=Symbol("maybeEmitEnd"),Zt=Symbol("emittedEnd"),Ri=Symbol("emittingEnd"),Be=Symbol("emittedError"),Ci=Symbol("closed"),Ds=Symbol("read"),Oi=Symbol("flush"),js=Symbol("flushChunk"),vt=Symbol("encoding"),ke=Symbol("decoder"),J=Symbol("flowing"),Ue=Symbol("paused"),Re=Symbol("resume"),q=Symbol("buffer"),et=Symbol("pipes"),Z=Symbol("bufferLength"),Xi=Symbol("bufferPush"),Ai=Symbol("bufferShift"),Q=Symbol("objectMode"),z=Symbol("destroyed"),Qi=Symbol("error"),ts=Symbol("emitData"),Ns=Symbol("emitEnd"),es=Symbol("emitEnd2"),Mt=Symbol("async"),is=Symbol("abort"),Fi=Symbol("aborted"),Ge=Symbol("signal"),ae=Symbol("dataListeners"),ct=Symbol("discarded"),Ie=e=>Promise.resolve().then(e),zn=e=>e(),_n=e=>e==="end"||e==="finish"||e==="prefinish",$n=e=>e instanceof ArrayBuffer||!!e&&typeof e=="object"&&e.constructor&&e.constructor.name==="ArrayBuffer"&&e.byteLength>=0,Bn=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),Nr=class{constructor(e,t,i){p(this,"src");p(this,"dest");p(this,"opts");p(this,"ondrain");this.src=e,this.dest=t,this.opts=i,this.ondrain=()=>e[Re](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Un=class extends Nr{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,i){super(e,t,i),this.proxyErrors=s=>this.dest.emit("error",s),e.on("error",this.proxyErrors);}},Gn=e=>!!e.objectMode,In=e=>!e.objectMode&&!!e.encoding&&e.encoding!=="buffer",Ks,Ys,Xs,Qs,tr,er,ir,sr,rr,hr,nr,or,ar,lr,cr,ur,pr,fr,dr,Ui=class extends events.EventEmitter{constructor(...t){let i=t[0]||{};super();p(this,dr,false);p(this,fr,false);p(this,pr,[]);p(this,ur,[]);p(this,cr);p(this,lr);p(this,ar);p(this,or);p(this,nr,false);p(this,hr,false);p(this,rr,false);p(this,sr,false);p(this,ir,null);p(this,er,0);p(this,tr,false);p(this,Qs);p(this,Xs,false);p(this,Ys,0);p(this,Ks,false);p(this,"writable",true);p(this,"readable",true);if(i.objectMode&&typeof i.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Gn(i)?(this[Q]=true,this[vt]=null):In(i)?(this[vt]=i.encoding,this[Q]=false):(this[Q]=false,this[vt]=null),this[Mt]=!!i.async,this[ke]=this[vt]?new string_decoder.StringDecoder(this[vt]):null,i&&i.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[q]}),i&&i.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[et]});let{signal:s}=i;s&&(this[Ge]=s,s.aborted?this[is]():s.addEventListener("abort",()=>this[is]()));}get bufferLength(){return this[Z]}get encoding(){return this[vt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Q]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Mt]}set async(t){this[Mt]=this[Mt]||!!t;}[(dr=J,fr=Ue,pr=et,ur=q,cr=Q,lr=vt,ar=Mt,or=ke,nr=zt,hr=Zt,rr=Ri,sr=Ci,ir=Be,er=Z,tr=z,Qs=Ge,Xs=Fi,Ys=ae,Ks=ct,is)](){this[Fi]=true,this.emit("abort",this[Ge]?.reason),this.destroy(this[Ge]?.reason);}get aborted(){return this[Fi]}set aborted(t){}write(t,i,s){if(this[Fi])return false;if(this[zt])throw new Error("write after end");if(this[z])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof i=="function"&&(s=i,i="utf8"),i||(i="utf8");let h=this[Mt]?Ie:zn;if(!this[Q]&&!Buffer.isBuffer(t)){if(Bn(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if($n(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Q]?(this[J]&&this[Z]!==0&&this[Oi](true),this[J]?this.emit("data",t):this[Xi](t),this[Z]!==0&&this.emit("readable"),s&&h(s),this[J]):t.length?(typeof t=="string"&&!(i===this[vt]&&!this[ke]?.lastNeed)&&(t=Buffer.from(t,i)),Buffer.isBuffer(t)&&this[vt]&&(t=this[ke].write(t)),this[J]&&this[Z]!==0&&this[Oi](true),this[J]?this.emit("data",t):this[Xi](t),this[Z]!==0&&this.emit("readable"),s&&h(s),this[J]):(this[Z]!==0&&this.emit("readable"),s&&h(s),this[J])}read(t){if(this[z])return null;if(this[ct]=false,this[Z]===0||t===0||t&&t>this[Z])return this[_t](),null;this[Q]&&(t=null),this[q].length>1&&!this[Q]&&(this[q]=[this[vt]?this[q].join(""):Buffer.concat(this[q],this[Z])]);let i=this[Ds](t||null,this[q][0]);return this[_t](),i}[Ds](t,i){if(this[Q])this[Ai]();else {let s=i;t===s.length||t===null?this[Ai]():typeof s=="string"?(this[q][0]=s.slice(t),i=s.slice(0,t),this[Z]-=t):(this[q][0]=s.subarray(t),i=s.subarray(0,t),this[Z]-=t);}return this.emit("data",i),!this[q].length&&!this[zt]&&this.emit("drain"),i}end(t,i,s){return typeof t=="function"&&(s=t,t=void 0),typeof i=="function"&&(s=i,i="utf8"),t!==void 0&&this.write(t,i),s&&this.once("end",s),this[zt]=true,this.writable=false,(this[J]||!this[Ue])&&this[_t](),this}[Re](){this[z]||(!this[ae]&&!this[et].length&&(this[ct]=true),this[Ue]=false,this[J]=true,this.emit("resume"),this[q].length?this[Oi]():this[zt]?this[_t]():this.emit("drain"));}resume(){return this[Re]()}pause(){this[J]=false,this[Ue]=true,this[ct]=false;}get destroyed(){return this[z]}get flowing(){return this[J]}get paused(){return this[Ue]}[Xi](t){this[Q]?this[Z]+=1:this[Z]+=t.length,this[q].push(t);}[Ai](){return this[Q]?this[Z]-=1:this[Z]-=this[q][0].length,this[q].shift()}[Oi](t=false){do;while(this[js](this[Ai]())&&this[q].length);!t&&!this[q].length&&!this[zt]&&this.emit("drain");}[js](t){return this.emit("data",t),this[J]}pipe(t,i){if(this[z])return t;this[ct]=false;let s=this[Zt];return i=i||{},t===Ps.stdout||t===Ps.stderr?i.end=false:i.end=i.end!==false,i.proxyErrors=!!i.proxyErrors,s?i.end&&t.end():(this[et].push(i.proxyErrors?new Un(this,t,i):new Nr(this,t,i)),this[Mt]?Ie(()=>this[Re]()):this[Re]()),t}unpipe(t){let i=this[et].find(s=>s.dest===t);i&&(this[et].length===1?(this[J]&&this[ae]===0&&(this[J]=false),this[et]=[]):this[et].splice(this[et].indexOf(i),1),i.unpipe());}addListener(t,i){return this.on(t,i)}on(t,i){let s=super.on(t,i);if(t==="data")this[ct]=false,this[ae]++,!this[et].length&&!this[J]&&this[Re]();else if(t==="readable"&&this[Z]!==0)super.emit("readable");else if(_n(t)&&this[Zt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Be]){let h=i;this[Mt]?Ie(()=>h.call(this,this[Be])):h.call(this,this[Be]);}return s}removeListener(t,i){return this.off(t,i)}off(t,i){let s=super.off(t,i);return t==="data"&&(this[ae]=this.listeners("data").length,this[ae]===0&&!this[ct]&&!this[et].length&&(this[J]=false)),s}removeAllListeners(t){let i=super.removeAllListeners(t);return (t==="data"||t===void 0)&&(this[ae]=0,!this[ct]&&!this[et].length&&(this[J]=false)),i}get emittedEnd(){return this[Zt]}[_t](){!this[Ri]&&!this[Zt]&&!this[z]&&this[q].length===0&&this[zt]&&(this[Ri]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ci]&&this.emit("close"),this[Ri]=false);}emit(t,...i){let s=i[0];if(t!=="error"&&t!=="close"&&t!==z&&this[z])return false;if(t==="data")return !this[Q]&&!s?false:this[Mt]?(Ie(()=>this[ts](s)),true):this[ts](s);if(t==="end")return this[Ns]();if(t==="close"){if(this[Ci]=true,!this[Zt]&&!this[z])return false;let n=super.emit("close");return this.removeAllListeners("close"),n}else if(t==="error"){this[Be]=s,super.emit(Qi,s);let n=!this[Ge]||this.listeners("error").length?super.emit("error",s):false;return this[_t](),n}else if(t==="resume"){let n=super.emit("resume");return this[_t](),n}else if(t==="finish"||t==="prefinish"){let n=super.emit(t);return this.removeAllListeners(t),n}let h=super.emit(t,...i);return this[_t](),h}[ts](t){for(let s of this[et])s.dest.write(t)===false&&this.pause();let i=this[ct]?false:super.emit("data",t);return this[_t](),i}[Ns](){return this[Zt]?false:(this[Zt]=true,this.readable=false,this[Mt]?(Ie(()=>this[es]()),true):this[es]())}[es](){if(this[ke]){let i=this[ke].end();if(i){for(let s of this[et])s.dest.write(i);this[ct]||super.emit("data",i);}}for(let i of this[et])i.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Q]||(t.dataLength=0);let i=this.promise();return this.on("data",s=>{t.push(s),this[Q]||(t.dataLength+=s.length);}),await i,t}async concat(){if(this[Q])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[vt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,i)=>{this.on(z,()=>i(new Error("stream destroyed"))),this.on("error",s=>i(s)),this.on("end",()=>t());})}[Symbol.asyncIterator](){this[ct]=false;let t=false,i=async()=>(this.pause(),t=true,{value:void 0,done:true});return {next:()=>{if(t)return i();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[zt])return i();let h,n,o=d=>{this.off("data",a),this.off("end",l),this.off(z,u),i(),n(d);},a=d=>{this.off("error",o),this.off("end",l),this.off(z,u),this.pause(),h({value:d,done:!!this[zt]});},l=()=>{this.off("error",o),this.off("data",a),this.off(z,u),i(),h({done:true,value:void 0});},u=()=>o(new Error("stream destroyed"));return new Promise((d,f)=>{n=f,h=d,this.once(z,u),this.once("error",o),this.once("end",l),this.once("data",a);})},throw:i,return:i,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ct]=false;let t=false,i=()=>(this.pause(),this.off(Qi,i),this.off(z,i),this.off("end",i),t=true,{done:true,value:void 0}),s=()=>{if(t)return i();let h=this.read();return h===null?i():{done:false,value:h}};return this.once("end",i),this.once(Qi,i),this.once(z,i),{next:s,throw:i,return:i,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[z])return t?this.emit("error",t):this.emit(z),this;this[z]=true,this[ct]=true,this[q].length=0,this[Z]=0;let i=this;return typeof i.close=="function"&&!this[Ci]&&i.close(),t?this.emit("error",t):this.emit(z),this}static get isStream(){return Dn}},Hn=Fn.realpathSync.native,Ze={lstatSync:Fn.lstatSync,readdir:Fn.readdir,readdirSync:Fn.readdirSync,readlinkSync:Fn.readlinkSync,realpathSync:Hn,promises:{lstat:lh.lstat,readdir:lh.readdir,readlink:lh.readlink,realpath:lh.realpath}},zr=e=>!e||e===Ze||e===Fn__namespace?Ze:{...Ze,...e,promises:{...Ze.promises,...e.promises||{}}},_r=/^\\\\\?\\([a-z]:)\\?$/i,Jn=e=>e.replace(/\//g,"\\").replace(_r,"$1\\"),qn=/[\\\/]/,bt=0,$r=1,Br=2,Wt=4,Ur=6,Gr=8,le=10,Ir=12,wt=15,He=~wt,ss=16,zs=32,Ve=64,Et=128,Ti=256,ji=512,_s=Ve|Et|ji,Zn=1023,rs=e=>e.isFile()?Gr:e.isDirectory()?Wt:e.isSymbolicLink()?le:e.isCharacterDevice()?Br:e.isBlockDevice()?Ur:e.isSocket()?Ir:e.isFIFO()?$r:bt,$s=new Ii({max:2**12}),Ke=e=>{let t=$s.get(e);if(t)return t;let i=e.normalize("NFKD");return $s.set(e,i),i},Bs=new Ii({max:2**12}),Li=e=>{let t=Bs.get(e);if(t)return t;let i=Ke(e.toLowerCase());return Bs.set(e,i),i},Us=class extends Ii{constructor(){super({max:256});}},Vn=class extends Ii{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Hr=Symbol("PathScurry setAsCwd"),rt,ii,si,ri,hi,ni,oi,ai,li,ci,ui,pi,fi,di,gi,mi,wi,yi,bi,ie,me,Dt,Ut,Gt,It,C,we,Ht,jt,k,ps,Ni,Ye,fs,ds,Xe,zi,gs,ms,_i,Jr,qr,Zr,ws,We,Pe,Vr,ye,gr,at=(gr=class{constructor(e,t=bt,i,s,h,n,o){m(this,k);p(this,"name");p(this,"root");p(this,"roots");p(this,"parent");p(this,"nocase");p(this,"isCWD",false);m(this,rt);m(this,ii);m(this,si);m(this,ri);m(this,hi);m(this,ni);m(this,oi);m(this,ai);m(this,li);m(this,ci);m(this,ui);m(this,pi);m(this,fi);m(this,di);m(this,gi);m(this,mi);m(this,wi);m(this,yi);m(this,bi);m(this,ie);m(this,me);m(this,Dt);m(this,Ut);m(this,Gt);m(this,It);m(this,C);m(this,we);m(this,Ht);m(this,jt);m(this,We,[]);m(this,Pe,false);m(this,ye);this.name=e,c(this,ie,h?Li(e):Ke(e)),c(this,C,t&Zn),this.nocase=h,this.roots=s,this.root=i||this,c(this,we,n),c(this,Dt,o.fullpath),c(this,Gt,o.relative),c(this,It,o.relativePosix),this.parent=o.parent,this.parent?c(this,rt,r(this.parent,rt)):c(this,rt,zr(o.fs));}get dev(){return r(this,ii)}get mode(){return r(this,si)}get nlink(){return r(this,ri)}get uid(){return r(this,hi)}get gid(){return r(this,ni)}get rdev(){return r(this,oi)}get blksize(){return r(this,ai)}get ino(){return r(this,li)}get size(){return r(this,ci)}get blocks(){return r(this,ui)}get atimeMs(){return r(this,pi)}get mtimeMs(){return r(this,fi)}get ctimeMs(){return r(this,di)}get birthtimeMs(){return r(this,gi)}get atime(){return r(this,mi)}get mtime(){return r(this,wi)}get ctime(){return r(this,yi)}get birthtime(){return r(this,bi)}get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}depth(){return r(this,me)!==void 0?r(this,me):this.parent?c(this,me,this.parent.depth()+1):c(this,me,0)}childrenCache(){return r(this,we)}resolve(e){var s;if(!e)return this;let t=this.getRootString(e),i=e.substring(t.length).split(this.splitSep);return t?g(s=this.getRoot(t),k,ps).call(s,i):g(this,k,ps).call(this,i)}children(){let e=r(this,we).get(this);if(e)return e;let t=Object.assign([],{provisional:0});return r(this,we).set(this,t),c(this,C,r(this,C)&~ss),t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let i=this.children(),s=this.nocase?Li(e):Ke(e);for(let a of i)if(r(a,ie)===s)return a;let h=this.parent?this.sep:"",n=r(this,Dt)?r(this,Dt)+h+e:void 0,o=this.newChild(e,bt,{...t,parent:this,fullpath:n});return this.canReaddir()||c(o,C,r(o,C)|Et),i.push(o),o}relative(){if(this.isCWD)return "";if(r(this,Gt)!==void 0)return r(this,Gt);let e=this.name,t=this.parent;if(!t)return c(this,Gt,this.name);let i=t.relative();return i+(!i||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(r(this,It)!==void 0)return r(this,It);let e=this.name,t=this.parent;if(!t)return c(this,It,this.fullpathPosix());let i=t.relativePosix();return i+(!i||!t.parent?"":"/")+e}fullpath(){if(r(this,Dt)!==void 0)return r(this,Dt);let e=this.name,t=this.parent;if(!t)return c(this,Dt,this.name);let i=t.fullpath()+(t.parent?this.sep:"")+e;return c(this,Dt,i)}fullpathPosix(){if(r(this,Ut)!==void 0)return r(this,Ut);if(this.sep==="/")return c(this,Ut,this.fullpath());if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?c(this,Ut,`//?/${s}`):c(this,Ut,s)}let e=this.parent,t=e.fullpathPosix(),i=t+(!t||!e.parent?"":"/")+this.name;return c(this,Ut,i)}isUnknown(){return (r(this,C)&wt)===bt}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (r(this,C)&wt)===Gr}isDirectory(){return (r(this,C)&wt)===Wt}isCharacterDevice(){return (r(this,C)&wt)===Br}isBlockDevice(){return (r(this,C)&wt)===Ur}isFIFO(){return (r(this,C)&wt)===$r}isSocket(){return (r(this,C)&wt)===Ir}isSymbolicLink(){return (r(this,C)&le)===le}lstatCached(){return r(this,C)&zs?this:void 0}readlinkCached(){return r(this,Ht)}realpathCached(){return r(this,jt)}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(r(this,Ht))return true;if(!this.parent)return false;let e=r(this,C)&wt;return !(e!==bt&&e!==le||r(this,C)&Ti||r(this,C)&Et)}calledReaddir(){return !!(r(this,C)&ss)}isENOENT(){return !!(r(this,C)&Et)}isNamed(e){return this.nocase?r(this,ie)===Li(e):r(this,ie)===Ke(e)}async readlink(){let e=r(this,Ht);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await r(this,rt).promises.readlink(this.fullpath()),i=(await this.parent.realpath())?.resolve(t);if(i)return c(this,Ht,i)}catch(t){g(this,k,ms).call(this,t.code);return}}readlinkSync(){let e=r(this,Ht);if(e)return e;if(this.canReadlink()&&this.parent)try{let t=r(this,rt).readlinkSync(this.fullpath()),i=this.parent.realpathSync()?.resolve(t);if(i)return c(this,Ht,i)}catch(t){g(this,k,ms).call(this,t.code);return}}async lstat(){if((r(this,C)&Et)===0)try{return g(this,k,ws).call(this,await r(this,rt).promises.lstat(this.fullpath())),this}catch(e){g(this,k,gs).call(this,e.code);}}lstatSync(){if((r(this,C)&Et)===0)try{return g(this,k,ws).call(this,r(this,rt).lstatSync(this.fullpath())),this}catch(e){g(this,k,gs).call(this,e.code);}}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let i=this.children();if(this.calledReaddir()){let h=i.slice(0,i.provisional);t?e(null,h):queueMicrotask(()=>e(null,h));return}if(r(this,We).push(e),r(this,Pe))return;c(this,Pe,true);let s=this.fullpath();r(this,rt).readdir(s,{withFileTypes:true},(h,n)=>{if(h)g(this,k,zi).call(this,h.code),i.provisional=0;else {for(let o of n)g(this,k,_i).call(this,o,i);g(this,k,Ni).call(this,i);}g(this,k,Vr).call(this,i.slice(0,i.provisional));});}async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(r(this,ye))await r(this,ye);else {let i=()=>{};c(this,ye,new Promise(s=>i=s));try{for(let s of await r(this,rt).promises.readdir(t,{withFileTypes:!0}))g(this,k,_i).call(this,s,e);g(this,k,Ni).call(this,e);}catch(s){g(this,k,zi).call(this,s.code),e.provisional=0;}c(this,ye,void 0),i();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let i of r(this,rt).readdirSync(t,{withFileTypes:!0}))g(this,k,_i).call(this,i,e);g(this,k,Ni).call(this,e);}catch(i){g(this,k,zi).call(this,i.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(r(this,C)&_s)return false;let e=wt&r(this,C);return e===bt||e===Wt||e===le}shouldWalk(e,t){return (r(this,C)&Wt)===Wt&&!(r(this,C)&_s)&&!e.has(this)&&(!t||t(this))}async realpath(){if(r(this,jt))return r(this,jt);if(!((ji|Ti|Et)&r(this,C)))try{let e=await r(this,rt).promises.realpath(this.fullpath());return c(this,jt,this.resolve(e))}catch{g(this,k,ds).call(this);}}realpathSync(){if(r(this,jt))return r(this,jt);if(!((ji|Ti|Et)&r(this,C)))try{let e=r(this,rt).realpathSync(this.fullpath());return c(this,jt,this.resolve(e))}catch{g(this,k,ds).call(this);}}[Hr](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),i=[],s=this;for(;s&&s.parent;)t.add(s),c(s,Gt,i.join(this.sep)),c(s,It,i.join("/")),s=s.parent,i.push("..");for(s=e;s&&s.parent&&!t.has(s);)c(s,Gt,void 0),c(s,It,void 0),s=s.parent;}},rt=new WeakMap,ii=new WeakMap,si=new WeakMap,ri=new WeakMap,hi=new WeakMap,ni=new WeakMap,oi=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap,ui=new WeakMap,pi=new WeakMap,fi=new WeakMap,di=new WeakMap,gi=new WeakMap,mi=new WeakMap,wi=new WeakMap,yi=new WeakMap,bi=new WeakMap,ie=new WeakMap,me=new WeakMap,Dt=new WeakMap,Ut=new WeakMap,Gt=new WeakMap,It=new WeakMap,C=new WeakMap,we=new WeakMap,Ht=new WeakMap,jt=new WeakMap,k=new WeakSet,ps=function(e){let t=this;for(let i of e)t=t.child(i);return t},Ni=function(e){var t;c(this,C,r(this,C)|ss);for(let i=e.provisional;i<e.length;i++){let s=e[i];s&&g(t=s,k,Ye).call(t);}},Ye=function(){r(this,C)&Et||(c(this,C,(r(this,C)|Et)&He),g(this,k,fs).call(this));},fs=function(){var t;let e=this.children();e.provisional=0;for(let i of e)g(t=i,k,Ye).call(t);},ds=function(){c(this,C,r(this,C)|ji),g(this,k,Xe).call(this);},Xe=function(){if(r(this,C)&Ve)return;let e=r(this,C);(e&wt)===Wt&&(e&=He),c(this,C,e|Ve),g(this,k,fs).call(this);},zi=function(e=""){e==="ENOTDIR"||e==="EPERM"?g(this,k,Xe).call(this):e==="ENOENT"?g(this,k,Ye).call(this):this.children().provisional=0;},gs=function(e=""){var t;e==="ENOTDIR"?g(t=this.parent,k,Xe).call(t):e==="ENOENT"&&g(this,k,Ye).call(this);},ms=function(e=""){var i;let t=r(this,C);t|=Ti,e==="ENOENT"&&(t|=Et),(e==="EINVAL"||e==="UNKNOWN")&&(t&=He),c(this,C,t),e==="ENOTDIR"&&this.parent&&g(i=this.parent,k,Xe).call(i);},_i=function(e,t){return g(this,k,qr).call(this,e,t)||g(this,k,Jr).call(this,e,t)},Jr=function(e,t){let i=rs(e),s=this.newChild(e.name,i,{parent:this}),h=r(s,C)&wt;return h!==Wt&&h!==le&&h!==bt&&c(s,C,r(s,C)|Ve),t.unshift(s),t.provisional++,s},qr=function(e,t){for(let i=t.provisional;i<t.length;i++){let s=t[i];if((this.nocase?Li(e.name):Ke(e.name))===r(s,ie))return g(this,k,Zr).call(this,e,s,i,t)}},Zr=function(e,t,i,s){let h=t.name;return c(t,C,r(t,C)&He|rs(e)),h!==e.name&&(t.name=e.name),i!==s.provisional&&(i===s.length-1?s.pop():s.splice(i,1),s.unshift(t)),s.provisional++,t},ws=function(e){let{atime:t,atimeMs:i,birthtime:s,birthtimeMs:h,blksize:n,blocks:o,ctime:a,ctimeMs:l,dev:u,gid:d,ino:f,mode:w,mtime:S,mtimeMs:E,nlink:b,rdev:x,size:v,uid:R}=e;c(this,mi,t),c(this,pi,i),c(this,bi,s),c(this,gi,h),c(this,ai,n),c(this,ui,o),c(this,yi,a),c(this,di,l),c(this,ii,u),c(this,ni,d),c(this,li,f),c(this,si,w),c(this,wi,S),c(this,fi,E),c(this,ri,b),c(this,oi,x),c(this,ci,v),c(this,hi,R);let A=rs(e);c(this,C,r(this,C)&He|A|zs),A!==bt&&A!==Wt&&A!==le&&c(this,C,r(this,C)|Ve);},We=new WeakMap,Pe=new WeakMap,Vr=function(e){c(this,Pe,false);let t=r(this,We).slice();r(this,We).length=0,t.forEach(i=>i(null,e));},ye=new WeakMap,gr),Kr=class Yr extends at{constructor(i,s=bt,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"sep","\\");p(this,"splitSep",qn);}newChild(i,s=bt,h={}){return new Yr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}getRootString(i){return qi.win32.parse(i).root}getRoot(i){if(i=Jn(i.toUpperCase()),i===this.root.name)return this.root;for(let[s,h]of Object.entries(this.roots))if(this.sameRoot(i,s))return this.roots[i]=h;return this.roots[i]=new Es(i,this).root}sameRoot(i,s=this.root.name){return i=i.toUpperCase().replace(/\//g,"\\").replace(_r,"$1\\"),i===s}},Xr=class Qr extends at{constructor(i,s=bt,h,n,o,a,l){super(i,s,h,n,o,a,l);p(this,"splitSep","/");p(this,"sep","/");}getRootString(i){return i.startsWith("/")?"/":""}getRoot(i){return this.root}newChild(i,s=bt,h={}){return new Qr(i,s,this.root,this.roots,this.nocase,this.childrenCache(),h)}},De,je,Si,vi,mr,th=(mr=class{constructor(e=process.cwd(),t,i,{nocase:s,childrenCacheSize:h=16*1024,fs:n=Ze}={}){p(this,"root");p(this,"rootPath");p(this,"roots");p(this,"cwd");m(this,De);m(this,je);m(this,Si);p(this,"nocase");m(this,vi);c(this,vi,zr(n)),(e instanceof URL||e.startsWith("file://"))&&(e=url.fileURLToPath(e));let o=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),c(this,De,new Us),c(this,je,new Us),c(this,Si,new Vn(h));let a=o.substring(this.rootPath.length).split(i);if(a.length===1&&!a[0]&&a.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(r(this,vi)),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1,d=t.sep,f=this.rootPath,w=false;for(let S of a){let E=u--;l=l.child(S,{relative:new Array(E).fill("..").join(d),relativePosix:new Array(E).fill("..").join("/"),fullpath:f+=(w?"":d)+S}),w=true;}this.cwd=l;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return r(this,Si)}resolve(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,De).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpath();return r(this,De).set(t,s),s}resolvePosix(...e){let t="";for(let h=e.length-1;h>=0;h--){let n=e[h];if(!(!n||n===".")&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}let i=r(this,je).get(t);if(i!==void 0)return i;let s=this.cwd.resolve(t).fullpathPosix();return r(this,je).set(t,s),s}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i}=t;if(e.canReaddir()){let s=await e.readdir();return i?s:s.map(h=>h.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true}=t;return e.canReaddir()?i?e.readdirSync():e.readdirSync().map(s=>s.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.readlink();return t?i:i?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.readlinkSync();return t?i:i?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=await e.realpath();return t?i:i?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e.withFileTypes,e=this.cwd);let i=e.realpathSync();return t?i:i?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set,l=(d,f)=>{a.add(d),d.readdirCB((w,S)=>{if(w)return f(w);let E=S.length;if(!E)return f();let b=()=>{--E===0&&f();};for(let x of S)(!h||h(x))&&o.push(i?x:x.fullpath()),s&&x.isSymbolicLink()?x.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(a,n)?l(v,b):b()):x.shouldWalk(a,n)?l(x,b):b();},true);},u=e;return new Promise((d,f)=>{l(u,w=>{if(w)return f(w);d(o);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=[];(!h||h(e))&&o.push(i?e:e.fullpath());let a=new Set([e]);for(let l of a){let u=l.readdirSync();for(let d of u){(!h||h(d))&&o.push(i?d:d.fullpath());let f=d;if(d.isSymbolicLink()){if(!(s&&(f=d.realpathSync())))continue;f.isUnknown()&&f.lstatSync();}f.shouldWalk(a,n)&&a.add(f);}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t;(!h||h(e))&&(yield i?e:e.fullpath());let o=new Set([e]);for(let a of o){let l=a.readdirSync();for(let u of l){(!h||h(u))&&(yield i?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(o,n)&&o.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ui({objectMode:true});(!h||h(e))&&o.write(i?e:e.fullpath());let a=new Set,l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let S=(b,x,v=false)=>{if(b)return o.emit("error",b);if(s&&!v){let R=[];for(let A of x)A.isSymbolicLink()&&R.push(A.realpath().then(T=>T?.isUnknown()?T.lstat():T));if(R.length){Promise.all(R).then(()=>S(null,x,true));return}}for(let R of x)R&&(!h||h(R))&&(o.write(i?R:R.fullpath())||(f=true));u--;for(let R of x){let A=R.realpathCached()||R;A.shouldWalk(a,n)&&l.push(A);}f&&!o.flowing?o.once("drain",d):E||d();},E=true;w.readdirCB(S,true),E=false;}};return d(),o}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof at||(t=e,e=this.cwd);let{withFileTypes:i=true,follow:s=false,filter:h,walkFilter:n}=t,o=new Ui({objectMode:true}),a=new Set;(!h||h(e))&&o.write(i?e:e.fullpath());let l=[e],u=0,d=()=>{let f=false;for(;!f;){let w=l.shift();if(!w){u===0&&o.end();return}u++,a.add(w);let S=w.readdirSync();for(let E of S)(!h||h(E))&&(o.write(i?E:E.fullpath())||(f=true));u--;for(let E of S){let b=E;if(E.isSymbolicLink()){if(!(s&&(b=E.realpathSync())))continue;b.isUnknown()&&b.lstatSync();}b.shouldWalk(a,n)&&l.push(b);}}f&&!o.flowing&&o.once("drain",d);};return d(),o}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Hr](t);}},De=new WeakMap,je=new WeakMap,Si=new WeakMap,vi=new WeakMap,mr),Es=class extends th{constructor(t=process.cwd(),i={}){let{nocase:s=true}=i;super(t,qi.win32,"\\",{...i,nocase:s});p(this,"sep","\\");this.nocase=s;for(let h=this.cwd;h;h=h.parent)h.nocase=this.nocase;}parseRootPath(t){return qi.win32.parse(t).root.toUpperCase()}newRoot(t){return new Kr(this.rootPath,Wt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}},xs=class extends th{constructor(t=process.cwd(),i={}){let{nocase:s=false}=i;super(t,qi.posix,"/",{...i,nocase:s});p(this,"sep","/");this.nocase=s;}parseRootPath(t){return "/"}newRoot(t){return new Xr(this.rootPath,Wt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}},eh=class extends xs{constructor(e=process.cwd(),t={}){let{nocase:i=true}=t;super(e,{...t,nocase:i});}};process.platform==="win32"?Kr:Xr;var Kn=process.platform==="win32"?Es:process.platform==="darwin"?eh:xs,Yn=e=>e.length>=1,Xn=e=>e.length>=1,Qn=Symbol.for("nodejs.util.inspect.custom"),I,lt,H,be,Lt,Ei,se,re,he,Ne,ze,ih=(ze=class{constructor(t,i,s,h){m(this,I);m(this,lt);m(this,H);p(this,"length");m(this,be);m(this,Lt);m(this,Ei);m(this,se);m(this,re);m(this,he);m(this,Ne,true);if(!Yn(t))throw new TypeError("empty pattern list");if(!Xn(i))throw new TypeError("empty glob list");if(i.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(c(this,I,t),c(this,lt,i),c(this,H,s),c(this,be,h),r(this,H)===0){if(this.isUNC()){let[n,o,a,l,...u]=r(this,I),[d,f,w,S,...E]=r(this,lt);u[0]===""&&(u.shift(),E.shift());let b=[n,o,a,l,""].join("/"),x=[d,f,w,S,""].join("/");c(this,I,[b,...u]),c(this,lt,[x,...E]),this.length=r(this,I).length;}else if(this.isDrive()||this.isAbsolute()){let[n,...o]=r(this,I),[a,...l]=r(this,lt);o[0]===""&&(o.shift(),l.shift());let u=n+"/",d=a+"/";c(this,I,[u,...o]),c(this,lt,[d,...l]),this.length=r(this,I).length;}}}[Qn](){return "Pattern <"+r(this,lt).slice(r(this,H)).join("/")+">"}pattern(){return r(this,I)[r(this,H)]}isString(){return typeof r(this,I)[r(this,H)]=="string"}isGlobstar(){return r(this,I)[r(this,H)]===ht}isRegExp(){return r(this,I)[r(this,H)]instanceof RegExp}globString(){return c(this,Ei,r(this,Ei)||(r(this,H)===0?this.isAbsolute()?r(this,lt)[0]+r(this,lt).slice(1).join("/"):r(this,lt).join("/"):r(this,lt).slice(r(this,H)).join("/")))}hasMore(){return this.length>r(this,H)+1}rest(){return r(this,Lt)!==void 0?r(this,Lt):this.hasMore()?(c(this,Lt,new ze(r(this,I),r(this,lt),r(this,H)+1,r(this,be))),c(r(this,Lt),he,r(this,he)),c(r(this,Lt),re,r(this,re)),c(r(this,Lt),se,r(this,se)),r(this,Lt)):c(this,Lt,null)}isUNC(){let t=r(this,I);return r(this,re)!==void 0?r(this,re):c(this,re,r(this,be)==="win32"&&r(this,H)===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3])}isDrive(){let t=r(this,I);return r(this,se)!==void 0?r(this,se):c(this,se,r(this,be)==="win32"&&r(this,H)===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]))}isAbsolute(){let t=r(this,I);return r(this,he)!==void 0?r(this,he):c(this,he,t[0]===""&&t.length>1||this.isDrive()||this.isUNC())}root(){let t=r(this,I)[0];return typeof t=="string"&&this.isAbsolute()&&r(this,H)===0?t:""}checkFollowGlobstar(){return !(r(this,H)===0||!this.isGlobstar()||!r(this,Ne))}markFollowGlobstar(){return r(this,H)===0||!this.isGlobstar()||!r(this,Ne)?false:(c(this,Ne,false),true)}},I=new WeakMap,lt=new WeakMap,H=new WeakMap,be=new WeakMap,Lt=new WeakMap,Ei=new WeakMap,se=new WeakMap,re=new WeakMap,he=new WeakMap,Ne=new WeakMap,ze),to=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Gs=class{constructor(e,{nobrace:t,nocase:i,noext:s,noglobstar:h,platform:n=to}){p(this,"relative");p(this,"relativeChildren");p(this,"absolute");p(this,"absoluteChildren");p(this,"platform");p(this,"mmopts");this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=n,this.mmopts={dot:true,nobrace:t,nocase:i,noext:s,noglobstar:h,optimizationLevel:2,platform:n,nocomment:true,nonegate:true};for(let o of e)this.add(o);}add(e){let t=new oe(e,this.mmopts);for(let i=0;i<t.set.length;i++){let s=t.set[i],h=t.globParts[i];if(!s||!h)throw new Error("invalid pattern object");for(;s[0]==="."&&h[0]===".";)s.shift(),h.shift();let n=new ih(s,h,0,this.platform),o=new oe(n.globString(),this.mmopts),a=h[h.length-1]==="**",l=n.isAbsolute();l?this.absolute.push(o):this.relative.push(o),a&&(l?this.absoluteChildren.push(o):this.relativeChildren.push(o));}}ignored(e){let t=e.fullpath(),i=`${t}/`,s=e.relative()||".",h=`${s}/`;for(let n of this.relative)if(n.match(s)||n.match(h))return true;for(let n of this.absolute)if(n.match(t)||n.match(i))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",i=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(i))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}},eo=class sh{constructor(t=new Map){p(this,"store");this.store=t;}copy(){return new sh(new Map(this.store))}hasWalked(t,i){return this.store.get(t.fullpath())?.has(i.globString())}storeWalked(t,i){let s=t.fullpath(),h=this.store.get(s);h?h.add(i.globString()):this.store.set(s,new Set([i.globString()]));}},io=class{constructor(){p(this,"store",new Map);}add(e,t,i){let s=(t?2:0)|(i?1:0),h=this.store.get(e);this.store.set(e,h===void 0?s:s&h);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},so=class{constructor(){p(this,"store",new Map);}add(e,t){if(!e.canReaddir())return;let i=this.store.get(e);i?i.find(s=>s.globString()===t.globString())||i.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},Is=class rh{constructor(t,i){p(this,"hasWalkedCache");p(this,"matches",new io);p(this,"subwalks",new so);p(this,"patterns");p(this,"follow");p(this,"dot");p(this,"opts");this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=i?i.copy():new eo;}processPatterns(t,i){this.patterns=i;let s=i.map(h=>[t,h]);for(let[h,n]of s){this.hasWalkedCache.storeWalked(h,n);let o=n.root(),a=n.isAbsolute()&&this.opts.absolute!==false;if(o){h=h.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let f=n.rest();if(f)n=f;else {this.matches.add(h,true,false);continue}}if(h.isENOENT())continue;let l,u,d=false;for(;typeof(l=n.pattern())=="string"&&(u=n.rest());)h=h.resolve(l),n=u,d=true;if(l=n.pattern(),u=n.rest(),d){if(this.hasWalkedCache.hasWalked(h,n))continue;this.hasWalkedCache.storeWalked(h,n);}if(typeof l=="string"){let f=l===".."||l===""||l===".";this.matches.add(h.resolve(l),a,f);continue}else if(l===ht){(!h.isSymbolicLink()||this.follow||n.checkFollowGlobstar())&&this.subwalks.add(h,n);let f=u?.pattern(),w=u?.rest();if(!u||(f===""||f===".")&&!w)this.matches.add(h,a,f===""||f===".");else if(f===".."){let S=h.parent||h;w?this.hasWalkedCache.hasWalked(S,w)||this.subwalks.add(S,w):this.matches.add(S,a,true);}}else l instanceof RegExp&&this.subwalks.add(h,n);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new rh(this.opts,this.hasWalkedCache)}filterEntries(t,i){let s=this.subwalks.get(t),h=this.child();for(let n of i)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),u=o.rest();l===ht?h.testGlobstar(n,o,u,a):l instanceof RegExp?h.testRegExp(n,l,u,a):h.testString(n,l,u,a);}return h}testGlobstar(t,i,s,h){if((this.dot||!t.name.startsWith("."))&&(i.hasMore()||this.matches.add(t,h,false),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,i):t.isSymbolicLink()&&(s&&i.checkFollowGlobstar()?this.subwalks.add(t,s):i.markFollowGlobstar()&&this.subwalks.add(t,i)))),s){let n=s.pattern();if(typeof n=="string"&&n!==".."&&n!==""&&n!==".")this.testString(t,n,s.rest(),h);else if(n===".."){let o=t.parent||t;this.subwalks.add(o,s);}else n instanceof RegExp&&this.testRegExp(t,n,s.rest(),h);}}testRegExp(t,i,s,h){i.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}testString(t,i,s,h){t.isNamed(i)&&(s?this.subwalks.add(t,s):this.matches.add(t,h,false));}},ro=(e,t)=>typeof e=="string"?new Gs([e],t):Array.isArray(e)?new Gs(e,t):e,_e,Jt,Se,St,ce,ys,wr,hh=(wr=class{constructor(e,t,i){m(this,St);p(this,"path");p(this,"patterns");p(this,"opts");p(this,"seen",new Set);p(this,"paused",false);p(this,"aborted",false);m(this,_e,[]);m(this,Jt);m(this,Se);p(this,"signal");p(this,"maxDepth");p(this,"includeChildMatches");if(this.patterns=e,this.path=t,this.opts=i,c(this,Se,!i.posix&&i.platform==="win32"?"\\":"/"),this.includeChildMatches=i.includeChildMatches!==false,(i.ignore||!this.includeChildMatches)&&(c(this,Jt,ro(i.ignore??[],i)),!this.includeChildMatches&&typeof r(this,Jt).add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=i.maxDepth||1/0,i.signal&&(this.signal=i.signal,this.signal.addEventListener("abort",()=>{r(this,_e).length=0;}));}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=r(this,_e).shift());)e();}onResume(e){this.signal?.aborted||(this.paused?r(this,_e).push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||await e.realpath(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=await s.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat();}return this.matchCheckTest(s,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!g(this,St,ce).call(this,e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let i;if(this.opts.realpath){if(i=e.realpathCached()||e.realpathSync(),!i)return;e=i;}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let h=s.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync();}return this.matchCheckTest(s,t)}matchFinish(e,t){if(g(this,St,ce).call(this,e))return;if(!this.includeChildMatches&&r(this,Jt)?.add){let h=`${e.relativePosix()}/**`;r(this,Jt).add(h);}let i=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?r(this,Se):"";if(this.opts.withFileTypes)this.matchEmit(e);else if(i){let h=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(h+s);}else {let h=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!h.startsWith(".."+r(this,Se))?"."+r(this,Se):"";this.matchEmit(h?n+h+s:"."+s);}}async match(e,t,i){let s=await this.matchCheck(e,i);s&&this.matchFinish(s,t);}matchSync(e,t,i){let s=this.matchCheckSync(e,i);s&&this.matchFinish(s,t);}walkCB(e,t,i){this.signal?.aborted&&i(),this.walkCB2(e,t,new Is(this.opts),i);}walkCB2(e,t,i,s){if(g(this,St,ys).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,St,ce).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,i,n):o.readdirCB((l,u)=>this.walkCB3(o,u,i,n),true);}n();}walkCB3(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,St,ce).call(this,o)||(h++,this.match(o,a,l).then(()=>n()));for(let[o,a]of i.subwalks.entries())h++,this.walkCB2(o,a,i.child(),n);n();}walkCBSync(e,t,i){this.signal?.aborted&&i(),this.walkCB2Sync(e,t,new Is(this.opts),i);}walkCB2Sync(e,t,i,s){if(g(this,St,ys).call(this,e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,i,s));return}i.processPatterns(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,St,ce).call(this,o)||this.matchSync(o,a,l);for(let o of i.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;h++;let a=o.readdirSync();this.walkCB3Sync(o,a,i,n);}n();}walkCB3Sync(e,t,i,s){i=i.filterEntries(e,t);let h=1,n=()=>{--h===0&&s();};for(let[o,a,l]of i.matches.entries())g(this,St,ce).call(this,o)||this.matchSync(o,a,l);for(let[o,a]of i.subwalks.entries())h++,this.walkCB2Sync(o,a,i.child(),n);n();}},_e=new WeakMap,Jt=new WeakMap,Se=new WeakMap,St=new WeakSet,ce=function(e){return this.seen.has(e)||!!r(this,Jt)?.ignored?.(e)},ys=function(e){return !!r(this,Jt)?.childrenIgnored?.(e)},wr),Hs=class extends hh{constructor(t,i,s){super(t,i,s);p(this,"matches",new Set);}matchEmit(t){this.matches.add(t);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,i)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?i(this.signal.reason):t(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Js=class extends hh{constructor(t,i,s){super(t,i,s);p(this,"results");this.results=new Ui({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(t){this.results.write(t),this.results.flowing||this.pause();}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end());}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}},ho=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ee=class{constructor(e,t){p(this,"absolute");p(this,"cwd");p(this,"root");p(this,"dot");p(this,"dotRelative");p(this,"follow");p(this,"ignore");p(this,"magicalBraces");p(this,"mark");p(this,"matchBase");p(this,"maxDepth");p(this,"nobrace");p(this,"nocase");p(this,"nodir");p(this,"noext");p(this,"noglobstar");p(this,"pattern");p(this,"platform");p(this,"realpath");p(this,"scurry");p(this,"stat");p(this,"signal");p(this,"windowsPathsNoEscape");p(this,"withFileTypes");p(this,"includeChildMatches");p(this,"opts");p(this,"patterns");if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=url.fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(a=>a.includes("/")?a:`./**/${a}`);}if(this.pattern=e,this.platform=t.platform||ho,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let a=t.platform==="win32"?Es:t.platform==="darwin"?eh:t.platform?xs:Kn;this.scurry=new a(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let i=this.platform==="darwin"||this.platform==="win32",s={braceExpandMax:1e4,...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:i,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},h=this.pattern.map(a=>new oe(a,s)),[n,o]=h.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=n.map((a,l)=>{let u=o[l];if(!u)throw new Error("invalid pattern object");return new ih(a,u,0,this.platform)});}async walk(){return [...await new Hs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new Hs(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Js(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Js(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}},no=(e,t={})=>{Array.isArray(e)||(e=[e]);for(let i of e)if(new oe(i,t).hasMagic())return true;return false};function Hi(e,t={}){return new Ee(e,t).streamSync()}function nh(e,t={}){return new Ee(e,t).stream()}function oh(e,t={}){return new Ee(e,t).walkSync()}async function qs(e,t={}){return new Ee(e,t).walk()}function Ji(e,t={}){return new Ee(e,t).iterateSync()}function ah(e,t={}){return new Ee(e,t).iterate()}var oo=Hi,ao=Object.assign(nh,{sync:Hi}),lo=Ji,co=Object.assign(ah,{sync:Ji}),uo=Object.assign(oh,{stream:Hi,iterate:Ji}),Gi=Object.assign(qs,{glob:qs,globSync:oh,sync:uo,globStream:nh,stream:ao,globStreamSync:Hi,streamSync:oo,globIterate:ah,iterate:co,globIterateSync:Ji,iterateSync:lo,Glob:Ee,hasMagic:no,escape:Or,unescape:Ce});Gi.glob=Gi;exports.b=void 0;(L=>{L.Level=fo__default.default.enum(["DEBUG","INFO","WARN","ERROR"]).meta({ref:"LogLevel",description:"Log level"});let t={DEBUG:0,INFO:1,WARN:2,ERROR:3},i="INFO";function s(F){return t[F]>=t[i]}function h(){return i}L.getLevel=h;let n=new Map;L.Default=T({service:"default"});let a="";function l(){return a}L.file=l;let u,d,f=false,w=()=>{},S=false,E=false;async function b(F){if(f)return;if(F.print){f=true;return}F.level&&(i=F.level);let j=F.logDir||qi__default.default.join(process.env.EASBOT_LOG_PATH??process.cwd(),"logs");F.logFile?a=qi__default.default.join(j,F.logFile??"mcp.log"):a=qi__default.default.join(j,"mcp.log");try{await lh__default.default.mkdir(j,{recursive:!0}),u=await lh__default.default.open(a,"a"),d=Fn.createWriteStream("",{fd:u.fd,autoClose:!1}),w=N=>{if(!(S||E||!d||d.destroyed))try{if(!d.writable)return;d.write(N,B=>{if(B&&!S){let M=B;if(M.code==="EPIPE"||M.code==="EIO"){E=!0,d?.destroy();return}S=!0,setTimeout(()=>{S=!1;},1e3);}});}catch(B){let M=B;if(M.code==="EPIPE"||M.code==="EIO"){E=!0,d?.destroy();return}S||(S=!0,setTimeout(()=>{S=!1;},1e3));}},f=!0;}catch(N){process.stderr.write(`[LOG ERROR] Failed to init log file: ${N}
4
- `),w=B=>{try{process.stderr.write(B);}catch{}},f=true;}}L.init=b;async function x(){f&&(d&&!d.destroyed&&(await new Promise((F,j)=>{d.end(N=>{N?j(N):F();});}).catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log stream: ${F}
5
- `);}),d=void 0),u&&(await u.close().catch(F=>{process.stderr.write(`[LOG ERROR] Failed to close log file: ${F}
6
- `);}),u=void 0),w=F=>{try{process.stderr.write(F);}catch{}},f=false);}L.close=x;function R(F,j=0){let N=F.message;return F.cause instanceof Error&&j<10?N+" Caused by: "+R(F.cause,j+1):N}let A=Date.now();function T(F){F=F||{};let j=F.service;if(j&&typeof j=="string"){let M=n.get(j);if(M)return M}function N(M,ot){let Zi=Object.entries({...F,...ot}).filter(([ks,qt])=>qt!=null).map(([ks,qt])=>{let Vi=`${ks}=`;return qt instanceof Error?Vi+R(qt):typeof qt=="object"?Vi+JSON.stringify(qt):Vi+qt}).join(" "),xe=new Date,uh=xe.getTime()-A;return A=xe.getTime(),[utils.formatLogTime(xe),"+"+uh+"ms",Zi,M].filter(Boolean).join(" ")+`
7
- `}let B={debug(M,ot){s("DEBUG")&&w("DEBUG "+N(M,ot));},info(M,ot){s("INFO")&&w("INFO "+N(M,ot));},error(M,ot){s("ERROR")&&w("ERROR "+N(M,ot));},warn(M,ot){s("WARN")&&w("WARN "+N(M,ot));},tag(M,ot){return F&&(F[M]=ot),B},clone(){return L.create({...F})},time(M,ot){let Zi=Date.now();B.info(M,{status:"started",...ot});function xe(){B.info(M,{status:"completed",duration:Date.now()-Zi,...ot});}return {stop:xe,[Symbol.dispose](){xe();}}}};return j&&typeof j=="string"&&n.set(j,B),B}L.create=T;})(exports.b||(exports.b={}));exports.a=p;