@decocms/mesh 2.21.0 → 2.22.0

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.
@@ -1054,7 +1054,7 @@ data:
1054
1054
  `;if(J)G+=`id: ${J}
1055
1055
  `;return G+=`data: ${JSON.stringify(Q)}
1056
1056
 
1057
- `,X.enqueue(Y.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(X,Y){try{let Q=X.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=X.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(X.headers.entries())},W;if(Y?.parsedBody!==void 0)W=Y.parsedBody;else try{W=await X.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let Z;try{if(Array.isArray(W))Z=W.map((L)=>YJ.parse(L));else Z=[YJ.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(L10);if($){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(Z.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!$){let L=this.validateSession(X);if(L)return L;let w=this.validateProtocolVersion(X);if(w)return w}if(!Z.some(T7)){for(let L of Z)this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=Z.find((L)=>L10(L)),V=F?F.params.protocolVersion:X.headers.get("mcp-protocol-version")??J46;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let w of Z)if(T7(w))this._requestToStreamMapping.set(w.id,H);for(let w of Z)this.onmessage?.(w,{authInfo:Y?.authInfo,requestInfo:G})});let q=new TextEncoder,z,D=new ReadableStream({start:(L)=>{z=L},cancel:()=>{this._streamMapping.delete(H)}}),N={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)N["mcp-session-id"]=this.sessionId;for(let L of Z)if(T7(L))this._streamMapping.set(H,{controller:z,encoder:q,cleanup:()=>{this._streamMapping.delete(H);try{z.close()}catch{}}}),this._requestToStreamMapping.set(L.id,H);await this.writePrimingEvent(z,q,H,V);for(let L of Z){let w,C;if(T7(L)&&this._eventStore&&V>="2025-11-25")w=()=>{this.closeSSEStream(L.id)},C=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:C})}return new Response(D,{status:200,headers:N})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(X){let Y=this.validateSession(X);if(Y)return Y;let Q=this.validateProtocolVersion(X);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(X){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Y=X.headers.get("mcp-session-id");if(!Y)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Y!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(X){let Y=X.headers.get("mcp-protocol-version");if(Y!==null&&!OF.includes(Y))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Y} (supported versions: ${OF.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:X})=>{X()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(X){let Y=this._requestToStreamMapping.get(X);if(!Y)return;let Q=this._streamMapping.get(Y);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let X=this._streamMapping.get(this._standaloneSseStreamId);if(X)X.cleanup()}async send(X,Y){let Q=Y?.relatedRequestId;if(m5(X)||uU(X))Q=X.id;if(Q===void 0){if(m5(X)||uU(X))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let W;if(this._eventStore)W=await this._eventStore.storeEvent(this._standaloneSseStreamId,X);let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z===void 0)return;if(Z.controller&&Z.encoder)this.writeSSEEvent(Z.controller,Z.encoder,X,W);return}let J=this._requestToStreamMapping.get(Q);if(!J)throw Error(`No connection established for request ID: ${String(Q)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let W;if(this._eventStore)W=await this._eventStore.storeEvent(J,X);this.writeSSEEvent(G.controller,G.encoder,X,W)}if(m5(X)||uU(X)){this._requestResponseMap.set(Q,X);let W=Array.from(this._requestToStreamMapping.entries()).filter(([$,K])=>K===J).map(([$])=>$);if(W.every(($)=>this._requestResponseMap.has($))){if(!G)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&G.resolveJson){let $={"Content-Type":"application/json"};if(this.sessionId!==void 0)$["mcp-session-id"]=this.sessionId;let K=W.map((H)=>this._requestResponseMap.get(H));if(K.length===1)G.resolveJson(new Response(JSON.stringify(K[0]),{status:200,headers:$}));else G.resolveJson(new Response(JSON.stringify(K),{status:200,headers:$}))}else G.cleanup();for(let $ of W)this._requestResponseMap.delete($),this._requestToStreamMapping.delete($)}}}}var vb=v(()=>{E9()});var nP=(...X)=>{return function(Q,J){let G=(W)=>{let Z=X[W];if(!Z)return J();return Z(Q,()=>G(W+1))};return G(0)}};class Y56{config;tools=[];callToolMiddlewares=[];constructor(X){this.config={...X,capabilities:X.capabilities??{tools:{}}}}withTool(X){return this.tools.push(X),this}withTools(X){return this.tools.push(...X),this}callToolMiddleware(...X){return this.callToolMiddlewares.push(...X),this}build(){let X=this.callToolMiddlewares.length>0?nP(...this.callToolMiddlewares):null,Y=()=>{let Q=new IF({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(K)=>{try{let H=await J.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},W=X?async(K)=>{let H={method:"tools/call",params:{name:J.name,arguments:K}};return await X(H,()=>G(K))}:G,Z="shape"in J.inputSchema?J.inputSchema.shape:U.object({}).shape,$=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:U.object({}).shape;Q.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:Z,outputSchema:$},W)}return Q};return{callStreamableTool:async(Q,J)=>{let G=this.tools.find((Z)=>Z.name===Q);if(!G)throw Error(`Tool ${Q} not found`);let W=await G.handler(J);if(!(W instanceof Response))throw Error(`Tool ${Q} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((Q)=>({name:Q.name,description:Q.description??"",inputSchema:U.toJSONSchema(Q.inputSchema),outputSchema:Q.outputSchema?U.toJSONSchema(Q.outputSchema):void 0}))}},callTool:async(Q)=>{let J=this.tools.find((G)=>G.name===Q.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Q.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Q)=>{let J=new RF({enableJsonResponse:Q.headers.get("Accept")?.includes("application/json")??!1});return await Y().connect(J),await J.handleRequest(Q)}}}}function Q56(X){return new Y56(X)}var J56=v(()=>{kb();vb();X6()});function s0(X){return{...X,execute:async(Y,Q)=>{let J=Date.now();return await Q.timings.measure(`tool.${X.name}`,async()=>Q.tracer.startActiveSpan(`tool.${X.name}`,{attributes:{"tool.name":X.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Q.toolName=X.name,Q.access.setToolName?.(X.name);let W=await X.handler(Y,Q),Z=Date.now()-J;return Q.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(Z,{"tool.name":X.name,"organization.id":Q.organization?.id??"system",status:"success"}),Q.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":X.name,status:"success"}),G.setStatus({code:q90.SpanStatusCode.OK}),W}catch(W){throw Q.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":X.name,"error.type":W.constructor.name}),G.setStatus({code:q90.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}}))}}}var q90;var W1=v(()=>{q90=b1($6(),1)});function I6(X){if(!X.organization)throw Error("This operation requires organization scope");return X.organization}function g8(X){return X.auth.user?.id??X.auth.apiKey?.userId}function ny1(X){return!!(X.auth.user||X.auth.apiKey)}function q6(X){if(!ny1(X))throw Error("Authentication required")}var _b,G56,W56,Z56,$56,K56,H56,F56,V56,q56;var DB=v(()=>{X6();_b=U.record(U.string(),U.array(U.string())),G56=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),userId:U.string().describe("ID of the user who owns this API key"),permissions:_b.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),W56=U.object({name:U.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:_b.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:U.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:U.record(U.string(),U.unknown()).optional().describe("Additional metadata to store with the API key")}),Z56=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),key:U.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:_b.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),$56=U.object({}),K56=U.object({items:U.array(G56).describe("List of API keys (without key values)")}),H56=U.object({keyId:U.string().describe("ID of the API key to update"),name:U.string().min(1).max(64).optional().describe("New name for the API key"),permissions:_b.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:U.record(U.string(),U.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),F56=U.object({item:G56.describe("The updated API key (without key value)")}),V56=U.object({keyId:U.string().describe("ID of the API key to delete")}),q56=U.object({success:U.boolean().describe("Whether the deletion was successful"),keyId:U.string().describe("ID of the deleted API key")})});var z90;var z56=v(()=>{W1();DB();z90=s0({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:W56,outputSchema:Z56,handler:async(X,Y)=>{q6(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.create({name:X.name,permissions:X.permissions,expiresIn:X.expiresIn,metadata:{...X.metadata,organization:Y.organization}}),J=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,G=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt;return{id:Q.id,name:Q.name??X.name,key:Q.key,permissions:Q.permissions??{},expiresAt:J,createdAt:G}}})});var U90;var U56=v(()=>{W1();DB();U90=s0({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:V56,outputSchema:q56,handler:async(X,Y)=>{if(q6(Y),await Y.access.check(),!g8(Y))throw Error("User ID required to delete API key");let G=(await Y.boundAuth.apiKey.list())?.find((K)=>K.id===X.keyId);if(!G)throw Error("API key not found");let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot delete API key from another organization");return await Y.boundAuth.apiKey.delete(X.keyId),{success:!0,keyId:X.keyId}}})});var B90;var B56=v(()=>{W1();DB();B90=s0({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:$56,outputSchema:K56,handler:async(X,Y)=>{q6(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.list(),J=Y.organization?.id;return{items:(Q??[]).filter((W)=>{return W.metadata?.organization?.id===J}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt?W.expiresAt instanceof Date?W.expiresAt.toISOString():W.expiresAt:null,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var D90;var D56=v(()=>{W1();DB();D90=s0({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:H56,outputSchema:F56,handler:async(X,Y)=>{if(q6(Y),await Y.access.check(),!g8(Y))throw Error("User ID required to update API key");let G=(await Y.boundAuth.apiKey.list())?.find((H)=>H.id===X.keyId);if(!G)throw Error(`API key not found: ${X.keyId}`);let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot update API key from another organization");let K=await Y.boundAuth.apiKey.update({keyId:X.keyId,name:X.name,permissions:X.permissions,metadata:{...X.metadata,organization:Y.organization}});if(!K)throw Error(`Failed to update API key: ${X.keyId}`);return{item:{id:K.id,name:K.name??X.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var N56=v(()=>{z56();U56();B56();D56();DB()});var O56,L56,w56,M56,P56,T56;var iP=v(()=>{X6();O56=U.object({query:U.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:U.number().default(10).describe("Maximum results to return (default: 10)")}),L56=U.object({query:U.string(),results:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string()})),totalAvailable:U.number()}),w56=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),M56=U.object({tools:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string(),inputSchema:U.unknown(),outputSchema:U.unknown().optional()})),notFound:U.array(U.string())}),P56=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),T56=U.object({returnValue:U.unknown().optional(),error:U.string().optional(),consoleLogs:U.array(U.object({type:U.enum(["log","warn","error"]),content:U.string()}))})});class SF{proxies=new Map;constructor(){}static async create(X,Y){let Q=new SF,J=await Promise.allSettled(X.map(async({connection:G,selectedTools:W,selectedResources:Z,selectedPrompts:$})=>{try{let K=await Y.createMCPProxy(G);return{connection:G,proxy:K,selectedTools:W,selectedResources:Z,selectedPrompts:$}}catch(K){return console.error(`[aggregator] Failed to create proxy for connection ${G.id}:`,K),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Q.proxies.set(G.value.connection.id,G.value);return Q}get(X){return this.proxies.get(X)}entries(){return this.proxies.entries()}forEach(X){this.proxies.forEach((Y,Q)=>X(Y,Q))}async mapAsync(X){let Y=[];for(let[Q,J]of this.proxies.entries())Y.push(X(J,Q));return await Promise.all(Y)}async mapSettled(X){return Promise.allSettled(Array.from(this.proxies.entries()).map(([Y,Q])=>X(Q,Y)))}get size(){return this.proxies.size}}function A56(X){let Y=[],Q=[],J=(K)=>{let H=X.newFunction(K,(...F)=>{try{let V=F.map((q)=>X.dump(q));Y.push({type:K??"log",content:V.map(String).join(" ")})}finally{F.forEach((V)=>V.dispose())}return X.undefined});return Q.push(H),H},G=X.newObject();Q.push(G);let W=J("log"),Z=J("warn"),$=J("error");return X.setProp(G,"log",W),X.setProp(G,"warn",Z),X.setProp(G,"error",$),X.setProp(X.global,"console",G),{logs:Y,[Symbol.dispose](){Q.forEach((K)=>K.dispose())}}}var kF,N90,yb,vF,aP;var bb=v(()=>{kF={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},N90={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},yb={Pending:0,Fulfilled:1,Rejected:2},vF={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},aP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function NB(...X){T90&&console.log("quickjs-emscripten:",...X)}function*h56(X){return yield X}function oy1(X){return h56(E90(X))}function E56(X,Y){return(...Q)=>{let J=Y.call(X,A90,...Q);return E90(J)}}function sy1(X,Y){let Q=Y.call(X,A90);return E90(Q)}function E90(X){function Y(Q){return Q.done?Q.value:Q.value instanceof Promise?Q.value.then((J)=>Y(X.next(J)),(J)=>Y(X.throw(J))):Y(X.next(Q.value))}return Y(X.next())}function O90(X,Y){let Q;try{X.dispose()}catch(J){Q=J}if(Y&&Q)throw Object.assign(Y,{message:`${Y.message}
1057
+ `,X.enqueue(Y.encode(G)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(X,Y){try{let Q=X.headers.get("accept");if(!Q?.includes("application/json")||!Q.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let J=X.headers.get("content-type");if(!J||!J.includes("application/json"))return this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let G={headers:Object.fromEntries(X.headers.entries())},W;if(Y?.parsedBody!==void 0)W=Y.parsedBody;else try{W=await X.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let Z;try{if(Array.isArray(W))Z=W.map((L)=>YJ.parse(L));else Z=[YJ.parse(W)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let $=Z.some(L10);if($){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(Z.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!$){let L=this.validateSession(X);if(L)return L;let w=this.validateProtocolVersion(X);if(w)return w}if(!Z.some(T7)){for(let L of Z)this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G});return new Response(null,{status:202})}let H=crypto.randomUUID(),F=Z.find((L)=>L10(L)),V=F?F.params.protocolVersion:X.headers.get("mcp-protocol-version")??J46;if(this._enableJsonResponse)return new Promise((L)=>{this._streamMapping.set(H,{resolveJson:L,cleanup:()=>{this._streamMapping.delete(H)}});for(let w of Z)if(T7(w))this._requestToStreamMapping.set(w.id,H);for(let w of Z)this.onmessage?.(w,{authInfo:Y?.authInfo,requestInfo:G})});let q=new TextEncoder,z,D=new ReadableStream({start:(L)=>{z=L},cancel:()=>{this._streamMapping.delete(H)}}),N={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)N["mcp-session-id"]=this.sessionId;for(let L of Z)if(T7(L))this._streamMapping.set(H,{controller:z,encoder:q,cleanup:()=>{this._streamMapping.delete(H);try{z.close()}catch{}}}),this._requestToStreamMapping.set(L.id,H);await this.writePrimingEvent(z,q,H,V);for(let L of Z){let w,C;if(T7(L)&&this._eventStore&&V>="2025-11-25")w=()=>{this.closeSSEStream(L.id)},C=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(L,{authInfo:Y?.authInfo,requestInfo:G,closeSSEStream:w,closeStandaloneSSEStream:C})}return new Response(D,{status:200,headers:N})}catch(Q){return this.onerror?.(Q),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(Q)})}}async handleDeleteRequest(X){let Y=this.validateSession(X);if(Y)return Y;let Q=this.validateProtocolVersion(X);if(Q)return Q;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(X){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let Y=X.headers.get("mcp-session-id");if(!Y)return this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(Y!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(X){let Y=X.headers.get("mcp-protocol-version");if(Y!==null&&!OF.includes(Y))return this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${Y} (supported versions: ${OF.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:X})=>{X()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(X){let Y=this._requestToStreamMapping.get(X);if(!Y)return;let Q=this._streamMapping.get(Y);if(Q)Q.cleanup()}closeStandaloneSSEStream(){let X=this._streamMapping.get(this._standaloneSseStreamId);if(X)X.cleanup()}async send(X,Y){let Q=Y?.relatedRequestId;if(m5(X)||uU(X))Q=X.id;if(Q===void 0){if(m5(X)||uU(X))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let W;if(this._eventStore)W=await this._eventStore.storeEvent(this._standaloneSseStreamId,X);let Z=this._streamMapping.get(this._standaloneSseStreamId);if(Z===void 0)return;if(Z.controller&&Z.encoder)this.writeSSEEvent(Z.controller,Z.encoder,X,W);return}let J=this._requestToStreamMapping.get(Q);if(!J)throw Error(`No connection established for request ID: ${String(Q)}`);let G=this._streamMapping.get(J);if(!this._enableJsonResponse&&G?.controller&&G?.encoder){let W;if(this._eventStore)W=await this._eventStore.storeEvent(J,X);this.writeSSEEvent(G.controller,G.encoder,X,W)}if(m5(X)||uU(X)){this._requestResponseMap.set(Q,X);let W=Array.from(this._requestToStreamMapping.entries()).filter(([$,K])=>K===J).map(([$])=>$);if(W.every(($)=>this._requestResponseMap.has($))){if(!G)throw Error(`No connection established for request ID: ${String(Q)}`);if(this._enableJsonResponse&&G.resolveJson){let $={"Content-Type":"application/json"};if(this.sessionId!==void 0)$["mcp-session-id"]=this.sessionId;let K=W.map((H)=>this._requestResponseMap.get(H));if(K.length===1)G.resolveJson(new Response(JSON.stringify(K[0]),{status:200,headers:$}));else G.resolveJson(new Response(JSON.stringify(K),{status:200,headers:$}))}else G.cleanup();for(let $ of W)this._requestResponseMap.delete($),this._requestToStreamMapping.delete($)}}}}var vb=v(()=>{E9()});var nP=(...X)=>{return function(Q,J){let G=(W)=>{let Z=X[W];if(!Z)return J();return Z(Q,()=>G(W+1))};return G(0)}};class Y56{config;tools=[];callToolMiddlewares=[];constructor(X){this.config={...X,capabilities:X.capabilities??{tools:{}}}}withTool(X){return this.tools.push(X),this}withTools(X){return this.tools.push(...X),this}callToolMiddleware(...X){return this.callToolMiddlewares.push(...X),this}build(){let X=this.callToolMiddlewares.length>0?nP(...this.callToolMiddlewares):null,Y=()=>{let Q=new IF({name:this.config.name,version:this.config.version},{capabilities:this.config.capabilities});for(let J of this.tools){let G=async(K)=>{try{let H=await J.handler(K);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}},W=X?async(K)=>{let H={method:"tools/call",params:{name:J.name,arguments:K}};return await X(H,()=>G(K))}:G,Z="shape"in J.inputSchema?J.inputSchema.shape:U.object({}).shape,$=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:U.object({}).shape;Q.registerTool(J.name,{annotations:J.annotations,description:J.description??"",inputSchema:Z,outputSchema:$},W)}return Q};return{callStreamableTool:async(Q,J)=>{let G=this.tools.find((Z)=>Z.name===Q);if(!G)throw Error(`Tool ${Q} not found`);let W=await G.handler(J);if(!(W instanceof Response))throw Error(`Tool ${Q} returned a non-response`);return W},client:{listTools:async()=>{return{tools:this.tools.map((Q)=>({name:Q.name,description:Q.description??"",inputSchema:U.toJSONSchema(Q.inputSchema),outputSchema:Q.outputSchema?U.toJSONSchema(Q.outputSchema):void 0}))}},callTool:async(Q)=>{let J=this.tools.find((G)=>G.name===Q.name);if(!J)return{content:[{type:"text",text:"Tool not found"}]};try{let G=await J?.handler(Q.arguments??{});return{content:[{type:"text",text:JSON.stringify(G)}],structuredContent:G}}catch(G){return{content:[{type:"text",text:`Error: ${G.message}`}]}}}},fetch:async(Q)=>{let J=new RF({enableJsonResponse:Q.headers.get("Accept")?.includes("application/json")??!1});await Y().connect(J);try{return await J.handleRequest(Q)}finally{try{await J.close?.()}catch{}}}}}}function Q56(X){return new Y56(X)}var J56=v(()=>{kb();vb();X6()});function s0(X){return{...X,execute:async(Y,Q)=>{let J=Date.now();return await Q.timings.measure(`tool.${X.name}`,async()=>Q.tracer.startActiveSpan(`tool.${X.name}`,{attributes:{"tool.name":X.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(G)=>{try{Q.toolName=X.name,Q.access.setToolName?.(X.name);let W=await X.handler(Y,Q),Z=Date.now()-J;return Q.meter.createHistogram("tool.execution.duration",{description:"Duration of tool executions in milliseconds",unit:"ms"}).record(Z,{"tool.name":X.name,"organization.id":Q.organization?.id??"system",status:"success"}),Q.meter.createCounter("tool.execution.count",{description:"Number of tool executions"}).add(1,{"tool.name":X.name,status:"success"}),G.setStatus({code:q90.SpanStatusCode.OK}),W}catch(W){throw Q.meter.createCounter("tool.execution.errors",{description:"Number of tool execution errors"}).add(1,{"tool.name":X.name,"error.type":W.constructor.name}),G.setStatus({code:q90.SpanStatusCode.ERROR,message:W.message}),G.recordException(W),W}finally{G.end()}}))}}}var q90;var W1=v(()=>{q90=b1($6(),1)});function I6(X){if(!X.organization)throw Error("This operation requires organization scope");return X.organization}function g8(X){return X.auth.user?.id??X.auth.apiKey?.userId}function ny1(X){return!!(X.auth.user||X.auth.apiKey)}function q6(X){if(!ny1(X))throw Error("Authentication required")}var _b,G56,W56,Z56,$56,K56,H56,F56,V56,q56;var DB=v(()=>{X6();_b=U.record(U.string(),U.array(U.string())),G56=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),userId:U.string().describe("ID of the user who owns this API key"),permissions:_b.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),W56=U.object({name:U.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:_b.optional().describe('Permissions to grant. Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["API_KEY_CREATE"]) or ["*"] for all. Example: { "self": ["API_KEY_CREATE", "COLLECTION_CONNECTIONS_LIST"] }. Defaults to read-only permissions.'),expiresIn:U.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:U.record(U.string(),U.unknown()).optional().describe("Additional metadata to store with the API key")}),Z56=U.object({id:U.string().describe("Unique identifier for the API key"),name:U.string().describe("Human-readable name for the API key"),key:U.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:_b.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:U.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:U.string().datetime().describe("When the API key was created (ISO 8601)")}),$56=U.object({}),K56=U.object({items:U.array(G56).describe("List of API keys (without key values)")}),H56=U.object({keyId:U.string().describe("ID of the API key to update"),name:U.string().min(1).max(64).optional().describe("New name for the API key"),permissions:_b.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:U.record(U.string(),U.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),F56=U.object({item:G56.describe("The updated API key (without key value)")}),V56=U.object({keyId:U.string().describe("ID of the API key to delete")}),q56=U.object({success:U.boolean().describe("Whether the deletion was successful"),keyId:U.string().describe("ID of the deleted API key")})});var z90;var z56=v(()=>{W1();DB();z90=s0({name:"API_KEY_CREATE",description:"Create a new API key with specified permissions. The key value is only returned once - store it securely!",inputSchema:W56,outputSchema:Z56,handler:async(X,Y)=>{q6(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.create({name:X.name,permissions:X.permissions,expiresIn:X.expiresIn,metadata:{...X.metadata,organization:Y.organization}}),J=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,G=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt;return{id:Q.id,name:Q.name??X.name,key:Q.key,permissions:Q.permissions??{},expiresAt:J,createdAt:G}}})});var U90;var U56=v(()=>{W1();DB();U90=s0({name:"API_KEY_DELETE",description:"Delete an API key. This instantly revokes the key - it can no longer be used for authentication.",inputSchema:V56,outputSchema:q56,handler:async(X,Y)=>{if(q6(Y),await Y.access.check(),!g8(Y))throw Error("User ID required to delete API key");let G=(await Y.boundAuth.apiKey.list())?.find((K)=>K.id===X.keyId);if(!G)throw Error("API key not found");let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot delete API key from another organization");return await Y.boundAuth.apiKey.delete(X.keyId),{success:!0,keyId:X.keyId}}})});var B90;var B56=v(()=>{W1();DB();B90=s0({name:"API_KEY_LIST",description:"List all API keys for the current user in the current organization. Returns metadata only - key values are never shown after creation.",inputSchema:$56,outputSchema:K56,handler:async(X,Y)=>{q6(Y),await Y.access.check();let Q=await Y.boundAuth.apiKey.list(),J=Y.organization?.id;return{items:(Q??[]).filter((W)=>{return W.metadata?.organization?.id===J}).map((W)=>({id:W.id,name:W.name??"Unnamed Key",userId:W.userId,permissions:W.permissions??{},expiresAt:W.expiresAt?W.expiresAt instanceof Date?W.expiresAt.toISOString():W.expiresAt:null,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():W.createdAt}))}}})});var D90;var D56=v(()=>{W1();DB();D90=s0({name:"API_KEY_UPDATE",description:"Update an existing API key's name, permissions, or metadata. Note: Key value cannot be changed or retrieved.",inputSchema:H56,outputSchema:F56,handler:async(X,Y)=>{if(q6(Y),await Y.access.check(),!g8(Y))throw Error("User ID required to update API key");let G=(await Y.boundAuth.apiKey.list())?.find((H)=>H.id===X.keyId);if(!G)throw Error(`API key not found: ${X.keyId}`);let Z=G.metadata?.organization?.id,$=Y.organization?.id;if(Z!==$)throw Error("Cannot update API key from another organization");let K=await Y.boundAuth.apiKey.update({keyId:X.keyId,name:X.name,permissions:X.permissions,metadata:{...X.metadata,organization:Y.organization}});if(!K)throw Error(`Failed to update API key: ${X.keyId}`);return{item:{id:K.id,name:K.name??X.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var N56=v(()=>{z56();U56();B56();D56();DB()});var O56,L56,w56,M56,P56,T56;var iP=v(()=>{X6();O56=U.object({query:U.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:U.number().default(10).describe("Maximum results to return (default: 10)")}),L56=U.object({query:U.string(),results:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string()})),totalAvailable:U.number()}),w56=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),M56=U.object({tools:U.array(U.object({name:U.string(),description:U.string().optional(),connection:U.string(),inputSchema:U.unknown(),outputSchema:U.unknown().optional()})),notFound:U.array(U.string())}),P56=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),T56=U.object({returnValue:U.unknown().optional(),error:U.string().optional(),consoleLogs:U.array(U.object({type:U.enum(["log","warn","error"]),content:U.string()}))})});class SF{proxies=new Map;constructor(){}static async create(X,Y){let Q=new SF,J=await Promise.allSettled(X.map(async({connection:G,selectedTools:W,selectedResources:Z,selectedPrompts:$})=>{try{let K=await Y.createMCPProxy(G);return{connection:G,proxy:K,selectedTools:W,selectedResources:Z,selectedPrompts:$}}catch(K){return console.error(`[aggregator] Failed to create proxy for connection ${G.id}:`,K),null}}));for(let G of J)if(G.status==="fulfilled"&&G.value)Q.proxies.set(G.value.connection.id,G.value);return Q}get(X){return this.proxies.get(X)}entries(){return this.proxies.entries()}forEach(X){this.proxies.forEach((Y,Q)=>X(Y,Q))}async mapAsync(X){let Y=[];for(let[Q,J]of this.proxies.entries())Y.push(X(J,Q));return await Promise.all(Y)}async mapSettled(X){return Promise.allSettled(Array.from(this.proxies.entries()).map(([Y,Q])=>X(Q,Y)))}get size(){return this.proxies.size}}function A56(X){let Y=[],Q=[],J=(K)=>{let H=X.newFunction(K,(...F)=>{try{let V=F.map((q)=>X.dump(q));Y.push({type:K??"log",content:V.map(String).join(" ")})}finally{F.forEach((V)=>V.dispose())}return X.undefined});return Q.push(H),H},G=X.newObject();Q.push(G);let W=J("log"),Z=J("warn"),$=J("error");return X.setProp(G,"log",W),X.setProp(G,"warn",Z),X.setProp(G,"error",$),X.setProp(X.global,"console",G),{logs:Y,[Symbol.dispose](){Q.forEach((K)=>K.dispose())}}}var kF,N90,yb,vF,aP;var bb=v(()=>{kF={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},N90={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},yb={Pending:0,Fulfilled:1,Rejected:2},vF={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},aP={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2}});function NB(...X){T90&&console.log("quickjs-emscripten:",...X)}function*h56(X){return yield X}function oy1(X){return h56(E90(X))}function E56(X,Y){return(...Q)=>{let J=Y.call(X,A90,...Q);return E90(J)}}function sy1(X,Y){let Q=Y.call(X,A90);return E90(Q)}function E90(X){function Y(Q){return Q.done?Q.value:Q.value instanceof Promise?Q.value.then((J)=>Y(X.next(J)),(J)=>Y(X.throw(J))):Y(X.next(Q.value))}return Y(X.next())}function O90(X,Y){let Q;try{X.dispose()}catch(J){Q=J}if(Y&&Q)throw Object.assign(Y,{message:`${Y.message}
1058
1058
  Then, failed to dispose scope: ${Q.message}`,disposeError:Q}),Y;if(Y||Q)throw Y||Q}function x56(X){let Y=X?Array.from(X):[];function Q(){return Y.forEach((G)=>G.alive?G.dispose():void 0)}function J(){return Y.some((G)=>G.alive)}return Object.defineProperty(Y,M90,{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(Y,"dispose",{configurable:!0,enumerable:!1,value:Q}),Object.defineProperty(Y,"alive",{configurable:!0,enumerable:!1,get:J}),Y}function fb(X){return!!(X&&(typeof X=="object"||typeof X=="function")&&("alive"in X)&&typeof X.alive=="boolean"&&("dispose"in X)&&typeof X.dispose=="function")}function ty1(X){if(!X)return 0;let Y=0;for(let[Q,J]of Object.entries(X)){if(!(Q in N90))throw new y56(Q);J&&(Y|=N90[Q])}return Y}function ey1(X){if(typeof X=="number")return X;if(X===void 0)return 0;let{type:Y,strict:Q,strip:J,compileOnly:G,backtraceBarrier:W}=X,Z=0;return Y==="global"&&(Z|=kF.JS_EVAL_TYPE_GLOBAL),Y==="module"&&(Z|=kF.JS_EVAL_TYPE_MODULE),Q&&(Z|=kF.JS_EVAL_FLAG_STRICT),J&&(Z|=kF.JS_EVAL_FLAG_STRIP),G&&(Z|=kF.JS_EVAL_FLAG_COMPILE_ONLY),W&&(Z|=kF.JS_EVAL_FLAG_BACKTRACE_BARRIER),Z}function Xb1(X){if(typeof X=="number")return X;if(X===void 0)return 0;let{strings:Y,symbols:Q,quickjsPrivate:J,onlyEnumerable:G,numbers:W,numbersAsStrings:Z}=X,$=0;return Y&&($|=vF.JS_GPN_STRING_MASK),Q&&($|=vF.JS_GPN_SYMBOL_MASK),J&&($|=vF.JS_GPN_PRIVATE_MASK),G&&($|=vF.JS_GPN_ENUM_ONLY),W&&($|=vF.QTS_GPN_NUMBER_MASK),Z&&($|=vF.QTS_STANDARD_COMPLIANT_NUMBER),$}function Yb1(...X){let Y=[];for(let Q of X)Q!==void 0&&(Y=Y.concat(Q));return Y}function R90(X,Y){Y.interruptHandler&&X.setInterruptHandler(Y.interruptHandler),Y.maxStackSizeBytes!==void 0&&X.setMaxStackSize(Y.maxStackSizeBytes),Y.memoryLimitBytes!==void 0&&X.setMemoryLimit(Y.memoryLimitBytes)}function S90(X,Y){Y.moduleLoader&&X.setModuleLoader(Y.moduleLoader),Y.shouldInterrupt&&X.setInterruptHandler(Y.shouldInterrupt),Y.memoryLimitBytes!==void 0&&X.setMemoryLimit(Y.memoryLimitBytes),Y.maxStackSizeBytes!==void 0&&X.setMaxStackSize(Y.maxStackSizeBytes)}var ay1,ry1=(X,Y)=>{for(var Q in Y)ay1(X,Q,{get:Y[Q],enumerable:!0})},T90=!1,C56,L90,I56,w90,R56,S56,k56,v56,_56,y56,b56,f56,A90,FZ,M90,j56,QY,jK,P90,s5,j90,g56,u56,_F,m56,l56=class{constructor(X){this.module=X}toPointerArray(X){let Y=new Int32Array(X.map((G)=>G.value)),Q=Y.length*Y.BYTES_PER_ELEMENT,J=this.module._malloc(Q);return new Uint8Array(this.module.HEAPU8.buffer,J,Q).set(new Uint8Array(Y.buffer)),new QY(J,void 0,(G)=>this.module._free(G))}newTypedArray(X,Y){let Q=new X(Array(Y).fill(0)),J=Q.length*Q.BYTES_PER_ELEMENT,G=this.module._malloc(J),W=new X(this.module.HEAPU8.buffer,G,Y);return W.set(Q),new QY({typedArray:W,ptr:G},void 0,(Z)=>this.module._free(Z.ptr))}newMutablePointerArray(X){return this.newTypedArray(Int32Array,X)}newHeapCharPointer(X){let Y=this.module.lengthBytesUTF8(X),Q=Y+1,J=this.module._malloc(Q);return this.module.stringToUTF8(X,J,Q),new QY({ptr:J,strlen:Y},void 0,(G)=>this.module._free(G.ptr))}newHeapBufferPointer(X){let Y=X.byteLength,Q=this.module._malloc(Y);return this.module.HEAPU8.set(X,Q),new QY({pointer:Q,numBytes:Y},void 0,(J)=>this.module._free(J.pointer))}consumeHeapCharPointer(X){let Y=this.module.UTF8ToString(X);return this.module._free(X),Y}},zg4,C90,Qb1,Jb1,d56,p56,Gb1=class{constructor(X){this.callFunction=X.callFunction,this.shouldInterrupt=X.shouldInterrupt,this.loadModuleSource=X.loadModuleSource,this.normalizeModule=X.normalizeModule}},I90=class{constructor(X){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new Gb1({callFunction:(Y,Q,J,G,W,Z)=>this.handleAsyncify(Y,()=>{try{let $=this.contextCallbacks.get(Q);if(!$)throw Error(`QuickJSContext(ctx = ${Q}) not found for C function call "${Z}"`);return $.callFunction(Q,J,G,W,Z)}catch($){return console.error("[C to host error: returning null]",$),0}}),shouldInterrupt:(Y,Q)=>this.handleAsyncify(Y,()=>{try{let J=this.runtimeCallbacks.get(Q);if(!J)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C interrupt`);return J.shouldInterrupt(Q)}catch(J){return console.error("[C to host interrupt: returning error]",J),1}}),loadModuleSource:(Y,Q,J,G)=>this.handleAsyncify(Y,()=>{try{let W=this.runtimeCallbacks.get(Q);if(!W)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let Z=W.loadModuleSource;if(!Z)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return Z(Q,J,G)}catch(W){return console.error("[C to host module loader error: returning null]",W),0}}),normalizeModule:(Y,Q,J,G,W)=>this.handleAsyncify(Y,()=>{try{let Z=this.runtimeCallbacks.get(Q);if(!Z)throw Error(`QuickJSRuntime(rt = ${Q}) not found for C module loader`);let $=Z.normalizeModule;if(!$)throw Error(`QuickJSRuntime(rt = ${Q}) does not support module loading`);return $(Q,J,G,W)}catch(Z){return console.error("[C to host module loader error: returning null]",Z),0}})}),this.module=X,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(X,Y){this.runtimeCallbacks.set(X,Y)}deleteRuntime(X){this.runtimeCallbacks.delete(X)}setContextCallbacks(X,Y){this.contextCallbacks.set(X,Y)}deleteContext(X){this.contextCallbacks.delete(X)}handleAsyncify(X,Y){if(X)return X.handleSleep((J)=>{try{let G=Y();if(!(G instanceof Promise)){NB("asyncify.handleSleep: not suspending:",G),J(G);return}if(this.suspended)throw new S56(`Already suspended at: ${this.suspended.stack}
1059
1059
  Attempted to suspend at:`);this.suspended=new k56(`(${this.suspendedCount++})`),NB("asyncify.handleSleep: suspending:",this.suspended),G.then((W)=>{this.suspended=void 0,NB("asyncify.handleSleep: resolved:",W),J(W)},(W)=>{NB("asyncify.handleSleep: rejected:",W),console.error("QuickJS: cannot handle error in suspended function",W),this.suspended=void 0})}catch(G){throw NB("asyncify.handleSleep: error:",G),this.suspended=void 0,G}});let Q=Y();if(Q instanceof Promise)throw Error("Promise return value not supported in non-asyncify context.");return Q}},k90=class{constructor(X,Y){this.module=X,this.ffi=Y,this.callbacks=new I90(X)}newRuntime(X={}){let Y=new QY(this.ffi.QTS_NewRuntime(),void 0,(J)=>{this.callbacks.deleteRuntime(J),this.ffi.QTS_FreeRuntime(J)}),Q=new p56({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:Y});return R90(Q,X),X.moduleLoader&&Q.setModuleLoader(X.moduleLoader),Q}newContext(X={}){let Y=this.newRuntime(),Q=Y.newContext({...X,ownedLifetimes:Yb1(Y,X.ownedLifetimes)});return Y.context=Q,Q}evalCode(X,Y={}){return s5.withScope((Q)=>{let J=Q.manage(this.newContext());S90(J.runtime,Y);let G=J.evalCode(X,"eval.js");if(Y.memoryLimitBytes!==void 0&&J.runtime.setMemoryLimit(-1),G.error)throw J.dump(Q.manage(G.error));return J.dump(Q.manage(G.value))})}getWasmMemory(){let X=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!X)throw Error("Variant does not support getting WebAssembly.Memory");return X}getFFI(){return this.ffi}};var v90=v(()=>{bb();bb();ay1=Object.defineProperty;C56={};ry1(C56,{QuickJSAsyncifyError:()=>S56,QuickJSAsyncifySuspended:()=>k56,QuickJSEmptyGetOwnPropertyNames:()=>f56,QuickJSEmscriptenModuleError:()=>_56,QuickJSMemoryLeakDetected:()=>v56,QuickJSNotImplemented:()=>R56,QuickJSPromisePending:()=>b56,QuickJSUnknownIntrinsic:()=>y56,QuickJSUnwrapError:()=>L90,QuickJSUseAfterFree:()=>w90,QuickJSWrongOwner:()=>I56});L90=class extends Error{constructor(X,Y){let Q=typeof X=="object"&&X&&"message"in X?String(X.message):String(X);super(Q);this.cause=X,this.context=Y,this.name="QuickJSUnwrapError"}},I56=class extends Error{constructor(){super(...arguments);this.name="QuickJSWrongOwner"}},w90=class extends Error{constructor(){super(...arguments);this.name="QuickJSUseAfterFree"}},R56=class extends Error{constructor(){super(...arguments);this.name="QuickJSNotImplemented"}},S56=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifyError"}},k56=class extends Error{constructor(){super(...arguments);this.name="QuickJSAsyncifySuspended"}},v56=class extends Error{constructor(){super(...arguments);this.name="QuickJSMemoryLeakDetected"}},_56=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmscriptenModuleError"}},y56=class extends TypeError{constructor(){super(...arguments);this.name="QuickJSUnknownIntrinsic"}},b56=class extends Error{constructor(){super(...arguments);this.name="QuickJSPromisePending"}},f56=class extends Error{constructor(){super(...arguments);this.name="QuickJSEmptyGetOwnPropertyNames"}};A90=h56;A90.of=oy1;FZ=class{[Symbol.dispose](){return this.dispose()}},M90=Symbol.dispose??Symbol.for("Symbol.dispose"),j56=FZ.prototype;j56[M90]||(j56[M90]=function(){return this.dispose()});QY=class X extends FZ{constructor(Y,Q,J,G){super();this._value=Y,this.copier=Q,this.disposer=J,this._owner=G,this._alive=!0,this._constructorStack=T90?Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw Error("Non-dupable lifetime");return new X(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(Y){this.assertAlive();let Q=Y(this);return this.dispose(),Q}map(Y){return this.assertAlive(),Y(this)}tap(Y){return Y(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new w90(`Lifetime not alive
1060
1060
  ${this._constructorStack}
@@ -1070,7 +1070,7 @@ ${Y.stack}`;return G}}catch{}if(typeof Y.toString==="function")try{let G=Y.toStr
1070
1070
  <h2>You've been invited!</h2>
1071
1071
  <p>${J} has invited you to join <strong>${Q.organization.name}</strong>.</p>
1072
1072
  <p><a href="${G}">Click here to accept the invitation</a></p>
1073
- `})}}}ih1=[bi({organizationCreation:{afterCreate:async(X)=>{await s76(X.organization.id,X.member.userId)}},ac:sb,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:e76,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:ph1,admin:ch1,owner:nh1},sendInvitationEmail:GW6}),Qa({loginPage:"/login",oidcConfig:{scopes:JW6,metadata:{scopes_supported:JW6},loginPage:"/login"}}),Ya({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(X)=>{if(X.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=X.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),li({defaultRole:"user",adminRoles:["admin","owner"]}),Za(),ci({jwt:{expirationTime:"5m"}}),uU0(X9.ssoConfig?XW6(X9.ssoConfig):void 0),...X9.magicLinkConfig&&X9.emailProviders&&X9.emailProviders.length>0?[Wa(L16(X9.magicLinkConfig,X9.emailProviders))]:[]],ah1=e60(),rh1=N16(ah1),e5=bn({baseURL:process.env.BASE_URL||"http://localhost:3000",database:rh1,emailAndPassword:{enabled:!0},...X9,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:ih1,databaseHooks:{user:{create:{after:async(X)=>{if(bL.autoCreateOrganizationOnSignup===!1)return;let Y=X.name?X.name.split(" ")[0]:X.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${Y} ${mh1()}`,W=uh1(G);try{await e5.api.createOrganization({body:{name:G,slug:W,userId:X.id}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",Z);return}}}}}}}})});async function WW6(){console.log("\uD83D\uDD10 Running Better Auth migrations...");try{let{toBeAdded:X,toBeCreated:Y,runMigrations:Q}=await iN(e5.options);if(!X.length&&!Y.length){console.log("\u2705 Better Auth schema is up to date (no migrations needed)");return}console.log("\uD83D\uDCCB Better Auth will create/update the following tables:");for(let J of[...Y,...X])console.log(` - ${J.table}`);await Q(),console.log("\u2705 Better Auth migrations completed successfully")}catch(X){console.warn("\u26A0\uFE0F Better Auth migration failed (tables may be created on first use):",X)}}var ZW6=v(()=>{OW0();EB()});var HW6={};$1(HW6,{runSeed:()=>Vh,runKyselyMigrations:()=>KW6,migrateToLatest:()=>oh1,migrateDown:()=>sh1});import{Migrator as $W6}from"kysely";async function KW6(X){let Y=new $W6({db:X,provider:{getMigrations:()=>Promise.resolve(nT)}}),{error:Q,results:J}=await Y.migrateToLatest();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" executed successfully`);else if(G.status==="Error")console.error(`\u274C Failed to execute migration "${G.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q}async function oh1(X){let{keepOpen:Y=!1,database:Q,skipBetterAuth:J=!1,seed:G}=X??{};if(!J&&!Q)await WW6();let W=Q??FF(),Z=async()=>{if(!Y&&!Q)console.log("\uD83D\uDD12 Closing database connection..."),await O16(W).catch(($)=>{console.warn("Warning: Error closing database:",$)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await KW6(W.db),console.log("\uD83C\uDF89 All Kysely migrations completed successfully");let $;if(G)$=await Vh(W.db,G);return await Z(),{seedResult:$}}catch($){throw await Z(),$}}async function sh1(){let X=FF(),Y=new $W6({db:X.db,provider:{getMigrations:()=>Promise.resolve(nT)}}),{error:Q,results:J}=await Y.migrateDown();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" rolled back successfully`);else if(G.status==="Error")console.error(`\u274C Failed to rollback migration "${G.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var FW6=v(()=>{Fh();_Q0();ZW6();hM()});var lX0;var dX0=v(()=>{lX0=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var VW6,th1,eh1=(X,Y)=>{if(!X)return{};let Q=new Headers(X.headers);if(Y){let J=Q.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!th1.test(Z));if(W.length>0)throw new lX0(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Q.delete(Z)})}}return VW6.forEach((J)=>{Q.delete(J)}),{method:X.method,body:X.body,duplex:X.body?"half":void 0,headers:Q,signal:X.signal}},Xx1=(X)=>{if(!X.headers||Array.isArray(X.headers)||X.headers instanceof Headers)return X;let Y=new Headers;for(let[Q,J]of Object.entries(X.headers))if(J==null)Y.delete(Q);else Y.set(Q,J);return X.headers=Y,X},qW6=async(X,Y)=>{let{raw:Q,customFetch:J,strictConnectionProcessing:G=!1,...W}=Y instanceof Request?{raw:Y}:Y??{},Z=new Request(X,{...eh1(Q,G),...Xx1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(VW6.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var zW6=v(()=>{dX0();VW6=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],th1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});var UW6=(X)=>(Y)=>{let Q=new URL(Y.req.raw.url),J=new URL(X);return J.pathname=Q.pathname,J.search=Q.search,qW6(J,{raw:Y.req.raw,headers:{...Y.req.raw.headers}})};var BW6=v(()=>{zW6()});import{resolve as OT,dirname as Yx1}from"path";function Gx1(X,Y){let Q=OT(Y),J=OT(X);return J===Q||J.startsWith(Q+"/")}function Wx1({requestPath:X,clientDir:Y}){let Q=X.startsWith("/")?X.slice(1):X,J=OT(Y,Q);if(!Gx1(J,Y))return null;return J}function DW6(X,Y="../client"){let Q=new URL(X),J=Yx1(Q.pathname);return OT(J,Y)}function NW6(X={}){let{env:Y="production",devServerUrl:Q=Qx1,clientDir:J=Jx1,isServerPath:G=()=>!1}=X;if(Y==="development"){let W=UW6(Q);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=Wx1({requestPath:K,clientDir:J});if(!H)return null;let F=OT(J,"index.html");for(let V of[H,F])try{let q=Bun.file(V);if(await q.exists())return new Response(q)}catch{}return null}}var Qx1="http://localhost:4000",Jx1="./dist/client";var OW6=v(()=>{BW6()});var pX0=(X,Y,Q)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(X[$])F=X[$][0][0],J.req.routeIndex=$;else F=$===X.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&Y)J.error=V,K=await Y(V,J),H=!0;else throw V}else if(J.finalized===!1&&Q)K=await Q(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var LW6=()=>{};var wW6;var MW6=v(()=>{wW6=Symbol()});async function Zx1(X,Y){let Q=await X.formData();if(Q)return $x1(Q,Y);return{}}function $x1(X,Y){let Q=Object.create(null);if(X.forEach((J,G)=>{if(!(Y.all||G.endsWith("[]")))Q[G]=J;else Kx1(Q,G,J)}),Y.dot)Object.entries(Q).forEach(([J,G])=>{if(J.includes("."))Hx1(Q,J,G),delete Q[J]});return Q}var PW6=async(X,Y=Object.create(null))=>{let{all:Q=!1,dot:J=!1}=Y,W=(X instanceof tb?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Zx1(X,{all:Q,dot:J});return{}},Kx1=(X,Y,Q)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(Q);else X[Y]=[X[Y],Q];else if(!Y.endsWith("[]"))X[Y]=Q;else X[Y]=[Q]},Hx1=(X,Y,Q)=>{let J=X,G=Y.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Q;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var TW6=v(()=>{cX0()});var iX0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},AW6=(X)=>{let{groups:Y,path:Q}=Fx1(X),J=iX0(Q);return Vx1(J,Y)},Fx1=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(Q,J)=>{let G=`@${J}`;return Y.push([G,Q]),G}),{groups:Y,path:X}},Vx1=(X,Y)=>{for(let Q=Y.length-1;Q>=0;Q--){let[J]=Y[Q];for(let G=X.length-1;G>=0;G--)if(X[G].includes(J)){X[G]=X[G].replace(J,Y[Q][1]);break}}return X},eb,EW6=(X,Y)=>{if(X==="*")return"*";let Q=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Q){let J=`${X}#${Y}`;if(!eb[J])if(Q[2])eb[J]=Y&&Y[0]!==":"&&Y[0]!=="*"?[J,Q[1],new RegExp(`^${Q[2]}(?=/${Y})`)]:[X,Q[1],new RegExp(`^${Q[2]}$`)];else eb[J]=[X,Q[1],!0];return eb[J]}return null},jB=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Q)=>{try{return Y(Q)}catch{return Q}})}},qx1=(X)=>jB(X,decodeURI),aX0=(X)=>{let Y=X.url,Q=Y.indexOf("/",Y.indexOf(":")+4),J=Q;for(;J<Y.length;J++){let G=Y.charCodeAt(J);if(G===37){let W=Y.indexOf("?",J),Z=Y.slice(Q,W===-1?void 0:W);return qx1(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return Y.slice(Q,J)},jW6=(X)=>{let Y=aX0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},xF=(X,Y,...Q)=>{if(Q.length)Y=xF(Y,...Q);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},Xf=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),Q=[],J="";return Y.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Q.length===0&&J==="")Q.push("/");else Q.push(J);let W=G.replace("?","");J+="/"+W,Q.push(J)}else J+="/"+G}),Q.filter((G,W,Z)=>Z.indexOf(G)===W)},nX0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?jB(X,LT):X},CW6=(X,Y,Q)=>{let J;if(!Q&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return nX0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(J=/[%+]/.test(X),!J)return}let G={};J??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=nX0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),J)H=nX0(H);if(Q){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return Y?G[Y]:G},IW6,RW6=(X,Y)=>{return CW6(X,Y,!0)},LT;var gF=v(()=>{eb={},IW6=CW6,LT=decodeURIComponent});var SW6=(X)=>jB(X,LT),tb;var cX0=v(()=>{dX0();MW6();TW6();gF();tb=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",Q=[[]]){this.raw=X,this.path=Y,this.#Y=Q,this.#X={}}param(X){return X?this.#Q(X):this.#J()}#Q(X){let Y=this.#Y[0][this.routeIndex][1][X],Q=this.#W(Y);return Q&&/\%/.test(Q)?SW6(Q):Q}#J(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let Q of Y){let J=this.#W(this.#Y[0][this.routeIndex][1][Q]);if(J!==void 0)X[Q]=/\%/.test(J)?SW6(J):J}return X}#W(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return IW6(this.url,X)}queries(X){return RW6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((Q,J)=>{Y[J]=Q}),Y}async parseBody(X){return this.bodyCache.parsedBody??=await PW6(this,X)}#G=(X)=>{let{bodyCache:Y,raw:Q}=this,J=Y[X];if(J)return J;let G=Object.keys(Y)[0];if(G)return Y[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=Q[X]()};json(){return this.#G("text").then((X)=>JSON.parse(X))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[wW6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var kW6,zx1=(X,Y)=>{let Q=new String(X);return Q.isEscaped=!0,Q.callbacks=Y,Q},rX0=async(X,Y,Q,J,G)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(G)G[0]+=X;else G=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>rX0(K,Y,!1,J,G))).then(()=>G[0]));if(Q)return zx1(await Z,W);else return Z};var vW6=v(()=>{kW6={Stringify:1,BeforeStream:2,Stream:3}});var Ux1="text/plain; charset=UTF-8",oX0=(X,Y)=>{return{"Content-Type":X,...Y}},_W6=class{#X;#Y;env={};#Q;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(X,Y){if(this.#X=X,Y)this.#W=Y.executionCtx,this.env=Y.env,this.#H=Y.notFoundHandler,this.#q=Y.path,this.#V=Y.matchResult}get req(){return this.#Y??=new tb(this.#X,this.#q,this.#V),this.#Y}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(X){if(this.#G&&X){X=new Response(X.body,X);for(let[Y,Q]of this.#G.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let J=this.#G.headers.getSetCookie();X.headers.delete("set-cookie");for(let G of J)X.headers.append("set-cookie",G)}else X.headers.set(Y,Q)}}this.#G=X,this.finalized=!0}render=(...X)=>{return this.#Z??=(Y)=>this.html(Y),this.#Z(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#Z=X};header=(X,Y,Q)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(Y===void 0)J.delete(X);else if(Q?.append)J.append(X,Y);else J.set(X,Y)};status=(X)=>{this.#J=X};set=(X,Y)=>{this.#Q??=new Map,this.#Q.set(X,Y)};get=(X)=>{return this.#Q?this.#Q.get(X):void 0};get var(){if(!this.#Q)return{};return Object.fromEntries(this.#Q)}#F(X,Y,Q){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Q)for(let[W,Z]of Object.entries(Q))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof Y==="number"?Y:Y?.status??this.#J;return new Response(X,{status:G,headers:J})}newResponse=(...X)=>this.#F(...X);body=(X,Y,Q)=>this.#F(X,Y,Q);text=(X,Y,Q)=>{return!this.#K&&!this.#J&&!Y&&!Q&&!this.finalized?new Response(X):this.#F(X,Y,oX0(Ux1,Q))};json=(X,Y,Q)=>{return this.#F(JSON.stringify(X),Y,oX0("application/json",Q))};html=(X,Y,Q)=>{let J=(G)=>this.#F(G,Y,oX0("text/html; charset=UTF-8",Q));return typeof X==="object"?rX0(X,kW6.Stringify,!1,{}).then(J):J(X)};redirect=(X,Y)=>{let Q=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,Y??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var sX0=v(()=>{cX0();vW6()});var t4="ALL",yW6="all",bW6,Yf="Can not add a route since the matcher is already built.",Qf;var uF=v(()=>{bW6=["get","post","put","delete","options","patch"],Qf=class extends Error{}});var fW6="__COMPOSED_HANDLER";var hW6=()=>{};var Bx1=(X)=>{return X.text("404 Not Found",404)},xW6=(X,Y)=>{if("getResponse"in X){let Q=X.getResponse();return Y.newResponse(Q.body,Q)}return console.error(X),Y.text("Internal Server Error",500)},gW6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...bW6,yW6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#J(W,this.#X,Z);return $.forEach((K)=>{this.#J(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#X,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(t4,this.#X,$)}),this};let{strict:J,...G}=Y;Object.assign(this,G),this.getPath=J??!0?Y.getPath??aX0:jW6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#Q=this.#Q,Y.routes=this.routes,Y}#Q=Bx1;errorHandler=xW6;route(Y,Q){let J=this.basePath(Y);return Q.routes.map((G)=>{let W;if(Q.errorHandler===xW6)W=G.handler;else W=async(Z,$)=>(await pX0([],Q.errorHandler)(Z,()=>G.handler(Z,$))).res,W[fW6]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(Y){let Q=this.#Y();return Q._basePath=xF(this._basePath,Y),Q}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#Q=Y,this};mount(Y,Q,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=xF(this._basePath,Y),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Q(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(t4,xF(Y,"*"),$),this}#J(Y,Q,J){Y=Y.toUpperCase(),Q=xF(this._basePath,Q);let G={basePath:this._basePath,path:Q,method:Y,handler:J};this.router.add(Y,Q,[J,G]),this.routes.push(G)}#W(Y,Q){if(Y instanceof Error)return this.errorHandler(Y,Q);throw Y}#G(Y,Q,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(Y,Q,J,"GET")))();let W=this.getPath(Y,{env:J}),Z=this.router.match(G,W),$=new _W6(Y,{path:W,matchResult:Z,env:J,executionCtx:Q,notFoundHandler:this.#Q});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Q($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Q($))).catch((F)=>this.#W(F,$)):H??this.#Q($)}let K=pX0(Z[0],this.errorHandler,this.#Q);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(Y,...Q)=>{return this.#G(Y,Q[1],Q[0],Y.method)};request=(Y,Q,J,G)=>{if(Y instanceof Request)return this.fetch(Q?new Request(Y,Q):Y,J,G);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${xF("/",Y)}`,Q),J,G)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#G(Y.request,Y,void 0,Y.request.method))})}};var uW6=v(()=>{LW6();sX0();uF();hW6();gF()});function Jf(X,Y){let Q=this.buildAllMatchers(),J=(G,W)=>{let Z=Q[G]||Q[t4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],wT];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(X,Y)}var wT;var tX0=v(()=>{uF();wT=[]});function Nx1(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===MT||X===PT)return 1;else if(Y===MT||Y===PT)return-1;if(X===Gf)return 1;else if(Y===Gf)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var Gf="[^/]+",MT=".*",PT="(?:|/.*)",mF,Dx1,mW6=class X{#X;#Y;#Q=Object.create(null);insert(Y,Q,J,G,W){if(Y.length===0){if(this.#X!==void 0)throw mF;if(W)return;this.#X=Q;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",MT]:["","",Gf]:Z==="/*"?["","",PT]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||Gf;if(F&&K[2]){if(V===".*")throw mF;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw mF}if(H=this.#Q[V],!H){if(Object.keys(this.#Q).some((q)=>q!==MT&&q!==PT))throw mF;if(W)return;if(H=this.#Q[V]=new X,F!=="")H.#Y=G.varIndex++}if(!W&&F!=="")J.push([F,H.#Y])}else if(H=this.#Q[Z],!H){if(Object.keys(this.#Q).some((F)=>F.length>1&&F!==MT&&F!==PT))throw mF;if(W)return;H=this.#Q[Z]=new X}H.insert($,Q,J,G,W)}buildRegExpStr(){let Q=Object.keys(this.#Q).sort(Nx1).map((J)=>{let G=this.#Q[J];return(typeof G.#Y==="number"?`(${J})@${G.#Y}`:Dx1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#X==="number")Q.unshift(`#${this.#X}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var eX0=v(()=>{mF=Symbol(),Dx1=new Set(".\\+*[^]$()")});var lW6=class{#X={varIndex:0};#Y=new mW6;insert(X,Y,Q){let J=[],G=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#Y.insert(W,Y,J,this.#X,Q),J}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,Q=[],J=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Q[++Y]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),Q,J]}};var dW6=v(()=>{eX0()});function cW6(X){return pW6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function Lx1(){pW6=Object.create(null)}function wx1(X){let Y=new lW6,Q=[];if(X.length===0)return Ox1;let J=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,z,D]=J[H];if(q)G[z]=[D.map(([L])=>[L,Object.create(null)]),wT];else F++;let N;try{N=Y.insert(z,F,q)}catch(L){throw L===mF?new Qf(z):L}if(q)continue;Q[F]=D.map(([L,w])=>{let C=Object.create(null);w-=1;for(;w>=0;w--){let[T,E]=N[w];C[T]=E}return[L,C]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,F=Q.length;H<F;H++)for(let V=0,q=Q[H].length;V<q;V++){let z=Q[H][V]?.[1];if(!z)continue;let D=Object.keys(z);for(let N=0,L=D.length;N<L;N++)z[D[N]]=$[z[D[N]]]}let K=[];for(let H in Z)K[H]=Q[Z[H]];return[W,K,G]}function CB(X,Y){if(!X)return;for(let Q of Object.keys(X).sort((J,G)=>G.length-J.length))if(cW6(Q).test(Y))return[...X[Q]];return}var Ox1,pW6,Wf=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[t4]:Object.create(null)},this.#Y={[t4]:Object.create(null)}}add(X,Y,Q){let J=this.#X,G=this.#Y;if(!J||!G)throw Error(Yf);if(!J[X])[J,G].forEach(($)=>{$[X]=Object.create(null),Object.keys($[t4]).forEach((K)=>{$[X][K]=[...$[t4][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=cW6(Y);if(X===t4)Object.keys(J).forEach((K)=>{J[K][Y]||=CB(J[K],Y)||CB(J[t4],Y)||[]});else J[X][Y]||=CB(J[X],Y)||CB(J[t4],Y)||[];Object.keys(J).forEach((K)=>{if(X===t4||X===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Q,W])})}),Object.keys(G).forEach((K)=>{if(X===t4||X===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Q,W]))});return}let Z=Xf(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(X===t4||X===F)G[F][H]||=[...CB(J[F],H)||CB(J[t4],H)||[]],G[F][H].push([Q,W-K+$+1])})}}match=Jf;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#Q(Y)}),this.#X=this.#Y=void 0,Lx1(),X}#Q(X){let Y=[],Q=X===t4;if([this.#X,this.#Y].forEach((J)=>{let G=J[X]?Object.keys(J[X]).map((W)=>[W,J[X][W]]):[];if(G.length!==0)Q||=!0,Y.push(...G);else if(X!==t4)Y.push(...Object.keys(J[t4]).map((W)=>[W,J[t4][W]]))}),!Q)return null;else return wx1(Y)}};var XY0=v(()=>{uF();gF();tX0();eX0();dW6();Ox1=[/^$/,[],Object.create(null)],pW6=Object.create(null)});var Mx1=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#Q(X,Y){let Q=this.#X[X];Q[1].forEach((J)=>J&&J.push(Y)),Object.values(Q[2]).forEach((J)=>J[0].push(Y))}#J(X,Y,Q,J,G){let W=this.#X[X];if(!G)W[2][Y][0].push([Q,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Q,G]);else W[2][Z||Y][0].push([Q,G])})}add(X,Y,Q){if(!this.#X[X]){let G=this.#X[t4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),wT];this.#X[X]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let G=[Q,{}];if(X===t4)for(let W in this.#X)this.#Q(W,G);else this.#Q(X,G);return}let J=this.#Y[Y];if(!J)throw Error(`Path ${Y} is not registered`);for(let[G,W]of J)if(X===t4)for(let Z in this.#X)this.#J(Z,Y,Q,G,W);else this.#J(X,Y,Q,G,W)}buildAllMatchers(){return this.#X}match=Jf};var nW6=v(()=>{uF();tX0();XY0()});var iW6=v(()=>{XY0();nW6()});var YY0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,Q){if(!this.#Y)throw Error(Yf);this.#Y.push([X,Y,Q])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let Q=this.#X,J=this.#Y,G=Q.length,W=0,Z;for(;W<G;W++){let $=Q[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(X,Y)}catch(K){if(K instanceof Qf)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var aW6=v(()=>{uF()});var rW6=v(()=>{aW6()});var TT,oW6=class X{#X;#Y;#Q;#J=0;#W=TT;constructor(Y,Q,J){if(this.#Y=J||Object.create(null),this.#X=[],Y&&Q){let G=Object.create(null);G[Y]={handler:Q,possibleKeys:[],score:0},this.#X=[G]}this.#Q=[]}insert(Y,Q,J){this.#J=++this.#J;let G=this,W=AW6(Q),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=EW6(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#Y){if(G=G.#Y[q],V)Z.push(V[1]);continue}if(G.#Y[q]=new X,V)G.#Q.push(V),Z.push(V[1]);G=G.#Y[q]}return G.#X.push({[Y]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(Y,Q,J,G){let W=[];for(let Z=0,$=Y.#X.length;Z<$;Z++){let K=Y.#X[Z],H=K[Q]||K[t4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==TT||G&&G!==TT)for(let V=0,q=H.possibleKeys.length;V<q;V++){let z=H.possibleKeys[V],D=F[H.score];H.params[z]=G?.[z]&&!D?G[z]:J[z]??G?.[z],F[H.score]=!0}}}return W}search(Y,Q){let J=[];this.#W=TT;let W=[this],Z=iX0(Q),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let z=0,D=W.length;z<D;z++){let N=W[z],L=N.#Y[F];if(L)if(L.#W=N.#W,V){if(L.#Y["*"])J.push(...this.#G(L.#Y["*"],Y,N.#W));J.push(...this.#G(L,Y,N.#W))}else q.push(L);for(let w=0,C=N.#Q.length;w<C;w++){let T=N.#Q[w],E=N.#W===TT?{}:{...N.#W};if(T==="*"){let b=N.#Y["*"];if(b)J.push(...this.#G(b,Y,N.#W)),b.#W=E,q.push(b);continue}let[P,j,R]=T;if(!F&&!(R instanceof RegExp))continue;let k=N.#Y[P],y=Z.slice(K).join("/");if(R instanceof RegExp){let b=R.exec(y);if(b){if(E[j]=b[0],J.push(...this.#G(k,Y,N.#W,E)),Object.keys(k.#Y).length){k.#W=E;let h=b[0].match(/\//)?.length??0;($[h]||=[]).push(k)}continue}}if(R===!0||R.test(F))if(E[j]=F,V){if(J.push(...this.#G(k,Y,E,N.#W)),k.#Y["*"])J.push(...this.#G(k.#Y["*"],Y,E,N.#W))}else k.#W=E,q.push(k)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var sW6=v(()=>{uF();gF();TT=Object.create(null)});var QY0=class{name="TrieRouter";#X;constructor(){this.#X=new oW6}add(X,Y,Q){let J=Xf(Y);if(J){for(let G=0,W=J.length;G<W;G++)this.#X.insert(X,J[G],Q);return}this.#X.insert(X,Y,Q)}match(X,Y){return this.#X.search(X,Y)}};var tW6=v(()=>{gF();sW6()});var eW6=v(()=>{tW6()});var C9;var XZ6=v(()=>{uW6();iW6();rW6();eW6();C9=class extends gW6{constructor(X={}){super(X);this.router=X.router??new YY0({routers:[new Wf,new QY0]})}}});var k7=v(()=>{XZ6()});function Px1(){let{process:X,Deno:Y}=globalThis;return!(typeof Y?.noColor==="boolean"?Y.noColor:X!==void 0?"NO_COLOR"in X?.env:!1)}async function YZ6(){let{navigator:X}=globalThis,Y="cloudflare:workers";return!(X!==void 0&&X.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!Px1())}var QZ6=()=>{};async function JZ6(X,Y,Q,J,G=0,W){let Z=Y==="<--"?`${Y} ${Q} ${J}`:`${Y} ${Q} ${J} ${await Ex1(G)} ${W}`;X(Z)}var Tx1=(X)=>{let[Y,Q]=[",","."];return X.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Y)).join(Q)},Ax1=(X)=>{let Y=Date.now()-X;return Tx1([Y<1000?Y+"ms":Math.round(Y/1000)+"s"])},Ex1=async(X)=>{if(await YZ6())switch(X/100|0){case 5:return`\x1B[31m${X}\x1B[0m`;case 4:return`\x1B[33m${X}\x1B[0m`;case 3:return`\x1B[36m${X}\x1B[0m`;case 2:return`\x1B[32m${X}\x1B[0m`}return`${X}`},GZ6=(X=console.log)=>{return async function(Q,J){let{method:G,url:W}=Q.req,Z=W.slice(W.indexOf("/",8));await JZ6(X,"<--",G,Z);let $=Date.now();await J(),await JZ6(X,"-->",G,Z,Q.res.status,Ax1($))}};var WZ6=v(()=>{QZ6()});var ZZ6=(X)=>{let Q={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Q.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Q.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Q.credentials)K("Access-Control-Allow-Credentials","true");if(Q.exposeHeaders?.length)K("Access-Control-Expose-Headers",Q.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Q.origin!=="*")K("Vary","Origin");if(Q.maxAge!=null)K("Access-Control-Max-Age",Q.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Q.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Q.origin!=="*")Z.header("Vary","Origin",{append:!0})}};var $Z6=()=>{};var KZ6=()=>{try{return performance.now()}catch{}return Date.now()},JY0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(J,G){let W=[],Z=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:W,timers:Z}),Y.total)IB(J,"total",Y.totalDescription);if(await G(),Y.total)lF(J,"total");if(Y.autoEnd)Z.forEach((K,H)=>lF(J,H));if(typeof Y.enabled==="function"?Y.enabled(J):Y.enabled){J.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(J):Y.crossOrigin;if(K)J.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},HZ6=(X,Y,Q,J,G)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Q==="number"){let Z=Q.toFixed(G||1),$=J?`${Y};dur=${Z};desc="${J}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=Q?`${Y};desc="${Q}"`:`${Y}`;W.headers.push(Z)}},IB=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(Y,{description:Q,start:KZ6()})},lF=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(Y);if(!G){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=G,$=KZ6()-Z;HZ6(X,Y,$,W,Q),J.timers.delete(Y)};var FZ6=v(()=>{sX0()});var VZ6=v(()=>{FZ6()});var jx1,Cx1,GY0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let Q=X.trim().split(";"),J={};for(let G of Q){G=G.trim();let W=G.indexOf("=");if(W===-1)continue;let Z=G.substring(0,W).trim();if(Y&&Y!==Z||!jx1.test(Z))continue;let $=G.substring(W+1).trim();if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Cx1.test($)){if(J[Z]=$.indexOf("%")!==-1?jB($,LT):$,Y)break}}return J};var qZ6=v(()=>{gF();jx1=/^[\w!#$%&'*.^`|~+-]+$/,Cx1=/^[ !#-:<-[\]-~]*$/});var zZ6=(X,Y,Q)=>{let J=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!J)return;let W=Y;if(Q==="secure")W="__Secure-"+Y;else if(Q==="host")W="__Host-"+Y;return GY0(J,W)[W]}if(!J)return{};return GY0(J)};var UZ6=v(()=>{qZ6()});import{randomBytes as Ix1}from"crypto";function BZ6(){if(AT)return AT;let X=process.env.MESH_JWT_SECRET??X9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(X)AT=new TextEncoder().encode(X);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),AT=new Uint8Array(Ix1(32));return AT}async function DZ6(X,Y="5m"){let Q=BZ6();return await new mY(X).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Y).sign(Q)}async function NZ6(X){try{let Y=BZ6(),{payload:Q}=await W8(X,Y);return Q}catch{return}}var AT=null;var WY0=v(()=>{EQ();EB()});class ZY0{db;constructor(X){this.db=X}async create(X,Y,Q){let J=qQ("vir"),G=new Date().toISOString();if(await this.db.insertInto("virtual_mcps").values({id:J,organization_id:X,title:Q.title,description:Q.description??null,tool_selection_mode:Q.tool_selection_mode??"inclusion",icon:Q.icon??null,status:Q.status??"active",created_at:G,updated_at:G,created_by:Y,updated_by:null}).execute(),Q.connections.length>0)await this.db.insertInto("virtual_mcp_connections").values(Q.connections.map((Z)=>({id:qQ("virc"),virtual_mcp_id:J,connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create virtual MCP with id: ${J}`);return W}async findById(X){return this.findByIdInternal(this.db,X)}async findByIdInternal(X,Y){let Q=await X.selectFrom("virtual_mcps").selectAll().where("id","=",Y).executeTakeFirst();if(!Q)return null;let J=await X.selectFrom("virtual_mcp_connections").selectAll().where("virtual_mcp_id","=",Y).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(X){let Y=await this.db.selectFrom("virtual_mcps").selectAll().where("organization_id","=",X).execute(),Q=Y.map((W)=>W.id);if(Q.length===0)return[];let J=await this.db.selectFrom("virtual_mcp_connections").selectAll().where("virtual_mcp_id","in",Q).execute(),G=new Map;for(let W of J){let Z=G.get(W.virtual_mcp_id)??[];Z.push(W),G.set(W.virtual_mcp_id,Z)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,G.get(W.id)??[]))}async listByConnectionId(X,Y){let J=(await this.db.selectFrom("virtual_mcp_connections").select("virtual_mcp_id").where("connection_id","=",Y).execute()).map((K)=>K.virtual_mcp_id);if(J.length===0)return[];let G=await this.db.selectFrom("virtual_mcps").selectAll().where("id","in",J).where("organization_id","=",X).execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("virtual_mcp_connections").selectAll().where("virtual_mcp_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.virtual_mcp_id)??[];H.push(K),$.set(K.virtual_mcp_id,H)}return G.map((K)=>this.deserializeVirtualMCPEntity(K,$.get(K.id)??[]))}async update(X,Y,Q){let J=new Date().toISOString(),G={updated_at:J,updated_by:Y};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.tool_selection_mode!==void 0)G.tool_selection_mode=Q.tool_selection_mode;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(await this.db.updateTable("virtual_mcps").set(G).where("id","=",X).execute(),Q.connections!==void 0){if(await this.db.deleteFrom("virtual_mcp_connections").where("virtual_mcp_id","=",X).execute(),Q.connections.length>0)await this.db.insertInto("virtual_mcp_connections").values(Q.connections.map((Z)=>({id:qQ("virc"),virtual_mcp_id:X,connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:J}))).execute()}let W=await this.findById(X);if(!W)throw Error("Virtual MCP not found after update");return W}async delete(X){await this.db.deleteFrom("virtual_mcps").where("id","=",X).execute()}deserializeVirtualMCPEntity(X,Y){let Q=X.created_at instanceof Date?X.created_at.toISOString():X.created_at,J=X.updated_at instanceof Date?X.updated_at.toISOString():X.updated_at;return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,tool_selection_mode:this.parseToolSelectionMode(X.tool_selection_mode),icon:X.icon,status:X.status,created_at:Q,updated_at:J,created_by:X.created_by,updated_by:X.updated_by??void 0,connections:Y.map((G)=>({connection_id:G.connection_id,selected_tools:this.parseJson(G.selected_tools),selected_resources:this.parseJson(G.selected_resources),selected_prompts:this.parseJson(G.selected_prompts)}))}}parseToolSelectionMode(X){if(X==="exclusion")return"exclusion";return"inclusion"}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}var OZ6=v(()=>{zF()});class $Y0{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(X){return bM.startActiveSpan("redactor.redact",(Y)=>{try{if(X===null||X===void 0)return X;if(typeof X==="string")return Y.setAttribute("data.type","string"),this.redactString(X);if(Array.isArray(X))return Y.setAttribute("data.type","array"),Y.setAttribute("data.length",X.length),X.map((Q)=>this.redact(Q));if(typeof X==="object"){Y.setAttribute("data.type","object");let Q={};for(let[J,G]of Object.entries(X)){let W=this.redactString(J);Q[W]=this.redact(G)}return Q}return Y.setAttribute("data.type",typeof X),X}finally{Y.end()}})}redactString(X){return bM.startActiveSpan("redactor.redactString",(Y)=>{try{Y.setAttribute("text.length",X.length);let Q=X,J=0;for(let G of this.patterns){let W=X.match(G.regex);if(W)J+=W.length,Y.setAttribute(`redaction.${G.type}.count`,W.length);Q=Q.replace(G.regex,`[REDACTED:${G.type}]`)}return Y.setAttribute("redaction.total_count",J),Q}finally{Y.end()}})}}var LZ6=v(()=>{fM()});import{sql as Zf}from"kysely";class KY0{db;redactor;databaseType;constructor(X,Y="sqlite"){this.db=X;this.redactor=new $Y0,this.databaseType=Y}jsonExtract(X,Y){if(this.databaseType==="postgres")return Zf`(${Zf.ref(X)}::jsonb)->>${Y}`;let Q=`$.${Y}`;return Zf`json_extract(${Zf.ref(X)}, ${Q})`}async log(X){await this.logBatch([X])}async logBatch(X){if(X.length===0)return;let Y=X.map((Q)=>({...Q,input:this.redactor.redact(Q.input),output:this.redactor.redact(Q.output)}));await this.db.transaction().execute(async(Q)=>{await Q.insertInto("monitoring_logs").values(Y.map((J)=>this.toDbRow(J))).execute()})}async query(X){let Y=this.db.selectFrom("monitoring_logs").selectAll(),Q=this.db.selectFrom("monitoring_logs").select(($)=>$.fn.count("id").as("count"));if(X.organizationId)Y=Y.where("organization_id","=",X.organizationId),Q=Q.where("organization_id","=",X.organizationId);if(X.connectionId)Y=Y.where("connection_id","=",X.connectionId),Q=Q.where("connection_id","=",X.connectionId);if(X.virtualMcpId)Y=Y.where("virtual_mcp_id","=",X.virtualMcpId),Q=Q.where("virtual_mcp_id","=",X.virtualMcpId);if(X.toolName)Y=Y.where("tool_name","=",X.toolName),Q=Q.where("tool_name","=",X.toolName);if(X.isError!==void 0)Y=Y.where("is_error","=",X.isError?1:0),Q=Q.where("is_error","=",X.isError?1:0);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString()),Q=Q.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString()),Q=Q.where("timestamp","<=",X.endDate.toISOString());if(X.propertyFilters){let{properties:$,propertyKeys:K,propertyPatterns:H}=X.propertyFilters;if($)for(let[F,V]of Object.entries($)){let q=this.jsonExtract("properties",F);Y=Y.where(q,"=",V),Q=Q.where(q,"=",V)}if(K&&K.length>0)for(let F of K){let V=this.jsonExtract("properties",F);Y=Y.where(V,"is not",null),Q=Q.where(V,"is not",null)}if(H)for(let[F,V]of Object.entries(H)){let q=this.jsonExtract("properties",F),z=this.databaseType==="postgres"?"ilike":"like";Y=Y.where(q,z,V),Q=Q.where(q,z,V)}}if(Y=Y.orderBy("timestamp","desc"),X.limit)Y=Y.limit(X.limit);if(X.offset)Y=Y.offset(X.offset);let[J,G]=await Promise.all([Y.execute(),Q.executeTakeFirst()]),W=Number(G?.count||0);return{logs:J.map(($)=>this.fromDbRow($)),total:W}}async getStats(X){let Y=this.db.selectFrom("monitoring_logs").where("organization_id","=",X.organizationId);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString());let Q=await Y.select([(Z)=>Z.fn.count("id").as("total_count"),(Z)=>Z.fn.sum(Z.ref("is_error")).as("error_count"),(Z)=>Z.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Q?.total_count||0),G=Number(Q?.error_count||0),W=Number(Q?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:W}}toDbRow(X){return{id:X.id||qQ("log"),organization_id:X.organizationId,connection_id:X.connectionId,connection_title:X.connectionTitle,tool_name:X.toolName,input:JSON.stringify(X.input),output:JSON.stringify(X.output),is_error:X.isError?1:0,error_message:X.errorMessage||null,duration_ms:X.durationMs,timestamp:X.timestamp instanceof Date?X.timestamp.toISOString():X.timestamp,user_id:X.userId||null,request_id:X.requestId,user_agent:X.userAgent||null,virtual_mcp_id:X.virtualMcpId||null,properties:X.properties?JSON.stringify(X.properties):null}}fromDbRow(X){let Y=typeof X.input==="string"?JSON.parse(X.input):X.input,Q=typeof X.output==="string"?JSON.parse(X.output):X.output,J=typeof X.timestamp==="string"?new Date(X.timestamp):X.timestamp,G=X.properties?typeof X.properties==="string"?JSON.parse(X.properties):X.properties:null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,connectionTitle:X.connection_title,toolName:X.tool_name,input:Y,output:Q,isError:X.is_error===1,errorMessage:X.error_message,durationMs:X.duration_ms,timestamp:J,userId:X.user_id,requestId:X.request_id,userAgent:X.user_agent,virtualMcpId:X.virtual_mcp_id,properties:G}}}var wZ6=v(()=>{LZ6();zF()});class HY0{db;constructor(X){this.db=X}async get(X){let Y=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",X).executeTakeFirst();if(!Y)return null;return{organizationId:Y.organizationId,sidebar_items:Y.sidebar_items?typeof Y.sidebar_items==="string"?JSON.parse(Y.sidebar_items):Y.sidebar_items:null,enabled_plugins:Y.enabled_plugins?typeof Y.enabled_plugins==="string"?JSON.parse(Y.enabled_plugins):Y.enabled_plugins:null,createdAt:Y.createdAt,updatedAt:Y.updatedAt}}async upsert(X,Y){let Q=new Date().toISOString(),J=Y?.sidebar_items?JSON.stringify(Y.sidebar_items):null,G=Y?.enabled_plugins?JSON.stringify(Y.enabled_plugins):null;await this.db.insertInto("organization_settings").values({organizationId:X,sidebar_items:J,enabled_plugins:G,createdAt:Q,updatedAt:Q}).onConflict((Z)=>Z.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,enabled_plugins:G?G:void 0,updatedAt:Q})).execute();let W=await this.get(X);if(!W)return{organizationId:X,sidebar_items:Y?.sidebar_items??null,enabled_plugins:Y?.enabled_plugins??null,createdAt:Q,updatedAt:Q};return W}}class FY0{db;constructor(X){this.db=X}async findById(X,Y){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",X).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",X).where("m2.userId","=",Y))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}var MZ6,VY0,RB;var qY0=v(()=>{JK();MZ6=class MZ6 extends Error{constructor(X){super(X);this.name="UnauthorizedError"}};VY0=class VY0 extends Error{constructor(X){super(X);this.name="ForbiddenError"}};RB=class RB{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(X,Y,Q,J,G,W=g5.SELF){this.userId=Y;this.toolName=Q;this.boundAuth=J;this.role=G;this.connectionId=W}[Symbol.dispose](){this._granted=!1}setToolName(X){this.toolName=X}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...X){if(this._granted)return;if(!this.userId&&!this.boundAuth)throw new MZ6("Authentication required. Please provide a valid OAuth token or API key.");let Y=X.length>0?X:this.toolName?[this.toolName]:[];if(Y.length===0)throw new VY0("No resources specified for access check");for(let Q of Y)if(await this.checkResource(Q)){this.grant();return}throw new VY0(`Access denied to: ${Y.join(", ")}`)}async checkResource(X){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Y={};if(this.connectionId)Y[this.connectionId]=[X];return this.boundAuth.hasPermission(Y)}granted(){return this._granted}}});function PZ6(X){let Y=null;return()=>{if(Y)return Y;return Y=X().catch((Q)=>{throw Y=null,Q}),Y}}class TZ6{factory;promise=null;constructor(X){this.factory=X}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(X,Y){return this.getOrCreatePromise().then(X,Y)}catch(X){return this.getOrCreatePromise().catch(X)}finally(X){return this.getOrCreatePromise().finally(X)}}function v7(X){return new TZ6(X)}async function AZ6(X){if(!X.refreshToken)return{success:!1,error:"No refresh token available"};if(!X.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!X.clientId)return{success:!1,error:"No client ID available"};try{let Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:X.refreshToken,client_id:X.clientId});if(X.clientSecret)Y.set("client_secret",X.clientSecret);if(X.scope)Y.set("scope",X.scope);let Q=await fetch(X.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!Q.ok){let G=await Q.text();console.error(`[TokenRefresh] Failed to refresh token: ${Q.status}`,G);try{let W=JSON.parse(G);return{success:!1,error:W.error_description||W.error||`Token refresh failed: ${Q.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Q.status}`}}}let J=await Q.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||X.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Y){return console.error("[TokenRefresh] Error refreshing token:",Y),{success:!1,error:Y instanceof Error?Y.message:"Token refresh failed"}}}function Rx1(X){return new Proxy(X,{get(Q,J,G){if(J==="close")return async()=>{};if(J==="__actualClient")return Q;return Reflect.get(Q,J,G)}})}async function CZ6(X){let Y=dF.get(X.id);if(Y?.status==="connected"&&Y.stableClient)return Y.stableClient;if(Y?.connectPromise&&(Y.status==="connecting"||Y.status==="reconnecting"))return Y.connectPromise;let Q=Y?.status==="failed",J=Y??{transport:null,client:null,stableClient:null,config:X,status:"connecting",connectPromise:null};if(!Y)dF.set(X.id,J);return J.status=Q?"reconnecting":"connecting",J.connectPromise=(async()=>{try{console.log(`[StableStdio] ${Q?"Respawning":"Spawning"}: ${X.id} (${X.command} ${X.args?.join(" ")??""})`);let G=new lP({command:X.command,args:X.args,env:X.env,cwd:X.cwd,stderr:"pipe"});J.transport=G;let W=new OQ({name:`mesh-stdio-${X.id}`,version:"1.0.0"});J.client=W,J.stableClient=Rx1(W),W.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${X.id}`),J.status="failed",J.connectPromise=null};let Z=X.name||X.id,$="\x1B[2m",K="\x1B[0m";G.stderr?.on("data",(V)=>{let q=V.toString().trimEnd();if(q)console.error(`${q} ${$}[${Z}]${K}`)});let H=new AbortController,F=setTimeout(()=>H.abort(),30000);try{await Promise.race([W.connect(G),new Promise((V,q)=>{H.signal.addEventListener("abort",()=>{q(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(F)}return J.status="connected",console.log(`[StableStdio] Connected: ${X.id}`),J.stableClient}catch(G){console.error(`[StableStdio] Failed to connect ${X.id}:`,G),J.status="failed",J.connectPromise=null;try{await J.transport?.close()}catch{}throw G}})(),J.connectPromise}async function Sx1(X){let Y=dF.get(X);if(!Y)return;console.log(`[StableStdio] Force closing: ${X}`);try{if(Y.client)Y.client.onclose=void 0;await Y.client?.close()}catch{}dF.delete(X)}async function kx1(){console.log(`[StableStdio] Closing all connections (${dF.size})`);let X=Array.from(dF.keys()).map((Y)=>Sx1(Y));await Promise.allSettled(X),dF.clear()}var EZ6="__mesh_stable_stdio_pool__",dF,jZ6="__mesh_stable_stdio_shutdown_registered__";var IZ6=v(()=>{XB();G90();dF=globalThis[EZ6]??(globalThis[EZ6]=new Map);if(!globalThis[jZ6]){globalThis[jZ6]=!0;let X=async(Y)=>{await kx1(),process.exit(Y==="SIGINT"?130:143)};process.on("SIGINT",()=>X("SIGINT")),process.on("SIGTERM",()=>X("SIGTERM"))}});async function RZ6(X,Y){return(await Y.storage.connections.findById(X))?.connection_url??null}function vx1(X){let Y=X.toLowerCase();return Y.includes("resource_metadata=")||Y.includes("invalid_token")||Y.includes("oauth")}async function SZ6(X,Y={}){try{let Q=await fetch(X,{method:"POST",headers:{...Y,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Q.status===401){let J=Q.headers.get("WWW-Authenticate");if(J){if(vx1(J))return J}}return null}catch{return null}}async function Kf(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=new URL(X);J.pathname=`${Q}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!zY0.includes(G.status))return G;let W=new URL(X);if(W.pathname=`/.well-known/oauth-protected-resource${Q}`,G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),!zY0.includes(G.status))return G;let Z=new URL(X);return Z.pathname="/.well-known/oauth-protected-resource",G=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function _x1(X,Y){let Q=await RZ6(X,Y);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Kf(Q);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function kZ6(X){let Y=X.get("meshContext");if(!Y)Y=await SK.create(X.req.raw),X.set("meshContext",Y);return Y}async function vZ6({error:X,reqUrl:Y,connectionId:Q,connectionUrl:J,headers:G}){let W=X.message?.toLowerCase()??"";if(!(X.status===401||X.code===401||X.message?.includes("401")||W.includes("unauthorized")||W.includes("invalid_token")||W.includes("api key required")||W.includes("api-key required")))return null;if(Boolean(await SZ6(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${Y.origin}/mcp/${Q}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}async function UY0(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=Q!==""&&Q!=="/",G=[];if(J){let Z=new URL(X);Z.pathname=`/.well-known/oauth-authorization-server${Q}`,G.push(Z);let $=new URL(X);$.pathname=`/.well-known/openid-configuration${Q}`,G.push($);let K=new URL(X);K.pathname=`${Q}/.well-known/openid-configuration`,G.push(K)}else{let Z=new URL(X);Z.pathname="/.well-known/oauth-authorization-server",G.push(Z);let $=new URL(X);$.pathname="/.well-known/openid-configuration",G.push($)}let W=null;for(let Z of G){if(W=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}var $f,zY0,Hf=(X)=>{if(!(X.hostname==="localhost"||X.hostname==="127.0.0.1"))X.protocol="https:";return X},_Z6=async(X)=>{let Y=X.req.param("connectionId"),Q=await kZ6(X),J=await RZ6(Y,Q);if(!J)return X.json({error:"Connection not found"},404);let G=Hf(new URL(X.req.url)),W=`${G.origin}/mcp/${Y}`,Z=`${G.origin}/oauth-proxy/${Y}`;try{let $=await Kf(J);if(!$.ok&&zY0.includes($.status)){if(await SZ6(J))return new Response(JSON.stringify({resource:W,authorization_servers:[Z],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}if(!$.ok)return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}});let H={...await $.json(),resource:W,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}catch($){let K=$;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",K),X.json({error:"Failed to proxy OAuth metadata",message:K.message},502)}},yZ6;var Ff=v(()=>{k7();Vf();$f=new C9,zY0=[404,401,406];$f.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(X)=>_Z6(X));$f.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(X)=>_Z6(X));$f.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=await kZ6(X),J=await _x1(Y,Q);if(!J)return X.json({error:"Connection not found or no auth server"},404);try{let G=await UY0(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let W=await G.json(),$=`${Hf(new URL(X.req.url)).origin}/oauth-proxy/${Y}`,K={...W,authorization_endpoint:W.authorization_endpoint?`${$}/authorize`:void 0,token_endpoint:W.token_endpoint?`${$}/token`:void 0,registration_endpoint:W.registration_endpoint?`${$}/register`:void 0};return new Response(JSON.stringify(K),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let W=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",W),X.json({error:"Failed to proxy auth server metadata",message:W.message},502)}});yZ6=$f});function yx1(X){if(!X.isError)return;let Y=X.content;if(!Array.isArray(Y))return;for(let Q of Y)if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text;return}function bx1(X){if(!X)return;let Y=X._meta;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let Q=Y.properties;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J={};for(let[G,W]of Object.entries(Q))if(typeof W==="string")J[G]=W;return Object.keys(J).length>0?J:void 0}function fx1(X,Y){if(!X&&!Y)return;if(!X)return Y;if(!Y)return X;return{...Y,...X}}function bZ6(X){if(X&&typeof X==="object"&&!Array.isArray(X)){let Y=X,Q=Y.structuredContent;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return Y}return{value:X}}async function hx1(X,Y){let Q=X.body;if(!Q)return{text:"",truncated:!1};let J=Q.getReader(),G=new TextDecoder,W=!1,Z=0,$=[];try{while(!0){let{value:K,done:H}=await J.read();if(H)break;if(K){if(Z+=K.byteLength,Z>Y){W=!0;let F=Y-(Z-K.byteLength);if(F>0)$.push(G.decode(K.slice(0,F),{stream:!0}));break}$.push(G.decode(K,{stream:!0}))}}}finally{J.releaseLock()}return $.push(G.decode()),{text:$.join(""),truncated:W}}async function ET(X){let{ctx:Y,enabled:Q}=X,J=X.organizationId??Y.organization?.id;if(!Q||!J)return;let G=bx1(X.request.params.arguments),W=fx1(Y.metadata.properties,G);await Y.storage.monitoring.log({organizationId:J,connectionId:X.connectionId,connectionTitle:X.connectionTitle,toolName:X.request.params.name,input:X.request.params.arguments??{},output:X.output,isError:X.isError,errorMessage:X.errorMessage,durationMs:X.durationMs,timestamp:new Date,userId:Y.auth.user?.id||Y.auth.apiKey?.userId||null,requestId:Y.metadata.requestId,userAgent:Y.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:W})}function fZ6(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G}=X;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=Date.now()-$;return await ET({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,request:W,output:bZ6(K),isError:Boolean(K.isError),errorMessage:yx1(K),durationMs:H}),K}catch(K){let H=K,F=Date.now()-$;throw await ET({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}function hZ6(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G}=X;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=Y.organization?.id;if(Q&&H){let F=K.clone();(async()=>{try{let{text:V,truncated:q}=await hx1(F,262144),z=Date.now()-$,D=F.headers.get("content-type")??"",N=V;if(D.includes("application/json"))try{N=V.length?JSON.parse(V):null}catch{N=V}let L=K.status>=400,w=L&&N&&typeof N==="object"&&"error"in N?N.error:void 0,C=typeof w==="string"&&w?w:L&&typeof N==="string"&&N.trim()?N.slice(0,500):L?`HTTP ${K.status} ${K.statusText}`.trim():q?"Response body truncated to 262144 bytes":void 0;await ET({ctx:Y,enabled:Q,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:bZ6(N),isError:L,errorMessage:C,durationMs:z})}catch(V){let q=Date.now()-$;await ET({ctx:Y,enabled:Q,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${V.message}`,durationMs:q})}})()}return K}catch(K){let H=K,F=Date.now()-$;throw await ET({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}function xx1(X,Y){return async(Q,J)=>{try{let G=Q.params.name;return await new RB(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,G,X.boundAuth,X.auth.user?.role,Y).check(G),await J()}catch(G){return{content:[{type:"text",text:`Authorization failed: ${G.message}`}],isError:!0}}}}function gx1(X,Y){return async(Q,J)=>{try{let G=Q.params.name;return await new RB(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,G,X.boundAuth,X.auth.user?.role,Y).check(G),await J()}catch(G){return new Response(JSON.stringify({error:`Authorization failed: ${G.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function gZ6(X,Y,{superUser:Q}){let J=typeof X==="string"?await Y.storage.connections.findById(X,Y.organization?.id):X;if(!J)throw Error("Connection not found");let G=J?.id;if(Y.organization&&J.organization_id!==Y.organization.id)throw Error("Connection does not belong to the active organization");if(Y.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let W,Z=Y.auth.user?.connectionId,$=PZ6(async()=>{let f=s90(J.configuration_state,J.configuration_scopes),S=Y.auth.user?.id??Y.auth.apiKey?.userId;if(!S){console.error("User ID required to issue configuration token");return}try{W=await DZ6({sub:S,user:{id:S},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??Y.baseUrl,connectionId:G,organizationId:Y.organization?.id},permissions:f})}catch(u){console.error("Failed to issue configuration token:",u)}}),K=async()=>{await $();let f={...Z?{"x-caller-id":Z}:{}},S=null,u=new qZ(Y.db,Y.vault),t=await u.get(G);if(t){let r=!!t.refreshToken&&!!t.tokenEndpoint;if(u.isExpired(t,r?300000:0))if(r){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let H0=await AZ6(t);if(H0.success&&H0.accessToken)await u.upsert({connectionId:G,accessToken:H0.accessToken,refreshToken:H0.refreshToken??t.refreshToken,scope:H0.scope??t.scope,expiresAt:H0.expiresIn?new Date(Date.now()+H0.expiresIn*1000):null,clientId:t.clientId,clientSecret:t.clientSecret,tokenEndpoint:t.tokenEndpoint}),S=H0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await u.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${H0.error}`)}else await u.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else S=t.accessToken}if(!S&&J.connection_token)S=J.connection_token;if(S)f.Authorization=`Bearer ${S}`;if(W)f["x-mesh-token"]=W;return f},H=J.connection_type==="STDIO",F=VF(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{switch(J.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");if(!F)throw Error("STDIO connection missing parameters");return CZ6({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd})}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=new OQ({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let u=new HZ(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(u),f}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=new OQ({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let u=new jF(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(u),f}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=Q?async(f,S)=>await S():xx1(Y,G),D=Q?async(f,S)=>await S():gx1(Y,G),N={enabled:EN0().enabled,connectionId:G,connectionTitle:J.title,ctx:Y},L=fZ6(N),w=hZ6(N),C=nP(L,z),T=nP(w,D),E=async(f)=>{return C(f,async()=>{let S=await q(),u=Date.now(),t={...f.params};if(t.arguments&&"_meta"in t.arguments){let{_meta:r,...Y0}=t.arguments;t.arguments=Y0}return await Y.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":f.params.name}},async(r)=>{try{let Y0=await S.callTool(t),H0=Date.now()-u;return Y.meter.createHistogram("connection.proxy.duration").record(H0,{"connection.id":G,"tool.name":f.params.name,status:"success"}),Y.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":f.params.name,status:"success"}),r.end(),Y0}catch(Y0){let H0=Y0,G0=Date.now()-u;throw Y.meter.createHistogram("connection.proxy.duration").record(G0,{"connection.id":G,"tool.name":f.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":f.params.name,error:H0.message}),r.recordException(H0),r.end(),Y0}finally{S.close().catch(console.error)}})})};return{fetch:async(f)=>{let S=new URL(f.url),u;try{u=await q()}catch(G0){let B0=J.connection_url?await vZ6({error:G0,reqUrl:S,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(B0)return B0;throw G0}let r=u.getServerCapabilities()??{tools:{},resources:{},prompts:{}},Y0=new IF({name:"mcp-mesh",version:"1.0.0"},{capabilities:r}),H0=new RF({enableJsonResponse:f.headers.get("Accept")?.includes("application/json")??!1});if(await Y0.connect(H0),Y0.server.setRequestHandler(UK,()=>u.listTools()),Y0.server.setRequestHandler(E7,E),r.resources)Y0.server.setRequestHandler(HK,()=>u.listResources()),Y0.server.setRequestHandler(VK,(G0)=>u.readResource(G0.params)),Y0.server.setRequestHandler(FK,()=>u.listResourceTemplates());if(r.prompts)Y0.server.setRequestHandler(qK,()=>u.listPrompts()),Y0.server.setRequestHandler(zK,(G0)=>u.getPrompt(G0.params));try{return await H0.handleRequest(f)}finally{try{await H0.close?.()}catch{}}},client:{callTool:(f)=>{return E({method:"tools/call",params:f})},listTools:async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((S)=>({name:S.name,description:S.description,inputSchema:S.inputSchema,outputSchema:S.outputSchema}))};let f;try{return f=await q(),await f.listTools()}finally{f?.close().catch(console.error)}},listResources:async()=>{let f;try{if(f=await q(),!f.getServerCapabilities()?.resources)return{resources:[]};return await f.listResources()}finally{f?.close().catch(console.error)}},readResource:async(f)=>{let S;try{return S=await q(),await S.readResource(f)}finally{S?.close().catch(console.error)}},listResourceTemplates:async()=>{let f;try{if(f=await q(),!f.getServerCapabilities()?.resources)return{resourceTemplates:[]};return await f.listResourceTemplates()}finally{f?.close().catch(console.error)}},listPrompts:async()=>{let f;try{if(f=await q(),!f.getServerCapabilities()?.prompts)return{prompts:[]};return await f.listPrompts()}finally{f?.close().catch(console.error)}},getPrompt:async(f)=>{let S;try{if(S=await q(),!S.getServerCapabilities()?.prompts)throw Error("Prompts capability not supported");return await S.getPrompt(f)}finally{S?.close().catch(console.error)}}},callStreamableTool:async(f,S)=>{if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let u=J.connection_url,t={method:"tools/call",params:{name:f,arguments:S}};return T(t,async()=>{let r=await K();if(V?.headers)Object.assign(r,V.headers);let Y0=new URL(u);return Y0.pathname=Y0.pathname.replace(/\/$/,"")+`/call-tool/${t.params.name}`,await Y.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":t.params.name}},async(H0)=>{let G0=Date.now();try{let B0=await fetch(Y0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(t.params.arguments),headers:{...r,"Content-Type":"application/json"}}),T0=Date.now()-G0;return Y.meter.createHistogram("connection.proxy.streamable.duration").record(T0,{"connection.id":G,"tool.name":t.params.name,status:B0.ok?"success":"error"}),Y.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":t.params.name,status:B0.ok?"success":"error"}),H0.end(),B0}catch(B0){let T0=B0,y0=Date.now()-G0;throw Y.meter.createHistogram("connection.proxy.streamable.duration").record(y0,{"connection.id":G,"tool.name":t.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":t.params.name,error:T0.message}),H0.recordException(T0),H0.end(),B0}})})}}}async function uZ6(X,Y){return gZ6(X,Y,{superUser:!1})}async function mZ6(X,Y){return gZ6(X,Y,{superUser:!0})}var xZ6,lZ6;var qf=v(()=>{t90();zS();IZ6();ab();aW();XB();Cb();pP();kb();vb();E9();k7();WY0();qY0();Ff();xZ6=new C9;xZ6.all("/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=X.get("meshContext");try{return await(await Q.createMCPProxy(Y)).fetch(X.req.raw)}catch(J){let G=J;if(G.message.includes("not found"))return X.json({error:G.message},404);if(G.message.includes("does not belong to the active organization"))return X.json({error:"Connection not found"},404);if(G.message.includes("inactive"))return X.json({error:G.message},503);return X.json({error:"Internal server error",message:G.message},500)}});lZ6=xZ6});class BY0{db;constructor(X){this.db=X}async create(X){let Y=X.id??qQ("thrd"),Q=new Date().toISOString();if(!X.organizationId)throw Error("organizationId is required");if(!X.createdBy)throw Error("createdBy is required");if(!X.title)X.title="New Thread - "+Q;let J={id:Y,organization_id:X.organizationId,title:X.title,description:X.description??null,created_at:Q,updated_at:Q,created_by:X.createdBy,updated_by:X.updatedBy??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(X){let Y=await this.db.selectFrom("threads").selectAll().where("id","=",X).executeTakeFirst();return Y?this.threadFromDbRow(Y):null}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.updatedBy!==void 0)J.updated_by=Y.updatedBy;await this.db.updateTable("threads").set(J).where("id","=",X).execute();let G=await this.get(X);if(!G)throw Error("Thread not found after update");return G}async delete(X){await this.db.deleteFrom("threads").where("id","=",X).execute()}async list(X,Y){let Q=this.db.selectFrom("threads").selectAll().where("organization_id","=",X).where("hidden","=",!1).orderBy("updated_at","desc"),J=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",X).where("hidden","=",!1);if(Y?.limit)Q=Q.limit(Y.limit);if(Y?.offset)Q=Q.offset(Y.offset);let[G,W]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{threads:G.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async listByUserId(X){let Y=await this.db.selectFrom("threads").selectAll().where("created_by","=",X).orderBy("updated_at","desc").execute();return{threads:Y.map((Q)=>this.threadFromDbRow(Q)),total:Y.length}}async saveMessages(X){let Y=new Date().toISOString(),Q=X[0]?.threadId;if(!Q)throw Error("threadId is required when creating multiple messages");let J=X.find((W)=>W.threadId!==Q);if(J)throw Error(`All messages must target the same thread. Expected threadId "${Q}", but message "${J.id}" has threadId "${J.threadId}"`);let G=X.map((W)=>({id:W.id,thread_id:Q,metadata:W.metadata?JSON.stringify(W.metadata):null,parts:JSON.stringify(W.parts),role:W.role,created_at:W.createdAt??Y,updated_at:Y}));await this.db.transaction().execute(async(W)=>{await W.insertInto("thread_messages").values(G).execute(),await W.updateTable("threads").set({updated_at:Y}).where("id","=",Q).execute()})}async listMessages(X,Y){let Q=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",X).orderBy("created_at","asc").orderBy("id","asc"),J=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",X);if(Y?.limit)Q=Q.limit(Y.limit);if(Y?.offset)Q=Q.offset(Y.offset);let[G,W]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{messages:G.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(X){return{id:X.id,organizationId:X.organization_id,title:X.title,description:X.description,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString(),createdBy:X.created_by,updatedBy:X.updated_by,hidden:X.hidden}}messageFromDbRow(X){let Y,Q;try{Y=X.metadata?JSON.parse(X.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${X.id}:`,X.metadata,J),Y=void 0}try{Q=typeof X.parts==="string"?JSON.parse(X.parts):X.parts}catch(J){console.error(`Failed to parse parts for message ${X.id}:`,X.parts,J),Q=[]}return{id:X.id,threadId:X.thread_id,metadata:Y,parts:Q,role:X.role,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString()}}}var dZ6=v(()=>{zF()});function ux1(X){if(!X)return;try{let Y=JSON.parse(X);if(typeof Y!=="object"||Y===null||Array.isArray(Y))return;let Q={};for(let[J,G]of Object.entries(Y))if(typeof G==="string")Q[J]=G;return Object.keys(Q).length>0?Q:void 0}catch{return}}function mx1(X,Y){for(let[Q,J]of Object.entries(Y)){let G=X[Q];if(!G||G.length===0){let W=X["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let Z of J)if(!W.includes(Z))return!1;continue}if(G.includes("*"))continue;for(let W of J)if(!G.includes(W))return!1}return!0}function lx1(X){let{auth:Y,headers:Q,role:J,permissions:G,userId:W}=X,Z=Y.api.hasPermission;return{hasPermission:async($)=>{if(J&&uX0.includes(J))return!0;if(G)return mx1(G,$);if(!Z)return console.error("[Auth] hasPermission API not available"),!1;try{if((await Z({headers:Q,body:{permission:$}}))?.success===!0)return!0;let H={};for(let V of Object.keys($))H[V]=["*"];return(await Z({headers:Q,body:{permission:H}}))?.success===!0}catch(K){return console.error("[Auth] Permission check failed:",K),!1}},organization:{create:async($)=>{return Y.api.createOrganization({headers:Q,body:$})},update:async($)=>{return Y.api.updateOrganization({headers:Q,body:$})},delete:async($)=>{await Y.api.deleteOrganization({headers:Q,body:{organizationId:$}})},get:async($)=>{return Y.api.getFullOrganization({headers:Q,query:$?{organizationId:$}:void 0})},list:async($)=>{return Y.api.listOrganizations({headers:Q,query:$?{userId:$}:void 0})},addMember:async($)=>{return Y.api.addMember({headers:Q,body:$})},removeMember:async($)=>{await Y.api.removeMember({headers:Q,body:$})},listMembers:async($)=>{return Y.api.listMembers({headers:Q,query:$?{organizationId:$.organizationId,limit:$.limit,offset:$.offset}:void 0})},updateMemberRole:async($)=>{return Y.api.updateMemberRole({headers:Q,body:$})}},apiKey:{create:async($)=>{return Y.api.createApiKey({body:{...$,userId:W}})},list:async()=>{return Y.api.listApiKeys({headers:Q})},update:async($)=>{return Y.api.updateApiKey({body:{...$,userId:W}})},delete:async($)=>{await Y.api.deleteApiKey({headers:Q,body:{keyId:$}})}}}}async function dx1(X,Y,Q){if(uX0.includes(Q))return;let J=await X.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Y).where("role","=",Q).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Q}`);return}}async function px1(X,Y,Q,J=cZ6){let G=X.headers.get("Authorization");try{let W=new Headers(X.headers);W.set("X-MCP-Session-Auth","true");let Z=await J.measure("auth_get_mcp_session",()=>Y.api.getMcpSession({headers:W}));if(Z){let $=Z.userId,K=await J.measure("auth_query_membership",()=>Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",$).executeTakeFirst()),H=K?.role,F=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,V;if(K&&H)V=await J.measure("auth_fetch_role_permissions",()=>dx1(Q,K.organizationId,H));return{user:{id:$,role:H},role:H,permissions:V,organization:F}}}catch(W){console.error("[Auth] OAuth session check failed:",W)}if(G?.startsWith("Bearer ")){let W=G.replace("Bearer ","").trim();try{let Z=await J.measure("auth_verify_mesh_jwt",()=>NZ6(W));if(Z){let $,K=Z.metadata?.organizationId;if(Z.sub&&K)$=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",Z.sub).where("member.organizationId","=",K).executeTakeFirst()))?.role;return{user:{id:Z.sub,connectionId:Z.metadata?.connectionId,role:$},role:$,permissions:Z.permissions,organization:Z.metadata?.organizationId?{id:Z.metadata?.organizationId}:void 0}}}catch{}try{let Z=await J.measure("auth_verify_api_key",()=>Y.api.verifyApiKey({body:{key:W}}));if(Z?.valid&&Z.key){let $=Z.key.metadata?.organization,K=Z.key.permissions,H,F=Z.key.userId;if(F&&$?.id)H=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",$.id).executeTakeFirst()))?.role;return{apiKeyId:Z.key.id,user:{id:Z.key.userId,role:H},role:H,permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(Z){console.error("[Auth] API key check failed:",Z)}}try{let W=await J.measure("auth_get_session",()=>Y.api.getSession({headers:X.headers}));if(W){let Z,$;if(W.session.activeOrganizationId){let K=await J.measure("auth_get_full_organization",()=>Y.api.getFullOrganization({headers:X.headers}).catch(()=>null));if(K)Z={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((F)=>F.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:$},role:$,organization:Z}}}catch(W){let Z=W;console.error("[Auth] Session check failed:",JSON.stringify({message:Z.message,body:Z.body,stack:Z.stack},null,2))}return{user:void 0}}function nZ6(X){let Y=new gM(X.encryption.key),Q={connections:new uM(X.db,Y),organizationSettings:new HY0(X.db),monitoring:new KY0(X.db,X.databaseType),virtualMcps:new ZY0(X.db),users:new FY0(X.db),threads:new BY0(X.db)};return async(J,G)=>{let W=G?.timings??cZ6,Z=J?.headers.get("x-caller-id")??void 0,$=J?await px1(J,X.auth,X.db,W):{user:void 0},K=lx1({auth:X.auth,headers:J?.headers??new Headers,role:$.role,permissions:$.permissions,userId:$.user?.id}),H={user:$.user};if($.apiKeyId)H.apiKey={id:$.apiKeyId,name:"",userId:""};let F=$.organization,V=J?new URL(J.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${V.protocol}//${V.host}`,z=new RB(X.auth,H.user?.id,void 0,K,$.role,g5.SELF),D={timings:W,auth:H,connectionId:Z,organization:F,storage:Q,vault:Y,authInstance:X.auth,boundAuth:K,access:z,db:X.db,tracer:X.observability.tracer,meter:X.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:ux1(J?.headers.get("x-mesh-properties"))},eventBus:X.eventBus,createMCPProxy:async(N)=>{return await uZ6(N,D)}};return D}}var pZ6,SK,cZ6;var Vf=v(()=>{WY0();J10();G10();OZ6();wZ6();qY0();qf();mX0();JK();dZ6();SK={set:(X)=>{pZ6=X},create:async(X,Y)=>{return await pZ6(X,Y)}},cZ6={measure:async(X,Y)=>{return await Y()}}});function iZ6(X){return X===jT.HEALTH||X===jT.METRICS||X.startsWith(SB.WELL_KNOWN)}function nx1(X){return X.startsWith(SB.API)}function ix1(X){return X==="/mcp"||X.startsWith(SB.MCP)}function ax1(X){return X.startsWith(SB.OAUTH_PROXY)}function rx1(X){return cx1.test(X)}function ox1(X){return X.startsWith(SB.ORG)}function aZ6(X){return nx1(X)||ix1(X)||ax1(X)||ox1(X)||iZ6(X)}function rZ6(X){return X==="/"||X.startsWith(SB.API_AUTH)||iZ6(X)||rx1(X)}var jT,SB,cx1;var DY0=v(()=>{jT={HEALTH:"/health",METRICS:"/metrics"},SB={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known",ORG:"/org/"},cx1=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/});class oZ6{db;constructor(X){this.db=X}async publishEvent(X){let Y=new Date().toISOString();return await this.db.insertInto("events").values({id:X.id,organization_id:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data?JSON.stringify(X.data):null,cron:X.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Y,updated_at:Y}).execute(),{id:X.id,organizationId:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data??null,cron:X.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Y,updatedAt:Y}}async subscribe(X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("connection_id","=",X.connectionId).where("event_type","=",X.eventType);if(X.publisher)Y=Y.where("publisher","=",X.publisher);else Y=Y.where("publisher","is",null);if(X.filter)Y=Y.where("filter","=",X.filter);else Y=Y.where("filter","is",null);let Q=await Y.executeTakeFirst();if(Q)return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:X.id,organization_id:X.organizationId,connection_id:X.connectionId,publisher:X.publisher??null,event_type:X.eventType,filter:X.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:X.id,organizationId:X.organizationId,connectionId:X.connectionId,publisher:X.publisher??null,eventType:X.eventType,filter:X.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(X,Y){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",X).where("organization_id","=",Y).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(X,Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X);if(Y)Q=Q.where("connection_id","=",Y);return(await Q.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(X,Y){let Q=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}}async getMatchingSubscriptions(X){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("enabled","=",1).where("event_type","=",X.type).where((Q)=>Q.or([Q("publisher","is",null),Q("publisher","=",X.source)])).execute()).map((Q)=>({id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}))}async createDeliveries(X,Y,Q){if(Y.length===0)return;let J=new Date().toISOString(),G=Q??null,W=Y.map((Z)=>({id:crypto.randomUUID(),event_id:X,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(X){let Y=new Date().toISOString(),Q;try{Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(W)=>W.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((Z)=>Z.or([Z("d.next_retry_at","is",null),Z("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X).execute();if(G.length===0)return[];Q=G.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Q).where("status","=","pending").execute()}if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(X){if(X.length===0)return;let Y=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Y}).where("id","in",X).execute()}async markDeliveriesFailed(X,Y,Q=20,J=1000,G=3600000){if(X.length===0)return;for(let W of X){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=Q)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(J*Math.pow(2,$-1),G),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(X){let Y=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",X).execute();if(Y.length===0)return;let Q=Y.every((W)=>W.status==="delivered"),J=Y.some((W)=>W.status==="failed"),G=Y.some((W)=>W.status==="pending"||W.status==="processing");if(Q)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",X).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",X).execute()}async resetStuckDeliveries(){let X=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(X.numUpdatedRows??0)}async getEvent(X,Y){let Q=await this.db.selectFrom("events").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,type:Q.type,source:Q.source,specversion:Q.specversion,subject:Q.subject,time:Q.time,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema,data:Q.data?JSON.parse(Q.data):null,cron:Q.cron,status:Q.status,attempts:Q.attempts,lastError:Q.last_error,nextRetryAt:Q.next_retry_at,createdAt:Q.created_at,updatedAt:Q.updated_at}}async findActiveCronEvent(X,Y,Q,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",X).where("type","=",Y).where("source","=",Q).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(X,Y,Q){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",X).where("organization_id","=",Y).where("source","=",Q).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",X).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(X,Y){if(X.length===0)return;let Q=new Date(Date.now()+Y).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Q}).where("id","in",X).execute()}async ackDelivery(X,Y,Q){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",X).where("organization_id","=",Y).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",X).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Q).where("event_subscriptions.organization_id","=",Y))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(X);return{success:W}}async syncSubscriptions(X){let{organizationId:Y,connectionId:Q,subscriptions:J}=X,G=(w,C)=>{return`${w}::${C??""}`},W=await this.listSubscriptions(Y,Q),Z=new Map;for(let w of W)Z.set(G(w.eventType,w.publisher),w);let $=new Map;for(let w of J)$.set(G(w.eventType,w.publisher),w);let K=new Date().toISOString(),H=[],F=[],V=[],q=0;for(let[w,C]of $){let T=Z.get(w);if(!T)H.push({id:crypto.randomUUID(),organization_id:Y,connection_id:Q,event_type:C.eventType,publisher:C.publisher??null,filter:C.filter??null,enabled:1,created_at:K,updated_at:K});else{let E=T.filter??null,P=C.filter??null;if(E!==P)F.push({id:T.id,filter:P});else q++}}for(let[w,C]of Z)if(!$.has(w))V.push(C.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:K}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let z=H.length,D=F.length,N=V.length,L=await this.listSubscriptions(Y,Q);return{created:z,updated:D,deleted:N,unchanged:q,subscriptions:L}}}function sZ6(X){return new oZ6(X)}function JY(X,Y,Q,J,G,W,Z,$){return JY.fromTZ(JY.tp(X,Y,Q,J,G,W,Z),$)}function NY0(X,Y=new Date){let Q=Y.toLocaleString("en-US",{timeZone:X,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Y.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Q}`)}function sx1(X,Y){let Q=new Date(Date.parse(X));if(isNaN(Q))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=X.substring(9);return X.includes("Z")||J.includes("-")||J.includes("+")?JY.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):JY.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),Y)}function tx1(X){if(X===void 0&&(X={}),delete X.name,X.legacyMode=X.legacyMode===void 0?!0:X.legacyMode,X.paused=X.paused===void 0?!1:X.paused,X.maxRuns=X.maxRuns===void 0?1/0:X.maxRuns,X.catch=X.catch===void 0?!1:X.catch,X.interval=X.interval===void 0?0:parseInt(X.interval.toString(),10),X.utcOffset=X.utcOffset===void 0?void 0:parseInt(X.utcOffset.toString(),10),X.unref=X.unref===void 0?!1:X.unref,X.startAt&&(X.startAt=new G5(X.startAt,X.timezone)),X.stopAt&&(X.stopAt=new G5(X.stopAt,X.timezone)),X.interval!==null){if(isNaN(X.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(X.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(X.utcOffset!==void 0){if(isNaN(X.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(X.utcOffset<-870||X.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(X.utcOffset!==void 0&&X.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(X.unref!==!0&&X.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return X}function CT(X){return Object.prototype.toString.call(X)==="[object Function]"||typeof X=="function"||X instanceof Function}function ex1(X){return CT(X)}function Xg1(X){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(X):X&&typeof X.unref<"u"&&X.unref()}var OY0=32,IT,Y$6,tZ6=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(X,Y){this.pattern=X,this.timezone=Y,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let X=this.pattern.replace(/\s+/g," ").split(" ");if(X.length<5||X.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(X.length===5&&X.unshift("0"),X[3].indexOf("L")>=0&&(X[3]=X[3].replace("L",""),this.lastDayOfMonth=!0),X[3]=="*"&&(this.starDOM=!0),X[4].length>=3&&(X[4]=this.replaceAlphaMonths(X[4])),X[5].length>=3&&(X[5]=this.replaceAlphaDays(X[5])),X[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Y=new G5(new Date,this.timezone).getDate(!0);X[0]=X[0].replace("?",Y.getSeconds().toString()),X[1]=X[1].replace("?",Y.getMinutes().toString()),X[2]=X[2].replace("?",Y.getHours().toString()),this.starDOM||(X[3]=X[3].replace("?",Y.getDate().toString())),X[4]=X[4].replace("?",(Y.getMonth()+1).toString()),this.starDOW||(X[5]=X[5].replace("?",Y.getDay().toString()))}this.throwAtIllegalCharacters(X),this.partToArray("second",X[0],0,1),this.partToArray("minute",X[1],0,1),this.partToArray("hour",X[2],0,1),this.partToArray("day",X[3],-1,1),this.partToArray("month",X[4],-1,1),this.partToArray("dayOfWeek",X[5],0,IT),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(X,Y,Q,J){let G=this[X],W=X==="day"&&this.lastDayOfMonth;if(Y===""&&!W)throw TypeError("CronPattern: configuration entry "+X+" ("+Y+") is empty, check for trailing spaces.");if(Y==="*")return G.fill(J);let Z=Y.split(",");if(Z.length>1)for(let $=0;$<Z.length;$++)this.partToArray(X,Z[$],Q,J);else Y.indexOf("-")!==-1&&Y.indexOf("/")!==-1?this.handleRangeWithStepping(Y,X,Q,J):Y.indexOf("-")!==-1?this.handleRange(Y,X,Q,J):Y.indexOf("/")!==-1?this.handleStepping(Y,X,Q,J):Y!==""&&this.handleNumber(Y,X,Q,J)}throwAtIllegalCharacters(X){for(let Y=0;Y<X.length;Y++)if((Y===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(X[Y]))throw TypeError("CronPattern: configuration entry "+Y+" ("+X[Y]+") contains illegal characters.")}handleNumber(X,Y,Q,J){let G=this.extractNth(X,Y),W=parseInt(G[0],10)+Q;if(isNaN(W))throw TypeError("CronPattern: "+Y+" is not a number: '"+X+"'");this.setPart(Y,W,G[1]||J)}setPart(X,Y,Q){if(!Object.prototype.hasOwnProperty.call(this,X))throw TypeError("CronPattern: Invalid part specified: "+X);if(X==="dayOfWeek"){if(Y===7&&(Y=0),Y<0||Y>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Y);this.setNthWeekdayOfMonth(Y,Q);return}if(X==="second"||X==="minute"){if(Y<0||Y>=60)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="hour"){if(Y<0||Y>=24)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="day"){if(Y<0||Y>=31)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="month"&&(Y<0||Y>=12))throw RangeError("CronPattern: Invalid value for "+X+": "+Y);this[X][Y]=Q}handleRangeWithStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+X+"'");let[,Z,$,K]=W,H=parseInt(Z,10)+Q,F=parseInt($,10)+Q,V=parseInt(K,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Y].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Y].length+")");if(H>F)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let q=H;q<=F;q+=V)this.setPart(Y,q,G[1]||J)}extractNth(X,Y){let Q=X,J;if(Q.includes("#")){if(Y!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Q.split("#")[1],Q=Q.split("#")[0]}return[Q,J]}handleRange(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+X+"'");let Z=parseInt(W[0],10)+Q,$=parseInt(W[1],10)+Q;if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Z>$)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let K=Z;K<=$;K++)this.setPart(Y,K,G[1]||J)}handleStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+X+"'");W[0]===""&&(W[0]="*");let Z=0;W[0]!=="*"&&(Z=parseInt(W[0],10)+Q);let $=parseInt(W[1],10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[Y].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Y].length+")");for(let K=Z;K<this[Y].length;K+=$)this.setPart(Y,K,G[1]||J)}replaceAlphaDays(X){return X.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(X){return X.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(X){let Y=X.trim().toLowerCase();return Y==="@yearly"||Y==="@annually"?"0 0 1 1 *":Y==="@monthly"?"0 0 1 * *":Y==="@weekly"?"0 0 * * 0":Y==="@daily"?"0 0 * * *":Y==="@hourly"?"0 * * * *":X}setNthWeekdayOfMonth(X,Y){if(typeof Y!="number"&&Y==="L")this.dayOfWeek[X]=this.dayOfWeek[X]|OY0;else if(Y===IT)this.dayOfWeek[X]=IT;else if(Y<6&&Y>0)this.dayOfWeek[X]=this.dayOfWeek[X]|Y$6[Y-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Y}, Type: ${typeof Y}`)}},eZ6,UZ,G5=class X{tz;ms;second;minute;hour;day;month;year;constructor(Y,Q){if(this.tz=Q,Y&&Y instanceof Date)if(!isNaN(Y))this.fromDate(Y);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Y===void 0)this.fromDate(new Date);else if(Y&&typeof Y=="string")this.fromString(Y);else if(Y instanceof X)this.fromCronDate(Y);else throw TypeError("CronDate: Invalid type ("+typeof Y+") passed to CronDate constructor")}isNthWeekdayOfMonth(Y,Q,J,G){let W=new Date(Date.UTC(Y,Q,J)).getUTCDay(),Z=0;for(let $=1;$<=J;$++)new Date(Date.UTC(Y,Q,$)).getUTCDay()===W&&Z++;if(G&IT&&Y$6[Z-1]&G)return!0;if(G&OY0){let $=new Date(Date.UTC(Y,Q+1,0)).getUTCDate();for(let K=J+1;K<=$;K++)if(new Date(Date.UTC(Y,Q,K)).getUTCDay()===W)return!1;return!0}return!1}fromDate(Y){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes()+this.tz,this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),this.apply();else{let Q=JY.toTZ(Y,this.tz);this.ms=Y.getMilliseconds(),this.second=Q.s,this.minute=Q.i,this.hour=Q.h,this.day=Q.d,this.month=Q.m-1,this.year=Q.y}else this.ms=Y.getMilliseconds(),this.second=Y.getSeconds(),this.minute=Y.getMinutes(),this.hour=Y.getHours(),this.day=Y.getDate(),this.month=Y.getMonth(),this.year=Y.getFullYear()}fromCronDate(Y){this.tz=Y.tz,this.year=Y.year,this.month=Y.month,this.day=Y.day,this.hour=Y.hour,this.minute=Y.minute,this.second=Y.second,this.ms=Y.ms}apply(){if(this.month>11||this.day>eZ6[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Y=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes(),this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),!0}else return!1}fromString(Y){if(typeof this.tz=="number"){let Q=JY.fromTZISO(Y);this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply()}else return this.fromDate(JY.fromTZISO(Y,this.tz))}findNext(Y,Q,J,G){let W=this[Q],Z;J.lastDayOfMonth&&(this.month!==1?Z=eZ6[this.month]:Z=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let $=!J.starDOW&&Q=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let K=this[Q]+G;K<J[Q].length;K++){let H=J[Q][K];if(Q==="day"&&J.lastDayOfMonth&&K-G==Z&&(H=1),Q==="day"&&!J.starDOW){let F=J.dayOfWeek[($+(K-G-1))%7];if(F&&F&IT)F=this.isNthWeekdayOfMonth(this.year,this.month,K-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Y.legacyMode&&!J.starDOM?H=H||F:H=H&&F}if(H)return this[Q]=K-G,W!==this[Q]?2:1}return 3}recurse(Y,Q,J){let G=this.findNext(Q,UZ[J][0],Y,UZ[J][2]);if(G>1){let W=J+1;for(;W<UZ.length;)this[UZ[W][0]]=-UZ[W][2],W++;if(G===3)return this[UZ[J][1]]++,this[UZ[J][0]]=-UZ[J][2],this.apply(),this.recurse(Y,Q,0);if(this.apply())return this.recurse(Y,Q,J-1)}return J+=1,J>=UZ.length?this:this.year>=3000?null:this.recurse(Y,Q,J)}increment(Y,Q,J){return this.second+=Q.interval!==void 0&&Q.interval>1&&J?Q.interval:1,this.ms=0,this.apply(),this.recurse(Y,Q,0)}getDate(Y){return Y||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):JY.fromTZ(JY.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},X$6=30000,zf,Uf=class{name;options;_states;fn;constructor(X,Y,Q){let J,G;if(CT(Y))G=Y;else if(typeof Y=="object")J=Y;else if(Y!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(CT(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=tx1(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new tZ6("* * * * *")},X&&(X instanceof Date||typeof X=="string"&&X.indexOf(":")>0)?this._states.once=new G5(X,this.options.timezone||this.options.utcOffset):this._states.pattern=new tZ6(X,this.options.timezone),this.name){if(zf.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");zf.push(this)}return G!==void 0&&ex1(G)&&(this.fn=G,this.schedule()),this}nextRun(X){let Y=this._next(X);return Y?Y.getDate(!1):null}nextRuns(X,Y){this._states.maxRuns!==void 0&&X>this._states.maxRuns&&(X=this._states.maxRuns);let Q=[],J=Y||this._states.currentRun||void 0;for(;X--&&(J=this.nextRun(J));)Q.push(J);return Q}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let X=this.nextRun(this._states.currentRun),Y=!this._states.paused,Q=this.fn!==void 0,J=!this._states.kill;return Y&&Q&&J&&X!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(X){let Y=this._next(X);return Y?X instanceof G5||X instanceof Date?Y.getTime()-X.getTime():Y.getTime()-new G5(X).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let X=zf.indexOf(this);X>=0&&zf.splice(X,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(X){if(X&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");X&&(this.fn=X);let Y=this.msToNext(),Q=this.nextRun(this._states.currentRun);return Y==null||isNaN(Y)||Q===null?this:(Y>X$6&&(Y=X$6),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),Y),this._states.currentTimeout&&this.options.unref&&Xg1(this._states.currentTimeout),this)}async _trigger(X){if(this._states.blocking=!0,this._states.currentRun=new G5(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Y){CT(this.options.catch)&&this.options.catch(Y,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new G5(X,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(X){let Y=new Date,Q=!this._states.paused&&Y.getTime()>=X.getTime(),J=this._states.blocking&&this.options.protect;Q&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Q&&J&&CT(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(X){let Y=!!(X||this._states.currentRun),Q=!1;!X&&this.options.startAt&&this.options.interval&&([X,Y]=this._calculatePreviousRun(X,Y),Q=!X),X=new G5(X,this.options.timezone||this.options.utcOffset),this.options.startAt&&X&&X.getTime()<this.options.startAt.getTime()&&(X=this.options.startAt);let J=this._states.once||new G5(X,this.options.timezone||this.options.utcOffset);return!Q&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Y)),this._states.once&&this._states.once.getTime()<=X.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(X,Y){let Q=new G5(void 0,this.options.timezone||this.options.utcOffset),J=X;if(this.options.startAt.getTime()<=Q.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Q.getTime();)J=new G5(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Y=!0}return J===null&&(J=void 0),[J,Y]}};var LY0=v(()=>{JY.fromTZISO=(X,Y,Q)=>JY.fromTZ(sx1(X,Y),Q);JY.fromTZ=function(X,Y){let Q=new Date(Date.UTC(X.y,X.m-1,X.d,X.h,X.i,X.s)),J=NY0(X.tz,Q),G=new Date(Q.getTime()-J),W=NY0(X.tz,G);if(W-J===0)return G;{let Z=new Date(Q.getTime()-W),$=NY0(X.tz,Z);if($-W===0)return Z;if(!Y&&$-W>0)return Z;if(Y)throw Error("Invalid date passed to fromTZ()");return G}};JY.toTZ=function(X,Y){let Q=X.toLocaleString("en-US",{timeZone:Y}).replace(/[\u202f]/," "),J=new Date(Q);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Y}};JY.tp=(X,Y,Q,J,G,W,Z)=>({y:X,m:Y,d:Q,h:J,i:G,s:W,tz:Z});JY.minitz=JY;IT=31|OY0,Y$6=[1,2,4,8,16],eZ6=[31,28,31,30,31,30,31,31,30,31,30,31],UZ=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];zf=[]});var Bf;var wY0=v(()=>{Bf={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function Q$6(){return async(X,Y)=>{try{let Q=await SK.create(),J=await mZ6(X,{...Q,auth:{...Q.auth,user:{id:"notify-worker"}}}),W=await c90.forClient(J).ON_EVENTS({events:Y});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(Q){let J=Q instanceof Error?Q.message:String(Q);return console.error(`[EventBus] Failed to notify connection ${X}:`,J),{success:!1,error:J}}}}var J$6=v(()=>{Vf();cb();qf()});function G$6(X){return{specversion:"1.0",id:X.id,source:X.source,type:X.type,time:X.time,subject:X.subject??void 0,datacontenttype:X.datacontenttype,dataschema:X.dataschema??void 0,data:X.data??void 0}}function Yg1(X){let Y=new Map;for(let J of X){let G=J.subscription.connectionId,W=Y.get(G);if(W){if(W.deliveryIds.push(J.delivery.id),!W.seenEventIds.has(J.event.id))W.seenEventIds.add(J.event.id),W.events.push(G$6(J.event))}else Y.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[G$6(J.event)],seenEventIds:new Set([J.event.id])})}let Q=new Map;for(let[J,G]of Y)Q.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Q}class MY0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(X,Y){this.storage=X;this.notifySubscriber=Q$6(),this.config={...Bf,...Y}}async start(){if(this.running)return;let X=await this.storage.resetStuckDeliveries();if(X>0)console.log(`[EventBus] Reset ${X} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(X){console.error("[EventBus] Error processing events:",X)}finally{this.processing=!1}}async processEvents(){let X=await this.storage.claimPendingDeliveries(this.config.batchSize);if(X.length===0)return;let Y=Yg1(X),Q=new Set;for(let[J,G]of Y){try{let W=await this.notifySubscriber(G.connectionId,G.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(G,W);else if(W.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let Z=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${J}:`,Z),await this.storage.markDeliveriesFailed(G.deliveryIds,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of X)if(G.deliveryIds.includes(W.delivery.id))Q.add(W.event.id)}for(let J of Q)try{await this.storage.updateEventStatus(J);let G=X.find((W)=>W.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(X,Y){let Q=[],J=new Map,G=[],W=new Map;for(let Z=0;Z<X.events.length;Z++){let $=X.events?.[Z];if(!$)continue;let K=X.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of X.events){let $=W.get(Z.id);if(!$)continue;let K=Y.results?.[Z.id];if(K)if(K.success)Q.push($);else if(K.retryAfter&&K.retryAfter>0){let H=J.get(K.retryAfter)||[];H.push($),J.set(K.retryAfter,H)}else G.push({deliveryId:$,error:K.error||"Event processing failed"});else if(Y.success)Q.push($);else if(Y.retryAfter&&Y.retryAfter>0){let H=J.get(Y.retryAfter)||[];H.push($),J.set(Y.retryAfter,H)}else G.push({deliveryId:$,error:Y.error||"Batch processing failed"})}if(Q.length>0)await this.storage.markDeliveriesDelivered(Q);for(let[Z,$]of J)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(G.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of G){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(X){if(!X.cron)return;try{let Q=new Uf(X.cron).nextRun();if(!Q){console.log(`[EventBus] Cron expression for event ${X.id} has no more runs`);return}let J=Q.toISOString(),G=await this.storage.getMatchingSubscriptions(X);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${X.id}, skipping next delivery`);return}await this.storage.createDeliveries(X.id,G.map((W)=>W.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${X.id} at ${J}`)}catch(Y){console.error(`[EventBus] Failed to schedule next cron delivery for event ${X.id}:`,Y)}}}var W$6=v(()=>{LY0();wY0();J$6()});class PY0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new MY0(this.storage,X.config)}async publish(X,Y,Q){if(Q.deliverAt&&Q.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Q.cron){try{let F=new Uf(Q.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(X,Q.type,Y,Q.cron);if(K)return K}let G=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:G,organizationId:X,type:Q.type,source:Y,subject:Q.subject,time:W,data:Q.data,cron:Q.cron}),$=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=Q.deliverAt??J;if(await this.storage.createDeliveries(G,$.map((H)=>H.id),K),this.notifyStrategy&&!K)await this.notifyStrategy.notify(G).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return Z}async subscribe(X,Y){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:X,connectionId:Y.connectionId,publisher:Y.publisher,eventType:Y.eventType,filter:Y.filter})}async unsubscribe(X,Y){return this.storage.unsubscribe(Y,X)}async listSubscriptions(X,Y){return this.storage.listSubscriptions(X,Y)}async getSubscription(X,Y){return this.storage.getSubscription(Y,X)}async getEvent(X,Y){return this.storage.getEvent(Y,X)}async cancelEvent(X,Y,Q){return this.storage.cancelEvent(Y,X,Q)}async ackEvent(X,Y,Q){return this.storage.ackDelivery(Y,X,Q)}async syncSubscriptions(X,Y){return this.storage.syncSubscriptions({organizationId:X,...Y})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing after notify:",X)})});await this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing pending events on startup:",X)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(X){console.error("[EventBus] Error stopping notify strategy:",X)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}var Z$6=v(()=>{LY0();W$6()});function $$6(...X){return{async start(Y){await Promise.all(X.map((Q)=>Q.start(Y)))},async stop(){await Promise.all(X.map((Y)=>Y.stop().catch((Q)=>{console.error("[NotifyStrategy] Error stopping strategy:",Q)})))},async notify(Y){await Promise.all(X.map((Q)=>Q.notify(Y).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class Df{intervalMs;timer=null;onNotify=null;constructor(X){this.intervalMs=X}async start(X){if(this.timer)return;this.onNotify=X,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(X){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Qg1}from"kysely";class TY0{db;pool;listenClient=null;onNotify=null;constructor(X,Y){this.db=X;this.pool=Y}async start(X){if(this.listenClient)return;this.onNotify=X;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Y)=>{if(Y.channel===kB&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Y)=>{console.error("[PostgresNotify] Connection error:",Y),this.cleanup()}),await this.listenClient.query(`LISTEN ${kB}`),console.log("[PostgresNotify] Started LISTEN on",kB)}catch(Y){console.error("[PostgresNotify] Failed to start LISTEN:",Y),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${kB}`),console.log("[PostgresNotify] Stopped LISTEN on",kB)}catch{}this.cleanup()}}async notify(X){try{await Qg1`SELECT pg_notify(${kB}, ${X})`.execute(this.db)}catch(Y){console.warn("[PostgresNotify] Failed to send NOTIFY:",Y)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var kB="mesh_events";var K$6=()=>{};function H$6(X,Y){let Q=sZ6(X.db),J=Y?.pollIntervalMs??Bf.pollIntervalMs,G=X.type==="postgres"?$$6(new Df(J),new TY0(X.db,X.pool)):new Df(J);return new PY0({storage:Q,config:Y,notifyStrategy:G})}var F$6=v(()=>{Z$6();wY0();K$6()});var V$6;var q$6=v(()=>{V$6={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var z$6,U$6;var B$6=v(()=>{k7();EB();q$6();z$6=new C9;z$6.get("/config",async(X)=>{try{let Y=Object.keys(X9.socialProviders??{}),Q=Y.length>0,J=Y.map((Z)=>({name:Z,icon:V$6[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:X9.emailAndPassword?.enabled??!1},magicLink:{enabled:X9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:X9.ssoConfig?{enabled:!0,providerId:X9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return X.json({success:!0,config:W})}catch(Y){let Q=Y instanceof Error?Y.message:"Failed to load auth config";return X.json({success:!1,error:Q},500)}});U$6=z$6});var Nf,D$6;var N$6=v(()=>{k7();ab();Nf=new C9;Nf.post("/connections/:connectionId/oauth-token",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("connectionId");if(!(Y.auth.user?.id??Y.auth.apiKey?.userId??null))return X.json({error:"Unauthorized"},401);if(!await Y.storage.connections.findById(Q,Y.organization?.id))return X.json({error:"Connection not found"},404);let W=await X.req.json();if(!W.accessToken)return X.json({error:"accessToken is required"},400);if(W.tokenEndpoint){let F;try{F=new URL(W.tokenEndpoint)}catch{return X.json({error:"tokenEndpoint must be a valid URL"},400)}if(F.protocol!=="http:"&&F.protocol!=="https:")return X.json({error:"tokenEndpoint must be an http(s) URL"},400)}let Z=W.expiresIn?new Date(Date.now()+W.expiresIn*1000):null,$=new qZ(Y.db,Y.vault),K={connectionId:Q,accessToken:W.accessToken,refreshToken:W.refreshToken??null,scope:W.scope??null,expiresAt:Z,clientId:W.clientId??null,clientSecret:W.clientSecret??null,tokenEndpoint:W.tokenEndpoint??null},H=await $.upsert(K);return X.json({success:!0,expiresAt:H.expiresAt})});Nf.delete("/connections/:connectionId/oauth-token",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("connectionId");if(!(Y.auth.user?.id??Y.auth.apiKey?.userId??null))return X.json({error:"Unauthorized"},401);return await new qZ(Y.db,Y.vault).delete(Q),X.json({success:!0})});Nf.get("/connections/:connectionId/oauth-token/status",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("connectionId");if(!(Y.auth.user?.id??Y.auth.apiKey?.userId??null))return X.json({error:"Unauthorized"},401);let G=new qZ(Y.db,Y.vault),W=await G.get(Q);if(!W)return X.json({hasToken:!1,isExpired:!0,canRefresh:!1});let Z=G.isExpired(W),$=!!W.refreshToken&&!!W.tokenEndpoint;return X.json({hasToken:!0,isExpired:Z,canRefresh:$,expiresAt:W.expiresAt})});D$6=Nf});function O$6(X){let Y=U.object({query:U.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:U.number().default(10).describe("Maximum results to return (default: 10)")}),Q=rP(X.tools);return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling GATEWAY_DESCRIBE_TOOLS for detailed schemas.${X.categories.length>0?` Available categories: ${X.categories.join(", ")}.`:""} Total tools: ${Q.length}.`,inputSchema:U.toJSONSchema(Y)},handler:async(G)=>{let W=Y.safeParse(G);if(!W.success)return MB({error:W.error.flatten()});let Z=hb(W.data.query,Q,W.data.limit);return ub({query:W.data.query,results:Z.map(($)=>({name:$.name,description:$.description,connection:$._meta.connectionTitle})),totalAvailable:Q.length})}}}function L$6(X){let Y=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),Q=rP(X.tools);return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:U.toJSONSchema(Y)},handler:async(J)=>{let G=Y.safeParse(J);if(!G.success)return MB({error:G.error.flatten()});let W=xb(G.data.tools,Q);return ub({tools:W.tools,notFound:W.notFound})}}}function Jg1(X){let Y=rP(X.tools),Q=Y.map((W)=>W.name),J=new Map(Y.map((W)=>[W.name,W])),G=U.object({name:(Q.length>0?U.enum(Q):U.string()).describe("The name of the tool to execute"),arguments:U.record(U.string(),U.unknown()).default({}).describe("Arguments to pass to the tool")});return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:U.toJSONSchema(G)},handler:async(W)=>{let Z=G.safeParse(W);if(!Z.success)return MB({error:Z.error.flatten()});let{name:$,arguments:K}=Z.data;if(!J.has($))return{content:[{type:"text",text:`Tool not found: ${$}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return X.callTool($,K)}}}function Gg1(X){let Y=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),Q=rP(X.tools);return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:U.toJSONSchema(Y)},handler:async(J)=>{let G=Y.safeParse(J);if(!G.success)return MB({error:G.error.flatten()});let W={...X,tools:Q},Z=await gb(G.data.code,W,G.data.timeoutMs);if(Z.error)return MB(Z);return ub(Z)}}}function w$6(X){let Y=new Map(X.map((J)=>[J.tool.name,J.handler])),Q=X.map((J)=>J.tool.name);return{tools:X.map((J)=>J.tool),callTool:async(J,G)=>{let W=Y.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Q.join(", ")}`}],isError:!0};return W(G)}}}function M$6(X){switch(X){case"smart_tool_selection":return $g1;case"code_execution":return Zg1;case"passthrough":default:return Wg1}}function P$6(X){switch(X){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}var Wg1=(X)=>({tools:X.tools,callTool:(Y,Q)=>X.callTool(Y,Q)}),Zg1=(X)=>w$6([O$6(X),L$6(X),Gg1(X)]),$g1=(X)=>w$6([O$6(X),L$6(X),Jg1(X)]);var AY0=v(()=>{X6();oP()});class Of{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=v7(()=>this.loadTools())}async loadTools(){let X=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){if(!(F instanceof G6)||F.code!==H6.MethodNotFound)console.error(`[aggregator] Failed to list tools ${H}: (defaulting to null)`,F);return null}}),Y=new Set,Q=[],J=new Map,G=new Set;for(let K of X){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(Y.has(q.name))continue;Y.add(q.name),Q.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=M$6(this.options.strategy)({tools:Q,callTool:W,categories:Array.from(G).sort()});return{tools:Q,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(X){return(await this.cache).strategyResult.callTool(X.name,X.arguments??{})}async callStreamable(X,Y){let Q=await this.cache,J=Q.mappings.get(X);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,Y)}let G=await Q.strategyResult.callTool(X,Y);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}var T$6=v(()=>{E9();AY0()});function Kg1(X,Y){if(X===Y)return!0;if(!Y.includes("*"))return!1;let Q=Y.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Q=`^${Q}$`;try{return new RegExp(Q).test(X)}catch{return!1}}function A$6(X,Y){return Y.some((Q)=>Kg1(X,Q))}class Lf{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=v7(()=>this.loadResources())}async loadResources(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!A$6(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>A$6(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){if(!(Z instanceof G6)||Z.code!==H6.MethodNotFound)console.error(`[aggregator] Failed to list resources for connection ${W}: (defaulting to empty array)`,Z);return{connectionId:W,resources:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(Y.has($.uri))continue;Y.add($.uri),Q.push($),J.set($.uri,W)}}return{resources:Q,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(X){let Q=(await this.cache).mappings.get(X.uri);if(!Q)throw Error(`Resource not found: ${X.uri}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for resource: ${X.uri}`);return await J.proxy.client.readResource(X)}}var E$6=v(()=>{E9()});class wf{proxies;cache;constructor(X){this.proxies=X;this.cache=v7(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let X=await this.proxies.mapSettled(async(Q,J)=>{try{let G=await Q.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){if(!(G instanceof G6)||G.code!==H6.MethodNotFound)console.error(`[aggregator] Failed to list resource templates for connection ${J}: (defaulting to empty array)`,G);return{connectionId:J,templates:[]}}}),Y=[];for(let Q of X){if(Q.status!=="fulfilled")continue;let{templates:J}=Q.value;for(let G of J)Y.push(G)}return{templates:Y}}async list(){return{resourceTemplates:(await this.cache).templates}}}var j$6=v(()=>{E9()});class Mf{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=v7(()=>this.loadPrompts())}async loadPrompts(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptAggregator] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(Y.has($.name))continue;Y.add($.name),Q.push($),J.set($.name,W)}}return{prompts:Q,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(X){let Q=(await this.cache).mappings.get(X.name);if(!Q)throw Error(`Prompt not found: ${X.name}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for prompt: ${X.name}`);return await J.proxy.client.getPrompt(X)}}var C$6=()=>{};var I$6=v(()=>{T$6();E$6();j$6();C$6()});async function Hg1(X,Y){let Q=await SF.create(X.connections,Y),J=new Of(Q,{selectionMode:X.toolSelectionMode,strategy:X.toolSelectionStrategy}),G=new Lf(Q,{selectionMode:X.toolSelectionMode}),W=new wf(Q),Z=new Mf(Q,{selectionMode:X.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function Fg1(X,Y,Q){let J;if(X.tool_selection_mode==="exclusion"){let Z=(await Y.storage.connections.list(X.organization_id)).filter((K)=>K.status==="active"),$=new Map;for(let K of X.connections)$.set(K.connection_id,{selectedTools:K.selected_tools,selectedResources:K.selected_resources,selectedPrompts:K.selected_prompts});J=[];for(let K of Z){let H=$.get(K.id);if(H===void 0)J.push({connection:K,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((H.selectedTools===null||H.selectedTools.length===0)&&(H.selectedResources===null||H.selectedResources.length===0)&&(H.selectedPrompts===null||H.selectedPrompts.length===0));else J.push({connection:K,selectedTools:H.selectedTools,selectedResources:H.selectedResources,selectedPrompts:H.selectedPrompts})}}else{let W=X.connections.map(($)=>$.connection_id),Z=[];for(let $ of W){let K=await Y.storage.connections.findById($);if(K&&K.status==="active")Z.push(K)}J=Z.map(($)=>{let K=X.connections.find((H)=>H.connection_id===$.id);return{connection:$,selectedTools:K?.selected_tools??null,selectedResources:K?.selected_resources??null,selectedPrompts:K?.selected_prompts??null}})}let G={connections:J,toolSelectionMode:X.tool_selection_mode,toolSelectionStrategy:Q};return Hg1(G,Y)}async function R$6(X,Y){let Q=X.get("meshContext");try{let J=X.req.header("x-org-id"),G=X.req.header("x-org-slug"),W=J?J:G?await Q.db.selectFrom("organization").select("id").where("slug","=",G).executeTakeFirst().then((z)=>z?.id):null,Z=Y?await Q.storage.virtualMcps.findById(Y):W?j16(W):null;if(!Z)return X.json({error:"Agent not found"},404);if(W&&Z.organization_id!==W)return X.json({error:"Agent not found"},404);if(Q.virtualMcpId=Z.id,Z.status!=="active")return X.json({error:`Agent is inactive: ${Z.id}`},503);let $=await Q.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",Z.organization_id).executeTakeFirst();if($)Q.organization={id:$.id,slug:$.slug,name:$.name};let K=X.req.query("mode"),H=P$6(K),F=await Fg1(Z,Q,H),V=new IF({name:`mcp-virtual-mcp-${Z.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),q=new RF({enableJsonResponse:X.req.header("Accept")?.includes("application/json")??!1});return await V.connect(q),V.server.setRequestHandler(UK,async(z)=>{return F.client.listTools()}),V.server.setRequestHandler(E7,async(z)=>{return await F.client.callTool(z.params)}),V.server.setRequestHandler(HK,async()=>{return F.client.listResources()}),V.server.setRequestHandler(VK,async(z)=>{return F.client.readResource(z.params)}),V.server.setRequestHandler(FK,async()=>{return F.client.listResourceTemplates()}),V.server.setRequestHandler(qK,async()=>{return F.client.listPrompts()}),V.server.setRequestHandler(zK,async(z)=>{return F.client.getPrompt(z.params)}),await q.handleRequest(X.req.raw)}catch(J){let G=J;return console.error("[virtual-mcp] Error handling virtual MCP request:",G),X.json({error:"Internal server error",message:G.message},500)}}var EY0,S$6;var k$6=v(()=>{kb();vb();E9();k7();I$6();AY0();JK();EY0=new C9;EY0.all("/gateway/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return R$6(X,Y)});EY0.all("/virtual-mcp/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return R$6(X,Y)});S$6=EY0});var v$6,_$6;var y$6=v(()=>{k7();gX0();v$6=new C9;v$6.all("/",async(X)=>{return xX0(X.get("meshContext")).fetch(X.req.raw)});_$6=v$6});function XG(X){if(X==null)return"unknown error";if(typeof X==="string")return X;if(X instanceof Error)return X.message;return JSON.stringify(X)}var HK6="vercel.ai.error",Vg1,b$6,f$6,N6,FK6="AI_APICallError",VK6,qg1,h$6,x$6,Y9,qK6="AI_EmptyResponseBodyError",zK6,zg1,g$6,u$6,UK6,BK6="AI_InvalidArgumentError",DK6,Ug1,m$6,l$6,NK6,OK6="AI_InvalidPromptError",LK6,Bg1,d$6,p$6,pF,wK6="AI_InvalidResponseDataError",MK6,Dg1,c$6,n$6,Ut4,PK6="AI_JSONParseError",TK6,Ng1,i$6,a$6,RT,AK6="AI_LoadAPIKeyError",EK6,Og1,r$6,o$6,Bt4,jK6="AI_LoadSettingError",CK6,Lg1,s$6,t$6,Dt4,IK6="AI_NoContentGeneratedError",RK6,wg1,e$6,XK6,Nt4,SK6="AI_NoSuchModelError",kK6,Mg1,YK6,QK6,Ot4,vK6="AI_TooManyEmbeddingValuesForCallError",_K6,Pg1,JK6,GK6,Lt4,yK6="AI_TypeValidationError",bK6,Tg1,WK6,ZK6,YG,fK6="AI_UnsupportedFunctionalityError",hK6,Ag1,$K6,KK6,xK6;var P4=v(()=>{Vg1=Symbol.for(HK6),N6=class X extends(f$6=Error,b$6=Vg1,f$6){constructor({name:Y,message:Q,cause:J}){super(Q);this[b$6]=!0,this.name=Y,this.cause=J}static isInstance(Y){return X.hasMarker(Y,HK6)}static hasMarker(Y,Q){let J=Symbol.for(Q);return Y!=null&&typeof Y==="object"&&J in Y&&typeof Y[J]==="boolean"&&Y[J]===!0}},VK6=`vercel.ai.error.${FK6}`,qg1=Symbol.for(VK6),Y9=class extends(x$6=N6,h$6=qg1,x$6){constructor({message:X,url:Y,requestBodyValues:Q,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:FK6,message:X,cause:Z});this[h$6]=!0,this.url=Y,this.requestBodyValues=Q,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(X){return N6.hasMarker(X,VK6)}},zK6=`vercel.ai.error.${qK6}`,zg1=Symbol.for(zK6),UK6=class extends(u$6=N6,g$6=zg1,u$6){constructor({message:X="Empty response body"}={}){super({name:qK6,message:X});this[g$6]=!0}static isInstance(X){return N6.hasMarker(X,zK6)}};DK6=`vercel.ai.error.${BK6}`,Ug1=Symbol.for(DK6),NK6=class extends(l$6=N6,m$6=Ug1,l$6){constructor({message:X,cause:Y,argument:Q}){super({name:BK6,message:X,cause:Y});this[m$6]=!0,this.argument=Q}static isInstance(X){return N6.hasMarker(X,DK6)}},LK6=`vercel.ai.error.${OK6}`,Bg1=Symbol.for(LK6),pF=class extends(p$6=N6,d$6=Bg1,p$6){constructor({prompt:X,message:Y,cause:Q}){super({name:OK6,message:`Invalid prompt: ${Y}`,cause:Q});this[d$6]=!0,this.prompt=X}static isInstance(X){return N6.hasMarker(X,LK6)}},MK6=`vercel.ai.error.${wK6}`,Dg1=Symbol.for(MK6),Ut4=class extends(n$6=N6,c$6=Dg1,n$6){constructor({data:X,message:Y=`Invalid response data: ${JSON.stringify(X)}.`}){super({name:wK6,message:Y});this[c$6]=!0,this.data=X}static isInstance(X){return N6.hasMarker(X,MK6)}},TK6=`vercel.ai.error.${PK6}`,Ng1=Symbol.for(TK6),RT=class extends(a$6=N6,i$6=Ng1,a$6){constructor({text:X,cause:Y}){super({name:PK6,message:`JSON parsing failed: Text: ${X}.
1073
+ `})}}}ih1=[bi({organizationCreation:{afterCreate:async(X)=>{await s76(X.organization.id,X.member.userId)}},ac:sb,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:e76,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:ph1,admin:ch1,owner:nh1},sendInvitationEmail:GW6}),Qa({loginPage:"/login",oidcConfig:{scopes:JW6,metadata:{scopes_supported:JW6},loginPage:"/login"}}),Ya({enableMetadata:!0,maximumNameLength:64,keyExpiration:{minExpiresIn:0.003472222222222222},enableSessionForAPIKeys:!0,customAPIKeyGetter:(X)=>{if(X.headers?.get("X-MCP-Session-Auth")==="true")return null;let Q=X.headers?.get("Authorization");if(Q?.startsWith("Bearer "))return Q.replace("Bearer ","").trim();return null},permissions:{defaultPermissions:{self:["ORGANIZATION_LIST","ORGANIZATION_GET","ORGANIZATION_MEMBER_LIST","COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","API_KEY_CREATE","API_KEY_LIST"]}},rateLimit:{enabled:!1}}),li({defaultRole:"user",adminRoles:["admin","owner"]}),Za(),ci({jwt:{expirationTime:"5m"}}),uU0(X9.ssoConfig?XW6(X9.ssoConfig):void 0),...X9.magicLinkConfig&&X9.emailProviders&&X9.emailProviders.length>0?[Wa(L16(X9.magicLinkConfig,X9.emailProviders))]:[]],ah1=e60(),rh1=N16(ah1),e5=bn({baseURL:process.env.BASE_URL||"http://localhost:3000",database:rh1,emailAndPassword:{enabled:!0},...X9,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:ih1,databaseHooks:{user:{create:{after:async(X)=>{if(bL.autoCreateOrganizationOnSignup===!1)return;let Y=X.name?X.name.split(" ")[0]:X.email.split("@")[0],Q=3;for(let J=0;J<Q;J++){let G=`${Y} ${mh1()}`,W=uh1(G);try{await e5.api.createOrganization({body:{name:G,slug:W,userId:X.id}});return}catch(Z){if(!(Z instanceof Error&&("body"in Z)&&Z.body?.code==="ORGANIZATION_ALREADY_EXISTS")||J===Q-1){console.error("Failed to create default organization:",Z);return}}}}}}}})});async function WW6(){console.log("\uD83D\uDD10 Running Better Auth migrations...");try{let{toBeAdded:X,toBeCreated:Y,runMigrations:Q}=await iN(e5.options);if(!X.length&&!Y.length){console.log("\u2705 Better Auth schema is up to date (no migrations needed)");return}console.log("\uD83D\uDCCB Better Auth will create/update the following tables:");for(let J of[...Y,...X])console.log(` - ${J.table}`);await Q(),console.log("\u2705 Better Auth migrations completed successfully")}catch(X){console.warn("\u26A0\uFE0F Better Auth migration failed (tables may be created on first use):",X)}}var ZW6=v(()=>{OW0();EB()});var HW6={};$1(HW6,{runSeed:()=>Vh,runKyselyMigrations:()=>KW6,migrateToLatest:()=>oh1,migrateDown:()=>sh1});import{Migrator as $W6}from"kysely";async function KW6(X){let Y=new $W6({db:X,provider:{getMigrations:()=>Promise.resolve(nT)}}),{error:Q,results:J}=await Y.migrateToLatest();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" executed successfully`);else if(G.status==="Error")console.error(`\u274C Failed to execute migration "${G.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q}async function oh1(X){let{keepOpen:Y=!1,database:Q,skipBetterAuth:J=!1,seed:G}=X??{};if(!J&&!Q)await WW6();let W=Q??FF(),Z=async()=>{if(!Y&&!Q)console.log("\uD83D\uDD12 Closing database connection..."),await O16(W).catch(($)=>{console.warn("Warning: Error closing database:",$)})};try{console.log("\uD83D\uDCCA Running Kysely migrations..."),await KW6(W.db),console.log("\uD83C\uDF89 All Kysely migrations completed successfully");let $;if(G)$=await Vh(W.db,G);return await Z(),{seedResult:$}}catch($){throw await Z(),$}}async function sh1(){let X=FF(),Y=new $W6({db:X.db,provider:{getMigrations:()=>Promise.resolve(nT)}}),{error:Q,results:J}=await Y.migrateDown();if(J?.forEach((G)=>{if(G.status==="Success")console.log(`\u2705 Migration "${G.migrationName}" rolled back successfully`);else if(G.status==="Error")console.error(`\u274C Failed to rollback migration "${G.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var FW6=v(()=>{Fh();_Q0();ZW6();hM()});var lX0;var dX0=v(()=>{lX0=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var VW6,th1,eh1=(X,Y)=>{if(!X)return{};let Q=new Headers(X.headers);if(Y){let J=Q.get("connection");if(J){let G=J.split(",").map((Z)=>Z.trim()),W=G.filter((Z)=>!th1.test(Z));if(W.length>0)throw new lX0(400,{message:`Invalid Connection header value: ${W.join(", ")}`});G.forEach((Z)=>{Q.delete(Z)})}}return VW6.forEach((J)=>{Q.delete(J)}),{method:X.method,body:X.body,duplex:X.body?"half":void 0,headers:Q,signal:X.signal}},Xx1=(X)=>{if(!X.headers||Array.isArray(X.headers)||X.headers instanceof Headers)return X;let Y=new Headers;for(let[Q,J]of Object.entries(X.headers))if(J==null)Y.delete(Q);else Y.set(Q,J);return X.headers=Y,X},qW6=async(X,Y)=>{let{raw:Q,customFetch:J,strictConnectionProcessing:G=!1,...W}=Y instanceof Request?{raw:Y}:Y??{},Z=new Request(X,{...eh1(Q,G),...Xx1(W)});Z.headers.delete("accept-encoding");let $=await(J||fetch)(Z),K=new Headers($.headers);if(VW6.forEach((H)=>{K.delete(H)}),K.has("content-encoding"))K.delete("content-encoding"),K.delete("content-length");return new Response($.body,{status:$.status,statusText:$.statusText,headers:K})};var zW6=v(()=>{dX0();VW6=["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"],th1=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});var UW6=(X)=>(Y)=>{let Q=new URL(Y.req.raw.url),J=new URL(X);return J.pathname=Q.pathname,J.search=Q.search,qW6(J,{raw:Y.req.raw,headers:{...Y.req.raw.headers}})};var BW6=v(()=>{zW6()});import{resolve as OT,dirname as Yx1}from"path";function Gx1(X,Y){let Q=OT(Y),J=OT(X);return J===Q||J.startsWith(Q+"/")}function Wx1({requestPath:X,clientDir:Y}){let Q=X.startsWith("/")?X.slice(1):X,J=OT(Y,Q);if(!Gx1(J,Y))return null;return J}function DW6(X,Y="../client"){let Q=new URL(X),J=Yx1(Q.pathname);return OT(J,Y)}function NW6(X={}){let{env:Y="production",devServerUrl:Q=Qx1,clientDir:J=Jx1,isServerPath:G=()=>!1}=X;if(Y==="development"){let W=UW6(Q);return async function($){let K=new URL($.url);if(G(K.pathname))return null;let H={req:{raw:$,url:$.url}};return W(H)}}return async function(Z){if(Z.method!=="GET")return null;let $=new URL(Z.url),K;try{K=decodeURIComponent($.pathname)}catch{return null}if(G(K))return null;let H=Wx1({requestPath:K,clientDir:J});if(!H)return null;let F=OT(J,"index.html");for(let V of[H,F])try{let q=Bun.file(V);if(await q.exists())return new Response(q)}catch{}return null}}var Qx1="http://localhost:4000",Jx1="./dist/client";var OW6=v(()=>{BW6()});var pX0=(X,Y,Q)=>{return(J,G)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,F;if(X[$])F=X[$][0][0],J.req.routeIndex=$;else F=$===X.length&&G||void 0;if(F)try{K=await F(J,()=>Z($+1))}catch(V){if(V instanceof Error&&Y)J.error=V,K=await Y(V,J),H=!0;else throw V}else if(J.finalized===!1&&Q)K=await Q(J);if(K&&(J.finalized===!1||H))J.res=K;return J}}};var LW6=()=>{};var wW6;var MW6=v(()=>{wW6=Symbol()});async function Zx1(X,Y){let Q=await X.formData();if(Q)return $x1(Q,Y);return{}}function $x1(X,Y){let Q=Object.create(null);if(X.forEach((J,G)=>{if(!(Y.all||G.endsWith("[]")))Q[G]=J;else Kx1(Q,G,J)}),Y.dot)Object.entries(Q).forEach(([J,G])=>{if(J.includes("."))Hx1(Q,J,G),delete Q[J]});return Q}var PW6=async(X,Y=Object.create(null))=>{let{all:Q=!1,dot:J=!1}=Y,W=(X instanceof tb?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Zx1(X,{all:Q,dot:J});return{}},Kx1=(X,Y,Q)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(Q);else X[Y]=[X[Y],Q];else if(!Y.endsWith("[]"))X[Y]=Q;else X[Y]=[Q]},Hx1=(X,Y,Q)=>{let J=X,G=Y.split(".");G.forEach((W,Z)=>{if(Z===G.length-1)J[W]=Q;else{if(!J[W]||typeof J[W]!=="object"||Array.isArray(J[W])||J[W]instanceof File)J[W]=Object.create(null);J=J[W]}})};var TW6=v(()=>{cX0()});var iX0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},AW6=(X)=>{let{groups:Y,path:Q}=Fx1(X),J=iX0(Q);return Vx1(J,Y)},Fx1=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(Q,J)=>{let G=`@${J}`;return Y.push([G,Q]),G}),{groups:Y,path:X}},Vx1=(X,Y)=>{for(let Q=Y.length-1;Q>=0;Q--){let[J]=Y[Q];for(let G=X.length-1;G>=0;G--)if(X[G].includes(J)){X[G]=X[G].replace(J,Y[Q][1]);break}}return X},eb,EW6=(X,Y)=>{if(X==="*")return"*";let Q=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(Q){let J=`${X}#${Y}`;if(!eb[J])if(Q[2])eb[J]=Y&&Y[0]!==":"&&Y[0]!=="*"?[J,Q[1],new RegExp(`^${Q[2]}(?=/${Y})`)]:[X,Q[1],new RegExp(`^${Q[2]}$`)];else eb[J]=[X,Q[1],!0];return eb[J]}return null},jB=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(Q)=>{try{return Y(Q)}catch{return Q}})}},qx1=(X)=>jB(X,decodeURI),aX0=(X)=>{let Y=X.url,Q=Y.indexOf("/",Y.indexOf(":")+4),J=Q;for(;J<Y.length;J++){let G=Y.charCodeAt(J);if(G===37){let W=Y.indexOf("?",J),Z=Y.slice(Q,W===-1?void 0:W);return qx1(Z.includes("%25")?Z.replace(/%25/g,"%2525"):Z)}else if(G===63)break}return Y.slice(Q,J)},jW6=(X)=>{let Y=aX0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},xF=(X,Y,...Q)=>{if(Q.length)Y=xF(Y,...Q);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},Xf=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),Q=[],J="";return Y.forEach((G)=>{if(G!==""&&!/\:/.test(G))J+="/"+G;else if(/\:/.test(G))if(/\?/.test(G)){if(Q.length===0&&J==="")Q.push("/");else Q.push(J);let W=G.replace("?","");J+="/"+W,Q.push(J)}else J+="/"+G}),Q.filter((G,W,Z)=>Z.indexOf(G)===W)},nX0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?jB(X,LT):X},CW6=(X,Y,Q)=>{let J;if(!Q&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return nX0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(J=/[%+]/.test(X),!J)return}let G={};J??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(J)K=nX0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),J)H=nX0(H);if(Q){if(!(G[K]&&Array.isArray(G[K])))G[K]=[];G[K].push(H)}else G[K]??=H}return Y?G[Y]:G},IW6,RW6=(X,Y)=>{return CW6(X,Y,!0)},LT;var gF=v(()=>{eb={},IW6=CW6,LT=decodeURIComponent});var SW6=(X)=>jB(X,LT),tb;var cX0=v(()=>{dX0();MW6();TW6();gF();tb=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",Q=[[]]){this.raw=X,this.path=Y,this.#Y=Q,this.#X={}}param(X){return X?this.#Q(X):this.#J()}#Q(X){let Y=this.#Y[0][this.routeIndex][1][X],Q=this.#W(Y);return Q&&/\%/.test(Q)?SW6(Q):Q}#J(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let Q of Y){let J=this.#W(this.#Y[0][this.routeIndex][1][Q]);if(J!==void 0)X[Q]=/\%/.test(J)?SW6(J):J}return X}#W(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return IW6(this.url,X)}queries(X){return RW6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((Q,J)=>{Y[J]=Q}),Y}async parseBody(X){return this.bodyCache.parsedBody??=await PW6(this,X)}#G=(X)=>{let{bodyCache:Y,raw:Q}=this,J=Y[X];if(J)return J;let G=Object.keys(Y)[0];if(G)return Y[G].then((W)=>{if(G==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=Q[X]()};json(){return this.#G("text").then((X)=>JSON.parse(X))}text(){return this.#G("text")}arrayBuffer(){return this.#G("arrayBuffer")}blob(){return this.#G("blob")}formData(){return this.#G("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[wW6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var kW6,zx1=(X,Y)=>{let Q=new String(X);return Q.isEscaped=!0,Q.callbacks=Y,Q},rX0=async(X,Y,Q,J,G)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(G)G[0]+=X;else G=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:G,context:J}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>rX0(K,Y,!1,J,G))).then(()=>G[0]));if(Q)return zx1(await Z,W);else return Z};var vW6=v(()=>{kW6={Stringify:1,BeforeStream:2,Stream:3}});var Ux1="text/plain; charset=UTF-8",oX0=(X,Y)=>{return{"Content-Type":X,...Y}},_W6=class{#X;#Y;env={};#Q;finalized=!1;error;#J;#W;#G;#$;#Z;#H;#K;#V;#q;constructor(X,Y){if(this.#X=X,Y)this.#W=Y.executionCtx,this.env=Y.env,this.#H=Y.notFoundHandler,this.#q=Y.path,this.#V=Y.matchResult}get req(){return this.#Y??=new tb(this.#X,this.#q,this.#V),this.#Y}get event(){if(this.#W&&"respondWith"in this.#W)return this.#W;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#W)return this.#W;else throw Error("This context has no ExecutionContext")}get res(){return this.#G||=new Response(null,{headers:this.#K??=new Headers})}set res(X){if(this.#G&&X){X=new Response(X.body,X);for(let[Y,Q]of this.#G.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let J=this.#G.headers.getSetCookie();X.headers.delete("set-cookie");for(let G of J)X.headers.append("set-cookie",G)}else X.headers.set(Y,Q)}}this.#G=X,this.finalized=!0}render=(...X)=>{return this.#Z??=(Y)=>this.html(Y),this.#Z(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#Z=X};header=(X,Y,Q)=>{if(this.finalized)this.#G=new Response(this.#G.body,this.#G);let J=this.#G?this.#G.headers:this.#K??=new Headers;if(Y===void 0)J.delete(X);else if(Q?.append)J.append(X,Y);else J.set(X,Y)};status=(X)=>{this.#J=X};set=(X,Y)=>{this.#Q??=new Map,this.#Q.set(X,Y)};get=(X)=>{return this.#Q?this.#Q.get(X):void 0};get var(){if(!this.#Q)return{};return Object.fromEntries(this.#Q)}#F(X,Y,Q){let J=this.#G?new Headers(this.#G.headers):this.#K??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")J.append(Z,$);else J.set(Z,$)}if(Q)for(let[W,Z]of Object.entries(Q))if(typeof Z==="string")J.set(W,Z);else{J.delete(W);for(let $ of Z)J.append(W,$)}let G=typeof Y==="number"?Y:Y?.status??this.#J;return new Response(X,{status:G,headers:J})}newResponse=(...X)=>this.#F(...X);body=(X,Y,Q)=>this.#F(X,Y,Q);text=(X,Y,Q)=>{return!this.#K&&!this.#J&&!Y&&!Q&&!this.finalized?new Response(X):this.#F(X,Y,oX0(Ux1,Q))};json=(X,Y,Q)=>{return this.#F(JSON.stringify(X),Y,oX0("application/json",Q))};html=(X,Y,Q)=>{let J=(G)=>this.#F(G,Y,oX0("text/html; charset=UTF-8",Q));return typeof X==="object"?rX0(X,kW6.Stringify,!1,{}).then(J):J(X)};redirect=(X,Y)=>{let Q=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(Q)?Q:encodeURI(Q)),this.newResponse(null,Y??302)};notFound=()=>{return this.#H??=()=>new Response,this.#H(this)}};var sX0=v(()=>{cX0();vW6()});var t4="ALL",yW6="all",bW6,Yf="Can not add a route since the matcher is already built.",Qf;var uF=v(()=>{bW6=["get","post","put","delete","options","patch"],Qf=class extends Error{}});var fW6="__COMPOSED_HANDLER";var hW6=()=>{};var Bx1=(X)=>{return X.text("404 Not Found",404)},xW6=(X,Y)=>{if("getResponse"in X){let Q=X.getResponse();return Y.newResponse(Q.body,Q)}return console.error(X),Y.text("Internal Server Error",500)},gW6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...bW6,yW6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#J(W,this.#X,Z);return $.forEach((K)=>{this.#J(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((F)=>{this.#J(H.toUpperCase(),this.#X,F)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#J(t4,this.#X,$)}),this};let{strict:J,...G}=Y;Object.assign(this,G),this.getPath=J??!0?Y.getPath??aX0:jW6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#Q=this.#Q,Y.routes=this.routes,Y}#Q=Bx1;errorHandler=xW6;route(Y,Q){let J=this.basePath(Y);return Q.routes.map((G)=>{let W;if(Q.errorHandler===xW6)W=G.handler;else W=async(Z,$)=>(await pX0([],Q.errorHandler)(Z,()=>G.handler(Z,$))).res,W[fW6]=G.handler;J.#J(G.method,G.path,W)}),this}basePath(Y){let Q=this.#Y();return Q._basePath=xF(this._basePath,Y),Q}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#Q=Y,this};mount(Y,Q,J){let G,W;if(J)if(typeof J==="function")W=J;else if(W=J.optionHandler,J.replaceRequest===!1)G=(K)=>K;else G=J.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};G||=(()=>{let K=xF(this._basePath,Y),H=K==="/"?0:K.length;return(F)=>{let V=new URL(F.url);return V.pathname=V.pathname.slice(H)||"/",new Request(V,F)}})();let $=async(K,H)=>{let F=await Q(G(K.req.raw),...Z(K));if(F)return F;await H()};return this.#J(t4,xF(Y,"*"),$),this}#J(Y,Q,J){Y=Y.toUpperCase(),Q=xF(this._basePath,Q);let G={basePath:this._basePath,path:Q,method:Y,handler:J};this.router.add(Y,Q,[J,G]),this.routes.push(G)}#W(Y,Q){if(Y instanceof Error)return this.errorHandler(Y,Q);throw Y}#G(Y,Q,J,G){if(G==="HEAD")return(async()=>new Response(null,await this.#G(Y,Q,J,"GET")))();let W=this.getPath(Y,{env:J}),Z=this.router.match(G,W),$=new _W6(Y,{path:W,matchResult:Z,env:J,executionCtx:Q,notFoundHandler:this.#Q});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#Q($)})}catch(F){return this.#W(F,$)}return H instanceof Promise?H.then((F)=>F||($.finalized?$.res:this.#Q($))).catch((F)=>this.#W(F,$)):H??this.#Q($)}let K=pX0(Z[0],this.errorHandler,this.#Q);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#W(H,$)}})()}fetch=(Y,...Q)=>{return this.#G(Y,Q[1],Q[0],Y.method)};request=(Y,Q,J,G)=>{if(Y instanceof Request)return this.fetch(Q?new Request(Y,Q):Y,J,G);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${xF("/",Y)}`,Q),J,G)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#G(Y.request,Y,void 0,Y.request.method))})}};var uW6=v(()=>{LW6();sX0();uF();hW6();gF()});function Jf(X,Y){let Q=this.buildAllMatchers(),J=(G,W)=>{let Z=Q[G]||Q[t4],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],wT];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=J,J(X,Y)}var wT;var tX0=v(()=>{uF();wT=[]});function Nx1(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===MT||X===PT)return 1;else if(Y===MT||Y===PT)return-1;if(X===Gf)return 1;else if(Y===Gf)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var Gf="[^/]+",MT=".*",PT="(?:|/.*)",mF,Dx1,mW6=class X{#X;#Y;#Q=Object.create(null);insert(Y,Q,J,G,W){if(Y.length===0){if(this.#X!==void 0)throw mF;if(W)return;this.#X=Q;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",MT]:["","",Gf]:Z==="/*"?["","",PT]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let F=K[1],V=K[2]||Gf;if(F&&K[2]){if(V===".*")throw mF;if(V=V.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(V))throw mF}if(H=this.#Q[V],!H){if(Object.keys(this.#Q).some((q)=>q!==MT&&q!==PT))throw mF;if(W)return;if(H=this.#Q[V]=new X,F!=="")H.#Y=G.varIndex++}if(!W&&F!=="")J.push([F,H.#Y])}else if(H=this.#Q[Z],!H){if(Object.keys(this.#Q).some((F)=>F.length>1&&F!==MT&&F!==PT))throw mF;if(W)return;H=this.#Q[Z]=new X}H.insert($,Q,J,G,W)}buildRegExpStr(){let Q=Object.keys(this.#Q).sort(Nx1).map((J)=>{let G=this.#Q[J];return(typeof G.#Y==="number"?`(${J})@${G.#Y}`:Dx1.has(J)?`\\${J}`:J)+G.buildRegExpStr()});if(typeof this.#X==="number")Q.unshift(`#${this.#X}`);if(Q.length===0)return"";if(Q.length===1)return Q[0];return"(?:"+Q.join("|")+")"}};var eX0=v(()=>{mF=Symbol(),Dx1=new Set(".\\+*[^]$()")});var lW6=class{#X={varIndex:0};#Y=new mW6;insert(X,Y,Q){let J=[],G=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return G[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=G.length-1;Z>=0;Z--){let[$]=G[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,G[Z][1]);break}}return this.#Y.insert(W,Y,J,this.#X,Q),J}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,Q=[],J=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(G,W,Z)=>{if(W!==void 0)return Q[++Y]=Number(W),"$()";if(Z!==void 0)return J[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),Q,J]}};var dW6=v(()=>{eX0()});function cW6(X){return pW6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,Q)=>Q?`\\${Q}`:"(?:|/.*)")}$`)}function Lx1(){pW6=Object.create(null)}function wx1(X){let Y=new lW6,Q=[];if(X.length===0)return Ox1;let J=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,F],[V,q])=>H?1:V?-1:F.length-q.length),G=Object.create(null);for(let H=0,F=-1,V=J.length;H<V;H++){let[q,z,D]=J[H];if(q)G[z]=[D.map(([L])=>[L,Object.create(null)]),wT];else F++;let N;try{N=Y.insert(z,F,q)}catch(L){throw L===mF?new Qf(z):L}if(q)continue;Q[F]=D.map(([L,w])=>{let C=Object.create(null);w-=1;for(;w>=0;w--){let[T,E]=N[w];C[T]=E}return[L,C]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,F=Q.length;H<F;H++)for(let V=0,q=Q[H].length;V<q;V++){let z=Q[H][V]?.[1];if(!z)continue;let D=Object.keys(z);for(let N=0,L=D.length;N<L;N++)z[D[N]]=$[z[D[N]]]}let K=[];for(let H in Z)K[H]=Q[Z[H]];return[W,K,G]}function CB(X,Y){if(!X)return;for(let Q of Object.keys(X).sort((J,G)=>G.length-J.length))if(cW6(Q).test(Y))return[...X[Q]];return}var Ox1,pW6,Wf=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[t4]:Object.create(null)},this.#Y={[t4]:Object.create(null)}}add(X,Y,Q){let J=this.#X,G=this.#Y;if(!J||!G)throw Error(Yf);if(!J[X])[J,G].forEach(($)=>{$[X]=Object.create(null),Object.keys($[t4]).forEach((K)=>{$[X][K]=[...$[t4][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=cW6(Y);if(X===t4)Object.keys(J).forEach((K)=>{J[K][Y]||=CB(J[K],Y)||CB(J[t4],Y)||[]});else J[X][Y]||=CB(J[X],Y)||CB(J[t4],Y)||[];Object.keys(J).forEach((K)=>{if(X===t4||X===K)Object.keys(J[K]).forEach((H)=>{$.test(H)&&J[K][H].push([Q,W])})}),Object.keys(G).forEach((K)=>{if(X===t4||X===K)Object.keys(G[K]).forEach((H)=>$.test(H)&&G[K][H].push([Q,W]))});return}let Z=Xf(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(G).forEach((F)=>{if(X===t4||X===F)G[F][H]||=[...CB(J[F],H)||CB(J[t4],H)||[]],G[F][H].push([Q,W-K+$+1])})}}match=Jf;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#Q(Y)}),this.#X=this.#Y=void 0,Lx1(),X}#Q(X){let Y=[],Q=X===t4;if([this.#X,this.#Y].forEach((J)=>{let G=J[X]?Object.keys(J[X]).map((W)=>[W,J[X][W]]):[];if(G.length!==0)Q||=!0,Y.push(...G);else if(X!==t4)Y.push(...Object.keys(J[t4]).map((W)=>[W,J[t4][W]]))}),!Q)return null;else return wx1(Y)}};var XY0=v(()=>{uF();gF();tX0();eX0();dW6();Ox1=[/^$/,[],Object.create(null)],pW6=Object.create(null)});var Mx1=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#Q(X,Y){let Q=this.#X[X];Q[1].forEach((J)=>J&&J.push(Y)),Object.values(Q[2]).forEach((J)=>J[0].push(Y))}#J(X,Y,Q,J,G){let W=this.#X[X];if(!G)W[2][Y][0].push([Q,{}]);else J.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([Q,G]);else W[2][Z||Y][0].push([Q,G])})}add(X,Y,Q){if(!this.#X[X]){let G=this.#X[t4],W={};for(let Z in G[2])W[Z]=[G[2][Z][0].slice(),wT];this.#X[X]=[G[0],G[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let G=[Q,{}];if(X===t4)for(let W in this.#X)this.#Q(W,G);else this.#Q(X,G);return}let J=this.#Y[Y];if(!J)throw Error(`Path ${Y} is not registered`);for(let[G,W]of J)if(X===t4)for(let Z in this.#X)this.#J(Z,Y,Q,G,W);else this.#J(X,Y,Q,G,W)}buildAllMatchers(){return this.#X}match=Jf};var nW6=v(()=>{uF();tX0();XY0()});var iW6=v(()=>{XY0();nW6()});var YY0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,Q){if(!this.#Y)throw Error(Yf);this.#Y.push([X,Y,Q])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let Q=this.#X,J=this.#Y,G=Q.length,W=0,Z;for(;W<G;W++){let $=Q[W];try{for(let K=0,H=J.length;K<H;K++)$.add(...J[K]);Z=$.match(X,Y)}catch(K){if(K instanceof Qf)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===G)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var aW6=v(()=>{uF()});var rW6=v(()=>{aW6()});var TT,oW6=class X{#X;#Y;#Q;#J=0;#W=TT;constructor(Y,Q,J){if(this.#Y=J||Object.create(null),this.#X=[],Y&&Q){let G=Object.create(null);G[Y]={handler:Q,possibleKeys:[],score:0},this.#X=[G]}this.#Q=[]}insert(Y,Q,J){this.#J=++this.#J;let G=this,W=AW6(Q),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],F=W[$+1],V=EW6(H,F),q=Array.isArray(V)?V[0]:H;if(q in G.#Y){if(G=G.#Y[q],V)Z.push(V[1]);continue}if(G.#Y[q]=new X,V)G.#Q.push(V),Z.push(V[1]);G=G.#Y[q]}return G.#X.push({[Y]:{handler:J,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#J}}),G}#G(Y,Q,J,G){let W=[];for(let Z=0,$=Y.#X.length;Z<$;Z++){let K=Y.#X[Z],H=K[Q]||K[t4],F={};if(H!==void 0){if(H.params=Object.create(null),W.push(H),J!==TT||G&&G!==TT)for(let V=0,q=H.possibleKeys.length;V<q;V++){let z=H.possibleKeys[V],D=F[H.score];H.params[z]=G?.[z]&&!D?G[z]:J[z]??G?.[z],F[H.score]=!0}}}return W}search(Y,Q){let J=[];this.#W=TT;let W=[this],Z=iX0(Q),$=[];for(let K=0,H=Z.length;K<H;K++){let F=Z[K],V=K===H-1,q=[];for(let z=0,D=W.length;z<D;z++){let N=W[z],L=N.#Y[F];if(L)if(L.#W=N.#W,V){if(L.#Y["*"])J.push(...this.#G(L.#Y["*"],Y,N.#W));J.push(...this.#G(L,Y,N.#W))}else q.push(L);for(let w=0,C=N.#Q.length;w<C;w++){let T=N.#Q[w],E=N.#W===TT?{}:{...N.#W};if(T==="*"){let b=N.#Y["*"];if(b)J.push(...this.#G(b,Y,N.#W)),b.#W=E,q.push(b);continue}let[P,j,R]=T;if(!F&&!(R instanceof RegExp))continue;let k=N.#Y[P],y=Z.slice(K).join("/");if(R instanceof RegExp){let b=R.exec(y);if(b){if(E[j]=b[0],J.push(...this.#G(k,Y,N.#W,E)),Object.keys(k.#Y).length){k.#W=E;let h=b[0].match(/\//)?.length??0;($[h]||=[]).push(k)}continue}}if(R===!0||R.test(F))if(E[j]=F,V){if(J.push(...this.#G(k,Y,E,N.#W)),k.#Y["*"])J.push(...this.#G(k.#Y["*"],Y,E,N.#W))}else k.#W=E,q.push(k)}}W=q.concat($.shift()??[])}if(J.length>1)J.sort((K,H)=>{return K.score-H.score});return[J.map(({handler:K,params:H})=>[K,H])]}};var sW6=v(()=>{uF();gF();TT=Object.create(null)});var QY0=class{name="TrieRouter";#X;constructor(){this.#X=new oW6}add(X,Y,Q){let J=Xf(Y);if(J){for(let G=0,W=J.length;G<W;G++)this.#X.insert(X,J[G],Q);return}this.#X.insert(X,Y,Q)}match(X,Y){return this.#X.search(X,Y)}};var tW6=v(()=>{gF();sW6()});var eW6=v(()=>{tW6()});var C9;var XZ6=v(()=>{uW6();iW6();rW6();eW6();C9=class extends gW6{constructor(X={}){super(X);this.router=X.router??new YY0({routers:[new Wf,new QY0]})}}});var k7=v(()=>{XZ6()});function Px1(){let{process:X,Deno:Y}=globalThis;return!(typeof Y?.noColor==="boolean"?Y.noColor:X!==void 0?"NO_COLOR"in X?.env:!1)}async function YZ6(){let{navigator:X}=globalThis,Y="cloudflare:workers";return!(X!==void 0&&X.userAgent==="Cloudflare-Workers"?await(async()=>{try{return"NO_COLOR"in((await import("cloudflare:workers")).env??{})}catch{return!1}})():!Px1())}var QZ6=()=>{};async function JZ6(X,Y,Q,J,G=0,W){let Z=Y==="<--"?`${Y} ${Q} ${J}`:`${Y} ${Q} ${J} ${await Ex1(G)} ${W}`;X(Z)}var Tx1=(X)=>{let[Y,Q]=[",","."];return X.map((G)=>G.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+Y)).join(Q)},Ax1=(X)=>{let Y=Date.now()-X;return Tx1([Y<1000?Y+"ms":Math.round(Y/1000)+"s"])},Ex1=async(X)=>{if(await YZ6())switch(X/100|0){case 5:return`\x1B[31m${X}\x1B[0m`;case 4:return`\x1B[33m${X}\x1B[0m`;case 3:return`\x1B[36m${X}\x1B[0m`;case 2:return`\x1B[32m${X}\x1B[0m`}return`${X}`},GZ6=(X=console.log)=>{return async function(Q,J){let{method:G,url:W}=Q.req,Z=W.slice(W.indexOf("/",8));await JZ6(X,"<--",G,Z);let $=Date.now();await J(),await JZ6(X,"-->",G,Z,Q.res.status,Ax1($))}};var WZ6=v(()=>{QZ6()});var ZZ6=(X)=>{let Q={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},J=((W)=>{if(typeof W==="string")if(W==="*")return()=>W;else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(Q.origin),G=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(Q.allowMethods);return async function(Z,$){function K(F,V){Z.res.headers.set(F,V)}let H=await J(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(Q.credentials)K("Access-Control-Allow-Credentials","true");if(Q.exposeHeaders?.length)K("Access-Control-Expose-Headers",Q.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(Q.origin!=="*")K("Vary","Origin");if(Q.maxAge!=null)K("Access-Control-Max-Age",Q.maxAge.toString());let F=await G(Z.req.header("origin")||"",Z);if(F.length)K("Access-Control-Allow-Methods",F.join(","));let V=Q.allowHeaders;if(!V?.length){let q=Z.req.header("Access-Control-Request-Headers");if(q)V=q.split(/\s*,\s*/)}if(V?.length)K("Access-Control-Allow-Headers",V.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),Q.origin!=="*")Z.header("Vary","Origin",{append:!0})}};var $Z6=()=>{};var KZ6=()=>{try{return performance.now()}catch{}return Date.now()},JY0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(J,G){let W=[],Z=new Map;if(J.get("metric"))return await G();if(J.set("metric",{headers:W,timers:Z}),Y.total)IB(J,"total",Y.totalDescription);if(await G(),Y.total)lF(J,"total");if(Y.autoEnd)Z.forEach((K,H)=>lF(J,H));if(typeof Y.enabled==="function"?Y.enabled(J):Y.enabled){J.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(J):Y.crossOrigin;if(K)J.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},HZ6=(X,Y,Q,J,G)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof Q==="number"){let Z=Q.toFixed(G||1),$=J?`${Y};dur=${Z};desc="${J}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=Q?`${Y};desc="${Q}"`:`${Y}`;W.headers.push(Z)}},IB=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}J.timers.set(Y,{description:Q,start:KZ6()})},lF=(X,Y,Q)=>{let J=X.get("metric");if(!J){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let G=J.timers.get(Y);if(!G){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=G,$=KZ6()-Z;HZ6(X,Y,$,W,Q),J.timers.delete(Y)};var FZ6=v(()=>{sX0()});var VZ6=v(()=>{FZ6()});var jx1,Cx1,GY0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let Q=X.trim().split(";"),J={};for(let G of Q){G=G.trim();let W=G.indexOf("=");if(W===-1)continue;let Z=G.substring(0,W).trim();if(Y&&Y!==Z||!jx1.test(Z))continue;let $=G.substring(W+1).trim();if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(Cx1.test($)){if(J[Z]=$.indexOf("%")!==-1?jB($,LT):$,Y)break}}return J};var qZ6=v(()=>{gF();jx1=/^[\w!#$%&'*.^`|~+-]+$/,Cx1=/^[ !#-:<-[\]-~]*$/});var zZ6=(X,Y,Q)=>{let J=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!J)return;let W=Y;if(Q==="secure")W="__Secure-"+Y;else if(Q==="host")W="__Host-"+Y;return GY0(J,W)[W]}if(!J)return{};return GY0(J)};var UZ6=v(()=>{qZ6()});import{randomBytes as Ix1}from"crypto";function BZ6(){if(AT)return AT;let X=process.env.MESH_JWT_SECRET??X9.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(X)AT=new TextEncoder().encode(X);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),AT=new Uint8Array(Ix1(32));return AT}async function DZ6(X,Y="5m"){let Q=BZ6();return await new mY(X).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Y).sign(Q)}async function NZ6(X){try{let Y=BZ6(),{payload:Q}=await W8(X,Y);return Q}catch{return}}var AT=null;var WY0=v(()=>{EQ();EB()});class ZY0{db;constructor(X){this.db=X}async create(X,Y,Q){let J=qQ("vir"),G=new Date().toISOString();if(await this.db.insertInto("virtual_mcps").values({id:J,organization_id:X,title:Q.title,description:Q.description??null,tool_selection_mode:Q.tool_selection_mode??"inclusion",icon:Q.icon??null,status:Q.status??"active",created_at:G,updated_at:G,created_by:Y,updated_by:null}).execute(),Q.connections.length>0)await this.db.insertInto("virtual_mcp_connections").values(Q.connections.map((Z)=>({id:qQ("virc"),virtual_mcp_id:J,connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:G}))).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create virtual MCP with id: ${J}`);return W}async findById(X){return this.findByIdInternal(this.db,X)}async findByIdInternal(X,Y){let Q=await X.selectFrom("virtual_mcps").selectAll().where("id","=",Y).executeTakeFirst();if(!Q)return null;let J=await X.selectFrom("virtual_mcp_connections").selectAll().where("virtual_mcp_id","=",Y).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(X){let Y=await this.db.selectFrom("virtual_mcps").selectAll().where("organization_id","=",X).execute(),Q=Y.map((W)=>W.id);if(Q.length===0)return[];let J=await this.db.selectFrom("virtual_mcp_connections").selectAll().where("virtual_mcp_id","in",Q).execute(),G=new Map;for(let W of J){let Z=G.get(W.virtual_mcp_id)??[];Z.push(W),G.set(W.virtual_mcp_id,Z)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,G.get(W.id)??[]))}async listByConnectionId(X,Y){let J=(await this.db.selectFrom("virtual_mcp_connections").select("virtual_mcp_id").where("connection_id","=",Y).execute()).map((K)=>K.virtual_mcp_id);if(J.length===0)return[];let G=await this.db.selectFrom("virtual_mcps").selectAll().where("id","in",J).where("organization_id","=",X).execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("virtual_mcp_connections").selectAll().where("virtual_mcp_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.virtual_mcp_id)??[];H.push(K),$.set(K.virtual_mcp_id,H)}return G.map((K)=>this.deserializeVirtualMCPEntity(K,$.get(K.id)??[]))}async update(X,Y,Q){let J=new Date().toISOString(),G={updated_at:J,updated_by:Y};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.tool_selection_mode!==void 0)G.tool_selection_mode=Q.tool_selection_mode;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(await this.db.updateTable("virtual_mcps").set(G).where("id","=",X).execute(),Q.connections!==void 0){if(await this.db.deleteFrom("virtual_mcp_connections").where("virtual_mcp_id","=",X).execute(),Q.connections.length>0)await this.db.insertInto("virtual_mcp_connections").values(Q.connections.map((Z)=>({id:qQ("virc"),virtual_mcp_id:X,connection_id:Z.connection_id,selected_tools:Z.selected_tools?JSON.stringify(Z.selected_tools):null,selected_resources:Z.selected_resources?JSON.stringify(Z.selected_resources):null,selected_prompts:Z.selected_prompts?JSON.stringify(Z.selected_prompts):null,created_at:J}))).execute()}let W=await this.findById(X);if(!W)throw Error("Virtual MCP not found after update");return W}async delete(X){await this.db.deleteFrom("virtual_mcps").where("id","=",X).execute()}deserializeVirtualMCPEntity(X,Y){let Q=X.created_at instanceof Date?X.created_at.toISOString():X.created_at,J=X.updated_at instanceof Date?X.updated_at.toISOString():X.updated_at;return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,tool_selection_mode:this.parseToolSelectionMode(X.tool_selection_mode),icon:X.icon,status:X.status,created_at:Q,updated_at:J,created_by:X.created_by,updated_by:X.updated_by??void 0,connections:Y.map((G)=>({connection_id:G.connection_id,selected_tools:this.parseJson(G.selected_tools),selected_resources:this.parseJson(G.selected_resources),selected_prompts:this.parseJson(G.selected_prompts)}))}}parseToolSelectionMode(X){if(X==="exclusion")return"exclusion";return"inclusion"}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}var OZ6=v(()=>{zF()});class $Y0{patterns=[{type:"email",regex:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g},{type:"api_key",regex:/(?:api[_-]?key|token|secret|password|bearer)\s*[:=]\s*['"]?[\w-]{16,}['"]?/gi},{type:"jwt",regex:/eyJ[A-Za-z0-9-_]+\.eyJ[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*/g},{type:"credit_card",regex:/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g},{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g}];redact(X){return bM.startActiveSpan("redactor.redact",(Y)=>{try{if(X===null||X===void 0)return X;if(typeof X==="string")return Y.setAttribute("data.type","string"),this.redactString(X);if(Array.isArray(X))return Y.setAttribute("data.type","array"),Y.setAttribute("data.length",X.length),X.map((Q)=>this.redact(Q));if(typeof X==="object"){Y.setAttribute("data.type","object");let Q={};for(let[J,G]of Object.entries(X)){let W=this.redactString(J);Q[W]=this.redact(G)}return Q}return Y.setAttribute("data.type",typeof X),X}finally{Y.end()}})}redactString(X){return bM.startActiveSpan("redactor.redactString",(Y)=>{try{Y.setAttribute("text.length",X.length);let Q=X,J=0;for(let G of this.patterns){let W=X.match(G.regex);if(W)J+=W.length,Y.setAttribute(`redaction.${G.type}.count`,W.length);Q=Q.replace(G.regex,`[REDACTED:${G.type}]`)}return Y.setAttribute("redaction.total_count",J),Q}finally{Y.end()}})}}var LZ6=v(()=>{fM()});import{sql as Zf}from"kysely";class KY0{db;redactor;databaseType;constructor(X,Y="sqlite"){this.db=X;this.redactor=new $Y0,this.databaseType=Y}jsonExtract(X,Y){if(this.databaseType==="postgres")return Zf`(${Zf.ref(X)}::jsonb)->>${Y}`;let Q=`$.${Y}`;return Zf`json_extract(${Zf.ref(X)}, ${Q})`}async log(X){await this.logBatch([X])}async logBatch(X){if(X.length===0)return;let Y=X.map((Q)=>({...Q,input:this.redactor.redact(Q.input),output:this.redactor.redact(Q.output)}));await this.db.transaction().execute(async(Q)=>{await Q.insertInto("monitoring_logs").values(Y.map((J)=>this.toDbRow(J))).execute()})}async query(X){let Y=this.db.selectFrom("monitoring_logs").selectAll(),Q=this.db.selectFrom("monitoring_logs").select(($)=>$.fn.count("id").as("count"));if(X.organizationId)Y=Y.where("organization_id","=",X.organizationId),Q=Q.where("organization_id","=",X.organizationId);if(X.connectionId)Y=Y.where("connection_id","=",X.connectionId),Q=Q.where("connection_id","=",X.connectionId);if(X.virtualMcpId)Y=Y.where("virtual_mcp_id","=",X.virtualMcpId),Q=Q.where("virtual_mcp_id","=",X.virtualMcpId);if(X.toolName)Y=Y.where("tool_name","=",X.toolName),Q=Q.where("tool_name","=",X.toolName);if(X.isError!==void 0)Y=Y.where("is_error","=",X.isError?1:0),Q=Q.where("is_error","=",X.isError?1:0);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString()),Q=Q.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString()),Q=Q.where("timestamp","<=",X.endDate.toISOString());if(X.propertyFilters){let{properties:$,propertyKeys:K,propertyPatterns:H}=X.propertyFilters;if($)for(let[F,V]of Object.entries($)){let q=this.jsonExtract("properties",F);Y=Y.where(q,"=",V),Q=Q.where(q,"=",V)}if(K&&K.length>0)for(let F of K){let V=this.jsonExtract("properties",F);Y=Y.where(V,"is not",null),Q=Q.where(V,"is not",null)}if(H)for(let[F,V]of Object.entries(H)){let q=this.jsonExtract("properties",F),z=this.databaseType==="postgres"?"ilike":"like";Y=Y.where(q,z,V),Q=Q.where(q,z,V)}}if(Y=Y.orderBy("timestamp","desc"),X.limit)Y=Y.limit(X.limit);if(X.offset)Y=Y.offset(X.offset);let[J,G]=await Promise.all([Y.execute(),Q.executeTakeFirst()]),W=Number(G?.count||0);return{logs:J.map(($)=>this.fromDbRow($)),total:W}}async getStats(X){let Y=this.db.selectFrom("monitoring_logs").where("organization_id","=",X.organizationId);if(X.startDate)Y=Y.where("timestamp",">=",X.startDate.toISOString());if(X.endDate)Y=Y.where("timestamp","<=",X.endDate.toISOString());let Q=await Y.select([(Z)=>Z.fn.count("id").as("total_count"),(Z)=>Z.fn.sum(Z.ref("is_error")).as("error_count"),(Z)=>Z.fn.avg("duration_ms").as("avg_duration")]).executeTakeFirst(),J=Number(Q?.total_count||0),G=Number(Q?.error_count||0),W=Number(Q?.avg_duration||0);return{totalCalls:J,errorRate:J>0?G/J:0,avgDurationMs:W}}toDbRow(X){return{id:X.id||qQ("log"),organization_id:X.organizationId,connection_id:X.connectionId,connection_title:X.connectionTitle,tool_name:X.toolName,input:JSON.stringify(X.input),output:JSON.stringify(X.output),is_error:X.isError?1:0,error_message:X.errorMessage||null,duration_ms:X.durationMs,timestamp:X.timestamp instanceof Date?X.timestamp.toISOString():X.timestamp,user_id:X.userId||null,request_id:X.requestId,user_agent:X.userAgent||null,virtual_mcp_id:X.virtualMcpId||null,properties:X.properties?JSON.stringify(X.properties):null}}fromDbRow(X){let Y=typeof X.input==="string"?JSON.parse(X.input):X.input,Q=typeof X.output==="string"?JSON.parse(X.output):X.output,J=typeof X.timestamp==="string"?new Date(X.timestamp):X.timestamp,G=X.properties?typeof X.properties==="string"?JSON.parse(X.properties):X.properties:null;return{id:X.id,organizationId:X.organization_id,connectionId:X.connection_id,connectionTitle:X.connection_title,toolName:X.tool_name,input:Y,output:Q,isError:X.is_error===1,errorMessage:X.error_message,durationMs:X.duration_ms,timestamp:J,userId:X.user_id,requestId:X.request_id,userAgent:X.user_agent,virtualMcpId:X.virtual_mcp_id,properties:G}}}var wZ6=v(()=>{LZ6();zF()});class HY0{db;constructor(X){this.db=X}async get(X){let Y=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",X).executeTakeFirst();if(!Y)return null;return{organizationId:Y.organizationId,sidebar_items:Y.sidebar_items?typeof Y.sidebar_items==="string"?JSON.parse(Y.sidebar_items):Y.sidebar_items:null,enabled_plugins:Y.enabled_plugins?typeof Y.enabled_plugins==="string"?JSON.parse(Y.enabled_plugins):Y.enabled_plugins:null,createdAt:Y.createdAt,updatedAt:Y.updatedAt}}async upsert(X,Y){let Q=new Date().toISOString(),J=Y?.sidebar_items?JSON.stringify(Y.sidebar_items):null,G=Y?.enabled_plugins?JSON.stringify(Y.enabled_plugins):null;await this.db.insertInto("organization_settings").values({organizationId:X,sidebar_items:J,enabled_plugins:G,createdAt:Q,updatedAt:Q}).onConflict((Z)=>Z.column("organizationId").doUpdateSet({sidebar_items:J?J:void 0,enabled_plugins:G?G:void 0,updatedAt:Q})).execute();let W=await this.get(X);if(!W)return{organizationId:X,sidebar_items:Y?.sidebar_items??null,enabled_plugins:Y?.enabled_plugins??null,createdAt:Q,updatedAt:Q};return W}}class FY0{db;constructor(X){this.db=X}async findById(X,Y){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",X).where((J)=>J.exists(J.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",X).where("m2.userId","=",Y))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}var MZ6,VY0,RB;var qY0=v(()=>{JK();MZ6=class MZ6 extends Error{constructor(X){super(X);this.name="UnauthorizedError"}};VY0=class VY0 extends Error{constructor(X){super(X);this.name="ForbiddenError"}};RB=class RB{userId;toolName;boundAuth;role;connectionId;_granted=!1;constructor(X,Y,Q,J,G,W=g5.SELF){this.userId=Y;this.toolName=Q;this.boundAuth=J;this.role=G;this.connectionId=W}[Symbol.dispose](){this._granted=!1}setToolName(X){this.toolName=X}grant(){return this._granted=!0,{[Symbol.dispose]:()=>{this._granted=!1}}}async check(...X){if(this._granted)return;if(!this.userId&&!this.boundAuth)throw new MZ6("Authentication required. Please provide a valid OAuth token or API key.");let Y=X.length>0?X:this.toolName?[this.toolName]:[];if(Y.length===0)throw new VY0("No resources specified for access check");for(let Q of Y)if(await this.checkResource(Q)){this.grant();return}throw new VY0(`Access denied to: ${Y.join(", ")}`)}async checkResource(X){if(!this.userId&&!this.boundAuth)return!1;if(this.role==="admin"||this.role==="owner")return!0;if(!this.boundAuth)return!1;let Y={};if(this.connectionId)Y[this.connectionId]=[X];return this.boundAuth.hasPermission(Y)}granted(){return this._granted}}});function PZ6(X){let Y=null;return()=>{if(Y)return Y;return Y=X().catch((Q)=>{throw Y=null,Q}),Y}}class TZ6{factory;promise=null;constructor(X){this.factory=X}getOrCreatePromise(){if(!this.promise)this.promise=this.factory();return this.promise}then(X,Y){return this.getOrCreatePromise().then(X,Y)}catch(X){return this.getOrCreatePromise().catch(X)}finally(X){return this.getOrCreatePromise().finally(X)}}function v7(X){return new TZ6(X)}async function AZ6(X){if(!X.refreshToken)return{success:!1,error:"No refresh token available"};if(!X.tokenEndpoint)return{success:!1,error:"No token endpoint available"};if(!X.clientId)return{success:!1,error:"No client ID available"};try{let Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:X.refreshToken,client_id:X.clientId});if(X.clientSecret)Y.set("client_secret",X.clientSecret);if(X.scope)Y.set("scope",X.scope);let Q=await fetch(X.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!Q.ok){let G=await Q.text();console.error(`[TokenRefresh] Failed to refresh token: ${Q.status}`,G);try{let W=JSON.parse(G);return{success:!1,error:W.error_description||W.error||`Token refresh failed: ${Q.status}`}}catch{return{success:!1,error:`Token refresh failed: ${Q.status}`}}}let J=await Q.json();return{success:!0,accessToken:J.access_token,refreshToken:J.refresh_token||X.refreshToken,expiresIn:J.expires_in,scope:J.scope}}catch(Y){return console.error("[TokenRefresh] Error refreshing token:",Y),{success:!1,error:Y instanceof Error?Y.message:"Token refresh failed"}}}function Rx1(X){return new Proxy(X,{get(Q,J,G){if(J==="close")return async()=>{};if(J==="__actualClient")return Q;return Reflect.get(Q,J,G)}})}async function CZ6(X){let Y=dF.get(X.id);if(Y?.status==="connected"&&Y.stableClient)return Y.stableClient;if(Y?.connectPromise&&(Y.status==="connecting"||Y.status==="reconnecting"))return Y.connectPromise;let Q=Y?.status==="failed",J=Y??{transport:null,client:null,stableClient:null,config:X,status:"connecting",connectPromise:null};if(!Y)dF.set(X.id,J);return J.status=Q?"reconnecting":"connecting",J.connectPromise=(async()=>{try{console.log(`[StableStdio] ${Q?"Respawning":"Spawning"}: ${X.id} (${X.command} ${X.args?.join(" ")??""})`);let G=new lP({command:X.command,args:X.args,env:X.env,cwd:X.cwd,stderr:"pipe"});J.transport=G;let W=new OQ({name:`mesh-stdio-${X.id}`,version:"1.0.0"});J.client=W,J.stableClient=Rx1(W),W.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${X.id}`),J.status="failed",J.connectPromise=null};let Z=X.name||X.id,$="\x1B[2m",K="\x1B[0m";G.stderr?.on("data",(V)=>{let q=V.toString().trimEnd();if(q)console.error(`${q} ${$}[${Z}]${K}`)});let H=new AbortController,F=setTimeout(()=>H.abort(),30000);try{await Promise.race([W.connect(G),new Promise((V,q)=>{H.signal.addEventListener("abort",()=>{q(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(F)}return J.status="connected",console.log(`[StableStdio] Connected: ${X.id}`),J.stableClient}catch(G){console.error(`[StableStdio] Failed to connect ${X.id}:`,G),J.status="failed",J.connectPromise=null;try{await J.transport?.close()}catch{}throw G}})(),J.connectPromise}async function Sx1(X){let Y=dF.get(X);if(!Y)return;console.log(`[StableStdio] Force closing: ${X}`);try{if(Y.client)Y.client.onclose=void 0;await Y.client?.close()}catch{}dF.delete(X)}async function kx1(){console.log(`[StableStdio] Closing all connections (${dF.size})`);let X=Array.from(dF.keys()).map((Y)=>Sx1(Y));await Promise.allSettled(X),dF.clear()}var EZ6="__mesh_stable_stdio_pool__",dF,jZ6="__mesh_stable_stdio_shutdown_registered__";var IZ6=v(()=>{XB();G90();dF=globalThis[EZ6]??(globalThis[EZ6]=new Map);if(!globalThis[jZ6]){globalThis[jZ6]=!0;let X=async(Y)=>{await kx1(),process.exit(Y==="SIGINT"?130:143)};process.on("SIGINT",()=>X("SIGINT")),process.on("SIGTERM",()=>X("SIGTERM"))}});async function RZ6(X,Y){return(await Y.storage.connections.findById(X))?.connection_url??null}function vx1(X){let Y=X.toLowerCase();return Y.includes("resource_metadata=")||Y.includes("invalid_token")||Y.includes("oauth")}async function SZ6(X,Y={}){try{let Q=await fetch(X,{method:"POST",headers:{...Y,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"mcp-mesh-proxy",version:"1.0.0"}}})});if(Q.status===401){let J=Q.headers.get("WWW-Authenticate");if(J){if(vx1(J))return J}}return null}catch{return null}}async function Kf(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=new URL(X);J.pathname=`${Q}/.well-known/oauth-protected-resource`;let G=await fetch(J.toString(),{method:"GET",headers:{Accept:"application/json"}});if(G.ok)return G;if(!zY0.includes(G.status))return G;let W=new URL(X);if(W.pathname=`/.well-known/oauth-protected-resource${Q}`,G=await fetch(W.toString(),{method:"GET",headers:{Accept:"application/json"}}),!zY0.includes(G.status))return G;let Z=new URL(X);return Z.pathname="/.well-known/oauth-protected-resource",G=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),G}async function _x1(X,Y){let Q=await RZ6(X,Y);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Kf(Q);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function kZ6(X){let Y=X.get("meshContext");if(!Y)Y=await SK.create(X.req.raw),X.set("meshContext",Y);return Y}async function vZ6({error:X,reqUrl:Y,connectionId:Q,connectionUrl:J,headers:G}){let W=X.message?.toLowerCase()??"";if(!(X.status===401||X.code===401||X.message?.includes("401")||W.includes("unauthorized")||W.includes("invalid_token")||W.includes("api key required")||W.includes("api-key required")))return null;if(Boolean(await SZ6(J,G)))return new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${Y.origin}/mcp/${Q}/.well-known/oauth-protected-resource"`}});return new Response(JSON.stringify({error:"unauthorized",message:"Authentication required but server does not support OAuth"}),{status:401,headers:{"Content-Type":"application/json"}})}async function UY0(X){let Q=new URL(X).pathname;if(Q.endsWith("/"))Q=Q.slice(0,-1);let J=Q!==""&&Q!=="/",G=[];if(J){let Z=new URL(X);Z.pathname=`/.well-known/oauth-authorization-server${Q}`,G.push(Z);let $=new URL(X);$.pathname=`/.well-known/openid-configuration${Q}`,G.push($);let K=new URL(X);K.pathname=`${Q}/.well-known/openid-configuration`,G.push(K)}else{let Z=new URL(X);Z.pathname="/.well-known/oauth-authorization-server",G.push(Z);let $=new URL(X);$.pathname="/.well-known/openid-configuration",G.push($)}let W=null;for(let Z of G){if(W=await fetch(Z.toString(),{method:"GET",headers:{Accept:"application/json"}}),W.ok)return W;if(W.status!==404&&W.status!==401)return W}return W}var $f,zY0,Hf=(X)=>{if(!(X.hostname==="localhost"||X.hostname==="127.0.0.1"))X.protocol="https:";return X},_Z6=async(X)=>{let Y=X.req.param("connectionId"),Q=await kZ6(X),J=await RZ6(Y,Q);if(!J)return X.json({error:"Connection not found"},404);let G=Hf(new URL(X.req.url)),W=`${G.origin}/mcp/${Y}`,Z=`${G.origin}/oauth-proxy/${Y}`;try{let $=await Kf(J);if(!$.ok&&zY0.includes($.status)){if(await SZ6(J))return new Response(JSON.stringify({resource:W,authorization_servers:[Z],bearer_methods_supported:["header"],scopes_supported:["*"]}),{status:200,headers:{"Content-Type":"application/json"}});return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}if(!$.ok)return new Response($.body,{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}});let H={...await $.json(),resource:W,authorization_servers:[Z]};return new Response(JSON.stringify(H),{status:$.status,statusText:$.statusText,headers:{"Content-Type":"application/json"}})}catch($){let K=$;return console.error("[oauth-proxy] Failed to proxy OAuth protected resource metadata:",K),X.json({error:"Failed to proxy OAuth metadata",message:K.message},502)}},yZ6;var Ff=v(()=>{k7();Vf();$f=new C9,zY0=[404,401,406];$f.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(X)=>_Z6(X));$f.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(X)=>_Z6(X));$f.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=await kZ6(X),J=await _x1(Y,Q);if(!J)return X.json({error:"Connection not found or no auth server"},404);try{let G=await UY0(J);if(!G.ok)return new Response(G.body,{status:G.status,statusText:G.statusText,headers:{"Content-Type":"application/json"}});let W=await G.json(),$=`${Hf(new URL(X.req.url)).origin}/oauth-proxy/${Y}`,K={...W,authorization_endpoint:W.authorization_endpoint?`${$}/authorize`:void 0,token_endpoint:W.token_endpoint?`${$}/token`:void 0,registration_endpoint:W.registration_endpoint?`${$}/register`:void 0};return new Response(JSON.stringify(K),{status:200,headers:{"Content-Type":"application/json"}})}catch(G){let W=G;return console.error("[oauth-proxy] Failed to proxy auth server metadata:",W),X.json({error:"Failed to proxy auth server metadata",message:W.message},502)}});yZ6=$f});function yx1(X){if(!X.isError)return;let Y=X.content;if(!Array.isArray(Y))return;for(let Q of Y)if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text;return}function bx1(X){if(!X)return;let Y=X._meta;if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let Q=Y.properties;if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J={};for(let[G,W]of Object.entries(Q))if(typeof W==="string")J[G]=W;return Object.keys(J).length>0?J:void 0}function fx1(X,Y){if(!X&&!Y)return;if(!X)return Y;if(!Y)return X;return{...Y,...X}}function bZ6(X){if(X&&typeof X==="object"&&!Array.isArray(X)){let Y=X,Q=Y.structuredContent;if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return Y}return{value:X}}async function hx1(X,Y){let Q=X.body;if(!Q)return{text:"",truncated:!1};let J=Q.getReader(),G=new TextDecoder,W=!1,Z=0,$=[];try{while(!0){let{value:K,done:H}=await J.read();if(H)break;if(K){if(Z+=K.byteLength,Z>Y){W=!0;let F=Y-(Z-K.byteLength);if(F>0)$.push(G.decode(K.slice(0,F),{stream:!0}));break}$.push(G.decode(K,{stream:!0}))}}}finally{J.releaseLock()}return $.push(G.decode()),{text:$.join(""),truncated:W}}async function ET(X){let{ctx:Y,enabled:Q}=X,J=X.organizationId??Y.organization?.id;if(!Q||!J)return;let G=bx1(X.request.params.arguments),W=fx1(Y.metadata.properties,G);await Y.storage.monitoring.log({organizationId:J,connectionId:X.connectionId,connectionTitle:X.connectionTitle,toolName:X.request.params.name,input:X.request.params.arguments??{},output:X.output,isError:X.isError,errorMessage:X.errorMessage,durationMs:X.durationMs,timestamp:new Date,userId:Y.auth.user?.id||Y.auth.apiKey?.userId||null,requestId:Y.metadata.requestId,userAgent:Y.metadata.userAgent,virtualMcpId:Y.virtualMcpId,properties:W})}function fZ6(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G}=X;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=Date.now()-$;return await ET({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,request:W,output:bZ6(K),isError:Boolean(K.isError),errorMessage:yx1(K),durationMs:H}),K}catch(K){let H=K,F=Date.now()-$;throw await ET({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}function hZ6(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G}=X;return async(W,Z)=>{let $=Date.now();try{let K=await Z(),H=Y.organization?.id;if(Q&&H){let F=K.clone();(async()=>{try{let{text:V,truncated:q}=await hx1(F,262144),z=Date.now()-$,D=F.headers.get("content-type")??"",N=V;if(D.includes("application/json"))try{N=V.length?JSON.parse(V):null}catch{N=V}let L=K.status>=400,w=L&&N&&typeof N==="object"&&"error"in N?N.error:void 0,C=typeof w==="string"&&w?w:L&&typeof N==="string"&&N.trim()?N.slice(0,500):L?`HTTP ${K.status} ${K.statusText}`.trim():q?"Response body truncated to 262144 bytes":void 0;await ET({ctx:Y,enabled:Q,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:bZ6(N),isError:L,errorMessage:C,durationMs:z})}catch(V){let q=Date.now()-$;await ET({ctx:Y,enabled:Q,organizationId:H,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${V.message}`,durationMs:q})}})()}return K}catch(K){let H=K,F=Date.now()-$;throw await ET({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,request:W,output:{},isError:!0,errorMessage:H.message,durationMs:F}),K}}}function xx1(X,Y){return async(Q,J)=>{try{let G=Q.params.name;return await new RB(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,G,X.boundAuth,X.auth.user?.role,Y).check(G),await J()}catch(G){return{content:[{type:"text",text:`Authorization failed: ${G.message}`}],isError:!0}}}}function gx1(X,Y){return async(Q,J)=>{try{let G=Q.params.name;return await new RB(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,G,X.boundAuth,X.auth.user?.role,Y).check(G),await J()}catch(G){return new Response(JSON.stringify({error:`Authorization failed: ${G.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function gZ6(X,Y,{superUser:Q}){let J=typeof X==="string"?await Y.storage.connections.findById(X,Y.organization?.id):X;if(!J)throw Error("Connection not found");let G=J?.id;if(Y.organization&&J.organization_id!==Y.organization.id)throw Error("Connection does not belong to the active organization");if(Y.organization??={id:J.organization_id},J.status!=="active")throw Error(`Connection inactive: ${J.status}`);let W,Z=Y.auth.user?.connectionId,$=PZ6(async()=>{let f=s90(J.configuration_state,J.configuration_scopes),S=Y.auth.user?.id??Y.auth.apiKey?.userId;if(!S){console.error("User ID required to issue configuration token");return}try{W=await DZ6({sub:S,user:{id:S},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??Y.baseUrl,connectionId:G,organizationId:Y.organization?.id},permissions:f})}catch(u){console.error("Failed to issue configuration token:",u)}}),K=async()=>{await $();let f={...Z?{"x-caller-id":Z}:{}},S=null,u=new qZ(Y.db,Y.vault),t=await u.get(G);if(t){let r=!!t.refreshToken&&!!t.tokenEndpoint;if(u.isExpired(t,r?300000:0))if(r){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let H0=await AZ6(t);if(H0.success&&H0.accessToken)await u.upsert({connectionId:G,accessToken:H0.accessToken,refreshToken:H0.refreshToken??t.refreshToken,scope:H0.scope??t.scope,expiresAt:H0.expiresIn?new Date(Date.now()+H0.expiresIn*1000):null,clientId:t.clientId,clientSecret:t.clientSecret,tokenEndpoint:t.tokenEndpoint}),S=H0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await u.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${H0.error}`)}else await u.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else S=t.accessToken}if(!S&&J.connection_token)S=J.connection_token;if(S)f.Authorization=`Bearer ${S}`;if(W)f["x-mesh-token"]=W;return f},H=J.connection_type==="STDIO",F=VF(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{switch(J.connection_type){case"STDIO":{if(process.env.UNSAFE_ALLOW_STDIO_TRANSPORT!=="true")throw Error("STDIO connections are disabled in production. Set UNSAFE_ALLOW_STDIO_TRANSPORT=true to enable.");if(!F)throw Error("STDIO connection missing parameters");return CZ6({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd})}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=new OQ({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let u=new HZ(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(u),f}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=new OQ({name:"mcp-mesh-proxy",version:"1.0.0"}),S=await K();if(V?.headers)Object.assign(S,V.headers);let u=new jF(new URL(J.connection_url),{requestInit:{headers:S}});return await f.connect(u),f}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=Q?async(f,S)=>await S():xx1(Y,G),D=Q?async(f,S)=>await S():gx1(Y,G),N={enabled:EN0().enabled,connectionId:G,connectionTitle:J.title,ctx:Y},L=fZ6(N),w=hZ6(N),C=nP(L,z),T=nP(w,D),E=async(f)=>{return C(f,async()=>{let S=await q(),u=Date.now(),t={...f.params};if(t.arguments&&"_meta"in t.arguments){let{_meta:r,...Y0}=t.arguments;t.arguments=Y0}return await Y.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":f.params.name}},async(r)=>{try{let Y0=await S.callTool(t),H0=Date.now()-u;return Y.meter.createHistogram("connection.proxy.duration").record(H0,{"connection.id":G,"tool.name":f.params.name,status:"success"}),Y.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":f.params.name,status:"success"}),r.end(),Y0}catch(Y0){let H0=Y0,G0=Date.now()-u;throw Y.meter.createHistogram("connection.proxy.duration").record(G0,{"connection.id":G,"tool.name":f.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":f.params.name,error:H0.message}),r.recordException(H0),r.end(),Y0}finally{S.close().catch(console.error)}})})};return{fetch:async(f)=>{let S=new URL(f.url),u;try{u=await q()}catch(G0){let B0=J.connection_url?await vZ6({error:G0,reqUrl:S,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(B0)return B0;throw G0}let r=u.getServerCapabilities()??{tools:{},resources:{},prompts:{}},Y0=new IF({name:"mcp-mesh",version:"1.0.0"},{capabilities:r}),H0=new RF({enableJsonResponse:f.headers.get("Accept")?.includes("application/json")??!1});if(await Y0.connect(H0),Y0.server.setRequestHandler(UK,()=>u.listTools()),Y0.server.setRequestHandler(E7,E),r.resources)Y0.server.setRequestHandler(HK,()=>u.listResources()),Y0.server.setRequestHandler(VK,(G0)=>u.readResource(G0.params)),Y0.server.setRequestHandler(FK,()=>u.listResourceTemplates());if(r.prompts)Y0.server.setRequestHandler(qK,()=>u.listPrompts()),Y0.server.setRequestHandler(zK,(G0)=>u.getPrompt(G0.params));try{return await H0.handleRequest(f)}finally{try{await H0.close?.()}catch{}}},client:{callTool:(f)=>{return E({method:"tools/call",params:f})},listTools:async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((S)=>({name:S.name,description:S.description,inputSchema:S.inputSchema,outputSchema:S.outputSchema}))};let f;try{return f=await q(),await f.listTools()}finally{f?.close().catch(console.error)}},listResources:async()=>{let f;try{if(f=await q(),!f.getServerCapabilities()?.resources)return{resources:[]};return await f.listResources()}finally{f?.close().catch(console.error)}},readResource:async(f)=>{let S;try{return S=await q(),await S.readResource(f)}finally{S?.close().catch(console.error)}},listResourceTemplates:async()=>{let f;try{if(f=await q(),!f.getServerCapabilities()?.resources)return{resourceTemplates:[]};return await f.listResourceTemplates()}finally{f?.close().catch(console.error)}},listPrompts:async()=>{let f;try{if(f=await q(),!f.getServerCapabilities()?.prompts)return{prompts:[]};return await f.listPrompts()}finally{f?.close().catch(console.error)}},getPrompt:async(f)=>{let S;try{if(S=await q(),!S.getServerCapabilities()?.prompts)throw Error("Prompts capability not supported");return await S.getPrompt(f)}finally{S?.close().catch(console.error)}}},callStreamableTool:async(f,S)=>{if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let u=J.connection_url,t={method:"tools/call",params:{name:f,arguments:S}};return T(t,async()=>{let r=await K();if(V?.headers)Object.assign(r,V.headers);let Y0=new URL(u);return Y0.pathname=Y0.pathname.replace(/\/$/,"")+`/call-tool/${t.params.name}`,await Y.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":t.params.name}},async(H0)=>{let G0=Date.now();try{let B0=await fetch(Y0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(t.params.arguments),headers:{...r,"Content-Type":"application/json"}}),T0=Date.now()-G0;return Y.meter.createHistogram("connection.proxy.streamable.duration").record(T0,{"connection.id":G,"tool.name":t.params.name,status:B0.ok?"success":"error"}),Y.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":t.params.name,status:B0.ok?"success":"error"}),H0.end(),B0}catch(B0){let T0=B0,y0=Date.now()-G0;throw Y.meter.createHistogram("connection.proxy.streamable.duration").record(y0,{"connection.id":G,"tool.name":t.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":t.params.name,error:T0.message}),H0.recordException(T0),H0.end(),B0}})})}}}async function uZ6(X,Y){return gZ6(X,Y,{superUser:!1})}async function mZ6(X,Y){return gZ6(X,Y,{superUser:!0})}var xZ6,lZ6;var qf=v(()=>{t90();zS();IZ6();ab();aW();XB();Cb();pP();kb();vb();E9();k7();WY0();qY0();Ff();xZ6=new C9;xZ6.all("/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=X.get("meshContext");try{return await(await Q.createMCPProxy(Y)).fetch(X.req.raw)}catch(J){let G=J;if(G.message.includes("not found"))return X.json({error:G.message},404);if(G.message.includes("does not belong to the active organization"))return X.json({error:"Connection not found"},404);if(G.message.includes("inactive"))return X.json({error:G.message},503);return X.json({error:"Internal server error",message:G.message},500)}});lZ6=xZ6});class BY0{db;constructor(X){this.db=X}async create(X){let Y=X.id??qQ("thrd"),Q=new Date().toISOString();if(!X.organizationId)throw Error("organizationId is required");if(!X.createdBy)throw Error("createdBy is required");if(!X.title)X.title="New Thread - "+Q;let J={id:Y,organization_id:X.organizationId,title:X.title,description:X.description??null,created_at:Q,updated_at:Q,created_by:X.createdBy,updated_by:X.updatedBy??null},G=await this.db.insertInto("threads").values(J).returningAll().executeTakeFirstOrThrow();return this.threadFromDbRow(G)}async get(X){let Y=await this.db.selectFrom("threads").selectAll().where("id","=",X).executeTakeFirst();return Y?this.threadFromDbRow(Y):null}async update(X,Y){let J={updated_at:new Date().toISOString()};if(Y.title!==void 0)J.title=Y.title;if(Y.description!==void 0)J.description=Y.description;if(Y.updatedBy!==void 0)J.updated_by=Y.updatedBy;await this.db.updateTable("threads").set(J).where("id","=",X).execute();let G=await this.get(X);if(!G)throw Error("Thread not found after update");return G}async delete(X){await this.db.deleteFrom("threads").where("id","=",X).execute()}async list(X,Y){let Q=this.db.selectFrom("threads").selectAll().where("organization_id","=",X).where("hidden","=",!1).orderBy("updated_at","desc"),J=this.db.selectFrom("threads").select((Z)=>Z.fn.count("id").as("count")).where("organization_id","=",X).where("hidden","=",!1);if(Y?.limit)Q=Q.limit(Y.limit);if(Y?.offset)Q=Q.offset(Y.offset);let[G,W]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{threads:G.map((Z)=>this.threadFromDbRow(Z)),total:Number(W?.count||0)}}async listByUserId(X){let Y=await this.db.selectFrom("threads").selectAll().where("created_by","=",X).orderBy("updated_at","desc").execute();return{threads:Y.map((Q)=>this.threadFromDbRow(Q)),total:Y.length}}async saveMessages(X){let Y=new Date().toISOString(),Q=X[0]?.threadId;if(!Q)throw Error("threadId is required when creating multiple messages");let J=X.find((W)=>W.threadId!==Q);if(J)throw Error(`All messages must target the same thread. Expected threadId "${Q}", but message "${J.id}" has threadId "${J.threadId}"`);let G=X.map((W)=>({id:W.id,thread_id:Q,metadata:W.metadata?JSON.stringify(W.metadata):null,parts:JSON.stringify(W.parts),role:W.role,created_at:W.createdAt??Y,updated_at:Y}));await this.db.transaction().execute(async(W)=>{await W.insertInto("thread_messages").values(G).execute(),await W.updateTable("threads").set({updated_at:Y}).where("id","=",Q).execute()})}async listMessages(X,Y){let Q=this.db.selectFrom("thread_messages").selectAll().where("thread_id","=",X).orderBy("created_at","asc").orderBy("id","asc"),J=this.db.selectFrom("thread_messages").select((Z)=>Z.fn.count("id").as("count")).where("thread_id","=",X);if(Y?.limit)Q=Q.limit(Y.limit);if(Y?.offset)Q=Q.offset(Y.offset);let[G,W]=await Promise.all([Q.execute(),J.executeTakeFirst()]);return{messages:G.map((Z)=>this.messageFromDbRow(Z)),total:Number(W?.count||0)}}threadFromDbRow(X){return{id:X.id,organizationId:X.organization_id,title:X.title,description:X.description,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString(),createdBy:X.created_by,updatedBy:X.updated_by,hidden:X.hidden}}messageFromDbRow(X){let Y,Q;try{Y=X.metadata?JSON.parse(X.metadata):void 0}catch(J){console.error(`Failed to parse metadata for message ${X.id}:`,X.metadata,J),Y=void 0}try{Q=typeof X.parts==="string"?JSON.parse(X.parts):X.parts}catch(J){console.error(`Failed to parse parts for message ${X.id}:`,X.parts,J),Q=[]}return{id:X.id,threadId:X.thread_id,metadata:Y,parts:Q,role:X.role,createdAt:typeof X.created_at==="string"?X.created_at:X.created_at.toISOString(),updatedAt:typeof X.updated_at==="string"?X.updated_at:X.updated_at.toISOString()}}}var dZ6=v(()=>{zF()});function ux1(X){if(!X)return;try{let Y=JSON.parse(X);if(typeof Y!=="object"||Y===null||Array.isArray(Y))return;let Q={};for(let[J,G]of Object.entries(Y))if(typeof G==="string")Q[J]=G;return Object.keys(Q).length>0?Q:void 0}catch{return}}function mx1(X,Y){for(let[Q,J]of Object.entries(Y)){let G=X[Q];if(!G||G.length===0){let W=X["*"];if(!W||W.length===0)return!1;if(W.includes("*"))continue;for(let Z of J)if(!W.includes(Z))return!1;continue}if(G.includes("*"))continue;for(let W of J)if(!G.includes(W))return!1}return!0}function lx1(X){let{auth:Y,headers:Q,role:J,permissions:G,userId:W}=X,Z=Y.api.hasPermission;return{hasPermission:async($)=>{if(J&&uX0.includes(J))return!0;if(G)return mx1(G,$);if(!Z)return console.error("[Auth] hasPermission API not available"),!1;try{if((await Z({headers:Q,body:{permission:$}}))?.success===!0)return!0;let H={};for(let V of Object.keys($))H[V]=["*"];return(await Z({headers:Q,body:{permission:H}}))?.success===!0}catch(K){return console.error("[Auth] Permission check failed:",K),!1}},organization:{create:async($)=>{return Y.api.createOrganization({headers:Q,body:$})},update:async($)=>{return Y.api.updateOrganization({headers:Q,body:$})},delete:async($)=>{await Y.api.deleteOrganization({headers:Q,body:{organizationId:$}})},get:async($)=>{return Y.api.getFullOrganization({headers:Q,query:$?{organizationId:$}:void 0})},list:async($)=>{return Y.api.listOrganizations({headers:Q,query:$?{userId:$}:void 0})},addMember:async($)=>{return Y.api.addMember({headers:Q,body:$})},removeMember:async($)=>{await Y.api.removeMember({headers:Q,body:$})},listMembers:async($)=>{return Y.api.listMembers({headers:Q,query:$?{organizationId:$.organizationId,limit:$.limit,offset:$.offset}:void 0})},updateMemberRole:async($)=>{return Y.api.updateMemberRole({headers:Q,body:$})}},apiKey:{create:async($)=>{return Y.api.createApiKey({body:{...$,userId:W}})},list:async()=>{return Y.api.listApiKeys({headers:Q})},update:async($)=>{return Y.api.updateApiKey({body:{...$,userId:W}})},delete:async($)=>{await Y.api.deleteApiKey({headers:Q,body:{keyId:$}})}}}}async function dx1(X,Y,Q){if(uX0.includes(Q))return;let J=await X.selectFrom("organizationRole").select(["permission"]).where("organizationId","=",Y).where("role","=",Q).executeTakeFirst();if(!J?.permission)return;try{return JSON.parse(J.permission)}catch{console.error(`[Auth] Failed to parse permissions for role: ${Q}`);return}}async function px1(X,Y,Q,J=cZ6){let G=X.headers.get("Authorization");try{let W=new Headers(X.headers);W.set("X-MCP-Session-Auth","true");let Z=await J.measure("auth_get_mcp_session",()=>Y.api.getMcpSession({headers:W}));if(Z){let $=Z.userId,K=await J.measure("auth_query_membership",()=>Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","member.organizationId","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",$).executeTakeFirst()),H=K?.role,F=K?{id:K.orgId,slug:K.orgSlug,name:K.orgName}:void 0,V;if(K&&H)V=await J.measure("auth_fetch_role_permissions",()=>dx1(Q,K.organizationId,H));return{user:{id:$,role:H},role:H,permissions:V,organization:F}}}catch(W){console.error("[Auth] OAuth session check failed:",W)}if(G?.startsWith("Bearer ")){let W=G.replace("Bearer ","").trim();try{let Z=await J.measure("auth_verify_mesh_jwt",()=>NZ6(W));if(Z){let $,K=Z.metadata?.organizationId;if(Z.sub&&K)$=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",Z.sub).where("member.organizationId","=",K).executeTakeFirst()))?.role;return{user:{id:Z.sub,connectionId:Z.metadata?.connectionId,role:$},role:$,permissions:Z.permissions,organization:Z.metadata?.organizationId?{id:Z.metadata?.organizationId}:void 0}}}catch{}try{let Z=await J.measure("auth_verify_api_key",()=>Y.api.verifyApiKey({body:{key:W}}));if(Z?.valid&&Z.key){let $=Z.key.metadata?.organization,K=Z.key.permissions,H,F=Z.key.userId;if(F&&$?.id)H=(await J.measure("auth_query_membership",()=>Q.selectFrom("member").select(["member.role"]).where("member.userId","=",F).where("member.organizationId","=",$.id).executeTakeFirst()))?.role;return{apiKeyId:Z.key.id,user:{id:Z.key.userId,role:H},role:H,permissions:K,organization:$?{id:$.id,slug:$.slug,name:$.name}:void 0}}}catch(Z){console.error("[Auth] API key check failed:",Z)}}try{let W=await J.measure("auth_get_session",()=>Y.api.getSession({headers:X.headers}));if(W){let Z,$;if(W.session.activeOrganizationId){let K=await J.measure("auth_get_full_organization",()=>Y.api.getFullOrganization({headers:X.headers}).catch(()=>null));if(K)Z={id:K.id,slug:K.slug,name:K.name},$=K.members?.find((F)=>F.userId===W.user.id)?.role;else Z={id:W.session.activeOrganizationId,slug:"",name:""}}return{user:{id:W.user.id,email:W.user.email,role:$},role:$,organization:Z}}}catch(W){let Z=W;console.error("[Auth] Session check failed:",JSON.stringify({message:Z.message,body:Z.body,stack:Z.stack},null,2))}return{user:void 0}}function nZ6(X){let Y=new gM(X.encryption.key),Q={connections:new uM(X.db,Y),organizationSettings:new HY0(X.db),monitoring:new KY0(X.db,X.databaseType),virtualMcps:new ZY0(X.db),users:new FY0(X.db),threads:new BY0(X.db)};return async(J,G)=>{let W=G?.timings??cZ6,Z=J?.headers.get("x-caller-id")??void 0,$=J?await px1(J,X.auth,X.db,W):{user:void 0},K=lx1({auth:X.auth,headers:J?.headers??new Headers,role:$.role,permissions:$.permissions,userId:$.user?.id}),H={user:$.user};if($.apiKeyId)H.apiKey={id:$.apiKeyId,name:"",userId:""};let F=$.organization,V=J?new URL(J.url):new URL("http://localhost:3000"),q=process.env.BASE_URL??`${V.protocol}//${V.host}`,z=new RB(X.auth,H.user?.id,void 0,K,$.role,g5.SELF),D={timings:W,auth:H,connectionId:Z,organization:F,storage:Q,vault:Y,authInstance:X.auth,boundAuth:K,access:z,db:X.db,tracer:X.observability.tracer,meter:X.observability.meter,baseUrl:q,metadata:{requestId:crypto.randomUUID(),timestamp:new Date,userAgent:J?.headers.get("x-mesh-client")||J?.headers.get("User-Agent")||void 0,ipAddress:(J?.headers.get("CF-Connecting-IP")||J?.headers.get("X-Forwarded-For"))??void 0,properties:ux1(J?.headers.get("x-mesh-properties"))},eventBus:X.eventBus,createMCPProxy:async(N)=>{return await uZ6(N,D)}};return D}}var pZ6,SK,cZ6;var Vf=v(()=>{WY0();J10();G10();OZ6();wZ6();qY0();qf();mX0();JK();dZ6();SK={set:(X)=>{pZ6=X},create:async(X,Y)=>{return await pZ6(X,Y)}},cZ6={measure:async(X,Y)=>{return await Y()}}});function iZ6(X){return X===jT.HEALTH||X===jT.METRICS||X.startsWith(SB.WELL_KNOWN)}function nx1(X){return X.startsWith(SB.API)}function ix1(X){return X==="/mcp"||X.startsWith(SB.MCP)}function ax1(X){return X.startsWith(SB.OAUTH_PROXY)}function rx1(X){return cx1.test(X)}function ox1(X){return X.startsWith(SB.ORG)}function aZ6(X){return nx1(X)||ix1(X)||ax1(X)||ox1(X)||iZ6(X)}function rZ6(X){return X==="/"||X.startsWith(SB.API_AUTH)||iZ6(X)||rx1(X)}var jT,SB,cx1;var DY0=v(()=>{jT={HEALTH:"/health",METRICS:"/metrics"},SB={API:"/api/",API_AUTH:"/api/auth/",MCP:"/mcp/",OAUTH_PROXY:"/oauth-proxy/",WELL_KNOWN:"/.well-known",ORG:"/org/"},cx1=/\.(html|css|js|ico|svg|png|jpg|jpeg|gif|webp|woff|woff2)$/});class oZ6{db;constructor(X){this.db=X}async publishEvent(X){let Y=new Date().toISOString();return await this.db.insertInto("events").values({id:X.id,organization_id:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data?JSON.stringify(X.data):null,cron:X.cron??null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Y,updated_at:Y}).execute(),{id:X.id,organizationId:X.organizationId,type:X.type,source:X.source,specversion:"1.0",subject:X.subject??null,time:X.time,datacontenttype:X.datacontenttype??"application/json",dataschema:X.dataschema??null,data:X.data??null,cron:X.cron??null,status:"pending",attempts:0,lastError:null,nextRetryAt:null,createdAt:Y,updatedAt:Y}}async subscribe(X){let Y=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("connection_id","=",X.connectionId).where("event_type","=",X.eventType);if(X.publisher)Y=Y.where("publisher","=",X.publisher);else Y=Y.where("publisher","is",null);if(X.filter)Y=Y.where("filter","=",X.filter);else Y=Y.where("filter","is",null);let Q=await Y.executeTakeFirst();if(Q)return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at};let J=new Date().toISOString();return await this.db.insertInto("event_subscriptions").values({id:X.id,organization_id:X.organizationId,connection_id:X.connectionId,publisher:X.publisher??null,event_type:X.eventType,filter:X.filter??null,enabled:1,created_at:J,updated_at:J}).execute(),{id:X.id,organizationId:X.organizationId,connectionId:X.connectionId,publisher:X.publisher??null,eventType:X.eventType,filter:X.filter??null,enabled:!0,createdAt:J,updatedAt:J}}async unsubscribe(X,Y){return{success:((await this.db.deleteFrom("event_subscriptions").where("id","=",X).where("organization_id","=",Y).executeTakeFirst()).numDeletedRows??0n)>0n}}async listSubscriptions(X,Y){let Q=this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X);if(Y)Q=Q.where("connection_id","=",Y);return(await Q.execute()).map((G)=>({id:G.id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.created_at,updatedAt:G.updated_at}))}async getSubscription(X,Y){let Q=await this.db.selectFrom("event_subscriptions").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}}async getMatchingSubscriptions(X){return(await this.db.selectFrom("event_subscriptions").selectAll().where("organization_id","=",X.organizationId).where("enabled","=",1).where("event_type","=",X.type).where((Q)=>Q.or([Q("publisher","is",null),Q("publisher","=",X.source)])).execute()).map((Q)=>({id:Q.id,organizationId:Q.organization_id,connectionId:Q.connection_id,publisher:Q.publisher,eventType:Q.event_type,filter:Q.filter,enabled:Q.enabled===1,createdAt:Q.created_at,updatedAt:Q.updated_at}))}async createDeliveries(X,Y,Q){if(Y.length===0)return;let J=new Date().toISOString(),G=Q??null,W=Y.map((Z)=>({id:crypto.randomUUID(),event_id:X,subscription_id:Z,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:G,created_at:J}));await this.db.insertInto("event_deliveries").values(W).execute()}async claimPendingDeliveries(X){let Y=new Date().toISOString(),Q;try{Q=(await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",(W)=>W.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select("d.id").where("d.status","=","pending").where("s.enabled","=",1).where((Z)=>Z.or([Z("d.next_retry_at","is",null),Z("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X)).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id)}catch{let G=await this.db.selectFrom("event_deliveries as d").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id"]).where("d.status","=","pending").where("s.enabled","=",1).where((W)=>W.or([W("d.next_retry_at","is",null),W("d.next_retry_at","<=",Y)])).orderBy("d.created_at","asc").limit(X).execute();if(G.length===0)return[];Q=G.map((W)=>W.id),await this.db.updateTable("event_deliveries").set({status:"processing"}).where("id","in",Q).where("status","=","pending").execute()}if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((G)=>({delivery:{id:G.delivery_id,eventId:G.event_id,subscriptionId:G.subscription_id,status:G.delivery_status,attempts:G.delivery_attempts,lastError:G.delivery_last_error,deliveredAt:G.delivered_at,nextRetryAt:G.delivery_next_retry_at,createdAt:G.delivery_created_at},event:{id:G.event_id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.event_status,attempts:G.event_attempts,lastError:G.event_last_error,nextRetryAt:G.next_retry_at,createdAt:G.event_created_at,updatedAt:G.event_updated_at},subscription:{id:G.subscription_id,organizationId:G.organization_id,connectionId:G.connection_id,publisher:G.publisher,eventType:G.event_type,filter:G.filter,enabled:G.enabled===1,createdAt:G.subscription_created_at,updatedAt:G.subscription_updated_at}}))}async markDeliveriesDelivered(X){if(X.length===0)return;let Y=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Y}).where("id","in",X).execute()}async markDeliveriesFailed(X,Y,Q=20,J=1000,G=3600000){if(X.length===0)return;for(let W of X){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=Q)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(J*Math.pow(2,$-1),G),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(X){let Y=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",X).execute();if(Y.length===0)return;let Q=Y.every((W)=>W.status==="delivered"),J=Y.some((W)=>W.status==="failed"),G=Y.some((W)=>W.status==="pending"||W.status==="processing");if(Q)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",X).execute();else if(J&&!G)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",X).execute()}async resetStuckDeliveries(){let X=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(X.numUpdatedRows??0)}async getEvent(X,Y){let Q=await this.db.selectFrom("events").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!Q)return null;return{id:Q.id,organizationId:Q.organization_id,type:Q.type,source:Q.source,specversion:Q.specversion,subject:Q.subject,time:Q.time,datacontenttype:Q.datacontenttype,dataschema:Q.dataschema,data:Q.data?JSON.parse(Q.data):null,cron:Q.cron,status:Q.status,attempts:Q.attempts,lastError:Q.last_error,nextRetryAt:Q.next_retry_at,createdAt:Q.created_at,updatedAt:Q.updated_at}}async findActiveCronEvent(X,Y,Q,J){let G=await this.db.selectFrom("events").selectAll().where("organization_id","=",X).where("type","=",Y).where("source","=",Q).where("cron","=",J).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async cancelEvent(X,Y,Q){let J=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",X).where("organization_id","=",Y).where("source","=",Q).where("status","in",["pending","processing"]).executeTakeFirst();if((J.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",X).where("status","in",["pending","processing"]).execute();return{success:(J.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(X,Y){if(X.length===0)return;let Q=new Date(Date.now()+Y).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:Q}).where("id","in",X).execute()}async ackDelivery(X,Y,Q){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",X).where("organization_id","=",Y).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",X).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",Q).where("event_subscriptions.organization_id","=",Y))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(X);return{success:W}}async syncSubscriptions(X){let{organizationId:Y,connectionId:Q,subscriptions:J}=X,G=(w,C)=>{return`${w}::${C??""}`},W=await this.listSubscriptions(Y,Q),Z=new Map;for(let w of W)Z.set(G(w.eventType,w.publisher),w);let $=new Map;for(let w of J)$.set(G(w.eventType,w.publisher),w);let K=new Date().toISOString(),H=[],F=[],V=[],q=0;for(let[w,C]of $){let T=Z.get(w);if(!T)H.push({id:crypto.randomUUID(),organization_id:Y,connection_id:Q,event_type:C.eventType,publisher:C.publisher??null,filter:C.filter??null,enabled:1,created_at:K,updated_at:K});else{let E=T.filter??null,P=C.filter??null;if(E!==P)F.push({id:T.id,filter:P});else q++}}for(let[w,C]of Z)if(!$.has(w))V.push(C.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(F.length>0)await Promise.all(F.map((w)=>this.db.updateTable("event_subscriptions").set({filter:w.filter,updated_at:K}).where("id","=",w.id).execute()));if(V.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",V).execute();let z=H.length,D=F.length,N=V.length,L=await this.listSubscriptions(Y,Q);return{created:z,updated:D,deleted:N,unchanged:q,subscriptions:L}}}function sZ6(X){return new oZ6(X)}function JY(X,Y,Q,J,G,W,Z,$){return JY.fromTZ(JY.tp(X,Y,Q,J,G,W,Z),$)}function NY0(X,Y=new Date){let Q=Y.toLocaleString("en-US",{timeZone:X,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],J=Y.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${J} GMT`)-Date.parse(`${J} ${Q}`)}function sx1(X,Y){let Q=new Date(Date.parse(X));if(isNaN(Q))throw Error("minitz: Invalid ISO8601 passed to parser.");let J=X.substring(9);return X.includes("Z")||J.includes("-")||J.includes("+")?JY.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):JY.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),Y)}function tx1(X){if(X===void 0&&(X={}),delete X.name,X.legacyMode=X.legacyMode===void 0?!0:X.legacyMode,X.paused=X.paused===void 0?!1:X.paused,X.maxRuns=X.maxRuns===void 0?1/0:X.maxRuns,X.catch=X.catch===void 0?!1:X.catch,X.interval=X.interval===void 0?0:parseInt(X.interval.toString(),10),X.utcOffset=X.utcOffset===void 0?void 0:parseInt(X.utcOffset.toString(),10),X.unref=X.unref===void 0?!1:X.unref,X.startAt&&(X.startAt=new G5(X.startAt,X.timezone)),X.stopAt&&(X.stopAt=new G5(X.stopAt,X.timezone)),X.interval!==null){if(isNaN(X.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(X.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(X.utcOffset!==void 0){if(isNaN(X.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(X.utcOffset<-870||X.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(X.utcOffset!==void 0&&X.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(X.unref!==!0&&X.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return X}function CT(X){return Object.prototype.toString.call(X)==="[object Function]"||typeof X=="function"||X instanceof Function}function ex1(X){return CT(X)}function Xg1(X){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(X):X&&typeof X.unref<"u"&&X.unref()}var OY0=32,IT,Y$6,tZ6=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(X,Y){this.pattern=X,this.timezone=Y,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let X=this.pattern.replace(/\s+/g," ").split(" ");if(X.length<5||X.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(X.length===5&&X.unshift("0"),X[3].indexOf("L")>=0&&(X[3]=X[3].replace("L",""),this.lastDayOfMonth=!0),X[3]=="*"&&(this.starDOM=!0),X[4].length>=3&&(X[4]=this.replaceAlphaMonths(X[4])),X[5].length>=3&&(X[5]=this.replaceAlphaDays(X[5])),X[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Y=new G5(new Date,this.timezone).getDate(!0);X[0]=X[0].replace("?",Y.getSeconds().toString()),X[1]=X[1].replace("?",Y.getMinutes().toString()),X[2]=X[2].replace("?",Y.getHours().toString()),this.starDOM||(X[3]=X[3].replace("?",Y.getDate().toString())),X[4]=X[4].replace("?",(Y.getMonth()+1).toString()),this.starDOW||(X[5]=X[5].replace("?",Y.getDay().toString()))}this.throwAtIllegalCharacters(X),this.partToArray("second",X[0],0,1),this.partToArray("minute",X[1],0,1),this.partToArray("hour",X[2],0,1),this.partToArray("day",X[3],-1,1),this.partToArray("month",X[4],-1,1),this.partToArray("dayOfWeek",X[5],0,IT),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(X,Y,Q,J){let G=this[X],W=X==="day"&&this.lastDayOfMonth;if(Y===""&&!W)throw TypeError("CronPattern: configuration entry "+X+" ("+Y+") is empty, check for trailing spaces.");if(Y==="*")return G.fill(J);let Z=Y.split(",");if(Z.length>1)for(let $=0;$<Z.length;$++)this.partToArray(X,Z[$],Q,J);else Y.indexOf("-")!==-1&&Y.indexOf("/")!==-1?this.handleRangeWithStepping(Y,X,Q,J):Y.indexOf("-")!==-1?this.handleRange(Y,X,Q,J):Y.indexOf("/")!==-1?this.handleStepping(Y,X,Q,J):Y!==""&&this.handleNumber(Y,X,Q,J)}throwAtIllegalCharacters(X){for(let Y=0;Y<X.length;Y++)if((Y===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(X[Y]))throw TypeError("CronPattern: configuration entry "+Y+" ("+X[Y]+") contains illegal characters.")}handleNumber(X,Y,Q,J){let G=this.extractNth(X,Y),W=parseInt(G[0],10)+Q;if(isNaN(W))throw TypeError("CronPattern: "+Y+" is not a number: '"+X+"'");this.setPart(Y,W,G[1]||J)}setPart(X,Y,Q){if(!Object.prototype.hasOwnProperty.call(this,X))throw TypeError("CronPattern: Invalid part specified: "+X);if(X==="dayOfWeek"){if(Y===7&&(Y=0),Y<0||Y>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Y);this.setNthWeekdayOfMonth(Y,Q);return}if(X==="second"||X==="minute"){if(Y<0||Y>=60)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="hour"){if(Y<0||Y>=24)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="day"){if(Y<0||Y>=31)throw RangeError("CronPattern: Invalid value for "+X+": "+Y)}else if(X==="month"&&(Y<0||Y>=12))throw RangeError("CronPattern: Invalid value for "+X+": "+Y);this[X][Y]=Q}handleRangeWithStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(W===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+X+"'");let[,Z,$,K]=W,H=parseInt(Z,10)+Q,F=parseInt($,10)+Q,V=parseInt(K,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(F))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(V))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(V===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(V>this[Y].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Y].length+")");if(H>F)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let q=H;q<=F;q+=V)this.setPart(Y,q,G[1]||J)}extractNth(X,Y){let Q=X,J;if(Q.includes("#")){if(Y!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");J=Q.split("#")[1],Q=Q.split("#")[0]}return[Q,J]}handleRange(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("-");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+X+"'");let Z=parseInt(W[0],10)+Q,$=parseInt(W[1],10)+Q;if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Z>$)throw TypeError("CronPattern: From value is larger than to value: '"+X+"'");for(let K=Z;K<=$;K++)this.setPart(Y,K,G[1]||J)}handleStepping(X,Y,Q,J){let G=this.extractNth(X,Y),W=G[0].split("/");if(W.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+X+"'");W[0]===""&&(W[0]="*");let Z=0;W[0]!=="*"&&(Z=parseInt(W[0],10)+Q);let $=parseInt(W[1],10);if(isNaN($))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if($===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if($>this[Y].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Y].length+")");for(let K=Z;K<this[Y].length;K+=$)this.setPart(Y,K,G[1]||J)}replaceAlphaDays(X){return X.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(X){return X.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(X){let Y=X.trim().toLowerCase();return Y==="@yearly"||Y==="@annually"?"0 0 1 1 *":Y==="@monthly"?"0 0 1 * *":Y==="@weekly"?"0 0 * * 0":Y==="@daily"?"0 0 * * *":Y==="@hourly"?"0 * * * *":X}setNthWeekdayOfMonth(X,Y){if(typeof Y!="number"&&Y==="L")this.dayOfWeek[X]=this.dayOfWeek[X]|OY0;else if(Y===IT)this.dayOfWeek[X]=IT;else if(Y<6&&Y>0)this.dayOfWeek[X]=this.dayOfWeek[X]|Y$6[Y-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Y}, Type: ${typeof Y}`)}},eZ6,UZ,G5=class X{tz;ms;second;minute;hour;day;month;year;constructor(Y,Q){if(this.tz=Q,Y&&Y instanceof Date)if(!isNaN(Y))this.fromDate(Y);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Y===void 0)this.fromDate(new Date);else if(Y&&typeof Y=="string")this.fromString(Y);else if(Y instanceof X)this.fromCronDate(Y);else throw TypeError("CronDate: Invalid type ("+typeof Y+") passed to CronDate constructor")}isNthWeekdayOfMonth(Y,Q,J,G){let W=new Date(Date.UTC(Y,Q,J)).getUTCDay(),Z=0;for(let $=1;$<=J;$++)new Date(Date.UTC(Y,Q,$)).getUTCDay()===W&&Z++;if(G&IT&&Y$6[Z-1]&G)return!0;if(G&OY0){let $=new Date(Date.UTC(Y,Q+1,0)).getUTCDate();for(let K=J+1;K<=$;K++)if(new Date(Date.UTC(Y,Q,K)).getUTCDay()===W)return!1;return!0}return!1}fromDate(Y){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes()+this.tz,this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),this.apply();else{let Q=JY.toTZ(Y,this.tz);this.ms=Y.getMilliseconds(),this.second=Q.s,this.minute=Q.i,this.hour=Q.h,this.day=Q.d,this.month=Q.m-1,this.year=Q.y}else this.ms=Y.getMilliseconds(),this.second=Y.getSeconds(),this.minute=Y.getMinutes(),this.hour=Y.getHours(),this.day=Y.getDate(),this.month=Y.getMonth(),this.year=Y.getFullYear()}fromCronDate(Y){this.tz=Y.tz,this.year=Y.year,this.month=Y.month,this.day=Y.day,this.hour=Y.hour,this.minute=Y.minute,this.second=Y.second,this.ms=Y.ms}apply(){if(this.month>11||this.day>eZ6[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Y=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Y.getUTCMilliseconds(),this.second=Y.getUTCSeconds(),this.minute=Y.getUTCMinutes(),this.hour=Y.getUTCHours(),this.day=Y.getUTCDate(),this.month=Y.getUTCMonth(),this.year=Y.getUTCFullYear(),!0}else return!1}fromString(Y){if(typeof this.tz=="number"){let Q=JY.fromTZISO(Y);this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply()}else return this.fromDate(JY.fromTZISO(Y,this.tz))}findNext(Y,Q,J,G){let W=this[Q],Z;J.lastDayOfMonth&&(this.month!==1?Z=eZ6[this.month]:Z=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let $=!J.starDOW&&Q=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let K=this[Q]+G;K<J[Q].length;K++){let H=J[Q][K];if(Q==="day"&&J.lastDayOfMonth&&K-G==Z&&(H=1),Q==="day"&&!J.starDOW){let F=J.dayOfWeek[($+(K-G-1))%7];if(F&&F&IT)F=this.isNthWeekdayOfMonth(this.year,this.month,K-G,F)?1:0;else if(F)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${F}`);Y.legacyMode&&!J.starDOM?H=H||F:H=H&&F}if(H)return this[Q]=K-G,W!==this[Q]?2:1}return 3}recurse(Y,Q,J){let G=this.findNext(Q,UZ[J][0],Y,UZ[J][2]);if(G>1){let W=J+1;for(;W<UZ.length;)this[UZ[W][0]]=-UZ[W][2],W++;if(G===3)return this[UZ[J][1]]++,this[UZ[J][0]]=-UZ[J][2],this.apply(),this.recurse(Y,Q,0);if(this.apply())return this.recurse(Y,Q,J-1)}return J+=1,J>=UZ.length?this:this.year>=3000?null:this.recurse(Y,Q,J)}increment(Y,Q,J){return this.second+=Q.interval!==void 0&&Q.interval>1&&J?Q.interval:1,this.ms=0,this.apply(),this.recurse(Y,Q,0)}getDate(Y){return Y||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):JY.fromTZ(JY.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}},X$6=30000,zf,Uf=class{name;options;_states;fn;constructor(X,Y,Q){let J,G;if(CT(Y))G=Y;else if(typeof Y=="object")J=Y;else if(Y!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(CT(Q))G=Q;else if(typeof Q=="object")J=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=J?.name,this.options=tx1(J),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:J?J.maxRuns:void 0,paused:J?J.paused:!1,pattern:new tZ6("* * * * *")},X&&(X instanceof Date||typeof X=="string"&&X.indexOf(":")>0)?this._states.once=new G5(X,this.options.timezone||this.options.utcOffset):this._states.pattern=new tZ6(X,this.options.timezone),this.name){if(zf.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");zf.push(this)}return G!==void 0&&ex1(G)&&(this.fn=G,this.schedule()),this}nextRun(X){let Y=this._next(X);return Y?Y.getDate(!1):null}nextRuns(X,Y){this._states.maxRuns!==void 0&&X>this._states.maxRuns&&(X=this._states.maxRuns);let Q=[],J=Y||this._states.currentRun||void 0;for(;X--&&(J=this.nextRun(J));)Q.push(J);return Q}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let X=this.nextRun(this._states.currentRun),Y=!this._states.paused,Q=this.fn!==void 0,J=!this._states.kill;return Y&&Q&&J&&X!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(X){let Y=this._next(X);return Y?X instanceof G5||X instanceof Date?Y.getTime()-X.getTime():Y.getTime()-new G5(X).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let X=zf.indexOf(this);X>=0&&zf.splice(X,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(X){if(X&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");X&&(this.fn=X);let Y=this.msToNext(),Q=this.nextRun(this._states.currentRun);return Y==null||isNaN(Y)||Q===null?this:(Y>X$6&&(Y=X$6),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),Y),this._states.currentTimeout&&this.options.unref&&Xg1(this._states.currentTimeout),this)}async _trigger(X){if(this._states.blocking=!0,this._states.currentRun=new G5(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Y){CT(this.options.catch)&&this.options.catch(Y,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new G5(X,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(X){let Y=new Date,Q=!this._states.paused&&Y.getTime()>=X.getTime(),J=this._states.blocking&&this.options.protect;Q&&!J?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):Q&&J&&CT(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(X){let Y=!!(X||this._states.currentRun),Q=!1;!X&&this.options.startAt&&this.options.interval&&([X,Y]=this._calculatePreviousRun(X,Y),Q=!X),X=new G5(X,this.options.timezone||this.options.utcOffset),this.options.startAt&&X&&X.getTime()<this.options.startAt.getTime()&&(X=this.options.startAt);let J=this._states.once||new G5(X,this.options.timezone||this.options.utcOffset);return!Q&&J!==this._states.once&&(J=J.increment(this._states.pattern,this.options,Y)),this._states.once&&this._states.once.getTime()<=X.getTime()||J===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&J.getTime()>=this.options.stopAt.getTime()?null:J}_calculatePreviousRun(X,Y){let Q=new G5(void 0,this.options.timezone||this.options.utcOffset),J=X;if(this.options.startAt.getTime()<=Q.getTime()){J=this.options.startAt;let G=J.getTime()+this.options.interval*1000;for(;G<=Q.getTime();)J=new G5(J,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),G=J.getTime()+this.options.interval*1000;Y=!0}return J===null&&(J=void 0),[J,Y]}};var LY0=v(()=>{JY.fromTZISO=(X,Y,Q)=>JY.fromTZ(sx1(X,Y),Q);JY.fromTZ=function(X,Y){let Q=new Date(Date.UTC(X.y,X.m-1,X.d,X.h,X.i,X.s)),J=NY0(X.tz,Q),G=new Date(Q.getTime()-J),W=NY0(X.tz,G);if(W-J===0)return G;{let Z=new Date(Q.getTime()-W),$=NY0(X.tz,Z);if($-W===0)return Z;if(!Y&&$-W>0)return Z;if(Y)throw Error("Invalid date passed to fromTZ()");return G}};JY.toTZ=function(X,Y){let Q=X.toLocaleString("en-US",{timeZone:Y}).replace(/[\u202f]/," "),J=new Date(Q);return{y:J.getFullYear(),m:J.getMonth()+1,d:J.getDate(),h:J.getHours(),i:J.getMinutes(),s:J.getSeconds(),tz:Y}};JY.tp=(X,Y,Q,J,G,W,Z)=>({y:X,m:Y,d:Q,h:J,i:G,s:W,tz:Z});JY.minitz=JY;IT=31|OY0,Y$6=[1,2,4,8,16],eZ6=[31,28,31,30,31,30,31,31,30,31,30,31],UZ=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];zf=[]});var Bf;var wY0=v(()=>{Bf={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function Q$6(){return async(X,Y)=>{try{let Q=await SK.create(),J=await mZ6(X,{...Q,auth:{...Q.auth,user:{id:"notify-worker"}}}),W=await c90.forClient(J).ON_EVENTS({events:Y});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(Q){let J=Q instanceof Error?Q.message:String(Q);return console.error(`[EventBus] Failed to notify connection ${X}:`,J),{success:!1,error:J}}}}var J$6=v(()=>{Vf();cb();qf()});function G$6(X){return{specversion:"1.0",id:X.id,source:X.source,type:X.type,time:X.time,subject:X.subject??void 0,datacontenttype:X.datacontenttype,dataschema:X.dataschema??void 0,data:X.data??void 0}}function Yg1(X){let Y=new Map;for(let J of X){let G=J.subscription.connectionId,W=Y.get(G);if(W){if(W.deliveryIds.push(J.delivery.id),!W.seenEventIds.has(J.event.id))W.seenEventIds.add(J.event.id),W.events.push(G$6(J.event))}else Y.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[G$6(J.event)],seenEventIds:new Set([J.event.id])})}let Q=new Map;for(let[J,G]of Y)Q.set(J,{connectionId:G.connectionId,deliveryIds:G.deliveryIds,events:G.events});return Q}class MY0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(X,Y){this.storage=X;this.notifySubscriber=Q$6(),this.config={...Bf,...Y}}async start(){if(this.running)return;let X=await this.storage.resetStuckDeliveries();if(X>0)console.log(`[EventBus] Reset ${X} stuck deliveries from previous shutdown`);this.running=!0}stop(){this.running=!1,console.log("[EventBus] Worker stopped")}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing)return;this.processing=!0;try{await this.processEvents()}catch(X){console.error("[EventBus] Error processing events:",X)}finally{this.processing=!1}}async processEvents(){let X=await this.storage.claimPendingDeliveries(this.config.batchSize);if(X.length===0)return;let Y=Yg1(X),Q=new Set;for(let[J,G]of Y){try{let W=await this.notifySubscriber(G.connectionId,G.events);if(W.results&&Object.keys(W.results).length>0)await this.processPerEventResults(G,W);else if(W.success)await this.storage.markDeliveriesDelivered(G.deliveryIds);else if(W.retryAfter&&W.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(G.deliveryIds,W.retryAfter);else await this.storage.markDeliveriesFailed(G.deliveryIds,W.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(W){let Z=W instanceof Error?W.message:String(W);console.error(`[EventBus] Failed to notify subscription ${J}:`,Z),await this.storage.markDeliveriesFailed(G.deliveryIds,Z,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}for(let W of X)if(G.deliveryIds.includes(W.delivery.id))Q.add(W.event.id)}for(let J of Q)try{await this.storage.updateEventStatus(J);let G=X.find((W)=>W.event.id===J)?.event;if(G?.cron)await this.scheduleNextCronDelivery(G)}catch(G){console.error(`[EventBus] Failed to update event status ${J}:`,G)}}async processPerEventResults(X,Y){let Q=[],J=new Map,G=[],W=new Map;for(let Z=0;Z<X.events.length;Z++){let $=X.events?.[Z];if(!$)continue;let K=X.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of X.events){let $=W.get(Z.id);if(!$)continue;let K=Y.results?.[Z.id];if(K)if(K.success)Q.push($);else if(K.retryAfter&&K.retryAfter>0){let H=J.get(K.retryAfter)||[];H.push($),J.set(K.retryAfter,H)}else G.push({deliveryId:$,error:K.error||"Event processing failed"});else if(Y.success)Q.push($);else if(Y.retryAfter&&Y.retryAfter>0){let H=J.get(Y.retryAfter)||[];H.push($),J.set(Y.retryAfter,H)}else G.push({deliveryId:$,error:Y.error||"Batch processing failed"})}if(Q.length>0)await this.storage.markDeliveriesDelivered(Q);for(let[Z,$]of J)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(G.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of G){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(X){if(!X.cron)return;try{let Q=new Uf(X.cron).nextRun();if(!Q){console.log(`[EventBus] Cron expression for event ${X.id} has no more runs`);return}let J=Q.toISOString(),G=await this.storage.getMatchingSubscriptions(X);if(G.length===0){console.log(`[EventBus] No subscriptions for cron event ${X.id}, skipping next delivery`);return}await this.storage.createDeliveries(X.id,G.map((W)=>W.id),J),console.log(`[EventBus] Scheduled next cron delivery for event ${X.id} at ${J}`)}catch(Y){console.error(`[EventBus] Failed to schedule next cron delivery for event ${X.id}:`,Y)}}}var W$6=v(()=>{LY0();wY0();J$6()});class PY0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new MY0(this.storage,X.config)}async publish(X,Y,Q){if(Q.deliverAt&&Q.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let J;if(Q.cron){try{let F=new Uf(Q.cron).nextRun();if(!F)throw Error("Cron expression does not produce a next run time");J=F.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(X,Q.type,Y,Q.cron);if(K)return K}let G=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:G,organizationId:X,type:Q.type,source:Y,subject:Q.subject,time:W,data:Q.data,cron:Q.cron}),$=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=Q.deliverAt??J;if(await this.storage.createDeliveries(G,$.map((H)=>H.id),K),this.notifyStrategy&&!K)await this.notifyStrategy.notify(G).catch((H)=>{console.warn("[EventBus] Notify failed (non-critical):",H)})}return Z}async subscribe(X,Y){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:X,connectionId:Y.connectionId,publisher:Y.publisher,eventType:Y.eventType,filter:Y.filter})}async unsubscribe(X,Y){return this.storage.unsubscribe(Y,X)}async listSubscriptions(X,Y){return this.storage.listSubscriptions(X,Y)}async getSubscription(X,Y){return this.storage.getSubscription(Y,X)}async getEvent(X,Y){return this.storage.getEvent(Y,X)}async cancelEvent(X,Y,Q){return this.storage.cancelEvent(Y,X,Q)}async ackEvent(X,Y,Q){return this.storage.ackDelivery(Y,X,Q)}async syncSubscriptions(X,Y){return this.storage.syncSubscriptions({organizationId:X,...Y})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing after notify:",X)})});await this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing pending events on startup:",X)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(X){console.error("[EventBus] Error stopping notify strategy:",X)}console.log("[EventBus] Stopped")}isRunning(){return this.running}}var Z$6=v(()=>{LY0();W$6()});function $$6(...X){return{async start(Y){await Promise.all(X.map((Q)=>Q.start(Y)))},async stop(){await Promise.all(X.map((Y)=>Y.stop().catch((Q)=>{console.error("[NotifyStrategy] Error stopping strategy:",Q)})))},async notify(Y){await Promise.all(X.map((Q)=>Q.notify(Y).catch((J)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",J)})))}}}class Df{intervalMs;timer=null;onNotify=null;constructor(X){this.intervalMs=X}async start(X){if(this.timer)return;this.onNotify=X,this.scheduleNext(),console.log(`[Polling] Started polling every ${this.intervalMs}ms`)}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null,console.log("[Polling] Stopped polling");this.onNotify=null}async notify(X){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}import{sql as Qg1}from"kysely";class TY0{db;pool;listenClient=null;onNotify=null;constructor(X,Y){this.db=X;this.pool=Y}async start(X){if(this.listenClient)return;this.onNotify=X;try{this.listenClient=await this.pool.connect(),this.listenClient.on("notification",(Y)=>{if(Y.channel===kB&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Y)=>{console.error("[PostgresNotify] Connection error:",Y),this.cleanup()}),await this.listenClient.query(`LISTEN ${kB}`),console.log("[PostgresNotify] Started LISTEN on",kB)}catch(Y){console.error("[PostgresNotify] Failed to start LISTEN:",Y),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${kB}`),console.log("[PostgresNotify] Stopped LISTEN on",kB)}catch{}this.cleanup()}}async notify(X){try{await Qg1`SELECT pg_notify(${kB}, ${X})`.execute(this.db)}catch(Y){console.warn("[PostgresNotify] Failed to send NOTIFY:",Y)}}cleanup(){if(this.listenClient)this.listenClient.release(),this.listenClient=null;this.onNotify=null}}var kB="mesh_events";var K$6=()=>{};function H$6(X,Y){let Q=sZ6(X.db),J=Y?.pollIntervalMs??Bf.pollIntervalMs,G=X.type==="postgres"?$$6(new Df(J),new TY0(X.db,X.pool)):new Df(J);return new PY0({storage:Q,config:Y,notifyStrategy:G})}var F$6=v(()=>{Z$6();wY0();K$6()});var V$6;var q$6=v(()=>{V$6={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/webdraw/5f999dcb-c8a6-4572-948c-9996ef1d502f/github.svg"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var z$6,U$6;var B$6=v(()=>{k7();EB();q$6();z$6=new C9;z$6.get("/config",async(X)=>{try{let Y=Object.keys(X9.socialProviders??{}),Q=Y.length>0,J=Y.map((Z)=>({name:Z,icon:V$6[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:X9.emailAndPassword?.enabled??!1},magicLink:{enabled:X9.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:X9.ssoConfig?{enabled:!0,providerId:X9.ssoConfig.providerId}:{enabled:!1},stdioEnabled:G};return X.json({success:!0,config:W})}catch(Y){let Q=Y instanceof Error?Y.message:"Failed to load auth config";return X.json({success:!1,error:Q},500)}});U$6=z$6});var Nf,D$6;var N$6=v(()=>{k7();ab();Nf=new C9;Nf.post("/connections/:connectionId/oauth-token",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("connectionId");if(!(Y.auth.user?.id??Y.auth.apiKey?.userId??null))return X.json({error:"Unauthorized"},401);if(!await Y.storage.connections.findById(Q,Y.organization?.id))return X.json({error:"Connection not found"},404);let W=await X.req.json();if(!W.accessToken)return X.json({error:"accessToken is required"},400);if(W.tokenEndpoint){let F;try{F=new URL(W.tokenEndpoint)}catch{return X.json({error:"tokenEndpoint must be a valid URL"},400)}if(F.protocol!=="http:"&&F.protocol!=="https:")return X.json({error:"tokenEndpoint must be an http(s) URL"},400)}let Z=W.expiresIn?new Date(Date.now()+W.expiresIn*1000):null,$=new qZ(Y.db,Y.vault),K={connectionId:Q,accessToken:W.accessToken,refreshToken:W.refreshToken??null,scope:W.scope??null,expiresAt:Z,clientId:W.clientId??null,clientSecret:W.clientSecret??null,tokenEndpoint:W.tokenEndpoint??null},H=await $.upsert(K);return X.json({success:!0,expiresAt:H.expiresAt})});Nf.delete("/connections/:connectionId/oauth-token",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("connectionId");if(!(Y.auth.user?.id??Y.auth.apiKey?.userId??null))return X.json({error:"Unauthorized"},401);return await new qZ(Y.db,Y.vault).delete(Q),X.json({success:!0})});Nf.get("/connections/:connectionId/oauth-token/status",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("connectionId");if(!(Y.auth.user?.id??Y.auth.apiKey?.userId??null))return X.json({error:"Unauthorized"},401);let G=new qZ(Y.db,Y.vault),W=await G.get(Q);if(!W)return X.json({hasToken:!1,isExpired:!0,canRefresh:!1});let Z=G.isExpired(W),$=!!W.refreshToken&&!!W.tokenEndpoint;return X.json({hasToken:!0,isExpired:Z,canRefresh:$,expiresAt:W.expiresAt})});D$6=Nf});function O$6(X){let Y=U.object({query:U.string().describe("Natural language search query (e.g., 'send email', 'create order')"),limit:U.number().default(10).describe("Maximum results to return (default: 10)")}),Q=rP(X.tools);return{tool:{name:"GATEWAY_SEARCH_TOOLS",description:`Search for available tools by name or description. Returns tool names and brief descriptions without full schemas. Use this to discover tools before calling GATEWAY_DESCRIBE_TOOLS for detailed schemas.${X.categories.length>0?` Available categories: ${X.categories.join(", ")}.`:""} Total tools: ${Q.length}.`,inputSchema:U.toJSONSchema(Y)},handler:async(G)=>{let W=Y.safeParse(G);if(!W.success)return MB({error:W.error.flatten()});let Z=hb(W.data.query,Q,W.data.limit);return ub({query:W.data.query,results:Z.map(($)=>({name:$.name,description:$.description,connection:$._meta.connectionTitle})),totalAvailable:Q.length})}}}function L$6(X){let Y=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),Q=rP(X.tools);return{tool:{name:"GATEWAY_DESCRIBE_TOOLS",description:"Get detailed schemas for specific tools. Call after GATEWAY_SEARCH_TOOLS to get full input/output schemas.",inputSchema:U.toJSONSchema(Y)},handler:async(J)=>{let G=Y.safeParse(J);if(!G.success)return MB({error:G.error.flatten()});let W=xb(G.data.tools,Q);return ub({tools:W.tools,notFound:W.notFound})}}}function Jg1(X){let Y=rP(X.tools),Q=Y.map((W)=>W.name),J=new Map(Y.map((W)=>[W.name,W])),G=U.object({name:(Q.length>0?U.enum(Q):U.string()).describe("The name of the tool to execute"),arguments:U.record(U.string(),U.unknown()).default({}).describe("Arguments to pass to the tool")});return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:U.toJSONSchema(G)},handler:async(W)=>{let Z=G.safeParse(W);if(!Z.success)return MB({error:Z.error.flatten()});let{name:$,arguments:K}=Z.data;if(!J.has($))return{content:[{type:"text",text:`Tool not found: ${$}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return X.callTool($,K)}}}function Gg1(X){let Y=U.object({code:U.string().min(1).describe("JavaScript code to execute. It runs as an async function body; you can use top-level `return` and `await`."),timeoutMs:U.number().default(3000).describe("Max execution time in milliseconds (default: 3000).")}),Q=rP(X.tools);return{tool:{name:"GATEWAY_RUN_CODE",description:'Run JavaScript code in a sandbox. Code must be an ES module that `export default`s an async function that receives (tools) as its first parameter. Use GATEWAY_DESCRIBE_TOOLS to understand the input/output schemas for a tool before calling it. Use `await tools.toolName(args)` or `await tools["tool-name"](args)` to call tools.',inputSchema:U.toJSONSchema(Y)},handler:async(J)=>{let G=Y.safeParse(J);if(!G.success)return MB({error:G.error.flatten()});let W={...X,tools:Q},Z=await gb(G.data.code,W,G.data.timeoutMs);if(Z.error)return MB(Z);return ub(Z)}}}function w$6(X){let Y=new Map(X.map((J)=>[J.tool.name,J.handler])),Q=X.map((J)=>J.tool.name);return{tools:X.map((J)=>J.tool),callTool:async(J,G)=>{let W=Y.get(J);if(!W)return{content:[{type:"text",text:`Unknown meta-tool: ${J}. Available: ${Q.join(", ")}`}],isError:!0};return W(G)}}}function M$6(X){switch(X){case"smart_tool_selection":return $g1;case"code_execution":return Zg1;case"passthrough":default:return Wg1}}function P$6(X){switch(X){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}var Wg1=(X)=>({tools:X.tools,callTool:(Y,Q)=>X.callTool(Y,Q)}),Zg1=(X)=>w$6([O$6(X),L$6(X),Gg1(X)]),$g1=(X)=>w$6([O$6(X),L$6(X),Jg1(X)]);var AY0=v(()=>{X6();oP()});class Of{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=v7(()=>this.loadTools())}async loadTools(){let X=await this.proxies.mapSettled(async(K,H)=>{try{let V=(await K.proxy.client.listTools()).tools;if(this.options.selectionMode==="exclusion"){if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>!q.has(z.name))}}else if(K.selectedTools&&K.selectedTools.length>0){let q=new Set(K.selectedTools);V=V.filter((z)=>q.has(z.name))}return{connectionId:H,connectionTitle:K.connection.title,tools:V}}catch(F){if(!(F instanceof G6)||F.code!==H6.MethodNotFound)console.error(`[aggregator] Failed to list tools ${H}: (defaulting to null)`,F);return null}}),Y=new Set,Q=[],J=new Map,G=new Set;for(let K of X){if(K.status!=="fulfilled"||!K.value)continue;let{connectionId:H,connectionTitle:F,tools:V}=K.value;G.add(F);for(let q of V){if(Y.has(q.name))continue;Y.add(q.name),Q.push({...q,_meta:{connectionId:H,connectionTitle:F}}),J.set(q.name,{connectionId:H,originalName:q.name})}}let W=async(K,H)=>{let F=J.get(K);if(!F)return{content:[{type:"text",text:`Tool not found: ${K}`}],isError:!0};let V=this.proxies.get(F.connectionId);if(!V)return{content:[{type:"text",text:`Connection not found for tool: ${K}`}],isError:!0};return await V.proxy.client.callTool({name:F.originalName,arguments:H})},$=M$6(this.options.strategy)({tools:Q,callTool:W,categories:Array.from(G).sort()});return{tools:Q,mappings:J,strategyResult:$}}async list(){return{tools:(await this.cache).strategyResult.tools}}async call(X){return(await this.cache).strategyResult.callTool(X.name,X.arguments??{})}async callStreamable(X,Y){let Q=await this.cache,J=Q.mappings.get(X);if(J){let W=this.proxies.get(J.connectionId);if(W)return W.proxy.callStreamableTool(J.originalName,Y)}let G=await Q.strategyResult.callTool(X,Y);return new Response(JSON.stringify(G),{headers:{"Content-Type":"application/json"}})}}var T$6=v(()=>{E9();AY0()});function Kg1(X,Y){if(X===Y)return!0;if(!Y.includes("*"))return!1;let Q=Y.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"<<<DOUBLE_STAR>>>").replace(/\*/g,"[^/]*").replace(/<<<DOUBLE_STAR>>>/g,".*");Q=`^${Q}$`;try{return new RegExp(Q).test(X)}catch{return!1}}function A$6(X,Y){return Y.some((Q)=>Kg1(X,Q))}class Lf{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=v7(()=>this.loadResources())}async loadResources(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listResources()).resources;if(this.options.selectionMode==="exclusion"){if(G.selectedResources&&G.selectedResources.length>0)$=$.filter((K)=>!A$6(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>A$6(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){if(!(Z instanceof G6)||Z.code!==H6.MethodNotFound)console.error(`[aggregator] Failed to list resources for connection ${W}: (defaulting to empty array)`,Z);return{connectionId:W,resources:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,resources:Z}=G.value;for(let $ of Z){if(Y.has($.uri))continue;Y.add($.uri),Q.push($),J.set($.uri,W)}}return{resources:Q,mappings:J}}async list(){return{resources:(await this.cache).resources}}async read(X){let Q=(await this.cache).mappings.get(X.uri);if(!Q)throw Error(`Resource not found: ${X.uri}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for resource: ${X.uri}`);return await J.proxy.client.readResource(X)}}var E$6=v(()=>{E9()});class wf{proxies;cache;constructor(X){this.proxies=X;this.cache=v7(()=>this.loadResourceTemplates())}async loadResourceTemplates(){let X=await this.proxies.mapSettled(async(Q,J)=>{try{let G=await Q.proxy.client.listResourceTemplates();return{connectionId:J,templates:G.resourceTemplates}}catch(G){if(!(G instanceof G6)||G.code!==H6.MethodNotFound)console.error(`[aggregator] Failed to list resource templates for connection ${J}: (defaulting to empty array)`,G);return{connectionId:J,templates:[]}}}),Y=[];for(let Q of X){if(Q.status!=="fulfilled")continue;let{templates:J}=Q.value;for(let G of J)Y.push(G)}return{templates:Y}}async list(){return{resourceTemplates:(await this.cache).templates}}}var j$6=v(()=>{E9()});class Mf{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=v7(()=>this.loadPrompts())}async loadPrompts(){let X=await this.proxies.mapSettled(async(G,W)=>{try{let $=(await G.proxy.client.listPrompts()).prompts;if(this.options.selectionMode==="exclusion"){if(G.selectedPrompts&&G.selectedPrompts.length>0){let K=new Set(G.selectedPrompts);$=$.filter((H)=>!K.has(H.name))}}else if(!G.selectedPrompts||G.selectedPrompts.length===0)$=[];else{let K=new Set(G.selectedPrompts);$=$.filter((H)=>K.has(H.name))}return{connectionId:W,prompts:$}}catch(Z){return console.error(`[PromptAggregator] Failed to list prompts for connection ${W}:`,Z),{connectionId:W,prompts:[]}}}),Y=new Set,Q=[],J=new Map;for(let G of X){if(G.status!=="fulfilled")continue;let{connectionId:W,prompts:Z}=G.value;for(let $ of Z){if(Y.has($.name))continue;Y.add($.name),Q.push($),J.set($.name,W)}}return{prompts:Q,mappings:J}}async list(){return{prompts:(await this.cache).prompts}}async get(X){let Q=(await this.cache).mappings.get(X.name);if(!Q)throw Error(`Prompt not found: ${X.name}`);let J=this.proxies.get(Q);if(!J)throw Error(`Connection not found for prompt: ${X.name}`);return await J.proxy.client.getPrompt(X)}}var C$6=()=>{};var I$6=v(()=>{T$6();E$6();j$6();C$6()});async function Hg1(X,Y){let Q=await SF.create(X.connections,Y),J=new Of(Q,{selectionMode:X.toolSelectionMode,strategy:X.toolSelectionStrategy}),G=new Lf(Q,{selectionMode:X.toolSelectionMode}),W=new wf(Q),Z=new Mf(Q,{selectionMode:X.toolSelectionMode});return{client:{listTools:J.list.bind(J),callTool:J.call.bind(J),listResources:G.list.bind(G),readResource:G.read.bind(G),listResourceTemplates:W.list.bind(W),listPrompts:Z.list.bind(Z),getPrompt:Z.get.bind(Z)},callStreamableTool:J.callStreamable.bind(J)}}async function Fg1(X,Y,Q){let J;if(X.tool_selection_mode==="exclusion"){let Z=(await Y.storage.connections.list(X.organization_id)).filter((K)=>K.status==="active"),$=new Map;for(let K of X.connections)$.set(K.connection_id,{selectedTools:K.selected_tools,selectedResources:K.selected_resources,selectedPrompts:K.selected_prompts});J=[];for(let K of Z){let H=$.get(K.id);if(H===void 0)J.push({connection:K,selectedTools:null,selectedResources:null,selectedPrompts:null});else if((H.selectedTools===null||H.selectedTools.length===0)&&(H.selectedResources===null||H.selectedResources.length===0)&&(H.selectedPrompts===null||H.selectedPrompts.length===0));else J.push({connection:K,selectedTools:H.selectedTools,selectedResources:H.selectedResources,selectedPrompts:H.selectedPrompts})}}else{let W=X.connections.map(($)=>$.connection_id),Z=[];for(let $ of W){let K=await Y.storage.connections.findById($);if(K&&K.status==="active")Z.push(K)}J=Z.map(($)=>{let K=X.connections.find((H)=>H.connection_id===$.id);return{connection:$,selectedTools:K?.selected_tools??null,selectedResources:K?.selected_resources??null,selectedPrompts:K?.selected_prompts??null}})}let G={connections:J,toolSelectionMode:X.tool_selection_mode,toolSelectionStrategy:Q};return Hg1(G,Y)}async function R$6(X,Y){let Q=X.get("meshContext");try{let J=X.req.header("x-org-id"),G=X.req.header("x-org-slug"),W=J?J:G?await Q.db.selectFrom("organization").select("id").where("slug","=",G).executeTakeFirst().then((z)=>z?.id):null,Z=Y?await Q.storage.virtualMcps.findById(Y):W?j16(W):null;if(!Z)return X.json({error:"Agent not found"},404);if(W&&Z.organization_id!==W)return X.json({error:"Agent not found"},404);if(Q.virtualMcpId=Z.id,Z.status!=="active")return X.json({error:`Agent is inactive: ${Z.id}`},503);let $=await Q.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",Z.organization_id).executeTakeFirst();if($)Q.organization={id:$.id,slug:$.slug,name:$.name};let K=X.req.query("mode"),H=P$6(K),F=await Fg1(Z,Q,H),V=new IF({name:`mcp-virtual-mcp-${Z.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}}}),q=new RF({enableJsonResponse:X.req.header("Accept")?.includes("application/json")??!1});await V.connect(q),V.server.setRequestHandler(UK,async(z)=>{return F.client.listTools()}),V.server.setRequestHandler(E7,async(z)=>{return await F.client.callTool(z.params)}),V.server.setRequestHandler(HK,async()=>{return F.client.listResources()}),V.server.setRequestHandler(VK,async(z)=>{return F.client.readResource(z.params)}),V.server.setRequestHandler(FK,async()=>{return F.client.listResourceTemplates()}),V.server.setRequestHandler(qK,async()=>{return F.client.listPrompts()}),V.server.setRequestHandler(zK,async(z)=>{return F.client.getPrompt(z.params)});try{return await q.handleRequest(X.req.raw)}finally{try{await q.close?.()}catch{}}}catch(J){let G=J;return console.error("[virtual-mcp] Error handling virtual MCP request:",G),X.json({error:"Internal server error",message:G.message},500)}}var EY0,S$6;var k$6=v(()=>{kb();vb();E9();k7();I$6();AY0();JK();EY0=new C9;EY0.all("/gateway/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return R$6(X,Y)});EY0.all("/virtual-mcp/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return R$6(X,Y)});S$6=EY0});var v$6,_$6;var y$6=v(()=>{k7();gX0();v$6=new C9;v$6.all("/",async(X)=>{return xX0(X.get("meshContext")).fetch(X.req.raw)});_$6=v$6});function XG(X){if(X==null)return"unknown error";if(typeof X==="string")return X;if(X instanceof Error)return X.message;return JSON.stringify(X)}var HK6="vercel.ai.error",Vg1,b$6,f$6,N6,FK6="AI_APICallError",VK6,qg1,h$6,x$6,Y9,qK6="AI_EmptyResponseBodyError",zK6,zg1,g$6,u$6,UK6,BK6="AI_InvalidArgumentError",DK6,Ug1,m$6,l$6,NK6,OK6="AI_InvalidPromptError",LK6,Bg1,d$6,p$6,pF,wK6="AI_InvalidResponseDataError",MK6,Dg1,c$6,n$6,Ut4,PK6="AI_JSONParseError",TK6,Ng1,i$6,a$6,RT,AK6="AI_LoadAPIKeyError",EK6,Og1,r$6,o$6,Bt4,jK6="AI_LoadSettingError",CK6,Lg1,s$6,t$6,Dt4,IK6="AI_NoContentGeneratedError",RK6,wg1,e$6,XK6,Nt4,SK6="AI_NoSuchModelError",kK6,Mg1,YK6,QK6,Ot4,vK6="AI_TooManyEmbeddingValuesForCallError",_K6,Pg1,JK6,GK6,Lt4,yK6="AI_TypeValidationError",bK6,Tg1,WK6,ZK6,YG,fK6="AI_UnsupportedFunctionalityError",hK6,Ag1,$K6,KK6,xK6;var P4=v(()=>{Vg1=Symbol.for(HK6),N6=class X extends(f$6=Error,b$6=Vg1,f$6){constructor({name:Y,message:Q,cause:J}){super(Q);this[b$6]=!0,this.name=Y,this.cause=J}static isInstance(Y){return X.hasMarker(Y,HK6)}static hasMarker(Y,Q){let J=Symbol.for(Q);return Y!=null&&typeof Y==="object"&&J in Y&&typeof Y[J]==="boolean"&&Y[J]===!0}},VK6=`vercel.ai.error.${FK6}`,qg1=Symbol.for(VK6),Y9=class extends(x$6=N6,h$6=qg1,x$6){constructor({message:X,url:Y,requestBodyValues:Q,statusCode:J,responseHeaders:G,responseBody:W,cause:Z,isRetryable:$=J!=null&&(J===408||J===409||J===429||J>=500),data:K}){super({name:FK6,message:X,cause:Z});this[h$6]=!0,this.url=Y,this.requestBodyValues=Q,this.statusCode=J,this.responseHeaders=G,this.responseBody=W,this.isRetryable=$,this.data=K}static isInstance(X){return N6.hasMarker(X,VK6)}},zK6=`vercel.ai.error.${qK6}`,zg1=Symbol.for(zK6),UK6=class extends(u$6=N6,g$6=zg1,u$6){constructor({message:X="Empty response body"}={}){super({name:qK6,message:X});this[g$6]=!0}static isInstance(X){return N6.hasMarker(X,zK6)}};DK6=`vercel.ai.error.${BK6}`,Ug1=Symbol.for(DK6),NK6=class extends(l$6=N6,m$6=Ug1,l$6){constructor({message:X,cause:Y,argument:Q}){super({name:BK6,message:X,cause:Y});this[m$6]=!0,this.argument=Q}static isInstance(X){return N6.hasMarker(X,DK6)}},LK6=`vercel.ai.error.${OK6}`,Bg1=Symbol.for(LK6),pF=class extends(p$6=N6,d$6=Bg1,p$6){constructor({prompt:X,message:Y,cause:Q}){super({name:OK6,message:`Invalid prompt: ${Y}`,cause:Q});this[d$6]=!0,this.prompt=X}static isInstance(X){return N6.hasMarker(X,LK6)}},MK6=`vercel.ai.error.${wK6}`,Dg1=Symbol.for(MK6),Ut4=class extends(n$6=N6,c$6=Dg1,n$6){constructor({data:X,message:Y=`Invalid response data: ${JSON.stringify(X)}.`}){super({name:wK6,message:Y});this[c$6]=!0,this.data=X}static isInstance(X){return N6.hasMarker(X,MK6)}},TK6=`vercel.ai.error.${PK6}`,Ng1=Symbol.for(TK6),RT=class extends(a$6=N6,i$6=Ng1,a$6){constructor({text:X,cause:Y}){super({name:PK6,message:`JSON parsing failed: Text: ${X}.
1074
1074
  Error message: ${XG(Y)}`,cause:Y});this[i$6]=!0,this.text=X}static isInstance(X){return N6.hasMarker(X,TK6)}},EK6=`vercel.ai.error.${AK6}`,Og1=Symbol.for(EK6),Bt4=class extends(o$6=N6,r$6=Og1,o$6){constructor({message:X}){super({name:AK6,message:X});this[r$6]=!0}static isInstance(X){return N6.hasMarker(X,EK6)}},CK6=`vercel.ai.error.${jK6}`,Lg1=Symbol.for(CK6),Dt4=class extends(t$6=N6,s$6=Lg1,t$6){constructor({message:X}){super({name:jK6,message:X});this[s$6]=!0}static isInstance(X){return N6.hasMarker(X,CK6)}},RK6=`vercel.ai.error.${IK6}`,wg1=Symbol.for(RK6),Nt4=class extends(XK6=N6,e$6=wg1,XK6){constructor({message:X="No content generated."}={}){super({name:IK6,message:X});this[e$6]=!0}static isInstance(X){return N6.hasMarker(X,RK6)}},kK6=`vercel.ai.error.${SK6}`,Mg1=Symbol.for(kK6),Ot4=class extends(QK6=N6,YK6=Mg1,QK6){constructor({errorName:X=SK6,modelId:Y,modelType:Q,message:J=`No such ${Q}: ${Y}`}){super({name:X,message:J});this[YK6]=!0,this.modelId=Y,this.modelType=Q}static isInstance(X){return N6.hasMarker(X,kK6)}},_K6=`vercel.ai.error.${vK6}`,Pg1=Symbol.for(_K6),Lt4=class extends(GK6=N6,JK6=Pg1,GK6){constructor(X){super({name:vK6,message:`Too many values for a single embedding call. The ${X.provider} model "${X.modelId}" can only embed up to ${X.maxEmbeddingsPerCall} values per call, but ${X.values.length} values were provided.`});this[JK6]=!0,this.provider=X.provider,this.modelId=X.modelId,this.maxEmbeddingsPerCall=X.maxEmbeddingsPerCall,this.values=X.values}static isInstance(X){return N6.hasMarker(X,_K6)}},bK6=`vercel.ai.error.${yK6}`,Tg1=Symbol.for(bK6),YG=class X extends(ZK6=N6,WK6=Tg1,ZK6){constructor({value:Y,cause:Q}){super({name:yK6,message:`Type validation failed: Value: ${JSON.stringify(Y)}.
1075
1075
  Error message: ${XG(Q)}`,cause:Q});this[WK6]=!0,this.value=Y}static isInstance(Y){return N6.hasMarker(Y,bK6)}static wrap({value:Y,cause:Q}){return X.isInstance(Q)&&Q.value===Y?Q:new X({value:Y,cause:Q})}},hK6=`vercel.ai.error.${fK6}`,Ag1=Symbol.for(hK6),xK6=class extends(KK6=N6,$K6=Ag1,KK6){constructor({functionality:X,message:Y=`'${X}' functionality not supported.`}){super({name:fK6,message:Y});this[$K6]=!0,this.functionality=X}static isInstance(X){return N6.hasMarker(X,hK6)}}});var gK6=()=>{};function nF(...X){return X.reduce((Y,Q)=>({...Y,...Q!=null?Q:{}}),{})}async function nK6(X,Y){if(X==null)return Promise.resolve();let Q=Y==null?void 0:Y.abortSignal;return new Promise((J,G)=>{if(Q==null?void 0:Q.aborted){G(uK6());return}let W=setTimeout(()=>{Z(),J()},X),Z=()=>{clearTimeout(W),Q==null||Q.removeEventListener("abort",$)},$=()=>{Z(),G(uK6())};Q==null||Q.addEventListener("abort",$)})}function uK6(){return new DOMException("Delay was aborted","AbortError")}function ST(X){return Object.fromEntries([...X.headers])}function vB(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),Q=jg1(Y);return Uint8Array.from(Q,(J)=>J.codePointAt(0))}function aF(X){let Y="";for(let Q=0;Q<X.length;Q++)Y+=String.fromCodePoint(X[Q]);return Eg1(Y)}function kT(X){if(X==null)return"unknown error";if(typeof X==="string")return X;if(X instanceof Error)return X.message;return JSON.stringify(X)}function BZ(X){return(X instanceof Error||X instanceof DOMException)&&(X.name==="AbortError"||X.name==="ResponseAborted"||X.name==="TimeoutError")}function rK6({error:X,url:Y,requestBodyValues:Q}){if(BZ(X))return X;if(X instanceof TypeError&&Rg1.includes(X.message.toLowerCase())){let J=X.cause;if(J!=null)return new Y9({message:`Cannot connect to API: ${J.message}`,cause:J,url:Y,requestBodyValues:Q,isRetryable:!0})}return X}function Tf(X=globalThis){var Y,Q,J;if(X.window)return"runtime/browser";if((Y=X.navigator)==null?void 0:Y.userAgent)return`runtime/${X.navigator.userAgent.toLowerCase()}`;if((J=(Q=X.process)==null?void 0:Q.versions)==null?void 0:J.node)return`runtime/node.js/${X.process.version.substring(0)}`;if(X.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function Sg1(X){if(X==null)return{};let Y={};if(X instanceof Headers)X.forEach((Q,J)=>{Y[J.toLowerCase()]=Q});else{if(!Array.isArray(X))X=Object.entries(X);for(let[Q,J]of X)if(J!=null)Y[Q.toLowerCase()]=J}return Y}function kK(X,...Y){let Q=new Headers(Sg1(X)),J=Q.get("user-agent")||"";return Q.set("user-agent",[J,...Y].filter(Boolean).join(" ")),Object.fromEntries(Q.entries())}function sK6(X){return X!=null}function tK6({mediaType:X,url:Y,supportedUrls:Q}){return Y=Y.toLowerCase(),X=X.toLowerCase(),Object.entries(Q).map(([J,G])=>{let W=J.toLowerCase();return W==="*"||W==="*/*"?{mediaTypePrefix:"",regexes:G}:{mediaTypePrefix:W.replace(/\*/,""),regexes:G}}).filter(({mediaTypePrefix:J})=>X.startsWith(J)).flatMap(({regexes:J})=>J).some((J)=>J.test(Y))}function vT({settingValue:X,environmentVariableName:Y}){if(typeof X==="string")return X;if(X!=null||typeof process>"u")return;if(X=process.env[Y],X==null||typeof X!=="string")return;return X}function dK6(X){let Y=JSON.parse(X);if(Y===null||typeof Y!=="object")return Y;if(vg1.test(X)===!1&&_g1.test(X)===!1)return Y;return yg1(Y)}function yg1(X){let Y=[X];while(Y.length){let Q=Y;Y=[];for(let J of Q){if(Object.prototype.hasOwnProperty.call(J,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(J,"constructor")&&Object.prototype.hasOwnProperty.call(J.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let G in J){let W=J[G];if(W&&typeof W==="object")Y.push(W)}}}return X}function eK6(X){let{stackTraceLimit:Y}=Error;try{Error.stackTraceLimit=0}catch(Q){return dK6(X)}try{return dK6(X)}finally{Error.stackTraceLimit=Y}}function kY0(X){if(X.type==="object"||Array.isArray(X.type)&&X.type.includes("object")){X.additionalProperties=!1;let{properties:Q}=X;if(Q!=null)for(let J of Object.keys(Q))Q[J]=cF(Q[J])}if(X.items!=null)X.items=Array.isArray(X.items)?X.items.map(cF):cF(X.items);if(X.anyOf!=null)X.anyOf=X.anyOf.map(cF);if(X.allOf!=null)X.allOf=X.allOf.map(cF);if(X.oneOf!=null)X.oneOf=X.oneOf.map(cF);let{definitions:Y}=X;if(Y!=null)for(let Q of Object.keys(Y))Y[Q]=cF(Y[Q]);return X}function cF(X){if(typeof X==="boolean")return X;return kY0(X)}function QJ(){return{}}function hg1(X,Y){var Q,J,G;let W={type:"array"};if(((Q=X.type)==null?void 0:Q._def)&&((G=(J=X.type)==null?void 0:J._def)==null?void 0:G.typeName)!==A0.ZodAny)W.items=f4(X.type._def,{...Y,currentPath:[...Y.currentPath,"items"]});if(X.minLength)W.minItems=X.minLength.value;if(X.maxLength)W.maxItems=X.maxLength.value;if(X.exactLength)W.minItems=X.exactLength.value,W.maxItems=X.exactLength.value;return W}function xg1(X){let Y={type:"integer",format:"int64"};if(!X.checks)return Y;for(let Q of X.checks)switch(Q.kind){case"min":if(Q.inclusive)Y.minimum=Q.value;else Y.exclusiveMinimum=Q.value;break;case"max":if(Q.inclusive)Y.maximum=Q.value;else Y.exclusiveMaximum=Q.value;break;case"multipleOf":Y.multipleOf=Q.value;break}return Y}function gg1(){return{type:"boolean"}}function XH6(X,Y){return f4(X.type._def,Y)}function YH6(X,Y,Q){let J=Q!=null?Q:Y.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>YH6(X,Y,G))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return mg1(X)}}function lg1(X,Y){return{...f4(X.innerType._def,Y),default:X.defaultValue()}}function dg1(X,Y){return Y.effectStrategy==="input"?f4(X.schema._def,Y):QJ()}function pg1(X){return{type:"string",enum:Array.from(X.values)}}function ng1(X,Y){let Q=[f4(X.left._def,{...Y,currentPath:[...Y.currentPath,"allOf","0"]}),f4(X.right._def,{...Y,currentPath:[...Y.currentPath,"allOf","1"]})].filter((G)=>!!G),J=[];return Q.forEach((G)=>{if(cg1(G))J.push(...G.allOf);else{let W=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:Z,...$}=G;W=$}J.push(W)}}),J.length?{allOf:J}:void 0}function ig1(X){let Y=typeof X.value;if(Y!=="bigint"&&Y!=="number"&&Y!=="boolean"&&Y!=="string")return{type:Array.isArray(X.value)?"array":"object"};return{type:Y==="bigint"?"integer":Y,const:X.value}}function QH6(X,Y){let Q={type:"string"};if(X.checks)for(let J of X.checks)switch(J.kind){case"min":Q.minLength=typeof Q.minLength==="number"?Math.max(Q.minLength,J.value):J.value;break;case"max":Q.maxLength=typeof Q.maxLength==="number"?Math.min(Q.maxLength,J.value):J.value;break;case"email":switch(Y.emailStrategy){case"format:email":JG(Q,"email",J.message,Y);break;case"format:idn-email":JG(Q,"idn-email",J.message,Y);break;case"pattern:zod":hY(Q,QG.email,J.message,Y);break}break;case"url":JG(Q,"uri",J.message,Y);break;case"uuid":JG(Q,"uuid",J.message,Y);break;case"regex":hY(Q,J.regex,J.message,Y);break;case"cuid":hY(Q,QG.cuid,J.message,Y);break;case"cuid2":hY(Q,QG.cuid2,J.message,Y);break;case"startsWith":hY(Q,RegExp(`^${CY0(J.value,Y)}`),J.message,Y);break;case"endsWith":hY(Q,RegExp(`${CY0(J.value,Y)}$`),J.message,Y);break;case"datetime":JG(Q,"date-time",J.message,Y);break;case"date":JG(Q,"date",J.message,Y);break;case"time":JG(Q,"time",J.message,Y);break;case"duration":JG(Q,"duration",J.message,Y);break;case"length":Q.minLength=typeof Q.minLength==="number"?Math.max(Q.minLength,J.value):J.value,Q.maxLength=typeof Q.maxLength==="number"?Math.min(Q.maxLength,J.value):J.value;break;case"includes":{hY(Q,RegExp(CY0(J.value,Y)),J.message,Y);break}case"ip":{if(J.version!=="v6")JG(Q,"ipv4",J.message,Y);if(J.version!=="v4")JG(Q,"ipv6",J.message,Y);break}case"base64url":hY(Q,QG.base64url,J.message,Y);break;case"jwt":hY(Q,QG.jwt,J.message,Y);break;case"cidr":{if(J.version!=="v6")hY(Q,QG.ipv4Cidr,J.message,Y);if(J.version!=="v4")hY(Q,QG.ipv6Cidr,J.message,Y);break}case"emoji":hY(Q,QG.emoji(),J.message,Y);break;case"ulid":{hY(Q,QG.ulid,J.message,Y);break}case"base64":{switch(Y.base64Strategy){case"format:binary":{JG(Q,"binary",J.message,Y);break}case"contentEncoding:base64":{Q.contentEncoding="base64";break}case"pattern:zod":{hY(Q,QG.base64,J.message,Y);break}}break}case"nanoid":hY(Q,QG.nanoid,J.message,Y);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Q}function CY0(X,Y){return Y.patternStrategy==="escape"?rg1(X):X}function rg1(X){let Y="";for(let Q=0;Q<X.length;Q++){if(!ag1.has(X[Q]))Y+="\\";Y+=X[Q]}return Y}function JG(X,Y,Q,J){var G;if(X.format||((G=X.anyOf)==null?void 0:G.some((W)=>W.format))){if(!X.anyOf)X.anyOf=[];if(X.format)X.anyOf.push({format:X.format}),delete X.format;X.anyOf.push({format:Y,...Q&&J.errorMessages&&{errorMessage:{format:Q}}})}else X.format=Y}function hY(X,Y,Q,J){var G;if(X.pattern||((G=X.allOf)==null?void 0:G.some((W)=>W.pattern))){if(!X.allOf)X.allOf=[];if(X.pattern)X.allOf.push({pattern:X.pattern}),delete X.pattern;X.allOf.push({pattern:cK6(Y,J),...Q&&J.errorMessages&&{errorMessage:{pattern:Q}}})}else X.pattern=cK6(Y,J)}function cK6(X,Y){var Q;if(!Y.applyRegexFlags||!X.flags)return X.source;let J={i:X.flags.includes("i"),m:X.flags.includes("m"),s:X.flags.includes("s")},G=J.i?X.source.toLowerCase():X.source,W="",Z=!1,$=!1,K=!1;for(let H=0;H<G.length;H++){if(Z){W+=G[H],Z=!1;continue}if(J.i){if($){if(G[H].match(/[a-z]/)){if(K)W+=G[H],W+=`${G[H-2]}-${G[H]}`.toUpperCase(),K=!1;else if(G[H+1]==="-"&&((Q=G[H+2])==null?void 0:Q.match(/[a-z]/)))W+=G[H],K=!0;else W+=`${G[H]}${G[H].toUpperCase()}`;continue}}else if(G[H].match(/[a-z]/)){W+=`[${G[H]}${G[H].toUpperCase()}]`;continue}}if(J.m){if(G[H]==="^"){W+=`(^|(?<=[\r
1076
1076
  ]))`;continue}else if(G[H]==="$"){W+=`($|(?=[\r
@@ -1135,7 +1135,7 @@ Follow this state machine when handling user requests:
1135
1135
  - All tool calls are logged and audited for security and compliance
1136
1136
  - You have access to the tools exposed through the selected agent/gateway
1137
1137
  - Connections may expose resources that users can browse and edit
1138
- - When users mention "agents", they are typically referring to gateways`},rp1=U.object({messages:U.any(),model:U.object({id:U.string(),connectionId:U.string(),provider:U.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable(),limits:U.object({contextWindow:U.number().optional(),maxOutputTokens:U.number().optional()}).optional()}).loose(),gateway:U.object({id:U.string().nullable()}).loose(),stream:U.boolean().optional(),temperature:U.number().optional(),maxWindowSize:U.number().optional(),thread_id:U.string().optional()}),mF6=new C9;mF6.post("/:org/models/stream",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("org"),J=null;try{let G=op1(Y,Q),W=await X.req.json(),Z=rp1.safeParse(W);if(!Z.success)return X.json({error:"Invalid request body",details:Z.error.issues},400);let $=Z.data,{model:K,gateway:H,messages:F,temperature:V,maxWindowSize:q=ip1,thread_id:z}=$,D=K.limits?.maxOutputTokens??np1,N=ep1(X.req.raw,G.id,H.id),L=new OQ({name:"mcp-mesh-proxy",version:"1.0.0"}),[w,C]=await Promise.all([bF6(F,{ignoreIncompleteToolCalls:!0}),sp1(Y,G.id,K.connectionId),L.connect(N)]);if(!C)return X.json({error:`Model connection not found: ${K.connectionId}`},404);J=L;let T=[ap1,...w.filter((a)=>a.role==="system")],E=w.filter((a)=>a.role!=="system"),P=fF6({messages:E,reasoning:"before-last-message",emptyMessages:"remove",toolCalls:"none"}).slice(-q),j=z?{thread_id:z}:void 0,[R,k]=await Promise.all([Y.createMCPProxy(C),tp1(L,j)]),y=cG6.forClient(R),b=gF6(y).languageModel(K.id);return yF6({model:b,system:T,messages:P,tools:k,temperature:V,maxOutputTokens:D,abortSignal:X.req.raw.signal,stopWhen:KQ0(30),onError:async(a)=>{console.error("[models:stream] Error",a),await L.close().catch(console.error)},onFinish:async()=>{await L.close().catch(console.error)}}).toUIMessageStreamResponse({messageMetadata:({part:a})=>{if(a.type==="start")return{gateway:H,model:K,created_at:new Date,thread_id:z};if(a.type==="reasoning-start")return{reasoning_start_at:new Date};if(a.type==="reasoning-end")return{reasoning_end_at:new Date};if(a.type==="finish-step")return{usage:{...a.usage,providerMetadata:a.providerMetadata}};return{}}})}catch(G){let W=G;if(await J?.close().catch(console.error),W.name==="AbortError")return console.warn("[models:stream] Aborted",JSON.stringify({org:Q})),X.json({error:"Request aborted"},400);return console.error("[models:stream] Failed",JSON.stringify({org:Q,error:W.message,stack:W.stack})),X.json({error:W.message},500)}});lF6=mF6});var pF6,cF6;var nF6=v(()=>{k7();zS();pF6=new C9;pF6.get("/",(X)=>{let Y={theme:jN0()};return X.json({success:!0,config:Y})});cF6=pF6});var iF6=()=>{};async function Xc1(X,Y){let J=(await X.storage.connections.list(Y)).find((G)=>G.connection_url?.startsWith(M16));if(!J?.configuration_state)return null;return J.configuration_state.project_locator}function Yc1(X){let Y=new URLSearchParams;if(X){let[Q,J]=X.split("/");if(Q)Y.set("workspace_hint",Q);if(J)Y.set("project_hint",J)}else Y.set("auto_personal","true");return Y}function rF6(X={}){let Y=X.database??FF();if(yf&&yf.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(yf.stop()).catch((Z)=>{console.error("[EventBus] Error stopping previous worker:",Z)});let Q;if(X.eventBus)Q=X.eventBus;else Q=H$6(Y);yf=Q;let J=new C9;J.use("*",JY0({enabled:(Z)=>zZ6(Z,"debug")==="1"})),J.use("/*",ZZ6({origin:(Z)=>{if(Z.includes("localhost")||Z.includes("127.0.0.1"))return Z;return Z},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]})),J.use("*",GZ6()),J.use("*",async(Z,$)=>{if(await $(),Z.res.status>=500){let H=await Z.res.clone().text();console.error(`[5xx Response] ${Z.req.method} ${Z.req.path} - ${Z.res.status}:`,H)}}),J.get(jT.HEALTH,(Z)=>{return Z.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),J.get(jT.METRICS,async(Z)=>{try{let $=await s60.collect(),K=Qc1.serialize($.resourceMetrics);return Z.text(K,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch($){return console.error("Failed to collect metrics:",$),Z.text("# Error collecting metrics",500)}}),J.route("/api/config",cF6),J.route("/api/auth/custom",U$6),J.all("/api/auth/*",async(Z)=>{return await e5.handler(Z.req.raw)}),J.route("/",yZ6),J.all("/oauth-proxy/:connectionId/*",async(Z)=>{let $=Z.req.param("connectionId"),K=Z.req.path.split("/").filter(Boolean),H=K[K.length-1],F=Z.get("meshContext");if(!F)F=await SK.create(Z.req.raw),Z.set("meshContext",F);let V=await F.storage.connections.findById($);if(!V?.connection_url)return Z.json({error:"Connection not found"},404);let q=await Kf(V.connection_url),z,D=new URL(V.connection_url);if(q.ok)z=(await q.json()).authorization_servers?.[0];if(!z)z=D.origin;let N=await UY0(z);if(!N.ok)return Z.json({error:"Failed to get auth server metadata"},502);let L=await N.json(),w;if(H==="authorize")w=L.authorization_endpoint;else if(H==="token")w=L.token_endpoint;else if(H==="register")w=L.registration_endpoint;if(!w)return Z.json({error:`Unknown OAuth endpoint: ${H}`},404);let C=new URL(w),T=new URL(Z.req.url);if(C.search=T.search,H==="authorize"){if(C.searchParams.has("resource"))C.searchParams.set("resource",V.connection_url);if(P16(V.connection_url))try{let h=await Xc1(F,V.organization_id),a=Yc1(h);for(let[f,S]of a)C.searchParams.set(f,S)}catch(h){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",h)}return Z.redirect(C.toString(),302)}let E={Accept:Z.req.header("Accept")||"application/json"},P=Z.req.header("Content-Type");if(P)E["Content-Type"]=P;let j=Z.req.header("Authorization");if(j)E.Authorization=j;let R;if(Z.req.method!=="GET"&&Z.req.method!=="HEAD")if(H==="token"&&P?.includes("application/x-www-form-urlencoded")){let h=await Z.req.formData();if(h.has("resource"))h.set("resource",V.connection_url);let a=new URLSearchParams;for(let[f,S]of h.entries())a.append(f,S.toString());R=a.toString()}else R=Z.req.raw.body??void 0;let k=await fetch(C.toString(),{method:Z.req.method,headers:E,body:R,duplex:"half",redirect:"manual"}),y=new Headers,b=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[h,a]of k.headers.entries())if(!b.includes(h.toLowerCase()))y.set(h,a);return new Response(k.body,{status:k.status,statusText:k.statusText,headers:y})}),J.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async(Z)=>{let K=await Jc1()(Z.req.raw),H=await K.json();return Response.json(H,K)});let G=async(Z)=>{let K=await Gc1()(Z.req.raw),H=await K.json();return Response.json(H,K)};J.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",G),SK.set(nZ6({db:Y.db,databaseType:Y.type,auth:e5,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:bM,meter:f_},eventBus:Q})),Promise.resolve(Q.start()).then(()=>{console.log("[EventBus] Worker started")}),J.use("*",async(Z,$)=>{if(rZ6(Z.req.path))return $();let K={measure:async(F,V)=>{IB(Z,F);try{return await V()}finally{lF(Z,F)}}},H=await SK.create(Z.req.raw,{timings:K});return Z.set("meshContext",H),$()}),J.get("/api/tools/management",(Z)=>{return Z.json({tools:al,grouped:aN()})}),J.use("/mcp/*",async(Z,$)=>{IB(Z,"mcp");try{return await $()}finally{lF(Z,"mcp")}});let W=async(Z,$)=>{let K=Z.var.meshContext;if(!K.auth.user?.id&&!K.auth.apiKey?.id){let H=new URL(Z.req.url);return Z.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${H.origin}${H.pathname}/.well-known/oauth-protected-resource"`}})}return await $()};return J.use("/mcp/:connectionId?",W),J.use("/mcp/gateway/:virtualMcpId?",W),J.use("/mcp/virtual-mcp/:virtualMcpId?",W),J.route("/mcp",S$6),J.route("/mcp",_$6),J.route("/mcp",lZ6),J.use("/api/:org/models/*",async(Z,$)=>{IB(Z,"llm_models");try{return await $()}finally{lF(Z,"llm_models")}}),J.route("/api",lF6),J.post("/org/:organizationId/events/:type",async(Z)=>{let $=Z.req.param("organizationId");return await Z.var.meshContext.eventBus.publish($,QK.SELF($),{data:await Z.req.json(),type:`public:${Z.req.param("type")}`,subject:Z.req.query("subject"),deliverAt:Z.req.query("deliverAt"),cron:Z.req.query("cron")}),Z.json({success:!0})}),J.route("/api",D$6),J.notFound((Z)=>{return Z.json({error:"Not Found",path:Z.req.path},404)}),J.onError((Z,$)=>{console.error("Server error :",Z);let K=Z instanceof Error?Z.message:"Unknown error";return $.json({error:"Internal Server Error",message:K},500)}),J}var aF6,yf=null,Qc1,Jc1=()=>Ga(e5),Gc1=()=>Ja(e5);var oF6=v(()=>{k7();WZ6();$Z6();VZ6();UZ6();EB();Vf();hM();DY0();F$6();fM();B$6();N$6();k$6();y$6();dF6();Ff();qf();nF6();JK();$a();rl();iF6();aF6=b1(o60(),1);Qc1=new aF6.PrometheusSerializer});import Wc1 from"v8";function sF6(X){let{port:Y,hostname:Q="0.0.0.0"}=X;return Bun.serve({port:Y,hostname:Q,fetch:async(J)=>{let G=new URL(J.url);if(G.pathname==="/health")return Response.json({status:"ok",uptime:process.uptime()});if(G.pathname==="/memory")return Response.json({...process.memoryUsage(),uptimeSeconds:process.uptime()});if(G.pathname==="/heap-snapshot"){let W=Date.now();try{let Z=Wc1.writeHeapSnapshot(),$=Bun.file(Z);return new Response($,{headers:{"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="heap-${W}.heapsnapshot"`}})}catch(Z){return Response.json({error:String(Z)},{status:500})}}if(G.pathname==="/gc"){if(typeof Bun.gc==="function")return Bun.gc(!0),Response.json({status:"gc triggered"});return Response.json({status:"gc not available"},{status:501})}return Response.json({error:"Not found"},{status:404})}})}var tF6=()=>{};var qc1={};var XV6,eF6,Zc1,uB="\x1B[0m",$c1="\x1B[1m",YV6="\x1B[2m",Kc1="\x1B[32m",QV6="\x1B[36m",JV6="\x1B[4m",Hc1,Fc1,Vc1;var GV6=v(()=>{fM();OW6();oF6();DY0();tF6();XV6=parseInt(process.env.PORT||"3000",10),eF6=parseInt(process.env.DEBUG_PORT||"9090",10),Zc1=process.env.ENABLE_DEBUG_SERVER==="true",Hc1=`http://localhost:${XV6}`,Fc1=NW6({clientDir:DW6(import.meta.url,"../client"),isServerPath:aZ6}),Vc1=rF6();console.log("");console.log(`${Kc1}\u2713${uB} ${$c1}Ready${uB}`);console.log("");console.log(` ${YV6}Open in browser:${uB} ${QV6}${JV6}${Hc1}${uB}`);console.log("");Bun.serve({idleTimeout:0,port:XV6,hostname:"0.0.0.0",fetch:async(X)=>{return await Fc1(X)??Vc1.fetch(X)},development:!1});if(Zc1)sF6({port:eF6}),console.log(` ${YV6}Debug server:${uB} ${QV6}${JV6}http://localhost:${eF6}${uB}`),console.log("")});import{parseArgs as zc1}from"util";var{values:bf}=zc1({args:process.argv.slice(2),options:{port:{type:"string",short:"p",default:process.env.PORT||"3000"},help:{type:"boolean",short:"h",default:!1},version:{type:"boolean",short:"v",default:!1},"skip-migrations":{type:"boolean",default:!1}},allowPositionals:!0});if(bf.help)console.log(`
1138
+ - When users mention "agents", they are typically referring to gateways`},rp1=U.object({messages:U.any(),model:U.object({id:U.string(),connectionId:U.string(),provider:U.enum(["openai","anthropic","google","xai","deepseek","openrouter","openai-compatible"]).optional().nullable(),limits:U.object({contextWindow:U.number().optional(),maxOutputTokens:U.number().optional()}).optional()}).loose(),gateway:U.object({id:U.string().nullable()}).loose(),stream:U.boolean().optional(),temperature:U.number().optional(),maxWindowSize:U.number().optional(),thread_id:U.string().optional()}),mF6=new C9;mF6.post("/:org/models/stream",async(X)=>{let Y=X.get("meshContext"),Q=X.req.param("org"),J=null;try{let G=op1(Y,Q),W=await X.req.json(),Z=rp1.safeParse(W);if(!Z.success)return X.json({error:"Invalid request body",details:Z.error.issues},400);let $=Z.data,{model:K,gateway:H,messages:F,temperature:V,maxWindowSize:q=ip1,thread_id:z}=$,D=K.limits?.maxOutputTokens??np1,N=ep1(X.req.raw,G.id,H.id),L=new OQ({name:"mcp-mesh-proxy",version:"1.0.0"});J=L;let[w,C]=await Promise.all([bF6(F,{ignoreIncompleteToolCalls:!0}),sp1(Y,G.id,K.connectionId),L.connect(N)]);if(!C)return await L.close().catch(console.error),X.json({error:`Model connection not found: ${K.connectionId}`},404);let T=[ap1,...w.filter((a)=>a.role==="system")],E=w.filter((a)=>a.role!=="system"),P=fF6({messages:E,reasoning:"before-last-message",emptyMessages:"remove",toolCalls:"none"}).slice(-q),j=z?{thread_id:z}:void 0,[R,k]=await Promise.all([Y.createMCPProxy(C),tp1(L,j)]),y=cG6.forClient(R),b=gF6(y).languageModel(K.id);return yF6({model:b,system:T,messages:P,tools:k,temperature:V,maxOutputTokens:D,abortSignal:X.req.raw.signal,stopWhen:KQ0(30),onError:async(a)=>{console.error("[models:stream] Error",a),await L.close().catch(console.error)},onFinish:async()=>{await L.close().catch(console.error)}}).toUIMessageStreamResponse({messageMetadata:({part:a})=>{if(a.type==="start")return{gateway:H,model:K,created_at:new Date,thread_id:z};if(a.type==="reasoning-start")return{reasoning_start_at:new Date};if(a.type==="reasoning-end")return{reasoning_end_at:new Date};if(a.type==="finish-step")return{usage:{...a.usage,providerMetadata:a.providerMetadata}};return{}}})}catch(G){let W=G;if(await J?.close().catch(console.error),W.name==="AbortError")return console.warn("[models:stream] Aborted",JSON.stringify({org:Q})),X.json({error:"Request aborted"},400);return console.error("[models:stream] Failed",JSON.stringify({org:Q,error:W.message,stack:W.stack})),X.json({error:W.message},500)}});lF6=mF6});var pF6,cF6;var nF6=v(()=>{k7();zS();pF6=new C9;pF6.get("/",(X)=>{let Y={theme:jN0()};return X.json({success:!0,config:Y})});cF6=pF6});var iF6=()=>{};async function Xc1(X,Y){let J=(await X.storage.connections.list(Y)).find((G)=>G.connection_url?.startsWith(M16));if(!J?.configuration_state)return null;return J.configuration_state.project_locator}function Yc1(X){let Y=new URLSearchParams;if(X){let[Q,J]=X.split("/");if(Q)Y.set("workspace_hint",Q);if(J)Y.set("project_hint",J)}else Y.set("auto_personal","true");return Y}function rF6(X={}){let Y=X.database??FF();if(yf&&yf.isRunning())console.log("[EventBus] Stopping previous worker (HMR cleanup)"),Promise.resolve(yf.stop()).catch((Z)=>{console.error("[EventBus] Error stopping previous worker:",Z)});let Q;if(X.eventBus)Q=X.eventBus;else Q=H$6(Y);yf=Q;let J=new C9;J.use("*",JY0({enabled:(Z)=>zZ6(Z,"debug")==="1"})),J.use("/*",ZZ6({origin:(Z)=>{if(Z.includes("localhost")||Z.includes("127.0.0.1"))return Z;return Z},credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"]})),J.use("*",GZ6()),J.use("*",async(Z,$)=>{if(await $(),Z.res.status>=500){let H=await Z.res.clone().text();console.error(`[5xx Response] ${Z.req.method} ${Z.req.path} - ${Z.res.status}:`,H)}}),J.get(jT.HEALTH,(Z)=>{return Z.json({status:"ok",timestamp:new Date().toISOString(),version:"1.0.0"})}),J.get(jT.METRICS,async(Z)=>{try{let $=await s60.collect(),K=Qc1.serialize($.resourceMetrics);return Z.text(K,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch($){return console.error("Failed to collect metrics:",$),Z.text("# Error collecting metrics",500)}}),J.route("/api/config",cF6),J.route("/api/auth/custom",U$6),J.all("/api/auth/*",async(Z)=>{return await e5.handler(Z.req.raw)}),J.route("/",yZ6),J.all("/oauth-proxy/:connectionId/*",async(Z)=>{let $=Z.req.param("connectionId"),K=Z.req.path.split("/").filter(Boolean),H=K[K.length-1],F=Z.get("meshContext");if(!F)F=await SK.create(Z.req.raw),Z.set("meshContext",F);let V=await F.storage.connections.findById($);if(!V?.connection_url)return Z.json({error:"Connection not found"},404);let q=await Kf(V.connection_url),z,D=new URL(V.connection_url);if(q.ok)z=(await q.json()).authorization_servers?.[0];if(!z)z=D.origin;let N=await UY0(z);if(!N.ok)return Z.json({error:"Failed to get auth server metadata"},502);let L=await N.json(),w;if(H==="authorize")w=L.authorization_endpoint;else if(H==="token")w=L.token_endpoint;else if(H==="register")w=L.registration_endpoint;if(!w)return Z.json({error:`Unknown OAuth endpoint: ${H}`},404);let C=new URL(w),T=new URL(Z.req.url);if(C.search=T.search,H==="authorize"){if(C.searchParams.has("resource"))C.searchParams.set("resource",V.connection_url);if(P16(V.connection_url))try{let h=await Xc1(F,V.organization_id),a=Yc1(h);for(let[f,S]of a)C.searchParams.set(f,S)}catch(h){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",h)}return Z.redirect(C.toString(),302)}let E={Accept:Z.req.header("Accept")||"application/json"},P=Z.req.header("Content-Type");if(P)E["Content-Type"]=P;let j=Z.req.header("Authorization");if(j)E.Authorization=j;let R;if(Z.req.method!=="GET"&&Z.req.method!=="HEAD")if(H==="token"&&P?.includes("application/x-www-form-urlencoded")){let h=await Z.req.formData();if(h.has("resource"))h.set("resource",V.connection_url);let a=new URLSearchParams;for(let[f,S]of h.entries())a.append(f,S.toString());R=a.toString()}else R=Z.req.raw.body??void 0;let k=await fetch(C.toString(),{method:Z.req.method,headers:E,body:R,duplex:"half",redirect:"manual"}),y=new Headers,b=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[h,a]of k.headers.entries())if(!b.includes(h.toLowerCase()))y.set(h,a);return new Response(k.body,{status:k.status,statusText:k.statusText,headers:y})}),J.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",async(Z)=>{let K=await Jc1()(Z.req.raw),H=await K.json();return Response.json(H,K)});let G=async(Z)=>{let K=await Gc1()(Z.req.raw),H=await K.json();return Response.json(H,K)};J.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",G),SK.set(nZ6({db:Y.db,databaseType:Y.type,auth:e5,encryption:{key:process.env.ENCRYPTION_KEY||""},observability:{tracer:bM,meter:f_},eventBus:Q})),Promise.resolve(Q.start()).then(()=>{console.log("[EventBus] Worker started")}),J.use("*",async(Z,$)=>{if(rZ6(Z.req.path))return $();let K={measure:async(F,V)=>{IB(Z,F);try{return await V()}finally{lF(Z,F)}}},H=await SK.create(Z.req.raw,{timings:K});return Z.set("meshContext",H),$()}),J.get("/api/tools/management",(Z)=>{return Z.json({tools:al,grouped:aN()})}),J.use("/mcp/*",async(Z,$)=>{IB(Z,"mcp");try{return await $()}finally{lF(Z,"mcp")}});let W=async(Z,$)=>{let K=Z.var.meshContext;if(!K.auth.user?.id&&!K.auth.apiKey?.id){let H=new URL(Z.req.url);return Z.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${H.origin}${H.pathname}/.well-known/oauth-protected-resource"`}})}return await $()};return J.use("/mcp/:connectionId?",W),J.use("/mcp/gateway/:virtualMcpId?",W),J.use("/mcp/virtual-mcp/:virtualMcpId?",W),J.route("/mcp",S$6),J.route("/mcp",_$6),J.route("/mcp",lZ6),J.use("/api/:org/models/*",async(Z,$)=>{IB(Z,"llm_models");try{return await $()}finally{lF(Z,"llm_models")}}),J.route("/api",lF6),J.post("/org/:organizationId/events/:type",async(Z)=>{let $=Z.req.param("organizationId");return await Z.var.meshContext.eventBus.publish($,QK.SELF($),{data:await Z.req.json(),type:`public:${Z.req.param("type")}`,subject:Z.req.query("subject"),deliverAt:Z.req.query("deliverAt"),cron:Z.req.query("cron")}),Z.json({success:!0})}),J.route("/api",D$6),J.notFound((Z)=>{return Z.json({error:"Not Found",path:Z.req.path},404)}),J.onError((Z,$)=>{console.error("Server error :",Z);let K=Z instanceof Error?Z.message:"Unknown error";return $.json({error:"Internal Server Error",message:K},500)}),J}var aF6,yf=null,Qc1,Jc1=()=>Ga(e5),Gc1=()=>Ja(e5);var oF6=v(()=>{k7();WZ6();$Z6();VZ6();UZ6();EB();Vf();hM();DY0();F$6();fM();B$6();N$6();k$6();y$6();dF6();Ff();qf();nF6();JK();$a();rl();iF6();aF6=b1(o60(),1);Qc1=new aF6.PrometheusSerializer});import Wc1 from"v8";function sF6(X){let{port:Y,hostname:Q="0.0.0.0"}=X;return Bun.serve({port:Y,hostname:Q,fetch:async(J)=>{let G=new URL(J.url);if(G.pathname==="/health")return Response.json({status:"ok",uptime:process.uptime()});if(G.pathname==="/memory")return Response.json({...process.memoryUsage(),uptimeSeconds:process.uptime()});if(G.pathname==="/heap-snapshot"){let W=Date.now();try{let Z=Wc1.writeHeapSnapshot(),$=Bun.file(Z);return new Response($,{headers:{"Content-Type":"application/octet-stream","Content-Disposition":`attachment; filename="heap-${W}.heapsnapshot"`}})}catch(Z){return Response.json({error:String(Z)},{status:500})}}if(G.pathname==="/gc"){if(typeof Bun.gc==="function")return Bun.gc(!0),Response.json({status:"gc triggered"});return Response.json({status:"gc not available"},{status:501})}return Response.json({error:"Not found"},{status:404})}})}var tF6=()=>{};var qc1={};var XV6,eF6,Zc1,uB="\x1B[0m",$c1="\x1B[1m",YV6="\x1B[2m",Kc1="\x1B[32m",QV6="\x1B[36m",JV6="\x1B[4m",Hc1,Fc1,Vc1;var GV6=v(()=>{fM();OW6();oF6();DY0();tF6();XV6=parseInt(process.env.PORT||"3000",10),eF6=parseInt(process.env.DEBUG_PORT||"9090",10),Zc1=process.env.ENABLE_DEBUG_SERVER==="true",Hc1=`http://localhost:${XV6}`,Fc1=NW6({clientDir:DW6(import.meta.url,"../client"),isServerPath:aZ6}),Vc1=rF6();console.log("");console.log(`${Kc1}\u2713${uB} ${$c1}Ready${uB}`);console.log("");console.log(` ${YV6}Open in browser:${uB} ${QV6}${JV6}${Hc1}${uB}`);console.log("");Bun.serve({idleTimeout:0,port:XV6,hostname:"0.0.0.0",fetch:async(X)=>{return await Fc1(X)??Vc1.fetch(X)},development:!1});if(Zc1)sF6({port:eF6}),console.log(` ${YV6}Debug server:${uB} ${QV6}${JV6}http://localhost:${eF6}${uB}`),console.log("")});import{parseArgs as zc1}from"util";var{values:bf}=zc1({args:process.argv.slice(2),options:{port:{type:"string",short:"p",default:process.env.PORT||"3000"},help:{type:"boolean",short:"h",default:!1},version:{type:"boolean",short:"v",default:!1},"skip-migrations":{type:"boolean",default:!1}},allowPositionals:!0});if(bf.help)console.log(`
1139
1139
  MCP Mesh - Self-hostable MCP Gateway
1140
1140
 
1141
1141
  Usage: