@interactive-inc/claude-funnel 0.22.0 → 0.22.1

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/bin.js CHANGED
@@ -904,7 +904,7 @@ Since you have not provided a token or authorize, you might be missing one or mo
904
904
  * Copyright(c) 2013 Roman Shtylman
905
905
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
906
906
  * MIT Licensed
907
- */var ap=Yxq(),X9K=gA("events").EventEmitter,IMq=Xxq(),PMq=JOq(),NMq=F4A(),_Mq=cOq(),wMq=OMq();ZG=BMq.exports=G9K;function G9K(){var A=function(q,K,F){A.handle(q,K,F)};return IMq(A,X9K.prototype,!1),IMq(A,PMq,!1),A.request=Object.create(_Mq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.response=Object.create(wMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.init(),A}ZG.application=PMq;ZG.request=_Mq;ZG.response=wMq;ZG.Route=NMq.Route;ZG.Router=NMq;ZG.json=ap.json;ZG.raw=ap.raw;ZG.static=zMq();ZG.text=ap.text;ZG.urlencoded=ap.urlencoded});var yMq=I((b$)=>{var j9K=b$&&b$.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),J9K=b$&&b$.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),SMq=b$&&b$.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))j9K(q,A,K)}return J9K(q,A),q},dp=b$&&b$.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(b$,"__esModule",{value:!0});b$.buildBodyParserMiddleware=b$.verifySignatureAndParseBody=b$.verifySignatureAndParseRawBody=b$.respondToUrlVerification=b$.respondToSslCheck=void 0;var H9K=dp(gA("crypto")),E9K=gA("http"),W9K=gA("https"),g9K=dp(gA("querystring")),RMq=gY(),V9K=FR(),TMq=SMq(DMq()),L9K=dp(Qp()),x9K=dp(Xp()),Z7=xY(),nz=SMq(JR()),O9K=jp(),M9K=Hp(),z9K=["ALPNProtocols","clientCertEngine","enableTrace","handshakeTimeout","rejectUnauthorized","requestCert","sessionTimeout","SNICallback","ticketKeys","pskCallback","pskIdentityHint","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext"],z4A="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",I9K=(A,q,K)=>{if(A.body?.ssl_check){q.send();return}K()};b$.respondToSslCheck=I9K;var P9K=(A,q,K)=>{if(A.body?.type&&A.body.type==="url_verification"){q.json({challenge:A.body.challenge});return}K()};b$.respondToUrlVerification=P9K;class bMq{app;server;bolt;logger;processBeforeResponse;signatureVerification;router;installer=void 0;installerOptions;customPropertiesExtractor;dispatchErrorHandler;processEventErrorHandler;unhandledRequestHandler;unhandledRequestTimeoutMillis;constructor({signingSecret:A="",logger:q=void 0,logLevel:K=RMq.LogLevel.INFO,endpoints:F={events:"/slack/events"},processBeforeResponse:Z=!1,signatureVerification:$=!0,clientId:U=void 0,clientSecret:Y=void 0,stateSecret:X=void 0,redirectUri:j=void 0,installationStore:J=void 0,scopes:E=void 0,installerOptions:W={},app:g=void 0,router:L=void 0,customPropertiesExtractor:M=(v)=>({}),dispatchErrorHandler:O=nz.defaultAsyncDispatchErrorHandler,processEventErrorHandler:_=nz.defaultProcessEventErrorHandler,unhandledRequestHandler:R=nz.defaultUnhandledRequestHandler,unhandledRequestTimeoutMillis:T=3001}){if(this.app=g!==void 0?g:(0,TMq.default)(),typeof q<"u")this.logger=q;else this.logger=new RMq.ConsoleLogger,this.logger.setLevel(K);this.signatureVerification=$;let y=[this.signatureVerification?vMq(this.logger,A):CMq(this.logger),b$.respondToSslCheck,b$.respondToUrlVerification,this.requestHandler.bind(this)];this.processBeforeResponse=Z;let i=typeof F==="string"?[F]:Object.values(F);this.router=L!==void 0?L:(0,TMq.Router)();for(let n of i)this.router.post(n,...y);if(this.customPropertiesExtractor=M,this.dispatchErrorHandler=O,this.processEventErrorHandler=_,this.unhandledRequestHandler=R,this.unhandledRequestTimeoutMillis=T,(0,M9K.verifyRedirectOpts)({redirectUri:j,redirectUriPath:W.redirectUriPath}),U!==void 0&&Y!==void 0&&(W.stateVerification===!1||X!==void 0||W.stateStore!==void 0))this.installer=new V9K.InstallProvider({clientId:U,clientSecret:Y,stateSecret:X,installationStore:J,logLevel:K,logger:q,directInstall:W.directInstall,stateStore:W.stateStore,stateVerification:W.stateVerification,legacyStateVerification:W.legacyStateVerification,stateCookieName:W.stateCookieName,stateCookieExpirationSeconds:W.stateCookieExpirationSeconds,renderHtmlForInstallPath:W.renderHtmlForInstallPath,authVersion:W.authVersion??"v2",clientOptions:W.clientOptions,authorizationUrl:W.authorizationUrl});let l={metadata:W.metadata,scopes:E??[],userScopes:W.userScopes,redirectUri:j};if(this.installer!==void 0){let{installer:n}=this,a=W.redirectUriPath===void 0?"/slack/oauth_redirect":W.redirectUriPath,{callbackOptions:qA,stateVerification:JA}=W;this.router.use(a,async(sA,_A)=>{try{if(JA===!1)await n.handleCallback(sA,_A,qA,l);else await n.handleCallback(sA,_A,qA)}catch(zA){await this.dispatchErrorHandler({error:zA,logger:this.logger,request:sA,response:_A})}});let VA=W.installPath===void 0?"/slack/install":W.installPath,{installPathOptions:mA}=W;this.router.get(VA,async(sA,_A,zA)=>{try{try{await n.handleInstallPath(sA,_A,mA,l)}catch(e){zA(e)}}catch(e){await this.dispatchErrorHandler({error:e,logger:this.logger,request:sA,response:_A})}})}this.app.use(this.router)}async requestHandler(A,q){let K=new O9K.HTTPResponseAck({logger:this.logger,processBeforeResponse:this.processBeforeResponse,unhandledRequestHandler:this.unhandledRequestHandler,unhandledRequestTimeoutMillis:this.unhandledRequestTimeoutMillis,httpRequest:A,httpRequestBody:A.body,httpResponse:q}),F={body:A.body,ack:K.bind(),retryNum:nz.extractRetryNumFromHTTPRequest(A),retryReason:nz.extractRetryReasonFromHTTPRequest(A),customProperties:this.customPropertiesExtractor(A)};try{if(await this.bolt?.processEvent(F),K.storedResponse!==void 0)nz.buildContentResponse(q,K.storedResponse),this.logger.debug("stored response sent")}catch(Z){if(await this.processEventErrorHandler({error:Z,logger:this.logger,request:A,response:q,storedResponse:K.storedResponse}))K.ack()}}init(A){this.bolt=A}start(A,q={}){let K=E9K.createServer;if(Object.keys(q).filter((F)=>z9K.includes(F)).length>0)K=W9K.createServer;if(this.server!==void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be started because it was already started."));return this.server=K(q,this.app),new Promise((F,Z)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.on("error",($)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.close(),Z($)}),this.server.on("close",()=>{this.server=void 0}),this.server.listen(A,()=>{if(this.server===void 0)return Z(new Z7.ReceiverInconsistentStateError(z4A));return F(this.server)})})}stop(){if(this.server===void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be stopped because it was not started."));return new Promise((A,q)=>{this.server?.close((K)=>{if(K!==void 0)return q(K);return this.server=void 0,A()})})}}b$.default=bMq;function N9K(A,q){return vMq(A,q)}b$.verifySignatureAndParseRawBody=N9K;function vMq(A,q){return async(K,F,Z)=>{let $=await hMq(K);try{K.body=kMq(typeof q==="string"?q:await q(),$,K.headers)}catch(U){if(U){if(U instanceof Z7.ReceiverAuthenticityError){I4A(A,"Request verification failed",U),F.status(401).send();return}I4A(A,"Parsing request body failed",U),F.status(400).send();return}}Z()}}function I4A(A,q,K){let F="code"in K?`${q} (code: ${K.code}, message: ${K.message})`:`${q} (error: ${K})`;A.warn(F)}function _9K(A,q,K,F){if(K===void 0||F===void 0)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Some headers are missing.");let Z=Number(F);if(Number.isNaN(Z))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is invalid.");let $=Math.floor(Date.now()/1000)-300;if(Z<$)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is too old.");let U=H9K.default.createHmac("sha256",A),[Y,X]=K.split("=");if(U.update(`${Y}:${Z}:${q}`),!(0,x9K.default)(X,U.digest("hex")))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function kMq(A,q,K){let{"x-slack-signature":F,"x-slack-request-timestamp":Z,"content-type":$}=K;return _9K(A,q,F,Z),fMq(q,$)}b$.verifySignatureAndParseBody=kMq;function CMq(A){return async(q,K,F)=>{let Z=await hMq(q);try{let{"content-type":$}=q.headers;q.body=fMq(Z,$)}catch($){if($){I4A(A,"Parsing request body failed",$),K.status(400).send();return}}F()}}b$.buildBodyParserMiddleware=CMq;function fMq(A,q){if(q==="application/x-www-form-urlencoded"){let K=g9K.default.parse(A);if(typeof K.payload==="string")return JSON.parse(K.payload);return K}return JSON.parse(A)}async function hMq(A){if("rawBody"in A&&A.rawBody)return Promise.resolve(A.rawBody.toString());return(await(0,L9K.default)(A)).toString()}});var lMq=I((mMq)=>{Object.defineProperty(mMq,"__esModule",{value:!0});mMq.DefaultThreadContextStore=void 0;var uMq=P4A();class cMq{context={};async get(A){let{context:q,client:K,payload:F,logger:Z}=A;if(Z.debug("DefaultAssistantThreadStore: get method called"),this.context.channel_id)return this.context;let{channelId:$,threadTs:U}=(0,uMq.extractThreadInfo)(F),Y=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!Y.messages)return{};let X=Y.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);return(X?.metadata?X.metadata.event_payload:null)||{}}async save(A){let{context:q,client:K,payload:F,logger:Z}=A,{channelId:$,threadTs:U,context:Y}=(0,uMq.extractThreadInfo)(F);Z.debug("DefaultAssistantThreadStore: save method called");let X=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!X.messages)return;let j=X.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);if(j?.ts){let J={channel:$,ts:j.ts,text:j.text,blocks:j.blocks?j.blocks:[],metadata:{event_type:"assistant_thread_context",event_payload:Y}};await K.chat.update(J)}this.context=Y}}mMq.DefaultThreadContextStore=cMq});var P4A=I((l9)=>{var w9K=l9&&l9.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(l9,"__esModule",{value:!0});l9.extractThreadInfo=l9.processAssistantMiddleware=l9.validate=l9.isAssistantMessage=l9.matchesConstraints=l9.isAssistantEvent=l9.enrichAssistantArgs=l9.Assistant=void 0;var B9K=lMq(),iMq=T8A(),SL=xY(),np=rc(),D9K=w9K(tc()),R9K=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class aMq{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor(A){rMq(A);let{threadContextStore:q=new B9K.DefaultThreadContextStore,threadStarted:K,threadContextChanged:F=($)=>q.save($),userMessage:Z}=A;this.threadContextStore=q,this.threadStarted=Array.isArray(K)?K:[K],this.threadContextChanged=Array.isArray(F)?F:[F],this.userMessage=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(nMq(A)&&sMq(A))return this.processEvent(A);return A.next()}}async processEvent(A){let{payload:q}=A,K=dMq(this.threadContextStore,A),F=this.getAssistantMiddleware(q);return tMq(K,F)}getAssistantMiddleware(A){switch(A.type){case"assistant_thread_started":return this.threadStarted;case"assistant_thread_context_changed":return this.threadContextChanged;case"message":return this.userMessage;default:return[]}}}l9.Assistant=aMq;function dMq(A,q){let{next:K,...F}=q,Z={...F};return Z.getThreadContext=()=>A.get(q),Z.saveThreadContext=()=>A.save(q),Z.say=T9K(Z),Z.sayStream=S9K(Z),Z.setStatus=b9K(Z),Z.setSuggestedPrompts=v9K(Z),Z.setTitle=k9K(Z),Z}l9.enrichAssistantArgs=dMq;function nMq(A){return R9K.has(A.payload.type)}l9.isAssistantEvent=nMq;function sMq(A){return A.payload.type==="message"?oMq(A.payload):!0}l9.matchesConstraints=sMq;function oMq(A){let q="channel"in A&&"thread_ts"in A,K="channel_type"in A&&A.channel_type==="im"&&(!("subtype"in A)||A.subtype==="file_share"||A.subtype===void 0);return q&&K}l9.isAssistantMessage=oMq;function rMq(A){if(typeof A!=="object")throw new SL.AssistantInitializationError("Assistant expects a configuration object as the argument");let q=["threadStarted","userMessage"],K=[];for(let Z of q)if(A[Z]===void 0)K.push(Z);if(K.length>0){let Z=`Assistant is missing required keys: ${K.join(", ")}`;throw new SL.AssistantInitializationError(Z)}let F=["threadStarted","userMessage"];if("threadContextChanged"in A)F.push("threadContextChanged");for(let Z of F)if(typeof A[Z]!=="function"&&!Array.isArray(A[Z])){let $=`Assistant ${Z} property must be a function or an array of functions`;throw new SL.AssistantInitializationError($)}if(A.threadContextStore){if(typeof A.threadContextStore!=="object")throw new SL.AssistantInitializationError("Assistant expects threadContextStore to be a configuration object");let Z=["get","save"],$=[];for(let Y of Z)if(A.threadContextStore&&A.threadContextStore[Y]===void 0)$.push(Y);if($.length>0){let Y=`threadContextStore is missing required keys: ${$.join(", ")}`;throw new SL.AssistantInitializationError(Y)}let U=["get","save"];for(let Y of U)if(A.threadContextStore&&typeof A.threadContextStore[Y]!=="function"){let X=`threadContextStore ${Y} property must be a function`;throw new SL.AssistantInitializationError(X)}}}l9.validate=rMq;async function tMq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,D9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}l9.processAssistantMiddleware=tMq;function T9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z,context:$}=sz(K);return async(U)=>{let Y=$.channel_id?$:await A.getThreadContext(),X=typeof U==="string"?{text:U,channel:F,thread_ts:Z}:{...U,channel:F,thread_ts:Z};if(Y||X.metadata)X.metadata={event_type:X.metadata?.event_type??"assistant_thread_context",event_payload:{...Y,...X.metadata?.event_payload??{}}};return q.chat.postMessage(X)}}function S9K(A){let{client:q,context:K,payload:F}=A,{channelId:Z,threadTs:$}=sz(F);return(0,iMq.createSayStream)(q,K,Z,$)}function b9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return(0,iMq.createSetStatus)(q,F,Z)}function v9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>{let{prompts:U,title:Y}=$;return q.assistant.threads.setSuggestedPrompts({channel_id:F,thread_ts:Z,prompts:U,title:Y})}}function k9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>q.assistant.threads.setTitle({channel_id:F,thread_ts:Z,title:$})}function sz(A){let q={};if("assistant_thread"in A&&(0,np.isRecord)(A.assistant_thread)){if((0,np.isRecord)(A.assistant_thread.context))q=A.assistant_thread.context}let K=(0,np.extractEventChannelId)(A),F=(0,np.extractEventThreadTs)(A);if(!K||!F){let Z=[];if(!K)Z.push("channel_id");if(!F)Z.push("thread_ts");throw new SL.AssistantMissingPropertyError(`Assistant message event is missing required properties: ${Z.join(", ")}`)}return{channelId:K,threadTs:F,context:q}}l9.extractThreadInfo=sz});var Zzq=I((F8)=>{var C9K=F8&&F8.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(F8,"__esModule",{value:!0});F8.prepareStepArgs=F8.isStepEvent=F8.processStepMiddleware=F8.validate=F8.WorkflowStep=void 0;var sp=xY(),f9K=C9K(tc()),h9K=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class eMq{callbackId;edit;save;execute;constructor(A,q){Azq(A,q);let{save:K,edit:F,execute:Z}=q;this.callbackId=A,this.save=Array.isArray(K)?K:[K],this.edit=Array.isArray(F)?F:[F],this.execute=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(Kzq(A)&&this.matchesConstraints(A))return this.processEvent(A);return A.next()}}matchesConstraints(A){return A.payload.callback_id===this.callbackId}async processEvent(A){let{payload:q}=A,K=Fzq(A),F=this.getStepMiddleware(q);return qzq(K,F)}getStepMiddleware(A){switch(A.type){case"workflow_step_edit":return this.edit;case"workflow_step":return this.save;case"workflow_step_execute":return this.execute;default:return[]}}}F8.WorkflowStep=eMq;function Azq(A,q){if(typeof A!=="string")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof q!=="object")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a configuration object as the second argument");let K=["save","edit","execute"],F=[];for(let $ of K)if(q[$]===void 0)F.push($);if(F.length>0){let $=`WorkflowStep is missing required keys: ${F.join(", ")}`;throw new sp.WorkflowStepInitializationError($)}let Z=["save","edit","execute"];for(let $ of Z)if(typeof q[$]!=="function"&&!Array.isArray(q[$])){let U=`WorkflowStep ${$} property must be a function or an array of functions`;throw new sp.WorkflowStepInitializationError(U)}}F8.validate=Azq;async function qzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,f9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}F8.processStepMiddleware=qzq;function Kzq(A){return h9K.has(A.payload.type)}F8.isStepEvent=Kzq;function op(A){return A.botToken!==void 0?A.botToken:A.userToken}function y9K(A){let{context:q,client:K,body:{callback_id:F,trigger_id:Z}}=A,$=op(q);return(U)=>K.views.open({token:$,trigger_id:Z,view:{callback_id:F,type:"workflow_step",...U}})}function u9K(A){let{context:q,client:K,body:{workflow_step:{workflow_step_edit_id:F}}}=A,Z=op(q);return($={})=>K.workflows.updateStep({token:Z,workflow_step_edit_id:F,...$})}function c9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($={})=>K.workflows.stepCompleted({token:Z,workflow_step_execute_id:F,...$})}function m9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($)=>{let{error:U}=$;return K.workflows.stepFailed({token:Z,workflow_step_execute_id:F,error:U})}}function Fzq(A){let{next:q,...K}=A,F={...K};switch(F.payload.type){case"workflow_step_edit":F.step=F.action.workflow_step,F.configure=y9K(F);break;case"workflow_step":F.step=F.body.workflow_step,F.update=u9K(F);break;case"workflow_step_execute":F.step=F.event.workflow_step,F.complete=c9K(F),F.fail=m9K(F);break;default:break}return F}F8.prepareStepArgs=Fzq});var Xzq=I((WK)=>{var $zq=WK&&WK.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),p9K=WK&&WK.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),N4A=WK&&WK.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))$zq(q,A,K)}return p9K(q,A),q},_4A=WK&&WK.__exportStar||function(A,q){for(var K in A)if(K!=="default"&&!Object.prototype.hasOwnProperty.call(q,K))$zq(q,A,K)},fR=WK&&WK.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(WK,"__esModule",{value:!0});WK.webApi=WK.types=WK.FileInstallationStore=WK.MemoryInstallationStore=WK.WorkflowStep=WK.Assistant=WK.buildReceiverRoutes=WK.MemoryStore=WK.defaultProcessEventErrorHandler=WK.HTTPResponseAck=WK.HTTPModuleFunctions=WK.AwsLambdaReceiver=WK.HTTPReceiver=WK.SocketModeReceiver=WK.ExpressReceiver=WK.isValidSlackRequest=WK.verifySlackRequest=WK.App=WK.LogLevel=void 0;var Uzq=fR(gjA());WK.App=Uzq.default;var l9K=gjA();Object.defineProperty(WK,"LogLevel",{enumerable:!0,get:function(){return l9K.LogLevel}});WK.default=Uzq.default;var Yzq=KjA();Object.defineProperty(WK,"verifySlackRequest",{enumerable:!0,get:function(){return Yzq.verifySlackRequest}});Object.defineProperty(WK,"isValidSlackRequest",{enumerable:!0,get:function(){return Yzq.isValidSlackRequest}});var i9K=fR(DLq());WK.AwsLambdaReceiver=i9K.default;var a9K=fR(yMq());WK.ExpressReceiver=a9K.default;var d9K=fR(ZjA());WK.HTTPReceiver=d9K.default;var n9K=fR(GjA());WK.SocketModeReceiver=n9K.default;WK.HTTPModuleFunctions=N4A(JR());var s9K=jp();Object.defineProperty(WK,"HTTPResponseAck",{enumerable:!0,get:function(){return s9K.HTTPResponseAck}});var o9K=XjA();Object.defineProperty(WK,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return o9K.defaultProcessEventErrorHandler}});_4A(xY(),WK);_4A(oc(),WK);_4A(JjA(),WK);var r9K=S8A();Object.defineProperty(WK,"MemoryStore",{enumerable:!0,get:function(){return r9K.MemoryStore}});var t9K=Jp();Object.defineProperty(WK,"buildReceiverRoutes",{enumerable:!0,get:function(){return t9K.buildReceiverRoutes}});var e9K=P4A();Object.defineProperty(WK,"Assistant",{enumerable:!0,get:function(){return e9K.Assistant}});var AUK=Zzq();Object.defineProperty(WK,"WorkflowStep",{enumerable:!0,get:function(){return AUK.WorkflowStep}});var Qzq=FR();Object.defineProperty(WK,"MemoryInstallationStore",{enumerable:!0,get:function(){return Qzq.MemoryInstallationStore}});Object.defineProperty(WK,"FileInstallationStore",{enumerable:!0,get:function(){return Qzq.FileInstallationStore}});WK.types=N4A(O8A());WK.webApi=N4A(sc())});var f7A={name:"@interactive-inc/claude-funnel",version:"0.21.1",description:"Hub CLI that routes external events (Slack / GitHub / Discord) to Claude Code agents through subscription channels over MCP.",keywords:["bun","claude","claude-code","cli","discord","github","mcp","slack"],homepage:"https://github.com/interactive-inc/open-claude-funnel#readme",bugs:{url:"https://github.com/interactive-inc/open-claude-funnel/issues"},license:"MIT",author:"Interactive Inc.",repository:{type:"git",url:"git+https://github.com/interactive-inc/open-claude-funnel.git"},bin:{fnl:"./dist/bin.js",funnel:"./dist/bin.js"},files:["dist/**/*","funnel.schema.json","README.md","LICENSE"],type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./connectors/slack":{types:"./dist/connectors/slack.d.ts",import:"./dist/connectors/slack.js",default:"./dist/connectors/slack.js"},"./connectors/discord":{types:"./dist/connectors/discord.d.ts",import:"./dist/connectors/discord.js",default:"./dist/connectors/discord.js"},"./connectors/gh":{types:"./dist/connectors/gh.d.ts",import:"./dist/connectors/gh.js",default:"./dist/connectors/gh.js"},"./connectors/schedule":{types:"./dist/connectors/schedule.d.ts",import:"./dist/connectors/schedule.js",default:"./dist/connectors/schedule.js"},"./bin":"./dist/bin.js","./package.json":"./package.json"},publishConfig:{access:"public"},dependencies:{"@hono/zod-validator":"^0.8.0","@modelcontextprotocol/sdk":"^1.29.0","@opentui/core":"^0.2.12","@opentui/react":"^0.2.12","@slack/bolt":"^4.7.2","@slack/web-api":"^7.16.0","discord.js":"^14.26.4",hono:"^4.12.19",react:"^19.2.6",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@types/react":"^19.2.14","@typescript/native-preview":"^7.0.0-dev.20260516.1","vite-plus":"^0.1.21",vitest:"^4.1.6"},engines:{bun:">=1.3.0"}};var pK=class extends Error{res;status;constructor(A=500,q){super(q?.message,{cause:q?.cause});this.res=q?.res,this.status=A}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var c={};iG(c,{xor:()=>WHA,xid:()=>hJA,void:()=>XHA,uuidv7:()=>RJA,uuidv6:()=>DJA,uuidv4:()=>BJA,uuid:()=>wJA,util:()=>oq,url:()=>TJA,uppercase:()=>Yx,unknown:()=>g5,union:()=>fb,undefined:()=>YHA,ulid:()=>fJA,uint64:()=>$HA,uint32:()=>KHA,tuple:()=>fo,trim:()=>Hx,treeifyError:()=>wi,transform:()=>yb,toUpperCase:()=>Wx,toLowerCase:()=>Ex,toJSONSchema:()=>Gb,templateLiteral:()=>DHA,symbol:()=>UHA,superRefine:()=>Jr,success:()=>NHA,stringbool:()=>fHA,stringFormat:()=>sJA,string:()=>nP,strictObject:()=>HHA,startsWith:()=>Xx,slugify:()=>gx,size:()=>H5,setErrorMap:()=>DNq,set:()=>OHA,safeParseAsync:()=>jo,safeParse:()=>Go,safeEncodeAsync:()=>Lo,safeEncode:()=>go,safeDecodeAsync:()=>xo,safeDecode:()=>Vo,registry:()=>kS,regexes:()=>O8,regex:()=>$x,refine:()=>jr,record:()=>ho,readonly:()=>$r,property:()=>Ub,promise:()=>RHA,prettifyError:()=>Bi,preprocess:()=>yHA,prefault:()=>ro,positive:()=>Kb,pipe:()=>Vb,partialRecord:()=>VHA,parseAsync:()=>Xo,parse:()=>Qo,overwrite:()=>aG,optional:()=>oP,object:()=>JHA,number:()=>Mo,nullish:()=>PHA,nullable:()=>rP,null:()=>_o,normalize:()=>Jx,nonpositive:()=>Zb,nonoptional:()=>to,nonnegative:()=>$b,never:()=>Cb,negative:()=>Fb,nativeEnum:()=>MHA,nanoid:()=>vJA,nan:()=>_HA,multipleOf:()=>xE,minSize:()=>x4,minLength:()=>$J,mime:()=>jx,meta:()=>kHA,maxSize:()=>OE,maxLength:()=>E5,map:()=>xHA,mac:()=>cJA,lte:()=>M8,lt:()=>V4,lowercase:()=>Ux,looseRecord:()=>LHA,looseObject:()=>EHA,locales:()=>lP,literal:()=>zHA,length:()=>W5,lazy:()=>Qr,ksuid:()=>yJA,keyof:()=>jHA,jwt:()=>nJA,json:()=>hHA,iso:()=>xx,ipv6:()=>mJA,ipv4:()=>uJA,invertCodec:()=>BHA,intersection:()=>ko,int64:()=>ZHA,int32:()=>qHA,int:()=>gb,instanceof:()=>CHA,includes:()=>Qx,httpUrl:()=>SJA,hostname:()=>oJA,hex:()=>rJA,hash:()=>tJA,guid:()=>_JA,gte:()=>DQ,gt:()=>L4,globalRegistry:()=>rU,getErrorMap:()=>RNq,function:()=>THA,fromJSONSchema:()=>cHA,formatError:()=>bP,float64:()=>AHA,float32:()=>eJA,flattenError:()=>SP,file:()=>IHA,exactOptional:()=>io,enum:()=>hb,endsWith:()=>Gx,encodeAsync:()=>Eo,encode:()=>Jo,emoji:()=>bJA,email:()=>NJA,e164:()=>dJA,discriminatedUnion:()=>gHA,describe:()=>vHA,decodeAsync:()=>Wo,decode:()=>Ho,date:()=>GHA,custom:()=>bHA,cuid2:()=>CJA,cuid:()=>kJA,core:()=>UJ,config:()=>d$,coerce:()=>Er,codec:()=>wHA,clone:()=>wQ,cidrv6:()=>lJA,cidrv4:()=>pJA,check:()=>SHA,catch:()=>qr,boolean:()=>zo,bigint:()=>FHA,base64url:()=>aJA,base64:()=>iJA,array:()=>qN,any:()=>QHA,_function:()=>THA,_default:()=>so,_ZodString:()=>Lb,ZodXor:()=>So,ZodXID:()=>Nb,ZodVoid:()=>Ro,ZodUnknown:()=>Bo,ZodUnion:()=>FN,ZodUndefined:()=>Po,ZodUUID:()=>O4,ZodURL:()=>eP,ZodULID:()=>Pb,ZodType:()=>ZF,ZodTuple:()=>Co,ZodTransform:()=>po,ZodTemplateLiteral:()=>Ur,ZodSymbol:()=>Io,ZodSuccess:()=>eo,ZodStringFormat:()=>o1,ZodString:()=>zx,ZodSet:()=>uo,ZodRecord:()=>Ox,ZodRealError:()=>_0,ZodReadonly:()=>Zr,ZodPromise:()=>Xr,ZodPreprocess:()=>Fr,ZodPrefault:()=>oo,ZodPipe:()=>ZN,ZodOptional:()=>ub,ZodObject:()=>KN,ZodNumberFormat:()=>V5,ZodNumber:()=>Px,ZodNullable:()=>ao,ZodNull:()=>No,ZodNonOptional:()=>cb,ZodNever:()=>Do,ZodNanoID:()=>Mb,ZodNaN:()=>Kr,ZodMap:()=>yo,ZodMAC:()=>Oo,ZodLiteral:()=>co,ZodLazy:()=>Yr,ZodKSUID:()=>_b,ZodJWT:()=>vb,ZodIssueCode:()=>BNq,ZodIntersection:()=>vo,ZodISOTime:()=>Eb,ZodISODuration:()=>Wb,ZodISODateTime:()=>Jb,ZodISODate:()=>Hb,ZodIPv6:()=>Bb,ZodIPv4:()=>wb,ZodGUID:()=>sP,ZodFunction:()=>Gr,ZodFirstPartyTypeKind:()=>Hr,ZodFile:()=>mo,ZodExactOptional:()=>lo,ZodError:()=>_Nq,ZodEnum:()=>Mx,ZodEmoji:()=>Ob,ZodEmail:()=>xb,ZodE164:()=>bb,ZodDiscriminatedUnion:()=>bo,ZodDefault:()=>no,ZodDate:()=>AN,ZodCustomStringFormat:()=>Ix,ZodCustom:()=>UN,ZodCodec:()=>$N,ZodCatch:()=>Ar,ZodCUID2:()=>Ib,ZodCUID:()=>zb,ZodCIDRv6:()=>Rb,ZodCIDRv4:()=>Db,ZodBoolean:()=>Nx,ZodBigIntFormat:()=>kb,ZodBigInt:()=>_x,ZodBase64URL:()=>Sb,ZodBase64:()=>Tb,ZodArray:()=>To,ZodAny:()=>wo,TimePrecision:()=>Cn,NEVER:()=>Wi,$output:()=>Rn,$input:()=>Tn,$brand:()=>gi});var UJ={};iG(UJ,{version:()=>Pa,util:()=>oq,treeifyError:()=>wi,toJSONSchema:()=>Gb,toDotPath:()=>l7A,safeParseAsync:()=>Ri,safeParse:()=>Di,safeEncodeAsync:()=>BIq,safeEncode:()=>_Iq,safeDecodeAsync:()=>DIq,safeDecode:()=>wIq,registry:()=>kS,regexes:()=>O8,process:()=>D1,prettifyError:()=>Bi,parseAsync:()=>HS,parse:()=>JS,meta:()=>Vs,locales:()=>lP,isValidJWT:()=>JJA,isValidBase64URL:()=>jJA,isValidBase64:()=>aa,initializeContext:()=>ME,globalRegistry:()=>rU,globalConfig:()=>Q5,formatError:()=>bP,flattenError:()=>SP,finalize:()=>IE,extractDefs:()=>zE,encodeAsync:()=>PIq,encode:()=>zIq,describe:()=>gs,decodeAsync:()=>NIq,decode:()=>IIq,createToJSONSchemaMethod:()=>xs,createStandardJSONSchemaMethod:()=>Lx,config:()=>d$,clone:()=>wQ,_xor:()=>KNq,_xid:()=>aS,_void:()=>Ys,_uuidv7:()=>uS,_uuidv6:()=>yS,_uuidv4:()=>hS,_uuid:()=>fS,_url:()=>aP,_uppercase:()=>Yx,_unknown:()=>$s,_union:()=>qNq,_undefined:()=>Ks,_ulid:()=>iS,_uint64:()=>As,_uint32:()=>nn,_tuple:()=>$Nq,_trim:()=>Hx,_transform:()=>JNq,_toUpperCase:()=>Wx,_toLowerCase:()=>Ex,_templateLiteral:()=>MNq,_symbol:()=>qs,_superRefine:()=>Ws,_success:()=>VNq,_stringbool:()=>Ls,_stringFormat:()=>Vx,_string:()=>bn,_startsWith:()=>Xx,_slugify:()=>gx,_size:()=>H5,_set:()=>QNq,_safeParseAsync:()=>Kx,_safeParse:()=>qx,_safeEncodeAsync:()=>OS,_safeEncode:()=>LS,_safeDecodeAsync:()=>MS,_safeDecode:()=>xS,_regex:()=>$x,_refine:()=>Es,_record:()=>UNq,_readonly:()=>ONq,_property:()=>Ub,_promise:()=>INq,_positive:()=>Kb,_pipe:()=>xNq,_parseAsync:()=>Ax,_parse:()=>e2,_overwrite:()=>aG,_optional:()=>HNq,_number:()=>cn,_nullable:()=>ENq,_null:()=>Fs,_normalize:()=>Jx,_nonpositive:()=>Zb,_nonoptional:()=>gNq,_nonnegative:()=>$b,_never:()=>Us,_negative:()=>Fb,_nativeEnum:()=>GNq,_nanoid:()=>mS,_nan:()=>Gs,_multipleOf:()=>xE,_minSize:()=>x4,_minLength:()=>$J,_min:()=>DQ,_mime:()=>jx,_maxSize:()=>OE,_maxLength:()=>E5,_max:()=>M8,_map:()=>YNq,_mac:()=>kn,_lte:()=>M8,_lt:()=>V4,_lowercase:()=>Ux,_literal:()=>jNq,_length:()=>W5,_lazy:()=>zNq,_ksuid:()=>dS,_jwt:()=>qb,_isoTime:()=>yn,_isoDuration:()=>un,_isoDateTime:()=>fn,_isoDate:()=>hn,_ipv6:()=>sS,_ipv4:()=>nS,_intersection:()=>ZNq,_int64:()=>en,_int32:()=>dn,_int:()=>pn,_includes:()=>Qx,_guid:()=>iP,_gte:()=>DQ,_gt:()=>L4,_float64:()=>an,_float32:()=>ln,_file:()=>Js,_enum:()=>XNq,_endsWith:()=>Gx,_encodeAsync:()=>gS,_encode:()=>ES,_emoji:()=>cS,_email:()=>CS,_e164:()=>Ab,_discriminatedUnion:()=>FNq,_default:()=>WNq,_decodeAsync:()=>VS,_decode:()=>WS,_date:()=>Qs,_custom:()=>Hs,_cuid2:()=>lS,_cuid:()=>pS,_coercedString:()=>vn,_coercedNumber:()=>mn,_coercedDate:()=>Xs,_coercedBoolean:()=>on,_coercedBigint:()=>tn,_cidrv6:()=>rS,_cidrv4:()=>oS,_check:()=>MJA,_catch:()=>LNq,_boolean:()=>sn,_bigint:()=>rn,_base64url:()=>eS,_base64:()=>tS,_array:()=>js,_any:()=>Zs,TimePrecision:()=>Cn,NEVER:()=>Wi,JSONSchemaGenerator:()=>Fo,JSONSchema:()=>zJA,Doc:()=>NS,$output:()=>Rn,$input:()=>Tn,$constructor:()=>nA,$brand:()=>gi,$ZodXor:()=>Gd,$ZodXID:()=>ka,$ZodVoid:()=>Ud,$ZodUnknown:()=>Zd,$ZodUnion:()=>hP,$ZodUndefined:()=>qd,$ZodUUID:()=>wa,$ZodURL:()=>Da,$ZodULID:()=>va,$ZodType:()=>yK,$ZodTuple:()=>SS,$ZodTransform:()=>xd,$ZodTemplateLiteral:()=>Rd,$ZodSymbol:()=>Ad,$ZodSuccess:()=>Nd,$ZodStringFormat:()=>s1,$ZodString:()=>J5,$ZodSet:()=>Wd,$ZodRegistry:()=>Sn,$ZodRecord:()=>Hd,$ZodRealError:()=>N0,$ZodReadonly:()=>Dd,$ZodPromise:()=>Sd,$ZodPreprocess:()=>Bd,$ZodPrefault:()=>Id,$ZodPipe:()=>vS,$ZodOptional:()=>bS,$ZodObjectJIT:()=>Xd,$ZodObject:()=>WJA,$ZodNumberFormat:()=>ta,$ZodNumber:()=>RS,$ZodNullable:()=>Md,$ZodNull:()=>Kd,$ZodNonOptional:()=>Pd,$ZodNever:()=>$d,$ZodNanoID:()=>Ta,$ZodNaN:()=>wd,$ZodMap:()=>Ed,$ZodMAC:()=>pa,$ZodLiteral:()=>Vd,$ZodLazy:()=>bd,$ZodKSUID:()=>Ca,$ZodJWT:()=>oa,$ZodIntersection:()=>Jd,$ZodISOTime:()=>ya,$ZodISODuration:()=>ua,$ZodISODateTime:()=>fa,$ZodISODate:()=>ha,$ZodIPv6:()=>ma,$ZodIPv4:()=>ca,$ZodGUID:()=>_a,$ZodFunction:()=>Td,$ZodFile:()=>Ld,$ZodExactOptional:()=>Od,$ZodError:()=>TP,$ZodEnum:()=>gd,$ZodEncodeError:()=>X5,$ZodEmoji:()=>Ra,$ZodEmail:()=>Ba,$ZodE164:()=>sa,$ZodDiscriminatedUnion:()=>jd,$ZodDefault:()=>zd,$ZodDate:()=>Yd,$ZodCustomStringFormat:()=>ra,$ZodCustom:()=>vd,$ZodCodec:()=>yP,$ZodCheckUpperCase:()=>Va,$ZodCheckStringFormat:()=>Fx,$ZodCheckStartsWith:()=>xa,$ZodCheckSizeEquals:()=>ja,$ZodCheckRegex:()=>Wa,$ZodCheckProperty:()=>Ma,$ZodCheckOverwrite:()=>Ia,$ZodCheckNumberFormat:()=>Ya,$ZodCheckMultipleOf:()=>Ua,$ZodCheckMinSize:()=>Ga,$ZodCheckMinLength:()=>Ha,$ZodCheckMimeType:()=>za,$ZodCheckMaxSize:()=>Xa,$ZodCheckMaxLength:()=>Ja,$ZodCheckLowerCase:()=>ga,$ZodCheckLessThan:()=>IS,$ZodCheckLengthEquals:()=>Ea,$ZodCheckIncludes:()=>La,$ZodCheckGreaterThan:()=>PS,$ZodCheckEndsWith:()=>Oa,$ZodCheckBigIntFormat:()=>Qa,$ZodCheck:()=>XZ,$ZodCatch:()=>_d,$ZodCUID2:()=>ba,$ZodCUID:()=>Sa,$ZodCIDRv6:()=>ia,$ZodCIDRv4:()=>la,$ZodBoolean:()=>fP,$ZodBigIntFormat:()=>ea,$ZodBigInt:()=>TS,$ZodBase64URL:()=>na,$ZodBase64:()=>da,$ZodAsyncError:()=>g4,$ZodArray:()=>Qd,$ZodAny:()=>Fd});var h7A,Wi=Object.freeze({status:"aborted"});function nA(A,q,K){function F(Y,X){if(!Y._zod)Object.defineProperty(Y,"_zod",{value:{def:X,constr:U,traits:new Set},enumerable:!1});if(Y._zod.traits.has(A))return;Y._zod.traits.add(A),q(Y,X);let j=U.prototype,J=Object.keys(j);for(let E=0;E<J.length;E++){let W=J[E];if(!(W in Y))Y[W]=j[W].bind(Y)}}let Z=K?.Parent??Object;class $ extends Z{}Object.defineProperty($,"name",{value:A});function U(Y){var X;let j=K?.Parent?new $:this;F(j,Y),(X=j._zod).deferred??(X.deferred=[]);for(let J of j._zod.deferred)J();return j}return Object.defineProperty(U,"init",{value:F}),Object.defineProperty(U,Symbol.hasInstance,{value:(Y)=>{if(K?.Parent&&Y instanceof K.Parent)return!0;return Y?._zod?.traits?.has(A)}}),Object.defineProperty(U,"name",{value:A}),U}var gi=Symbol("zod_brand");class g4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class X5 extends Error{constructor(A){super(`Encountered unidirectional transform during encode: ${A}`);this.name="ZodEncodeError"}}(h7A=globalThis).__zod_globalConfig??(h7A.__zod_globalConfig={});var Q5=globalThis.__zod_globalConfig;function d$(A){if(A)Object.assign(Q5,A);return Q5}var oq={};iG(oq,{unwrapMessage:()=>NP,uint8ArrayToHex:()=>OIq,uint8ArrayToBase64url:()=>LIq,uint8ArrayToBase64:()=>c7A,stringifyPrimitive:()=>pq,slugify:()=>xi,shallowClone:()=>Mi,safeExtend:()=>JIq,required:()=>WIq,randomString:()=>$Iq,propertyKeyTypes:()=>BP,promiseAllObject:()=>ZIq,primitiveTypes:()=>zi,prefixIssues:()=>P0,pick:()=>XIq,partial:()=>EIq,parsedType:()=>nq,optionalKeys:()=>Ii,omit:()=>GIq,objectClone:()=>qIq,numKeys:()=>UIq,nullish:()=>WE,normalizeParams:()=>A6,mergeDefs:()=>ZJ,merge:()=>HIq,jsonStringifyReplacer:()=>o2,joinValues:()=>Qq,issue:()=>t2,isPlainObject:()=>VE,isObject:()=>G5,hexToUint8Array:()=>xIq,getSizableOrigin:()=>DP,getParsedType:()=>YIq,getLengthableOrigin:()=>RP,getEnumValues:()=>_P,getElementAtPath:()=>FIq,floatSafeRemainder:()=>Li,finalizeIssue:()=>BQ,extend:()=>jIq,explicitlyAborted:()=>_i,escapeRegex:()=>PX,esc:()=>GS,defineLazy:()=>NF,createTransparentProxy:()=>QIq,cloneDef:()=>KIq,clone:()=>wQ,cleanRegex:()=>wP,cleanEnum:()=>gIq,captureStackTrace:()=>jS,cached:()=>r2,base64urlToUint8Array:()=>VIq,base64ToUint8Array:()=>u7A,assignProp:()=>gE,assertNotEqual:()=>rzq,assertNever:()=>ezq,assertIs:()=>tzq,assertEqual:()=>ozq,assert:()=>AIq,allowsEval:()=>Oi,aborted:()=>LE,NUMBER_FORMAT_RANGES:()=>Pi,Class:()=>m7A,BIGINT_FORMAT_RANGES:()=>Ni});function ozq(A){return A}function rzq(A){return A}function tzq(A){}function ezq(A){throw Error("Unexpected value in exhaustive check")}function AIq(A){}function _P(A){let q=Object.values(A).filter((F)=>typeof F==="number");return Object.entries(A).filter(([F,Z])=>q.indexOf(+F)===-1).map(([F,Z])=>Z)}function Qq(A,q="|"){return A.map((K)=>pq(K)).join(q)}function o2(A,q){if(typeof q==="bigint")return q.toString();return q}function r2(A){return{get value(){{let K=A();return Object.defineProperty(this,"value",{value:K}),K}throw Error("cached value already set")}}}function WE(A){return A===null||A===void 0}function wP(A){let q=A.startsWith("^")?1:0,K=A.endsWith("$")?A.length-1:A.length;return A.slice(q,K)}function Li(A,q){let K=A/q,F=Math.round(K),Z=Number.EPSILON*Math.max(Math.abs(K),1);if(Math.abs(K-F)<Z)return 0;return K-F}var y7A=Symbol("evaluating");function NF(A,q,K){let F=void 0;Object.defineProperty(A,q,{get(){if(F===y7A)return;if(F===void 0)F=y7A,F=K();return F},set(Z){Object.defineProperty(A,q,{value:Z})},configurable:!0})}function qIq(A){return Object.create(Object.getPrototypeOf(A),Object.getOwnPropertyDescriptors(A))}function gE(A,q,K){Object.defineProperty(A,q,{value:K,writable:!0,enumerable:!0,configurable:!0})}function ZJ(...A){let q={};for(let K of A){let F=Object.getOwnPropertyDescriptors(K);Object.assign(q,F)}return Object.defineProperties({},q)}function KIq(A){return ZJ(A._zod.def)}function FIq(A,q){if(!q)return A;return q.reduce((K,F)=>K?.[F],A)}function ZIq(A){let q=Object.keys(A),K=q.map((F)=>A[F]);return Promise.all(K).then((F)=>{let Z={};for(let $=0;$<q.length;$++)Z[q[$]]=F[$];return Z})}function $Iq(A=10){let K="";for(let F=0;F<A;F++)K+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return K}function GS(A){return JSON.stringify(A)}function xi(A){return A.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var jS="captureStackTrace"in Error?Error.captureStackTrace:(...A)=>{};function G5(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var Oi=r2(()=>{if(Q5.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(A){return!1}});function VE(A){if(G5(A)===!1)return!1;let q=A.constructor;if(q===void 0)return!0;if(typeof q!=="function")return!0;let K=q.prototype;if(G5(K)===!1)return!1;if(Object.prototype.hasOwnProperty.call(K,"isPrototypeOf")===!1)return!1;return!0}function Mi(A){if(VE(A))return{...A};if(Array.isArray(A))return[...A];if(A instanceof Map)return new Map(A);if(A instanceof Set)return new Set(A);return A}function UIq(A){let q=0;for(let K in A)if(Object.prototype.hasOwnProperty.call(A,K))q++;return q}var YIq=(A)=>{let q=typeof A;switch(q){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(A)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(A))return"array";if(A===null)return"null";if(A.then&&typeof A.then==="function"&&A.catch&&typeof A.catch==="function")return"promise";if(typeof Map<"u"&&A instanceof Map)return"map";if(typeof Set<"u"&&A instanceof Set)return"set";if(typeof Date<"u"&&A instanceof Date)return"date";if(typeof File<"u"&&A instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${q}`)}},BP=new Set(["string","number","symbol"]),zi=new Set(["string","number","bigint","boolean","symbol","undefined"]);function PX(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wQ(A,q,K){let F=new A._zod.constr(q??A._zod.def);if(!q||K?.parent)F._zod.parent=A;return F}function A6(A){let q=A;if(!q)return{};if(typeof q==="string")return{error:()=>q};if(q?.message!==void 0){if(q?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");q.error=q.message}if(delete q.message,typeof q.error==="string")return{...q,error:()=>q.error};return q}function QIq(A){let q;return new Proxy({},{get(K,F,Z){return q??(q=A()),Reflect.get(q,F,Z)},set(K,F,Z,$){return q??(q=A()),Reflect.set(q,F,Z,$)},has(K,F){return q??(q=A()),Reflect.has(q,F)},deleteProperty(K,F){return q??(q=A()),Reflect.deleteProperty(q,F)},ownKeys(K){return q??(q=A()),Reflect.ownKeys(q)},getOwnPropertyDescriptor(K,F){return q??(q=A()),Reflect.getOwnPropertyDescriptor(q,F)},defineProperty(K,F,Z){return q??(q=A()),Reflect.defineProperty(q,F,Z)}})}function pq(A){if(typeof A==="bigint")return A.toString()+"n";if(typeof A==="string")return`"${A}"`;return`${A}`}function Ii(A){return Object.keys(A).filter((q)=>{return A[q]._zod.optin==="optional"&&A[q]._zod.optout==="optional"})}var Pi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ni={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function XIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;U[Y]=K.shape[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function GIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={...A._zod.def.shape};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;delete U[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function jIq(A,q){if(!VE(q))throw Error("Invalid input to extend: expected a plain object");let K=A._zod.def.checks;if(K&&K.length>0){let $=A._zod.def.shape;for(let U in q)if(Object.getOwnPropertyDescriptor($,U)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let Z=ZJ(A._zod.def,{get shape(){let $={...A._zod.def.shape,...q};return gE(this,"shape",$),$}});return wQ(A,Z)}function JIq(A,q){if(!VE(q))throw Error("Invalid input to safeExtend: expected a plain object");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q};return gE(this,"shape",F),F}});return wQ(A,K)}function HIq(A,q){if(A._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q._zod.def.shape};return gE(this,"shape",F),F},get catchall(){return q._zod.def.catchall},checks:q._zod.def.checks??[]});return wQ(A,K)}function EIq(A,q,K){let Z=q._zod.def.checks;if(Z&&Z.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let U=ZJ(q._zod.def,{get shape(){let Y=q._zod.def.shape,X={...Y};if(K)for(let j in K){if(!(j in Y))throw Error(`Unrecognized key: "${j}"`);if(!K[j])continue;X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j]}else for(let j in Y)X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j];return gE(this,"shape",X),X},checks:[]});return wQ(q,U)}function WIq(A,q,K){let F=ZJ(q._zod.def,{get shape(){let Z=q._zod.def.shape,$={...Z};if(K)for(let U in K){if(!(U in $))throw Error(`Unrecognized key: "${U}"`);if(!K[U])continue;$[U]=new A({type:"nonoptional",innerType:Z[U]})}else for(let U in Z)$[U]=new A({type:"nonoptional",innerType:Z[U]});return gE(this,"shape",$),$}});return wQ(q,F)}function LE(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue!==!0)return!0;return!1}function _i(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue===!1)return!0;return!1}function P0(A,q){return q.map((K)=>{var F;return(F=K).path??(F.path=[]),K.path.unshift(A),K})}function NP(A){return typeof A==="string"?A:A?.message}function BQ(A,q,K){let F=A.message?A.message:NP(A.inst?._zod.def?.error?.(A))??NP(q?.error?.(A))??NP(K.customError?.(A))??NP(K.localeError?.(A))??"Invalid input",{inst:Z,continue:$,input:U,...Y}=A;if(Y.path??(Y.path=[]),Y.message=F,q?.reportInput)Y.input=U;return Y}function DP(A){if(A instanceof Set)return"set";if(A instanceof Map)return"map";if(A instanceof File)return"file";return"unknown"}function RP(A){if(Array.isArray(A))return"array";if(typeof A==="string")return"string";return"unknown"}function nq(A){let q=typeof A;switch(q){case"number":return Number.isNaN(A)?"nan":"number";case"object":{if(A===null)return"null";if(Array.isArray(A))return"array";let K=A;if(K&&Object.getPrototypeOf(K)!==Object.prototype&&"constructor"in K&&K.constructor)return K.constructor.name}}return q}function t2(...A){let[q,K,F]=A;if(typeof q==="string")return{message:q,code:"custom",input:K,inst:F};return{...q}}function gIq(A){return Object.entries(A).filter(([q,K])=>{return Number.isNaN(Number.parseInt(q,10))}).map((q)=>q[1])}function u7A(A){let q=atob(A),K=new Uint8Array(q.length);for(let F=0;F<q.length;F++)K[F]=q.charCodeAt(F);return K}function c7A(A){let q="";for(let K=0;K<A.length;K++)q+=String.fromCharCode(A[K]);return btoa(q)}function VIq(A){let q=A.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-q.length%4)%4);return u7A(q+K)}function LIq(A){return c7A(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xIq(A){let q=A.replace(/^0x/,"");if(q.length%2!==0)throw Error("Invalid hex string length");let K=new Uint8Array(q.length/2);for(let F=0;F<q.length;F+=2)K[F/2]=Number.parseInt(q.slice(F,F+2),16);return K}function OIq(A){return Array.from(A).map((q)=>q.toString(16).padStart(2,"0")).join("")}class m7A{constructor(...A){}}var p7A=(A,q)=>{A.name="$ZodError",Object.defineProperty(A,"_zod",{value:A._zod,enumerable:!1}),Object.defineProperty(A,"issues",{value:q,enumerable:!1}),A.message=JSON.stringify(q,o2,2),Object.defineProperty(A,"toString",{value:()=>A.message,enumerable:!1})},TP=nA("$ZodError",p7A),N0=nA("$ZodError",p7A,{Parent:Error});function SP(A,q=(K)=>K.message){let K={},F=[];for(let Z of A.issues)if(Z.path.length>0)K[Z.path[0]]=K[Z.path[0]]||[],K[Z.path[0]].push(q(Z));else F.push(q(Z));return{formErrors:F,fieldErrors:K}}function bP(A,q=(K)=>K.message){let K={_errors:[]},F=(Z,$=[])=>{for(let U of Z.issues)if(U.code==="invalid_union"&&U.errors.length)U.errors.map((Y)=>F({issues:Y},[...$,...U.path]));else if(U.code==="invalid_key")F({issues:U.issues},[...$,...U.path]);else if(U.code==="invalid_element")F({issues:U.issues},[...$,...U.path]);else{let Y=[...$,...U.path];if(Y.length===0)K._errors.push(q(U));else{let X=K,j=0;while(j<Y.length){let J=Y[j];if(j!==Y.length-1)X[J]=X[J]||{_errors:[]};else X[J]=X[J]||{_errors:[]},X[J]._errors.push(q(U));X=X[J],j++}}}};return F(A),K}function wi(A,q=(K)=>K.message){let K={errors:[]},F=(Z,$=[])=>{var U,Y;for(let X of Z.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((j)=>F({issues:j},[...$,...X.path]));else if(X.code==="invalid_key")F({issues:X.issues},[...$,...X.path]);else if(X.code==="invalid_element")F({issues:X.issues},[...$,...X.path]);else{let j=[...$,...X.path];if(j.length===0){K.errors.push(q(X));continue}let J=K,E=0;while(E<j.length){let W=j[E],g=E===j.length-1;if(typeof W==="string")J.properties??(J.properties={}),(U=J.properties)[W]??(U[W]={errors:[]}),J=J.properties[W];else J.items??(J.items=[]),(Y=J.items)[W]??(Y[W]={errors:[]}),J=J.items[W];if(g)J.errors.push(q(X));E++}}};return F(A),K}function l7A(A){let q=[],K=A.map((F)=>typeof F==="object"?F.key:F);for(let F of K)if(typeof F==="number")q.push(`[${F}]`);else if(typeof F==="symbol")q.push(`[${JSON.stringify(String(F))}]`);else if(/[^\w$]/.test(F))q.push(`[${JSON.stringify(F)}]`);else{if(q.length)q.push(".");q.push(F)}return q.join("")}function Bi(A){let q=[],K=[...A.issues].sort((F,Z)=>(F.path??[]).length-(Z.path??[]).length);for(let F of K)if(q.push(`\u2716 ${F.message}`),F.path?.length)q.push(` \u2192 at ${l7A(F.path)}`);return q.join(`
907
+ */var ap=Yxq(),X9K=gA("events").EventEmitter,IMq=Xxq(),PMq=JOq(),NMq=F4A(),_Mq=cOq(),wMq=OMq();ZG=BMq.exports=G9K;function G9K(){var A=function(q,K,F){A.handle(q,K,F)};return IMq(A,X9K.prototype,!1),IMq(A,PMq,!1),A.request=Object.create(_Mq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.response=Object.create(wMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.init(),A}ZG.application=PMq;ZG.request=_Mq;ZG.response=wMq;ZG.Route=NMq.Route;ZG.Router=NMq;ZG.json=ap.json;ZG.raw=ap.raw;ZG.static=zMq();ZG.text=ap.text;ZG.urlencoded=ap.urlencoded});var yMq=I((b$)=>{var j9K=b$&&b$.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),J9K=b$&&b$.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),SMq=b$&&b$.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))j9K(q,A,K)}return J9K(q,A),q},dp=b$&&b$.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(b$,"__esModule",{value:!0});b$.buildBodyParserMiddleware=b$.verifySignatureAndParseBody=b$.verifySignatureAndParseRawBody=b$.respondToUrlVerification=b$.respondToSslCheck=void 0;var H9K=dp(gA("crypto")),E9K=gA("http"),W9K=gA("https"),g9K=dp(gA("querystring")),RMq=gY(),V9K=FR(),TMq=SMq(DMq()),L9K=dp(Qp()),x9K=dp(Xp()),Z7=xY(),nz=SMq(JR()),O9K=jp(),M9K=Hp(),z9K=["ALPNProtocols","clientCertEngine","enableTrace","handshakeTimeout","rejectUnauthorized","requestCert","sessionTimeout","SNICallback","ticketKeys","pskCallback","pskIdentityHint","ca","cert","sigalgs","ciphers","clientCertEngine","crl","dhparam","ecdhCurve","honorCipherOrder","key","privateKeyEngine","privateKeyIdentifier","maxVersion","minVersion","passphrase","pfx","secureOptions","secureProtocol","sessionIdContext"],z4A="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",I9K=(A,q,K)=>{if(A.body?.ssl_check){q.send();return}K()};b$.respondToSslCheck=I9K;var P9K=(A,q,K)=>{if(A.body?.type&&A.body.type==="url_verification"){q.json({challenge:A.body.challenge});return}K()};b$.respondToUrlVerification=P9K;class bMq{app;server;bolt;logger;processBeforeResponse;signatureVerification;router;installer=void 0;installerOptions;customPropertiesExtractor;dispatchErrorHandler;processEventErrorHandler;unhandledRequestHandler;unhandledRequestTimeoutMillis;constructor({signingSecret:A="",logger:q=void 0,logLevel:K=RMq.LogLevel.INFO,endpoints:F={events:"/slack/events"},processBeforeResponse:Z=!1,signatureVerification:$=!0,clientId:U=void 0,clientSecret:Y=void 0,stateSecret:X=void 0,redirectUri:j=void 0,installationStore:J=void 0,scopes:E=void 0,installerOptions:W={},app:g=void 0,router:L=void 0,customPropertiesExtractor:M=(v)=>({}),dispatchErrorHandler:O=nz.defaultAsyncDispatchErrorHandler,processEventErrorHandler:_=nz.defaultProcessEventErrorHandler,unhandledRequestHandler:R=nz.defaultUnhandledRequestHandler,unhandledRequestTimeoutMillis:T=3001}){if(this.app=g!==void 0?g:(0,TMq.default)(),typeof q<"u")this.logger=q;else this.logger=new RMq.ConsoleLogger,this.logger.setLevel(K);this.signatureVerification=$;let y=[this.signatureVerification?vMq(this.logger,A):CMq(this.logger),b$.respondToSslCheck,b$.respondToUrlVerification,this.requestHandler.bind(this)];this.processBeforeResponse=Z;let i=typeof F==="string"?[F]:Object.values(F);this.router=L!==void 0?L:(0,TMq.Router)();for(let n of i)this.router.post(n,...y);if(this.customPropertiesExtractor=M,this.dispatchErrorHandler=O,this.processEventErrorHandler=_,this.unhandledRequestHandler=R,this.unhandledRequestTimeoutMillis=T,(0,M9K.verifyRedirectOpts)({redirectUri:j,redirectUriPath:W.redirectUriPath}),U!==void 0&&Y!==void 0&&(W.stateVerification===!1||X!==void 0||W.stateStore!==void 0))this.installer=new V9K.InstallProvider({clientId:U,clientSecret:Y,stateSecret:X,installationStore:J,logLevel:K,logger:q,directInstall:W.directInstall,stateStore:W.stateStore,stateVerification:W.stateVerification,legacyStateVerification:W.legacyStateVerification,stateCookieName:W.stateCookieName,stateCookieExpirationSeconds:W.stateCookieExpirationSeconds,renderHtmlForInstallPath:W.renderHtmlForInstallPath,authVersion:W.authVersion??"v2",clientOptions:W.clientOptions,authorizationUrl:W.authorizationUrl});let l={metadata:W.metadata,scopes:E??[],userScopes:W.userScopes,redirectUri:j};if(this.installer!==void 0){let{installer:n}=this,a=W.redirectUriPath===void 0?"/slack/oauth_redirect":W.redirectUriPath,{callbackOptions:qA,stateVerification:JA}=W;this.router.use(a,async(sA,_A)=>{try{if(JA===!1)await n.handleCallback(sA,_A,qA,l);else await n.handleCallback(sA,_A,qA)}catch(zA){await this.dispatchErrorHandler({error:zA,logger:this.logger,request:sA,response:_A})}});let VA=W.installPath===void 0?"/slack/install":W.installPath,{installPathOptions:mA}=W;this.router.get(VA,async(sA,_A,zA)=>{try{try{await n.handleInstallPath(sA,_A,mA,l)}catch(e){zA(e)}}catch(e){await this.dispatchErrorHandler({error:e,logger:this.logger,request:sA,response:_A})}})}this.app.use(this.router)}async requestHandler(A,q){let K=new O9K.HTTPResponseAck({logger:this.logger,processBeforeResponse:this.processBeforeResponse,unhandledRequestHandler:this.unhandledRequestHandler,unhandledRequestTimeoutMillis:this.unhandledRequestTimeoutMillis,httpRequest:A,httpRequestBody:A.body,httpResponse:q}),F={body:A.body,ack:K.bind(),retryNum:nz.extractRetryNumFromHTTPRequest(A),retryReason:nz.extractRetryReasonFromHTTPRequest(A),customProperties:this.customPropertiesExtractor(A)};try{if(await this.bolt?.processEvent(F),K.storedResponse!==void 0)nz.buildContentResponse(q,K.storedResponse),this.logger.debug("stored response sent")}catch(Z){if(await this.processEventErrorHandler({error:Z,logger:this.logger,request:A,response:q,storedResponse:K.storedResponse}))K.ack()}}init(A){this.bolt=A}start(A,q={}){let K=E9K.createServer;if(Object.keys(q).filter((F)=>z9K.includes(F)).length>0)K=W9K.createServer;if(this.server!==void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be started because it was already started."));return this.server=K(q,this.app),new Promise((F,Z)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.on("error",($)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(z4A);this.server.close(),Z($)}),this.server.on("close",()=>{this.server=void 0}),this.server.listen(A,()=>{if(this.server===void 0)return Z(new Z7.ReceiverInconsistentStateError(z4A));return F(this.server)})})}stop(){if(this.server===void 0)return Promise.reject(new Z7.ReceiverInconsistentStateError("The receiver cannot be stopped because it was not started."));return new Promise((A,q)=>{this.server?.close((K)=>{if(K!==void 0)return q(K);return this.server=void 0,A()})})}}b$.default=bMq;function N9K(A,q){return vMq(A,q)}b$.verifySignatureAndParseRawBody=N9K;function vMq(A,q){return async(K,F,Z)=>{let $=await hMq(K);try{K.body=kMq(typeof q==="string"?q:await q(),$,K.headers)}catch(U){if(U){if(U instanceof Z7.ReceiverAuthenticityError){I4A(A,"Request verification failed",U),F.status(401).send();return}I4A(A,"Parsing request body failed",U),F.status(400).send();return}}Z()}}function I4A(A,q,K){let F="code"in K?`${q} (code: ${K.code}, message: ${K.message})`:`${q} (error: ${K})`;A.warn(F)}function _9K(A,q,K,F){if(K===void 0||F===void 0)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Some headers are missing.");let Z=Number(F);if(Number.isNaN(Z))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is invalid.");let $=Math.floor(Date.now()/1000)-300;if(Z<$)throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is too old.");let U=H9K.default.createHmac("sha256",A),[Y,X]=K.split("=");if(U.update(`${Y}:${Z}:${q}`),!(0,x9K.default)(X,U.digest("hex")))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function kMq(A,q,K){let{"x-slack-signature":F,"x-slack-request-timestamp":Z,"content-type":$}=K;return _9K(A,q,F,Z),fMq(q,$)}b$.verifySignatureAndParseBody=kMq;function CMq(A){return async(q,K,F)=>{let Z=await hMq(q);try{let{"content-type":$}=q.headers;q.body=fMq(Z,$)}catch($){if($){I4A(A,"Parsing request body failed",$),K.status(400).send();return}}F()}}b$.buildBodyParserMiddleware=CMq;function fMq(A,q){if(q==="application/x-www-form-urlencoded"){let K=g9K.default.parse(A);if(typeof K.payload==="string")return JSON.parse(K.payload);return K}return JSON.parse(A)}async function hMq(A){if("rawBody"in A&&A.rawBody)return Promise.resolve(A.rawBody.toString());return(await(0,L9K.default)(A)).toString()}});var lMq=I((mMq)=>{Object.defineProperty(mMq,"__esModule",{value:!0});mMq.DefaultThreadContextStore=void 0;var uMq=P4A();class cMq{context={};async get(A){let{context:q,client:K,payload:F,logger:Z}=A;if(Z.debug("DefaultAssistantThreadStore: get method called"),this.context.channel_id)return this.context;let{channelId:$,threadTs:U}=(0,uMq.extractThreadInfo)(F),Y=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!Y.messages)return{};let X=Y.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);return(X?.metadata?X.metadata.event_payload:null)||{}}async save(A){let{context:q,client:K,payload:F,logger:Z}=A,{channelId:$,threadTs:U,context:Y}=(0,uMq.extractThreadInfo)(F);Z.debug("DefaultAssistantThreadStore: save method called");let X=await K.conversations.replies({channel:$,ts:U,oldest:U,include_all_metadata:!0,limit:4});if(!X.messages)return;let j=X.messages.find((J)=>!("subtype"in J)&&J.user===q.botUserId);if(j?.ts){let J={channel:$,ts:j.ts,text:j.text,blocks:j.blocks?j.blocks:[],metadata:{event_type:"assistant_thread_context",event_payload:Y}};await K.chat.update(J)}this.context=Y}}mMq.DefaultThreadContextStore=cMq});var P4A=I((l9)=>{var w9K=l9&&l9.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(l9,"__esModule",{value:!0});l9.extractThreadInfo=l9.processAssistantMiddleware=l9.validate=l9.isAssistantMessage=l9.matchesConstraints=l9.isAssistantEvent=l9.enrichAssistantArgs=l9.Assistant=void 0;var B9K=lMq(),iMq=T8A(),SL=xY(),np=rc(),D9K=w9K(tc()),R9K=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class aMq{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor(A){rMq(A);let{threadContextStore:q=new B9K.DefaultThreadContextStore,threadStarted:K,threadContextChanged:F=($)=>q.save($),userMessage:Z}=A;this.threadContextStore=q,this.threadStarted=Array.isArray(K)?K:[K],this.threadContextChanged=Array.isArray(F)?F:[F],this.userMessage=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(nMq(A)&&sMq(A))return this.processEvent(A);return A.next()}}async processEvent(A){let{payload:q}=A,K=dMq(this.threadContextStore,A),F=this.getAssistantMiddleware(q);return tMq(K,F)}getAssistantMiddleware(A){switch(A.type){case"assistant_thread_started":return this.threadStarted;case"assistant_thread_context_changed":return this.threadContextChanged;case"message":return this.userMessage;default:return[]}}}l9.Assistant=aMq;function dMq(A,q){let{next:K,...F}=q,Z={...F};return Z.getThreadContext=()=>A.get(q),Z.saveThreadContext=()=>A.save(q),Z.say=T9K(Z),Z.sayStream=S9K(Z),Z.setStatus=b9K(Z),Z.setSuggestedPrompts=v9K(Z),Z.setTitle=k9K(Z),Z}l9.enrichAssistantArgs=dMq;function nMq(A){return R9K.has(A.payload.type)}l9.isAssistantEvent=nMq;function sMq(A){return A.payload.type==="message"?oMq(A.payload):!0}l9.matchesConstraints=sMq;function oMq(A){let q="channel"in A&&"thread_ts"in A,K="channel_type"in A&&A.channel_type==="im"&&(!("subtype"in A)||A.subtype==="file_share"||A.subtype===void 0);return q&&K}l9.isAssistantMessage=oMq;function rMq(A){if(typeof A!=="object")throw new SL.AssistantInitializationError("Assistant expects a configuration object as the argument");let q=["threadStarted","userMessage"],K=[];for(let Z of q)if(A[Z]===void 0)K.push(Z);if(K.length>0){let Z=`Assistant is missing required keys: ${K.join(", ")}`;throw new SL.AssistantInitializationError(Z)}let F=["threadStarted","userMessage"];if("threadContextChanged"in A)F.push("threadContextChanged");for(let Z of F)if(typeof A[Z]!=="function"&&!Array.isArray(A[Z])){let $=`Assistant ${Z} property must be a function or an array of functions`;throw new SL.AssistantInitializationError($)}if(A.threadContextStore){if(typeof A.threadContextStore!=="object")throw new SL.AssistantInitializationError("Assistant expects threadContextStore to be a configuration object");let Z=["get","save"],$=[];for(let Y of Z)if(A.threadContextStore&&A.threadContextStore[Y]===void 0)$.push(Y);if($.length>0){let Y=`threadContextStore is missing required keys: ${$.join(", ")}`;throw new SL.AssistantInitializationError(Y)}let U=["get","save"];for(let Y of U)if(A.threadContextStore&&typeof A.threadContextStore[Y]!=="function"){let X=`threadContextStore ${Y} property must be a function`;throw new SL.AssistantInitializationError(X)}}}l9.validate=rMq;async function tMq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,D9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}l9.processAssistantMiddleware=tMq;function T9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z,context:$}=sz(K);return async(U)=>{let Y=$.channel_id?$:await A.getThreadContext(),X=typeof U==="string"?{text:U,channel:F,thread_ts:Z}:{...U,channel:F,thread_ts:Z};if(Y||X.metadata)X.metadata={event_type:X.metadata?.event_type??"assistant_thread_context",event_payload:{...Y,...X.metadata?.event_payload??{}}};return q.chat.postMessage(X)}}function S9K(A){let{client:q,context:K,payload:F}=A,{channelId:Z,threadTs:$}=sz(F);return(0,iMq.createSayStream)(q,K,Z,$)}function b9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return(0,iMq.createSetStatus)(q,F,Z)}function v9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>{let{prompts:U,title:Y}=$;return q.assistant.threads.setSuggestedPrompts({channel_id:F,thread_ts:Z,prompts:U,title:Y})}}function k9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return($)=>q.assistant.threads.setTitle({channel_id:F,thread_ts:Z,title:$})}function sz(A){let q={};if("assistant_thread"in A&&(0,np.isRecord)(A.assistant_thread)){if((0,np.isRecord)(A.assistant_thread.context))q=A.assistant_thread.context}let K=(0,np.extractEventChannelId)(A),F=(0,np.extractEventThreadTs)(A);if(!K||!F){let Z=[];if(!K)Z.push("channel_id");if(!F)Z.push("thread_ts");throw new SL.AssistantMissingPropertyError(`Assistant message event is missing required properties: ${Z.join(", ")}`)}return{channelId:K,threadTs:F,context:q}}l9.extractThreadInfo=sz});var Zzq=I((F8)=>{var C9K=F8&&F8.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(F8,"__esModule",{value:!0});F8.prepareStepArgs=F8.isStepEvent=F8.processStepMiddleware=F8.validate=F8.WorkflowStep=void 0;var sp=xY(),f9K=C9K(tc()),h9K=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class eMq{callbackId;edit;save;execute;constructor(A,q){Azq(A,q);let{save:K,edit:F,execute:Z}=q;this.callbackId=A,this.save=Array.isArray(K)?K:[K],this.edit=Array.isArray(F)?F:[F],this.execute=Array.isArray(Z)?Z:[Z]}getMiddleware(){return async(A)=>{if(Kzq(A)&&this.matchesConstraints(A))return this.processEvent(A);return A.next()}}matchesConstraints(A){return A.payload.callback_id===this.callbackId}async processEvent(A){let{payload:q}=A,K=Fzq(A),F=this.getStepMiddleware(q);return qzq(K,F)}getStepMiddleware(A){switch(A.type){case"workflow_step_edit":return this.edit;case"workflow_step":return this.save;case"workflow_step_execute":return this.execute;default:return[]}}}F8.WorkflowStep=eMq;function Azq(A,q){if(typeof A!=="string")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof q!=="object")throw new sp.WorkflowStepInitializationError("WorkflowStep expects a configuration object as the second argument");let K=["save","edit","execute"],F=[];for(let $ of K)if(q[$]===void 0)F.push($);if(F.length>0){let $=`WorkflowStep is missing required keys: ${F.join(", ")}`;throw new sp.WorkflowStepInitializationError($)}let Z=["save","edit","execute"];for(let $ of Z)if(typeof q[$]!=="function"&&!Array.isArray(q[$])){let U=`WorkflowStep ${$} property must be a function or an array of functions`;throw new sp.WorkflowStepInitializationError(U)}}F8.validate=Azq;async function qzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,f9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}F8.processStepMiddleware=qzq;function Kzq(A){return h9K.has(A.payload.type)}F8.isStepEvent=Kzq;function op(A){return A.botToken!==void 0?A.botToken:A.userToken}function y9K(A){let{context:q,client:K,body:{callback_id:F,trigger_id:Z}}=A,$=op(q);return(U)=>K.views.open({token:$,trigger_id:Z,view:{callback_id:F,type:"workflow_step",...U}})}function u9K(A){let{context:q,client:K,body:{workflow_step:{workflow_step_edit_id:F}}}=A,Z=op(q);return($={})=>K.workflows.updateStep({token:Z,workflow_step_edit_id:F,...$})}function c9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($={})=>K.workflows.stepCompleted({token:Z,workflow_step_execute_id:F,...$})}function m9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=op(q);return($)=>{let{error:U}=$;return K.workflows.stepFailed({token:Z,workflow_step_execute_id:F,error:U})}}function Fzq(A){let{next:q,...K}=A,F={...K};switch(F.payload.type){case"workflow_step_edit":F.step=F.action.workflow_step,F.configure=y9K(F);break;case"workflow_step":F.step=F.body.workflow_step,F.update=u9K(F);break;case"workflow_step_execute":F.step=F.event.workflow_step,F.complete=c9K(F),F.fail=m9K(F);break;default:break}return F}F8.prepareStepArgs=Fzq});var Xzq=I((WK)=>{var $zq=WK&&WK.__createBinding||(Object.create?function(A,q,K,F){if(F===void 0)F=K;var Z=Object.getOwnPropertyDescriptor(q,K);if(!Z||("get"in Z?!q.__esModule:Z.writable||Z.configurable))Z={enumerable:!0,get:function(){return q[K]}};Object.defineProperty(A,F,Z)}:function(A,q,K,F){if(F===void 0)F=K;A[F]=q[K]}),p9K=WK&&WK.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),N4A=WK&&WK.__importStar||function(A){if(A&&A.__esModule)return A;var q={};if(A!=null){for(var K in A)if(K!=="default"&&Object.prototype.hasOwnProperty.call(A,K))$zq(q,A,K)}return p9K(q,A),q},_4A=WK&&WK.__exportStar||function(A,q){for(var K in A)if(K!=="default"&&!Object.prototype.hasOwnProperty.call(q,K))$zq(q,A,K)},fR=WK&&WK.__importDefault||function(A){return A&&A.__esModule?A:{default:A}};Object.defineProperty(WK,"__esModule",{value:!0});WK.webApi=WK.types=WK.FileInstallationStore=WK.MemoryInstallationStore=WK.WorkflowStep=WK.Assistant=WK.buildReceiverRoutes=WK.MemoryStore=WK.defaultProcessEventErrorHandler=WK.HTTPResponseAck=WK.HTTPModuleFunctions=WK.AwsLambdaReceiver=WK.HTTPReceiver=WK.SocketModeReceiver=WK.ExpressReceiver=WK.isValidSlackRequest=WK.verifySlackRequest=WK.App=WK.LogLevel=void 0;var Uzq=fR(gjA());WK.App=Uzq.default;var l9K=gjA();Object.defineProperty(WK,"LogLevel",{enumerable:!0,get:function(){return l9K.LogLevel}});WK.default=Uzq.default;var Yzq=KjA();Object.defineProperty(WK,"verifySlackRequest",{enumerable:!0,get:function(){return Yzq.verifySlackRequest}});Object.defineProperty(WK,"isValidSlackRequest",{enumerable:!0,get:function(){return Yzq.isValidSlackRequest}});var i9K=fR(DLq());WK.AwsLambdaReceiver=i9K.default;var a9K=fR(yMq());WK.ExpressReceiver=a9K.default;var d9K=fR(ZjA());WK.HTTPReceiver=d9K.default;var n9K=fR(GjA());WK.SocketModeReceiver=n9K.default;WK.HTTPModuleFunctions=N4A(JR());var s9K=jp();Object.defineProperty(WK,"HTTPResponseAck",{enumerable:!0,get:function(){return s9K.HTTPResponseAck}});var o9K=XjA();Object.defineProperty(WK,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return o9K.defaultProcessEventErrorHandler}});_4A(xY(),WK);_4A(oc(),WK);_4A(JjA(),WK);var r9K=S8A();Object.defineProperty(WK,"MemoryStore",{enumerable:!0,get:function(){return r9K.MemoryStore}});var t9K=Jp();Object.defineProperty(WK,"buildReceiverRoutes",{enumerable:!0,get:function(){return t9K.buildReceiverRoutes}});var e9K=P4A();Object.defineProperty(WK,"Assistant",{enumerable:!0,get:function(){return e9K.Assistant}});var AUK=Zzq();Object.defineProperty(WK,"WorkflowStep",{enumerable:!0,get:function(){return AUK.WorkflowStep}});var Qzq=FR();Object.defineProperty(WK,"MemoryInstallationStore",{enumerable:!0,get:function(){return Qzq.MemoryInstallationStore}});Object.defineProperty(WK,"FileInstallationStore",{enumerable:!0,get:function(){return Qzq.FileInstallationStore}});WK.types=N4A(O8A());WK.webApi=N4A(sc())});var f7A={name:"@interactive-inc/claude-funnel",version:"0.22.1",description:"Hub CLI that routes external events (Slack / GitHub / Discord) to Claude Code agents through subscription channels over MCP.",keywords:["bun","claude","claude-code","cli","discord","github","mcp","slack"],homepage:"https://github.com/interactive-inc/open-claude-funnel#readme",bugs:{url:"https://github.com/interactive-inc/open-claude-funnel/issues"},license:"MIT",author:"Interactive Inc.",repository:{type:"git",url:"git+https://github.com/interactive-inc/open-claude-funnel.git"},bin:{fnl:"./dist/bin.js",funnel:"./dist/bin.js"},files:["dist/**/*","funnel.schema.json","README.md","LICENSE"],type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./connectors/slack":{types:"./dist/connectors/slack.d.ts",import:"./dist/connectors/slack.js",default:"./dist/connectors/slack.js"},"./connectors/discord":{types:"./dist/connectors/discord.d.ts",import:"./dist/connectors/discord.js",default:"./dist/connectors/discord.js"},"./connectors/gh":{types:"./dist/connectors/gh.d.ts",import:"./dist/connectors/gh.js",default:"./dist/connectors/gh.js"},"./connectors/schedule":{types:"./dist/connectors/schedule.d.ts",import:"./dist/connectors/schedule.js",default:"./dist/connectors/schedule.js"},"./bin":"./dist/bin.js","./package.json":"./package.json"},publishConfig:{access:"public"},dependencies:{"@hono/zod-validator":"^0.8.0","@modelcontextprotocol/sdk":"^1.29.0","@opentui/core":"^0.2.12","@opentui/react":"^0.2.12","@slack/bolt":"^4.7.2","@slack/web-api":"^7.16.0","discord.js":"^14.26.4",hono:"^4.12.19",react:"^19.2.6",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@types/react":"^19.2.14","@typescript/native-preview":"^7.0.0-dev.20260516.1","vite-plus":"^0.1.21",vitest:"^4.1.6"},engines:{bun:">=1.3.0"},scripts:{prepack:"make build"}};var pK=class extends Error{res;status;constructor(A=500,q){super(q?.message,{cause:q?.cause});this.res=q?.res,this.status=A}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}};var c={};iG(c,{xor:()=>WHA,xid:()=>hJA,void:()=>XHA,uuidv7:()=>RJA,uuidv6:()=>DJA,uuidv4:()=>BJA,uuid:()=>wJA,util:()=>oq,url:()=>TJA,uppercase:()=>Yx,unknown:()=>g5,union:()=>fb,undefined:()=>YHA,ulid:()=>fJA,uint64:()=>$HA,uint32:()=>KHA,tuple:()=>fo,trim:()=>Hx,treeifyError:()=>wi,transform:()=>yb,toUpperCase:()=>Wx,toLowerCase:()=>Ex,toJSONSchema:()=>Gb,templateLiteral:()=>DHA,symbol:()=>UHA,superRefine:()=>Jr,success:()=>NHA,stringbool:()=>fHA,stringFormat:()=>sJA,string:()=>nP,strictObject:()=>HHA,startsWith:()=>Xx,slugify:()=>gx,size:()=>H5,setErrorMap:()=>DNq,set:()=>OHA,safeParseAsync:()=>jo,safeParse:()=>Go,safeEncodeAsync:()=>Lo,safeEncode:()=>go,safeDecodeAsync:()=>xo,safeDecode:()=>Vo,registry:()=>kS,regexes:()=>O8,regex:()=>$x,refine:()=>jr,record:()=>ho,readonly:()=>$r,property:()=>Ub,promise:()=>RHA,prettifyError:()=>Bi,preprocess:()=>yHA,prefault:()=>ro,positive:()=>Kb,pipe:()=>Vb,partialRecord:()=>VHA,parseAsync:()=>Xo,parse:()=>Qo,overwrite:()=>aG,optional:()=>oP,object:()=>JHA,number:()=>Mo,nullish:()=>PHA,nullable:()=>rP,null:()=>_o,normalize:()=>Jx,nonpositive:()=>Zb,nonoptional:()=>to,nonnegative:()=>$b,never:()=>Cb,negative:()=>Fb,nativeEnum:()=>MHA,nanoid:()=>vJA,nan:()=>_HA,multipleOf:()=>xE,minSize:()=>x4,minLength:()=>$J,mime:()=>jx,meta:()=>kHA,maxSize:()=>OE,maxLength:()=>E5,map:()=>xHA,mac:()=>cJA,lte:()=>M8,lt:()=>V4,lowercase:()=>Ux,looseRecord:()=>LHA,looseObject:()=>EHA,locales:()=>lP,literal:()=>zHA,length:()=>W5,lazy:()=>Qr,ksuid:()=>yJA,keyof:()=>jHA,jwt:()=>nJA,json:()=>hHA,iso:()=>xx,ipv6:()=>mJA,ipv4:()=>uJA,invertCodec:()=>BHA,intersection:()=>ko,int64:()=>ZHA,int32:()=>qHA,int:()=>gb,instanceof:()=>CHA,includes:()=>Qx,httpUrl:()=>SJA,hostname:()=>oJA,hex:()=>rJA,hash:()=>tJA,guid:()=>_JA,gte:()=>DQ,gt:()=>L4,globalRegistry:()=>rU,getErrorMap:()=>RNq,function:()=>THA,fromJSONSchema:()=>cHA,formatError:()=>bP,float64:()=>AHA,float32:()=>eJA,flattenError:()=>SP,file:()=>IHA,exactOptional:()=>io,enum:()=>hb,endsWith:()=>Gx,encodeAsync:()=>Eo,encode:()=>Jo,emoji:()=>bJA,email:()=>NJA,e164:()=>dJA,discriminatedUnion:()=>gHA,describe:()=>vHA,decodeAsync:()=>Wo,decode:()=>Ho,date:()=>GHA,custom:()=>bHA,cuid2:()=>CJA,cuid:()=>kJA,core:()=>UJ,config:()=>d$,coerce:()=>Er,codec:()=>wHA,clone:()=>wQ,cidrv6:()=>lJA,cidrv4:()=>pJA,check:()=>SHA,catch:()=>qr,boolean:()=>zo,bigint:()=>FHA,base64url:()=>aJA,base64:()=>iJA,array:()=>qN,any:()=>QHA,_function:()=>THA,_default:()=>so,_ZodString:()=>Lb,ZodXor:()=>So,ZodXID:()=>Nb,ZodVoid:()=>Ro,ZodUnknown:()=>Bo,ZodUnion:()=>FN,ZodUndefined:()=>Po,ZodUUID:()=>O4,ZodURL:()=>eP,ZodULID:()=>Pb,ZodType:()=>ZF,ZodTuple:()=>Co,ZodTransform:()=>po,ZodTemplateLiteral:()=>Ur,ZodSymbol:()=>Io,ZodSuccess:()=>eo,ZodStringFormat:()=>o1,ZodString:()=>zx,ZodSet:()=>uo,ZodRecord:()=>Ox,ZodRealError:()=>_0,ZodReadonly:()=>Zr,ZodPromise:()=>Xr,ZodPreprocess:()=>Fr,ZodPrefault:()=>oo,ZodPipe:()=>ZN,ZodOptional:()=>ub,ZodObject:()=>KN,ZodNumberFormat:()=>V5,ZodNumber:()=>Px,ZodNullable:()=>ao,ZodNull:()=>No,ZodNonOptional:()=>cb,ZodNever:()=>Do,ZodNanoID:()=>Mb,ZodNaN:()=>Kr,ZodMap:()=>yo,ZodMAC:()=>Oo,ZodLiteral:()=>co,ZodLazy:()=>Yr,ZodKSUID:()=>_b,ZodJWT:()=>vb,ZodIssueCode:()=>BNq,ZodIntersection:()=>vo,ZodISOTime:()=>Eb,ZodISODuration:()=>Wb,ZodISODateTime:()=>Jb,ZodISODate:()=>Hb,ZodIPv6:()=>Bb,ZodIPv4:()=>wb,ZodGUID:()=>sP,ZodFunction:()=>Gr,ZodFirstPartyTypeKind:()=>Hr,ZodFile:()=>mo,ZodExactOptional:()=>lo,ZodError:()=>_Nq,ZodEnum:()=>Mx,ZodEmoji:()=>Ob,ZodEmail:()=>xb,ZodE164:()=>bb,ZodDiscriminatedUnion:()=>bo,ZodDefault:()=>no,ZodDate:()=>AN,ZodCustomStringFormat:()=>Ix,ZodCustom:()=>UN,ZodCodec:()=>$N,ZodCatch:()=>Ar,ZodCUID2:()=>Ib,ZodCUID:()=>zb,ZodCIDRv6:()=>Rb,ZodCIDRv4:()=>Db,ZodBoolean:()=>Nx,ZodBigIntFormat:()=>kb,ZodBigInt:()=>_x,ZodBase64URL:()=>Sb,ZodBase64:()=>Tb,ZodArray:()=>To,ZodAny:()=>wo,TimePrecision:()=>Cn,NEVER:()=>Wi,$output:()=>Rn,$input:()=>Tn,$brand:()=>gi});var UJ={};iG(UJ,{version:()=>Pa,util:()=>oq,treeifyError:()=>wi,toJSONSchema:()=>Gb,toDotPath:()=>l7A,safeParseAsync:()=>Ri,safeParse:()=>Di,safeEncodeAsync:()=>BIq,safeEncode:()=>_Iq,safeDecodeAsync:()=>DIq,safeDecode:()=>wIq,registry:()=>kS,regexes:()=>O8,process:()=>D1,prettifyError:()=>Bi,parseAsync:()=>HS,parse:()=>JS,meta:()=>Vs,locales:()=>lP,isValidJWT:()=>JJA,isValidBase64URL:()=>jJA,isValidBase64:()=>aa,initializeContext:()=>ME,globalRegistry:()=>rU,globalConfig:()=>Q5,formatError:()=>bP,flattenError:()=>SP,finalize:()=>IE,extractDefs:()=>zE,encodeAsync:()=>PIq,encode:()=>zIq,describe:()=>gs,decodeAsync:()=>NIq,decode:()=>IIq,createToJSONSchemaMethod:()=>xs,createStandardJSONSchemaMethod:()=>Lx,config:()=>d$,clone:()=>wQ,_xor:()=>KNq,_xid:()=>aS,_void:()=>Ys,_uuidv7:()=>uS,_uuidv6:()=>yS,_uuidv4:()=>hS,_uuid:()=>fS,_url:()=>aP,_uppercase:()=>Yx,_unknown:()=>$s,_union:()=>qNq,_undefined:()=>Ks,_ulid:()=>iS,_uint64:()=>As,_uint32:()=>nn,_tuple:()=>$Nq,_trim:()=>Hx,_transform:()=>JNq,_toUpperCase:()=>Wx,_toLowerCase:()=>Ex,_templateLiteral:()=>MNq,_symbol:()=>qs,_superRefine:()=>Ws,_success:()=>VNq,_stringbool:()=>Ls,_stringFormat:()=>Vx,_string:()=>bn,_startsWith:()=>Xx,_slugify:()=>gx,_size:()=>H5,_set:()=>QNq,_safeParseAsync:()=>Kx,_safeParse:()=>qx,_safeEncodeAsync:()=>OS,_safeEncode:()=>LS,_safeDecodeAsync:()=>MS,_safeDecode:()=>xS,_regex:()=>$x,_refine:()=>Es,_record:()=>UNq,_readonly:()=>ONq,_property:()=>Ub,_promise:()=>INq,_positive:()=>Kb,_pipe:()=>xNq,_parseAsync:()=>Ax,_parse:()=>e2,_overwrite:()=>aG,_optional:()=>HNq,_number:()=>cn,_nullable:()=>ENq,_null:()=>Fs,_normalize:()=>Jx,_nonpositive:()=>Zb,_nonoptional:()=>gNq,_nonnegative:()=>$b,_never:()=>Us,_negative:()=>Fb,_nativeEnum:()=>GNq,_nanoid:()=>mS,_nan:()=>Gs,_multipleOf:()=>xE,_minSize:()=>x4,_minLength:()=>$J,_min:()=>DQ,_mime:()=>jx,_maxSize:()=>OE,_maxLength:()=>E5,_max:()=>M8,_map:()=>YNq,_mac:()=>kn,_lte:()=>M8,_lt:()=>V4,_lowercase:()=>Ux,_literal:()=>jNq,_length:()=>W5,_lazy:()=>zNq,_ksuid:()=>dS,_jwt:()=>qb,_isoTime:()=>yn,_isoDuration:()=>un,_isoDateTime:()=>fn,_isoDate:()=>hn,_ipv6:()=>sS,_ipv4:()=>nS,_intersection:()=>ZNq,_int64:()=>en,_int32:()=>dn,_int:()=>pn,_includes:()=>Qx,_guid:()=>iP,_gte:()=>DQ,_gt:()=>L4,_float64:()=>an,_float32:()=>ln,_file:()=>Js,_enum:()=>XNq,_endsWith:()=>Gx,_encodeAsync:()=>gS,_encode:()=>ES,_emoji:()=>cS,_email:()=>CS,_e164:()=>Ab,_discriminatedUnion:()=>FNq,_default:()=>WNq,_decodeAsync:()=>VS,_decode:()=>WS,_date:()=>Qs,_custom:()=>Hs,_cuid2:()=>lS,_cuid:()=>pS,_coercedString:()=>vn,_coercedNumber:()=>mn,_coercedDate:()=>Xs,_coercedBoolean:()=>on,_coercedBigint:()=>tn,_cidrv6:()=>rS,_cidrv4:()=>oS,_check:()=>MJA,_catch:()=>LNq,_boolean:()=>sn,_bigint:()=>rn,_base64url:()=>eS,_base64:()=>tS,_array:()=>js,_any:()=>Zs,TimePrecision:()=>Cn,NEVER:()=>Wi,JSONSchemaGenerator:()=>Fo,JSONSchema:()=>zJA,Doc:()=>NS,$output:()=>Rn,$input:()=>Tn,$constructor:()=>nA,$brand:()=>gi,$ZodXor:()=>Gd,$ZodXID:()=>ka,$ZodVoid:()=>Ud,$ZodUnknown:()=>Zd,$ZodUnion:()=>hP,$ZodUndefined:()=>qd,$ZodUUID:()=>wa,$ZodURL:()=>Da,$ZodULID:()=>va,$ZodType:()=>yK,$ZodTuple:()=>SS,$ZodTransform:()=>xd,$ZodTemplateLiteral:()=>Rd,$ZodSymbol:()=>Ad,$ZodSuccess:()=>Nd,$ZodStringFormat:()=>s1,$ZodString:()=>J5,$ZodSet:()=>Wd,$ZodRegistry:()=>Sn,$ZodRecord:()=>Hd,$ZodRealError:()=>N0,$ZodReadonly:()=>Dd,$ZodPromise:()=>Sd,$ZodPreprocess:()=>Bd,$ZodPrefault:()=>Id,$ZodPipe:()=>vS,$ZodOptional:()=>bS,$ZodObjectJIT:()=>Xd,$ZodObject:()=>WJA,$ZodNumberFormat:()=>ta,$ZodNumber:()=>RS,$ZodNullable:()=>Md,$ZodNull:()=>Kd,$ZodNonOptional:()=>Pd,$ZodNever:()=>$d,$ZodNanoID:()=>Ta,$ZodNaN:()=>wd,$ZodMap:()=>Ed,$ZodMAC:()=>pa,$ZodLiteral:()=>Vd,$ZodLazy:()=>bd,$ZodKSUID:()=>Ca,$ZodJWT:()=>oa,$ZodIntersection:()=>Jd,$ZodISOTime:()=>ya,$ZodISODuration:()=>ua,$ZodISODateTime:()=>fa,$ZodISODate:()=>ha,$ZodIPv6:()=>ma,$ZodIPv4:()=>ca,$ZodGUID:()=>_a,$ZodFunction:()=>Td,$ZodFile:()=>Ld,$ZodExactOptional:()=>Od,$ZodError:()=>TP,$ZodEnum:()=>gd,$ZodEncodeError:()=>X5,$ZodEmoji:()=>Ra,$ZodEmail:()=>Ba,$ZodE164:()=>sa,$ZodDiscriminatedUnion:()=>jd,$ZodDefault:()=>zd,$ZodDate:()=>Yd,$ZodCustomStringFormat:()=>ra,$ZodCustom:()=>vd,$ZodCodec:()=>yP,$ZodCheckUpperCase:()=>Va,$ZodCheckStringFormat:()=>Fx,$ZodCheckStartsWith:()=>xa,$ZodCheckSizeEquals:()=>ja,$ZodCheckRegex:()=>Wa,$ZodCheckProperty:()=>Ma,$ZodCheckOverwrite:()=>Ia,$ZodCheckNumberFormat:()=>Ya,$ZodCheckMultipleOf:()=>Ua,$ZodCheckMinSize:()=>Ga,$ZodCheckMinLength:()=>Ha,$ZodCheckMimeType:()=>za,$ZodCheckMaxSize:()=>Xa,$ZodCheckMaxLength:()=>Ja,$ZodCheckLowerCase:()=>ga,$ZodCheckLessThan:()=>IS,$ZodCheckLengthEquals:()=>Ea,$ZodCheckIncludes:()=>La,$ZodCheckGreaterThan:()=>PS,$ZodCheckEndsWith:()=>Oa,$ZodCheckBigIntFormat:()=>Qa,$ZodCheck:()=>XZ,$ZodCatch:()=>_d,$ZodCUID2:()=>ba,$ZodCUID:()=>Sa,$ZodCIDRv6:()=>ia,$ZodCIDRv4:()=>la,$ZodBoolean:()=>fP,$ZodBigIntFormat:()=>ea,$ZodBigInt:()=>TS,$ZodBase64URL:()=>na,$ZodBase64:()=>da,$ZodAsyncError:()=>g4,$ZodArray:()=>Qd,$ZodAny:()=>Fd});var h7A,Wi=Object.freeze({status:"aborted"});function nA(A,q,K){function F(Y,X){if(!Y._zod)Object.defineProperty(Y,"_zod",{value:{def:X,constr:U,traits:new Set},enumerable:!1});if(Y._zod.traits.has(A))return;Y._zod.traits.add(A),q(Y,X);let j=U.prototype,J=Object.keys(j);for(let E=0;E<J.length;E++){let W=J[E];if(!(W in Y))Y[W]=j[W].bind(Y)}}let Z=K?.Parent??Object;class $ extends Z{}Object.defineProperty($,"name",{value:A});function U(Y){var X;let j=K?.Parent?new $:this;F(j,Y),(X=j._zod).deferred??(X.deferred=[]);for(let J of j._zod.deferred)J();return j}return Object.defineProperty(U,"init",{value:F}),Object.defineProperty(U,Symbol.hasInstance,{value:(Y)=>{if(K?.Parent&&Y instanceof K.Parent)return!0;return Y?._zod?.traits?.has(A)}}),Object.defineProperty(U,"name",{value:A}),U}var gi=Symbol("zod_brand");class g4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class X5 extends Error{constructor(A){super(`Encountered unidirectional transform during encode: ${A}`);this.name="ZodEncodeError"}}(h7A=globalThis).__zod_globalConfig??(h7A.__zod_globalConfig={});var Q5=globalThis.__zod_globalConfig;function d$(A){if(A)Object.assign(Q5,A);return Q5}var oq={};iG(oq,{unwrapMessage:()=>NP,uint8ArrayToHex:()=>OIq,uint8ArrayToBase64url:()=>LIq,uint8ArrayToBase64:()=>c7A,stringifyPrimitive:()=>pq,slugify:()=>xi,shallowClone:()=>Mi,safeExtend:()=>JIq,required:()=>WIq,randomString:()=>$Iq,propertyKeyTypes:()=>BP,promiseAllObject:()=>ZIq,primitiveTypes:()=>zi,prefixIssues:()=>P0,pick:()=>XIq,partial:()=>EIq,parsedType:()=>nq,optionalKeys:()=>Ii,omit:()=>GIq,objectClone:()=>qIq,numKeys:()=>UIq,nullish:()=>WE,normalizeParams:()=>A6,mergeDefs:()=>ZJ,merge:()=>HIq,jsonStringifyReplacer:()=>o2,joinValues:()=>Qq,issue:()=>t2,isPlainObject:()=>VE,isObject:()=>G5,hexToUint8Array:()=>xIq,getSizableOrigin:()=>DP,getParsedType:()=>YIq,getLengthableOrigin:()=>RP,getEnumValues:()=>_P,getElementAtPath:()=>FIq,floatSafeRemainder:()=>Li,finalizeIssue:()=>BQ,extend:()=>jIq,explicitlyAborted:()=>_i,escapeRegex:()=>PX,esc:()=>GS,defineLazy:()=>NF,createTransparentProxy:()=>QIq,cloneDef:()=>KIq,clone:()=>wQ,cleanRegex:()=>wP,cleanEnum:()=>gIq,captureStackTrace:()=>jS,cached:()=>r2,base64urlToUint8Array:()=>VIq,base64ToUint8Array:()=>u7A,assignProp:()=>gE,assertNotEqual:()=>rzq,assertNever:()=>ezq,assertIs:()=>tzq,assertEqual:()=>ozq,assert:()=>AIq,allowsEval:()=>Oi,aborted:()=>LE,NUMBER_FORMAT_RANGES:()=>Pi,Class:()=>m7A,BIGINT_FORMAT_RANGES:()=>Ni});function ozq(A){return A}function rzq(A){return A}function tzq(A){}function ezq(A){throw Error("Unexpected value in exhaustive check")}function AIq(A){}function _P(A){let q=Object.values(A).filter((F)=>typeof F==="number");return Object.entries(A).filter(([F,Z])=>q.indexOf(+F)===-1).map(([F,Z])=>Z)}function Qq(A,q="|"){return A.map((K)=>pq(K)).join(q)}function o2(A,q){if(typeof q==="bigint")return q.toString();return q}function r2(A){return{get value(){{let K=A();return Object.defineProperty(this,"value",{value:K}),K}throw Error("cached value already set")}}}function WE(A){return A===null||A===void 0}function wP(A){let q=A.startsWith("^")?1:0,K=A.endsWith("$")?A.length-1:A.length;return A.slice(q,K)}function Li(A,q){let K=A/q,F=Math.round(K),Z=Number.EPSILON*Math.max(Math.abs(K),1);if(Math.abs(K-F)<Z)return 0;return K-F}var y7A=Symbol("evaluating");function NF(A,q,K){let F=void 0;Object.defineProperty(A,q,{get(){if(F===y7A)return;if(F===void 0)F=y7A,F=K();return F},set(Z){Object.defineProperty(A,q,{value:Z})},configurable:!0})}function qIq(A){return Object.create(Object.getPrototypeOf(A),Object.getOwnPropertyDescriptors(A))}function gE(A,q,K){Object.defineProperty(A,q,{value:K,writable:!0,enumerable:!0,configurable:!0})}function ZJ(...A){let q={};for(let K of A){let F=Object.getOwnPropertyDescriptors(K);Object.assign(q,F)}return Object.defineProperties({},q)}function KIq(A){return ZJ(A._zod.def)}function FIq(A,q){if(!q)return A;return q.reduce((K,F)=>K?.[F],A)}function ZIq(A){let q=Object.keys(A),K=q.map((F)=>A[F]);return Promise.all(K).then((F)=>{let Z={};for(let $=0;$<q.length;$++)Z[q[$]]=F[$];return Z})}function $Iq(A=10){let K="";for(let F=0;F<A;F++)K+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return K}function GS(A){return JSON.stringify(A)}function xi(A){return A.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var jS="captureStackTrace"in Error?Error.captureStackTrace:(...A)=>{};function G5(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var Oi=r2(()=>{if(Q5.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(A){return!1}});function VE(A){if(G5(A)===!1)return!1;let q=A.constructor;if(q===void 0)return!0;if(typeof q!=="function")return!0;let K=q.prototype;if(G5(K)===!1)return!1;if(Object.prototype.hasOwnProperty.call(K,"isPrototypeOf")===!1)return!1;return!0}function Mi(A){if(VE(A))return{...A};if(Array.isArray(A))return[...A];if(A instanceof Map)return new Map(A);if(A instanceof Set)return new Set(A);return A}function UIq(A){let q=0;for(let K in A)if(Object.prototype.hasOwnProperty.call(A,K))q++;return q}var YIq=(A)=>{let q=typeof A;switch(q){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(A)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(A))return"array";if(A===null)return"null";if(A.then&&typeof A.then==="function"&&A.catch&&typeof A.catch==="function")return"promise";if(typeof Map<"u"&&A instanceof Map)return"map";if(typeof Set<"u"&&A instanceof Set)return"set";if(typeof Date<"u"&&A instanceof Date)return"date";if(typeof File<"u"&&A instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${q}`)}},BP=new Set(["string","number","symbol"]),zi=new Set(["string","number","bigint","boolean","symbol","undefined"]);function PX(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wQ(A,q,K){let F=new A._zod.constr(q??A._zod.def);if(!q||K?.parent)F._zod.parent=A;return F}function A6(A){let q=A;if(!q)return{};if(typeof q==="string")return{error:()=>q};if(q?.message!==void 0){if(q?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");q.error=q.message}if(delete q.message,typeof q.error==="string")return{...q,error:()=>q.error};return q}function QIq(A){let q;return new Proxy({},{get(K,F,Z){return q??(q=A()),Reflect.get(q,F,Z)},set(K,F,Z,$){return q??(q=A()),Reflect.set(q,F,Z,$)},has(K,F){return q??(q=A()),Reflect.has(q,F)},deleteProperty(K,F){return q??(q=A()),Reflect.deleteProperty(q,F)},ownKeys(K){return q??(q=A()),Reflect.ownKeys(q)},getOwnPropertyDescriptor(K,F){return q??(q=A()),Reflect.getOwnPropertyDescriptor(q,F)},defineProperty(K,F,Z){return q??(q=A()),Reflect.defineProperty(q,F,Z)}})}function pq(A){if(typeof A==="bigint")return A.toString()+"n";if(typeof A==="string")return`"${A}"`;return`${A}`}function Ii(A){return Object.keys(A).filter((q)=>{return A[q]._zod.optin==="optional"&&A[q]._zod.optout==="optional"})}var Pi={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ni={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function XIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;U[Y]=K.shape[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function GIq(A,q){let K=A._zod.def,F=K.checks;if(F&&F.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let $=ZJ(A._zod.def,{get shape(){let U={...A._zod.def.shape};for(let Y in q){if(!(Y in K.shape))throw Error(`Unrecognized key: "${Y}"`);if(!q[Y])continue;delete U[Y]}return gE(this,"shape",U),U},checks:[]});return wQ(A,$)}function jIq(A,q){if(!VE(q))throw Error("Invalid input to extend: expected a plain object");let K=A._zod.def.checks;if(K&&K.length>0){let $=A._zod.def.shape;for(let U in q)if(Object.getOwnPropertyDescriptor($,U)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let Z=ZJ(A._zod.def,{get shape(){let $={...A._zod.def.shape,...q};return gE(this,"shape",$),$}});return wQ(A,Z)}function JIq(A,q){if(!VE(q))throw Error("Invalid input to safeExtend: expected a plain object");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q};return gE(this,"shape",F),F}});return wQ(A,K)}function HIq(A,q){if(A._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let K=ZJ(A._zod.def,{get shape(){let F={...A._zod.def.shape,...q._zod.def.shape};return gE(this,"shape",F),F},get catchall(){return q._zod.def.catchall},checks:q._zod.def.checks??[]});return wQ(A,K)}function EIq(A,q,K){let Z=q._zod.def.checks;if(Z&&Z.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let U=ZJ(q._zod.def,{get shape(){let Y=q._zod.def.shape,X={...Y};if(K)for(let j in K){if(!(j in Y))throw Error(`Unrecognized key: "${j}"`);if(!K[j])continue;X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j]}else for(let j in Y)X[j]=A?new A({type:"optional",innerType:Y[j]}):Y[j];return gE(this,"shape",X),X},checks:[]});return wQ(q,U)}function WIq(A,q,K){let F=ZJ(q._zod.def,{get shape(){let Z=q._zod.def.shape,$={...Z};if(K)for(let U in K){if(!(U in $))throw Error(`Unrecognized key: "${U}"`);if(!K[U])continue;$[U]=new A({type:"nonoptional",innerType:Z[U]})}else for(let U in Z)$[U]=new A({type:"nonoptional",innerType:Z[U]});return gE(this,"shape",$),$}});return wQ(q,F)}function LE(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue!==!0)return!0;return!1}function _i(A,q=0){if(A.aborted===!0)return!0;for(let K=q;K<A.issues.length;K++)if(A.issues[K]?.continue===!1)return!0;return!1}function P0(A,q){return q.map((K)=>{var F;return(F=K).path??(F.path=[]),K.path.unshift(A),K})}function NP(A){return typeof A==="string"?A:A?.message}function BQ(A,q,K){let F=A.message?A.message:NP(A.inst?._zod.def?.error?.(A))??NP(q?.error?.(A))??NP(K.customError?.(A))??NP(K.localeError?.(A))??"Invalid input",{inst:Z,continue:$,input:U,...Y}=A;if(Y.path??(Y.path=[]),Y.message=F,q?.reportInput)Y.input=U;return Y}function DP(A){if(A instanceof Set)return"set";if(A instanceof Map)return"map";if(A instanceof File)return"file";return"unknown"}function RP(A){if(Array.isArray(A))return"array";if(typeof A==="string")return"string";return"unknown"}function nq(A){let q=typeof A;switch(q){case"number":return Number.isNaN(A)?"nan":"number";case"object":{if(A===null)return"null";if(Array.isArray(A))return"array";let K=A;if(K&&Object.getPrototypeOf(K)!==Object.prototype&&"constructor"in K&&K.constructor)return K.constructor.name}}return q}function t2(...A){let[q,K,F]=A;if(typeof q==="string")return{message:q,code:"custom",input:K,inst:F};return{...q}}function gIq(A){return Object.entries(A).filter(([q,K])=>{return Number.isNaN(Number.parseInt(q,10))}).map((q)=>q[1])}function u7A(A){let q=atob(A),K=new Uint8Array(q.length);for(let F=0;F<q.length;F++)K[F]=q.charCodeAt(F);return K}function c7A(A){let q="";for(let K=0;K<A.length;K++)q+=String.fromCharCode(A[K]);return btoa(q)}function VIq(A){let q=A.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-q.length%4)%4);return u7A(q+K)}function LIq(A){return c7A(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xIq(A){let q=A.replace(/^0x/,"");if(q.length%2!==0)throw Error("Invalid hex string length");let K=new Uint8Array(q.length/2);for(let F=0;F<q.length;F+=2)K[F/2]=Number.parseInt(q.slice(F,F+2),16);return K}function OIq(A){return Array.from(A).map((q)=>q.toString(16).padStart(2,"0")).join("")}class m7A{constructor(...A){}}var p7A=(A,q)=>{A.name="$ZodError",Object.defineProperty(A,"_zod",{value:A._zod,enumerable:!1}),Object.defineProperty(A,"issues",{value:q,enumerable:!1}),A.message=JSON.stringify(q,o2,2),Object.defineProperty(A,"toString",{value:()=>A.message,enumerable:!1})},TP=nA("$ZodError",p7A),N0=nA("$ZodError",p7A,{Parent:Error});function SP(A,q=(K)=>K.message){let K={},F=[];for(let Z of A.issues)if(Z.path.length>0)K[Z.path[0]]=K[Z.path[0]]||[],K[Z.path[0]].push(q(Z));else F.push(q(Z));return{formErrors:F,fieldErrors:K}}function bP(A,q=(K)=>K.message){let K={_errors:[]},F=(Z,$=[])=>{for(let U of Z.issues)if(U.code==="invalid_union"&&U.errors.length)U.errors.map((Y)=>F({issues:Y},[...$,...U.path]));else if(U.code==="invalid_key")F({issues:U.issues},[...$,...U.path]);else if(U.code==="invalid_element")F({issues:U.issues},[...$,...U.path]);else{let Y=[...$,...U.path];if(Y.length===0)K._errors.push(q(U));else{let X=K,j=0;while(j<Y.length){let J=Y[j];if(j!==Y.length-1)X[J]=X[J]||{_errors:[]};else X[J]=X[J]||{_errors:[]},X[J]._errors.push(q(U));X=X[J],j++}}}};return F(A),K}function wi(A,q=(K)=>K.message){let K={errors:[]},F=(Z,$=[])=>{var U,Y;for(let X of Z.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((j)=>F({issues:j},[...$,...X.path]));else if(X.code==="invalid_key")F({issues:X.issues},[...$,...X.path]);else if(X.code==="invalid_element")F({issues:X.issues},[...$,...X.path]);else{let j=[...$,...X.path];if(j.length===0){K.errors.push(q(X));continue}let J=K,E=0;while(E<j.length){let W=j[E],g=E===j.length-1;if(typeof W==="string")J.properties??(J.properties={}),(U=J.properties)[W]??(U[W]={errors:[]}),J=J.properties[W];else J.items??(J.items=[]),(Y=J.items)[W]??(Y[W]={errors:[]}),J=J.items[W];if(g)J.errors.push(q(X));E++}}};return F(A),K}function l7A(A){let q=[],K=A.map((F)=>typeof F==="object"?F.key:F);for(let F of K)if(typeof F==="number")q.push(`[${F}]`);else if(typeof F==="symbol")q.push(`[${JSON.stringify(String(F))}]`);else if(/[^\w$]/.test(F))q.push(`[${JSON.stringify(F)}]`);else{if(q.length)q.push(".");q.push(F)}return q.join("")}function Bi(A){let q=[],K=[...A.issues].sort((F,Z)=>(F.path??[]).length-(Z.path??[]).length);for(let F of K)if(q.push(`\u2716 ${F.message}`),F.path?.length)q.push(` \u2192 at ${l7A(F.path)}`);return q.join(`
908
908
  `)}var e2=(A)=>(q,K,F,Z)=>{let $=F?{...F,async:!1}:{async:!1},U=q._zod.run({value:K,issues:[]},$);if(U instanceof Promise)throw new g4;if(U.issues.length){let Y=new(Z?.Err??A)(U.issues.map((X)=>BQ(X,$,d$())));throw jS(Y,Z?.callee),Y}return U.value},JS=e2(N0),Ax=(A)=>async(q,K,F,Z)=>{let $=F?{...F,async:!0}:{async:!0},U=q._zod.run({value:K,issues:[]},$);if(U instanceof Promise)U=await U;if(U.issues.length){let Y=new(Z?.Err??A)(U.issues.map((X)=>BQ(X,$,d$())));throw jS(Y,Z?.callee),Y}return U.value},HS=Ax(N0),qx=(A)=>(q,K,F)=>{let Z=F?{...F,async:!1}:{async:!1},$=q._zod.run({value:K,issues:[]},Z);if($ instanceof Promise)throw new g4;return $.issues.length?{success:!1,error:new(A??TP)($.issues.map((U)=>BQ(U,Z,d$())))}:{success:!0,data:$.value}},Di=qx(N0),Kx=(A)=>async(q,K,F)=>{let Z=F?{...F,async:!0}:{async:!0},$=q._zod.run({value:K,issues:[]},Z);if($ instanceof Promise)$=await $;return $.issues.length?{success:!1,error:new A($.issues.map((U)=>BQ(U,Z,d$())))}:{success:!0,data:$.value}},Ri=Kx(N0),ES=(A)=>(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return e2(A)(q,K,Z)},zIq=ES(N0),WS=(A)=>(q,K,F)=>{return e2(A)(q,K,F)},IIq=WS(N0),gS=(A)=>async(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return Ax(A)(q,K,Z)},PIq=gS(N0),VS=(A)=>async(q,K,F)=>{return Ax(A)(q,K,F)},NIq=VS(N0),LS=(A)=>(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return qx(A)(q,K,Z)},_Iq=LS(N0),xS=(A)=>(q,K,F)=>{return qx(A)(q,K,F)},wIq=xS(N0),OS=(A)=>async(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return Kx(A)(q,K,Z)},BIq=OS(N0),MS=(A)=>async(q,K,F)=>{return Kx(A)(q,K,F)},DIq=MS(N0);var O8={};iG(O8,{xid:()=>vi,uuid7:()=>bIq,uuid6:()=>SIq,uuid4:()=>TIq,uuid:()=>j5,uppercase:()=>$a,unicodeEmail:()=>i7A,undefined:()=>Fa,ulid:()=>bi,time:()=>oi,string:()=>ti,sha512_hex:()=>APq,sha512_base64url:()=>KPq,sha512_base64:()=>qPq,sha384_hex:()=>rIq,sha384_base64url:()=>eIq,sha384_base64:()=>tIq,sha256_hex:()=>nIq,sha256_base64url:()=>oIq,sha256_base64:()=>sIq,sha1_hex:()=>iIq,sha1_base64url:()=>dIq,sha1_base64:()=>aIq,rfc5322Email:()=>kIq,number:()=>vP,null:()=>Ka,nanoid:()=>Ci,md5_hex:()=>mIq,md5_base64url:()=>lIq,md5_base64:()=>pIq,mac:()=>pi,lowercase:()=>Za,ksuid:()=>ki,ipv6:()=>mi,ipv4:()=>ci,integer:()=>Aa,idnEmail:()=>CIq,httpProtocol:()=>di,html5Email:()=>vIq,hostname:()=>yIq,hex:()=>cIq,guid:()=>hi,extendedDuration:()=>RIq,emoji:()=>ui,email:()=>yi,e164:()=>ni,duration:()=>fi,domain:()=>uIq,datetime:()=>ri,date:()=>si,cuid2:()=>Si,cuid:()=>Ti,cidrv6:()=>ii,cidrv4:()=>li,browserEmail:()=>fIq,boolean:()=>qa,bigint:()=>ei,base64url:()=>zS,base64:()=>ai});var Ti=/^[cC][0-9a-z]{6,}$/,Si=/^[0-9a-z]+$/,bi=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vi=/^[0-9a-vA-V]{20}$/,ki=/^[A-Za-z0-9]{27}$/,Ci=/^[a-zA-Z0-9_-]{21}$/,fi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,RIq=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,hi=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,j5=(A)=>{if(!A)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${A}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},TIq=j5(4),SIq=j5(6),bIq=j5(7),yi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vIq=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,kIq=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,i7A=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,CIq=i7A,fIq=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,hIq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ui(){return new RegExp(hIq,"u")}var ci=/^(?:(?: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])$/,mi=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,pi=(A)=>{let q=PX(A??":");return new RegExp(`^(?:[0-9A-F]{2}${q}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${q}){5}[0-9a-f]{2}$`)},li=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,ii=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ai=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zS=/^[A-Za-z0-9_-]*$/,yIq=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,uIq=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,di=/^https?$/,ni=/^\+[1-9]\d{6,14}$/,a7A="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",si=new RegExp(`^${a7A}$`);function d7A(A){return typeof A.precision==="number"?A.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":A.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${A.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function oi(A){return new RegExp(`^${d7A(A)}$`)}function ri(A){let q=d7A({precision:A.precision}),K=["Z"];if(A.local)K.push("");if(A.offset)K.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let F=`${q}(?:${K.join("|")})`;return new RegExp(`^${a7A}T(?:${F})$`)}var ti=(A)=>{let q=A?`[\\s\\S]{${A?.minimum??0},${A?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${q}$`)},ei=/^-?\d+n?$/,Aa=/^-?\d+$/,vP=/^-?\d+(?:\.\d+)?$/,qa=/^(?:true|false)$/i,Ka=/^null$/i;var Fa=/^undefined$/i;var Za=/^[^A-Z]*$/,$a=/^[^a-z]*$/,cIq=/^[0-9a-fA-F]*$/;function kP(A,q){return new RegExp(`^[A-Za-z0-9+/]{${A}}${q}$`)}function CP(A){return new RegExp(`^[A-Za-z0-9_-]{${A}}$`)}var mIq=/^[0-9a-fA-F]{32}$/,pIq=kP(22,"=="),lIq=CP(22),iIq=/^[0-9a-fA-F]{40}$/,aIq=kP(27,"="),dIq=CP(27),nIq=/^[0-9a-fA-F]{64}$/,sIq=kP(43,"="),oIq=CP(43),rIq=/^[0-9a-fA-F]{96}$/,tIq=kP(64,""),eIq=CP(64),APq=/^[0-9a-fA-F]{128}$/,qPq=kP(86,"=="),KPq=CP(86);var XZ=nA("$ZodCheck",(A,q)=>{var K;A._zod??(A._zod={}),A._zod.def=q,(K=A._zod).onattach??(K.onattach=[])}),s7A={number:"number",bigint:"bigint",object:"date"},IS=nA("$ZodCheckLessThan",(A,q)=>{XZ.init(A,q);let K=s7A[typeof q.value];A._zod.onattach.push((F)=>{let Z=F._zod.bag,$=(q.inclusive?Z.maximum:Z.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(q.value<$)if(q.inclusive)Z.maximum=q.value;else Z.exclusiveMaximum=q.value}),A._zod.check=(F)=>{if(q.inclusive?F.value<=q.value:F.value<q.value)return;F.issues.push({origin:K,code:"too_big",maximum:typeof q.value==="object"?q.value.getTime():q.value,input:F.value,inclusive:q.inclusive,inst:A,continue:!q.abort})}}),PS=nA("$ZodCheckGreaterThan",(A,q)=>{XZ.init(A,q);let K=s7A[typeof q.value];A._zod.onattach.push((F)=>{let Z=F._zod.bag,$=(q.inclusive?Z.minimum:Z.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(q.value>$)if(q.inclusive)Z.minimum=q.value;else Z.exclusiveMinimum=q.value}),A._zod.check=(F)=>{if(q.inclusive?F.value>=q.value:F.value>q.value)return;F.issues.push({origin:K,code:"too_small",minimum:typeof q.value==="object"?q.value.getTime():q.value,input:F.value,inclusive:q.inclusive,inst:A,continue:!q.abort})}}),Ua=nA("$ZodCheckMultipleOf",(A,q)=>{XZ.init(A,q),A._zod.onattach.push((K)=>{var F;(F=K._zod.bag).multipleOf??(F.multipleOf=q.value)}),A._zod.check=(K)=>{if(typeof K.value!==typeof q.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof K.value==="bigint"?K.value%q.value===BigInt(0):Li(K.value,q.value)===0)return;K.issues.push({origin:typeof K.value,code:"not_multiple_of",divisor:q.value,input:K.value,inst:A,continue:!q.abort})}}),Ya=nA("$ZodCheckNumberFormat",(A,q)=>{XZ.init(A,q),q.format=q.format||"float64";let K=q.format?.includes("int"),F=K?"int":"number",[Z,$]=Pi[q.format];A._zod.onattach.push((U)=>{let Y=U._zod.bag;if(Y.format=q.format,Y.minimum=Z,Y.maximum=$,K)Y.pattern=Aa}),A._zod.check=(U)=>{let Y=U.value;if(K){if(!Number.isInteger(Y)){U.issues.push({expected:F,format:q.format,code:"invalid_type",continue:!1,input:Y,inst:A});return}if(!Number.isSafeInteger(Y)){if(Y>0)U.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:A,origin:F,inclusive:!0,continue:!q.abort});else U.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:A,origin:F,inclusive:!0,continue:!q.abort});return}}if(Y<Z)U.issues.push({origin:"number",input:Y,code:"too_small",minimum:Z,inclusive:!0,inst:A,continue:!q.abort});if(Y>$)U.issues.push({origin:"number",input:Y,code:"too_big",maximum:$,inclusive:!0,inst:A,continue:!q.abort})}}),Qa=nA("$ZodCheckBigIntFormat",(A,q)=>{XZ.init(A,q);let[K,F]=Ni[q.format];A._zod.onattach.push((Z)=>{let $=Z._zod.bag;$.format=q.format,$.minimum=K,$.maximum=F}),A._zod.check=(Z)=>{let $=Z.value;if($<K)Z.issues.push({origin:"bigint",input:$,code:"too_small",minimum:K,inclusive:!0,inst:A,continue:!q.abort});if($>F)Z.issues.push({origin:"bigint",input:$,code:"too_big",maximum:F,inclusive:!0,inst:A,continue:!q.abort})}}),Xa=nA("$ZodCheckMaxSize",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.size!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.maximum??Number.POSITIVE_INFINITY;if(q.maximum<Z)F._zod.bag.maximum=q.maximum}),A._zod.check=(F)=>{let Z=F.value;if(Z.size<=q.maximum)return;F.issues.push({origin:DP(Z),code:"too_big",maximum:q.maximum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),Ga=nA("$ZodCheckMinSize",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.size!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(q.minimum>Z)F._zod.bag.minimum=q.minimum}),A._zod.check=(F)=>{let Z=F.value;if(Z.size>=q.minimum)return;F.issues.push({origin:DP(Z),code:"too_small",minimum:q.minimum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),ja=nA("$ZodCheckSizeEquals",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.size!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.minimum=q.size,Z.maximum=q.size,Z.size=q.size}),A._zod.check=(F)=>{let Z=F.value,$=Z.size;if($===q.size)return;let U=$>q.size;F.issues.push({origin:DP(Z),...U?{code:"too_big",maximum:q.size}:{code:"too_small",minimum:q.size},inclusive:!0,exact:!0,input:F.value,inst:A,continue:!q.abort})}}),Ja=nA("$ZodCheckMaxLength",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.length!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.maximum??Number.POSITIVE_INFINITY;if(q.maximum<Z)F._zod.bag.maximum=q.maximum}),A._zod.check=(F)=>{let Z=F.value;if(Z.length<=q.maximum)return;let U=RP(Z);F.issues.push({origin:U,code:"too_big",maximum:q.maximum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),Ha=nA("$ZodCheckMinLength",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.length!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(q.minimum>Z)F._zod.bag.minimum=q.minimum}),A._zod.check=(F)=>{let Z=F.value;if(Z.length>=q.minimum)return;let U=RP(Z);F.issues.push({origin:U,code:"too_small",minimum:q.minimum,inclusive:!0,input:Z,inst:A,continue:!q.abort})}}),Ea=nA("$ZodCheckLengthEquals",(A,q)=>{var K;XZ.init(A,q),(K=A._zod.def).when??(K.when=(F)=>{let Z=F.value;return!WE(Z)&&Z.length!==void 0}),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.minimum=q.length,Z.maximum=q.length,Z.length=q.length}),A._zod.check=(F)=>{let Z=F.value,$=Z.length;if($===q.length)return;let U=RP(Z),Y=$>q.length;F.issues.push({origin:U,...Y?{code:"too_big",maximum:q.length}:{code:"too_small",minimum:q.length},inclusive:!0,exact:!0,input:F.value,inst:A,continue:!q.abort})}}),Fx=nA("$ZodCheckStringFormat",(A,q)=>{var K,F;if(XZ.init(A,q),A._zod.onattach.push((Z)=>{let $=Z._zod.bag;if($.format=q.format,q.pattern)$.patterns??($.patterns=new Set),$.patterns.add(q.pattern)}),q.pattern)(K=A._zod).check??(K.check=(Z)=>{if(q.pattern.lastIndex=0,q.pattern.test(Z.value))return;Z.issues.push({origin:"string",code:"invalid_format",format:q.format,input:Z.value,...q.pattern?{pattern:q.pattern.toString()}:{},inst:A,continue:!q.abort})});else(F=A._zod).check??(F.check=()=>{})}),Wa=nA("$ZodCheckRegex",(A,q)=>{Fx.init(A,q),A._zod.check=(K)=>{if(q.pattern.lastIndex=0,q.pattern.test(K.value))return;K.issues.push({origin:"string",code:"invalid_format",format:"regex",input:K.value,pattern:q.pattern.toString(),inst:A,continue:!q.abort})}}),ga=nA("$ZodCheckLowerCase",(A,q)=>{q.pattern??(q.pattern=Za),Fx.init(A,q)}),Va=nA("$ZodCheckUpperCase",(A,q)=>{q.pattern??(q.pattern=$a),Fx.init(A,q)}),La=nA("$ZodCheckIncludes",(A,q)=>{XZ.init(A,q);let K=PX(q.includes),F=new RegExp(typeof q.position==="number"?`^.{${q.position}}${K}`:K);q.pattern=F,A._zod.onattach.push((Z)=>{let $=Z._zod.bag;$.patterns??($.patterns=new Set),$.patterns.add(F)}),A._zod.check=(Z)=>{if(Z.value.includes(q.includes,q.position))return;Z.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:q.includes,input:Z.value,inst:A,continue:!q.abort})}}),xa=nA("$ZodCheckStartsWith",(A,q)=>{XZ.init(A,q);let K=new RegExp(`^${PX(q.prefix)}.*`);q.pattern??(q.pattern=K),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.patterns??(Z.patterns=new Set),Z.patterns.add(K)}),A._zod.check=(F)=>{if(F.value.startsWith(q.prefix))return;F.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:q.prefix,input:F.value,inst:A,continue:!q.abort})}}),Oa=nA("$ZodCheckEndsWith",(A,q)=>{XZ.init(A,q);let K=new RegExp(`.*${PX(q.suffix)}$`);q.pattern??(q.pattern=K),A._zod.onattach.push((F)=>{let Z=F._zod.bag;Z.patterns??(Z.patterns=new Set),Z.patterns.add(K)}),A._zod.check=(F)=>{if(F.value.endsWith(q.suffix))return;F.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:q.suffix,input:F.value,inst:A,continue:!q.abort})}});function n7A(A,q,K){if(A.issues.length)q.issues.push(...P0(K,A.issues))}var Ma=nA("$ZodCheckProperty",(A,q)=>{XZ.init(A,q),A._zod.check=(K)=>{let F=q.schema._zod.run({value:K.value[q.property],issues:[]},{});if(F instanceof Promise)return F.then((Z)=>n7A(Z,K,q.property));n7A(F,K,q.property);return}}),za=nA("$ZodCheckMimeType",(A,q)=>{XZ.init(A,q);let K=new Set(q.mime);A._zod.onattach.push((F)=>{F._zod.bag.mime=q.mime}),A._zod.check=(F)=>{if(K.has(F.value.type))return;F.issues.push({code:"invalid_value",values:q.mime,input:F.value.type,inst:A,continue:!q.abort})}}),Ia=nA("$ZodCheckOverwrite",(A,q)=>{XZ.init(A,q),A._zod.check=(K)=>{K.value=q.tx(K.value)}});class NS{constructor(A=[]){if(this.content=[],this.indent=0,this)this.args=A}indented(A){this.indent+=1,A(this),this.indent-=1}write(A){if(typeof A==="function"){A(this,{execution:"sync"}),A(this,{execution:"async"});return}let K=A.split(`
909
909
  `).filter(($)=>$),F=Math.min(...K.map(($)=>$.length-$.trimStart().length)),Z=K.map(($)=>$.slice(F)).map(($)=>" ".repeat(this.indent*2)+$);for(let $ of Z)this.content.push($)}compile(){let A=Function,q=this?.args,F=[...(this?.content??[""]).map((Z)=>` ${Z}`)];return new A(...q,F.join(`
910
910
  `))}}var Pa={major:4,minor:4,patch:3};var yK=nA("$ZodType",(A,q)=>{var K;A??(A={}),A._zod.def=q,A._zod.bag=A._zod.bag||{},A._zod.version=Pa;let F=[...A._zod.def.checks??[]];if(A._zod.traits.has("$ZodCheck"))F.unshift(A);for(let Z of F)for(let $ of Z._zod.onattach)$(A);if(F.length===0)(K=A._zod).deferred??(K.deferred=[]),A._zod.deferred?.push(()=>{A._zod.run=A._zod.parse});else{let Z=(U,Y,X)=>{let j=LE(U),J;for(let E of Y){if(E._zod.def.when){if(_i(U))continue;if(!E._zod.def.when(U))continue}else if(j)continue;let W=U.issues.length,g=E._zod.check(U);if(g instanceof Promise&&X?.async===!1)throw new g4;if(J||g instanceof Promise)J=(J??Promise.resolve()).then(async()=>{if(await g,U.issues.length===W)return;if(!j)j=LE(U,W)});else{if(U.issues.length===W)continue;if(!j)j=LE(U,W)}}if(J)return J.then(()=>{return U});return U},$=(U,Y,X)=>{if(LE(U))return U.aborted=!0,U;let j=Z(Y,F,X);if(j instanceof Promise){if(X.async===!1)throw new g4;return j.then((J)=>A._zod.parse(J,X))}return A._zod.parse(j,X)};A._zod.run=(U,Y)=>{if(Y.skipChecks)return A._zod.parse(U,Y);if(Y.direction==="backward"){let j=A._zod.parse({value:U.value,issues:[]},{...Y,skipChecks:!0});if(j instanceof Promise)return j.then((J)=>{return $(J,U,Y)});return $(j,U,Y)}let X=A._zod.parse(U,Y);if(X instanceof Promise){if(Y.async===!1)throw new g4;return X.then((j)=>Z(j,F,Y))}return Z(X,F,Y)}}NF(A,"~standard",()=>({validate:(Z)=>{try{let $=Di(A,Z);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return Ri(A,Z).then((U)=>U.success?{value:U.data}:{issues:U.error?.issues})}},vendor:"zod",version:1}))}),J5=nA("$ZodString",(A,q)=>{yK.init(A,q),A._zod.pattern=[...A?._zod.bag?.patterns??[]].pop()??ti(A._zod.bag),A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=String(K.value)}catch(Z){}if(typeof K.value==="string")return K;return K.issues.push({expected:"string",code:"invalid_type",input:K.value,inst:A}),K}}),s1=nA("$ZodStringFormat",(A,q)=>{Fx.init(A,q),J5.init(A,q)}),_a=nA("$ZodGUID",(A,q)=>{q.pattern??(q.pattern=hi),s1.init(A,q)}),wa=nA("$ZodUUID",(A,q)=>{if(q.version){let F={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[q.version];if(F===void 0)throw Error(`Invalid UUID version: "${q.version}"`);q.pattern??(q.pattern=j5(F))}else q.pattern??(q.pattern=j5());s1.init(A,q)}),Ba=nA("$ZodEmail",(A,q)=>{q.pattern??(q.pattern=yi),s1.init(A,q)}),Da=nA("$ZodURL",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{try{let F=K.value.trim();if(!q.normalize&&q.protocol?.source===di.source){if(!/^https?:\/\//i.test(F)){K.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:K.value,inst:A,continue:!q.abort});return}}let Z=new URL(F);if(q.hostname){if(q.hostname.lastIndex=0,!q.hostname.test(Z.hostname))K.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:q.hostname.source,input:K.value,inst:A,continue:!q.abort})}if(q.protocol){if(q.protocol.lastIndex=0,!q.protocol.test(Z.protocol.endsWith(":")?Z.protocol.slice(0,-1):Z.protocol))K.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:q.protocol.source,input:K.value,inst:A,continue:!q.abort})}if(q.normalize)K.value=Z.href;else K.value=F;return}catch(F){K.issues.push({code:"invalid_format",format:"url",input:K.value,inst:A,continue:!q.abort})}}}),Ra=nA("$ZodEmoji",(A,q)=>{q.pattern??(q.pattern=ui()),s1.init(A,q)}),Ta=nA("$ZodNanoID",(A,q)=>{q.pattern??(q.pattern=Ci),s1.init(A,q)}),Sa=nA("$ZodCUID",(A,q)=>{q.pattern??(q.pattern=Ti),s1.init(A,q)}),ba=nA("$ZodCUID2",(A,q)=>{q.pattern??(q.pattern=Si),s1.init(A,q)}),va=nA("$ZodULID",(A,q)=>{q.pattern??(q.pattern=bi),s1.init(A,q)}),ka=nA("$ZodXID",(A,q)=>{q.pattern??(q.pattern=vi),s1.init(A,q)}),Ca=nA("$ZodKSUID",(A,q)=>{q.pattern??(q.pattern=ki),s1.init(A,q)}),fa=nA("$ZodISODateTime",(A,q)=>{q.pattern??(q.pattern=ri(q)),s1.init(A,q)}),ha=nA("$ZodISODate",(A,q)=>{q.pattern??(q.pattern=si),s1.init(A,q)}),ya=nA("$ZodISOTime",(A,q)=>{q.pattern??(q.pattern=oi(q)),s1.init(A,q)}),ua=nA("$ZodISODuration",(A,q)=>{q.pattern??(q.pattern=fi),s1.init(A,q)}),ca=nA("$ZodIPv4",(A,q)=>{q.pattern??(q.pattern=ci),s1.init(A,q),A._zod.bag.format="ipv4"}),ma=nA("$ZodIPv6",(A,q)=>{q.pattern??(q.pattern=mi),s1.init(A,q),A._zod.bag.format="ipv6",A._zod.check=(K)=>{try{new URL(`http://[${K.value}]`)}catch{K.issues.push({code:"invalid_format",format:"ipv6",input:K.value,inst:A,continue:!q.abort})}}}),pa=nA("$ZodMAC",(A,q)=>{q.pattern??(q.pattern=pi(q.delimiter)),s1.init(A,q),A._zod.bag.format="mac"}),la=nA("$ZodCIDRv4",(A,q)=>{q.pattern??(q.pattern=li),s1.init(A,q)}),ia=nA("$ZodCIDRv6",(A,q)=>{q.pattern??(q.pattern=ii),s1.init(A,q),A._zod.check=(K)=>{let F=K.value.split("/");try{if(F.length!==2)throw Error();let[Z,$]=F;if(!$)throw Error();let U=Number($);if(`${U}`!==$)throw Error();if(U<0||U>128)throw Error();new URL(`http://[${Z}]`)}catch{K.issues.push({code:"invalid_format",format:"cidrv6",input:K.value,inst:A,continue:!q.abort})}}});function aa(A){if(A==="")return!0;if(/\s/.test(A))return!1;if(A.length%4!==0)return!1;try{return atob(A),!0}catch{return!1}}var da=nA("$ZodBase64",(A,q)=>{q.pattern??(q.pattern=ai),s1.init(A,q),A._zod.bag.contentEncoding="base64",A._zod.check=(K)=>{if(aa(K.value))return;K.issues.push({code:"invalid_format",format:"base64",input:K.value,inst:A,continue:!q.abort})}});function jJA(A){if(!zS.test(A))return!1;let q=A.replace(/[-_]/g,(F)=>F==="-"?"+":"/"),K=q.padEnd(Math.ceil(q.length/4)*4,"=");return aa(K)}var na=nA("$ZodBase64URL",(A,q)=>{q.pattern??(q.pattern=zS),s1.init(A,q),A._zod.bag.contentEncoding="base64url",A._zod.check=(K)=>{if(jJA(K.value))return;K.issues.push({code:"invalid_format",format:"base64url",input:K.value,inst:A,continue:!q.abort})}}),sa=nA("$ZodE164",(A,q)=>{q.pattern??(q.pattern=ni),s1.init(A,q)});function JJA(A,q=null){try{let K=A.split(".");if(K.length!==3)return!1;let[F]=K;if(!F)return!1;let Z=JSON.parse(atob(F));if("typ"in Z&&Z?.typ!=="JWT")return!1;if(!Z.alg)return!1;if(q&&(!("alg"in Z)||Z.alg!==q))return!1;return!0}catch{return!1}}var oa=nA("$ZodJWT",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{if(JJA(K.value,q.alg))return;K.issues.push({code:"invalid_format",format:"jwt",input:K.value,inst:A,continue:!q.abort})}}),ra=nA("$ZodCustomStringFormat",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{if(q.fn(K.value))return;K.issues.push({code:"invalid_format",format:q.format,input:K.value,inst:A,continue:!q.abort})}}),RS=nA("$ZodNumber",(A,q)=>{yK.init(A,q),A._zod.pattern=A._zod.bag.pattern??vP,A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=Number(K.value)}catch(U){}let Z=K.value;if(typeof Z==="number"&&!Number.isNaN(Z)&&Number.isFinite(Z))return K;let $=typeof Z==="number"?Number.isNaN(Z)?"NaN":!Number.isFinite(Z)?"Infinity":void 0:void 0;return K.issues.push({expected:"number",code:"invalid_type",input:Z,inst:A,...$?{received:$}:{}}),K}}),ta=nA("$ZodNumberFormat",(A,q)=>{Ya.init(A,q),RS.init(A,q)}),fP=nA("$ZodBoolean",(A,q)=>{yK.init(A,q),A._zod.pattern=qa,A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=Boolean(K.value)}catch($){}let Z=K.value;if(typeof Z==="boolean")return K;return K.issues.push({expected:"boolean",code:"invalid_type",input:Z,inst:A}),K}}),TS=nA("$ZodBigInt",(A,q)=>{yK.init(A,q),A._zod.pattern=ei,A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=BigInt(K.value)}catch(Z){}if(typeof K.value==="bigint")return K;return K.issues.push({expected:"bigint",code:"invalid_type",input:K.value,inst:A}),K}}),ea=nA("$ZodBigIntFormat",(A,q)=>{Qa.init(A,q),TS.init(A,q)}),Ad=nA("$ZodSymbol",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{let Z=K.value;if(typeof Z==="symbol")return K;return K.issues.push({expected:"symbol",code:"invalid_type",input:Z,inst:A}),K}}),qd=nA("$ZodUndefined",(A,q)=>{yK.init(A,q),A._zod.pattern=Fa,A._zod.values=new Set([void 0]),A._zod.parse=(K,F)=>{let Z=K.value;if(typeof Z>"u")return K;return K.issues.push({expected:"undefined",code:"invalid_type",input:Z,inst:A}),K}}),Kd=nA("$ZodNull",(A,q)=>{yK.init(A,q),A._zod.pattern=Ka,A._zod.values=new Set([null]),A._zod.parse=(K,F)=>{let Z=K.value;if(Z===null)return K;return K.issues.push({expected:"null",code:"invalid_type",input:Z,inst:A}),K}}),Fd=nA("$ZodAny",(A,q)=>{yK.init(A,q),A._zod.parse=(K)=>K}),Zd=nA("$ZodUnknown",(A,q)=>{yK.init(A,q),A._zod.parse=(K)=>K}),$d=nA("$ZodNever",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{return K.issues.push({expected:"never",code:"invalid_type",input:K.value,inst:A}),K}}),Ud=nA("$ZodVoid",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{let Z=K.value;if(typeof Z>"u")return K;return K.issues.push({expected:"void",code:"invalid_type",input:Z,inst:A}),K}}),Yd=nA("$ZodDate",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{if(q.coerce)try{K.value=new Date(K.value)}catch(Y){}let Z=K.value,$=Z instanceof Date;if($&&!Number.isNaN(Z.getTime()))return K;return K.issues.push({expected:"date",code:"invalid_type",input:Z,...$?{received:"Invalid Date"}:{},inst:A}),K}});function r7A(A,q,K){if(A.issues.length)q.issues.push(...P0(K,A.issues));q.value[K]=A.value}var Qd=nA("$ZodArray",(A,q)=>{yK.init(A,q),A._zod.parse=(K,F)=>{let Z=K.value;if(!Array.isArray(Z))return K.issues.push({expected:"array",code:"invalid_type",input:Z,inst:A}),K;K.value=Array(Z.length);let $=[];for(let U=0;U<Z.length;U++){let Y=Z[U],X=q.element._zod.run({value:Y,issues:[]},F);if(X instanceof Promise)$.push(X.then((j)=>r7A(j,K,U)));else r7A(X,K,U)}if($.length)return Promise.all($).then(()=>K);return K}});function DS(A,q,K,F,Z,$){let U=K in F;if(A.issues.length){if(Z&&$&&!U)return;q.issues.push(...P0(K,A.issues))}if(!U&&!Z){if(!A.issues.length)q.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[K]});return}if(A.value===void 0){if(U)q.value[K]=void 0}else q.value[K]=A.value}function HJA(A){let q=Object.keys(A.shape);for(let F of q)if(!A.shape?.[F]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${F}": expected a Zod schema`);let K=Ii(A.shape);return{...A,keys:q,keySet:new Set(q),numKeys:q.length,optionalKeys:new Set(K)}}function EJA(A,q,K,F,Z,$){let U=[],Y=Z.keySet,X=Z.catchall._zod,j=X.def.type,J=X.optin==="optional",E=X.optout==="optional";for(let W in q){if(W==="__proto__")continue;if(Y.has(W))continue;if(j==="never"){U.push(W);continue}let g=X.run({value:q[W],issues:[]},F);if(g instanceof Promise)A.push(g.then((L)=>DS(L,K,W,q,J,E)));else DS(g,K,W,q,J,E)}if(U.length)K.issues.push({code:"unrecognized_keys",keys:U,input:q,inst:$});if(!A.length)return K;return Promise.all(A).then(()=>{return K})}var WJA=nA("$ZodObject",(A,q)=>{if(yK.init(A,q),!Object.getOwnPropertyDescriptor(q,"shape")?.get){let Y=q.shape;Object.defineProperty(q,"shape",{get:()=>{let X={...Y};return Object.defineProperty(q,"shape",{value:X}),X}})}let F=r2(()=>HJA(q));NF(A._zod,"propValues",()=>{let Y=q.shape,X={};for(let j in Y){let J=Y[j]._zod;if(J.values){X[j]??(X[j]=new Set);for(let E of J.values)X[j].add(E)}}return X});let Z=G5,$=q.catchall,U;A._zod.parse=(Y,X)=>{U??(U=F.value);let j=Y.value;if(!Z(j))return Y.issues.push({expected:"object",code:"invalid_type",input:j,inst:A}),Y;Y.value={};let J=[],E=U.shape;for(let W of U.keys){let g=E[W],L=g._zod.optin==="optional",M=g._zod.optout==="optional",O=g._zod.run({value:j[W],issues:[]},X);if(O instanceof Promise)J.push(O.then((_)=>DS(_,Y,W,j,L,M)));else DS(O,Y,W,j,L,M)}if(!$)return J.length?Promise.all(J).then(()=>Y):Y;return EJA(J,j,Y,X,F.value,A)}}),Xd=nA("$ZodObjectJIT",(A,q)=>{WJA.init(A,q);let K=A._zod.parse,F=r2(()=>HJA(q)),Z=(W)=>{let g=new NS(["shape","payload","ctx"]),L=F.value,M=(T)=>{let v=GS(T);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};g.write("const input = payload.value;");let O=Object.create(null),_=0;for(let T of L.keys)O[T]=`key_${_++}`;g.write("const newResult = {};");for(let T of L.keys){let v=O[T],y=GS(T),i=W[T],l=i?._zod?.optin==="optional",n=i?._zod?.optout==="optional";if(g.write(`const ${v} = ${M(T)};`),l&&n)g.write(`
@@ -1429,8 +1429,8 @@ usage: funnel update
1429
1429
  Runs "bun i -g @interactive-inc/claude-funnel".`,S3A="@interactive-inc/claude-funnel",b3A=_6.createHandlers(tq("query",c.object({}),ttq),async(A)=>{let K=await new jY().attach(["bun","i","-g",S3A]);if(K!==0)throw new pK(500,{message:`update failed (exit ${K})`});return A.text(`updated ${S3A}`)});import{join as IYK}from"path";class XV{}class sKA{}class oKA extends sKA{constructor(){super();Object.freeze(this)}async fetch(A){let q=await globalThis.fetch(A.url,{method:A.method,headers:A.headers,body:A.body});return{status:q.status,ok:q.ok,text:()=>q.text(),json:()=>q.json()}}}var etq="https://discord.com/api/v10",Aeq=new oKA;class rKA extends XV{token;http;constructor(A){super();this.token=A.config.botToken,this.http=A.http??Aeq,Object.freeze(this)}async call(A){let q=(A.method||"GET").toUpperCase(),K=A.path.startsWith("/")?A.path:`/${A.path}`,F=A.body,Z=F!==null&&typeof F==="object"&&q!=="GET"&&Object.keys(F).length>0,$=await this.http.fetch({method:q,url:`${etq}${K}`,headers:{Authorization:`Bot ${this.token}`,"Content-Type":"application/json"},body:Z?JSON.stringify(A.body):void 0});if(!$.ok)throw Error(`Discord API failed (${$.status}): ${await $.text()}`);if($.status===204)return null;return await $.json()}}var tJ=MK(V1q(),1);class rJ{isAlive(){return!0}}class lYA{ownUserId;constructor(A){this.ownUserId=A.ownUserId}process(A){if(A.authorIsBot)return{skip:!0};let q=this.ownUserId?A.mentionedUserIds.includes(this.ownUserId):!1;return{skip:!1,content:JSON.stringify(A.raw),meta:{event_type:"discord",channel_id:A.channelId,user_id:A.authorId,mentioned:String(q),guild_id:A.guildId??""}}}}var y_6=new w$;class iYA extends rJ{config;logger;client=null;constructor(A){super();this.config=A.config,this.logger=A.logger??y_6}async start(A){let q=new tJ.Client({intents:[tJ.GatewayIntentBits.Guilds,tJ.GatewayIntentBits.GuildMessages,tJ.GatewayIntentBits.MessageContent,tJ.GatewayIntentBits.DirectMessages],partials:[tJ.Partials.Channel]});q.on("messageCreate",async(K)=>{let F=q.user?.id??"",Z=[...K.mentions.users.keys()];this.logger.info("discord messageCreate",{author:K.author.id,authorIsBot:String(K.author.bot),channelId:K.channelId,guildId:K.guildId??"",mentions:Z.join(","),ownUserId:F,mentioned:String(Z.includes(F))});let U=new lYA({ownUserId:F}).process({authorId:K.author.id,authorIsBot:K.author.bot,channelId:K.channelId,guildId:K.guildId,mentionedUserIds:Z,raw:K.toJSON()});if(U.skip){this.logger.info("discord skip",{reason:"bot author"});return}try{await A(U.content,U.meta)}catch(Y){this.logger.error("discord notify error",{error:Y instanceof Error?Y.message:String(Y)})}}),q.on("ready",(K)=>{this.logger.info("discord ready",{userId:K.user.id,tag:K.user.tag,guilds:String(K.guilds.cache.size)})}),q.on("error",(K)=>{this.logger.error("discord client error",{error:K instanceof Error?K.message:String(K)})}),await q.login(this.config.botToken),this.client=q}async stop(){if(!this.client)return;try{await this.client.destroy()}catch(A){this.logger.error("discord stop error",{error:A instanceof Error?A.message:String(A)})}finally{this.client=null}}isAlive(){return this.client!==null}}var u_6=new jY;class aYA extends XV{process;constructor(A={}){super();this.process=A.process??u_6,Object.freeze(this)}async call(A){let q=["api",A.path];if(A.method&&A.method.toLowerCase()!=="get")q.push("-X",A.method.toUpperCase());let K=A.body&&typeof A.body==="object"&&Object.keys(A.body).length>0;if(K)q.push("--input","-");let F=await this.process.run(["gh",...q],{input:K?JSON.stringify(A.body):void 0});if(F.exitCode!==0)throw Error(`gh api failed: ${F.stderr.trim()||F.stdout.trim()}`);try{return JSON.parse(F.stdout)}catch{return F.stdout}}}var c_6=c.object({id:c.string(),reason:c.string(),subject:c.object({type:c.string(),url:c.string(),title:c.string()}),repository:c.object({full_name:c.string()}),updated_at:c.string()}),m_6=c.array(c_6),p_6=new jY,l_6=new w$,i_6=1e4,a_6=5000;class dYA extends rJ{config;process;logger;now;seen=new Map;bootstrapped=!1;since;timer=null;constructor(A){super();this.config=A.config,this.process=A.process??p_6,this.logger=A.logger??l_6,this.now=A.now??(()=>new Date),this.since=this.now().toISOString()}async start(A){await this.pollOnce(A);let q=this.config.pollInterval??60;this.timer=setInterval(()=>void this.pollOnce(A),q*1000),this.timer.unref()}async stop(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}isAlive(){return this.timer!==null}async pollOnce(A){let q=this.now().toISOString(),K=new URLSearchParams({since:this.since,all:"false"});try{let F=await this.process.run(["gh","api",`/notifications?${K}`]);if(F.exitCode!==0){this.logger.error("gh poll failed",{stderr:F.stderr});return}let Z=m_6.safeParse(JSON.parse(F.stdout));if(!Z.success){this.logger.warn("gh response did not match schema",{error:Z.error.message});return}let $=Z.data;for(let U of $){if(this.seen.get(U.id)===U.updated_at)continue;if(this.seen.set(U.id,U.updated_at),!this.bootstrapped)continue;let Y={event_type:"gh",reason:U.reason,subject_type:U.subject.type,subject_url:U.subject.url,repository:U.repository.full_name,thread_id:U.id,updated_at:U.updated_at};await A(JSON.stringify(U),Y)}if(this.seen.size>i_6){let U=this.seen.size-a_6,Y=0;for(let X of this.seen.keys()){if(Y>=U)break;this.seen.delete(X),Y++}}this.since=q,this.bootstrapped=!0}catch(F){this.logger.error("gh poll error",{error:F instanceof Error?F.message:String(F)})}}}var fB=(A,q,K)=>{let F=new Set;for(let Z of A.split(",")){let[$,U]=Z.split("/"),Y=U?Number(U):1;if(!Number.isFinite(Y)||Y<=0)throw Error(`invalid cron step: "${U}"`);let X=q,j=K;if($==="*"||$===void 0||$==="")X=q,j=K;else if($.includes("-")){let[J,E]=$.split("-"),W=Number(J),g=Number(E);if(!Number.isFinite(W)||!Number.isFinite(g))throw Error(`invalid cron range: "${$}"`);X=W,j=g}else{let J=Number($);if(!Number.isFinite(J))throw Error(`invalid cron value: "${$}"`);X=J,j=U?K:J}if(X<q||j>K||X>j)throw Error(`cron value out of range: ${$} (must be ${q}-${K})`);for(let J=X;J<=j;J+=Y)F.add(J)}return{min:q,max:K,values:F}},iu=(A,q)=>{let K=A.trim().split(/\s+/);if(K.length!==5)throw Error(`cron must have 5 fields (got ${K.length}): "${A}"`);let[F,Z,$,U,Y]=K;if(!F||!Z||!$||!U||!Y)throw Error(`cron has empty fields: "${A}"`);let X=[{field:fB(F,0,59),value:q.getMinutes()},{field:fB(Z,0,23),value:q.getHours()},{field:fB($,1,31),value:q.getDate()},{field:fB(U,1,12),value:q.getMonth()+1},{field:fB(Y,0,6),value:q.getDay()}];for(let{field:j,value:J}of X)if(!j.values.has(J))return!1;return!0};var d_6=new w$,L1q=1440;class nYA extends rJ{config;lastFiredStore;logger;now;onFired;timer=null;stopped=!1;constructor(A){super();this.config=A.config,this.lastFiredStore=A.lastFiredStore,this.logger=A.logger??d_6,this.now=A.now??(()=>new Date),this.onFired=A.onFired??null}async start(A){this.stopped=!1;let q=()=>{if(this.stopped)return;let K=this.now(),F=60000-(K.getSeconds()*1000+K.getMilliseconds());this.timer=setTimeout(async()=>{if(this.stopped)return;await this.tick(A),q()},F),this.timer.unref()};await this.tick(A),q()}async stop(){if(this.stopped=!0,this.timer)clearTimeout(this.timer),this.timer=null}isAlive(){return!this.stopped&&this.timer!==null}async tick(A){let q=this.truncateToMinute(this.now()),K=this.lastFiredStore.load(),F=!1;for(let Z of this.config.entries){if(!Z.enabled)continue;if(await this.fireEntry(Z,q,K,A))F=!0}if(F)this.lastFiredStore.save(K)}async fireEntry(A,q,K,F){let Z=K.get(A.id),$=Z?new Date(Z.getTime()+60000):q;if($.getTime()>q.getTime())return!1;if(A.catchupPolicy==="skip"){try{if(!iu(A.cron,q))return!1}catch(Y){return this.logInvalidCron(A,Y),!1}return await this.notifyOne(A,q,F,!1),K.set(A.id,q),!0}if(A.catchupPolicy==="all"){let Y=this.findAllMatches(A.cron,$,q,A.id);if(Y.length===0)return!1;for(let X of Y)await this.notifyOne(A,X,F,X.getTime()!==q.getTime());return K.set(A.id,Y[Y.length-1]??q),!0}let U=this.findMostRecentMatch(A.cron,$,q,A.id);if(!U)return!1;return await this.notifyOne(A,U,F,U.getTime()!==q.getTime()),K.set(A.id,U),!0}async notifyOne(A,q,K,F){let Z={event_type:"schedule",schedule_id:A.id,cron:A.cron,fired_at:q.toISOString(),catchup_policy:A.catchupPolicy};if(F)Z.catchup="true";if(await K(A.prompt,Z),this.onFired)try{await this.onFired(A,q)}catch($){this.logger.error("schedule onFired callback failed",{connector:this.config.name,id:A.id,error:$ instanceof Error?$.message:String($)})}}findMostRecentMatch(A,q,K,F){let Z=Math.min(L1q,Math.floor((K.getTime()-q.getTime())/60000)+1);for(let $=0;$<Z;$++){let U=new Date(K.getTime()-$*60000);try{if(iu(A,U))return U}catch(Y){return this.logInvalidCron({id:F,cron:A},Y),null}}return null}findAllMatches(A,q,K,F){let Z=Math.min(L1q,Math.floor((K.getTime()-q.getTime())/60000)+1),$=[];for(let U=0;U<Z;U++){let Y=new Date(q.getTime()+U*60000);if(Y.getTime()>K.getTime())break;try{if(iu(A,Y))$.push(Y)}catch(X){return this.logInvalidCron({id:F,cron:A},X),[]}}return $}logInvalidCron(A,q){this.logger.error("invalid cron expression in schedule",{connector:this.config.name,id:A.id,cron:A.cron,error:q instanceof Error?q.message:String(q)})}truncateToMinute(A){let q=new Date(A.getTime());return q.setSeconds(0,0),q}}import{dirname as n_6}from"path";var s_6=new FY;class sYA{path;fs;constructor(A){this.path=A.path,this.fs=A.fs??s_6,Object.freeze(this)}load(){let A=new Map;if(!this.fs.existsSync(this.path))return A;let q=JSON.parse(this.fs.readFileSync(this.path));if(q===null||typeof q!=="object")return A;for(let[K,F]of Object.entries(q))if(typeof F==="string")A.set(K,new Date(F));return A}save(A){let q={};for(let[K,F]of A)q[K]=F.toISOString();this.fs.mkdirSync(n_6(this.path),{recursive:!0}),this.fs.writeFileSync(this.path,`${JSON.stringify(q,null,2)}
1430
1430
  `)}}var kQq=MK(vQq(),1);var bb6=(A)=>{let q={};for(let[K,F]of Object.entries(A))q[K]=F;return q},vb6=(A)=>{if(!A||typeof A!=="object")return null;if(!("code"in A))return null;let q=A.code;if(typeof q!=="string"||!q.startsWith("slack_webapi_"))return null;if(!("data"in A))return null;let K=A.data;if(!K||typeof K!=="object")return null;return K};class P0A extends XV{client;constructor(A){super();this.client=A.client??new kQq.WebClient(A.config.botToken),Object.freeze(this)}async call(A){let q=A.body!==null&&typeof A.body==="object"?bb6(A.body):{};try{return await this.client.apiCall(A.path,q)}catch(K){let F=vb6(K);if(F)return F;throw K}}}var rp=MK(Xzq(),1);var qUK=new Set(["message","app_mention"]),KUK=new Set([void 0,"thread_broadcast","bot_message","file_share"]);var bj=(A,q)=>{let K=A[q];return typeof K==="string"?K:void 0};class w4A{ownBotUserId;ownBotId;now;dedup=new Map;constructor(A){this.ownBotUserId=A.ownBotUserId,this.ownBotId=A.ownBotId,this.now=A.now??(()=>Date.now())}process(A){let q=bj(A,"type");if(!q||!qUK.has(q))return{skip:!0};let K=bj(A,"subtype");if(!KUK.has(K))return{skip:!0};let F=bj(A,"channel")??"",Z=bj(A,"event_ts")??bj(A,"ts")??"",$=`${F}:${Z}`,U=this.now();if(this.dedup.has($))return{skip:!0};this.dedup.set($,U);for(let W of this.dedup.keys())if((this.dedup.get(W)??0)<U-1e4)this.dedup.delete(W);let Y=bj(A,"user"),X=bj(A,"bot_id");if(Y===this.ownBotUserId)return{skip:!0};if(X===this.ownBotId)return{skip:!0};let J=(bj(A,"text")??"").includes(`<@${this.ownBotUserId}>`),E=bj(A,"thread_ts")??bj(A,"ts")??"";return{skip:!1,content:JSON.stringify(A),meta:{event_type:"slack",channel_id:F,user_id:Y??"",mentioned:String(J),thread_ts:E},shouldReact:J,channel:F,timestamp:bj(A,"ts")??""}}}var FUK=c.object({event:c.record(c.string(),c.unknown()).optional()}),ZUK=new w$;class B4A extends rJ{config;logger;onAppCreated;preprocessEvent;app=null;constructor(A){super();this.config=A.config,this.logger=A.logger??ZUK,this.onAppCreated=A.onAppCreated??null,this.preprocessEvent=A.preprocessEvent??null}async start(A){let q=new rp.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:rp.LogLevel.ERROR}),K=await q.client.auth.test({token:this.config.botToken}),F=new w4A({ownBotUserId:K.user_id??"",ownBotId:K.bot_id??""}),Z=this.preprocessEvent;if(q.use(async($)=>{let U=FUK.safeParse($);if(!U.success||!U.data.event)return;let Y=U.data.event,X=Z?Z(Y):Y;if(X===null)return;let j=F.process(X);if(j.skip)return;if(j.shouldReact)try{await q.client.reactions.add({token:this.config.botToken,channel:j.channel,timestamp:j.timestamp,name:"eyes"})}catch{}await A(j.content,j.meta)}),q.error(async($)=>{this.logger.error("Slack error",{error:$ instanceof Error?$.message:String($)})}),this.onAppCreated)await this.onAppCreated(q);await q.start(),this.app=q}async stop(){if(!this.app)return;try{await this.app.stop()}catch(A){this.logger.error("Slack stop error",{error:A instanceof Error?A.message:String(A)})}finally{this.app=null}}isAlive(){return this.app!==null}}import{homedir as $UK}from"os";import{dirname as UUK,join as Gzq}from"path";class hR{}var c8=Gzq($UK(),".funnel"),YUK=Gzq(c8,"settings.json"),QUK=new FY;class D4A extends hR{path;fs;constructor(A={}){super();this.path=A.path??YUK,this.fs=A.fs??QUK,Object.freeze(this)}read(){if(!this.fs.existsSync(this.path))return{version:VJ,channels:[],profiles:[]};let A=this.fs.readFileSync(this.path),q=JSON.parse(A);if(this.looksLikeLegacy(q))throw Error(`legacy settings.json detected at ${this.path}. The schema changed (channel.connectors are now nested objects with ids; profile fields renamed). Migration is intentionally not provided. Back up and remove the old file:
1431
1431
  mv ${this.path} ${this.path}.bak`);if(q&&typeof q==="object"&&"version"in q&&q.version!==VJ)throw Error(`unsupported settings.json version (${this.path}): expected ${VJ}, got ${String(q.version)}`);let K=Lk.safeParse(q);if(!K.success)throw Error(`invalid settings.json (${this.path}): ${K.error.issues.map((F)=>`${F.path.join(".")}: ${F.message}`).join(", ")}`);return K.data}looksLikeLegacy(A){if(!A||typeof A!=="object")return!1;let q=A;if(Array.isArray(q.channels))for(let K of q.channels){if(!K||typeof K!=="object")continue;let F=K;if(Array.isArray(F.connectors)&&F.connectors.some((Z)=>typeof Z==="string"))return!0;if(!("id"in F)&&"name"in F)return!0}if(Array.isArray(q.connectors))return!0;if(Array.isArray(q.repositories))return!0;if(Array.isArray(q.profiles))for(let K of q.profiles){if(!K||typeof K!=="object")continue;let F=K;if("repository"in F||"envFiles"in F||"channel"in F&&!("channelId"in F))return!0}return!1}write(A){this.fs.mkdirSync(UUK(this.path),{recursive:!0});let q={...A,version:VJ};this.fs.writeFileSync(this.path,`${JSON.stringify(q,null,2)}
1432
- `)}}import{join as R4A}from"path";var XUK=new FY,GUK=new jY,jUK=new w$;class T4A{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor(A={}){this.fs=A.fs??XUK,this.process=A.process??GUK,this.logger=A.logger??jUK,this.dir=A.dir??c8,this.slackListenerOptions=A.slackListenerOptions??{},this.scheduleListenerOptions=A.scheduleListenerOptions??{},Object.freeze(this)}createListener(A,q){if(q.type==="slack")return new B4A({config:q,logger:this.logger,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(q.type==="gh")return new dYA({config:q,process:this.process,logger:this.logger});if(q.type==="discord")return new iYA({config:q,logger:this.logger});let K=new sYA({path:R4A(this.connectorDir(A,q.id),"state.json"),fs:this.fs});return new nYA({config:q,lastFiredStore:K,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter(A){if(A.type==="slack")return new P0A({config:A});if(A.type==="gh")return new aYA({process:this.process});if(A.type==="discord")return new rKA({config:A});return null}connectorDir(A,q){return R4A(this.dir,"channels",A,"connectors",q)}channelDir(A){return R4A(this.dir,"channels",A)}}function S4A(A){switch(A.type){case"slack":return[A.botToken,A.appToken];case"discord":return[A.botToken];case"gh":case"schedule":return[]}}function JUK(A,q){return A.type===q}function bL(A,q,K){let F=A.connectors.find((Z)=>Z.name===q);if(!F)throw Error(`connector "${q}" not found in channel "${A.name}"`);if(!JUK(F,K))throw Error(`connector "${q}" is type "${F.type}", not "${K}"`);return F}class yR{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class vL extends yR{now(){return new Date}}class uR{}class cR extends uR{generate(){return crypto.randomUUID()}}var HUK=new vL,EUK=new cR;class b4A{store;factory;profileChecker;clock;idGenerator;constructor(A){this.store=A.store,this.factory=A.factory,this.profileChecker=A.profileChecker,this.clock=A.clock??HUK,this.idGenerator=A.idGenerator??EUK,Object.freeze(this)}list(){return this.store.read().channels}get(A){return this.list().find((q)=>q.name===A)??null}getById(A){return this.list().find((q)=>q.id===A)??null}add(A){let q=this.store.read();if(q.channels.some((F)=>F.name===A.name))throw Error(`channel "${A.name}" already exists`);let K={id:this.idGenerator.generate(),name:A.name,delivery:A.delivery??"fanout",options:A.options??[],env:A.env??{},resume:A.resume??!0,connectors:[]};return q.channels.push(K),this.store.write(q),K}setDelivery(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.delivery=q,this.store.write(K)}setResume(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.resume=q,this.store.write(K)}setOptions(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.options=q,this.store.write(K)}setEnv(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.env=q,this.store.write(K)}remove(A){let q=this.store.read(),K=q.channels.findIndex((Z)=>Z.name===A);if(K<0)throw Error(`channel "${A}" not found`);let F=q.channels[K];if(F&&this.profileChecker.hasChannelRef(F.id))throw Error(`channel "${A}" is referenced by a profile`);q.channels.splice(K,1),this.store.write(q)}rename(A,q){let K=this.store.read(),F=K.channels.find((Z)=>Z.name===A);if(!F)throw Error(`channel "${A}" not found`);if(K.channels.some((Z)=>Z.name===q))throw Error(`channel "${q}" already exists`);F.name=q,this.store.write(K)}listConnectors(A){return this.requireChannel(this.store.read(),A).connectors}getConnector(A,q){let K=this.get(A);if(!K)return null;return K.connectors.find((F)=>F.name===q)??null}listAllConnectors(){let A=[];for(let q of this.list())for(let K of q.connectors)A.push({...K,channelId:q.id,channelName:q.name});return A}addConnector(A,q){let K=this.store.read(),F=this.requireChannel(K,A);if(F.connectors.some(($)=>$.name===q.name))throw Error(`connector "${q.name}" already exists in channel "${A}"`);let Z=this.fromInput(q);return this.assertNoTokenCollision(K,Z),F.connectors.push(Z),this.store.write(K),Z}fromInput(A){let q=this.idGenerator.generate(),K=this.clock.iso(),F=K,Z=K;switch(A.type){case"slack":return{id:q,type:"slack",name:A.name,botToken:A.botToken,appToken:A.appToken,createdAt:F,updatedAt:Z};case"gh":return{id:q,type:"gh",name:A.name,...A.pollInterval!==void 0?{pollInterval:A.pollInterval}:{},createdAt:F,updatedAt:Z};case"discord":return{id:q,type:"discord",name:A.name,botToken:A.botToken,createdAt:F,updatedAt:Z};case"schedule":return{id:q,type:"schedule",name:A.name,entries:A.entries??[],createdAt:F,updatedAt:Z}}}removeConnector(A,q){let K=this.store.read(),F=this.requireChannel(K,A),Z=F.connectors.findIndex(($)=>$.name===q);if(Z<0)throw Error(`connector "${q}" not found in channel "${A}"`);F.connectors.splice(Z,1),this.store.write(K)}renameConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=Z.connectors.find((U)=>U.name===q);if(!$)throw Error(`connector "${q}" not found in channel "${A}"`);if(Z.connectors.some((U)=>U.name===K))throw Error(`connector "${K}" already exists in channel "${A}"`);$.name=K,$.updatedAt=this.clock.iso(),this.store.write(F)}updateSlackConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"slack"),U={...$,botToken:K.botToken??$.botToken,appToken:K.appToken??$.appToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(F,U),Object.assign($,U),this.store.write(F)}updateGhConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"gh");if(K.pollInterval!==void 0)$.pollInterval=K.pollInterval;$.updatedAt=this.clock.iso(),this.store.write(F)}updateDiscordConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"discord"),U={...$,botToken:K.botToken??$.botToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(F,U),Object.assign($,U),this.store.write(F)}listScheduleEntries(A,q){let K=this.requireChannel(this.store.read(),A);return bL(K,q,"schedule").entries}addScheduleEntry(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"schedule"),U={id:K.id??this.idGenerator.generate(),cron:K.cron,prompt:K.prompt,enabled:K.enabled??!0,catchupPolicy:K.catchupPolicy??"latest"};return $.entries.push(U),$.updatedAt=this.clock.iso(),this.store.write(F),U}removeScheduleEntry(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"schedule"),U=$.entries.findIndex((Y)=>Y.id===K);if(U<0)throw Error(`schedule entry "${K}" not found`);$.entries.splice(U,1),$.updatedAt=this.clock.iso(),this.store.write(F)}async call(A,q,K){let F=this.getConnector(A,q);if(!F)throw Error(`connector "${q}" not found in channel "${A}"`);let Z=this.factory.createAdapter(F);if(!Z)throw Error(`connector type "${F.type}" does not support outbound calls`);return await Z.call(K)}createListener(A,q){let K=this.get(A);if(!K)return null;let F=K.connectors.find((Z)=>Z.name===q);if(!F)return null;return{config:F,channelId:K.id,listener:this.factory.createListener(K.id,F)}}createAllListeners(){let A=[];for(let q of this.list())for(let K of q.connectors)A.push({config:K,channelId:q.id,channelName:q.name,listener:this.factory.createListener(q.id,K)});return A}requireChannel(A,q){let K=A.channels.find((F)=>F.name===q);if(!K)throw Error(`channel "${q}" not found`);return K}assertNoTokenCollision(A,q){let K=S4A(q);if(K.length===0)return;for(let F of A.channels)for(let Z of F.connectors){if(Z.id===q.id)continue;for(let $ of S4A(Z))if(K.includes($))throw Error(`token already in use by connector "${Z.name}" in channel "${F.name}"`)}}}import{join as jzq}from"path";var WUK=new jY,gUK=new FY,VUK=new w$;class v4A{channels;mcp;gateway;sessions;process;fs;logger;pidDir;constructor(A){this.channels=A.channels,this.mcp=A.mcp,this.gateway=A.gateway,this.sessions=A.sessions,this.process=A.process??WUK,this.fs=A.fs??gUK,this.logger=A.logger??VUK,this.pidDir=jzq(A.dir??c8,"claude"),Object.freeze(this)}async launch(A){let q=this.channels.get(A.channel)??this.channels.getById(A.channel);if(!q)throw Error(`channel "${A.channel}" not found`);if(A.profileName&&this.isRunning(A.profileName))throw Error(`profile "${A.profileName}" is already running`);let K=A.cwd??globalThis.process.cwd();if((A.installMcp??!0)&&!this.mcp.findInstalledName(K))this.mcp.install(K),this.logger.info("added funnel MCP to .mcp.json",{cwd:K});if(!this.gateway.isRunning())this.logger.info("starting gateway automatically"),await this.gateway.start();if(A.profileName)this.writePidFile(A.profileName),this.installCleanup(A.profileName);let Z=q.resume?this.resolveSessionId(q.id,K,A.userArgs??[]):null,$=this.buildArgs(q.options,A.userArgs??[],K,Z),U=this.buildEnv(q.id,q.env);this.logger.info("claude launch",{channel:A.channel,channelId:q.id,cwd:K});try{return await this.process.attach(["claude",...$],{cwd:K,env:U,onSpawned:A.onSpawned})}finally{if(A.profileName)this.removePidFile(A.profileName)}}isRunning(A){let q=this.readPid(A);if(!q)return!1;return this.isProcessAlive(q)}pidPath(A){return jzq(this.pidDir,`${A}.pid`)}readPid(A){let q=this.pidPath(A);if(!this.fs.existsSync(q))return null;try{let K=this.fs.readFileSync(q).trim(),F=Number(K);if(!F||F<=0)return null;return F}catch{return null}}writePidFile(A){this.fs.mkdirSync(this.pidDir,{recursive:!0}),this.fs.writeFileSync(this.pidPath(A),String(globalThis.process.pid))}removePidFile(A){let q=this.pidPath(A);if(this.fs.existsSync(q))this.fs.unlink(q)}installCleanup(A){globalThis.process.once("exit",()=>this.removePidFile(A))}isProcessAlive(A){return this.process.isAlive(A)}buildArgs(A,q,K,F){let Z=[...A,...q];if(F!==null)Z.push("--session-id",F);let $=this.mcp.findInstalledName(K);if($&&!Z.includes("--dangerously-load-development-channels")&&!Z.includes("--channels"))Z.push("--dangerously-load-development-channels",`server:${$}`);return Z}resolveSessionId(A,q,K){for(let F of K){if(F==="-c"||F==="--continue")return null;if(F==="--resume"||F.startsWith("--resume="))return null;if(F==="--session-id"||F.startsWith("--session-id="))return null}return this.sessions.getOrCreate(A,q)}buildEnv(A,q){let K={};for(let[F,Z]of Object.entries(q))K[F]=Z;for(let[F,Z]of Object.entries(globalThis.process.env))if(typeof Z==="string")K[F]=Z;return K.FUNNEL_CHANNEL_ID=A,K}}var LUK=384;class k4A extends G_{dirs;files;mtimes;modes;now;constructor(A={}){super();this.dirs=new Set(A.dirs??[]),this.files=new Map(Object.entries(A.files??{})),this.mtimes=new Map(Object.entries(A.mtimes??{})),this.modes=new Map(Object.entries(A.modes??{})),this.now=A.now??(()=>Date.now())}existsSync(A){return this.dirs.has(A)||this.files.has(A)}readFileSync(A){return this.files.get(A)??""}writeFileSync(A,q){this.files.set(A,q),this.touch(A)}writeSecretFileSync(A,q){this.files.set(A,q),this.modes.set(A,LUK),this.touch(A)}appendFileSync(A,q){let K=this.files.get(A)??"";this.files.set(A,K+q),this.touch(A)}unlink(A){this.files.delete(A),this.mtimes.delete(A),this.modes.delete(A)}mkdirSync(A,q){this.dirs.add(A)}readdirSync(A){let q=A.endsWith("/")?A:`${A}/`,K=[];for(let F of this.files.keys()){if(!F.startsWith(q))continue;let Z=F.slice(q.length);if(!Z.includes("/"))K.push(Z)}return K}statSync(A){let q=this.mtimes.get(A);if(q===void 0)throw Error(`not found: ${A}`);return{mtimeMs:q,mode:this.modes.get(A)??null}}setMtime(A,q){this.mtimes.set(A,q)}setMode(A,q){this.modes.set(A,q)}touch(A){if(!this.mtimes.has(A))this.mtimes.set(A,this.now());else this.mtimes.set(A,this.now())}}class C4A extends uR{counter=0;prefix;constructor(A={}){super();this.prefix=A.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}import{join as xUK}from"path";var OUK=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,MUK=(A)=>{if(A.length<2)return A;let q=A[0],K=A[A.length-1];if(q==='"'&&K==='"')return A.slice(1,-1);if(q==="'"&&K==="'")return A.slice(1,-1);return A};class f4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=xUK(A,N3A);if(!this.fs.existsSync(q))return{};let K=this.fs.readFileSync(q),F={};for(let Z of K.split(`
1433
- `)){let $=Z.trim();if($===""||$.startsWith("#"))continue;let U=$.match(OUK);if(!U)continue;let Y=U[1],X=U[2];if(!Y)continue;F[Y]=MUK(X??"")}return F}}import{join as zUK}from"path";class h4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=zUK(A,Df);if(!this.fs.existsSync(q))return null;let K=this.fs.readFileSync(q),F=(()=>{try{return JSON.parse(K)}catch($){let U=$ instanceof Error?$.message:String($);throw Error(`${Df} is not valid JSON: ${U}`)}})(),Z=Bf.safeParse(F);if(!Z.success)throw Error(`${Df} is invalid: ${Z.error.message}`);return Z.data}}var IUK=(A,q)=>{if(A.length!==q.length)return!1;for(let K=0;K<A.length;K++)if(A[K]!==q[K])return!1;return!0},PUK=(A,q)=>{let K=Object.keys(A);if(K.length!==Object.keys(q).length)return!1;for(let F of K)if(A[F]!==q[F])return!1;return!0};class y4A{channels;dotenv;prompter;env;constructor(A){this.channels=A.channels,this.dotenv=A.dotenv,this.prompter=A.prompter,this.env=A.env??process.env,Object.freeze(this)}async ensure(A,q){let K=this.channels.get(A.name),F=A.resume??!0;if(!K)this.channels.add({name:A.name,options:A.options??[],env:A.env??{},resume:F});else{let X=A.options??[],j=A.env??{};if(!IUK(K.options,X))this.channels.setOptions(A.name,X);if(!PUK(K.env,j))this.channels.setEnv(A.name,j);if(K.resume!==F)this.channels.setResume(A.name,F)}if(A.connectors===void 0)return{touched:[],removed:[]};let Z=this.dotenv.read(q),$=[],U=new Set;for(let X of A.connectors){let j=await this.ensureConnector(A.name,X,Z);$.push({name:j.name,changed:j.changed}),U.add(j.id)}let Y=this.removeExtras(A.name,U);return{touched:$,removed:Y}}async ensureConnector(A,q,K){if(q.type==="slack")return await this.ensureSlack(A,q,K);if(q.type==="discord")return await this.ensureDiscord(A,q,K);if(q.type==="gh")return this.ensureGh(A,q);return this.ensureSchedule(A,q)}async ensureSlack(A,q,K){let F=this.findExistingSlack(A,q.name),Z=await this.resolveField({literal:q.botToken,envVar:q.env?.botToken,dotenv:K,label:`${q.name}.botToken`,existing:F?.botToken}),$=await this.resolveField({literal:q.appToken,envVar:q.env?.appToken,dotenv:K,label:`${q.name}.appToken`,existing:F?.appToken});if(F){if(F.botToken!==Z||F.appToken!==$)return this.channels.updateSlackConnector(A,q.name,{botToken:Z,appToken:$}),{id:F.id,name:q.name,changed:!0};return{id:F.id,name:q.name,changed:!1}}let U=this.findSlackByToken(A,[Z,$]);if(U){if(this.channels.renameConnector(A,U.name,q.name),U.botToken!==Z||U.appToken!==$)this.channels.updateSlackConnector(A,q.name,{botToken:Z,appToken:$});return{id:U.id,name:q.name,changed:!0}}return{id:this.channels.addConnector(A,{type:"slack",name:q.name,botToken:Z,appToken:$}).id,name:q.name,changed:!0}}async ensureDiscord(A,q,K){let F=this.findExistingDiscord(A,q.name),Z=await this.resolveField({literal:q.botToken,envVar:q.env?.botToken,dotenv:K,label:`${q.name}.botToken`,existing:F?.botToken});if(F){if(F.botToken!==Z)return this.channels.updateDiscordConnector(A,q.name,{botToken:Z}),{id:F.id,name:q.name,changed:!0};return{id:F.id,name:q.name,changed:!1}}let $=this.findDiscordByToken(A,Z);if($){if(this.channels.renameConnector(A,$.name,q.name),$.botToken!==Z)this.channels.updateDiscordConnector(A,q.name,{botToken:Z});return{id:$.id,name:q.name,changed:!0}}return{id:this.channels.addConnector(A,{type:"discord",name:q.name,botToken:Z}).id,name:q.name,changed:!0}}ensureGh(A,q){let K=this.channels.getConnector(A,q.name);if(K&&K.type!=="gh")throw Error(`connector "${q.name}" exists in channel "${A}" with type "${K.type}", funnel.json declares "gh"`);if(K&&K.type==="gh"){if(q.pollInterval!==void 0&&K.pollInterval!==q.pollInterval)return this.channels.updateGhConnector(A,q.name,{pollInterval:q.pollInterval}),{id:K.id,name:q.name,changed:!0};return{id:K.id,name:q.name,changed:!1}}return{id:this.channels.addConnector(A,{type:"gh",name:q.name,...q.pollInterval!==void 0?{pollInterval:q.pollInterval}:{}}).id,name:q.name,changed:!0}}ensureSchedule(A,q){let K=this.channels.getConnector(A,q.name);if(K&&K.type!=="schedule")throw Error(`connector "${q.name}" exists in channel "${A}" with type "${K.type}", funnel.json declares "schedule"`);if(K&&K.type==="schedule")return{id:K.id,name:q.name,changed:!1};return{id:this.channels.addConnector(A,{type:"schedule",name:q.name}).id,name:q.name,changed:!0}}findExistingSlack(A,q){let K=this.channels.getConnector(A,q);if(!K)return null;if(K.type!=="slack")throw Error(`connector "${q}" exists in channel "${A}" with type "${K.type}", funnel.json declares "slack"`);return K}findExistingDiscord(A,q){let K=this.channels.getConnector(A,q);if(!K)return null;if(K.type!=="discord")throw Error(`connector "${q}" exists in channel "${A}" with type "${K.type}", funnel.json declares "discord"`);return K}findSlackByToken(A,q){let K=this.channels.get(A);if(!K)return null;for(let F of K.connectors){if(F.type!=="slack")continue;if(q.includes(F.botToken)||q.includes(F.appToken))return F}return null}findDiscordByToken(A,q){let K=this.channels.get(A);if(!K)return null;for(let F of K.connectors){if(F.type!=="discord")continue;if(F.botToken===q)return F}return null}removeExtras(A,q){let K=this.channels.get(A);if(!K)return[];let F=K.connectors.filter((Z)=>!q.has(Z.id));for(let Z of F)this.channels.removeConnector(A,Z.name);return F.map((Z)=>Z.name)}async resolveField(A){if(A.literal!==void 0&&A.envVar!==void 0)throw Error(`${A.label} is set both as a literal and as env.${A.label.split(".").pop()}; pick one`);if(A.literal!==void 0&&A.literal!=="")return A.literal;if(A.envVar!==void 0&&A.envVar!==""){let q=this.env[A.envVar];if(q)return q;let K=A.dotenv[A.envVar];if(K)return K;throw Error(`${A.label} references env var "${A.envVar}" but it is not set in process env or .env.local`)}if(A.existing)return A.existing;return await this.prompter.promptSecret(A.label)}}class u4A extends QV{file=null;entries=[];info(A,q){this.entries.push({level:"info",message:A,meta:q})}warn(A,q){this.entries.push({level:"warn",message:A,meta:q})}error(A,q){this.entries.push({level:"error",message:A,meta:q})}clear(){this.entries.length=0}}var Jzq={exitCode:0,stdout:"",stderr:""};class c4A extends ew{calls=[];killed=[];handler=()=>Jzq;syncHandler=()=>Jzq;aliveStub=null;listStub=null;on(A){return this.handler=A,this}onSync(A){return this.syncHandler=A,this}onIsAlive(A){return this.aliveStub=A,this}onListProcessesContaining(A){return this.listStub=A,this}async run(A,q={}){this.calls.push({kind:"run",command:A,options:q});let K=await this.handler(A);return{exitCode:K.exitCode??0,stdout:K.stdout??"",stderr:K.stderr??""}}runSync(A){this.calls.push({kind:"runSync",command:A});let q=this.syncHandler(A);return{exitCode:q.exitCode??0,stdout:q.stdout??"",stderr:q.stderr??""}}async attach(A,q={}){if(this.calls.push({kind:"attach",command:A,options:q}),q.onSpawned)q.onSpawned(1);return(await this.handler(A)).exitCode??0}detach(A,q={}){this.calls.push({kind:"detach",command:A,options:q})}kill(A,q="SIGTERM"){this.calls.push({kind:"kill",command:[String(A),q]}),this.killed.push({pid:A,signal:q})}isAlive(A){if(this.aliveStub)return this.aliveStub(A);let q=this.syncHandler(["ps","-p",String(A),"-o","state="]);if((q.exitCode??0)!==0)return!1;let K=(q.stdout??"").trim();if(!K)return!1;return!K.startsWith("Z")}listProcessesContaining(A){if(this.listStub)return this.listStub(A);return[]}}class m4A{store;constructor(A){this.store=A.store,Object.freeze(this)}list(){return this.store.read().profiles}get(A){return this.list().find((q)=>q.name===A)??null}getDefault(){return this.list()[0]??null}add(A){let q=this.store.read();if(q.profiles.some((K)=>K.name===A.name))throw Error(`profile "${A.name}" already exists`);if(!q.channels.some((K)=>K.id===A.channelId))throw Error(`channel id "${A.channelId}" not found`);q.profiles.push(A),this.store.write(q)}remove(A){let q=this.store.read(),K=q.profiles.findIndex((F)=>F.name===A);if(K<0)throw Error(`profile "${A}" not found`);q.profiles.splice(K,1),this.store.write(q)}rename(A,q){let K=this.store.read(),F=K.profiles.find((Z)=>Z.name===A);if(!F)throw Error(`profile "${A}" not found`);if(K.profiles.some((Z)=>Z.name===q))throw Error(`profile "${q}" already exists`);F.name=q,this.store.write(K)}asDefault(A){let q=this.store.read(),K=q.profiles.findIndex((Z)=>Z.name===A);if(K<0)throw Error(`profile "${A}" not found`);if(K===0)return;let[F]=q.profiles.splice(K,1);if(!F)return;q.profiles.unshift(F),this.store.write(q)}hasChannelRef(A){return this.store.read().profiles.some((q)=>q.channelId===A)}update(A,q){let K=this.store.read(),F=K.profiles.find((Z)=>Z.name===A);if(!F)throw Error(`profile "${A}" not found`);if(q.channelId!==void 0){if(!K.channels.some((Z)=>Z.id===q.channelId))throw Error(`channel id "${q.channelId}" not found`);F.channelId=q.channelId}if(q.path!==void 0)F.path=q.path;this.store.write(K)}}import{join as Hzq}from"path";var NUK=c.record(c.string(),c.string());class p4A{fs;idGenerator;dir;constructor(A){this.fs=A.fs,this.idGenerator=A.idGenerator,this.dir=A.dir,Object.freeze(this)}getOrCreate(A,q){let K=this.readMap(A),F=K[q];if(F)return F;let Z=this.idGenerator.generate();return K[q]=Z,this.writeMap(A,K),Z}get(A,q){return this.readMap(A)[q]??null}clear(A,q){let K=this.readMap(A);if(!(q in K))return;delete K[q],this.writeMap(A,K)}clearAll(A){let q=this.pathFor(A);if(this.fs.existsSync(q))this.fs.unlink(q)}readMap(A){let q=this.pathFor(A);if(!this.fs.existsSync(q))return{};let K=this.fs.readFileSync(q);try{let F=NUK.safeParse(JSON.parse(K));return F.success?F.data:{}}catch{return{}}}writeMap(A,q){let K=this.pathFor(A),F=this.channelDir(A);if(!this.fs.existsSync(F))this.fs.mkdirSync(F,{recursive:!0});this.fs.writeFileSync(K,`${JSON.stringify(q,null,2)}
1432
+ `)}}import{join as R4A}from"path";var XUK=new FY,GUK=new jY,jUK=new w$;class T4A{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor(A={}){this.fs=A.fs??XUK,this.process=A.process??GUK,this.logger=A.logger??jUK,this.dir=A.dir??c8,this.slackListenerOptions=A.slackListenerOptions??{},this.scheduleListenerOptions=A.scheduleListenerOptions??{},Object.freeze(this)}createListener(A,q){if(q.type==="slack")return new B4A({config:q,logger:this.logger,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(q.type==="gh")return new dYA({config:q,process:this.process,logger:this.logger});if(q.type==="discord")return new iYA({config:q,logger:this.logger});let K=new sYA({path:R4A(this.connectorDir(A,q.id),"state.json"),fs:this.fs});return new nYA({config:q,lastFiredStore:K,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter(A){if(A.type==="slack")return new P0A({config:A});if(A.type==="gh")return new aYA({process:this.process});if(A.type==="discord")return new rKA({config:A});return null}connectorDir(A,q){return R4A(this.dir,"channels",A,"connectors",q)}channelDir(A){return R4A(this.dir,"channels",A)}}function S4A(A){switch(A.type){case"slack":return[A.botToken,A.appToken];case"discord":return[A.botToken];case"gh":case"schedule":return[]}}function JUK(A,q){return A.type===q}function bL(A,q,K){let F=A.connectors.find((Z)=>Z.name===q);if(!F)throw Error(`connector "${q}" not found in channel "${A.name}"`);if(!JUK(F,K))throw Error(`connector "${q}" is type "${F.type}", not "${K}"`);return F}class yR{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class vL extends yR{now(){return new Date}}class uR{}class cR extends uR{generate(){return crypto.randomUUID()}}var HUK=new vL,EUK=new cR;class b4A{store;factory;profileChecker;clock;idGenerator;constructor(A){this.store=A.store,this.factory=A.factory,this.profileChecker=A.profileChecker,this.clock=A.clock??HUK,this.idGenerator=A.idGenerator??EUK,Object.freeze(this)}list(){return this.store.read().channels}get(A){return this.list().find((q)=>q.name===A)??null}getById(A){return this.list().find((q)=>q.id===A)??null}add(A){let q=this.store.read();if(q.channels.some((F)=>F.name===A.name))throw Error(`channel "${A.name}" already exists`);let K={id:this.idGenerator.generate(),name:A.name,delivery:A.delivery??"fanout",options:A.options??[],env:A.env??{},resume:A.resume??!0,connectors:[]};return q.channels.push(K),this.store.write(q),K}setDelivery(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.delivery=q,this.store.write(K)}setResume(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.resume=q,this.store.write(K)}setOptions(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.options=q,this.store.write(K)}setEnv(A,q){let K=this.store.read(),F=this.requireChannel(K,A);F.env=q,this.store.write(K)}remove(A){let q=this.store.read(),K=q.channels.findIndex((Z)=>Z.name===A);if(K<0)throw Error(`channel "${A}" not found`);let F=q.channels[K];if(F&&this.profileChecker.hasChannelRef(F.id))throw Error(`channel "${A}" is referenced by a profile`);q.channels.splice(K,1),this.store.write(q)}rename(A,q){let K=this.store.read(),F=K.channels.find((Z)=>Z.name===A);if(!F)throw Error(`channel "${A}" not found`);if(K.channels.some((Z)=>Z.name===q))throw Error(`channel "${q}" already exists`);F.name=q,this.store.write(K)}listConnectors(A){return this.requireChannel(this.store.read(),A).connectors}getConnector(A,q){let K=this.get(A);if(!K)return null;return K.connectors.find((F)=>F.name===q)??null}listAllConnectors(){let A=[];for(let q of this.list())for(let K of q.connectors)A.push({...K,channelId:q.id,channelName:q.name});return A}addConnector(A,q){let K=this.store.read(),F=this.requireChannel(K,A);if(F.connectors.some(($)=>$.name===q.name))throw Error(`connector "${q.name}" already exists in channel "${A}"`);let Z=this.fromInput(q);return this.assertNoTokenCollision(K,Z),F.connectors.push(Z),this.store.write(K),Z}fromInput(A){let q=this.idGenerator.generate(),K=this.clock.iso(),F=K,Z=K;switch(A.type){case"slack":return{id:q,type:"slack",name:A.name,botToken:A.botToken,appToken:A.appToken,createdAt:F,updatedAt:Z};case"gh":return{id:q,type:"gh",name:A.name,...A.pollInterval!==void 0?{pollInterval:A.pollInterval}:{},createdAt:F,updatedAt:Z};case"discord":return{id:q,type:"discord",name:A.name,botToken:A.botToken,createdAt:F,updatedAt:Z};case"schedule":return{id:q,type:"schedule",name:A.name,entries:A.entries??[],createdAt:F,updatedAt:Z}}}removeConnector(A,q){let K=this.store.read(),F=this.requireChannel(K,A),Z=F.connectors.findIndex(($)=>$.name===q);if(Z<0)throw Error(`connector "${q}" not found in channel "${A}"`);F.connectors.splice(Z,1),this.store.write(K)}renameConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=Z.connectors.find((U)=>U.name===q);if(!$)throw Error(`connector "${q}" not found in channel "${A}"`);if(Z.connectors.some((U)=>U.name===K))throw Error(`connector "${K}" already exists in channel "${A}"`);$.name=K,$.updatedAt=this.clock.iso(),this.store.write(F)}updateSlackConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"slack"),U={...$,botToken:K.botToken??$.botToken,appToken:K.appToken??$.appToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(F,U),Object.assign($,U),this.store.write(F)}updateGhConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"gh");if(K.pollInterval!==void 0)$.pollInterval=K.pollInterval;$.updatedAt=this.clock.iso(),this.store.write(F)}updateDiscordConnector(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"discord"),U={...$,botToken:K.botToken??$.botToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(F,U),Object.assign($,U),this.store.write(F)}listScheduleEntries(A,q){let K=this.requireChannel(this.store.read(),A);return bL(K,q,"schedule").entries}addScheduleEntry(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"schedule"),U={id:K.id??this.idGenerator.generate(),cron:K.cron,prompt:K.prompt,enabled:K.enabled??!0,catchupPolicy:K.catchupPolicy??"latest"};return $.entries.push(U),$.updatedAt=this.clock.iso(),this.store.write(F),U}removeScheduleEntry(A,q,K){let F=this.store.read(),Z=this.requireChannel(F,A),$=bL(Z,q,"schedule"),U=$.entries.findIndex((Y)=>Y.id===K);if(U<0)throw Error(`schedule entry "${K}" not found`);$.entries.splice(U,1),$.updatedAt=this.clock.iso(),this.store.write(F)}async call(A,q,K){let F=this.getConnector(A,q);if(!F)throw Error(`connector "${q}" not found in channel "${A}"`);let Z=this.factory.createAdapter(F);if(!Z)throw Error(`connector type "${F.type}" does not support outbound calls`);return await Z.call(K)}createListener(A,q){let K=this.get(A);if(!K)return null;let F=K.connectors.find((Z)=>Z.name===q);if(!F)return null;return{config:F,channelId:K.id,listener:this.factory.createListener(K.id,F)}}createAllListeners(){let A=[];for(let q of this.list())for(let K of q.connectors)A.push({config:K,channelId:q.id,channelName:q.name,listener:this.factory.createListener(q.id,K)});return A}requireChannel(A,q){let K=A.channels.find((F)=>F.name===q);if(!K)throw Error(`channel "${q}" not found`);return K}assertNoTokenCollision(A,q){let K=S4A(q);if(K.length===0)return;for(let F of A.channels)for(let Z of F.connectors){if(Z.id===q.id)continue;for(let $ of S4A(Z))if(K.includes($))throw Error(`token already in use by connector "${Z.name}" in channel "${F.name}"`)}}}import{join as jzq}from"path";var WUK=new jY,gUK=new FY,VUK=new w$;class v4A{channels;mcp;gateway;sessions;process;fs;logger;pidDir;constructor(A){this.channels=A.channels,this.mcp=A.mcp,this.gateway=A.gateway,this.sessions=A.sessions,this.process=A.process??WUK,this.fs=A.fs??gUK,this.logger=A.logger??VUK,this.pidDir=jzq(A.dir??c8,"claude"),Object.freeze(this)}async launch(A){let q=this.channels.get(A.channel)??this.channels.getById(A.channel);if(!q)throw Error(`channel "${A.channel}" not found`);if(A.profileName&&this.isRunning(A.profileName))throw Error(`profile "${A.profileName}" is already running`);let K=A.cwd??globalThis.process.cwd();if((A.installMcp??!0)&&!this.mcp.findInstalledName(K))this.mcp.install(K),this.logger.info("added funnel MCP to .mcp.json",{cwd:K});if(!this.gateway.isRunning())this.logger.info("starting gateway automatically"),await this.gateway.start();if(A.profileName)this.writePidFile(A.profileName),this.installCleanup(A.profileName);let Z=q.resume?this.resolveSession(q.id,K,A.userArgs??[]):null,$=this.buildArgs(q.options,A.userArgs??[],K,Z),U=this.buildEnv(q.id,q.env);this.logger.info("claude launch",{channel:A.channel,channelId:q.id,cwd:K});try{return await this.process.attach(["claude",...$],{cwd:K,env:U,onSpawned:A.onSpawned})}finally{if(A.profileName)this.removePidFile(A.profileName)}}isRunning(A){let q=this.readPid(A);if(!q)return!1;return this.isProcessAlive(q)}pidPath(A){return jzq(this.pidDir,`${A}.pid`)}readPid(A){let q=this.pidPath(A);if(!this.fs.existsSync(q))return null;try{let K=this.fs.readFileSync(q).trim(),F=Number(K);if(!F||F<=0)return null;return F}catch{return null}}writePidFile(A){this.fs.mkdirSync(this.pidDir,{recursive:!0}),this.fs.writeFileSync(this.pidPath(A),String(globalThis.process.pid))}removePidFile(A){let q=this.pidPath(A);if(this.fs.existsSync(q))this.fs.unlink(q)}installCleanup(A){globalThis.process.once("exit",()=>this.removePidFile(A))}isProcessAlive(A){return this.process.isAlive(A)}buildArgs(A,q,K,F){let Z=[...A,...q];if(F!==null)if(F.mode==="resume")Z.push("--resume",F.id);else Z.push("--session-id",F.id);let $=this.mcp.findInstalledName(K);if($&&!Z.includes("--dangerously-load-development-channels")&&!Z.includes("--channels"))Z.push("--dangerously-load-development-channels",`server:${$}`);return Z}resolveSession(A,q,K){for(let Z of K){if(Z==="-c"||Z==="--continue")return null;if(Z==="--resume"||Z.startsWith("--resume="))return null;if(Z==="--session-id"||Z.startsWith("--session-id="))return null}let F=this.sessions.get(A,q);if(F!==null)return{id:F,mode:"resume"};return{id:this.sessions.create(A,q),mode:"new"}}buildEnv(A,q){let K={};for(let[F,Z]of Object.entries(q))K[F]=Z;for(let[F,Z]of Object.entries(globalThis.process.env))if(typeof Z==="string")K[F]=Z;return K.FUNNEL_CHANNEL_ID=A,K}}var LUK=384;class k4A extends G_{dirs;files;mtimes;modes;now;constructor(A={}){super();this.dirs=new Set(A.dirs??[]),this.files=new Map(Object.entries(A.files??{})),this.mtimes=new Map(Object.entries(A.mtimes??{})),this.modes=new Map(Object.entries(A.modes??{})),this.now=A.now??(()=>Date.now())}existsSync(A){return this.dirs.has(A)||this.files.has(A)}readFileSync(A){return this.files.get(A)??""}writeFileSync(A,q){this.files.set(A,q),this.touch(A)}writeSecretFileSync(A,q){this.files.set(A,q),this.modes.set(A,LUK),this.touch(A)}appendFileSync(A,q){let K=this.files.get(A)??"";this.files.set(A,K+q),this.touch(A)}unlink(A){this.files.delete(A),this.mtimes.delete(A),this.modes.delete(A)}mkdirSync(A,q){this.dirs.add(A)}readdirSync(A){let q=A.endsWith("/")?A:`${A}/`,K=[];for(let F of this.files.keys()){if(!F.startsWith(q))continue;let Z=F.slice(q.length);if(!Z.includes("/"))K.push(Z)}return K}statSync(A){let q=this.mtimes.get(A);if(q===void 0)throw Error(`not found: ${A}`);return{mtimeMs:q,mode:this.modes.get(A)??null}}setMtime(A,q){this.mtimes.set(A,q)}setMode(A,q){this.modes.set(A,q)}touch(A){if(!this.mtimes.has(A))this.mtimes.set(A,this.now());else this.mtimes.set(A,this.now())}}class C4A extends uR{counter=0;prefix;constructor(A={}){super();this.prefix=A.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}import{join as xUK}from"path";var OUK=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,MUK=(A)=>{if(A.length<2)return A;let q=A[0],K=A[A.length-1];if(q==='"'&&K==='"')return A.slice(1,-1);if(q==="'"&&K==="'")return A.slice(1,-1);return A};class f4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=xUK(A,N3A);if(!this.fs.existsSync(q))return{};let K=this.fs.readFileSync(q),F={};for(let Z of K.split(`
1433
+ `)){let $=Z.trim();if($===""||$.startsWith("#"))continue;let U=$.match(OUK);if(!U)continue;let Y=U[1],X=U[2];if(!Y)continue;F[Y]=MUK(X??"")}return F}}import{join as zUK}from"path";class h4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=zUK(A,Df);if(!this.fs.existsSync(q))return null;let K=this.fs.readFileSync(q),F=(()=>{try{return JSON.parse(K)}catch($){let U=$ instanceof Error?$.message:String($);throw Error(`${Df} is not valid JSON: ${U}`)}})(),Z=Bf.safeParse(F);if(!Z.success)throw Error(`${Df} is invalid: ${Z.error.message}`);return Z.data}}var IUK=(A,q)=>{if(A.length!==q.length)return!1;for(let K=0;K<A.length;K++)if(A[K]!==q[K])return!1;return!0},PUK=(A,q)=>{let K=Object.keys(A);if(K.length!==Object.keys(q).length)return!1;for(let F of K)if(A[F]!==q[F])return!1;return!0};class y4A{channels;dotenv;prompter;env;constructor(A){this.channels=A.channels,this.dotenv=A.dotenv,this.prompter=A.prompter,this.env=A.env??process.env,Object.freeze(this)}async ensure(A,q){let K=this.channels.get(A.name),F=A.resume??!0;if(!K)this.channels.add({name:A.name,options:A.options??[],env:A.env??{},resume:F});else{let X=A.options??[],j=A.env??{};if(!IUK(K.options,X))this.channels.setOptions(A.name,X);if(!PUK(K.env,j))this.channels.setEnv(A.name,j);if(K.resume!==F)this.channels.setResume(A.name,F)}if(A.connectors===void 0)return{touched:[],removed:[]};let Z=this.dotenv.read(q),$=[],U=new Set;for(let X of A.connectors){let j=await this.ensureConnector(A.name,X,Z);$.push({name:j.name,changed:j.changed}),U.add(j.id)}let Y=this.removeExtras(A.name,U);return{touched:$,removed:Y}}async ensureConnector(A,q,K){if(q.type==="slack")return await this.ensureSlack(A,q,K);if(q.type==="discord")return await this.ensureDiscord(A,q,K);if(q.type==="gh")return this.ensureGh(A,q);return this.ensureSchedule(A,q)}async ensureSlack(A,q,K){let F=this.findExistingSlack(A,q.name),Z=await this.resolveField({literal:q.botToken,envVar:q.env?.botToken,dotenv:K,label:`${q.name}.botToken`,existing:F?.botToken}),$=await this.resolveField({literal:q.appToken,envVar:q.env?.appToken,dotenv:K,label:`${q.name}.appToken`,existing:F?.appToken});if(F){if(F.botToken!==Z||F.appToken!==$)return this.channels.updateSlackConnector(A,q.name,{botToken:Z,appToken:$}),{id:F.id,name:q.name,changed:!0};return{id:F.id,name:q.name,changed:!1}}let U=this.findSlackByToken(A,[Z,$]);if(U){if(this.channels.renameConnector(A,U.name,q.name),U.botToken!==Z||U.appToken!==$)this.channels.updateSlackConnector(A,q.name,{botToken:Z,appToken:$});return{id:U.id,name:q.name,changed:!0}}return{id:this.channels.addConnector(A,{type:"slack",name:q.name,botToken:Z,appToken:$}).id,name:q.name,changed:!0}}async ensureDiscord(A,q,K){let F=this.findExistingDiscord(A,q.name),Z=await this.resolveField({literal:q.botToken,envVar:q.env?.botToken,dotenv:K,label:`${q.name}.botToken`,existing:F?.botToken});if(F){if(F.botToken!==Z)return this.channels.updateDiscordConnector(A,q.name,{botToken:Z}),{id:F.id,name:q.name,changed:!0};return{id:F.id,name:q.name,changed:!1}}let $=this.findDiscordByToken(A,Z);if($){if(this.channels.renameConnector(A,$.name,q.name),$.botToken!==Z)this.channels.updateDiscordConnector(A,q.name,{botToken:Z});return{id:$.id,name:q.name,changed:!0}}return{id:this.channels.addConnector(A,{type:"discord",name:q.name,botToken:Z}).id,name:q.name,changed:!0}}ensureGh(A,q){let K=this.channels.getConnector(A,q.name);if(K&&K.type!=="gh")throw Error(`connector "${q.name}" exists in channel "${A}" with type "${K.type}", funnel.json declares "gh"`);if(K&&K.type==="gh"){if(q.pollInterval!==void 0&&K.pollInterval!==q.pollInterval)return this.channels.updateGhConnector(A,q.name,{pollInterval:q.pollInterval}),{id:K.id,name:q.name,changed:!0};return{id:K.id,name:q.name,changed:!1}}return{id:this.channels.addConnector(A,{type:"gh",name:q.name,...q.pollInterval!==void 0?{pollInterval:q.pollInterval}:{}}).id,name:q.name,changed:!0}}ensureSchedule(A,q){let K=this.channels.getConnector(A,q.name);if(K&&K.type!=="schedule")throw Error(`connector "${q.name}" exists in channel "${A}" with type "${K.type}", funnel.json declares "schedule"`);if(K&&K.type==="schedule")return{id:K.id,name:q.name,changed:!1};return{id:this.channels.addConnector(A,{type:"schedule",name:q.name}).id,name:q.name,changed:!0}}findExistingSlack(A,q){let K=this.channels.getConnector(A,q);if(!K)return null;if(K.type!=="slack")throw Error(`connector "${q}" exists in channel "${A}" with type "${K.type}", funnel.json declares "slack"`);return K}findExistingDiscord(A,q){let K=this.channels.getConnector(A,q);if(!K)return null;if(K.type!=="discord")throw Error(`connector "${q}" exists in channel "${A}" with type "${K.type}", funnel.json declares "discord"`);return K}findSlackByToken(A,q){let K=this.channels.get(A);if(!K)return null;for(let F of K.connectors){if(F.type!=="slack")continue;if(q.includes(F.botToken)||q.includes(F.appToken))return F}return null}findDiscordByToken(A,q){let K=this.channels.get(A);if(!K)return null;for(let F of K.connectors){if(F.type!=="discord")continue;if(F.botToken===q)return F}return null}removeExtras(A,q){let K=this.channels.get(A);if(!K)return[];let F=K.connectors.filter((Z)=>!q.has(Z.id));for(let Z of F)this.channels.removeConnector(A,Z.name);return F.map((Z)=>Z.name)}async resolveField(A){if(A.literal!==void 0&&A.envVar!==void 0)throw Error(`${A.label} is set both as a literal and as env.${A.label.split(".").pop()}; pick one`);if(A.literal!==void 0&&A.literal!=="")return A.literal;if(A.envVar!==void 0&&A.envVar!==""){let q=this.env[A.envVar];if(q)return q;let K=A.dotenv[A.envVar];if(K)return K;throw Error(`${A.label} references env var "${A.envVar}" but it is not set in process env or .env.local`)}if(A.existing)return A.existing;return await this.prompter.promptSecret(A.label)}}class u4A extends QV{file=null;entries=[];info(A,q){this.entries.push({level:"info",message:A,meta:q})}warn(A,q){this.entries.push({level:"warn",message:A,meta:q})}error(A,q){this.entries.push({level:"error",message:A,meta:q})}clear(){this.entries.length=0}}var Jzq={exitCode:0,stdout:"",stderr:""};class c4A extends ew{calls=[];killed=[];handler=()=>Jzq;syncHandler=()=>Jzq;aliveStub=null;listStub=null;on(A){return this.handler=A,this}onSync(A){return this.syncHandler=A,this}onIsAlive(A){return this.aliveStub=A,this}onListProcessesContaining(A){return this.listStub=A,this}async run(A,q={}){this.calls.push({kind:"run",command:A,options:q});let K=await this.handler(A);return{exitCode:K.exitCode??0,stdout:K.stdout??"",stderr:K.stderr??""}}runSync(A){this.calls.push({kind:"runSync",command:A});let q=this.syncHandler(A);return{exitCode:q.exitCode??0,stdout:q.stdout??"",stderr:q.stderr??""}}async attach(A,q={}){if(this.calls.push({kind:"attach",command:A,options:q}),q.onSpawned)q.onSpawned(1);return(await this.handler(A)).exitCode??0}detach(A,q={}){this.calls.push({kind:"detach",command:A,options:q})}kill(A,q="SIGTERM"){this.calls.push({kind:"kill",command:[String(A),q]}),this.killed.push({pid:A,signal:q})}isAlive(A){if(this.aliveStub)return this.aliveStub(A);let q=this.syncHandler(["ps","-p",String(A),"-o","state="]);if((q.exitCode??0)!==0)return!1;let K=(q.stdout??"").trim();if(!K)return!1;return!K.startsWith("Z")}listProcessesContaining(A){if(this.listStub)return this.listStub(A);return[]}}class m4A{store;constructor(A){this.store=A.store,Object.freeze(this)}list(){return this.store.read().profiles}get(A){return this.list().find((q)=>q.name===A)??null}getDefault(){return this.list()[0]??null}add(A){let q=this.store.read();if(q.profiles.some((K)=>K.name===A.name))throw Error(`profile "${A.name}" already exists`);if(!q.channels.some((K)=>K.id===A.channelId))throw Error(`channel id "${A.channelId}" not found`);q.profiles.push(A),this.store.write(q)}remove(A){let q=this.store.read(),K=q.profiles.findIndex((F)=>F.name===A);if(K<0)throw Error(`profile "${A}" not found`);q.profiles.splice(K,1),this.store.write(q)}rename(A,q){let K=this.store.read(),F=K.profiles.find((Z)=>Z.name===A);if(!F)throw Error(`profile "${A}" not found`);if(K.profiles.some((Z)=>Z.name===q))throw Error(`profile "${q}" already exists`);F.name=q,this.store.write(K)}asDefault(A){let q=this.store.read(),K=q.profiles.findIndex((Z)=>Z.name===A);if(K<0)throw Error(`profile "${A}" not found`);if(K===0)return;let[F]=q.profiles.splice(K,1);if(!F)return;q.profiles.unshift(F),this.store.write(q)}hasChannelRef(A){return this.store.read().profiles.some((q)=>q.channelId===A)}update(A,q){let K=this.store.read(),F=K.profiles.find((Z)=>Z.name===A);if(!F)throw Error(`profile "${A}" not found`);if(q.channelId!==void 0){if(!K.channels.some((Z)=>Z.id===q.channelId))throw Error(`channel id "${q.channelId}" not found`);F.channelId=q.channelId}if(q.path!==void 0)F.path=q.path;this.store.write(K)}}import{join as Hzq}from"path";var NUK=c.record(c.string(),c.string());class p4A{fs;idGenerator;dir;constructor(A){this.fs=A.fs,this.idGenerator=A.idGenerator,this.dir=A.dir,Object.freeze(this)}get(A,q){return this.readMap(A)[q]??null}create(A,q){let K=this.readMap(A),F=this.idGenerator.generate();return K[q]=F,this.writeMap(A,K),F}clear(A,q){let K=this.readMap(A);if(!(q in K))return;delete K[q],this.writeMap(A,K)}clearAll(A){let q=this.pathFor(A);if(this.fs.existsSync(q))this.fs.unlink(q)}readMap(A){let q=this.pathFor(A);if(!this.fs.existsSync(q))return{};let K=this.fs.readFileSync(q);try{let F=NUK.safeParse(JSON.parse(K));return F.success?F.data:{}}catch{return{}}}writeMap(A,q){let K=this.pathFor(A),F=this.channelDir(A);if(!this.fs.existsSync(F))this.fs.mkdirSync(F,{recursive:!0});this.fs.writeFileSync(K,`${JSON.stringify(q,null,2)}
1434
1434
  `)}channelDir(A){return Hzq(this.dir,"channels",A)}pathFor(A){return Hzq(this.channelDir(A),"sessions.json")}}import{stderr as tp,stdin as $7}from"process";class l4A{}var _UK="*",wUK="\r",Ezq=`
1435
1435
  `,BUK=String.fromCharCode(8),DUK=String.fromCharCode(127),RUK=String.fromCharCode(3),TUK=String.fromCharCode(4);class i4A extends l4A{async promptSecret(A){if(!$7.isTTY)throw Error(`cannot prompt for "${A}": stdin is not a TTY. Set the matching env var or run \`fnl channels <ch> connectors add ...\` first.`);tp.write(`${A}: `);let q=$7.isRaw;$7.setRawMode(!0),$7.resume();try{return await this.readSecret()}finally{$7.setRawMode(q),$7.pause(),tp.write(Ezq)}}readSecret(){return new Promise((A,q)=>{let K="",F=(Z)=>{for(let $ of Z){let U=String.fromCharCode($);if(U===Ezq||U===wUK){$7.off("data",F),A(K);return}if(U===RUK){$7.off("data",F),q(Error("prompt cancelled"));return}if(U===TUK){if($7.off("data",F),K.length===0)q(Error("prompt cancelled"));else A(K);return}if(U===BUK||U===DUK){if(K.length>0)K=K.slice(0,-1),tp.write("\b \b");continue}K+=U,tp.write(_UK)}};$7.on("data",F)})}}var SUK=(A={})=>({version:VJ,channels:[],profiles:[],...A});class a4A extends hR{state;constructor(A){super();this.state=SUK(A)}read(){return this.state}write(A){this.state=A}}class d4A extends yR{current;constructor(A={}){super();this.current=A.start??new Date(0)}now(){return new Date(this.current.getTime())}set(A){this.current=A}advance(A){this.current=new Date(this.current.getTime()+A)}}var Wzq=c.object({content:c.string().min(1),meta:c.record(c.string(),c.string()).optional(),connector:c.string().min(1).optional()}),gzq=c.object({ok:c.literal(!0),offset:c.number().int().nonnegative()});var bUK={state:"offline"};class n4A{port;isDaemonRunning;getToken;constructor(A){this.port=A.port,this.isDaemonRunning=A.isDaemonRunning,this.getToken=A.getToken??(()=>null),Object.freeze(this)}async publish(A,q){if(!this.isDaemonRunning())return bUK;try{let K=`http://localhost:${this.port}/channels/${encodeURIComponent(A)}/publish`,F=await fetch(K,{method:"POST",headers:{...this.authHeaders(),"content-type":"application/json"},body:JSON.stringify(q)});if(!F.ok)return{state:"error",reason:await F.text()||`HTTP ${F.status}`};let Z=gzq.safeParse(await F.json());if(!Z.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",offset:Z.data.offset}}catch(K){return{state:"error",reason:K instanceof Error?K.message:String(K)}}}authHeaders(){let A=this.getToken();return A?{authorization:`Bearer ${A}`}:{}}}import{join as Vzq}from"path";var vUK=9742,kUK=5000,CUK=2000,Lzq=100,fUK=200,hUK=new jY,yUK=new FY,uUK=new vL,cUK=(A)=>new Promise((q)=>{setTimeout(q,A)});class s4A{process;fs;clock;dir;pidFile;gatewayLog;tmpDir;port;sleep;constructor(A={}){this.process=A.process??hUK,this.fs=A.fs??yUK,this.clock=A.clock??uUK,this.dir=A.dir??c8,this.tmpDir=A.tmpDir??T8(),this.pidFile=Vzq(this.dir,"gateway.pid"),this.gatewayLog=Vzq(this.tmpDir,"gateway.log"),this.port=A.port??vUK,this.sleep=A.sleep??cUK,Object.freeze(this)}isRunning(){let A=this.readPid();if(!A)return!1;return this.isProcessAlive(A)}getStatus(){let A=this.readPid(),q=A!==null&&this.isProcessAlive(A);return{running:q,pid:q?A:null,port:this.port}}async start(A={}){if(this.isRunning())return!0;this.fs.mkdirSync(this.tmpDir,{recursive:!0});let q=_f(),K=this.buildStartCommand(q,A);this.process.detach(K,{stdoutFile:this.gatewayLog,stderrFile:this.gatewayLog});let F=this.clock.millis()+kUK;while(this.clock.millis()<F){if(this.isRunning())return!0;await this.sleep(Lzq)}return this.isRunning()}buildStartCommand(A,q={}){let K=`funnel-gateway[${this.dir}]`;if(q.caffeinate!==!1&&globalThis.process.platform==="darwin")return["caffeinate","-is","bun",A,K];return["bun",A,K]}async stop(){let A=this.readPid();if(!A)return!0;if(!this.isProcessAlive(A))return this.removePid(),!0;try{this.process.kill(A,"SIGTERM")}catch{return!1}let q=this.clock.millis()+CUK;while(this.clock.millis()<q){if(!this.isProcessAlive(A))return this.removePid(),!0;await this.sleep(Lzq)}try{this.process.kill(A,"SIGKILL")}catch{}return await this.sleep(fUK),this.removePid(),!this.isProcessAlive(A)}async restart(A={}){let q=this.isRunning();if(A.onlyIfRunning&&!q)return{ok:!0,wasRunning:!1,stopped:!1,started:!1};let K=q?await this.stop():!0;if(!K)return{ok:!1,wasRunning:q,stopped:!1,started:!1};let F=await this.start({caffeinate:A.caffeinate});return{ok:F,wasRunning:q,stopped:K,started:F}}getGatewayLog(){return this.gatewayLog}getPort(){return this.port}readPid(){if(!this.fs.existsSync(this.pidFile))return null;try{let A=this.fs.readFileSync(this.pidFile).trim(),q=Number(A);if(!q||q<=0)return null;return q}catch{return null}}removePid(){this.fs.unlink(this.pidFile)}isProcessAlive(A){return this.process.isAlive(A)}}import{existsSync as QYK,mkdirSync as XYK}from"fs";import{dirname as GYK,join as jYK}from"path";import{timingSafeEqual as mUK}from"crypto";var ep=(A)=>{return async(q,K)=>{let $=(q.req.header("authorization")??"").match(/^Bearer\s+(.+)$/i)?.[1]??"";if(!Al($,A.expected))return q.text("unauthorized",401);return await K()}},Al=(A,q)=>{let K=Buffer.from(A,"utf-8"),F=Buffer.from(q,"utf-8"),Z=Math.max(K.length,F.length,1),$=Buffer.alloc(Z),U=Buffer.alloc(Z);return K.copy($),F.copy(U),mUK($,U)&&K.length===F.length};var i9=ob();class o4A extends QV{file=null;info(){}warn(){}error(){}}var xzq=(A)=>{let q=Buffer.byteLength(A.content,"utf-8");if(A.meta)for(let[K,F]of Object.entries(A.meta))q+=Buffer.byteLength(K,"utf-8")+Buffer.byteLength(F,"utf-8");return q},pUK=1048576,lUK=200,iUK=4194304,aUK=new o4A;class r4A{clients=new Map;subscribers=new Set;logger;maxBufferedBytes;now;replayBufferSize;replayBufferMaxBytes;replayBuffer=[];persistentReplay;exclusiveCursor=new Map;replayBufferBytes=0;eventsBroadcast=0;droppedSlowClients=0;lastBroadcastAt=null;latestOffset=0;constructor(A={}){this.logger=A.logger??aUK,this.maxBufferedBytes=A.maxBufferedBytes??pUK,this.now=A.now??(()=>Date.now()),this.replayBufferSize=Math.max(0,A.replayBufferSize??lUK),this.replayBufferMaxBytes=Math.max(0,A.replayBufferMaxBytes??iUK),this.persistentReplay=A.persistentReplay??null}getMetrics(){return{clients:this.clients.size,subscribers:this.subscribers.size,eventsBroadcast:this.eventsBroadcast,droppedSlowClients:this.droppedSlowClients,lastBroadcastAt:this.lastBroadcastAt?new Date(this.lastBroadcastAt).toISOString():null,latestOffset:this.latestOffset,oldestReplayableOffset:this.replayBuffer[0]?.offset??null}}replaySince(A,q){let K=this.replayBuffer[0]?.offset,F=this.persistentReplay&&(K===void 0||A<K-1),Z=this.replayBuffer.filter((X)=>X.offset>A&&this.matchesClient(X,q));if(!F)return Z;let $=this.persistentReplay?this.persistentReplay.loadSince(A).filter((X)=>this.matchesClient(X,q)):[],U=K??Number.POSITIVE_INFINITY;return[...$.filter((X)=>X.offset<U),...Z]}matchesClient(A,q){if(q.tapAll)return!0;let K=A.meta?.channelId;if(K&&K!==q.channel)return!1;let F=A.meta?.connector;if(!F)return!0;return q.connectors.includes(F)}pickRecipients(A){let q=new Map,K=[];for(let[F,Z]of this.clients){if(!this.matchesClient(A,Z))continue;if(Z.tapAll){K.push(F);continue}if(Z.delivery==="exclusive"){let $=q.get(Z.channel)??[];$.push(F),q.set(Z.channel,$);continue}K.push(F)}for(let[F,Z]of q){if(Z.length===0)continue;let $=this.exclusiveCursor.get(F)??0,U=Z[$%Z.length];if(U)K.push(U);this.exclusiveCursor.set(F,$+1)}return K}addClient(A,q){this.clients.set(A,q)}removeClient(A){this.clients.delete(A)}getClientCount(){return this.clients.size}listChannels(){return[...this.clients.values()].map((A)=>({...A}))}subscribe(A){return this.subscribers.add(A),()=>{this.subscribers.delete(A)}}broadcast(A,q){this.latestOffset+=1;let K={content:A,meta:q,offset:this.latestOffset},F=JSON.stringify(K),Z=q?.connector;if(this.eventsBroadcast+=1,this.lastBroadcastAt=this.now(),this.replayBufferSize>0){let U=xzq(K);this.replayBuffer.push(K),this.replayBufferBytes+=U;while((this.replayBuffer.length>this.replayBufferSize||this.replayBufferBytes>this.replayBufferMaxBytes)&&this.replayBuffer.length>0){let Y=this.replayBuffer.shift();if(Y)this.replayBufferBytes-=xzq(Y)}}let $=this.pickRecipients(K);for(let U of $){let Y=U.getBufferedAmount();if(Y>this.maxBufferedBytes){let X=this.clients.get(U);this.logger.warn("dropping slow WS client (backpressure)",{channel:X?.channel,buffered:Y,max:this.maxBufferedBytes});try{U.close(1009,"backpressure")}catch{}this.clients.delete(U),this.droppedSlowClients+=1;continue}U.send(F)}for(let U of this.subscribers)try{U(K)}catch(Y){this.logger.error("broadcast subscriber threw",{error:Y instanceof Error?Y.message:String(Y)})}return K}seedLatestOffset(A){if(A>this.latestOffset)this.latestOffset=A}}import{Database as dUK}from"bun:sqlite";var nUK=/^[a-z_][a-z0-9_]*$/,sUK=new Set(["seq","ts","type","event"]),Ozq=[["CREATE TABLE IF NOT EXISTS leuco_log (seq INTEGER PRIMARY KEY, ts INTEGER NOT NULL, type TEXT, event TEXT NOT NULL)","CREATE INDEX IF NOT EXISTS idx_leuco_log_ts ON leuco_log (ts)","CREATE INDEX IF NOT EXISTS idx_leuco_log_type ON leuco_log (type)"]];class t4A{db;maxRows;maxAgeMs;now;indexes;extractIndexes;insertStmt;insertWithSeqStmt;maxSeqStmt;countStmt;trimRowsStmt;trimAgeStmt;constructor(A){if(this.db=new dUK(A.path),this.db.run("PRAGMA journal_mode = WAL"),this.migrate(),this.maxRows=A.maxRows??null,this.maxAgeMs=A.maxAgeMs??null,this.now=A.now??(()=>Date.now()),this.indexes=A.indexes??[],this.indexes.length>0)oUK(this.indexes),this.extractIndexes=A.extractIndexes??null,this.syncIndexColumns();else this.extractIndexes=null;let q=["ts","type","event",...this.indexes],K=q.map(()=>"?").join(", ");this.insertStmt=this.db.prepare(`INSERT INTO leuco_log (${q.join(", ")}) VALUES (${K})`);let F=["seq",...q],Z=F.map(()=>"?").join(", ");this.insertWithSeqStmt=this.db.prepare(`INSERT INTO leuco_log (${F.join(", ")}) VALUES (${Z})`),this.maxSeqStmt=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max FROM leuco_log"),this.countStmt=this.db.prepare("SELECT COUNT(*) AS n FROM leuco_log"),this.trimRowsStmt=this.db.prepare("DELETE FROM leuco_log WHERE seq <= (SELECT seq FROM leuco_log ORDER BY seq DESC LIMIT 1 OFFSET ?)"),this.trimAgeStmt=this.db.prepare("DELETE FROM leuco_log WHERE ts < ?")}insert(A){try{let q=this.buildInsertParams(A.ts,A.event),K=this.insertStmt.run(...q),F=Number(K.lastInsertRowid);return this.trim(),{seq:F,ts:A.ts,event:A.event}}catch(q){return q instanceof Error?q:Error(String(q))}}insertMany(A){if(A.length===0)return[];try{let q=[];return this.db.transaction((F)=>{for(let Z of F){let $=this.buildInsertParams(Z.ts,Z.event),U=this.insertStmt.run(...$);q.push({seq:Number(U.lastInsertRowid),ts:Z.ts,event:Z.event})}})(A),this.trim(),q}catch(q){return q instanceof Error?q:Error(String(q))}}write(A){try{let q=[A.seq,...this.buildInsertParams(A.ts,A.event)];this.insertWithSeqStmt.run(...q),this.trim()}catch(q){return q instanceof Error?q:Error(String(q))}}getMaxSeq(){let A=this.maxSeqStmt.get();return A?A.max:0}getRecords(A={}){let q=["seq > ?"],K=[A.sinceSeq??0];if(typeof A.type==="string")q.push("type = ?"),K.push(A.type);if(A.where)this.appendWhereConditions(A.where,q,K);let F=A.limit??1000;K.push(F);let Z=`SELECT seq, ts, type, event FROM leuco_log WHERE ${q.join(" AND ")} ORDER BY seq ASC LIMIT ?`;return this.db.prepare(Z).all(...K).map(tUK)}getSchemaVersion(){return this.db.prepare("PRAGMA user_version").get()?.user_version??0}close(){this.db.close()}buildInsertParams(A,q){let K=rUK(q),F=JSON.stringify(q);if(this.indexes.length===0)return[A,K,F];let Z=this.extractIndexes?this.extractIndexes(q):null,$=this.indexes.map((U)=>Z?.[U]??null);return[A,K,F,...$]}appendWhereConditions(A,q,K){let F=A;for(let Z of this.indexes){let $=F[Z];if($===void 0)continue;if($===null)q.push(`${Z} IS NULL`);else q.push(`${Z} = ?`),K.push($)}}trim(){if(this.maxRows!==null){let A=this.countStmt.get();if(A&&A.n>this.maxRows)this.trimRowsStmt.run(this.maxRows)}if(this.maxAgeMs!==null)this.trimAgeStmt.run(this.now()-this.maxAgeMs)}syncIndexColumns(){let A=new Set(this.db.prepare("PRAGMA table_info(leuco_log)").all().map((q)=>q.name));for(let q of this.indexes){if(!A.has(q))this.db.run(`ALTER TABLE leuco_log ADD COLUMN ${q} TEXT`);this.db.run(`CREATE INDEX IF NOT EXISTS idx_leuco_log_${q} ON leuco_log (${q})`)}}migrate(){let q=this.db.prepare("PRAGMA user_version").get()?.user_version??0;if(q>=Ozq.length)return;let K=Ozq.slice(q),F=q;for(let Z of K)F+=1,this.db.transaction(()=>{for(let U of Z)this.db.run(U);this.db.run(`PRAGMA user_version = ${F}`)})()}}function oUK(A){for(let q of A){if(!nUK.test(q))throw Error(`invalid index column name: ${q}`);if(sUK.has(q))throw Error(`reserved index column name: ${q}`)}}function rUK(A){if(typeof A!=="object"||A===null)return null;if(!("type"in A))return null;let q=A.type;return typeof q==="string"?q:null}function tUK(A){return{seq:A.seq,ts:A.ts,event:JSON.parse(A.event)}}var Mzq=2000,JnK=c.object({type:c.string(),content:c.string(),channel_id:c.string().nullable(),connector_id:c.string().nullable(),meta:c.record(c.string(),c.string()).nullable()});class e4A{sink;now;constructor(A){this.now=A.now??(()=>Date.now()),this.sink=new t4A({path:A.path,indexes:["channel_id","connector_id"],extractIndexes:(q)=>({channel_id:q.channel_id,connector_id:q.connector_id}),now:this.now,...A.maxRows!==void 0?{maxRows:A.maxRows}:{},...A.maxAgeMs!==void 0?{maxAgeMs:A.maxAgeMs}:{}})}record(A){let q={type:A.meta?.event_type??"unknown",content:eUK(A.content),channel_id:A.channelId,connector_id:A.connectorId,meta:A.meta};this.sink.write({seq:A.offset,ts:this.now(),event:q})}loadSince(A){let q=this.sink.getRecords({sinceSeq:A}),K=[];for(let F of q)K.push({content:F.event.content,meta:F.event.meta??void 0,offset:F.seq});return K}loadForChannel(A){let q={channel_id:A.channelId};if(A.connectorId!==void 0)q.connector_id=A.connectorId;let K=this.sink.getRecords({where:q,...A.sinceSeq!==void 0?{sinceSeq:A.sinceSeq}:{},...A.limit!==void 0?{limit:A.limit}:{}}),F=[];for(let Z of K)F.push({content:Z.event.content,meta:Z.event.meta??void 0,offset:Z.seq});return F}findMaxOffset(){return this.sink.getMaxSeq()}close(){this.sink.close()}}function eUK(A){if(A.length<=Mzq)return A;return`${A.slice(0,Mzq)}...`}var AYK=new w$,qYK=30000,KYK=60000,FYK=(A)=>new Promise((q)=>{setTimeout(q,A)});class kL{channels;notify;logger;running=new Map;failureCounts=new Map;stats=new Map;healthCheckIntervalMs;maxBackoffMs;sleep;now;healthCheckTimer=null;healthCheckInFlight=!1;constructor(A){this.channels=A.channels,this.notify=A.notify,this.logger=A.logger??AYK,this.healthCheckIntervalMs=A.healthCheckIntervalMs??qYK,this.maxBackoffMs=A.maxBackoffMs??KYK,this.sleep=A.sleep??FYK,this.now=A.now??(()=>Date.now())}static keyOf(A,q){return`${A}/${q}`}isRunning(A,q){return this.running.has(kL.keyOf(A,q))}list(){return[...this.running.entries()].map(([A,q])=>{let K=this.stats.get(A);return{channelName:q.channelName,channelId:q.channelId,name:q.config.name,type:q.config.type,alive:q.listener.isAlive(),events:K?.events??0,errors:K?.errors??0,failureCount:this.failureCounts.get(A)??0,lastEventAt:K?.lastEventAt??null}})}async start(A,q){let K=kL.keyOf(A,q);if(this.running.has(K))return{ok:!0,reason:"already running"};let F=this.channels.createListener(A,q);if(!F)return{ok:!1,reason:`connector "${q}" not found in channel "${A}"`};let Z=async($,U)=>{try{await this.notify(A,q,$,U),this.recordEvent(K)}catch(Y){throw this.recordError(K),Y}};try{return await F.listener.start(Z),this.running.set(K,{config:F.config,channelName:A,channelId:F.channelId,listener:F.listener}),this.ensureStats(K),this.logger.info(`${F.config.type} listener started`,{channel:A,connector:q}),{ok:!0}}catch($){return this.logger.error(`${F.config.type} listener failed to start`,{channel:A,connector:q,error:$ instanceof Error?$.message:String($)}),{ok:!1,reason:$ instanceof Error?$.message:String($)}}}async stop(A,q){let K=kL.keyOf(A,q),F=this.running.get(K);if(!F)return{ok:!0,reason:"not running"};try{return await F.listener.stop(),this.running.delete(K),this.failureCounts.delete(K),this.logger.info(`${F.config.type} listener stopped`,{channel:A,connector:q}),{ok:!0}}catch(Z){return this.logger.error(`${F.config.type} listener failed to stop`,{channel:A,connector:q,error:Z instanceof Error?Z.message:String(Z)}),{ok:!1,reason:Z instanceof Error?Z.message:String(Z)}}}async restart(A,q){let K=await this.stop(A,q);if(!K.ok)return K;return await this.start(A,q)}async startAll(){let A=this.channels.listAllConnectors();for(let q of A)await this.start(q.channelName,q.name);this.startHealthCheck()}async stopAll(){this.stopHealthCheck();for(let[,A]of[...this.running.entries()])await this.stop(A.channelName,A.config.name)}ensureStats(A){let q=this.stats.get(A);if(q)return q;let K={events:0,errors:0,failureCount:0,lastEventAt:null};return this.stats.set(A,K),K}recordEvent(A){let q=this.ensureStats(A);q.events+=1,q.lastEventAt=new Date(this.now()).toISOString()}recordError(A){this.ensureStats(A).errors+=1}startHealthCheck(){if(this.healthCheckTimer)return;this.healthCheckTimer=setInterval(()=>{this.runHealthCheck()},this.healthCheckIntervalMs),this.healthCheckTimer.unref()}stopHealthCheck(){if(!this.healthCheckTimer)return;clearInterval(this.healthCheckTimer),this.healthCheckTimer=null}async runHealthCheck(){if(this.healthCheckInFlight)return;this.healthCheckInFlight=!0;try{for(let[A,q]of[...this.running.entries()]){if(q.listener.isAlive()){this.failureCounts.delete(A);continue}await this.recoverDead(q.channelName,q.config.name,q.config.type)}}finally{this.healthCheckInFlight=!1}}async recoverDead(A,q,K){let F=kL.keyOf(A,q),Z=this.failureCounts.get(F)??0,$=Math.min(1000*2**Z,this.maxBackoffMs);if(this.logger.warn(`${K} listener unhealthy, restarting`,{channel:A,connector:q,attempt:Z+1,backoffMs:$}),await this.stop(A,q),await this.sleep($),(await this.start(A,q)).ok)this.failureCounts.delete(F),this.logger.info(`${K} listener recovered`,{channel:A,connector:q});else this.failureCounts.set(F,Z+1)}}var ZYK=new jY,$YK=new w$,UYK=(A)=>`funnel-gateway[${A}]`,zzq=async(A)=>{let q=A.process??ZYK,K=A.logger??$YK,F=UYK(A.dir),Z=q.listProcessesContaining(F),$=[];for(let U of Z){if(U.pid===A.selfPid)continue;q.kill(U.pid,"SIGTERM"),$.push(U.pid),K.info("killed competing Slack gateway process",{pid:U.pid,args:U.command.slice(0,160)})}return $};var U7=(A)=>Dx("param",A,(q,K)=>{if(q.success)return;let F=q.error.issues[0],Z=F?`${F.path.join(".")}: ${F.message}`:"invalid request";return K.json({ok:!1,reason:Z},400)});var YYK=c.object({method:c.string().min(1),path:c.string().min(1),body:c.unknown().optional()}),Izq=i9.createHandlers(U7(c.object({channel:c.string().min(1),connector:c.string().min(1)})),async(A)=>{let q=A.req.valid("param"),K=await A.req.json().catch(()=>null),F=YYK.safeParse(K);if(!F.success)throw new pK(400,{message:F.error.issues[0]?.message??"invalid body"});let Z=await A.var.deps.channels.call(q.channel,q.connector,{method:F.data.method,path:F.data.path,body:F.data.body??{}});return A.json({ok:!0,result:Z})});var Pzq=i9.createHandlers(U7(c.object({channel:c.string().min(1)})),Dx("json",Wzq,(A,q)=>{if(A.success)return;let K=A.error.issues[0],F=K?`${K.path.join(".")}: ${K.message}`:"invalid body";return q.json({ok:!1,reason:F},400)}),(A)=>{let q=A.req.valid("param"),K=A.req.valid("json"),Z={ok:!0,offset:A.var.deps.emit({channel:q.channel,connector:K.connector,content:K.content,meta:K.meta}).offset};return A.json(Z)});var Nzq=i9.createHandlers((A)=>{let q=A.var.deps;return A.json({ok:!0,pid:q.selfPid,clients:q.broadcaster.getClientCount(),listeners:q.supervisor.list()})});var _zq=i9.createHandlers((A)=>{return A.json({listeners:A.var.deps.supervisor.list()})});var wzq=i9.createHandlers(U7(c.object({channel:c.string().min(1),connector:c.string().min(1)})),async(A)=>{let q=A.req.valid("param"),K=await A.var.deps.supervisor.restart(q.channel,q.connector);return A.json(K,K.ok?200:400)});var Bzq=i9.createHandlers(U7(c.object({channel:c.string().min(1),connector:c.string().min(1)})),async(A)=>{let q=A.req.valid("param"),K=await A.var.deps.supervisor.start(q.channel,q.connector);return A.json(K,K.ok?200:400)});var Dzq=i9.createHandlers(U7(c.object({channel:c.string().min(1),connector:c.string().min(1)})),async(A)=>{let q=A.req.valid("param"),K=await A.var.deps.supervisor.stop(q.channel,q.connector);return A.json(K,K.ok?200:400)});var Rzq=i9.createHandlers((A)=>{let q=A.var.deps;return A.json({ok:!0,pid:q.selfPid,uptimeMs:q.uptimeMs(),clients:q.broadcaster.listChannels(),listeners:q.supervisor.list(),broadcaster:q.broadcaster.getMetrics()})});var Tzq=i9.createApp().get("/health",...Nzq).get("/status",...Rzq).get("/listeners",..._zq).post("/listeners/:channel/:connector/start",...Bzq).delete("/listeners/:channel/:connector",...Dzq).post("/listeners/:channel/:connector/restart",...wzq).post("/channels/:channel/connectors/:connector/call",...Izq).post("/channels/:channel/publish",...Pzq);var JYK=9742,HYK=()=>jYK(T8(),"events.db"),EYK=new w$;class A7A{channels;settings;port;dbPath;process;logger;selfPid;dir;killCompetingSlack;token;broadcaster;eventStore;supervisor;nowMs;extraRoutes;startedAt=null;server=null;constructor(A){this.channels=A.channels,this.settings=A.settings,this.port=A.port??JYK,this.dbPath=A.dbPath??HYK(),this.process=A.process,this.logger=A.logger??EYK,this.selfPid=A.selfPid??globalThis.process.pid,this.dir=A.dir??c8,this.killCompetingSlack=A.killCompetingSlack??!0,this.token=A.token??"",this.extraRoutes=A.extraRoutes??null;let q=A.clock;this.nowMs=q?()=>q.millis():()=>Date.now();let K=GYK(this.dbPath);if(!QYK(K))XYK(K,{recursive:!0});this.eventStore=new e4A({path:this.dbPath,now:this.nowMs}),this.broadcaster=new r4A({logger:this.logger,now:this.nowMs,persistentReplay:this.eventStore}),this.broadcaster.seedLatestOffset(this.eventStore.findMaxOffset()),this.supervisor=new kL({channels:this.channels,logger:this.logger,notify:async(F,Z,$,U)=>{this.emit({channel:F,connector:Z,content:$,meta:U})},now:this.nowMs})}async start(){if(this.server)return this.server;let A=this.buildApp();return this.startedAt=this.nowMs(),this.server=Bun.serve({port:this.port,development:!1,fetch:(q,K)=>this.handleFetch(q,K,A),websocket:{open:(q)=>this.handleWsOpen(q),close:(q)=>this.handleWsClose(q),message(){}}}),this.logServerStarted(),await this.bootListeners(),this.server}async stop(){if(await this.supervisor.stopAll(),this.server)this.server.stop(),this.server=null}getStatus(){return{clients:this.broadcaster.getClientCount(),channels:this.broadcaster.listChannels()}}getBroadcaster(){return this.broadcaster}getSupervisor(){return this.supervisor}getEventStore(){return this.eventStore}handleFetch(A,q,K){let F=new URL(A.url);if(F.pathname==="/ws"&&A.headers.get("upgrade")==="websocket"){if(this.token&&!this.tokenMatchesUpgrade(A))return new Response("unauthorized",{status:401});let Z=F.searchParams.get("tap")==="all",$=Z?"":F.searchParams.get("channel")??"",U=!Z&&$?this.resolveChannel($):null,Y=Z?"":U?.id??$,X=Z?null:U?.name??null,j=U?.connectors??[],J=U?.delivery??"fanout",E=F.searchParams.get("since"),W=E===null?Number.NaN:Number.parseInt(E,10),g=Number.isFinite(W)&&W>=0?W:void 0;if(q.upgrade(A,{data:{channel:Y,channelName:X,connectors:j,tapAll:Z,delivery:J,since:g}}))return;return new Response("WebSocket upgrade failed",{status:400})}return K.fetch(A)}handleWsOpen(A){if(typeof A.data.since==="number"){let q=this.broadcaster.replaySince(A.data.since,A.data);for(let K of q)A.send(JSON.stringify(K))}if(this.broadcaster.addClient(A,A.data),A.data.channelName){let q={event_type:"system",action:"channel_connect",channel:A.data.channelName,channelId:A.data.channel,connectors:A.data.connectors.join(","),total:String(this.broadcaster.getClientCount())};this.logger.info("channel connected",q)}else this.logger.info("tap-all client connected",{event_type:"system",action:"tap_connect",total:String(this.broadcaster.getClientCount())})}handleWsClose(A){if(this.broadcaster.removeClient(A),A.data.channelName)this.logger.info("channel disconnected",{event_type:"system",action:"channel_disconnect",channel:A.data.channelName,channelId:A.data.channel,total:String(this.broadcaster.getClientCount())});else this.logger.info("tap-all client disconnected",{event_type:"system",action:"tap_disconnect",total:String(this.broadcaster.getClientCount())})}logServerStarted(){this.logger.info("gateway started",{event_type:"system",action:"gateway_start",port:String(this.port),pid:String(this.selfPid)}),this.logger.info("funnel gateway listening",{url:`http://localhost:${this.port}`,websocket:`ws://localhost:${this.port}/ws`,health:`http://localhost:${this.port}/health`})}buildApp(){let A=i9.createApp();if(A.use((K,F)=>{return K.set("deps",{selfPid:this.selfPid,broadcaster:this.broadcaster,supervisor:this.supervisor,channels:this.channels,uptimeMs:()=>this.startedAt?this.nowMs()-this.startedAt:0,emit:(Z)=>this.emit(Z)}),F()}),this.token)A.use("/listeners/*",ep({expected:this.token})),A.use("/status",ep({expected:this.token})),A.use("/channels/*",ep({expected:this.token}));return(this.extraRoutes?A.route("/",this.extraRoutes):A).route("/",Tzq)}tokenMatchesUpgrade(A){let q=(A.headers.get("sec-websocket-protocol")??"").split(",").map((Z)=>Z.trim()).filter((Z)=>Z.length>0);for(let Z of q)if(Z.startsWith("funnel.token.")&&Al(Z.slice(13),this.token))return!0;let F=(A.headers.get("authorization")??"").match(/^Bearer\s+(.+)$/i);if(F&&Al(F[1]??"",this.token))return!0;return!1}resolveChannel(A){let K=this.settings.read()?.channels.find((F)=>F.id===A||F.name===A);if(!K)return null;return{id:K.id,name:K.name,connectors:K.connectors.map((F)=>F.name),delivery:K.delivery}}async bootListeners(){let A=this.channels.listAllConnectors();if(this.killCompetingSlack&&A.some((q)=>q.type==="slack")){let q=await zzq({selfPid:this.selfPid,dir:this.dir,process:this.process,logger:this.logger});if(q.length>0)this.logger.info("killed competing Slack gateway processes",{event_type:"system",action:"kill_competing",pids:q.join(",")})}await this.supervisor.startAll();for(let q of this.supervisor.list())this.logger.info(`${q.type} listener started: ${q.name}`,{event_type:"system",action:`${q.type}_connect`,channel:q.channelName,connector:q.name});this.logger.info(`event store: ${this.dbPath}`),this.logger.info("funnel gateway running")}emit(A){let q=this.lookupChannelId(A.channel),K=q&&A.connector?this.lookupConnectorId(q,A.connector):null,F={...A.meta,channel:A.channel};if(A.connector)F.connector=A.connector;if(q)F.channelId=q;if(K)F.connectorId=K;let Z=this.broadcaster.broadcast(A.content,F);return this.eventStore.record({content:A.content,channelId:q??null,connectorId:K??null,meta:F,offset:Z.offset}),{offset:Z.offset}}lookupChannelId(A){return this.settings.read().channels.find((K)=>K.name===A)?.id??null}lookupConnectorId(A,q){return this.settings.read().channels.find((Z)=>Z.id===A)?.connectors.find((Z)=>Z.name===q)?.id??null}}import{homedir as WYK}from"os";import{dirname as gYK,join as Szq}from"path";var bzq="gateway.token",VYK=32,LYK=new FY,xYK=()=>{let A=new Uint8Array(VYK);return crypto.getRandomValues(A),[...A].map((q)=>q.toString(16).padStart(2,"0")).join("")};class q7A{fs;path;generate;constructor(A={}){this.fs=A.fs??LYK,this.path=Szq(A.dir??c8,bzq),this.generate=A.generate??xYK,Object.freeze(this)}read(){if(!this.fs.existsSync(this.path))return null;let A=this.fs.readFileSync(this.path).trim();return A.length>0?A:null}ensure(){let A=this.read();if(A)return A;let q=this.generate();return this.fs.mkdirSync(gYK(this.path),{recursive:!0}),this.fs.writeSecretFileSync(this.path,`${q}
1436
1436
  `),q}getPath(){return this.path}}var IsK=Szq(WYK(),".funnel",bzq);var OYK=c.object({channelName:c.string(),channelId:c.string(),name:c.string(),type:c.string(),alive:c.boolean()}),MYK=c.object({listeners:c.array(OYK)}),zYK=c.object({reason:c.string().optional()}),K7A={state:"offline"};class F7A{port;isDaemonRunning;getToken;constructor(A){this.port=A.port,this.isDaemonRunning=A.isDaemonRunning,this.getToken=A.getToken??(()=>null),Object.freeze(this)}async list(){if(!this.isDaemonRunning())return{state:"offline"};try{let A=await fetch(`http://localhost:${this.port}/listeners`,{headers:this.authHeaders()});if(!A.ok)return{state:"error",reason:`HTTP ${A.status}`};let q=MYK.safeParse(await A.json());if(!q.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",listeners:q.data.listeners}}catch(A){return{state:"error",reason:A instanceof Error?A.message:String(A)}}}async start(A,q){if(!this.isDaemonRunning())return K7A;return await this.call("POST",`/listeners/${this.path(A,q)}/start`)}async stop(A,q){if(!this.isDaemonRunning())return K7A;return await this.call("DELETE",`/listeners/${this.path(A,q)}`)}async restart(A,q){if(!this.isDaemonRunning())return K7A;return await this.call("POST",`/listeners/${this.path(A,q)}/restart`)}path(A,q){return`${encodeURIComponent(A)}/${encodeURIComponent(q)}`}authHeaders(){let A=this.getToken();return A?{authorization:`Bearer ${A}`}:{}}async call(A,q){try{let K=await fetch(`http://localhost:${this.port}${q}`,{method:A,headers:this.authHeaders()});if(!K.ok){let F=zYK.safeParse(await K.json().catch(()=>null));return{state:"error",reason:(F.success?F.data.reason:void 0)??`HTTP ${K.status}`}}return{state:"ok"}}catch(K){return{state:"error",reason:K instanceof Error?K.message:String(K)}}}}var PYK="/sandbox/.funnel",NYK="/sandbox/tmp";class oz{props;memos={};constructor(A={}){this.props=A;Object.freeze(this)}static inMemory(A={}){return new oz({store:A.store??new a4A,fs:A.fs??new k4A,process:A.process??new c4A,logger:A.logger??new u4A,clock:A.clock??new d4A,idGenerator:A.idGenerator??new C4A,dir:A.dir??PYK,tmpDir:A.tmpDir??NYK})}get paths(){let A=this.props.dir??c8,q=this.props.tmpDir??T8();return{dir:A,tmpDir:q,settings:IYK(A,"settings.json")}}get fs(){if(!this.memos.fs)this.memos.fs=this.props.fs??new FY;return this.memos.fs}get process(){if(!this.memos.process)this.memos.process=this.props.process??new jY;return this.memos.process}get logger(){if(!this.memos.logger)this.memos.logger=this.props.logger??new w$;return this.memos.logger}get clock(){if(!this.memos.clock)this.memos.clock=this.props.clock??new vL;return this.memos.clock}get idGenerator(){if(!this.memos.idGenerator)this.memos.idGenerator=this.props.idGenerator??new cR;return this.memos.idGenerator}get store(){if(!this.memos.store)this.memos.store=this.props.store??new D4A({path:this.paths.settings,fs:this.fs});return this.memos.store}get factory(){if(!this.memos.factory)this.memos.factory=new T4A({fs:this.fs,process:this.process,logger:this.logger,dir:this.paths.dir,slackListenerOptions:this.props.slackListenerOptions,scheduleListenerOptions:this.props.scheduleListenerOptions});return this.memos.factory}get channels(){if(!this.memos.channels)this.memos.channels=new b4A({store:this.store,factory:this.factory,profileChecker:this.profiles,clock:this.clock,idGenerator:this.idGenerator});return this.memos.channels}get profiles(){if(!this.memos.profiles)this.memos.profiles=new m4A({store:this.store});return this.memos.profiles}get sessions(){if(!this.memos.sessions)this.memos.sessions=new p4A({fs:this.fs,idGenerator:this.idGenerator,dir:this.paths.dir});return this.memos.sessions}get localConfig(){if(!this.memos.localConfig)this.memos.localConfig=new h4A({fs:this.fs});return this.memos.localConfig}get dotenv(){if(!this.memos.dotenv)this.memos.dotenv=new f4A({fs:this.fs});return this.memos.dotenv}get tokenPrompter(){if(!this.memos.tokenPrompter)this.memos.tokenPrompter=this.props.tokenPrompter??new i4A;return this.memos.tokenPrompter}get localConfigSync(){if(!this.memos.localConfigSync)this.memos.localConfigSync=new y4A({channels:this.channels,dotenv:this.dotenv,prompter:this.tokenPrompter});return this.memos.localConfigSync}get mcp(){if(!this.memos.mcp)this.memos.mcp=new me({fs:this.fs});return this.memos.mcp}get claude(){if(!this.memos.claude)this.memos.claude=new v4A({channels:this.channels,mcp:this.mcp,gateway:this.gateway,sessions:this.sessions,fs:this.fs,process:this.process,logger:this.logger,dir:this.paths.dir});return this.memos.claude}get gateway(){if(!this.memos.gateway)this.memos.gateway=new s4A({fs:this.fs,process:this.process,clock:this.clock,dir:this.paths.dir,tmpDir:this.paths.tmpDir});return this.memos.gateway}get gatewayToken(){if(!this.memos.gatewayToken)this.memos.gatewayToken=new q7A({fs:this.fs,dir:this.paths.dir});return this.memos.gatewayToken}get publisher(){if(!this.memos.publisher){let A=this.gateway,q=this.gatewayToken;this.memos.publisher=new n4A({port:A.getPort(),isDaemonRunning:()=>A.isRunning(),getToken:()=>q.read()})}return this.memos.publisher}get listeners(){if(!this.memos.listeners){let A=this.gateway,q=this.gatewayToken;this.memos.listeners=new F7A({port:A.getPort(),isDaemonRunning:()=>A.isRunning(),getToken:()=>q.read()})}return this.memos.listeners}gatewayServer(A={}){return new A7A({channels:this.channels,settings:this.store,port:A.port,dbPath:A.dbPath,process:this.process,clock:this.clock,logger:this.logger,dir:this.paths.dir,killCompetingSlack:A.killCompetingSlack,token:A.token??this.gatewayToken.ensure(),extraRoutes:A.extraRoutes})}}var NY=(A)=>_6.createHandlers((q)=>q.text(A)),Z7A=(A)=>{let q=_6.createApp();return q.use((K,F)=>{return K.set("funnel",A),F()}),q.onError((K,F)=>{if(K instanceof pK)return F.text(`error: ${K.message}`,K.status);return F.text(`error: ${K instanceof Error?K.message:String(K)}`,400)}),q.get("/claude",...HEA).get("/channels",...A_A).post("/channels/add",...NY(x6A)).post("/channels/add/:channel",...uNA).post("/channels/remove",...NY(w6A)).post("/channels/remove/:channel",...rNA).post("/channels/rename/:channel/:newName",...B6A).post("/channels/:channel/rename/:newName",...B6A).post("/channels/rename",...NY(CC)).post("/channels/:channel/rename",...NY(CC)).post("/channels/:channel/set/delivery/:mode",...tNA).post("/channels/publish",...NY(_6A)).post("/channels/:channel/publish",...oNA).get("/channels/:channel",...eNA).get("/channels/:channel/connectors",...cNA).post("/channels/:channel/connectors/add",...NY(O6A)).post("/channels/:channel/connectors/add/:connector",...mNA).post("/channels/:channel/connectors/remove",...NY(M6A)).post("/channels/:channel/connectors/remove/:connector",...pNA).post("/channels/:channel/connectors/set",...NY(z6A)).post("/channels/:channel/connectors/set/:connector",...lNA).post("/channels/:channel/connectors/rename/:connector/:newName",...I6A).post("/channels/:channel/connectors/:connector/rename/:newName",...I6A).post("/channels/:channel/connectors/rename",...NY(kC)).post("/channels/:channel/connectors/:connector/rename",...NY(kC)).post("/channels/:channel/connectors/:connector/request",...aNA).get("/channels/:channel/connectors/:connector",...iNA).get("/channels/:channel/connectors/:connector/schedules",...dNA).post("/channels/:channel/connectors/:connector/schedules/add",...NY(P6A)).post("/channels/:channel/connectors/:connector/schedules/add/:id",...nNA).post("/channels/:channel/connectors/:connector/schedules/remove",...NY(N6A)).post("/channels/:channel/connectors/:connector/schedules/remove/:id",...sNA).get("/profiles",...P3A).post("/profiles/add",...NY(pKA)).post("/profiles/add/:profile",...O3A).post("/profiles/set",...NY(dKA)).post("/profiles/set/:profile",...I3A).post("/profiles/remove",...NY(aKA)).post("/profiles/remove/:profile",...z3A).post("/profiles/rename/:profile/:newName",...lKA).post("/profiles/:profile/rename/:newName",...lKA).post("/profiles/rename",...NY(wf)).post("/profiles/:profile/rename",...NY(wf)).post("/profiles/:profile/as-default",...M3A).get("/profiles/:profile/run",...iKA).get("/profiles/:profile",...iKA).get("/gateway",...q_A).get("/gateway/status",...L3A).get("/gateway/start",...V3A).get("/gateway/stop",...x3A).get("/gateway/restart",...W3A).get("/gateway/run",...g3A).get("/gateway/logs",...E3A).get("/gateway/listeners",...K_A).get("/schema",...w3A).get("/status",...B3A).get("/update",...b3A)},moK=Z7A(new oz);process.title="funnel";var ql=new oz,vzq=Z7A(ql),kzq=`funnel \u2014 Open Claude Funnel