@decocms/mesh 2.38.4 → 2.38.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/cli.js +1 -1
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
package/dist/server/server.js
CHANGED
|
@@ -1048,7 +1048,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
|
|
|
1048
1048
|
<h2>You've been invited!</h2>
|
|
1049
1049
|
<p>${J} has invited you to join <strong>${Q.organization.name}</strong>.</p>
|
|
1050
1050
|
<p><a href="${G}">Click here to accept the invitation</a></p>
|
|
1051
|
-
`})}}}var pf6=[f60({organizationCreation:{afterCreate:async(X)=>{await zG1(X.organization.id,X.member.userId)}},ac:Eb,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:BG1,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:mf6,admin:lf6,owner:df6},sendInvitationEmail:wG1}),s60({loginPage:"/login",oidcConfig:{scopes:LG1,metadata:{scopes_supported:LG1},loginPage:"/login"}}),o60({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}}),g60({defaultRole:"user",adminRoles:["admin","owner"]}),Y40(),l60({jwt:{expirationTime:"5m"}}),x61(e8.ssoConfig?DG1(e8.ssoConfig):void 0),...e8.magicLinkConfig&&e8.emailProviders&&e8.emailProviders.length>0?[X40($91(e8.magicLinkConfig,e8.emailProviders))]:[]],cf6=u40(),nf6=Z91(cf6),oW=i10({baseURL:process.env.BASE_URL||"http://localhost:3000",database:nf6,emailAndPassword:{enabled:!0},...e8,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:pf6,databaseHooks:{user:{create:{after:async(X)=>{if(JP.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} ${xf6()}`,W=hf6(G);try{await oW.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}}}}}}}});vQ();import{randomBytes as if6}from"crypto";var iP=null;function MG1(){if(iP)return iP;let X=process.env.MESH_JWT_SECRET??e8.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(X)iP=new TextEncoder().encode(X);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),iP=new Uint8Array(if6(32));return iP}async function PG1(X,Y="5m"){let Q=MG1();return await new YQ(X).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Y).sign(Q)}async function AG1(X){try{let Y=MG1(),{payload:Q}=await K8(X,Y);return Q}catch{return}}pW();class mX0{db;constructor(X){this.db=X}async create(X,Y,Q){let J=t8("vir"),G=new Date().toISOString();if(await this.db.insertInto("connections").values({id:J,organization_id:X,created_by:Y,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${J}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,tools:null,bindings:null,status:Q.status??"active",created_at:G,updated_at:G}).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:J,child_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("connections").selectAll().where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let J=await X.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Y).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(X){let Y=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute(),Q=Y.map((W)=>W.id);if(Q.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).execute(),G=new Map;for(let W of J){let Z=G.get(W.parent_connection_id)??[];Z.push(W),G.set(W.parent_connection_id,Z)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,G.get(W.id)??[]))}async listByConnectionId(X,Y){let J=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Y).execute()).map((K)=>K.parent_connection_id);if(J.length===0)return[];let G=await this.db.selectFrom("connections").selectAll().where("id","in",J).where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.parent_connection_id)??[];H.push(K),$.set(K.parent_connection_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};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(Q.metadata!==void 0)G.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(await this.db.updateTable("connections").set(G).where("id","=",X).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",X).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:X,child_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("connection_aggregations").where("parent_connection_id","=",X).execute(),await this.db.deleteFrom("connections").where("id","=",X).where("connection_type","=","VIRTUAL").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,G=X.status==="active"?"active":"inactive";return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,tool_selection_mode:"inclusion",icon:X.icon,status:G,created_at:Q,updated_at:J,created_by:X.created_by,updated_by:void 0,metadata:this.parseJson(X.metadata),connections:Y.map((W)=>({connection_id:W.child_connection_id,selected_tools:this.parseJson(W.selected_tools),selected_resources:this.parseJson(W.selected_resources),selected_prompts:this.parseJson(W.selected_prompts)}))}}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}import{sql as jb}from"kysely";class lX0{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 HN.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 HN.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()}})}}pW();class dX0{db;redactor;databaseType;constructor(X,Y="sqlite"){this.db=X;this.redactor=new lX0,this.databaseType=Y}jsonExtract(X,Y){if(this.databaseType==="postgres")return jb`(${jb.ref(X)}::jsonb)->>${Y}`;let Q=`$.${Y}`;return jb`json_extract(${jb.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||t8("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}}}class pX0{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 cX0{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 TG1="mcp.mesh";class EG1 extends Error{constructor(X){super(X);this.name="UnauthorizedError"}}class nX0 extends Error{constructor(X){super(X);this.name="ForbiddenError"}}class qK{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(X,Y,Q,J,G,W="self",Z){this.userId=Y;this.toolName=Q;this.boundAuth=J;this.role=G;this.connectionId=W;this.getToolMeta=Z}[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){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new EG1("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 nX0("No resources specified for access check");for(let Q of Y)if(await this.checkResource(Q)){this.grant();return}throw new nX0(`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)}async isToolPublic(){if(!this.getToolMeta)return!1;try{let X=await this.getToolMeta();if(!X)return!1;let Q=X[TG1]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}q7();function jG1(X){let Y=null;return()=>{if(Y)return Y;return Y=X().catch((Q)=>{throw Y=null,Q}),Y}}class CG1{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 B7(X){return new CG1(X)}class iX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>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)}}qX();function af6(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 IG1(X,Y){return Y.some((Q)=>af6(X,Q))}class aX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>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)=>!IG1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>IG1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){if(!(Z instanceof Q1)||Z.code!==$1.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)}}qX();class rX0{proxies;cache;constructor(X){this.proxies=X;this.cache=B7(()=>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 Q1)||G.code!==$1.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}}}qX();a0();jP();var SG1=U.object({query:U.string().min(1).describe("Search query to find tools by name or description"),limit:U.number().default(10).describe("Maximum number of results to return")}),rf6=U.toJSONSchema(SG1),kG1=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),of6=U.toJSONSchema(kG1),vG1=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).")}),sf6=U.toJSONSchema(vG1),RG1=new Map;function tf6(X){let Y=X.slice().sort().join(","),Q=RG1.get(Y);if(!Q){let J=U.object({name:(X.length>0?U.enum(X):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")});Q={schema:J,jsonSchema:U.toJSONSchema(J)},RG1.set(Y,Q)}return Q}function _G1(X){let Y=EP(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: ${Y.length}.`,inputSchema:rf6},handler:async(J)=>{let G=SG1.safeParse(J);if(!G.success)return QB({error:G.error.flatten()});let W=Fb(G.data.query,Y,G.data.limit);return Ub({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Y.length})}}}function yG1(X){let Y=EP(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:of6},handler:async(Q)=>{let J=kG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G=Vb(J.data.tools,Y);return Ub({tools:G.tools,notFound:G.notFound})}}}function ef6(X){let Y=EP(X.tools),Q=Y.map((Z)=>Z.name),J=new Map(Y.map((Z)=>[Z.name,Z])),{schema:G,jsonSchema:W}=tf6(Q);return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:W},handler:async(Z)=>{let $=G.safeParse(Z);if(!$.success)return QB({error:$.error.flatten()});let{name:K,arguments:H}=$.data;if(!J.has(K))return{content:[{type:"text",text:`Tool not found: ${K}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return X.callTool(K,H)}}}function Xh6(X){let Y=EP(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:sf6},handler:async(Q)=>{let J=vG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G={...X,tools:Y},W=await qb(J.data.code,G,J.data.timeoutMs);if(W.error)return QB(W);return Ub(W)}}}function bG1(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)}}}var Yh6=(X)=>({tools:X.tools,callTool:(Y,Q)=>X.callTool(Y,Q)}),Qh6=(X)=>bG1([_G1(X),yG1(X),Xh6(X)]),Jh6=(X)=>bG1([_G1(X),yG1(X),ef6(X)]);function fG1(X){switch(X){case"smart_tool_selection":return Jh6;case"code_execution":return Qh6;case"passthrough":default:return Yh6}}function hG1(X){switch(X){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}class oX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>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 Q1)||F.code!==$1.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})},$=fG1(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"}})}}function xG1(X,Y){if(X.connection_type!=="VIRTUAL")return!1;return ZK(X.connection_url)===Y}async function Gh6(X,Y){let Q=await sz.create(X.connections,Y),J=new oX0(Q,{selectionMode:X.toolSelectionMode,strategy:X.toolSelectionStrategy}),G=new aX0(Q,{selectionMode:X.toolSelectionMode}),W=new rX0(Q),Z=new iX0(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 aP(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"&&!xG1(K,X.id)),$=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"&&!xG1(K,X.id))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 Gh6(G,Y)}e80();async function gG1(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"}}}tH();H80();function Wh6(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)}})}var uG1="__mesh_stable_stdio_pool__",MF=globalThis[uG1]??(globalThis[uG1]=new Map);async function lG1(X,Y){let Q=MF.get(X.id);if(Q?.status==="connected"&&Q.stableClient)return Q.stableClient;if(Q?.connectPromise&&(Q.status==="connecting"||Q.status==="reconnecting"))return Q.connectPromise;let J=Q?.status==="failed",G=Q??{transport:null,client:null,stableClient:null,config:X,status:"connecting",connectPromise:null};if(!Q)MF.set(X.id,G);return G.status=J?"reconnecting":"connecting",G.connectPromise=(async()=>{try{console.log(`[StableStdio] ${J?"Respawning":"Spawning"}: ${X.id} (${X.command} ${X.args?.join(" ")??""})`);let W=new wP({command:X.command,args:X.args,env:X.env,cwd:X.cwd,stderr:"pipe"});G.transport=W;let Z=Y??new l9({name:`mesh-stdio-${X.id}`,version:"1.0.0"});G.client=Z,G.stableClient=Wh6(Z),Z.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${X.id}`),G.status="failed",G.connectPromise=null};let $=X.name||X.id,K="\x1B[2m",H="\x1B[0m";W.stderr?.on("data",(q)=>{let z=q.toString().trimEnd();if(z)console.error(`${z} ${K}[${$}]${H}`)});let F=new AbortController,V=setTimeout(()=>F.abort(),30000);try{await Promise.race([Z.connect(W),new Promise((q,z)=>{F.signal.addEventListener("abort",()=>{z(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(V)}return G.status="connected",console.log(`[StableStdio] Connected: ${X.id}`),G.stableClient}catch(W){console.error(`[StableStdio] Failed to connect ${X.id}:`,W),G.status="failed",G.connectPromise=null;try{await G.transport?.close()}catch{}throw W}})(),G.connectPromise}async function Zh6(X){let Y=MF.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{}MF.delete(X)}async function $h6(){console.log(`[StableStdio] Closing all connections (${MF.size})`);let X=Array.from(MF.keys()).map((Y)=>Zh6(Y));await Promise.allSettled(X),MF.clear()}var mG1="__mesh_stable_stdio_shutdown_registered__";if(!globalThis[mG1]){globalThis[mG1]=!0;let X=async(Y)=>{await $h6(),process.exit(Y==="SIGINT"?130:143)};process.on("SIGINT",()=>X("SIGINT")),process.on("SIGTERM",()=>X("SIGTERM"))}Ab();q7();tH();Xb();oq();Gb();Wb();qX();Gb();Wb();qX();gL();var sX0=new p8;async function Cb(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?Eo(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(Z.status!=="active")return X.json({error:`Agent is inactive: ${Z.id}`},503);Q.connectionId=Z.id;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=hG1(K),F=await aP(Z,Q,H),V=new qF({name:`mcp-virtual-mcp-${Z.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:Z.metadata?.instructions??void 0}),q=new UF({enableJsonResponse:X.req.header("Accept")?.includes("application/json")??!1});await V.connect(q),V.server.setRequestHandler(tZ,async(z)=>{return F.client.listTools()}),V.server.setRequestHandler(TG,async(z)=>{return await F.client.callTool(z.params)}),V.server.setRequestHandler(iZ,async()=>{return F.client.listResources()}),V.server.setRequestHandler(rZ,async(z)=>{return F.client.readResource(z.params)}),V.server.setRequestHandler(aZ,async()=>{return F.client.listResourceTemplates()}),V.server.setRequestHandler(oZ,async()=>{return F.client.listPrompts()}),V.server.setRequestHandler(sZ,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)}}sX0.all("/gateway/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});sX0.all("/virtual-mcp/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});var dG1=sX0;var Ib=new p8,tX0=[404,401,406];async function pG1(X,Y){return(await Y.storage.connections.findById(X))?.connection_url??null}function Kh6(X){let Y=X.toLowerCase();return Y.includes("resource_metadata=")||Y.includes("invalid_token")||Y.includes("oauth")}async function cG1(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(Kh6(J))return J}}return null}catch{return null}}async function Rb(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(!tX0.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"}}),!tX0.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 Hh6(X,Y){let Q=await pG1(X,Y);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Rb(Q);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function nG1(X){let Y=X.get("meshContext");if(!Y)Y=await UK.create(X.req.raw),X.set("meshContext",Y);return Y}async function iG1({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 cG1(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"}})}var Sb=(X)=>{if(!(X.hostname==="localhost"||X.hostname==="127.0.0.1"))X.protocol="https:";return X},aG1=async(X)=>{let Y=X.req.param("connectionId"),Q=await nG1(X),J=await pG1(Y,Q);if(!J)return X.json({error:"Connection not found"},404);let G=Sb(new URL(X.req.url)),W=`${G.origin}/mcp/${Y}`,Z=`${G.origin}/oauth-proxy/${Y}`;try{let $=await Rb(J);if(!$.ok&&tX0.includes($.status)){if(await cG1(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)}};Ib.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(X)=>aG1(X));Ib.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(X)=>aG1(X));async function eX0(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}Ib.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=await nG1(X),J=await Hh6(Y,Q);if(!J)return X.json({error:"Connection not found or no auth server"},404);try{let G=await eX0(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(),$=`${Sb(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)}});var rG1=Ib;function Fh6(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 Vh6(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 qh6(X,Y){if(!X&&!Y)return;if(!X)return Y;if(!Y)return X;return{...Y,...X}}function oG1(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 Uh6(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 rP(X){let{ctx:Y,enabled:Q}=X,J=X.organizationId??Y.organization?.id;if(!Q||!J)return;let G=Vh6(X.request.params.arguments),W=qh6(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:X.virtualMcpId,properties:W})}function sG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Date.now()-K;return await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:oG1(H),isError:Boolean(H.isError),errorMessage:Fh6(H),durationMs:F}),H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}function tG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Y.organization?.id;if(Q&&F){let V=H.clone();(async()=>{try{let{text:q,truncated:z}=await Uh6(V,262144),D=Date.now()-K,N=V.headers.get("content-type")??"",L=q;if(N.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=H.status>=400,C=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof C==="string"&&C?C:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${H.status} ${H.statusText}`.trim():z?"Response body truncated to 262144 bytes":void 0;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:oG1(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let z=Date.now()-K;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:z})}})()}return H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}var kb=new p8,XY0=300000;function zh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new qK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return{content:[{type:"text",text:`Authorization failed: ${W.message}`}],isError:!0}}}}function Bh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new qK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return new Response(JSON.stringify({error:`Authorization failed: ${W.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function eG1(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,$=jG1(async()=>{let S=t80(J.configuration_state,J.configuration_scopes),f=Y.auth.user?.id??Y.auth.apiKey?.userId;if(!f){console.error("User ID required to issue configuration token");return}try{W=await PG1({sub:f,user:{id:f},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??Y.baseUrl,connectionId:G,organizationId:Y.organization?.id},permissions:S})}catch(t){console.error("Failed to issue configuration token:",t)}}),K=async()=>{await $();let S={...Z?{"x-caller-id":Z}:{},...Y.metadata.wellKnownForwardableHeaders??{},"x-request-id":Y.metadata.requestId},f=null,t=new aW(Y.db,Y.vault),m=await t.get(G);if(m){let J0=!!m.refreshToken&&!!m.tokenEndpoint;if(t.isExpired(m,J0?300000:0))if(J0){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let Y0=await gG1(m);if(Y0.success&&Y0.accessToken)await t.upsert({connectionId:G,accessToken:Y0.accessToken,refreshToken:Y0.refreshToken??m.refreshToken,scope:Y0.scope??m.scope,expiresAt:Y0.expiresIn?new Date(Date.now()+Y0.expiresIn*1000):null,clientId:m.clientId,clientSecret:m.clientSecret,tokenEndpoint:m.tokenEndpoint}),f=Y0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await t.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${Y0.error}`)}else await t.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else f=m.accessToken}if(!f&&J.connection_token)f=J.connection_token;if(f)S.Authorization=`Bearer ${f}`;if(W)S["x-mesh-token"]=W;return S},H=J.connection_type==="STDIO",F=KF(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{let S=new l9({name:"mcp-mesh-proxy",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});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 lG1({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd},S)}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new IG(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new VF(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"VIRTUAL":{let f=ZK(J.connection_url);if(!f)throw Error("VIRTUAL connection missing virtual MCP ID in connection_url");let t=await Y.storage.virtualMcps.findById(f);if(!t)throw Error(`Virtual MCP not found: ${f}`);let m=await aP(t,Y,"passthrough");return{callTool:(J0)=>m.client.callTool(J0),listTools:()=>m.client.listTools(),listResources:()=>m.client.listResources(),readResource:(J0)=>m.client.readResource(J0),listResourceTemplates:()=>m.client.listResourceTemplates(),listPrompts:()=>m.client.listPrompts(),getPrompt:(J0)=>m.client.getPrompt(J0),close:async()=>{},getServerCapabilities:()=>({tools:{},resources:{},prompts:{}}),getInstructions:()=>t.metadata?.instructions??void 0}}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema,outputSchema:f.outputSchema,annotations:f.annotations,_meta:f._meta}))};let S;try{return S=await q(),await S.listTools()}finally{S?.close().catch(console.error)}},D=Q?async(S,f)=>await f():zh6(Y,G,z),N=Q?async(S,f)=>await f():Bh6(Y,G,z),L=Y.connectionId&&Y.connectionId!==G?Y.connectionId:void 0,w={enabled:T81().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:L,ctx:Y},C=sG1(w),T=tG1(w),A=PP(C,D),P=PP(T,N),j=async(S)=>{return A(S,async()=>{let f=await q(),t=Date.now(),m={...S.params};if(m.arguments&&"_meta"in m.arguments){let{_meta:J0,...V0}=m.arguments;m.arguments=V0}return await Y.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":S.params.name,"request.id":Y.metadata.requestId}},async(J0)=>{try{let V0=await f.callTool(m,void 0,{timeout:XY0}),Y0=Date.now()-t;return Y.meter.createHistogram("connection.proxy.duration").record(Y0,{"connection.id":G,"tool.name":S.params.name,status:"success"}),Y.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":S.params.name,status:"success"}),J0.end(),V0}catch(V0){let Y0=V0,U0=Date.now()-t;throw Y.meter.createHistogram("connection.proxy.duration").record(U0,{"connection.id":G,"tool.name":S.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":S.params.name,error:Y0.message}),J0.recordException(Y0),J0.end(),V0}finally{f.close().catch(console.error)}})})};return{fetch:async(S)=>{let f=new URL(S.url),t;try{t=await q()}catch(P0){let v0=J.connection_url?await iG1({error:P0,reqUrl:f,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(v0)return v0;throw P0}let m=t.getServerCapabilities(),J0=t.getInstructions(),V0=m??{tools:{},resources:{},prompts:{}},Y0=new qF({name:"mcp-mesh",version:"1.0.0"},{capabilities:V0,instructions:J0}),U0=new UF({enableJsonResponse:S.headers.get("Accept")?.includes("application/json")??!1});if(await Y0.connect(U0),Y0.server.setRequestHandler(tZ,()=>t.listTools()),Y0.server.setRequestHandler(TG,j),V0.resources)Y0.server.setRequestHandler(iZ,()=>t.listResources()),Y0.server.setRequestHandler(rZ,(P0)=>t.readResource(P0.params)),Y0.server.setRequestHandler(aZ,()=>t.listResourceTemplates());if(V0.prompts)Y0.server.setRequestHandler(oZ,()=>t.listPrompts()),Y0.server.setRequestHandler(sZ,(P0)=>t.getPrompt(P0.params));try{return await U0.handleRequest(S)}finally{try{await t.close()}catch{}try{await U0.close?.()}catch{}}},client:{callTool:(S)=>{return j({method:"tools/call",params:S})},listTools:z,listResources:async()=>{let S;try{return S=await q(),await S.listResources()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resources:[]};throw f}finally{S?.close().catch(console.error)}},readResource:async(S)=>{let f;try{return f=await q(),await f.readResource(S)}finally{f?.close().catch(console.error)}},listResourceTemplates:async()=>{let S;try{return S=await q(),await S.listResourceTemplates()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resourceTemplates:[]};throw f}finally{S?.close().catch(console.error)}},listPrompts:async()=>{let S;try{return S=await q(),await S.listPrompts()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{prompts:[]};throw f}finally{S?.close().catch(console.error)}},getPrompt:async(S)=>{let f;try{return f=await q(),await f.getPrompt(S)}finally{f?.close().catch(console.error)}}},callStreamableTool:async(S,f)=>{if(J.connection_type==="VIRTUAL"){let J0=await j({method:"tools/call",params:{name:S,arguments:f}});return new Response(JSON.stringify(J0),{headers:{"Content-Type":"application/json"}})}if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let t=J.connection_url,m={method:"tools/call",params:{name:S,arguments:f}};return P(m,async()=>{let J0=await K();if(V?.headers)Object.assign(J0,V.headers);let V0=new URL(t);return V0.pathname=V0.pathname.replace(/\/$/,"")+`/call-tool/${m.params.name}`,await Y.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":m.params.name,"request.id":Y.metadata.requestId}},async(Y0)=>{let U0=Date.now();try{let P0=await fetch(V0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(m.params.arguments),headers:{...J0,"Content-Type":"application/json"}}),v0=Date.now()-U0;return Y.meter.createHistogram("connection.proxy.streamable.duration").record(v0,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y0.end(),P0}catch(P0){let v0=P0,G1=Date.now()-U0;throw Y.meter.createHistogram("connection.proxy.streamable.duration").record(G1,{"connection.id":G,"tool.name":m.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":m.params.name,error:v0.message}),Y0.recordException(v0),Y0.end(),P0}})})}}}async function X71(X,Y){return eG1(X,Y,{superUser:!1})}async function Y71(X,Y){return eG1(X,Y,{superUser:!0})}kb.all("/",async(X)=>{return Cb(X,void 0)});kb.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){return Q71(J,X)}});var Q71=(X,Y)=>{if(X.message.includes("not found"))return Y.json({error:X.message},404);if(X.message.includes("does not belong to the active organization"))return Y.json({error:"Connection not found"},404);if(X.message.includes("inactive"))return Y.json({error:X.message},503);return Y.json({error:"Internal server error",message:X.message},500)};kb.all("/:connectionId/call-tool/:toolName",async(X)=>{let Y=X.req.param("connectionId"),Q=X.req.param("toolName"),J=X.get("meshContext");try{let W=await(await J.createMCPProxy(Y)).client.callTool({name:Q,arguments:await X.req.json()});if(W instanceof Response)return W;if(W.isError)return new Response(JSON.stringify(W.content),{headers:{"Content-Type":"application/json"},status:500});return new Response(JSON.stringify(W.structuredContent??W.content),{headers:{"Content-Type":"application/json"}})}catch(G){return Q71(G,X)}});var J71=kb;pW();class YY0{db;constructor(X){this.db=X}async create(X){let Y=X.id??t8("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;if(Y.hidden!==void 0)J.hidden=Y.hidden;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,Q){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",X).where("hidden","=",!1).orderBy("updated_at","desc");if(Y)J=J.where("created_by","=",Y);let G=this.db.selectFrom("threads").select(($)=>$.fn.count("id").as("count")).where("organization_id","=",X).where("hidden","=",!1);if(Y)G=G.where("created_by","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[W,Z]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:W.map(($)=>this.threadFromDbRow($)),total:Number(Z?.count||0)}}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()}}}function Dh6(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 Nh6(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 Oh6(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 Nh6(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 Lh6(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 wh6(X,Y,Q,J=W71){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",()=>Lh6(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",()=>AG1(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}}var G71,UK={set:(X)=>{G71=X},create:async(X,Y)=>{return await G71(X,Y)}},W71={measure:async(X,Y)=>{return await Y()}},Mh6=["x-hub-signature-256"];function Z71(X){let Y=new zP(X.encryption.key),Q={connections:new BP(X.db,Y),organizationSettings:new pX0(X.db),monitoring:new dX0(X.db,X.databaseType),virtualMcps:new mX0(X.db),users:new cX0(X.db),threads:new YY0(X.db)};return async(J,G)=>{let W=G?.timings??W71,Z=J?.headers.get("x-caller-id")??void 0,$=J?await wh6(J,X.auth,X.db,W):{user:void 0},K=Oh6({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 qK(X.auth,H.user?.id,void 0,K,$.role,"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,wellKnownForwardableHeaders:Object.fromEntries(Mh6.map((N)=>[N,J?.headers.get(N)??null]).filter(([N,L])=>L!==null)),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:Dh6(J?.headers.get("x-mesh-properties"))},eventBus:X.eventBus,createMCPProxy:async(N)=>{return await X71(N,D)}};return D}}class $71{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 A=T.filter??null,P=C.filter??null;if(A!==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 K71(X){return new $71(X)}function pY(X,Y,Q,J,G,W,Z,$){return pY.fromTZ(pY.tp(X,Y,Q,J,G,W,Z),$)}pY.fromTZISO=(X,Y,Q)=>pY.fromTZ(Ph6(X,Y),Q);pY.fromTZ=function(X,Y){let Q=new Date(Date.UTC(X.y,X.m-1,X.d,X.h,X.i,X.s)),J=QY0(X.tz,Q),G=new Date(Q.getTime()-J),W=QY0(X.tz,G);if(W-J===0)return G;{let Z=new Date(Q.getTime()-W),$=QY0(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}};pY.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}};pY.tp=(X,Y,Q,J,G,W,Z)=>({y:X,m:Y,d:Q,h:J,i:G,s:W,tz:Z});function QY0(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 Ph6(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("+")?pY.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):pY.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),Y)}pY.minitz=pY;var JY0=32,sP=31|JY0,q71=[1,2,4,8,16],H71=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 pJ(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,sP),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]|JY0;else if(Y===sP)this.dayOfWeek[X]=sP;else if(Y<6&&Y>0)this.dayOfWeek[X]=this.dayOfWeek[X]|q71[Y-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Y}, Type: ${typeof Y}`)}},F71=[31,28,31,30,31,30,31,31,30,31,30,31],sW=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],pJ=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&sP&&q71[Z-1]&G)return!0;if(G&JY0){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=pY.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>F71[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=pY.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(pY.fromTZISO(Y,this.tz))}findNext(Y,Q,J,G){let W=this[Q],Z;J.lastDayOfMonth&&(this.month!==1?Z=F71[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&sP)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,sW[J][0],Y,sW[J][2]);if(G>1){let W=J+1;for(;W<sW.length;)this[sW[W][0]]=-sW[W][2],W++;if(G===3)return this[sW[J][1]]++,this[sW[J][0]]=-sW[J][2],this.apply(),this.recurse(Y,Q,0);if(this.apply())return this.recurse(Y,Q,J-1)}return J+=1,J>=sW.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)):pY.fromTZ(pY.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Ah6(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 pJ(X.startAt,X.timezone)),X.stopAt&&(X.stopAt=new pJ(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 oP(X){return Object.prototype.toString.call(X)==="[object Function]"||typeof X=="function"||X instanceof Function}function Th6(X){return oP(X)}function Eh6(X){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(X):X&&typeof X.unref<"u"&&X.unref()}var V71=30000,vb=[],_b=class{name;options;_states;fn;constructor(X,Y,Q){let J,G;if(oP(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(oP(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=Ah6(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 H71("* * * * *")},X&&(X instanceof Date||typeof X=="string"&&X.indexOf(":")>0)?this._states.once=new pJ(X,this.options.timezone||this.options.utcOffset):this._states.pattern=new H71(X,this.options.timezone),this.name){if(vb.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");vb.push(this)}return G!==void 0&&Th6(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 pJ||X instanceof Date?Y.getTime()-X.getTime():Y.getTime()-new pJ(X).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let X=vb.indexOf(this);X>=0&&vb.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>V71&&(Y=V71),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),Y),this._states.currentTimeout&&this.options.unref&&Eh6(this._states.currentTimeout),this)}async _trigger(X){if(this._states.blocking=!0,this._states.currentRun=new pJ(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){oP(this.options.catch)&&this.options.catch(Y,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new pJ(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&&oP(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 pJ(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 pJ(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 pJ(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 pJ(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 yb={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Ob();function U71(){return async(X,Y)=>{try{let Q=await UK.create(),J=await Y71(X,{...Q,auth:{...Q.auth,user:{id:"notify-worker"}}}),W=await i80.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}}}}function z71(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 jh6(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(z71(J.event))}else Y.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[z71(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 GY0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(X,Y){this.storage=X;this.notifySubscriber=U71(),this.config={...yb,...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=jh6(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 _b(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)}}}class WY0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new GY0(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 _b(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}}function B71(...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 bb{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 Ch6}from"kysely";var ZB="mesh_events";class ZY0{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===ZB&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Y)=>{console.error("[PostgresNotify] Connection error:",Y),this.cleanup()}),await this.listenClient.query(`LISTEN ${ZB}`),console.log("[PostgresNotify] Started LISTEN on",ZB)}catch(Y){console.error("[PostgresNotify] Failed to start LISTEN:",Y),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${ZB}`),console.log("[PostgresNotify] Stopped LISTEN on",ZB)}catch{}this.cleanup()}}async notify(X){try{await Ch6`SELECT pg_notify(${ZB}, ${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}}function D71(X,Y){let Q=K71(X.db),J=Y?.pollIntervalMs??yb.pollIntervalMs,G=X.type==="postgres"?B71(new bb(J),new ZY0(X.db,X.pool)):new bb(J);return new WY0({storage:Q,config:Y,notifyStrategy:G})}var N71={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 O71=new p8;O71.get("/config",async(X)=>{try{let Y=Object.keys(e8.socialProviders??{}),Q=Y.length>0,J=Y.map((Z)=>({name:Z,icon:N71[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:e8.emailAndPassword?.enabled??!1},magicLink:{enabled:e8.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:e8.ssoConfig?{enabled:!0,providerId:e8.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)}});var L71=O71;tH();var a71="vercel.ai.error",Ih6=Symbol.for(a71),w71,M71,N1=class X extends(M71=Error,w71=Ih6,M71){constructor({name:Y,message:Q,cause:J}){super(Q);this[w71]=!0,this.name=Y,this.cause=J}static isInstance(Y){return X.hasMarker(Y,a71)}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}},r71="AI_APICallError",o71=`vercel.ai.error.${r71}`,Rh6=Symbol.for(o71),P71,A71,XX=class extends(A71=N1,P71=Rh6,A71){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:r71,message:X,cause:Z});this[P71]=!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 N1.hasMarker(X,o71)}},s71="AI_EmptyResponseBodyError",t71=`vercel.ai.error.${s71}`,Sh6=Symbol.for(t71),T71,E71,e71=class extends(E71=N1,T71=Sh6,E71){constructor({message:X="Empty response body"}={}){super({name:s71,message:X});this[T71]=!0}static isInstance(X){return N1.hasMarker(X,t71)}};function g5(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 XW1="AI_InvalidArgumentError",YW1=`vercel.ai.error.${XW1}`,kh6=Symbol.for(YW1),j71,C71,QW1=class extends(C71=N1,j71=kh6,C71){constructor({message:X,cause:Y,argument:Q}){super({name:XW1,message:X,cause:Y});this[j71]=!0,this.argument=Q}static isInstance(X){return N1.hasMarker(X,YW1)}},JW1="AI_InvalidPromptError",GW1=`vercel.ai.error.${JW1}`,vh6=Symbol.for(GW1),I71,R71,PF=class extends(R71=N1,I71=vh6,R71){constructor({prompt:X,message:Y,cause:Q}){super({name:JW1,message:`Invalid prompt: ${Y}`,cause:Q});this[I71]=!0,this.prompt=X}static isInstance(X){return N1.hasMarker(X,GW1)}},WW1="AI_InvalidResponseDataError",ZW1=`vercel.ai.error.${WW1}`,_h6=Symbol.for(ZW1),S71,k71,fo4=class extends(k71=N1,S71=_h6,k71){constructor({data:X,message:Y=`Invalid response data: ${JSON.stringify(X)}.`}){super({name:WW1,message:Y});this[S71]=!0,this.data=X}static isInstance(X){return N1.hasMarker(X,ZW1)}},$W1="AI_JSONParseError",KW1=`vercel.ai.error.${$W1}`,yh6=Symbol.for(KW1),v71,_71,tP=class extends(_71=N1,v71=yh6,_71){constructor({text:X,cause:Y}){super({name:$W1,message:`JSON parsing failed: Text: ${X}.
|
|
1051
|
+
`})}}}var pf6=[f60({organizationCreation:{afterCreate:async(X)=>{await zG1(X.organization.id,X.member.userId)}},ac:Eb,creatorRole:"owner",allowUserToCreateOrganization:!0,dynamicAccessControl:{enabled:!0,maximumRolesPerOrganization:500,enableCustomResources:!0,allowedRolesToCreateResources:BG1,resourceNameValidation:(X)=>{return{valid:/^[a-zA-Z0-9-_]+$/.test(X)}}},roles:{user:mf6,admin:lf6,owner:df6},sendInvitationEmail:wG1}),s60({loginPage:"/login",oidcConfig:{scopes:LG1,metadata:{scopes_supported:LG1},loginPage:"/login"}}),o60({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}}),g60({defaultRole:"user",adminRoles:["admin","owner"]}),Y40(),l60({jwt:{expirationTime:"5m"}}),x61(e8.ssoConfig?DG1(e8.ssoConfig):void 0),...e8.magicLinkConfig&&e8.emailProviders&&e8.emailProviders.length>0?[X40($91(e8.magicLinkConfig,e8.emailProviders))]:[]],cf6=u40(),nf6=Z91(cf6),oW=i10({baseURL:process.env.BASE_URL||"http://localhost:3000",database:nf6,emailAndPassword:{enabled:!0},...e8,rateLimit:{enabled:process.env.DISABLE_RATE_LIMIT!=="true",window:60,max:1e4},plugins:pf6,databaseHooks:{user:{create:{after:async(X)=>{if(JP.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} ${xf6()}`,W=hf6(G);try{await oW.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}}}}}}}});vQ();import{randomBytes as if6}from"crypto";var iP=null;function MG1(){if(iP)return iP;let X=process.env.MESH_JWT_SECRET??e8.jwt?.secret??process.env.BETTER_AUTH_SECRET;if(X)iP=new TextEncoder().encode(X);else console.warn("MESH_JWT_SECRET not set - generating random secret (not persistent)"),iP=new Uint8Array(if6(32));return iP}async function PG1(X,Y="5m"){let Q=MG1();return await new YQ(X).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Y).sign(Q)}async function AG1(X){try{let Y=MG1(),{payload:Q}=await K8(X,Y);return Q}catch{return}}pW();class mX0{db;constructor(X){this.db=X}async create(X,Y,Q){let J=t8("vir"),G=new Date().toISOString();if(await this.db.insertInto("connections").values({id:J,organization_id:X,created_by:Y,title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",connection_url:`virtual://${J}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata?JSON.stringify(Q.metadata):null,tools:null,bindings:null,status:Q.status??"active",created_at:G,updated_at:G}).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:J,child_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("connections").selectAll().where("id","=",Y).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!Q)return null;let J=await X.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Y).execute();return this.deserializeVirtualMCPEntity(Q,J)}async list(X){let Y=await this.db.selectFrom("connections").selectAll().where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute(),Q=Y.map((W)=>W.id);if(Q.length===0)return[];let J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).execute(),G=new Map;for(let W of J){let Z=G.get(W.parent_connection_id)??[];Z.push(W),G.set(W.parent_connection_id,Z)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,G.get(W.id)??[]))}async listByConnectionId(X,Y){let J=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Y).execute()).map((K)=>K.parent_connection_id);if(J.length===0)return[];let G=await this.db.selectFrom("connections").selectAll().where("id","in",J).where("organization_id","=",X).where("connection_type","=","VIRTUAL").execute();if(G.length===0)return[];let W=G.map((K)=>K.id),Z=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",W).execute(),$=new Map;for(let K of Z){let H=$.get(K.parent_connection_id)??[];H.push(K),$.set(K.parent_connection_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};if(Q.title!==void 0)G.title=Q.title;if(Q.description!==void 0)G.description=Q.description;if(Q.icon!==void 0)G.icon=Q.icon;if(Q.status!==void 0)G.status=Q.status;if(Q.metadata!==void 0)G.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(await this.db.updateTable("connections").set(G).where("id","=",X).where("connection_type","=","VIRTUAL").execute(),Q.connections!==void 0){if(await this.db.deleteFrom("connection_aggregations").where("parent_connection_id","=",X).execute(),Q.connections.length>0)await this.db.insertInto("connection_aggregations").values(Q.connections.map((Z)=>({id:t8("agg"),parent_connection_id:X,child_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("connection_aggregations").where("parent_connection_id","=",X).execute(),await this.db.deleteFrom("connections").where("id","=",X).where("connection_type","=","VIRTUAL").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,G=X.status==="active"?"active":"inactive";return{id:X.id,organization_id:X.organization_id,title:X.title,description:X.description,tool_selection_mode:"inclusion",icon:X.icon,status:G,created_at:Q,updated_at:J,created_by:X.created_by,updated_by:void 0,metadata:this.parseJson(X.metadata),connections:Y.map((W)=>({connection_id:W.child_connection_id,selected_tools:this.parseJson(W.selected_tools),selected_resources:this.parseJson(W.selected_resources),selected_prompts:this.parseJson(W.selected_prompts)}))}}parseJson(X){if(X===null)return null;if(typeof X==="string")try{return JSON.parse(X)}catch{return null}return X}}import{sql as jb}from"kysely";class lX0{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 HN.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 HN.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()}})}}pW();class dX0{db;redactor;databaseType;constructor(X,Y="sqlite"){this.db=X;this.redactor=new lX0,this.databaseType=Y}jsonExtract(X,Y){if(this.databaseType==="postgres")return jb`(${jb.ref(X)}::jsonb)->>${Y}`;let Q=`$.${Y}`;return jb`json_extract(${jb.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||t8("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}}}class pX0{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 cX0{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 TG1="mcp.mesh";class EG1 extends Error{constructor(X){super(X);this.name="UnauthorizedError"}}class nX0 extends Error{constructor(X){super(X);this.name="ForbiddenError"}}class qK{userId;toolName;boundAuth;role;connectionId;getToolMeta;_granted=!1;constructor(X,Y,Q,J,G,W="self",Z){this.userId=Y;this.toolName=Q;this.boundAuth=J;this.role=G;this.connectionId=W;this.getToolMeta=Z}[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){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new EG1("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 nX0("No resources specified for access check");for(let Q of Y)if(await this.checkResource(Q)){this.grant();return}throw new nX0(`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)}async isToolPublic(){if(this.toolName?.startsWith("MESH_PUBLIC_"))return!0;if(!this.getToolMeta)return!1;try{let X=await this.getToolMeta();if(!X)return!1;let Q=X[TG1]?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}q7();function jG1(X){let Y=null;return()=>{if(Y)return Y;return Y=X().catch((Q)=>{throw Y=null,Q}),Y}}class CG1{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 B7(X){return new CG1(X)}class iX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>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)}}qX();function af6(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 IG1(X,Y){return Y.some((Q)=>af6(X,Q))}class aX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>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)=>!IG1(K.uri,G.selectedResources))}else if(!G.selectedResources||G.selectedResources.length===0)$=[];else $=$.filter((K)=>IG1(K.uri,G.selectedResources));return{connectionId:W,resources:$}}catch(Z){if(!(Z instanceof Q1)||Z.code!==$1.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)}}qX();class rX0{proxies;cache;constructor(X){this.proxies=X;this.cache=B7(()=>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 Q1)||G.code!==$1.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}}}qX();a0();jP();var SG1=U.object({query:U.string().min(1).describe("Search query to find tools by name or description"),limit:U.number().default(10).describe("Maximum number of results to return")}),rf6=U.toJSONSchema(SG1),kG1=U.object({tools:U.array(U.string()).min(1).describe("Array of tool names to get detailed schemas for")}),of6=U.toJSONSchema(kG1),vG1=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).")}),sf6=U.toJSONSchema(vG1),RG1=new Map;function tf6(X){let Y=X.slice().sort().join(","),Q=RG1.get(Y);if(!Q){let J=U.object({name:(X.length>0?U.enum(X):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")});Q={schema:J,jsonSchema:U.toJSONSchema(J)},RG1.set(Y,Q)}return Q}function _G1(X){let Y=EP(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: ${Y.length}.`,inputSchema:rf6},handler:async(J)=>{let G=SG1.safeParse(J);if(!G.success)return QB({error:G.error.flatten()});let W=Fb(G.data.query,Y,G.data.limit);return Ub({query:G.data.query,results:W.map((Z)=>({name:Z.name,description:Z.description,connection:Z._meta.connectionTitle})),totalAvailable:Y.length})}}}function yG1(X){let Y=EP(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:of6},handler:async(Q)=>{let J=kG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G=Vb(J.data.tools,Y);return Ub({tools:G.tools,notFound:G.notFound})}}}function ef6(X){let Y=EP(X.tools),Q=Y.map((Z)=>Z.name),J=new Map(Y.map((Z)=>[Z.name,Z])),{schema:G,jsonSchema:W}=tf6(Q);return{tool:{name:"GATEWAY_CALL_TOOL",description:"Execute a tool by name. Use GATEWAY_DESCRIBE_TOOLS first to understand the input schema.",inputSchema:W},handler:async(Z)=>{let $=G.safeParse(Z);if(!$.success)return QB({error:$.error.flatten()});let{name:K,arguments:H}=$.data;if(!J.has(K))return{content:[{type:"text",text:`Tool not found: ${K}. Use GATEWAY_SEARCH_TOOLS to find available tools.`}],isError:!0};return X.callTool(K,H)}}}function Xh6(X){let Y=EP(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:sf6},handler:async(Q)=>{let J=vG1.safeParse(Q);if(!J.success)return QB({error:J.error.flatten()});let G={...X,tools:Y},W=await qb(J.data.code,G,J.data.timeoutMs);if(W.error)return QB(W);return Ub(W)}}}function bG1(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)}}}var Yh6=(X)=>({tools:X.tools,callTool:(Y,Q)=>X.callTool(Y,Q)}),Qh6=(X)=>bG1([_G1(X),yG1(X),Xh6(X)]),Jh6=(X)=>bG1([_G1(X),yG1(X),ef6(X)]);function fG1(X){switch(X){case"smart_tool_selection":return Jh6;case"code_execution":return Qh6;case"passthrough":default:return Yh6}}function hG1(X){switch(X){case"smart_tool_selection":return"smart_tool_selection";case"code_execution":return"code_execution";case"passthrough":default:return"passthrough"}}class oX0{proxies;options;cache;constructor(X,Y){this.proxies=X;this.options=Y;this.cache=B7(()=>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 Q1)||F.code!==$1.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})},$=fG1(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"}})}}function xG1(X,Y){if(X.connection_type!=="VIRTUAL")return!1;return ZK(X.connection_url)===Y}async function Gh6(X,Y){let Q=await sz.create(X.connections,Y),J=new oX0(Q,{selectionMode:X.toolSelectionMode,strategy:X.toolSelectionStrategy}),G=new aX0(Q,{selectionMode:X.toolSelectionMode}),W=new rX0(Q),Z=new iX0(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 aP(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"&&!xG1(K,X.id)),$=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"&&!xG1(K,X.id))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 Gh6(G,Y)}e80();async function gG1(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"}}}tH();H80();function Wh6(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)}})}var uG1="__mesh_stable_stdio_pool__",MF=globalThis[uG1]??(globalThis[uG1]=new Map);async function lG1(X,Y){let Q=MF.get(X.id);if(Q?.status==="connected"&&Q.stableClient)return Q.stableClient;if(Q?.connectPromise&&(Q.status==="connecting"||Q.status==="reconnecting"))return Q.connectPromise;let J=Q?.status==="failed",G=Q??{transport:null,client:null,stableClient:null,config:X,status:"connecting",connectPromise:null};if(!Q)MF.set(X.id,G);return G.status=J?"reconnecting":"connecting",G.connectPromise=(async()=>{try{console.log(`[StableStdio] ${J?"Respawning":"Spawning"}: ${X.id} (${X.command} ${X.args?.join(" ")??""})`);let W=new wP({command:X.command,args:X.args,env:X.env,cwd:X.cwd,stderr:"pipe"});G.transport=W;let Z=Y??new l9({name:`mesh-stdio-${X.id}`,version:"1.0.0"});G.client=Z,G.stableClient=Wh6(Z),Z.onclose=()=>{console.log(`[StableStdio] Connection closed unexpectedly: ${X.id}`),G.status="failed",G.connectPromise=null};let $=X.name||X.id,K="\x1B[2m",H="\x1B[0m";W.stderr?.on("data",(q)=>{let z=q.toString().trimEnd();if(z)console.error(`${z} ${K}[${$}]${H}`)});let F=new AbortController,V=setTimeout(()=>F.abort(),30000);try{await Promise.race([Z.connect(W),new Promise((q,z)=>{F.signal.addEventListener("abort",()=>{z(Error("Stdio connection timeout after 30s"))})})])}finally{clearTimeout(V)}return G.status="connected",console.log(`[StableStdio] Connected: ${X.id}`),G.stableClient}catch(W){console.error(`[StableStdio] Failed to connect ${X.id}:`,W),G.status="failed",G.connectPromise=null;try{await G.transport?.close()}catch{}throw W}})(),G.connectPromise}async function Zh6(X){let Y=MF.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{}MF.delete(X)}async function $h6(){console.log(`[StableStdio] Closing all connections (${MF.size})`);let X=Array.from(MF.keys()).map((Y)=>Zh6(Y));await Promise.allSettled(X),MF.clear()}var mG1="__mesh_stable_stdio_shutdown_registered__";if(!globalThis[mG1]){globalThis[mG1]=!0;let X=async(Y)=>{await $h6(),process.exit(Y==="SIGINT"?130:143)};process.on("SIGINT",()=>X("SIGINT")),process.on("SIGTERM",()=>X("SIGTERM"))}Ab();q7();tH();Xb();oq();Gb();Wb();qX();Gb();Wb();qX();gL();var sX0=new p8;async function Cb(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?Eo(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(Z.status!=="active")return X.json({error:`Agent is inactive: ${Z.id}`},503);Q.connectionId=Z.id;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=hG1(K),F=await aP(Z,Q,H),V=new qF({name:`mcp-virtual-mcp-${Z.title}`,version:"1.0.0"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:Z.metadata?.instructions??void 0}),q=new UF({enableJsonResponse:X.req.header("Accept")?.includes("application/json")??!1});await V.connect(q),V.server.setRequestHandler(tZ,async(z)=>{return F.client.listTools()}),V.server.setRequestHandler(TG,async(z)=>{return await F.client.callTool(z.params)}),V.server.setRequestHandler(iZ,async()=>{return F.client.listResources()}),V.server.setRequestHandler(rZ,async(z)=>{return F.client.readResource(z.params)}),V.server.setRequestHandler(aZ,async()=>{return F.client.listResourceTemplates()}),V.server.setRequestHandler(oZ,async()=>{return F.client.listPrompts()}),V.server.setRequestHandler(sZ,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)}}sX0.all("/gateway/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});sX0.all("/virtual-mcp/:virtualMcpId?",async(X)=>{let Y=X.req.param("virtualMcpId");return Cb(X,Y)});var dG1=sX0;var Ib=new p8,tX0=[404,401,406];async function pG1(X,Y){return(await Y.storage.connections.findById(X))?.connection_url??null}function Kh6(X){let Y=X.toLowerCase();return Y.includes("resource_metadata=")||Y.includes("invalid_token")||Y.includes("oauth")}async function cG1(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(Kh6(J))return J}}return null}catch{return null}}async function Rb(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(!tX0.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"}}),!tX0.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 Hh6(X,Y){let Q=await pG1(X,Y);if(!Q)return null;let J;try{J=new URL(Q).origin}catch{return null}try{let G=await Rb(Q);if(G.ok){let W=await G.json();if(W.authorization_servers?.[0])return W.authorization_servers[0]}}catch{}return J}async function nG1(X){let Y=X.get("meshContext");if(!Y)Y=await UK.create(X.req.raw),X.set("meshContext",Y);return Y}async function iG1({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 cG1(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"}})}var Sb=(X)=>{if(!(X.hostname==="localhost"||X.hostname==="127.0.0.1"))X.protocol="https:";return X},aG1=async(X)=>{let Y=X.req.param("connectionId"),Q=await nG1(X),J=await pG1(Y,Q);if(!J)return X.json({error:"Connection not found"},404);let G=Sb(new URL(X.req.url)),W=`${G.origin}/mcp/${Y}`,Z=`${G.origin}/oauth-proxy/${Y}`;try{let $=await Rb(J);if(!$.ok&&tX0.includes($.status)){if(await cG1(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)}};Ib.get("/.well-known/oauth-protected-resource/mcp/:connectionId",(X)=>aG1(X));Ib.get("/mcp/:connectionId/.well-known/oauth-protected-resource",(X)=>aG1(X));async function eX0(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}Ib.get("/.well-known/oauth-authorization-server/oauth-proxy/:connectionId",async(X)=>{let Y=X.req.param("connectionId"),Q=await nG1(X),J=await Hh6(Y,Q);if(!J)return X.json({error:"Connection not found or no auth server"},404);try{let G=await eX0(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(),$=`${Sb(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)}});var rG1=Ib;function Fh6(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 Vh6(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 qh6(X,Y){if(!X&&!Y)return;if(!X)return Y;if(!Y)return X;return{...Y,...X}}function oG1(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 Uh6(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 rP(X){let{ctx:Y,enabled:Q}=X,J=X.organizationId??Y.organization?.id;if(!Q||!J)return;let G=Vh6(X.request.params.arguments),W=qh6(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:X.virtualMcpId,properties:W})}function sG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Date.now()-K;return await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:oG1(H),isError:Boolean(H.isError),errorMessage:Fh6(H),durationMs:F}),H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}function tG1(X){let{ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W}=X;return async(Z,$)=>{let K=Date.now();try{let H=await $(),F=Y.organization?.id;if(Q&&F){let V=H.clone();(async()=>{try{let{text:q,truncated:z}=await Uh6(V,262144),D=Date.now()-K,N=V.headers.get("content-type")??"",L=q;if(N.includes("application/json"))try{L=q.length?JSON.parse(q):null}catch{L=q}let w=H.status>=400,C=w&&L&&typeof L==="object"&&"error"in L?L.error:void 0,T=typeof C==="string"&&C?C:w&&typeof L==="string"&&L.trim()?L.slice(0,500):w?`HTTP ${H.status} ${H.statusText}`.trim():z?"Response body truncated to 262144 bytes":void 0;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:oG1(L),isError:w,errorMessage:T,durationMs:D})}catch(q){let z=Date.now()-K;await rP({ctx:Y,enabled:Q,organizationId:F,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:`Failed to read streamable response body: ${q.message}`,durationMs:z})}})()}return H}catch(H){let F=H,V=Date.now()-K;throw await rP({ctx:Y,enabled:Q,connectionId:J,connectionTitle:G,virtualMcpId:W,request:Z,output:{},isError:!0,errorMessage:F.message,durationMs:V}),H}}}var kb=new p8,XY0=300000;function zh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new qK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return{content:[{type:"text",text:`Authorization failed: ${W.message}`}],isError:!0}}}}function Bh6(X,Y,Q){return async(J,G)=>{try{let W=J.params.name,Z=async()=>{let{tools:K}=await Q();return K.find((F)=>F.name===W)?._meta};return await new qK(X.authInstance,X.auth.user?.id??X.auth.apiKey?.userId,W,X.boundAuth,X.auth.user?.role,Y,Z).check(W),await G()}catch(W){return new Response(JSON.stringify({error:`Authorization failed: ${W.message}`}),{status:403,headers:{"Content-Type":"application/json"}})}}}async function eG1(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,$=jG1(async()=>{let S=t80(J.configuration_state,J.configuration_scopes),f=Y.auth.user?.id??Y.auth.apiKey?.userId;if(!f){console.error("User ID required to issue configuration token");return}try{W=await PG1({sub:f,user:{id:f},metadata:{state:J.configuration_state??void 0,meshUrl:process.env.MESH_URL??Y.baseUrl,connectionId:G,organizationId:Y.organization?.id},permissions:S})}catch(t){console.error("Failed to issue configuration token:",t)}}),K=async()=>{await $();let S={...Z?{"x-caller-id":Z}:{},...Y.metadata.wellKnownForwardableHeaders??{},"x-request-id":Y.metadata.requestId},f=null,t=new aW(Y.db,Y.vault),m=await t.get(G);if(m){let J0=!!m.refreshToken&&!!m.tokenEndpoint;if(t.isExpired(m,J0?300000:0))if(J0){console.log(`[Proxy] Token expired for ${G}, attempting refresh`);let Y0=await gG1(m);if(Y0.success&&Y0.accessToken)await t.upsert({connectionId:G,accessToken:Y0.accessToken,refreshToken:Y0.refreshToken??m.refreshToken,scope:Y0.scope??m.scope,expiresAt:Y0.expiresIn?new Date(Date.now()+Y0.expiresIn*1000):null,clientId:m.clientId,clientSecret:m.clientSecret,tokenEndpoint:m.tokenEndpoint}),f=Y0.accessToken,console.log(`[Proxy] Token refreshed for ${G}`);else await t.delete(G),console.error(`[Proxy] Token refresh failed for ${G}: ${Y0.error}`)}else await t.delete(G),console.log(`[Proxy] Token expired without refresh capability for ${G}`);else f=m.accessToken}if(!f&&J.connection_token)f=J.connection_token;if(f)S.Authorization=`Bearer ${f}`;if(W)S["x-mesh-token"]=W;return S},H=J.connection_type==="STDIO",F=KF(J.connection_headers)?J.connection_headers:null,V=!H?J.connection_headers:null,q=async()=>{let S=new l9({name:"mcp-mesh-proxy",version:"1.0.0"},{capabilities:{tasks:{list:{},cancel:{},requests:{tool:{call:{}}}}}});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 lG1({id:G,name:J.title,command:F.command,args:F.args,env:F.envVars,cwd:F.cwd},S)}case"HTTP":case"Websocket":{if(!J.connection_url)throw Error(`${J.connection_type} connection missing URL`);let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new IG(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"SSE":{if(!J.connection_url)throw Error("SSE connection missing URL");let f=await K();if(V?.headers)Object.assign(f,V.headers);let t=new VF(new URL(J.connection_url),{requestInit:{headers:f}});return await S.connect(t),S}case"VIRTUAL":{let f=ZK(J.connection_url);if(!f)throw Error("VIRTUAL connection missing virtual MCP ID in connection_url");let t=await Y.storage.virtualMcps.findById(f);if(!t)throw Error(`Virtual MCP not found: ${f}`);let m=await aP(t,Y,"passthrough");return{callTool:(J0)=>m.client.callTool(J0),listTools:()=>m.client.listTools(),listResources:()=>m.client.listResources(),readResource:(J0)=>m.client.readResource(J0),listResourceTemplates:()=>m.client.listResourceTemplates(),listPrompts:()=>m.client.listPrompts(),getPrompt:(J0)=>m.client.getPrompt(J0),close:async()=>{},getServerCapabilities:()=>({tools:{},resources:{},prompts:{}}),getInstructions:()=>t.metadata?.instructions??void 0}}default:throw Error(`Unknown connection type: ${J.connection_type}`)}},z=async()=>{if(J.tools&&J.tools.length>0)return{tools:J.tools.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema,outputSchema:f.outputSchema,annotations:f.annotations,_meta:f._meta}))};let S;try{return S=await q(),await S.listTools()}finally{S?.close().catch(console.error)}},D=Q?async(S,f)=>await f():zh6(Y,G,z),N=Q?async(S,f)=>await f():Bh6(Y,G,z),L=Y.connectionId&&Y.connectionId!==G?Y.connectionId:void 0,w={enabled:T81().enabled,connectionId:G,connectionTitle:J.title,virtualMcpId:L,ctx:Y},C=sG1(w),T=tG1(w),A=PP(C,D),P=PP(T,N),j=async(S)=>{return A(S,async()=>{let f=await q(),t=Date.now(),m={...S.params};if(m.arguments&&"_meta"in m.arguments){let{_meta:J0,...V0}=m.arguments;m.arguments=V0}return await Y.tracer.startActiveSpan("mcp.proxy.callTool",{attributes:{"connection.id":G,"tool.name":S.params.name,"request.id":Y.metadata.requestId}},async(J0)=>{try{let V0=await f.callTool(m,void 0,{timeout:XY0}),Y0=Date.now()-t;return Y.meter.createHistogram("connection.proxy.duration").record(Y0,{"connection.id":G,"tool.name":S.params.name,status:"success"}),Y.meter.createCounter("connection.proxy.requests").add(1,{"connection.id":G,"tool.name":S.params.name,status:"success"}),J0.end(),V0}catch(V0){let Y0=V0,U0=Date.now()-t;throw Y.meter.createHistogram("connection.proxy.duration").record(U0,{"connection.id":G,"tool.name":S.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.errors").add(1,{"connection.id":G,"tool.name":S.params.name,error:Y0.message}),J0.recordException(Y0),J0.end(),V0}finally{f.close().catch(console.error)}})})};return{fetch:async(S)=>{let f=new URL(S.url),t;try{t=await q()}catch(P0){let v0=J.connection_url?await iG1({error:P0,reqUrl:f,connectionId:G,connectionUrl:J.connection_url,headers:await K()}):null;if(v0)return v0;throw P0}let m=t.getServerCapabilities(),J0=t.getInstructions(),V0=m??{tools:{},resources:{},prompts:{}},Y0=new qF({name:"mcp-mesh",version:"1.0.0"},{capabilities:V0,instructions:J0}),U0=new UF({enableJsonResponse:S.headers.get("Accept")?.includes("application/json")??!1});if(await Y0.connect(U0),Y0.server.setRequestHandler(tZ,()=>t.listTools()),Y0.server.setRequestHandler(TG,j),V0.resources)Y0.server.setRequestHandler(iZ,()=>t.listResources()),Y0.server.setRequestHandler(rZ,(P0)=>t.readResource(P0.params)),Y0.server.setRequestHandler(aZ,()=>t.listResourceTemplates());if(V0.prompts)Y0.server.setRequestHandler(oZ,()=>t.listPrompts()),Y0.server.setRequestHandler(sZ,(P0)=>t.getPrompt(P0.params));try{return await U0.handleRequest(S)}finally{try{await t.close()}catch{}try{await U0.close?.()}catch{}}},client:{callTool:(S)=>{return j({method:"tools/call",params:S})},listTools:z,listResources:async()=>{let S;try{return S=await q(),await S.listResources()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resources:[]};throw f}finally{S?.close().catch(console.error)}},readResource:async(S)=>{let f;try{return f=await q(),await f.readResource(S)}finally{f?.close().catch(console.error)}},listResourceTemplates:async()=>{let S;try{return S=await q(),await S.listResourceTemplates()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{resourceTemplates:[]};throw f}finally{S?.close().catch(console.error)}},listPrompts:async()=>{let S;try{return S=await q(),await S.listPrompts()}catch(f){if(f instanceof Q1&&f.code===$1.MethodNotFound)return{prompts:[]};throw f}finally{S?.close().catch(console.error)}},getPrompt:async(S)=>{let f;try{return f=await q(),await f.getPrompt(S)}finally{f?.close().catch(console.error)}}},callStreamableTool:async(S,f)=>{if(J.connection_type==="VIRTUAL"){let J0=await j({method:"tools/call",params:{name:S,arguments:f}});return new Response(JSON.stringify(J0),{headers:{"Content-Type":"application/json"}})}if(!J.connection_url)throw Error("Streamable tools require HTTP connection with URL");let t=J.connection_url,m={method:"tools/call",params:{name:S,arguments:f}};return P(m,async()=>{let J0=await K();if(V?.headers)Object.assign(J0,V.headers);let V0=new URL(t);return V0.pathname=V0.pathname.replace(/\/$/,"")+`/call-tool/${m.params.name}`,await Y.tracer.startActiveSpan("mcp.proxy.callStreamableTool",{attributes:{"connection.id":G,"tool.name":m.params.name,"request.id":Y.metadata.requestId}},async(Y0)=>{let U0=Date.now();try{let P0=await fetch(V0.toString(),{method:"POST",redirect:"manual",body:JSON.stringify(m.params.arguments),headers:{...J0,"Content-Type":"application/json"}}),v0=Date.now()-U0;return Y.meter.createHistogram("connection.proxy.streamable.duration").record(v0,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y.meter.createCounter("connection.proxy.streamable.requests").add(1,{"connection.id":G,"tool.name":m.params.name,status:P0.ok?"success":"error"}),Y0.end(),P0}catch(P0){let v0=P0,G1=Date.now()-U0;throw Y.meter.createHistogram("connection.proxy.streamable.duration").record(G1,{"connection.id":G,"tool.name":m.params.name,status:"error"}),Y.meter.createCounter("connection.proxy.streamable.errors").add(1,{"connection.id":G,"tool.name":m.params.name,error:v0.message}),Y0.recordException(v0),Y0.end(),P0}})})}}}async function X71(X,Y){return eG1(X,Y,{superUser:!1})}async function Y71(X,Y){return eG1(X,Y,{superUser:!0})}kb.all("/",async(X)=>{return Cb(X,void 0)});kb.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){return Q71(J,X)}});var Q71=(X,Y)=>{if(X.message.includes("not found"))return Y.json({error:X.message},404);if(X.message.includes("does not belong to the active organization"))return Y.json({error:"Connection not found"},404);if(X.message.includes("inactive"))return Y.json({error:X.message},503);return Y.json({error:"Internal server error",message:X.message},500)};kb.all("/:connectionId/call-tool/:toolName",async(X)=>{let Y=X.req.param("connectionId"),Q=X.req.param("toolName"),J=X.get("meshContext");try{let W=await(await J.createMCPProxy(Y)).client.callTool({name:Q,arguments:await X.req.json()});if(W instanceof Response)return W;if(W.isError)return new Response(JSON.stringify(W.content),{headers:{"Content-Type":"application/json"},status:500});return new Response(JSON.stringify(W.structuredContent??W.content),{headers:{"Content-Type":"application/json"}})}catch(G){return Q71(G,X)}});var J71=kb;pW();class YY0{db;constructor(X){this.db=X}async create(X){let Y=X.id??t8("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;if(Y.hidden!==void 0)J.hidden=Y.hidden;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,Q){let J=this.db.selectFrom("threads").selectAll().where("organization_id","=",X).where("hidden","=",!1).orderBy("updated_at","desc");if(Y)J=J.where("created_by","=",Y);let G=this.db.selectFrom("threads").select(($)=>$.fn.count("id").as("count")).where("organization_id","=",X).where("hidden","=",!1);if(Y)G=G.where("created_by","=",Y);if(Q?.limit)J=J.limit(Q.limit);if(Q?.offset)J=J.offset(Q.offset);let[W,Z]=await Promise.all([J.execute(),G.executeTakeFirst()]);return{threads:W.map(($)=>this.threadFromDbRow($)),total:Number(Z?.count||0)}}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()}}}function Dh6(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 Nh6(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 Oh6(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 Nh6(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 Lh6(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 wh6(X,Y,Q,J=W71){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",()=>Lh6(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",()=>AG1(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}}var G71,UK={set:(X)=>{G71=X},create:async(X,Y)=>{return await G71(X,Y)}},W71={measure:async(X,Y)=>{return await Y()}},Mh6=["x-hub-signature-256"];function Z71(X){let Y=new zP(X.encryption.key),Q={connections:new BP(X.db,Y),organizationSettings:new pX0(X.db),monitoring:new dX0(X.db,X.databaseType),virtualMcps:new mX0(X.db),users:new cX0(X.db),threads:new YY0(X.db)};return async(J,G)=>{let W=G?.timings??W71,Z=J?.headers.get("x-caller-id")??void 0,$=J?await wh6(J,X.auth,X.db,W):{user:void 0},K=Oh6({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 qK(X.auth,H.user?.id,void 0,K,$.role,"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,wellKnownForwardableHeaders:Object.fromEntries(Mh6.map((N)=>[N,J?.headers.get(N)??null]).filter(([N,L])=>L!==null)),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:Dh6(J?.headers.get("x-mesh-properties"))},eventBus:X.eventBus,createMCPProxy:async(N)=>{return await X71(N,D)}};return D}}class $71{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 A=T.filter??null,P=C.filter??null;if(A!==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 K71(X){return new $71(X)}function pY(X,Y,Q,J,G,W,Z,$){return pY.fromTZ(pY.tp(X,Y,Q,J,G,W,Z),$)}pY.fromTZISO=(X,Y,Q)=>pY.fromTZ(Ph6(X,Y),Q);pY.fromTZ=function(X,Y){let Q=new Date(Date.UTC(X.y,X.m-1,X.d,X.h,X.i,X.s)),J=QY0(X.tz,Q),G=new Date(Q.getTime()-J),W=QY0(X.tz,G);if(W-J===0)return G;{let Z=new Date(Q.getTime()-W),$=QY0(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}};pY.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}};pY.tp=(X,Y,Q,J,G,W,Z)=>({y:X,m:Y,d:Q,h:J,i:G,s:W,tz:Z});function QY0(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 Ph6(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("+")?pY.tp(Q.getUTCFullYear(),Q.getUTCMonth()+1,Q.getUTCDate(),Q.getUTCHours(),Q.getUTCMinutes(),Q.getUTCSeconds(),"Etc/UTC"):pY.tp(Q.getFullYear(),Q.getMonth()+1,Q.getDate(),Q.getHours(),Q.getMinutes(),Q.getSeconds(),Y)}pY.minitz=pY;var JY0=32,sP=31|JY0,q71=[1,2,4,8,16],H71=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 pJ(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,sP),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]|JY0;else if(Y===sP)this.dayOfWeek[X]=sP;else if(Y<6&&Y>0)this.dayOfWeek[X]=this.dayOfWeek[X]|q71[Y-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Y}, Type: ${typeof Y}`)}},F71=[31,28,31,30,31,30,31,31,30,31,30,31],sW=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],pJ=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&sP&&q71[Z-1]&G)return!0;if(G&JY0){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=pY.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>F71[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=pY.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(pY.fromTZISO(Y,this.tz))}findNext(Y,Q,J,G){let W=this[Q],Z;J.lastDayOfMonth&&(this.month!==1?Z=F71[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&sP)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,sW[J][0],Y,sW[J][2]);if(G>1){let W=J+1;for(;W<sW.length;)this[sW[W][0]]=-sW[W][2],W++;if(G===3)return this[sW[J][1]]++,this[sW[J][0]]=-sW[J][2],this.apply(),this.recurse(Y,Q,0);if(this.apply())return this.recurse(Y,Q,J-1)}return J+=1,J>=sW.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)):pY.fromTZ(pY.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function Ah6(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 pJ(X.startAt,X.timezone)),X.stopAt&&(X.stopAt=new pJ(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 oP(X){return Object.prototype.toString.call(X)==="[object Function]"||typeof X=="function"||X instanceof Function}function Th6(X){return oP(X)}function Eh6(X){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(X):X&&typeof X.unref<"u"&&X.unref()}var V71=30000,vb=[],_b=class{name;options;_states;fn;constructor(X,Y,Q){let J,G;if(oP(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(oP(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=Ah6(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 H71("* * * * *")},X&&(X instanceof Date||typeof X=="string"&&X.indexOf(":")>0)?this._states.once=new pJ(X,this.options.timezone||this.options.utcOffset):this._states.pattern=new H71(X,this.options.timezone),this.name){if(vb.find((W)=>W.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");vb.push(this)}return G!==void 0&&Th6(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 pJ||X instanceof Date?Y.getTime()-X.getTime():Y.getTime()-new pJ(X).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let X=vb.indexOf(this);X>=0&&vb.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>V71&&(Y=V71),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(Q),Y),this._states.currentTimeout&&this.options.unref&&Eh6(this._states.currentTimeout),this)}async _trigger(X){if(this._states.blocking=!0,this._states.currentRun=new pJ(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){oP(this.options.catch)&&this.options.catch(Y,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new pJ(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&&oP(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 pJ(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 pJ(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 pJ(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 pJ(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 yb={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000};Ob();function U71(){return async(X,Y)=>{try{let Q=await UK.create(),J=await Y71(X,{...Q,auth:{...Q.auth,user:{id:"notify-worker"}}}),W=await i80.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}}}}function z71(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 jh6(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(z71(J.event))}else Y.set(G,{connectionId:J.subscription.connectionId,deliveryIds:[J.delivery.id],events:[z71(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 GY0{storage;notifySubscriber;running=!1;processing=!1;config;constructor(X,Y){this.storage=X;this.notifySubscriber=U71(),this.config={...yb,...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=jh6(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 _b(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)}}}class WY0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new GY0(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 _b(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}}function B71(...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 bb{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 Ch6}from"kysely";var ZB="mesh_events";class ZY0{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===ZB&&this.onNotify)this.onNotify()}),this.listenClient.on("error",(Y)=>{console.error("[PostgresNotify] Connection error:",Y),this.cleanup()}),await this.listenClient.query(`LISTEN ${ZB}`),console.log("[PostgresNotify] Started LISTEN on",ZB)}catch(Y){console.error("[PostgresNotify] Failed to start LISTEN:",Y),this.cleanup()}}async stop(){if(this.listenClient){try{await this.listenClient.query(`UNLISTEN ${ZB}`),console.log("[PostgresNotify] Stopped LISTEN on",ZB)}catch{}this.cleanup()}}async notify(X){try{await Ch6`SELECT pg_notify(${ZB}, ${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}}function D71(X,Y){let Q=K71(X.db),J=Y?.pollIntervalMs??yb.pollIntervalMs,G=X.type==="postgres"?B71(new bb(J),new ZY0(X.db,X.pool)):new bb(J);return new WY0({storage:Q,config:Y,notifyStrategy:G})}var N71={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 O71=new p8;O71.get("/config",async(X)=>{try{let Y=Object.keys(e8.socialProviders??{}),Q=Y.length>0,J=Y.map((Z)=>({name:Z,icon:N71[Z].icon})),G=process.env.UNSAFE_ALLOW_STDIO_TRANSPORT==="true",W={emailAndPassword:{enabled:e8.emailAndPassword?.enabled??!1},magicLink:{enabled:e8.magicLinkConfig?.enabled??!1},socialProviders:{enabled:Q,providers:J},sso:e8.ssoConfig?{enabled:!0,providerId:e8.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)}});var L71=O71;tH();var a71="vercel.ai.error",Ih6=Symbol.for(a71),w71,M71,N1=class X extends(M71=Error,w71=Ih6,M71){constructor({name:Y,message:Q,cause:J}){super(Q);this[w71]=!0,this.name=Y,this.cause=J}static isInstance(Y){return X.hasMarker(Y,a71)}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}},r71="AI_APICallError",o71=`vercel.ai.error.${r71}`,Rh6=Symbol.for(o71),P71,A71,XX=class extends(A71=N1,P71=Rh6,A71){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:r71,message:X,cause:Z});this[P71]=!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 N1.hasMarker(X,o71)}},s71="AI_EmptyResponseBodyError",t71=`vercel.ai.error.${s71}`,Sh6=Symbol.for(t71),T71,E71,e71=class extends(E71=N1,T71=Sh6,E71){constructor({message:X="Empty response body"}={}){super({name:s71,message:X});this[T71]=!0}static isInstance(X){return N1.hasMarker(X,t71)}};function g5(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 XW1="AI_InvalidArgumentError",YW1=`vercel.ai.error.${XW1}`,kh6=Symbol.for(YW1),j71,C71,QW1=class extends(C71=N1,j71=kh6,C71){constructor({message:X,cause:Y,argument:Q}){super({name:XW1,message:X,cause:Y});this[j71]=!0,this.argument=Q}static isInstance(X){return N1.hasMarker(X,YW1)}},JW1="AI_InvalidPromptError",GW1=`vercel.ai.error.${JW1}`,vh6=Symbol.for(GW1),I71,R71,PF=class extends(R71=N1,I71=vh6,R71){constructor({prompt:X,message:Y,cause:Q}){super({name:JW1,message:`Invalid prompt: ${Y}`,cause:Q});this[I71]=!0,this.prompt=X}static isInstance(X){return N1.hasMarker(X,GW1)}},WW1="AI_InvalidResponseDataError",ZW1=`vercel.ai.error.${WW1}`,_h6=Symbol.for(ZW1),S71,k71,fo4=class extends(k71=N1,S71=_h6,k71){constructor({data:X,message:Y=`Invalid response data: ${JSON.stringify(X)}.`}){super({name:WW1,message:Y});this[S71]=!0,this.data=X}static isInstance(X){return N1.hasMarker(X,ZW1)}},$W1="AI_JSONParseError",KW1=`vercel.ai.error.${$W1}`,yh6=Symbol.for(KW1),v71,_71,tP=class extends(_71=N1,v71=yh6,_71){constructor({text:X,cause:Y}){super({name:$W1,message:`JSON parsing failed: Text: ${X}.
|
|
1052
1052
|
Error message: ${g5(Y)}`,cause:Y});this[v71]=!0,this.text=X}static isInstance(X){return N1.hasMarker(X,KW1)}},HW1="AI_LoadAPIKeyError",FW1=`vercel.ai.error.${HW1}`,bh6=Symbol.for(FW1),y71,b71,ho4=class extends(b71=N1,y71=bh6,b71){constructor({message:X}){super({name:HW1,message:X});this[y71]=!0}static isInstance(X){return N1.hasMarker(X,FW1)}},VW1="AI_LoadSettingError",qW1=`vercel.ai.error.${VW1}`,fh6=Symbol.for(qW1),f71,h71,xo4=class extends(h71=N1,f71=fh6,h71){constructor({message:X}){super({name:VW1,message:X});this[f71]=!0}static isInstance(X){return N1.hasMarker(X,qW1)}},UW1="AI_NoContentGeneratedError",zW1=`vercel.ai.error.${UW1}`,hh6=Symbol.for(zW1),x71,g71,go4=class extends(g71=N1,x71=hh6,g71){constructor({message:X="No content generated."}={}){super({name:UW1,message:X});this[x71]=!0}static isInstance(X){return N1.hasMarker(X,zW1)}},BW1="AI_NoSuchModelError",DW1=`vercel.ai.error.${BW1}`,xh6=Symbol.for(DW1),u71,m71,uo4=class extends(m71=N1,u71=xh6,m71){constructor({errorName:X=BW1,modelId:Y,modelType:Q,message:J=`No such ${Q}: ${Y}`}){super({name:X,message:J});this[u71]=!0,this.modelId=Y,this.modelType=Q}static isInstance(X){return N1.hasMarker(X,DW1)}},NW1="AI_TooManyEmbeddingValuesForCallError",OW1=`vercel.ai.error.${NW1}`,gh6=Symbol.for(OW1),l71,d71,mo4=class extends(d71=N1,l71=gh6,d71){constructor(X){super({name:NW1,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[l71]=!0,this.provider=X.provider,this.modelId=X.modelId,this.maxEmbeddingsPerCall=X.maxEmbeddingsPerCall,this.values=X.values}static isInstance(X){return N1.hasMarker(X,OW1)}},LW1="AI_TypeValidationError",wW1=`vercel.ai.error.${LW1}`,uh6=Symbol.for(wW1),p71,c71,KQ=class X extends(c71=N1,p71=uh6,c71){constructor({value:Y,cause:Q}){super({name:LW1,message:`Type validation failed: Value: ${JSON.stringify(Y)}.
|
|
1053
1053
|
Error message: ${g5(Q)}`,cause:Q});this[p71]=!0,this.value=Y}static isInstance(Y){return N1.hasMarker(Y,wW1)}static wrap({value:Y,cause:Q}){return X.isInstance(Q)&&Q.value===Y?Q:new X({value:Y,cause:Q})}},MW1="AI_UnsupportedFunctionalityError",PW1=`vercel.ai.error.${MW1}`,mh6=Symbol.for(PW1),n71,i71,AW1=class extends(i71=N1,n71=mh6,i71){constructor({functionality:X,message:Y=`'${X}' functionality not supported.`}){super({name:MW1,message:Y});this[n71]=!0,this.functionality=X}static isInstance(X){return N1.hasMarker(X,PW1)}};c6();SZ();SZ();SZ();wo();function TF(...X){return X.reduce((Y,Q)=>({...Y,...Q!=null?Q:{}}),{})}async function SW1(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(TW1());return}let W=setTimeout(()=>{Z(),J()},X),Z=()=>{clearTimeout(W),Q==null||Q.removeEventListener("abort",$)},$=()=>{Z(),G(TW1())};Q==null||Q.addEventListener("abort",$)})}function TW1(){return new DOMException("Delay was aborted","AbortError")}var EF=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){if(this._promise)return this._promise;return this._promise=new Promise((X,Y)=>{if(this.status.type==="resolved")X(this.status.value);else if(this.status.type==="rejected")Y(this.status.error);this._resolve=X,this._reject=Y}),this._promise}resolve(X){var Y;if(this.status={type:"resolved",value:X},this._promise)(Y=this._resolve)==null||Y.call(this,X)}reject(X){var Y;if(this.status={type:"rejected",error:X},this._promise)(Y=this._reject)==null||Y.call(this,X)}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function eP(X){return Object.fromEntries([...X.headers])}var{btoa:lh6,atob:dh6}=globalThis;function $B(X){let Y=X.replace(/-/g,"+").replace(/_/g,"/"),Q=dh6(Y);return Uint8Array.from(Q,(J)=>J.codePointAt(0))}function jF(X){let Y="";for(let Q=0;Q<X.length;Q++)Y+=String.fromCodePoint(X[Q]);return lh6(Y)}var kW1="AI_DownloadError",vW1=`vercel.ai.error.${kW1}`,ph6=Symbol.for(vW1),EW1,jW1,fb=class extends(jW1=N1,EW1=ph6,jW1){constructor({url:X,statusCode:Y,statusText:Q,cause:J,message:G=J==null?`Failed to download ${X}: ${Y} ${Q}`:`Failed to download ${X}: ${J}`}){super({name:kW1,message:G,cause:J});this[EW1]=!0,this.url=X,this.statusCode=Y,this.statusText=Q}static isInstance(X){return N1.hasMarker(X,vW1)}};var D7=({prefix:X,size:Y=16,alphabet:Q="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:J="-"}={})=>{let G=()=>{let W=Q.length,Z=Array(Y);for(let $=0;$<Y;$++)Z[$]=Q[Math.random()*W|0];return Z.join("")};if(X==null)return G;if(Q.includes(J))throw new QW1({argument:"separator",message:`The separator "${J}" must not be part of the alphabet "${Q}".`});return()=>`${X}${J}${G()}`},ch6=D7();function KB(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 tW(X){return(X instanceof Error||X instanceof DOMException)&&(X.name==="AbortError"||X.name==="ResponseAborted"||X.name==="TimeoutError")}var nh6=["fetch failed","failed to fetch"];function _W1({error:X,url:Y,requestBodyValues:Q}){if(tW(X))return X;if(X instanceof TypeError&&nh6.includes(X.message.toLowerCase())){let J=X.cause;if(J!=null)return new XX({message:`Cannot connect to API: ${J.message}`,cause:J,url:Y,requestBodyValues:Q,isRetryable:!0})}return X}function hb(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 ih6(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 eW(X,...Y){let Q=new Headers(ih6(X)),J=Q.get("user-agent")||"";return Q.set("user-agent",[J,...Y].filter(Boolean).join(" ")),Object.fromEntries(Q.entries())}var yW1="4.0.9",ah6=()=>globalThis.fetch,VY0=async({url:X,headers:Y={},successfulResponseHandler:Q,failedResponseHandler:J,abortSignal:G,fetch:W=ah6()})=>{try{let Z=await W(X,{method:"GET",headers:eW(Y,`ai-sdk/provider-utils/${yW1}`,hb()),signal:G}),$=eP(Z);if(!Z.ok){let K;try{K=await J({response:Z,url:X,requestBodyValues:{}})}catch(H){if(tW(H)||XX.isInstance(H))throw H;throw new XX({message:"Failed to process error response",cause:H,statusCode:Z.status,url:X,responseHeaders:$,requestBodyValues:{}})}throw K.value}try{return await Q({response:Z,url:X,requestBodyValues:{}})}catch(K){if(K instanceof Error){if(tW(K)||XX.isInstance(K))throw K}throw new XX({message:"Failed to process successful response",cause:K,statusCode:Z.status,url:X,responseHeaders:$,requestBodyValues:{}})}}catch(Z){throw _W1({error:Z,url:X,requestBodyValues:{}})}};function bW1(X){return X!=null}function fW1({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 XA({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}var rh6=/"__proto__"\s*:/,oh6=/"constructor"\s*:/;function CW1(X){let Y=JSON.parse(X);if(Y===null||typeof Y!=="object")return Y;if(rh6.test(X)===!1&&oh6.test(X)===!1)return Y;return sh6(Y)}function sh6(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 hW1(X){let{stackTraceLimit:Y}=Error;try{Error.stackTraceLimit=0}catch(Q){return CW1(X)}try{return CW1(X)}finally{Error.stackTraceLimit=Y}}function qY0(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]=AF(Q[J])}if(X.items!=null)X.items=Array.isArray(X.items)?X.items.map(AF):AF(X.items);if(X.anyOf!=null)X.anyOf=X.anyOf.map(AF);if(X.allOf!=null)X.allOf=X.allOf.map(AF);if(X.oneOf!=null)X.oneOf=X.oneOf.map(AF);let{definitions:Y}=X;if(Y!=null)for(let Q of Object.keys(Y))Y[Q]=AF(Y[Q]);return X}function AF(X){if(typeof X==="boolean")return X;return qY0(X)}var th6=Symbol("Let zodToJsonSchema decide on which parser to use"),IW1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},eh6=(X)=>typeof X==="string"?{...IW1,name:X}:{...IW1,...X};function lQ(){return{}}function Xx6(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)!==j0.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 Yx6(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 Qx6(){return{type:"boolean"}}function xW1(X,Y){return f4(X.type._def,Y)}var Jx6=(X,Y)=>{return f4(X.innerType._def,Y)};function gW1(X,Y,Q){let J=Q!=null?Q:Y.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((G,W)=>gW1(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 Gx6(X)}}var Gx6=(X)=>{let Y={type:"integer",format:"unix-time"};for(let Q of X.checks)switch(Q.kind){case"min":Y.minimum=Q.value;break;case"max":Y.maximum=Q.value;break}return Y};function Wx6(X,Y){return{...f4(X.innerType._def,Y),default:X.defaultValue()}}function Zx6(X,Y){return Y.effectStrategy==="input"?f4(X.schema._def,Y):lQ()}function $x6(X){return{type:"string",enum:Array.from(X.values)}}var Kx6=(X)=>{if("type"in X&&X.type==="string")return!1;return"allOf"in X};function Hx6(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(Kx6(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 Fx6(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}}var $Y0=void 0,u5={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if($Y0===void 0)$Y0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return $Y0},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function uW1(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":m5(Q,"email",J.message,Y);break;case"format:idn-email":m5(Q,"idn-email",J.message,Y);break;case"pattern:zod":T9(Q,u5.email,J.message,Y);break}break;case"url":m5(Q,"uri",J.message,Y);break;case"uuid":m5(Q,"uuid",J.message,Y);break;case"regex":T9(Q,J.regex,J.message,Y);break;case"cuid":T9(Q,u5.cuid,J.message,Y);break;case"cuid2":T9(Q,u5.cuid2,J.message,Y);break;case"startsWith":T9(Q,RegExp(`^${KY0(J.value,Y)}`),J.message,Y);break;case"endsWith":T9(Q,RegExp(`${KY0(J.value,Y)}$`),J.message,Y);break;case"datetime":m5(Q,"date-time",J.message,Y);break;case"date":m5(Q,"date",J.message,Y);break;case"time":m5(Q,"time",J.message,Y);break;case"duration":m5(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":{T9(Q,RegExp(KY0(J.value,Y)),J.message,Y);break}case"ip":{if(J.version!=="v6")m5(Q,"ipv4",J.message,Y);if(J.version!=="v4")m5(Q,"ipv6",J.message,Y);break}case"base64url":T9(Q,u5.base64url,J.message,Y);break;case"jwt":T9(Q,u5.jwt,J.message,Y);break;case"cidr":{if(J.version!=="v6")T9(Q,u5.ipv4Cidr,J.message,Y);if(J.version!=="v4")T9(Q,u5.ipv6Cidr,J.message,Y);break}case"emoji":T9(Q,u5.emoji(),J.message,Y);break;case"ulid":{T9(Q,u5.ulid,J.message,Y);break}case"base64":{switch(Y.base64Strategy){case"format:binary":{m5(Q,"binary",J.message,Y);break}case"contentEncoding:base64":{Q.contentEncoding="base64";break}case"pattern:zod":{T9(Q,u5.base64,J.message,Y);break}}break}case"nanoid":T9(Q,u5.nanoid,J.message,Y);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Q}function KY0(X,Y){return Y.patternStrategy==="escape"?qx6(X):X}var Vx6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function qx6(X){let Y="";for(let Q=0;Q<X.length;Q++){if(!Vx6.has(X[Q]))Y+="\\";Y+=X[Q]}return Y}function m5(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 T9(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:RW1(Y,J),...Q&&J.errorMessages&&{errorMessage:{pattern:Q}}})}else X.pattern=RW1(Y,J)}function RW1(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
|
|
1054
1054
|
]))`;continue}else if(G[H]==="$"){W+=`($|(?=[\r
|