@interactive-inc/claude-funnel 0.25.1 → 0.25.2
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 dp=Jxq(),g9K=gA("events").EventEmitter,BMq=Exq(),DMq=VOq(),RMq=U4A(),TMq=aOq(),SMq=NMq();ZG=bMq.exports=V9K;function V9K(){var A=function(q,K,F){A.handle(q,K,F)};return BMq(A,g9K.prototype,!1),BMq(A,DMq,!1),A.request=Object.create(TMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.response=Object.create(SMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.init(),A}ZG.application=DMq;ZG.request=TMq;ZG.response=SMq;ZG.Route=RMq.Route;ZG.Router=RMq;ZG.json=dp.json;ZG.raw=dp.raw;ZG.static=wMq();ZG.text=dp.text;ZG.urlencoded=dp.urlencoded});var lMq=I((b$)=>{var L9K=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]}),x9K=b$&&b$.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),fMq=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))L9K(q,A,K)}return x9K(q,A),q},np=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 O9K=np(gA("crypto")),M9K=gA("http"),z9K=gA("https"),I9K=np(gA("querystring")),kMq=gY(),P9K=FR(),CMq=fMq(vMq()),N9K=np(Xp()),_9K=np(Gp()),Z7=xY(),nz=fMq(JR()),w9K=Jp(),B9K=Ep(),D9K=["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"],N4A="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",R9K=(A,q,K)=>{if(A.body?.ssl_check){q.send();return}K()};b$.respondToSslCheck=R9K;var T9K=(A,q,K)=>{if(A.body?.type&&A.body.type==="url_verification"){q.json({challenge:A.body.challenge});return}K()};b$.respondToUrlVerification=T9K;class hMq{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=kMq.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,CMq.default)(),typeof q<"u")this.logger=q;else this.logger=new kMq.ConsoleLogger,this.logger.setLevel(K);this.signatureVerification=$;let y=[this.signatureVerification?yMq(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,CMq.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,B9K.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 P9K.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 w9K.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=M9K.createServer;if(Object.keys(q).filter((F)=>D9K.includes(F)).length>0)K=z9K.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(N4A);this.server.on("error",($)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(N4A);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(N4A));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=hMq;function S9K(A,q){return yMq(A,q)}b$.verifySignatureAndParseRawBody=S9K;function yMq(A,q){return async(K,F,Z)=>{let $=await pMq(K);try{K.body=uMq(typeof q==="string"?q:await q(),$,K.headers)}catch(U){if(U){if(U instanceof Z7.ReceiverAuthenticityError){_4A(A,"Request verification failed",U),F.status(401).send();return}_4A(A,"Parsing request body failed",U),F.status(400).send();return}}Z()}}function _4A(A,q,K){let F="code"in K?`${q} (code: ${K.code}, message: ${K.message})`:`${q} (error: ${K})`;A.warn(F)}function b9K(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=O9K.default.createHmac("sha256",A),[Y,X]=K.split("=");if(U.update(`${Y}:${Z}:${q}`),!(0,_9K.default)(X,U.digest("hex")))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function uMq(A,q,K){let{"x-slack-signature":F,"x-slack-request-timestamp":Z,"content-type":$}=K;return b9K(A,q,F,Z),mMq(q,$)}b$.verifySignatureAndParseBody=uMq;function cMq(A){return async(q,K,F)=>{let Z=await pMq(q);try{let{"content-type":$}=q.headers;q.body=mMq(Z,$)}catch($){if($){_4A(A,"Parsing request body failed",$),K.status(400).send();return}}F()}}b$.buildBodyParserMiddleware=cMq;function mMq(A,q){if(q==="application/x-www-form-urlencoded"){let K=I9K.default.parse(A);if(typeof K.payload==="string")return JSON.parse(K.payload);return K}return JSON.parse(A)}async function pMq(A){if("rawBody"in A&&A.rawBody)return Promise.resolve(A.rawBody.toString());return(await(0,N9K.default)(A)).toString()}});var sMq=I((dMq)=>{Object.defineProperty(dMq,"__esModule",{value:!0});dMq.DefaultThreadContextStore=void 0;var iMq=w4A();class aMq{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,iMq.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,iMq.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}}dMq.DefaultThreadContextStore=aMq});var w4A=I((l9)=>{var v9K=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 k9K=sMq(),oMq=v8A(),SL=xY(),sp=tc(),C9K=v9K(ec()),f9K=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class rMq{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor(A){Kzq(A);let{threadContextStore:q=new k9K.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(eMq(A)&&Azq(A))return this.processEvent(A);return A.next()}}async processEvent(A){let{payload:q}=A,K=tMq(this.threadContextStore,A),F=this.getAssistantMiddleware(q);return Fzq(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=rMq;function tMq(A,q){let{next:K,...F}=q,Z={...F};return Z.getThreadContext=()=>A.get(q),Z.saveThreadContext=()=>A.save(q),Z.say=h9K(Z),Z.sayStream=y9K(Z),Z.setStatus=u9K(Z),Z.setSuggestedPrompts=c9K(Z),Z.setTitle=m9K(Z),Z}l9.enrichAssistantArgs=tMq;function eMq(A){return f9K.has(A.payload.type)}l9.isAssistantEvent=eMq;function Azq(A){return A.payload.type==="message"?qzq(A.payload):!0}l9.matchesConstraints=Azq;function qzq(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=qzq;function Kzq(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=Kzq;async function Fzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,C9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}l9.processAssistantMiddleware=Fzq;function h9K(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 y9K(A){let{client:q,context:K,payload:F}=A,{channelId:Z,threadTs:$}=sz(F);return(0,oMq.createSayStream)(q,K,Z,$)}function u9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return(0,oMq.createSetStatus)(q,F,Z)}function c9K(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 m9K(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,sp.isRecord)(A.assistant_thread)){if((0,sp.isRecord)(A.assistant_thread.context))q=A.assistant_thread.context}let K=(0,sp.extractEventChannelId)(A),F=(0,sp.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 Xzq=I((F8)=>{var p9K=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 op=xY(),l9K=p9K(ec()),i9K=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class Zzq{callbackId;edit;save;execute;constructor(A,q){$zq(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(Yzq(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=Qzq(A),F=this.getStepMiddleware(q);return Uzq(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=Zzq;function $zq(A,q){if(typeof A!=="string")throw new op.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof q!=="object")throw new op.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 op.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 op.WorkflowStepInitializationError(U)}}F8.validate=$zq;async function Uzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,l9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}F8.processStepMiddleware=Uzq;function Yzq(A){return i9K.has(A.payload.type)}F8.isStepEvent=Yzq;function rp(A){return A.botToken!==void 0?A.botToken:A.userToken}function a9K(A){let{context:q,client:K,body:{callback_id:F,trigger_id:Z}}=A,$=rp(q);return(U)=>K.views.open({token:$,trigger_id:Z,view:{callback_id:F,type:"workflow_step",...U}})}function d9K(A){let{context:q,client:K,body:{workflow_step:{workflow_step_edit_id:F}}}=A,Z=rp(q);return($={})=>K.workflows.updateStep({token:Z,workflow_step_edit_id:F,...$})}function n9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=rp(q);return($={})=>K.workflows.stepCompleted({token:Z,workflow_step_execute_id:F,...$})}function s9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=rp(q);return($)=>{let{error:U}=$;return K.workflows.stepFailed({token:Z,workflow_step_execute_id:F,error:U})}}function Qzq(A){let{next:q,...K}=A,F={...K};switch(F.payload.type){case"workflow_step_edit":F.step=F.action.workflow_step,F.configure=a9K(F);break;case"workflow_step":F.step=F.body.workflow_step,F.update=d9K(F);break;case"workflow_step_execute":F.step=F.event.workflow_step,F.complete=n9K(F),F.fail=s9K(F);break;default:break}return F}F8.prepareStepArgs=Qzq});var Ezq=I((WK)=>{var Gzq=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]}),o9K=WK&&WK.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),B4A=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))Gzq(q,A,K)}return o9K(q,A),q},D4A=WK&&WK.__exportStar||function(A,q){for(var K in A)if(K!=="default"&&!Object.prototype.hasOwnProperty.call(q,K))Gzq(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 jzq=fR(xjA());WK.App=jzq.default;var r9K=xjA();Object.defineProperty(WK,"LogLevel",{enumerable:!0,get:function(){return r9K.LogLevel}});WK.default=jzq.default;var Jzq=$jA();Object.defineProperty(WK,"verifySlackRequest",{enumerable:!0,get:function(){return Jzq.verifySlackRequest}});Object.defineProperty(WK,"isValidSlackRequest",{enumerable:!0,get:function(){return Jzq.isValidSlackRequest}});var t9K=fR(vLq());WK.AwsLambdaReceiver=t9K.default;var e9K=fR(lMq());WK.ExpressReceiver=e9K.default;var AUK=fR(YjA());WK.HTTPReceiver=AUK.default;var qUK=fR(HjA());WK.SocketModeReceiver=qUK.default;WK.HTTPModuleFunctions=B4A(JR());var KUK=Jp();Object.defineProperty(WK,"HTTPResponseAck",{enumerable:!0,get:function(){return KUK.HTTPResponseAck}});var FUK=JjA();Object.defineProperty(WK,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return FUK.defaultProcessEventErrorHandler}});D4A(xY(),WK);D4A(rc(),WK);D4A(WjA(),WK);var ZUK=k8A();Object.defineProperty(WK,"MemoryStore",{enumerable:!0,get:function(){return ZUK.MemoryStore}});var $UK=Hp();Object.defineProperty(WK,"buildReceiverRoutes",{enumerable:!0,get:function(){return $UK.buildReceiverRoutes}});var UUK=w4A();Object.defineProperty(WK,"Assistant",{enumerable:!0,get:function(){return UUK.Assistant}});var YUK=Xzq();Object.defineProperty(WK,"WorkflowStep",{enumerable:!0,get:function(){return YUK.WorkflowStep}});var Hzq=FR();Object.defineProperty(WK,"MemoryInstallationStore",{enumerable:!0,get:function(){return Hzq.MemoryInstallationStore}});Object.defineProperty(WK,"FileInstallationStore",{enumerable:!0,get:function(){return Hzq.FileInstallationStore}});WK.types=B4A(I8A());WK.webApi=B4A(oc())});var m7A={name:"@interactive-inc/claude-funnel",version:"0.25.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 u={};iG(u,{xor:()=>OHA,xid:()=>pJA,void:()=>EHA,uuidv7:()=>kJA,uuidv6:()=>vJA,uuidv4:()=>bJA,uuid:()=>SJA,util:()=>oq,url:()=>CJA,uppercase:()=>Yx,unknown:()=>g5,union:()=>fb,undefined:()=>JHA,ulid:()=>mJA,uint64:()=>GHA,uint32:()=>YHA,tuple:()=>uo,trim:()=>Hx,treeifyError:()=>Ri,transform:()=>yb,toUpperCase:()=>Wx,toLowerCase:()=>Ex,toJSONSchema:()=>Gb,templateLiteral:()=>vHA,symbol:()=>jHA,superRefine:()=>Wr,success:()=>RHA,stringbool:()=>mHA,stringFormat:()=>AHA,string:()=>nP,strictObject:()=>LHA,startsWith:()=>Xx,slugify:()=>gx,size:()=>H5,setErrorMap:()=>vNq,set:()=>NHA,safeParseAsync:()=>Eo,safeParse:()=>Ho,safeEncodeAsync:()=>Mo,safeEncode:()=>xo,safeDecodeAsync:()=>zo,safeDecode:()=>Oo,registry:()=>kS,regexes:()=>O8,regex:()=>$x,refine:()=>Er,record:()=>co,readonly:()=>Qr,property:()=>Ub,promise:()=>kHA,prettifyError:()=>Ti,preprocess:()=>lHA,prefault:()=>Ar,positive:()=>Kb,pipe:()=>Vb,partialRecord:()=>zHA,parseAsync:()=>Jo,parse:()=>jo,overwrite:()=>aG,optional:()=>oP,object:()=>VHA,number:()=>Po,nullish:()=>DHA,nullable:()=>rP,null:()=>Do,normalize:()=>Jx,nonpositive:()=>Zb,nonoptional:()=>qr,nonnegative:()=>$b,never:()=>Cb,negative:()=>Fb,nativeEnum:()=>_HA,nanoid:()=>yJA,nan:()=>THA,multipleOf:()=>xE,minSize:()=>x4,minLength:()=>$J,mime:()=>jx,meta:()=>uHA,maxSize:()=>OE,maxLength:()=>E5,map:()=>PHA,mac:()=>aJA,lte:()=>M8,lt:()=>V4,lowercase:()=>Ux,looseRecord:()=>IHA,looseObject:()=>xHA,locales:()=>lP,literal:()=>wHA,length:()=>W5,lazy:()=>jr,ksuid:()=>lJA,keyof:()=>gHA,jwt:()=>eJA,json:()=>pHA,iso:()=>xx,ipv6:()=>dJA,ipv4:()=>iJA,invertCodec:()=>bHA,intersection:()=>ho,int64:()=>XHA,int32:()=>UHA,int:()=>gb,instanceof:()=>cHA,includes:()=>Qx,httpUrl:()=>fJA,hostname:()=>qHA,hex:()=>KHA,hash:()=>FHA,guid:()=>TJA,gte:()=>DQ,gt:()=>L4,globalRegistry:()=>rU,getErrorMap:()=>kNq,function:()=>CHA,fromJSONSchema:()=>aHA,formatError:()=>bP,float64:()=>$HA,float32:()=>ZHA,flattenError:()=>SP,file:()=>BHA,exactOptional:()=>so,enum:()=>hb,endsWith:()=>Gx,encodeAsync:()=>Vo,encode:()=>Wo,emoji:()=>hJA,email:()=>RJA,e164:()=>tJA,discriminatedUnion:()=>MHA,describe:()=>yHA,decodeAsync:()=>Lo,decode:()=>go,date:()=>WHA,custom:()=>hHA,cuid2:()=>cJA,cuid:()=>uJA,core:()=>UJ,config:()=>d$,coerce:()=>Vr,codec:()=>SHA,clone:()=>wQ,cidrv6:()=>sJA,cidrv4:()=>nJA,check:()=>fHA,catch:()=>Zr,boolean:()=>No,bigint:()=>QHA,base64url:()=>rJA,base64:()=>oJA,array:()=>qN,any:()=>HHA,_function:()=>CHA,_default:()=>to,_ZodString:()=>Lb,ZodXor:()=>ko,ZodXID:()=>Nb,ZodVoid:()=>bo,ZodUnknown:()=>To,ZodUnion:()=>FN,ZodUndefined:()=>wo,ZodUUID:()=>O4,ZodURL:()=>eP,ZodULID:()=>Pb,ZodType:()=>ZF,ZodTuple:()=>yo,ZodTransform:()=>ao,ZodTemplateLiteral:()=>Xr,ZodSymbol:()=>_o,ZodSuccess:()=>Kr,ZodStringFormat:()=>o1,ZodString:()=>zx,ZodSet:()=>po,ZodRecord:()=>Ox,ZodRealError:()=>_0,ZodReadonly:()=>Yr,ZodPromise:()=>Jr,ZodPreprocess:()=>Ur,ZodPrefault:()=>eo,ZodPipe:()=>ZN,ZodOptional:()=>ub,ZodObject:()=>KN,ZodNumberFormat:()=>V5,ZodNumber:()=>Px,ZodNullable:()=>oo,ZodNull:()=>Bo,ZodNonOptional:()=>cb,ZodNever:()=>So,ZodNanoID:()=>Mb,ZodNaN:()=>$r,ZodMap:()=>mo,ZodMAC:()=>Io,ZodLiteral:()=>lo,ZodLazy:()=>Gr,ZodKSUID:()=>_b,ZodJWT:()=>vb,ZodIssueCode:()=>bNq,ZodIntersection:()=>fo,ZodISOTime:()=>Eb,ZodISODuration:()=>Wb,ZodISODateTime:()=>Jb,ZodISODate:()=>Hb,ZodIPv6:()=>Bb,ZodIPv4:()=>wb,ZodGUID:()=>sP,ZodFunction:()=>Hr,ZodFirstPartyTypeKind:()=>gr,ZodFile:()=>io,ZodExactOptional:()=>no,ZodError:()=>TNq,ZodEnum:()=>Mx,ZodEmoji:()=>Ob,ZodEmail:()=>xb,ZodE164:()=>bb,ZodDiscriminatedUnion:()=>Co,ZodDefault:()=>ro,ZodDate:()=>AN,ZodCustomStringFormat:()=>Ix,ZodCustom:()=>UN,ZodCodec:()=>$N,ZodCatch:()=>Fr,ZodCUID2:()=>Ib,ZodCUID:()=>zb,ZodCIDRv6:()=>Rb,ZodCIDRv4:()=>Db,ZodBoolean:()=>Nx,ZodBigIntFormat:()=>kb,ZodBigInt:()=>_x,ZodBase64URL:()=>Sb,ZodBase64:()=>Tb,ZodArray:()=>vo,ZodAny:()=>Ro,TimePrecision:()=>yn,NEVER:()=>Li,$output:()=>bn,$input:()=>vn,$brand:()=>xi});var UJ={};iG(UJ,{version:()=>wa,util:()=>oq,treeifyError:()=>Ri,toJSONSchema:()=>Gb,toDotPath:()=>s7A,safeParseAsync:()=>bi,safeParse:()=>Si,safeEncodeAsync:()=>bIq,safeEncode:()=>TIq,safeDecodeAsync:()=>vIq,safeDecode:()=>SIq,registry:()=>kS,regexes:()=>O8,process:()=>D1,prettifyError:()=>Ti,parseAsync:()=>HS,parse:()=>JS,meta:()=>Os,locales:()=>lP,isValidJWT:()=>VJA,isValidBase64URL:()=>gJA,isValidBase64:()=>sa,initializeContext:()=>ME,globalRegistry:()=>rU,globalConfig:()=>Q5,formatError:()=>bP,flattenError:()=>SP,finalize:()=>IE,extractDefs:()=>zE,encodeAsync:()=>DIq,encode:()=>wIq,describe:()=>xs,decodeAsync:()=>RIq,decode:()=>BIq,createToJSONSchemaMethod:()=>zs,createStandardJSONSchemaMethod:()=>Lx,config:()=>d$,clone:()=>wQ,_xor:()=>YNq,_xid:()=>aS,_void:()=>Gs,_uuidv7:()=>uS,_uuidv6:()=>yS,_uuidv4:()=>hS,_uuid:()=>fS,_url:()=>aP,_uppercase:()=>Yx,_unknown:()=>Qs,_union:()=>UNq,_undefined:()=>$s,_ulid:()=>iS,_uint64:()=>Fs,_uint32:()=>rn,_tuple:()=>GNq,_trim:()=>Hx,_transform:()=>VNq,_toUpperCase:()=>Wx,_toLowerCase:()=>Ex,_templateLiteral:()=>_Nq,_symbol:()=>Zs,_superRefine:()=>Ls,_success:()=>zNq,_stringbool:()=>Ms,_stringFormat:()=>Vx,_string:()=>Cn,_startsWith:()=>Xx,_slugify:()=>gx,_size:()=>H5,_set:()=>HNq,_safeParseAsync:()=>Kx,_safeParse:()=>qx,_safeEncodeAsync:()=>OS,_safeEncode:()=>LS,_safeDecodeAsync:()=>MS,_safeDecode:()=>xS,_regex:()=>$x,_refine:()=>Vs,_record:()=>jNq,_readonly:()=>NNq,_property:()=>Ub,_promise:()=>BNq,_positive:()=>Kb,_pipe:()=>PNq,_parseAsync:()=>Ax,_parse:()=>e2,_overwrite:()=>aG,_optional:()=>LNq,_number:()=>ln,_nullable:()=>xNq,_null:()=>Us,_normalize:()=>Jx,_nonpositive:()=>Zb,_nonoptional:()=>MNq,_nonnegative:()=>$b,_never:()=>Xs,_negative:()=>Fb,_nativeEnum:()=>WNq,_nanoid:()=>mS,_nan:()=>Hs,_multipleOf:()=>xE,_minSize:()=>x4,_minLength:()=>$J,_min:()=>DQ,_mime:()=>jx,_maxSize:()=>OE,_maxLength:()=>E5,_max:()=>M8,_map:()=>JNq,_mac:()=>hn,_lte:()=>M8,_lt:()=>V4,_lowercase:()=>Ux,_literal:()=>gNq,_length:()=>W5,_lazy:()=>wNq,_ksuid:()=>dS,_jwt:()=>qb,_isoTime:()=>mn,_isoDuration:()=>pn,_isoDateTime:()=>un,_isoDate:()=>cn,_ipv6:()=>sS,_ipv4:()=>nS,_intersection:()=>XNq,_int64:()=>Ks,_int32:()=>on,_int:()=>dn,_includes:()=>Qx,_guid:()=>iP,_gte:()=>DQ,_gt:()=>L4,_float64:()=>sn,_float32:()=>nn,_file:()=>Ws,_enum:()=>ENq,_endsWith:()=>Gx,_encodeAsync:()=>gS,_encode:()=>ES,_emoji:()=>cS,_email:()=>CS,_e164:()=>Ab,_discriminatedUnion:()=>QNq,_default:()=>ONq,_decodeAsync:()=>VS,_decode:()=>WS,_date:()=>js,_custom:()=>gs,_cuid2:()=>lS,_cuid:()=>pS,_coercedString:()=>fn,_coercedNumber:()=>an,_coercedDate:()=>Js,_coercedBoolean:()=>en,_coercedBigint:()=>qs,_cidrv6:()=>rS,_cidrv4:()=>oS,_check:()=>_JA,_catch:()=>INq,_boolean:()=>tn,_bigint:()=>As,_base64url:()=>eS,_base64:()=>tS,_array:()=>Es,_any:()=>Ys,TimePrecision:()=>yn,NEVER:()=>Li,JSONSchemaGenerator:()=>Uo,JSONSchema:()=>wJA,Doc:()=>NS,$output:()=>bn,$input:()=>vn,$constructor:()=>nA,$brand:()=>xi,$ZodXor:()=>Hd,$ZodXID:()=>ha,$ZodVoid:()=>Xd,$ZodUnknown:()=>Yd,$ZodUnion:()=>hP,$ZodUndefined:()=>Zd,$ZodUUID:()=>Ra,$ZodURL:()=>Sa,$ZodULID:()=>fa,$ZodType:()=>yK,$ZodTuple:()=>SS,$ZodTransform:()=>zd,$ZodTemplateLiteral:()=>bd,$ZodSymbol:()=>Fd,$ZodSuccess:()=>Bd,$ZodStringFormat:()=>s1,$ZodString:()=>J5,$ZodSet:()=>Ld,$ZodRegistry:()=>kn,$ZodRecord:()=>gd,$ZodRealError:()=>N0,$ZodReadonly:()=>Sd,$ZodPromise:()=>kd,$ZodPreprocess:()=>Td,$ZodPrefault:()=>_d,$ZodPipe:()=>vS,$ZodOptional:()=>bS,$ZodObjectJIT:()=>Jd,$ZodObject:()=>OJA,$ZodNumberFormat:()=>qd,$ZodNumber:()=>RS,$ZodNullable:()=>Pd,$ZodNull:()=>$d,$ZodNonOptional:()=>wd,$ZodNever:()=>Qd,$ZodNanoID:()=>va,$ZodNaN:()=>Rd,$ZodMap:()=>Vd,$ZodMAC:()=>aa,$ZodLiteral:()=>Od,$ZodLazy:()=>Cd,$ZodKSUID:()=>ya,$ZodJWT:()=>ea,$ZodIntersection:()=>Wd,$ZodISOTime:()=>ma,$ZodISODuration:()=>pa,$ZodISODateTime:()=>ua,$ZodISODate:()=>ca,$ZodIPv6:()=>ia,$ZodIPv4:()=>la,$ZodGUID:()=>Da,$ZodFunction:()=>vd,$ZodFile:()=>Md,$ZodExactOptional:()=>Id,$ZodError:()=>TP,$ZodEnum:()=>xd,$ZodEncodeError:()=>X5,$ZodEmoji:()=>ba,$ZodEmail:()=>Ta,$ZodE164:()=>ta,$ZodDiscriminatedUnion:()=>Ed,$ZodDefault:()=>Nd,$ZodDate:()=>Gd,$ZodCustomStringFormat:()=>Ad,$ZodCustom:()=>fd,$ZodCodec:()=>yP,$ZodCheckUpperCase:()=>Oa,$ZodCheckStringFormat:()=>Fx,$ZodCheckStartsWith:()=>za,$ZodCheckSizeEquals:()=>Ea,$ZodCheckRegex:()=>La,$ZodCheckProperty:()=>Pa,$ZodCheckOverwrite:()=>_a,$ZodCheckNumberFormat:()=>Ga,$ZodCheckMultipleOf:()=>Xa,$ZodCheckMinSize:()=>Ha,$ZodCheckMinLength:()=>ga,$ZodCheckMimeType:()=>Na,$ZodCheckMaxSize:()=>Ja,$ZodCheckMaxLength:()=>Wa,$ZodCheckLowerCase:()=>xa,$ZodCheckLessThan:()=>IS,$ZodCheckLengthEquals:()=>Va,$ZodCheckIncludes:()=>Ma,$ZodCheckGreaterThan:()=>PS,$ZodCheckEndsWith:()=>Ia,$ZodCheckBigIntFormat:()=>ja,$ZodCheck:()=>XZ,$ZodCatch:()=>Dd,$ZodCUID2:()=>Ca,$ZodCUID:()=>ka,$ZodCIDRv6:()=>na,$ZodCIDRv4:()=>da,$ZodBoolean:()=>fP,$ZodBigIntFormat:()=>Kd,$ZodBigInt:()=>TS,$ZodBase64URL:()=>ra,$ZodBase64:()=>oa,$ZodAsyncError:()=>g4,$ZodArray:()=>jd,$ZodAny:()=>Ud});var p7A,Li=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 xi=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"}}(p7A=globalThis).__zod_globalConfig??(p7A.__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:()=>NIq,uint8ArrayToBase64url:()=>IIq,uint8ArrayToBase64:()=>a7A,stringifyPrimitive:()=>pq,slugify:()=>zi,shallowClone:()=>Pi,safeExtend:()=>VIq,required:()=>OIq,randomString:()=>GIq,propertyKeyTypes:()=>BP,promiseAllObject:()=>XIq,primitiveTypes:()=>Ni,prefixIssues:()=>P0,pick:()=>EIq,partial:()=>xIq,parsedType:()=>nq,optionalKeys:()=>_i,omit:()=>WIq,objectClone:()=>UIq,numKeys:()=>jIq,nullish:()=>WE,normalizeParams:()=>A6,mergeDefs:()=>ZJ,merge:()=>LIq,jsonStringifyReplacer:()=>o2,joinValues:()=>Qq,issue:()=>t2,isPlainObject:()=>VE,isObject:()=>G5,hexToUint8Array:()=>PIq,getSizableOrigin:()=>DP,getParsedType:()=>JIq,getLengthableOrigin:()=>RP,getEnumValues:()=>_P,getElementAtPath:()=>QIq,floatSafeRemainder:()=>Mi,finalizeIssue:()=>BQ,extend:()=>gIq,explicitlyAborted:()=>Di,escapeRegex:()=>PX,esc:()=>GS,defineLazy:()=>NF,createTransparentProxy:()=>HIq,cloneDef:()=>YIq,clone:()=>wQ,cleanRegex:()=>wP,cleanEnum:()=>MIq,captureStackTrace:()=>jS,cached:()=>r2,base64urlToUint8Array:()=>zIq,base64ToUint8Array:()=>i7A,assignProp:()=>gE,assertNotEqual:()=>KIq,assertNever:()=>ZIq,assertIs:()=>FIq,assertEqual:()=>qIq,assert:()=>$Iq,allowsEval:()=>Ii,aborted:()=>LE,NUMBER_FORMAT_RANGES:()=>wi,Class:()=>d7A,BIGINT_FORMAT_RANGES:()=>Bi});function qIq(A){return A}function KIq(A){return A}function FIq(A){}function ZIq(A){throw Error("Unexpected value in exhaustive check")}function $Iq(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 Mi(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 l7A=Symbol("evaluating");function NF(A,q,K){let F=void 0;Object.defineProperty(A,q,{get(){if(F===l7A)return;if(F===void 0)F=l7A,F=K();return F},set(Z){Object.defineProperty(A,q,{value:Z})},configurable:!0})}function UIq(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 YIq(A){return ZJ(A._zod.def)}function QIq(A,q){if(!q)return A;return q.reduce((K,F)=>K?.[F],A)}function XIq(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 GIq(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 zi(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 Ii=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 Pi(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 jIq(A){let q=0;for(let K in A)if(Object.prototype.hasOwnProperty.call(A,K))q++;return q}var JIq=(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"]),Ni=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 HIq(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 _i(A){return Object.keys(A).filter((q)=>{return A[q]._zod.optin==="optional"&&A[q]._zod.optout==="optional"})}var wi={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]},Bi={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function EIq(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 WIq(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 gIq(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 VIq(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 LIq(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 xIq(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 OIq(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 Di(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 MIq(A){return Object.entries(A).filter(([q,K])=>{return Number.isNaN(Number.parseInt(q,10))}).map((q)=>q[1])}function i7A(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 a7A(A){let q="";for(let K=0;K<A.length;K++)q+=String.fromCharCode(A[K]);return btoa(q)}function zIq(A){let q=A.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-q.length%4)%4);return i7A(q+K)}function IIq(A){return a7A(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function PIq(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 NIq(A){return Array.from(A).map((q)=>q.toString(16).padStart(2,"0")).join("")}class d7A{constructor(...A){}}var n7A=(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",n7A),N0=nA("$ZodError",n7A,{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 Ri(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 s7A(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 Ti(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 ${s7A(F.path)}`);return q.join(`
|
|
907
|
+
*/var dp=Jxq(),g9K=gA("events").EventEmitter,BMq=Exq(),DMq=VOq(),RMq=U4A(),TMq=aOq(),SMq=NMq();ZG=bMq.exports=V9K;function V9K(){var A=function(q,K,F){A.handle(q,K,F)};return BMq(A,g9K.prototype,!1),BMq(A,DMq,!1),A.request=Object.create(TMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.response=Object.create(SMq,{app:{configurable:!0,enumerable:!0,writable:!0,value:A}}),A.init(),A}ZG.application=DMq;ZG.request=TMq;ZG.response=SMq;ZG.Route=RMq.Route;ZG.Router=RMq;ZG.json=dp.json;ZG.raw=dp.raw;ZG.static=wMq();ZG.text=dp.text;ZG.urlencoded=dp.urlencoded});var lMq=I((b$)=>{var L9K=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]}),x9K=b$&&b$.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),fMq=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))L9K(q,A,K)}return x9K(q,A),q},np=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 O9K=np(gA("crypto")),M9K=gA("http"),z9K=gA("https"),I9K=np(gA("querystring")),kMq=gY(),P9K=FR(),CMq=fMq(vMq()),N9K=np(Xp()),_9K=np(Gp()),Z7=xY(),nz=fMq(JR()),w9K=Jp(),B9K=Ep(),D9K=["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"],N4A="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",R9K=(A,q,K)=>{if(A.body?.ssl_check){q.send();return}K()};b$.respondToSslCheck=R9K;var T9K=(A,q,K)=>{if(A.body?.type&&A.body.type==="url_verification"){q.json({challenge:A.body.challenge});return}K()};b$.respondToUrlVerification=T9K;class hMq{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=kMq.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,CMq.default)(),typeof q<"u")this.logger=q;else this.logger=new kMq.ConsoleLogger,this.logger.setLevel(K);this.signatureVerification=$;let y=[this.signatureVerification?yMq(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,CMq.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,B9K.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 P9K.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 w9K.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=M9K.createServer;if(Object.keys(q).filter((F)=>D9K.includes(F)).length>0)K=z9K.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(N4A);this.server.on("error",($)=>{if(this.server===void 0)throw new Z7.ReceiverInconsistentStateError(N4A);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(N4A));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=hMq;function S9K(A,q){return yMq(A,q)}b$.verifySignatureAndParseRawBody=S9K;function yMq(A,q){return async(K,F,Z)=>{let $=await pMq(K);try{K.body=uMq(typeof q==="string"?q:await q(),$,K.headers)}catch(U){if(U){if(U instanceof Z7.ReceiverAuthenticityError){_4A(A,"Request verification failed",U),F.status(401).send();return}_4A(A,"Parsing request body failed",U),F.status(400).send();return}}Z()}}function _4A(A,q,K){let F="code"in K?`${q} (code: ${K.code}, message: ${K.message})`:`${q} (error: ${K})`;A.warn(F)}function b9K(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=O9K.default.createHmac("sha256",A),[Y,X]=K.split("=");if(U.update(`${Y}:${Z}:${q}`),!(0,_9K.default)(X,U.digest("hex")))throw new Z7.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function uMq(A,q,K){let{"x-slack-signature":F,"x-slack-request-timestamp":Z,"content-type":$}=K;return b9K(A,q,F,Z),mMq(q,$)}b$.verifySignatureAndParseBody=uMq;function cMq(A){return async(q,K,F)=>{let Z=await pMq(q);try{let{"content-type":$}=q.headers;q.body=mMq(Z,$)}catch($){if($){_4A(A,"Parsing request body failed",$),K.status(400).send();return}}F()}}b$.buildBodyParserMiddleware=cMq;function mMq(A,q){if(q==="application/x-www-form-urlencoded"){let K=I9K.default.parse(A);if(typeof K.payload==="string")return JSON.parse(K.payload);return K}return JSON.parse(A)}async function pMq(A){if("rawBody"in A&&A.rawBody)return Promise.resolve(A.rawBody.toString());return(await(0,N9K.default)(A)).toString()}});var sMq=I((dMq)=>{Object.defineProperty(dMq,"__esModule",{value:!0});dMq.DefaultThreadContextStore=void 0;var iMq=w4A();class aMq{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,iMq.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,iMq.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}}dMq.DefaultThreadContextStore=aMq});var w4A=I((l9)=>{var v9K=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 k9K=sMq(),oMq=v8A(),SL=xY(),sp=tc(),C9K=v9K(ec()),f9K=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class rMq{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor(A){Kzq(A);let{threadContextStore:q=new k9K.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(eMq(A)&&Azq(A))return this.processEvent(A);return A.next()}}async processEvent(A){let{payload:q}=A,K=tMq(this.threadContextStore,A),F=this.getAssistantMiddleware(q);return Fzq(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=rMq;function tMq(A,q){let{next:K,...F}=q,Z={...F};return Z.getThreadContext=()=>A.get(q),Z.saveThreadContext=()=>A.save(q),Z.say=h9K(Z),Z.sayStream=y9K(Z),Z.setStatus=u9K(Z),Z.setSuggestedPrompts=c9K(Z),Z.setTitle=m9K(Z),Z}l9.enrichAssistantArgs=tMq;function eMq(A){return f9K.has(A.payload.type)}l9.isAssistantEvent=eMq;function Azq(A){return A.payload.type==="message"?qzq(A.payload):!0}l9.matchesConstraints=Azq;function qzq(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=qzq;function Kzq(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=Kzq;async function Fzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,C9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}l9.processAssistantMiddleware=Fzq;function h9K(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 y9K(A){let{client:q,context:K,payload:F}=A,{channelId:Z,threadTs:$}=sz(F);return(0,oMq.createSayStream)(q,K,Z,$)}function u9K(A){let{client:q,payload:K}=A,{channelId:F,threadTs:Z}=sz(K);return(0,oMq.createSetStatus)(q,F,Z)}function c9K(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 m9K(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,sp.isRecord)(A.assistant_thread)){if((0,sp.isRecord)(A.assistant_thread.context))q=A.assistant_thread.context}let K=(0,sp.extractEventChannelId)(A),F=(0,sp.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 Xzq=I((F8)=>{var p9K=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 op=xY(),l9K=p9K(ec()),i9K=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class Zzq{callbackId;edit;save;execute;constructor(A,q){$zq(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(Yzq(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=Qzq(A),F=this.getStepMiddleware(q);return Uzq(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=Zzq;function $zq(A,q){if(typeof A!=="string")throw new op.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof q!=="object")throw new op.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 op.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 op.WorkflowStepInitializationError(U)}}F8.validate=$zq;async function Uzq(A,q){let{context:K,client:F,logger:Z}=A,$=[...q],U=$.pop();if(U!==void 0)await(0,l9K.default)($,A,K,F,Z,async()=>U({...A,context:K,client:F,logger:Z}))}F8.processStepMiddleware=Uzq;function Yzq(A){return i9K.has(A.payload.type)}F8.isStepEvent=Yzq;function rp(A){return A.botToken!==void 0?A.botToken:A.userToken}function a9K(A){let{context:q,client:K,body:{callback_id:F,trigger_id:Z}}=A,$=rp(q);return(U)=>K.views.open({token:$,trigger_id:Z,view:{callback_id:F,type:"workflow_step",...U}})}function d9K(A){let{context:q,client:K,body:{workflow_step:{workflow_step_edit_id:F}}}=A,Z=rp(q);return($={})=>K.workflows.updateStep({token:Z,workflow_step_edit_id:F,...$})}function n9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=rp(q);return($={})=>K.workflows.stepCompleted({token:Z,workflow_step_execute_id:F,...$})}function s9K(A){let{context:q,client:K,payload:{workflow_step:{workflow_step_execute_id:F}}}=A,Z=rp(q);return($)=>{let{error:U}=$;return K.workflows.stepFailed({token:Z,workflow_step_execute_id:F,error:U})}}function Qzq(A){let{next:q,...K}=A,F={...K};switch(F.payload.type){case"workflow_step_edit":F.step=F.action.workflow_step,F.configure=a9K(F);break;case"workflow_step":F.step=F.body.workflow_step,F.update=d9K(F);break;case"workflow_step_execute":F.step=F.event.workflow_step,F.complete=n9K(F),F.fail=s9K(F);break;default:break}return F}F8.prepareStepArgs=Qzq});var Ezq=I((WK)=>{var Gzq=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]}),o9K=WK&&WK.__setModuleDefault||(Object.create?function(A,q){Object.defineProperty(A,"default",{enumerable:!0,value:q})}:function(A,q){A.default=q}),B4A=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))Gzq(q,A,K)}return o9K(q,A),q},D4A=WK&&WK.__exportStar||function(A,q){for(var K in A)if(K!=="default"&&!Object.prototype.hasOwnProperty.call(q,K))Gzq(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 jzq=fR(xjA());WK.App=jzq.default;var r9K=xjA();Object.defineProperty(WK,"LogLevel",{enumerable:!0,get:function(){return r9K.LogLevel}});WK.default=jzq.default;var Jzq=$jA();Object.defineProperty(WK,"verifySlackRequest",{enumerable:!0,get:function(){return Jzq.verifySlackRequest}});Object.defineProperty(WK,"isValidSlackRequest",{enumerable:!0,get:function(){return Jzq.isValidSlackRequest}});var t9K=fR(vLq());WK.AwsLambdaReceiver=t9K.default;var e9K=fR(lMq());WK.ExpressReceiver=e9K.default;var AUK=fR(YjA());WK.HTTPReceiver=AUK.default;var qUK=fR(HjA());WK.SocketModeReceiver=qUK.default;WK.HTTPModuleFunctions=B4A(JR());var KUK=Jp();Object.defineProperty(WK,"HTTPResponseAck",{enumerable:!0,get:function(){return KUK.HTTPResponseAck}});var FUK=JjA();Object.defineProperty(WK,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return FUK.defaultProcessEventErrorHandler}});D4A(xY(),WK);D4A(rc(),WK);D4A(WjA(),WK);var ZUK=k8A();Object.defineProperty(WK,"MemoryStore",{enumerable:!0,get:function(){return ZUK.MemoryStore}});var $UK=Hp();Object.defineProperty(WK,"buildReceiverRoutes",{enumerable:!0,get:function(){return $UK.buildReceiverRoutes}});var UUK=w4A();Object.defineProperty(WK,"Assistant",{enumerable:!0,get:function(){return UUK.Assistant}});var YUK=Xzq();Object.defineProperty(WK,"WorkflowStep",{enumerable:!0,get:function(){return YUK.WorkflowStep}});var Hzq=FR();Object.defineProperty(WK,"MemoryInstallationStore",{enumerable:!0,get:function(){return Hzq.MemoryInstallationStore}});Object.defineProperty(WK,"FileInstallationStore",{enumerable:!0,get:function(){return Hzq.FileInstallationStore}});WK.types=B4A(I8A());WK.webApi=B4A(oc())});var m7A={name:"@interactive-inc/claude-funnel",version:"0.25.2",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 u={};iG(u,{xor:()=>OHA,xid:()=>pJA,void:()=>EHA,uuidv7:()=>kJA,uuidv6:()=>vJA,uuidv4:()=>bJA,uuid:()=>SJA,util:()=>oq,url:()=>CJA,uppercase:()=>Yx,unknown:()=>g5,union:()=>fb,undefined:()=>JHA,ulid:()=>mJA,uint64:()=>GHA,uint32:()=>YHA,tuple:()=>uo,trim:()=>Hx,treeifyError:()=>Ri,transform:()=>yb,toUpperCase:()=>Wx,toLowerCase:()=>Ex,toJSONSchema:()=>Gb,templateLiteral:()=>vHA,symbol:()=>jHA,superRefine:()=>Wr,success:()=>RHA,stringbool:()=>mHA,stringFormat:()=>AHA,string:()=>nP,strictObject:()=>LHA,startsWith:()=>Xx,slugify:()=>gx,size:()=>H5,setErrorMap:()=>vNq,set:()=>NHA,safeParseAsync:()=>Eo,safeParse:()=>Ho,safeEncodeAsync:()=>Mo,safeEncode:()=>xo,safeDecodeAsync:()=>zo,safeDecode:()=>Oo,registry:()=>kS,regexes:()=>O8,regex:()=>$x,refine:()=>Er,record:()=>co,readonly:()=>Qr,property:()=>Ub,promise:()=>kHA,prettifyError:()=>Ti,preprocess:()=>lHA,prefault:()=>Ar,positive:()=>Kb,pipe:()=>Vb,partialRecord:()=>zHA,parseAsync:()=>Jo,parse:()=>jo,overwrite:()=>aG,optional:()=>oP,object:()=>VHA,number:()=>Po,nullish:()=>DHA,nullable:()=>rP,null:()=>Do,normalize:()=>Jx,nonpositive:()=>Zb,nonoptional:()=>qr,nonnegative:()=>$b,never:()=>Cb,negative:()=>Fb,nativeEnum:()=>_HA,nanoid:()=>yJA,nan:()=>THA,multipleOf:()=>xE,minSize:()=>x4,minLength:()=>$J,mime:()=>jx,meta:()=>uHA,maxSize:()=>OE,maxLength:()=>E5,map:()=>PHA,mac:()=>aJA,lte:()=>M8,lt:()=>V4,lowercase:()=>Ux,looseRecord:()=>IHA,looseObject:()=>xHA,locales:()=>lP,literal:()=>wHA,length:()=>W5,lazy:()=>jr,ksuid:()=>lJA,keyof:()=>gHA,jwt:()=>eJA,json:()=>pHA,iso:()=>xx,ipv6:()=>dJA,ipv4:()=>iJA,invertCodec:()=>bHA,intersection:()=>ho,int64:()=>XHA,int32:()=>UHA,int:()=>gb,instanceof:()=>cHA,includes:()=>Qx,httpUrl:()=>fJA,hostname:()=>qHA,hex:()=>KHA,hash:()=>FHA,guid:()=>TJA,gte:()=>DQ,gt:()=>L4,globalRegistry:()=>rU,getErrorMap:()=>kNq,function:()=>CHA,fromJSONSchema:()=>aHA,formatError:()=>bP,float64:()=>$HA,float32:()=>ZHA,flattenError:()=>SP,file:()=>BHA,exactOptional:()=>so,enum:()=>hb,endsWith:()=>Gx,encodeAsync:()=>Vo,encode:()=>Wo,emoji:()=>hJA,email:()=>RJA,e164:()=>tJA,discriminatedUnion:()=>MHA,describe:()=>yHA,decodeAsync:()=>Lo,decode:()=>go,date:()=>WHA,custom:()=>hHA,cuid2:()=>cJA,cuid:()=>uJA,core:()=>UJ,config:()=>d$,coerce:()=>Vr,codec:()=>SHA,clone:()=>wQ,cidrv6:()=>sJA,cidrv4:()=>nJA,check:()=>fHA,catch:()=>Zr,boolean:()=>No,bigint:()=>QHA,base64url:()=>rJA,base64:()=>oJA,array:()=>qN,any:()=>HHA,_function:()=>CHA,_default:()=>to,_ZodString:()=>Lb,ZodXor:()=>ko,ZodXID:()=>Nb,ZodVoid:()=>bo,ZodUnknown:()=>To,ZodUnion:()=>FN,ZodUndefined:()=>wo,ZodUUID:()=>O4,ZodURL:()=>eP,ZodULID:()=>Pb,ZodType:()=>ZF,ZodTuple:()=>yo,ZodTransform:()=>ao,ZodTemplateLiteral:()=>Xr,ZodSymbol:()=>_o,ZodSuccess:()=>Kr,ZodStringFormat:()=>o1,ZodString:()=>zx,ZodSet:()=>po,ZodRecord:()=>Ox,ZodRealError:()=>_0,ZodReadonly:()=>Yr,ZodPromise:()=>Jr,ZodPreprocess:()=>Ur,ZodPrefault:()=>eo,ZodPipe:()=>ZN,ZodOptional:()=>ub,ZodObject:()=>KN,ZodNumberFormat:()=>V5,ZodNumber:()=>Px,ZodNullable:()=>oo,ZodNull:()=>Bo,ZodNonOptional:()=>cb,ZodNever:()=>So,ZodNanoID:()=>Mb,ZodNaN:()=>$r,ZodMap:()=>mo,ZodMAC:()=>Io,ZodLiteral:()=>lo,ZodLazy:()=>Gr,ZodKSUID:()=>_b,ZodJWT:()=>vb,ZodIssueCode:()=>bNq,ZodIntersection:()=>fo,ZodISOTime:()=>Eb,ZodISODuration:()=>Wb,ZodISODateTime:()=>Jb,ZodISODate:()=>Hb,ZodIPv6:()=>Bb,ZodIPv4:()=>wb,ZodGUID:()=>sP,ZodFunction:()=>Hr,ZodFirstPartyTypeKind:()=>gr,ZodFile:()=>io,ZodExactOptional:()=>no,ZodError:()=>TNq,ZodEnum:()=>Mx,ZodEmoji:()=>Ob,ZodEmail:()=>xb,ZodE164:()=>bb,ZodDiscriminatedUnion:()=>Co,ZodDefault:()=>ro,ZodDate:()=>AN,ZodCustomStringFormat:()=>Ix,ZodCustom:()=>UN,ZodCodec:()=>$N,ZodCatch:()=>Fr,ZodCUID2:()=>Ib,ZodCUID:()=>zb,ZodCIDRv6:()=>Rb,ZodCIDRv4:()=>Db,ZodBoolean:()=>Nx,ZodBigIntFormat:()=>kb,ZodBigInt:()=>_x,ZodBase64URL:()=>Sb,ZodBase64:()=>Tb,ZodArray:()=>vo,ZodAny:()=>Ro,TimePrecision:()=>yn,NEVER:()=>Li,$output:()=>bn,$input:()=>vn,$brand:()=>xi});var UJ={};iG(UJ,{version:()=>wa,util:()=>oq,treeifyError:()=>Ri,toJSONSchema:()=>Gb,toDotPath:()=>s7A,safeParseAsync:()=>bi,safeParse:()=>Si,safeEncodeAsync:()=>bIq,safeEncode:()=>TIq,safeDecodeAsync:()=>vIq,safeDecode:()=>SIq,registry:()=>kS,regexes:()=>O8,process:()=>D1,prettifyError:()=>Ti,parseAsync:()=>HS,parse:()=>JS,meta:()=>Os,locales:()=>lP,isValidJWT:()=>VJA,isValidBase64URL:()=>gJA,isValidBase64:()=>sa,initializeContext:()=>ME,globalRegistry:()=>rU,globalConfig:()=>Q5,formatError:()=>bP,flattenError:()=>SP,finalize:()=>IE,extractDefs:()=>zE,encodeAsync:()=>DIq,encode:()=>wIq,describe:()=>xs,decodeAsync:()=>RIq,decode:()=>BIq,createToJSONSchemaMethod:()=>zs,createStandardJSONSchemaMethod:()=>Lx,config:()=>d$,clone:()=>wQ,_xor:()=>YNq,_xid:()=>aS,_void:()=>Gs,_uuidv7:()=>uS,_uuidv6:()=>yS,_uuidv4:()=>hS,_uuid:()=>fS,_url:()=>aP,_uppercase:()=>Yx,_unknown:()=>Qs,_union:()=>UNq,_undefined:()=>$s,_ulid:()=>iS,_uint64:()=>Fs,_uint32:()=>rn,_tuple:()=>GNq,_trim:()=>Hx,_transform:()=>VNq,_toUpperCase:()=>Wx,_toLowerCase:()=>Ex,_templateLiteral:()=>_Nq,_symbol:()=>Zs,_superRefine:()=>Ls,_success:()=>zNq,_stringbool:()=>Ms,_stringFormat:()=>Vx,_string:()=>Cn,_startsWith:()=>Xx,_slugify:()=>gx,_size:()=>H5,_set:()=>HNq,_safeParseAsync:()=>Kx,_safeParse:()=>qx,_safeEncodeAsync:()=>OS,_safeEncode:()=>LS,_safeDecodeAsync:()=>MS,_safeDecode:()=>xS,_regex:()=>$x,_refine:()=>Vs,_record:()=>jNq,_readonly:()=>NNq,_property:()=>Ub,_promise:()=>BNq,_positive:()=>Kb,_pipe:()=>PNq,_parseAsync:()=>Ax,_parse:()=>e2,_overwrite:()=>aG,_optional:()=>LNq,_number:()=>ln,_nullable:()=>xNq,_null:()=>Us,_normalize:()=>Jx,_nonpositive:()=>Zb,_nonoptional:()=>MNq,_nonnegative:()=>$b,_never:()=>Xs,_negative:()=>Fb,_nativeEnum:()=>WNq,_nanoid:()=>mS,_nan:()=>Hs,_multipleOf:()=>xE,_minSize:()=>x4,_minLength:()=>$J,_min:()=>DQ,_mime:()=>jx,_maxSize:()=>OE,_maxLength:()=>E5,_max:()=>M8,_map:()=>JNq,_mac:()=>hn,_lte:()=>M8,_lt:()=>V4,_lowercase:()=>Ux,_literal:()=>gNq,_length:()=>W5,_lazy:()=>wNq,_ksuid:()=>dS,_jwt:()=>qb,_isoTime:()=>mn,_isoDuration:()=>pn,_isoDateTime:()=>un,_isoDate:()=>cn,_ipv6:()=>sS,_ipv4:()=>nS,_intersection:()=>XNq,_int64:()=>Ks,_int32:()=>on,_int:()=>dn,_includes:()=>Qx,_guid:()=>iP,_gte:()=>DQ,_gt:()=>L4,_float64:()=>sn,_float32:()=>nn,_file:()=>Ws,_enum:()=>ENq,_endsWith:()=>Gx,_encodeAsync:()=>gS,_encode:()=>ES,_emoji:()=>cS,_email:()=>CS,_e164:()=>Ab,_discriminatedUnion:()=>QNq,_default:()=>ONq,_decodeAsync:()=>VS,_decode:()=>WS,_date:()=>js,_custom:()=>gs,_cuid2:()=>lS,_cuid:()=>pS,_coercedString:()=>fn,_coercedNumber:()=>an,_coercedDate:()=>Js,_coercedBoolean:()=>en,_coercedBigint:()=>qs,_cidrv6:()=>rS,_cidrv4:()=>oS,_check:()=>_JA,_catch:()=>INq,_boolean:()=>tn,_bigint:()=>As,_base64url:()=>eS,_base64:()=>tS,_array:()=>Es,_any:()=>Ys,TimePrecision:()=>yn,NEVER:()=>Li,JSONSchemaGenerator:()=>Uo,JSONSchema:()=>wJA,Doc:()=>NS,$output:()=>bn,$input:()=>vn,$constructor:()=>nA,$brand:()=>xi,$ZodXor:()=>Hd,$ZodXID:()=>ha,$ZodVoid:()=>Xd,$ZodUnknown:()=>Yd,$ZodUnion:()=>hP,$ZodUndefined:()=>Zd,$ZodUUID:()=>Ra,$ZodURL:()=>Sa,$ZodULID:()=>fa,$ZodType:()=>yK,$ZodTuple:()=>SS,$ZodTransform:()=>zd,$ZodTemplateLiteral:()=>bd,$ZodSymbol:()=>Fd,$ZodSuccess:()=>Bd,$ZodStringFormat:()=>s1,$ZodString:()=>J5,$ZodSet:()=>Ld,$ZodRegistry:()=>kn,$ZodRecord:()=>gd,$ZodRealError:()=>N0,$ZodReadonly:()=>Sd,$ZodPromise:()=>kd,$ZodPreprocess:()=>Td,$ZodPrefault:()=>_d,$ZodPipe:()=>vS,$ZodOptional:()=>bS,$ZodObjectJIT:()=>Jd,$ZodObject:()=>OJA,$ZodNumberFormat:()=>qd,$ZodNumber:()=>RS,$ZodNullable:()=>Pd,$ZodNull:()=>$d,$ZodNonOptional:()=>wd,$ZodNever:()=>Qd,$ZodNanoID:()=>va,$ZodNaN:()=>Rd,$ZodMap:()=>Vd,$ZodMAC:()=>aa,$ZodLiteral:()=>Od,$ZodLazy:()=>Cd,$ZodKSUID:()=>ya,$ZodJWT:()=>ea,$ZodIntersection:()=>Wd,$ZodISOTime:()=>ma,$ZodISODuration:()=>pa,$ZodISODateTime:()=>ua,$ZodISODate:()=>ca,$ZodIPv6:()=>ia,$ZodIPv4:()=>la,$ZodGUID:()=>Da,$ZodFunction:()=>vd,$ZodFile:()=>Md,$ZodExactOptional:()=>Id,$ZodError:()=>TP,$ZodEnum:()=>xd,$ZodEncodeError:()=>X5,$ZodEmoji:()=>ba,$ZodEmail:()=>Ta,$ZodE164:()=>ta,$ZodDiscriminatedUnion:()=>Ed,$ZodDefault:()=>Nd,$ZodDate:()=>Gd,$ZodCustomStringFormat:()=>Ad,$ZodCustom:()=>fd,$ZodCodec:()=>yP,$ZodCheckUpperCase:()=>Oa,$ZodCheckStringFormat:()=>Fx,$ZodCheckStartsWith:()=>za,$ZodCheckSizeEquals:()=>Ea,$ZodCheckRegex:()=>La,$ZodCheckProperty:()=>Pa,$ZodCheckOverwrite:()=>_a,$ZodCheckNumberFormat:()=>Ga,$ZodCheckMultipleOf:()=>Xa,$ZodCheckMinSize:()=>Ha,$ZodCheckMinLength:()=>ga,$ZodCheckMimeType:()=>Na,$ZodCheckMaxSize:()=>Ja,$ZodCheckMaxLength:()=>Wa,$ZodCheckLowerCase:()=>xa,$ZodCheckLessThan:()=>IS,$ZodCheckLengthEquals:()=>Va,$ZodCheckIncludes:()=>Ma,$ZodCheckGreaterThan:()=>PS,$ZodCheckEndsWith:()=>Ia,$ZodCheckBigIntFormat:()=>ja,$ZodCheck:()=>XZ,$ZodCatch:()=>Dd,$ZodCUID2:()=>Ca,$ZodCUID:()=>ka,$ZodCIDRv6:()=>na,$ZodCIDRv4:()=>da,$ZodBoolean:()=>fP,$ZodBigIntFormat:()=>Kd,$ZodBigInt:()=>TS,$ZodBase64URL:()=>ra,$ZodBase64:()=>oa,$ZodAsyncError:()=>g4,$ZodArray:()=>jd,$ZodAny:()=>Ud});var p7A,Li=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 xi=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"}}(p7A=globalThis).__zod_globalConfig??(p7A.__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:()=>NIq,uint8ArrayToBase64url:()=>IIq,uint8ArrayToBase64:()=>a7A,stringifyPrimitive:()=>pq,slugify:()=>zi,shallowClone:()=>Pi,safeExtend:()=>VIq,required:()=>OIq,randomString:()=>GIq,propertyKeyTypes:()=>BP,promiseAllObject:()=>XIq,primitiveTypes:()=>Ni,prefixIssues:()=>P0,pick:()=>EIq,partial:()=>xIq,parsedType:()=>nq,optionalKeys:()=>_i,omit:()=>WIq,objectClone:()=>UIq,numKeys:()=>jIq,nullish:()=>WE,normalizeParams:()=>A6,mergeDefs:()=>ZJ,merge:()=>LIq,jsonStringifyReplacer:()=>o2,joinValues:()=>Qq,issue:()=>t2,isPlainObject:()=>VE,isObject:()=>G5,hexToUint8Array:()=>PIq,getSizableOrigin:()=>DP,getParsedType:()=>JIq,getLengthableOrigin:()=>RP,getEnumValues:()=>_P,getElementAtPath:()=>QIq,floatSafeRemainder:()=>Mi,finalizeIssue:()=>BQ,extend:()=>gIq,explicitlyAborted:()=>Di,escapeRegex:()=>PX,esc:()=>GS,defineLazy:()=>NF,createTransparentProxy:()=>HIq,cloneDef:()=>YIq,clone:()=>wQ,cleanRegex:()=>wP,cleanEnum:()=>MIq,captureStackTrace:()=>jS,cached:()=>r2,base64urlToUint8Array:()=>zIq,base64ToUint8Array:()=>i7A,assignProp:()=>gE,assertNotEqual:()=>KIq,assertNever:()=>ZIq,assertIs:()=>FIq,assertEqual:()=>qIq,assert:()=>$Iq,allowsEval:()=>Ii,aborted:()=>LE,NUMBER_FORMAT_RANGES:()=>wi,Class:()=>d7A,BIGINT_FORMAT_RANGES:()=>Bi});function qIq(A){return A}function KIq(A){return A}function FIq(A){}function ZIq(A){throw Error("Unexpected value in exhaustive check")}function $Iq(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 Mi(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 l7A=Symbol("evaluating");function NF(A,q,K){let F=void 0;Object.defineProperty(A,q,{get(){if(F===l7A)return;if(F===void 0)F=l7A,F=K();return F},set(Z){Object.defineProperty(A,q,{value:Z})},configurable:!0})}function UIq(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 YIq(A){return ZJ(A._zod.def)}function QIq(A,q){if(!q)return A;return q.reduce((K,F)=>K?.[F],A)}function XIq(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 GIq(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 zi(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 Ii=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 Pi(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 jIq(A){let q=0;for(let K in A)if(Object.prototype.hasOwnProperty.call(A,K))q++;return q}var JIq=(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"]),Ni=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 HIq(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 _i(A){return Object.keys(A).filter((q)=>{return A[q]._zod.optin==="optional"&&A[q]._zod.optout==="optional"})}var wi={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]},Bi={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function EIq(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 WIq(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 gIq(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 VIq(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 LIq(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 xIq(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 OIq(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 Di(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 MIq(A){return Object.entries(A).filter(([q,K])=>{return Number.isNaN(Number.parseInt(q,10))}).map((q)=>q[1])}function i7A(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 a7A(A){let q="";for(let K=0;K<A.length;K++)q+=String.fromCharCode(A[K]);return btoa(q)}function zIq(A){let q=A.replace(/-/g,"+").replace(/_/g,"/"),K="=".repeat((4-q.length%4)%4);return i7A(q+K)}function IIq(A){return a7A(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function PIq(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 NIq(A){return Array.from(A).map((q)=>q.toString(16).padStart(2,"0")).join("")}class d7A{constructor(...A){}}var n7A=(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",n7A),N0=nA("$ZodError",n7A,{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 Ri(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 s7A(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 Ti(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 ${s7A(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}},Si=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}},bi=Kx(N0),ES=(A)=>(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return e2(A)(q,K,Z)},wIq=ES(N0),WS=(A)=>(q,K,F)=>{return e2(A)(q,K,F)},BIq=WS(N0),gS=(A)=>async(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return Ax(A)(q,K,Z)},DIq=gS(N0),VS=(A)=>async(q,K,F)=>{return Ax(A)(q,K,F)},RIq=VS(N0),LS=(A)=>(q,K,F)=>{let Z=F?{...F,direction:"backward"}:{direction:"backward"};return qx(A)(q,K,Z)},TIq=LS(N0),xS=(A)=>(q,K,F)=>{return qx(A)(q,K,F)},SIq=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)},vIq=MS(N0);var O8={};iG(O8,{xid:()=>fi,uuid7:()=>hIq,uuid6:()=>fIq,uuid4:()=>CIq,uuid:()=>j5,uppercase:()=>Qa,unicodeEmail:()=>o7A,undefined:()=>Ua,ulid:()=>Ci,time:()=>ei,string:()=>qa,sha512_hex:()=>$Pq,sha512_base64url:()=>YPq,sha512_base64:()=>UPq,sha384_hex:()=>KPq,sha384_base64url:()=>ZPq,sha384_base64:()=>FPq,sha256_hex:()=>eIq,sha256_base64url:()=>qPq,sha256_base64:()=>APq,sha1_hex:()=>oIq,sha1_base64url:()=>tIq,sha1_base64:()=>rIq,rfc5322Email:()=>uIq,number:()=>vP,null:()=>$a,nanoid:()=>yi,md5_hex:()=>dIq,md5_base64url:()=>sIq,md5_base64:()=>nIq,mac:()=>ai,lowercase:()=>Ya,ksuid:()=>hi,ipv6:()=>ii,ipv4:()=>li,integer:()=>Fa,idnEmail:()=>cIq,httpProtocol:()=>oi,html5Email:()=>yIq,hostname:()=>lIq,hex:()=>aIq,guid:()=>ci,extendedDuration:()=>kIq,emoji:()=>pi,email:()=>mi,e164:()=>ri,duration:()=>ui,domain:()=>iIq,datetime:()=>Aa,date:()=>ti,cuid2:()=>ki,cuid:()=>vi,cidrv6:()=>ni,cidrv4:()=>di,browserEmail:()=>mIq,boolean:()=>Za,bigint:()=>Ka,base64url:()=>zS,base64:()=>si});var vi=/^[cC][0-9a-z]{6,}$/,ki=/^[0-9a-z]+$/,Ci=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fi=/^[0-9a-vA-V]{20}$/,hi=/^[A-Za-z0-9]{27}$/,yi=/^[a-zA-Z0-9_-]{21}$/,ui=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,kIq=/^[-+]?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)?)??$/,ci=/^([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})$`)},CIq=j5(4),fIq=j5(6),hIq=j5(7),mi=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,yIq=/^[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])?)*$/,uIq=/^(([^<>()\[\]\\.,;:\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,}))$/,o7A=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,cIq=o7A,mIq=/^[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])?)*$/,pIq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function pi(){return new RegExp(pIq,"u")}var 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])$/,ii=/^(([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}|:))$/,ai=(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}$`)},di=/^((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])$/,ni=/^(([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])$/,si=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zS=/^[A-Za-z0-9_-]*$/,lIq=/^(?=.{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])?)*\.?$/,iIq=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,oi=/^https?$/,ri=/^\+[1-9]\d{6,14}$/,r7A="(?:(?:\\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])))",ti=new RegExp(`^${r7A}$`);function t7A(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 ei(A){return new RegExp(`^${t7A(A)}$`)}function Aa(A){let q=t7A({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(`^${r7A}T(?:${F})$`)}var qa=(A)=>{let q=A?`[\\s\\S]{${A?.minimum??0},${A?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${q}$`)},Ka=/^-?\d+n?$/,Fa=/^-?\d+$/,vP=/^-?\d+(?:\.\d+)?$/,Za=/^(?:true|false)$/i,$a=/^null$/i;var Ua=/^undefined$/i;var Ya=/^[^A-Z]*$/,Qa=/^[^a-z]*$/,aIq=/^[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 dIq=/^[0-9a-fA-F]{32}$/,nIq=kP(22,"=="),sIq=CP(22),oIq=/^[0-9a-fA-F]{40}$/,rIq=kP(27,"="),tIq=CP(27),eIq=/^[0-9a-fA-F]{64}$/,APq=kP(43,"="),qPq=CP(43),KPq=/^[0-9a-fA-F]{96}$/,FPq=kP(64,""),ZPq=CP(64),$Pq=/^[0-9a-fA-F]{128}$/,UPq=kP(86,"=="),YPq=CP(86);var XZ=nA("$ZodCheck",(A,q)=>{var K;A._zod??(A._zod={}),A._zod.def=q,(K=A._zod).onattach??(K.onattach=[])}),AJA={number:"number",bigint:"bigint",object:"date"},IS=nA("$ZodCheckLessThan",(A,q)=>{XZ.init(A,q);let K=AJA[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=AJA[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})}}),Xa=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):Mi(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})}}),Ga=nA("$ZodCheckNumberFormat",(A,q)=>{XZ.init(A,q),q.format=q.format||"float64";let K=q.format?.includes("int"),F=K?"int":"number",[Z,$]=wi[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=Fa}),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})}}),ja=nA("$ZodCheckBigIntFormat",(A,q)=>{XZ.init(A,q);let[K,F]=Bi[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})}}),Ja=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})}}),Ha=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})}}),Ea=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})}}),Wa=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})}}),ga=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})}}),Va=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=()=>{})}),La=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})}}),xa=nA("$ZodCheckLowerCase",(A,q)=>{q.pattern??(q.pattern=Ya),Fx.init(A,q)}),Oa=nA("$ZodCheckUpperCase",(A,q)=>{q.pattern??(q.pattern=Qa),Fx.init(A,q)}),Ma=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})}}),za=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})}}),Ia=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 e7A(A,q,K){if(A.issues.length)q.issues.push(...P0(K,A.issues))}var Pa=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)=>e7A(Z,K,q.property));e7A(F,K,q.property);return}}),Na=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})}}),_a=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 wa={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=wa;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(Di(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 $=Si(A,Z);return $.success?{value:$.data}:{issues:$.error?.issues}}catch($){return bi(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()??qa(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)}),Da=nA("$ZodGUID",(A,q)=>{q.pattern??(q.pattern=ci),s1.init(A,q)}),Ra=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)}),Ta=nA("$ZodEmail",(A,q)=>{q.pattern??(q.pattern=mi),s1.init(A,q)}),Sa=nA("$ZodURL",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{try{let F=K.value.trim();if(!q.normalize&&q.protocol?.source===oi.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})}}}),ba=nA("$ZodEmoji",(A,q)=>{q.pattern??(q.pattern=pi()),s1.init(A,q)}),va=nA("$ZodNanoID",(A,q)=>{q.pattern??(q.pattern=yi),s1.init(A,q)}),ka=nA("$ZodCUID",(A,q)=>{q.pattern??(q.pattern=vi),s1.init(A,q)}),Ca=nA("$ZodCUID2",(A,q)=>{q.pattern??(q.pattern=ki),s1.init(A,q)}),fa=nA("$ZodULID",(A,q)=>{q.pattern??(q.pattern=Ci),s1.init(A,q)}),ha=nA("$ZodXID",(A,q)=>{q.pattern??(q.pattern=fi),s1.init(A,q)}),ya=nA("$ZodKSUID",(A,q)=>{q.pattern??(q.pattern=hi),s1.init(A,q)}),ua=nA("$ZodISODateTime",(A,q)=>{q.pattern??(q.pattern=Aa(q)),s1.init(A,q)}),ca=nA("$ZodISODate",(A,q)=>{q.pattern??(q.pattern=ti),s1.init(A,q)}),ma=nA("$ZodISOTime",(A,q)=>{q.pattern??(q.pattern=ei(q)),s1.init(A,q)}),pa=nA("$ZodISODuration",(A,q)=>{q.pattern??(q.pattern=ui),s1.init(A,q)}),la=nA("$ZodIPv4",(A,q)=>{q.pattern??(q.pattern=li),s1.init(A,q),A._zod.bag.format="ipv4"}),ia=nA("$ZodIPv6",(A,q)=>{q.pattern??(q.pattern=ii),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})}}}),aa=nA("$ZodMAC",(A,q)=>{q.pattern??(q.pattern=ai(q.delimiter)),s1.init(A,q),A._zod.bag.format="mac"}),da=nA("$ZodCIDRv4",(A,q)=>{q.pattern??(q.pattern=di),s1.init(A,q)}),na=nA("$ZodCIDRv6",(A,q)=>{q.pattern??(q.pattern=ni),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 sa(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 oa=nA("$ZodBase64",(A,q)=>{q.pattern??(q.pattern=si),s1.init(A,q),A._zod.bag.contentEncoding="base64",A._zod.check=(K)=>{if(sa(K.value))return;K.issues.push({code:"invalid_format",format:"base64",input:K.value,inst:A,continue:!q.abort})}});function gJA(A){if(!zS.test(A))return!1;let q=A.replace(/[-_]/g,(F)=>F==="-"?"+":"/"),K=q.padEnd(Math.ceil(q.length/4)*4,"=");return sa(K)}var ra=nA("$ZodBase64URL",(A,q)=>{q.pattern??(q.pattern=zS),s1.init(A,q),A._zod.bag.contentEncoding="base64url",A._zod.check=(K)=>{if(gJA(K.value))return;K.issues.push({code:"invalid_format",format:"base64url",input:K.value,inst:A,continue:!q.abort})}}),ta=nA("$ZodE164",(A,q)=>{q.pattern??(q.pattern=ri),s1.init(A,q)});function VJA(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 ea=nA("$ZodJWT",(A,q)=>{s1.init(A,q),A._zod.check=(K)=>{if(VJA(K.value,q.alg))return;K.issues.push({code:"invalid_format",format:"jwt",input:K.value,inst:A,continue:!q.abort})}}),Ad=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}}),qd=nA("$ZodNumberFormat",(A,q)=>{Ga.init(A,q),RS.init(A,q)}),fP=nA("$ZodBoolean",(A,q)=>{yK.init(A,q),A._zod.pattern=Za,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=Ka,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}}),Kd=nA("$ZodBigIntFormat",(A,q)=>{ja.init(A,q),TS.init(A,q)}),Fd=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}}),Zd=nA("$ZodUndefined",(A,q)=>{yK.init(A,q),A._zod.pattern=Ua,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}}),$d=nA("$ZodNull",(A,q)=>{yK.init(A,q),A._zod.pattern=$a,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}}),Ud=nA("$ZodAny",(A,q)=>{yK.init(A,q),A._zod.parse=(K)=>K}),Yd=nA("$ZodUnknown",(A,q)=>{yK.init(A,q),A._zod.parse=(K)=>K}),Qd=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}}),Xd=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}}),Gd=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 KJA(A,q,K){if(A.issues.length)q.issues.push(...P0(K,A.issues));q.value[K]=A.value}var jd=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)=>KJA(j,K,U)));else KJA(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 LJA(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=_i(A.shape);return{...A,keys:q,keySet:new Set(q),numKeys:q.length,optionalKeys:new Set(K)}}function xJA(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 OJA=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(()=>LJA(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 xJA(J,j,Y,X,F.value,A)}}),Jd=nA("$ZodObjectJIT",(A,q)=>{OJA.init(A,q);let K=A._zod.parse,F=r2(()=>LJA(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(`
|
|
@@ -1444,7 +1444,7 @@ Runs "bun i -g @interactive-inc/claude-funnel".`,f3A="@interactive-inc/claude-fu
|
|
|
1444
1444
|
`)}}var uQq=MK(yQq(),1);var ub6=(A)=>{let q={};for(let[K,F]of Object.entries(A))q[K]=F;return q},cb6=(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 w0A extends XV{client;constructor(A){super();this.client=A.client??new uQq.WebClient(A.config.botToken),Object.freeze(this)}async call(A){let q=A.body!==null&&typeof A.body==="object"?ub6(A.body):{};try{return await this.client.apiCall(A.path,q)}catch(K){let F=cb6(K);if(F)return F;throw K}}}var ep=MK(Ezq(),1);var QUK=["type","subtype","user","bot_id","text","ts","thread_ts","channel","channel_type","files","attachments"],XUK=["id","name","mimetype","filetype","size","url_private","permalink"],GUK=["title","text","fallback"],tp=(A)=>{return typeof A==="object"&&A!==null&&!Array.isArray(A)},R4A=(A,q)=>{let K={};for(let F of q)if(A[F]!==void 0)K[F]=A[F];return K},jUK=(A)=>{return Object.keys(A).some((q)=>q.startsWith("thumb")||q.startsWith("preview"))},JUK=(A)=>{if(!tp(A))return A;let q=R4A(A,XUK);if(jUK(A))q._funnel_omitted=["thumb_*"];return q},T4A=(A)=>{if(!tp(A))return"";let q=A.text;if(typeof q==="string")return q;let K=A.elements;if(!Array.isArray(K))return"";return K.map(T4A).join("")},HUK=(A)=>{if(!Array.isArray(A))return"";return A.map(T4A).join("\t")},EUK=(A)=>{if(!tp(A))return"";if(A.type==="table"&&Array.isArray(A.rows))return A.rows.map(HUK).join(`
|
|
1445
1445
|
`);return T4A(A)},WUK=(A)=>{return A.map(EUK).filter((q)=>q.length>0).join(`
|
|
1446
1446
|
`)},gUK=(A)=>{if(!tp(A))return A;let q=R4A(A,GUK),K=A.blocks;if(Array.isArray(K)){let F=WUK(K),Z=typeof q.text==="string"?q.text:"";q.text=Z?`${Z}
|
|
1447
|
-
${F}`:F,q._funnel_omitted=["blocks"]}return q},Wzq=(A)=>{let q=R4A(A,QUK);if(Array.isArray(q.files))q.files=q.files.map(JUK);if(Array.isArray(q.attachments))q.attachments=q.attachments.map(gUK);return q};var VUK=new Set(["message","app_mention"]),LUK=new Set([void 0,"thread_broadcast","bot_message","file_share"]),xUK=1e4,bj=(A,q)=>{let K=A[q];return typeof K==="string"?K:void 0};class S4A{ownBotUserId;ownBotId;minify;now;dedup=new Map;constructor(A){this.ownBotUserId=A.ownBotUserId,this.ownBotId=A.ownBotId,this.minify=A.minify??!0,this.now=A.now??(()=>Date.now())}process(A){let q=bj(A,"type");if(!q||!VUK.has(q))return{skip:!0};let K=bj(A,"subtype");if(!LUK.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 g of this.dedup.keys())if((this.dedup.get(g)??0)<U-xUK)this.dedup.delete(g);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")??"",W=this.minify?Wzq(A):A;return{skip:!1,content:JSON.stringify(W),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 OUK=u.object({event:u.record(u.string(),u.unknown()).optional()}),MUK=new w$;class b4A extends rJ{config;logger;onAppCreated;preprocessEvent;app=null;constructor(A){super();this.config=A.config,this.logger=A.logger??MUK,this.onAppCreated=A.onAppCreated??null,this.preprocessEvent=A.preprocessEvent??null}async start(A){let q=new ep.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:ep.LogLevel.ERROR}),K=await q.client.auth.test({token:this.config.botToken}),F=new S4A({ownBotUserId:K.user_id??"",ownBotId:K.bot_id??"",minify:this.config.minify}),Z=this.preprocessEvent;if(q.use(async($)=>{let U=OUK.safeParse($);if(!U.success||!U.data.event)return
|
|
1447
|
+
${F}`:F,q._funnel_omitted=["blocks"]}return q},Wzq=(A)=>{let q=R4A(A,QUK);if(Array.isArray(q.files))q.files=q.files.map(JUK);if(Array.isArray(q.attachments))q.attachments=q.attachments.map(gUK);return q};var VUK=new Set(["message","app_mention"]),LUK=new Set([void 0,"thread_broadcast","bot_message","file_share"]),xUK=1e4,bj=(A,q)=>{let K=A[q];return typeof K==="string"?K:void 0};class S4A{ownBotUserId;ownBotId;minify;now;dedup=new Map;constructor(A){this.ownBotUserId=A.ownBotUserId,this.ownBotId=A.ownBotId,this.minify=A.minify??!0,this.now=A.now??(()=>Date.now())}process(A){let q=bj(A,"type");if(!q||!VUK.has(q))return{skip:!0};let K=bj(A,"subtype");if(!LUK.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 g of this.dedup.keys())if((this.dedup.get(g)??0)<U-xUK)this.dedup.delete(g);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")??"",W=this.minify?Wzq(A):A;return{skip:!1,content:JSON.stringify(W),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 OUK=u.object({event:u.record(u.string(),u.unknown()).optional()}),MUK=new w$;class b4A extends rJ{config;logger;onAppCreated;preprocessEvent;app=null;constructor(A){super();this.config=A.config,this.logger=A.logger??MUK,this.onAppCreated=A.onAppCreated??null,this.preprocessEvent=A.preprocessEvent??null}async start(A){let q=new ep.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:ep.LogLevel.ERROR}),K=await q.client.auth.test({token:this.config.botToken}),F=new S4A({ownBotUserId:K.user_id??"",ownBotId:K.bot_id??"",minify:this.config.minify}),Z=this.preprocessEvent;if(q.use(async($)=>{let U=OUK.safeParse($);if(!U.success||!U.data.event){await $.next();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(await A(j.content,j.meta),j.shouldReact)try{await q.client.reactions.add({token:this.config.botToken,channel:j.channel,timestamp:j.timestamp,name:"eyes"})}catch{}}),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 zUK}from"os";import{dirname as IUK,join as gzq}from"path";class hR{}var c8=gzq(zUK(),".funnel"),PUK=gzq(c8,"settings.json"),NUK=new FY;class v4A extends hR{path;fs;constructor(A={}){super();this.path=A.path??PUK,this.fs=A.fs??NUK,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:
|
|
1448
1448
|
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(IUK(this.path),{recursive:!0});let q={...A,version:VJ};this.fs.writeFileSync(this.path,`${JSON.stringify(q,null,2)}
|
|
1449
1449
|
`)}}import{join as k4A}from"path";var _UK=new FY,wUK=new jY,BUK=new w$;class C4A{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor(A={}){this.fs=A.fs??_UK,this.process=A.process??wUK,this.logger=A.logger??BUK,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 oYA({config:q,process:this.process,logger:this.logger});if(q.type==="discord")return new nYA({config:q,logger:this.logger});let K=new tYA({path:k4A(this.connectorDir(A,q.id),"state.json"),fs:this.fs});return new rYA({config:q,lastFiredStore:K,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter(A){if(A.type==="slack")return new w0A({config:A});if(A.type==="gh")return new sYA({process:this.process});if(A.type==="discord")return new AFA({config:A});return null}connectorDir(A,q){return k4A(this.dir,"channels",A,"connectors",q)}channelDir(A){return k4A(this.dir,"channels",A)}}function f4A(A){switch(A.type){case"slack":return[A.botToken,A.appToken];case"discord":return[A.botToken];case"gh":case"schedule":return[]}}function DUK(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(!DUK(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 RUK=new vL,TUK=new cR;class h4A{store;factory;profileChecker;clock;idGenerator;constructor(A){this.store=A.store,this.factory=A.factory,this.profileChecker=A.profileChecker,this.clock=A.clock??RUK,this.idGenerator=A.idGenerator??TUK,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",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)}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,minify:A.minify??!0,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=f4A(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 f4A(Z))if(K.includes($))throw Error(`token already in use by connector "${Z.name}" in channel "${F.name}"`)}}}import{homedir as SUK}from"os";import{join as Al}from"path";var bUK=new jY,vUK=new FY,kUK=new w$;class y4A{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??bUK,this.fs=A.fs??vUK,this.logger=A.logger??kUK,this.pidDir=Al(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 $=A.resume??!0?this.resolveSession(q.id,K,A.userArgs??[],A.env??{}):null,U=this.buildArgs(A.options??[],A.userArgs??[],K,$),Y=this.buildEnv(q.id,A.env??{});this.logger.info("claude launch",{channel:A.channel,channelId:q.id,cwd:K});try{return await this.process.attach(["claude",...U],{cwd:K,env:Y,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 Al(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,F){for(let $ of K){if($==="-c"||$==="--continue")return null;if($==="--resume"||$.startsWith("--resume="))return null;if($==="--session-id"||$.startsWith("--session-id="))return null}let Z=this.sessions.get(A,q);if(Z!==null&&this.sessionFileExists(q,Z,F))return{id:Z,mode:"resume"};return{id:this.sessions.create(A,q),mode:"new"}}sessionFileExists(A,q,K){let F=K.CLAUDE_CONFIG_DIR??globalThis.process.env.CLAUDE_CONFIG_DIR??Al(SUK(),".claude"),Z=A.replace(/\//g,"-");return this.fs.existsSync(Al(F,"projects",Z,`${q}.jsonl`))}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 CUK=384;class u4A 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,CUK),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 fUK}from"path";var hUK=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,yUK=(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 m4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=fUK(A,R3A);if(!this.fs.existsSync(q))return{};let K=this.fs.readFileSync(q),F={};for(let Z of K.split(`
|
|
1450
1450
|
`)){let $=Z.trim();if($===""||$.startsWith("#"))continue;let U=$.match(hUK);if(!U)continue;let Y=U[1],X=U[2];if(!Y)continue;F[Y]=yUK(X??"")}return F}}import{join as uUK}from"path";class p4A{fs;constructor(A){this.fs=A.fs,Object.freeze(this)}read(A){let q=uUK(A,Rf);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(`${Rf} is not valid JSON: ${U}`)}})(),Z=Df.safeParse(F);if(!Z.success)throw Error(`${Rf} is invalid: ${Z.error.message}`);return Z.data}}class l4A{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){if(!this.channels.get(A.name))this.channels.add({name:A.name});if(A.connectors===void 0)return{touched:[],removed:[]};let F=this.dotenv.read(q),Z=[],$=new Set;for(let Y of A.connectors){let X=await this.ensureConnector(A.name,Y,F);Z.push({name:X.name,changed:X.changed}),$.add(X.id)}let U=this.removeExtras(A.name,$);return{touched:Z,removed:U}}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:$,...q.minify!==void 0?{minify:q.minify}:{}}).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 i4A 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 Vzq={exitCode:0,stdout:"",stderr:""};class a4A extends ew{calls=[];killed=[];handler=()=>Vzq;syncHandler=()=>Vzq;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 d4A{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({name:A.name,path:A.path,channelId:A.channelId,options:A.options??[],env:A.env??{},resume:A.resume??!0}),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;if(q.options!==void 0)F.options=q.options;if(q.env!==void 0)F.env=q.env;if(q.resume!==void 0)F.resume=q.resume;this.store.write(K)}}import{join as Lzq}from"path";var cUK=u.record(u.string(),u.string());class n4A{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=cUK.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)}
|
package/dist/connectors/slack.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "../slack-connector-schema-
|
|
1
|
+
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "../slack-connector-schema-Dhlnfp0g.js";
|
|
2
2
|
export { FunnelSlackAdapter, FunnelSlackEventProcessor, FunnelSlackListener, slackConnectorSchema };
|
package/dist/gateway/daemon.js
CHANGED
|
@@ -546,7 +546,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
546
546
|
`)}}var uB1=XL(CB1(),1);var aP0=($)=>{let x={};for(let[Y,X]of Object.entries($))x[Y]=X;return x},sP0=($)=>{if(!$||typeof $!=="object")return null;if(!("code"in $))return null;let x=$.code;if(typeof x!=="string"||!x.startsWith("slack_webapi_"))return null;if(!("data"in $))return null;let Y=$.data;if(!Y||typeof Y!=="object")return null;return Y};class ck extends kY{client;constructor($){super();this.client=$.client??new uB1.WebClient($.config.botToken),Object.freeze(this)}async call($){let x=$.body!==null&&typeof $.body==="object"?aP0($.body):{};try{return await this.client.apiCall($.path,x)}catch(Y){let X=sP0(Y);if(X)return X;throw Y}}}var WF=XL(Hc1(),1);var Br0=["type","subtype","user","bot_id","text","ts","thread_ts","channel","channel_type","files","attachments"],Dr0=["id","name","mimetype","filetype","size","url_private","permalink"],Fr0=["title","text","fallback"],KF=($)=>{return typeof $==="object"&&$!==null&&!Array.isArray($)},uC=($,x)=>{let Y={};for(let X of x)if($[X]!==void 0)Y[X]=$[X];return Y},Lr0=($)=>{return Object.keys($).some((x)=>x.startsWith("thumb")||x.startsWith("preview"))},Nr0=($)=>{if(!KF($))return $;let x=uC($,Dr0);if(Lr0($))x._funnel_omitted=["thumb_*"];return x},yC=($)=>{if(!KF($))return"";let x=$.text;if(typeof x==="string")return x;let Y=$.elements;if(!Array.isArray(Y))return"";return Y.map(yC).join("")},jr0=($)=>{if(!Array.isArray($))return"";return $.map(yC).join("\t")},Pr0=($)=>{if(!KF($))return"";if($.type==="table"&&Array.isArray($.rows))return $.rows.map(jr0).join(`
|
|
547
547
|
`);return yC($)},Ir0=($)=>{return $.map(Pr0).filter((x)=>x.length>0).join(`
|
|
548
548
|
`)},vr0=($)=>{if(!KF($))return $;let x=uC($,Fr0),Y=$.blocks;if(Array.isArray(Y)){let X=Ir0(Y),Q=typeof x.text==="string"?x.text:"";x.text=Q?`${Q}
|
|
549
|
-
${X}`:X,x._funnel_omitted=["blocks"]}return x},Gc1=($)=>{let x=uC($,Br0);if(Array.isArray(x.files))x.files=x.files.map(Nr0);if(Array.isArray(x.attachments))x.attachments=x.attachments.map(vr0);return x};var Mr0=new Set(["message","app_mention"]),_r0=new Set([void 0,"thread_broadcast","bot_message","file_share"]),Or0=1e4,J7=($,x)=>{let Y=$[x];return typeof Y==="string"?Y:void 0};class mC{ownBotUserId;ownBotId;minify;now;dedup=new Map;constructor($){this.ownBotUserId=$.ownBotUserId,this.ownBotId=$.ownBotId,this.minify=$.minify??!0,this.now=$.now??(()=>Date.now())}process($){let x=J7($,"type");if(!x||!Mr0.has(x))return{skip:!0};let Y=J7($,"subtype");if(!_r0.has(Y))return{skip:!0};let X=J7($,"channel")??"",Q=J7($,"event_ts")??J7($,"ts")??"",z=`${X}:${Q}`,Z=this.now();if(this.dedup.has(z))return{skip:!0};this.dedup.set(z,Z);for(let J of this.dedup.keys())if((this.dedup.get(J)??0)<Z-Or0)this.dedup.delete(J);let K=J7($,"user"),W=J7($,"bot_id");if(K===this.ownBotUserId)return{skip:!0};if(W===this.ownBotId)return{skip:!0};let w=(J7($,"text")??"").includes(`<@${this.ownBotUserId}>`),U=J7($,"thread_ts")??J7($,"ts")??"",H=this.minify?Gc1($):$;return{skip:!1,content:JSON.stringify(H),meta:{event_type:"slack",channel_id:X,user_id:K??"",mentioned:String(w),thread_ts:U},shouldReact:w,channel:X,timestamp:J7($,"ts")??""}}}var br0=u.object({event:u.record(u.string(),u.unknown()).optional()}),Ar0=new I6;class hC extends f2{config;logger;onAppCreated;preprocessEvent;app=null;constructor($){super();this.config=$.config,this.logger=$.logger??Ar0,this.onAppCreated=$.onAppCreated??null,this.preprocessEvent=$.preprocessEvent??null}async start($){let x=new WF.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:WF.LogLevel.ERROR}),Y=await x.client.auth.test({token:this.config.botToken}),X=new mC({ownBotUserId:Y.user_id??"",ownBotId:Y.bot_id??"",minify:this.config.minify}),Q=this.preprocessEvent;if(x.use(async(z)=>{let Z=br0.safeParse(z);if(!Z.success||!Z.data.event)return;let K=Z.data.event,W=Q?Q(K):K;if(W===null)return;let V=X.process(W);if(V.skip)return;if(await $(V.content,V.meta),V.shouldReact)try{await x.client.reactions.add({token:this.config.botToken,channel:V.channel,timestamp:V.timestamp,name:"eyes"})}catch{}}),x.error(async(z)=>{this.logger.error("Slack error",{error:z instanceof Error?z.message:String(z)})}),this.onAppCreated)await this.onAppCreated(x);await x.start(),this.app=x}async stop(){if(!this.app)return;try{await this.app.stop()}catch($){this.logger.error("Slack stop error",{error:$ instanceof Error?$.message:String($)})}finally{this.app=null}}isAlive(){return this.app!==null}}import{join as gC}from"path";var Rr0=new _8,fr0=new M8,kr0=new I6;class pC{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor($={}){this.fs=$.fs??Rr0,this.process=$.process??fr0,this.logger=$.logger??kr0,this.dir=$.dir??b8,this.slackListenerOptions=$.slackListenerOptions??{},this.scheduleListenerOptions=$.scheduleListenerOptions??{},Object.freeze(this)}createListener($,x){if(x.type==="slack")return new hC({config:x,logger:this.logger,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(x.type==="gh")return new Qf({config:x,process:this.process,logger:this.logger});if(x.type==="discord")return new xf({config:x,logger:this.logger});let Y=new zf({path:gC(this.connectorDir($,x.id),"state.json"),fs:this.fs});return new Xf({config:x,lastFiredStore:Y,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter($){if($.type==="slack")return new ck({config:$});if($.type==="gh")return new Yf({process:this.process});if($.type==="discord")return new KM({config:$});return null}connectorDir($,x){return gC(this.dir,"channels",$,"connectors",x)}channelDir($){return gC(this.dir,"channels",$)}}function iC($){switch($.type){case"slack":return[$.botToken,$.appToken];case"discord":return[$.botToken];case"gh":case"schedule":return[]}}function Tr0($,x){return $.type===x}function QX($,x,Y){let X=$.connectors.find((Q)=>Q.name===x);if(!X)throw Error(`connector "${x}" not found in channel "${$.name}"`);if(!Tr0(X,Y))throw Error(`connector "${x}" is type "${X.type}", not "${Y}"`);return X}class CV{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class XX extends CV{now(){return new Date}}class uV{}class yV extends uV{generate(){return crypto.randomUUID()}}var Sr0=new XX,cr0=new yV;class lC{store;factory;profileChecker;clock;idGenerator;constructor($){this.store=$.store,this.factory=$.factory,this.profileChecker=$.profileChecker,this.clock=$.clock??Sr0,this.idGenerator=$.idGenerator??cr0,Object.freeze(this)}list(){return this.store.read().channels}get($){return this.list().find((x)=>x.name===$)??null}getById($){return this.list().find((x)=>x.id===$)??null}add($){let x=this.store.read();if(x.channels.some((X)=>X.name===$.name))throw Error(`channel "${$.name}" already exists`);let Y={id:this.idGenerator.generate(),name:$.name,delivery:$.delivery??"fanout",connectors:[]};return x.channels.push(Y),this.store.write(x),Y}setDelivery($,x){let Y=this.store.read(),X=this.requireChannel(Y,$);X.delivery=x,this.store.write(Y)}remove($){let x=this.store.read(),Y=x.channels.findIndex((Q)=>Q.name===$);if(Y<0)throw Error(`channel "${$}" not found`);let X=x.channels[Y];if(X&&this.profileChecker.hasChannelRef(X.id))throw Error(`channel "${$}" is referenced by a profile`);x.channels.splice(Y,1),this.store.write(x)}rename($,x){let Y=this.store.read(),X=Y.channels.find((Q)=>Q.name===$);if(!X)throw Error(`channel "${$}" not found`);if(Y.channels.some((Q)=>Q.name===x))throw Error(`channel "${x}" already exists`);X.name=x,this.store.write(Y)}listConnectors($){return this.requireChannel(this.store.read(),$).connectors}getConnector($,x){let Y=this.get($);if(!Y)return null;return Y.connectors.find((X)=>X.name===x)??null}listAllConnectors(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({...Y,channelId:x.id,channelName:x.name});return $}addConnector($,x){let Y=this.store.read(),X=this.requireChannel(Y,$);if(X.connectors.some((z)=>z.name===x.name))throw Error(`connector "${x.name}" already exists in channel "${$}"`);let Q=this.fromInput(x);return this.assertNoTokenCollision(Y,Q),X.connectors.push(Q),this.store.write(Y),Q}fromInput($){let x=this.idGenerator.generate(),Y=this.clock.iso(),X=Y,Q=Y;switch($.type){case"slack":return{id:x,type:"slack",name:$.name,botToken:$.botToken,appToken:$.appToken,minify:$.minify??!0,createdAt:X,updatedAt:Q};case"gh":return{id:x,type:"gh",name:$.name,...$.pollInterval!==void 0?{pollInterval:$.pollInterval}:{},createdAt:X,updatedAt:Q};case"discord":return{id:x,type:"discord",name:$.name,botToken:$.botToken,createdAt:X,updatedAt:Q};case"schedule":return{id:x,type:"schedule",name:$.name,entries:$.entries??[],createdAt:X,updatedAt:Q}}}removeConnector($,x){let Y=this.store.read(),X=this.requireChannel(Y,$),Q=X.connectors.findIndex((z)=>z.name===x);if(Q<0)throw Error(`connector "${x}" not found in channel "${$}"`);X.connectors.splice(Q,1),this.store.write(Y)}renameConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=Q.connectors.find((Z)=>Z.name===x);if(!z)throw Error(`connector "${x}" not found in channel "${$}"`);if(Q.connectors.some((Z)=>Z.name===Y))throw Error(`connector "${Y}" already exists in channel "${$}"`);z.name=Y,z.updatedAt=this.clock.iso(),this.store.write(X)}updateSlackConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"slack"),Z={...z,botToken:Y.botToken??z.botToken,appToken:Y.appToken??z.appToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(X,Z),Object.assign(z,Z),this.store.write(X)}updateGhConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"gh");if(Y.pollInterval!==void 0)z.pollInterval=Y.pollInterval;z.updatedAt=this.clock.iso(),this.store.write(X)}updateDiscordConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"discord"),Z={...z,botToken:Y.botToken??z.botToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(X,Z),Object.assign(z,Z),this.store.write(X)}listScheduleEntries($,x){let Y=this.requireChannel(this.store.read(),$);return QX(Y,x,"schedule").entries}addScheduleEntry($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"schedule"),Z={id:Y.id??this.idGenerator.generate(),cron:Y.cron,prompt:Y.prompt,enabled:Y.enabled??!0,catchupPolicy:Y.catchupPolicy??"latest"};return z.entries.push(Z),z.updatedAt=this.clock.iso(),this.store.write(X),Z}removeScheduleEntry($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"schedule"),Z=z.entries.findIndex((K)=>K.id===Y);if(Z<0)throw Error(`schedule entry "${Y}" not found`);z.entries.splice(Z,1),z.updatedAt=this.clock.iso(),this.store.write(X)}async call($,x,Y){let X=this.getConnector($,x);if(!X)throw Error(`connector "${x}" not found in channel "${$}"`);let Q=this.factory.createAdapter(X);if(!Q)throw Error(`connector type "${X.type}" does not support outbound calls`);return await Q.call(Y)}createListener($,x){let Y=this.get($);if(!Y)return null;let X=Y.connectors.find((Q)=>Q.name===x);if(!X)return null;return{config:X,channelId:Y.id,listener:this.factory.createListener(Y.id,X)}}createAllListeners(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({config:Y,channelId:x.id,channelName:x.name,listener:this.factory.createListener(x.id,Y)});return $}requireChannel($,x){let Y=$.channels.find((X)=>X.name===x);if(!Y)throw Error(`channel "${x}" not found`);return Y}assertNoTokenCollision($,x){let Y=iC(x);if(Y.length===0)return;for(let X of $.channels)for(let Q of X.connectors){if(Q.id===x.id)continue;for(let z of iC(Q))if(Y.includes(z))throw Error(`token already in use by connector "${Q.name}" in channel "${X.name}"`)}}}import{homedir as Er0}from"os";import{join as VF}from"path";var Cr0=new M8,ur0=new _8,yr0=new I6;class nC{channels;mcp;gateway;sessions;process;fs;logger;pidDir;constructor($){this.channels=$.channels,this.mcp=$.mcp,this.gateway=$.gateway,this.sessions=$.sessions,this.process=$.process??Cr0,this.fs=$.fs??ur0,this.logger=$.logger??yr0,this.pidDir=VF($.dir??b8,"claude"),Object.freeze(this)}async launch($){let x=this.channels.get($.channel)??this.channels.getById($.channel);if(!x)throw Error(`channel "${$.channel}" not found`);if($.profileName&&this.isRunning($.profileName))throw Error(`profile "${$.profileName}" is already running`);let Y=$.cwd??globalThis.process.cwd();if(($.installMcp??!0)&&!this.mcp.findInstalledName(Y))this.mcp.install(Y),this.logger.info("added funnel MCP to .mcp.json",{cwd:Y});if(!this.gateway.isRunning())this.logger.info("starting gateway automatically"),await this.gateway.start();if($.profileName)this.writePidFile($.profileName),this.installCleanup($.profileName);let z=$.resume??!0?this.resolveSession(x.id,Y,$.userArgs??[],$.env??{}):null,Z=this.buildArgs($.options??[],$.userArgs??[],Y,z),K=this.buildEnv(x.id,$.env??{});this.logger.info("claude launch",{channel:$.channel,channelId:x.id,cwd:Y});try{return await this.process.attach(["claude",...Z],{cwd:Y,env:K,onSpawned:$.onSpawned})}finally{if($.profileName)this.removePidFile($.profileName)}}isRunning($){let x=this.readPid($);if(!x)return!1;return this.isProcessAlive(x)}pidPath($){return VF(this.pidDir,`${$}.pid`)}readPid($){let x=this.pidPath($);if(!this.fs.existsSync(x))return null;try{let Y=this.fs.readFileSync(x).trim(),X=Number(Y);if(!X||X<=0)return null;return X}catch{return null}}writePidFile($){this.fs.mkdirSync(this.pidDir,{recursive:!0}),this.fs.writeFileSync(this.pidPath($),String(globalThis.process.pid))}removePidFile($){let x=this.pidPath($);if(this.fs.existsSync(x))this.fs.unlink(x)}installCleanup($){globalThis.process.once("exit",()=>this.removePidFile($))}isProcessAlive($){return this.process.isAlive($)}buildArgs($,x,Y,X){let Q=[...$,...x];if(X!==null)if(X.mode==="resume")Q.push("--resume",X.id);else Q.push("--session-id",X.id);let z=this.mcp.findInstalledName(Y);if(z&&!Q.includes("--dangerously-load-development-channels")&&!Q.includes("--channels"))Q.push("--dangerously-load-development-channels",`server:${z}`);return Q}resolveSession($,x,Y,X){for(let z of Y){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 Q=this.sessions.get($,x);if(Q!==null&&this.sessionFileExists(x,Q,X))return{id:Q,mode:"resume"};return{id:this.sessions.create($,x),mode:"new"}}sessionFileExists($,x,Y){let X=Y.CLAUDE_CONFIG_DIR??globalThis.process.env.CLAUDE_CONFIG_DIR??VF(Er0(),".claude"),Q=$.replace(/\//g,"-");return this.fs.existsSync(VF(X,"projects",Q,`${x}.jsonl`))}buildEnv($,x){let Y={};for(let[X,Q]of Object.entries(x))Y[X]=Q;for(let[X,Q]of Object.entries(globalThis.process.env))if(typeof Q==="string")Y[X]=Q;return Y.FUNNEL_CHANNEL_ID=$,Y}}var mr0=384;class dC extends JK{dirs;files;mtimes;modes;now;constructor($={}){super();this.dirs=new Set($.dirs??[]),this.files=new Map(Object.entries($.files??{})),this.mtimes=new Map(Object.entries($.mtimes??{})),this.modes=new Map(Object.entries($.modes??{})),this.now=$.now??(()=>Date.now())}existsSync($){return this.dirs.has($)||this.files.has($)}readFileSync($){return this.files.get($)??""}writeFileSync($,x){this.files.set($,x),this.touch($)}writeSecretFileSync($,x){this.files.set($,x),this.modes.set($,mr0),this.touch($)}appendFileSync($,x){let Y=this.files.get($)??"";this.files.set($,Y+x),this.touch($)}unlink($){this.files.delete($),this.mtimes.delete($),this.modes.delete($)}mkdirSync($,x){this.dirs.add($)}readdirSync($){let x=$.endsWith("/")?$:`${$}/`,Y=[];for(let X of this.files.keys()){if(!X.startsWith(x))continue;let Q=X.slice(x.length);if(!Q.includes("/"))Y.push(Q)}return Y}statSync($){let x=this.mtimes.get($);if(x===void 0)throw Error(`not found: ${$}`);return{mtimeMs:x,mode:this.modes.get($)??null}}setMtime($,x){this.mtimes.set($,x)}setMode($,x){this.modes.set($,x)}touch($){if(!this.mtimes.has($))this.mtimes.set($,this.now());else this.mtimes.set($,this.now())}}class aC extends uV{counter=0;prefix;constructor($={}){super();this.prefix=$.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}import{join as or0}from"path";var hr0=u.object({botToken:u.string().optional(),appToken:u.string().optional()}).optional(),gr0=u.object({type:u.literal("slack"),name:u.string(),botToken:u.string().optional(),appToken:u.string().optional(),minify:u.boolean().optional(),env:hr0}),pr0=u.object({botToken:u.string().optional()}).optional(),ir0=u.object({type:u.literal("discord"),name:u.string(),botToken:u.string().optional(),env:pr0}),lr0=u.object({type:u.literal("gh"),name:u.string(),pollInterval:u.number().int().positive().optional()}),nr0=u.object({type:u.literal("schedule"),name:u.string()}),dr0=u.discriminatedUnion("type",[gr0,ir0,lr0,nr0]),ar0=u.object({name:u.string(),connectors:u.array(dr0).optional()}),sr0=u.object({name:u.string(),channel:u.string(),options:u.array(u.string()).optional(),env:u.record(u.string(),u.string()).optional(),resume:u.boolean().optional()}),Jc1=u.object({$schema:u.string().optional(),channels:u.array(ar0).min(1),profiles:u.array(sr0).optional()}),wF="funnel.json",qc1=".env.local";var rr0=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,tr0=($)=>{if($.length<2)return $;let x=$[0],Y=$[$.length-1];if(x==='"'&&Y==='"')return $.slice(1,-1);if(x==="'"&&Y==="'")return $.slice(1,-1);return $};class sC{fs;constructor($){this.fs=$.fs,Object.freeze(this)}read($){let x=or0($,qc1);if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x),X={};for(let Q of Y.split(`
|
|
549
|
+
${X}`:X,x._funnel_omitted=["blocks"]}return x},Gc1=($)=>{let x=uC($,Br0);if(Array.isArray(x.files))x.files=x.files.map(Nr0);if(Array.isArray(x.attachments))x.attachments=x.attachments.map(vr0);return x};var Mr0=new Set(["message","app_mention"]),_r0=new Set([void 0,"thread_broadcast","bot_message","file_share"]),Or0=1e4,J7=($,x)=>{let Y=$[x];return typeof Y==="string"?Y:void 0};class mC{ownBotUserId;ownBotId;minify;now;dedup=new Map;constructor($){this.ownBotUserId=$.ownBotUserId,this.ownBotId=$.ownBotId,this.minify=$.minify??!0,this.now=$.now??(()=>Date.now())}process($){let x=J7($,"type");if(!x||!Mr0.has(x))return{skip:!0};let Y=J7($,"subtype");if(!_r0.has(Y))return{skip:!0};let X=J7($,"channel")??"",Q=J7($,"event_ts")??J7($,"ts")??"",z=`${X}:${Q}`,Z=this.now();if(this.dedup.has(z))return{skip:!0};this.dedup.set(z,Z);for(let J of this.dedup.keys())if((this.dedup.get(J)??0)<Z-Or0)this.dedup.delete(J);let K=J7($,"user"),W=J7($,"bot_id");if(K===this.ownBotUserId)return{skip:!0};if(W===this.ownBotId)return{skip:!0};let w=(J7($,"text")??"").includes(`<@${this.ownBotUserId}>`),U=J7($,"thread_ts")??J7($,"ts")??"",H=this.minify?Gc1($):$;return{skip:!1,content:JSON.stringify(H),meta:{event_type:"slack",channel_id:X,user_id:K??"",mentioned:String(w),thread_ts:U},shouldReact:w,channel:X,timestamp:J7($,"ts")??""}}}var br0=u.object({event:u.record(u.string(),u.unknown()).optional()}),Ar0=new I6;class hC extends f2{config;logger;onAppCreated;preprocessEvent;app=null;constructor($){super();this.config=$.config,this.logger=$.logger??Ar0,this.onAppCreated=$.onAppCreated??null,this.preprocessEvent=$.preprocessEvent??null}async start($){let x=new WF.App({token:this.config.botToken,appToken:this.config.appToken,socketMode:!0,logLevel:WF.LogLevel.ERROR}),Y=await x.client.auth.test({token:this.config.botToken}),X=new mC({ownBotUserId:Y.user_id??"",ownBotId:Y.bot_id??"",minify:this.config.minify}),Q=this.preprocessEvent;if(x.use(async(z)=>{let Z=br0.safeParse(z);if(!Z.success||!Z.data.event){await z.next();return}let K=Z.data.event,W=Q?Q(K):K;if(W===null)return;let V=X.process(W);if(V.skip)return;if(await $(V.content,V.meta),V.shouldReact)try{await x.client.reactions.add({token:this.config.botToken,channel:V.channel,timestamp:V.timestamp,name:"eyes"})}catch{}}),x.error(async(z)=>{this.logger.error("Slack error",{error:z instanceof Error?z.message:String(z)})}),this.onAppCreated)await this.onAppCreated(x);await x.start(),this.app=x}async stop(){if(!this.app)return;try{await this.app.stop()}catch($){this.logger.error("Slack stop error",{error:$ instanceof Error?$.message:String($)})}finally{this.app=null}}isAlive(){return this.app!==null}}import{join as gC}from"path";var Rr0=new _8,fr0=new M8,kr0=new I6;class pC{fs;process;logger;dir;slackListenerOptions;scheduleListenerOptions;constructor($={}){this.fs=$.fs??Rr0,this.process=$.process??fr0,this.logger=$.logger??kr0,this.dir=$.dir??b8,this.slackListenerOptions=$.slackListenerOptions??{},this.scheduleListenerOptions=$.scheduleListenerOptions??{},Object.freeze(this)}createListener($,x){if(x.type==="slack")return new hC({config:x,logger:this.logger,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(x.type==="gh")return new Qf({config:x,process:this.process,logger:this.logger});if(x.type==="discord")return new xf({config:x,logger:this.logger});let Y=new zf({path:gC(this.connectorDir($,x.id),"state.json"),fs:this.fs});return new Xf({config:x,lastFiredStore:Y,logger:this.logger,onFired:this.scheduleListenerOptions.onFired})}createAdapter($){if($.type==="slack")return new ck({config:$});if($.type==="gh")return new Yf({process:this.process});if($.type==="discord")return new KM({config:$});return null}connectorDir($,x){return gC(this.dir,"channels",$,"connectors",x)}channelDir($){return gC(this.dir,"channels",$)}}function iC($){switch($.type){case"slack":return[$.botToken,$.appToken];case"discord":return[$.botToken];case"gh":case"schedule":return[]}}function Tr0($,x){return $.type===x}function QX($,x,Y){let X=$.connectors.find((Q)=>Q.name===x);if(!X)throw Error(`connector "${x}" not found in channel "${$.name}"`);if(!Tr0(X,Y))throw Error(`connector "${x}" is type "${X.type}", not "${Y}"`);return X}class CV{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class XX extends CV{now(){return new Date}}class uV{}class yV extends uV{generate(){return crypto.randomUUID()}}var Sr0=new XX,cr0=new yV;class lC{store;factory;profileChecker;clock;idGenerator;constructor($){this.store=$.store,this.factory=$.factory,this.profileChecker=$.profileChecker,this.clock=$.clock??Sr0,this.idGenerator=$.idGenerator??cr0,Object.freeze(this)}list(){return this.store.read().channels}get($){return this.list().find((x)=>x.name===$)??null}getById($){return this.list().find((x)=>x.id===$)??null}add($){let x=this.store.read();if(x.channels.some((X)=>X.name===$.name))throw Error(`channel "${$.name}" already exists`);let Y={id:this.idGenerator.generate(),name:$.name,delivery:$.delivery??"fanout",connectors:[]};return x.channels.push(Y),this.store.write(x),Y}setDelivery($,x){let Y=this.store.read(),X=this.requireChannel(Y,$);X.delivery=x,this.store.write(Y)}remove($){let x=this.store.read(),Y=x.channels.findIndex((Q)=>Q.name===$);if(Y<0)throw Error(`channel "${$}" not found`);let X=x.channels[Y];if(X&&this.profileChecker.hasChannelRef(X.id))throw Error(`channel "${$}" is referenced by a profile`);x.channels.splice(Y,1),this.store.write(x)}rename($,x){let Y=this.store.read(),X=Y.channels.find((Q)=>Q.name===$);if(!X)throw Error(`channel "${$}" not found`);if(Y.channels.some((Q)=>Q.name===x))throw Error(`channel "${x}" already exists`);X.name=x,this.store.write(Y)}listConnectors($){return this.requireChannel(this.store.read(),$).connectors}getConnector($,x){let Y=this.get($);if(!Y)return null;return Y.connectors.find((X)=>X.name===x)??null}listAllConnectors(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({...Y,channelId:x.id,channelName:x.name});return $}addConnector($,x){let Y=this.store.read(),X=this.requireChannel(Y,$);if(X.connectors.some((z)=>z.name===x.name))throw Error(`connector "${x.name}" already exists in channel "${$}"`);let Q=this.fromInput(x);return this.assertNoTokenCollision(Y,Q),X.connectors.push(Q),this.store.write(Y),Q}fromInput($){let x=this.idGenerator.generate(),Y=this.clock.iso(),X=Y,Q=Y;switch($.type){case"slack":return{id:x,type:"slack",name:$.name,botToken:$.botToken,appToken:$.appToken,minify:$.minify??!0,createdAt:X,updatedAt:Q};case"gh":return{id:x,type:"gh",name:$.name,...$.pollInterval!==void 0?{pollInterval:$.pollInterval}:{},createdAt:X,updatedAt:Q};case"discord":return{id:x,type:"discord",name:$.name,botToken:$.botToken,createdAt:X,updatedAt:Q};case"schedule":return{id:x,type:"schedule",name:$.name,entries:$.entries??[],createdAt:X,updatedAt:Q}}}removeConnector($,x){let Y=this.store.read(),X=this.requireChannel(Y,$),Q=X.connectors.findIndex((z)=>z.name===x);if(Q<0)throw Error(`connector "${x}" not found in channel "${$}"`);X.connectors.splice(Q,1),this.store.write(Y)}renameConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=Q.connectors.find((Z)=>Z.name===x);if(!z)throw Error(`connector "${x}" not found in channel "${$}"`);if(Q.connectors.some((Z)=>Z.name===Y))throw Error(`connector "${Y}" already exists in channel "${$}"`);z.name=Y,z.updatedAt=this.clock.iso(),this.store.write(X)}updateSlackConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"slack"),Z={...z,botToken:Y.botToken??z.botToken,appToken:Y.appToken??z.appToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(X,Z),Object.assign(z,Z),this.store.write(X)}updateGhConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"gh");if(Y.pollInterval!==void 0)z.pollInterval=Y.pollInterval;z.updatedAt=this.clock.iso(),this.store.write(X)}updateDiscordConnector($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"discord"),Z={...z,botToken:Y.botToken??z.botToken,updatedAt:this.clock.iso()};this.assertNoTokenCollision(X,Z),Object.assign(z,Z),this.store.write(X)}listScheduleEntries($,x){let Y=this.requireChannel(this.store.read(),$);return QX(Y,x,"schedule").entries}addScheduleEntry($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"schedule"),Z={id:Y.id??this.idGenerator.generate(),cron:Y.cron,prompt:Y.prompt,enabled:Y.enabled??!0,catchupPolicy:Y.catchupPolicy??"latest"};return z.entries.push(Z),z.updatedAt=this.clock.iso(),this.store.write(X),Z}removeScheduleEntry($,x,Y){let X=this.store.read(),Q=this.requireChannel(X,$),z=QX(Q,x,"schedule"),Z=z.entries.findIndex((K)=>K.id===Y);if(Z<0)throw Error(`schedule entry "${Y}" not found`);z.entries.splice(Z,1),z.updatedAt=this.clock.iso(),this.store.write(X)}async call($,x,Y){let X=this.getConnector($,x);if(!X)throw Error(`connector "${x}" not found in channel "${$}"`);let Q=this.factory.createAdapter(X);if(!Q)throw Error(`connector type "${X.type}" does not support outbound calls`);return await Q.call(Y)}createListener($,x){let Y=this.get($);if(!Y)return null;let X=Y.connectors.find((Q)=>Q.name===x);if(!X)return null;return{config:X,channelId:Y.id,listener:this.factory.createListener(Y.id,X)}}createAllListeners(){let $=[];for(let x of this.list())for(let Y of x.connectors)$.push({config:Y,channelId:x.id,channelName:x.name,listener:this.factory.createListener(x.id,Y)});return $}requireChannel($,x){let Y=$.channels.find((X)=>X.name===x);if(!Y)throw Error(`channel "${x}" not found`);return Y}assertNoTokenCollision($,x){let Y=iC(x);if(Y.length===0)return;for(let X of $.channels)for(let Q of X.connectors){if(Q.id===x.id)continue;for(let z of iC(Q))if(Y.includes(z))throw Error(`token already in use by connector "${Q.name}" in channel "${X.name}"`)}}}import{homedir as Er0}from"os";import{join as VF}from"path";var Cr0=new M8,ur0=new _8,yr0=new I6;class nC{channels;mcp;gateway;sessions;process;fs;logger;pidDir;constructor($){this.channels=$.channels,this.mcp=$.mcp,this.gateway=$.gateway,this.sessions=$.sessions,this.process=$.process??Cr0,this.fs=$.fs??ur0,this.logger=$.logger??yr0,this.pidDir=VF($.dir??b8,"claude"),Object.freeze(this)}async launch($){let x=this.channels.get($.channel)??this.channels.getById($.channel);if(!x)throw Error(`channel "${$.channel}" not found`);if($.profileName&&this.isRunning($.profileName))throw Error(`profile "${$.profileName}" is already running`);let Y=$.cwd??globalThis.process.cwd();if(($.installMcp??!0)&&!this.mcp.findInstalledName(Y))this.mcp.install(Y),this.logger.info("added funnel MCP to .mcp.json",{cwd:Y});if(!this.gateway.isRunning())this.logger.info("starting gateway automatically"),await this.gateway.start();if($.profileName)this.writePidFile($.profileName),this.installCleanup($.profileName);let z=$.resume??!0?this.resolveSession(x.id,Y,$.userArgs??[],$.env??{}):null,Z=this.buildArgs($.options??[],$.userArgs??[],Y,z),K=this.buildEnv(x.id,$.env??{});this.logger.info("claude launch",{channel:$.channel,channelId:x.id,cwd:Y});try{return await this.process.attach(["claude",...Z],{cwd:Y,env:K,onSpawned:$.onSpawned})}finally{if($.profileName)this.removePidFile($.profileName)}}isRunning($){let x=this.readPid($);if(!x)return!1;return this.isProcessAlive(x)}pidPath($){return VF(this.pidDir,`${$}.pid`)}readPid($){let x=this.pidPath($);if(!this.fs.existsSync(x))return null;try{let Y=this.fs.readFileSync(x).trim(),X=Number(Y);if(!X||X<=0)return null;return X}catch{return null}}writePidFile($){this.fs.mkdirSync(this.pidDir,{recursive:!0}),this.fs.writeFileSync(this.pidPath($),String(globalThis.process.pid))}removePidFile($){let x=this.pidPath($);if(this.fs.existsSync(x))this.fs.unlink(x)}installCleanup($){globalThis.process.once("exit",()=>this.removePidFile($))}isProcessAlive($){return this.process.isAlive($)}buildArgs($,x,Y,X){let Q=[...$,...x];if(X!==null)if(X.mode==="resume")Q.push("--resume",X.id);else Q.push("--session-id",X.id);let z=this.mcp.findInstalledName(Y);if(z&&!Q.includes("--dangerously-load-development-channels")&&!Q.includes("--channels"))Q.push("--dangerously-load-development-channels",`server:${z}`);return Q}resolveSession($,x,Y,X){for(let z of Y){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 Q=this.sessions.get($,x);if(Q!==null&&this.sessionFileExists(x,Q,X))return{id:Q,mode:"resume"};return{id:this.sessions.create($,x),mode:"new"}}sessionFileExists($,x,Y){let X=Y.CLAUDE_CONFIG_DIR??globalThis.process.env.CLAUDE_CONFIG_DIR??VF(Er0(),".claude"),Q=$.replace(/\//g,"-");return this.fs.existsSync(VF(X,"projects",Q,`${x}.jsonl`))}buildEnv($,x){let Y={};for(let[X,Q]of Object.entries(x))Y[X]=Q;for(let[X,Q]of Object.entries(globalThis.process.env))if(typeof Q==="string")Y[X]=Q;return Y.FUNNEL_CHANNEL_ID=$,Y}}var mr0=384;class dC extends JK{dirs;files;mtimes;modes;now;constructor($={}){super();this.dirs=new Set($.dirs??[]),this.files=new Map(Object.entries($.files??{})),this.mtimes=new Map(Object.entries($.mtimes??{})),this.modes=new Map(Object.entries($.modes??{})),this.now=$.now??(()=>Date.now())}existsSync($){return this.dirs.has($)||this.files.has($)}readFileSync($){return this.files.get($)??""}writeFileSync($,x){this.files.set($,x),this.touch($)}writeSecretFileSync($,x){this.files.set($,x),this.modes.set($,mr0),this.touch($)}appendFileSync($,x){let Y=this.files.get($)??"";this.files.set($,Y+x),this.touch($)}unlink($){this.files.delete($),this.mtimes.delete($),this.modes.delete($)}mkdirSync($,x){this.dirs.add($)}readdirSync($){let x=$.endsWith("/")?$:`${$}/`,Y=[];for(let X of this.files.keys()){if(!X.startsWith(x))continue;let Q=X.slice(x.length);if(!Q.includes("/"))Y.push(Q)}return Y}statSync($){let x=this.mtimes.get($);if(x===void 0)throw Error(`not found: ${$}`);return{mtimeMs:x,mode:this.modes.get($)??null}}setMtime($,x){this.mtimes.set($,x)}setMode($,x){this.modes.set($,x)}touch($){if(!this.mtimes.has($))this.mtimes.set($,this.now());else this.mtimes.set($,this.now())}}class aC extends uV{counter=0;prefix;constructor($={}){super();this.prefix=$.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}import{join as or0}from"path";var hr0=u.object({botToken:u.string().optional(),appToken:u.string().optional()}).optional(),gr0=u.object({type:u.literal("slack"),name:u.string(),botToken:u.string().optional(),appToken:u.string().optional(),minify:u.boolean().optional(),env:hr0}),pr0=u.object({botToken:u.string().optional()}).optional(),ir0=u.object({type:u.literal("discord"),name:u.string(),botToken:u.string().optional(),env:pr0}),lr0=u.object({type:u.literal("gh"),name:u.string(),pollInterval:u.number().int().positive().optional()}),nr0=u.object({type:u.literal("schedule"),name:u.string()}),dr0=u.discriminatedUnion("type",[gr0,ir0,lr0,nr0]),ar0=u.object({name:u.string(),connectors:u.array(dr0).optional()}),sr0=u.object({name:u.string(),channel:u.string(),options:u.array(u.string()).optional(),env:u.record(u.string(),u.string()).optional(),resume:u.boolean().optional()}),Jc1=u.object({$schema:u.string().optional(),channels:u.array(ar0).min(1),profiles:u.array(sr0).optional()}),wF="funnel.json",qc1=".env.local";var rr0=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/,tr0=($)=>{if($.length<2)return $;let x=$[0],Y=$[$.length-1];if(x==='"'&&Y==='"')return $.slice(1,-1);if(x==="'"&&Y==="'")return $.slice(1,-1);return $};class sC{fs;constructor($){this.fs=$.fs,Object.freeze(this)}read($){let x=or0($,qc1);if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x),X={};for(let Q of Y.split(`
|
|
550
550
|
`)){let z=Q.trim();if(z===""||z.startsWith("#"))continue;let Z=z.match(rr0);if(!Z)continue;let K=Z[1],W=Z[2];if(!K)continue;X[K]=tr0(W??"")}return X}}import{join as er0}from"path";class oC{fs;constructor($){this.fs=$.fs,Object.freeze(this)}read($){let x=er0($,wF);if(!this.fs.existsSync(x))return null;let Y=this.fs.readFileSync(x),X=(()=>{try{return JSON.parse(Y)}catch(z){let Z=z instanceof Error?z.message:String(z);throw Error(`${wF} is not valid JSON: ${Z}`)}})(),Q=Jc1.safeParse(X);if(!Q.success)throw Error(`${wF} is invalid: ${Q.error.message}`);return Q.data}}class rC{channels;dotenv;prompter;env;constructor($){this.channels=$.channels,this.dotenv=$.dotenv,this.prompter=$.prompter,this.env=$.env??process.env,Object.freeze(this)}async ensure($,x){if(!this.channels.get($.name))this.channels.add({name:$.name});if($.connectors===void 0)return{touched:[],removed:[]};let X=this.dotenv.read(x),Q=[],z=new Set;for(let K of $.connectors){let W=await this.ensureConnector($.name,K,X);Q.push({name:W.name,changed:W.changed}),z.add(W.id)}let Z=this.removeExtras($.name,z);return{touched:Q,removed:Z}}async ensureConnector($,x,Y){if(x.type==="slack")return await this.ensureSlack($,x,Y);if(x.type==="discord")return await this.ensureDiscord($,x,Y);if(x.type==="gh")return this.ensureGh($,x);return this.ensureSchedule($,x)}async ensureSlack($,x,Y){let X=this.findExistingSlack($,x.name),Q=await this.resolveField({literal:x.botToken,envVar:x.env?.botToken,dotenv:Y,label:`${x.name}.botToken`,existing:X?.botToken}),z=await this.resolveField({literal:x.appToken,envVar:x.env?.appToken,dotenv:Y,label:`${x.name}.appToken`,existing:X?.appToken});if(X){if(X.botToken!==Q||X.appToken!==z)return this.channels.updateSlackConnector($,x.name,{botToken:Q,appToken:z}),{id:X.id,name:x.name,changed:!0};return{id:X.id,name:x.name,changed:!1}}let Z=this.findSlackByToken($,[Q,z]);if(Z){if(this.channels.renameConnector($,Z.name,x.name),Z.botToken!==Q||Z.appToken!==z)this.channels.updateSlackConnector($,x.name,{botToken:Q,appToken:z});return{id:Z.id,name:x.name,changed:!0}}return{id:this.channels.addConnector($,{type:"slack",name:x.name,botToken:Q,appToken:z,...x.minify!==void 0?{minify:x.minify}:{}}).id,name:x.name,changed:!0}}async ensureDiscord($,x,Y){let X=this.findExistingDiscord($,x.name),Q=await this.resolveField({literal:x.botToken,envVar:x.env?.botToken,dotenv:Y,label:`${x.name}.botToken`,existing:X?.botToken});if(X){if(X.botToken!==Q)return this.channels.updateDiscordConnector($,x.name,{botToken:Q}),{id:X.id,name:x.name,changed:!0};return{id:X.id,name:x.name,changed:!1}}let z=this.findDiscordByToken($,Q);if(z){if(this.channels.renameConnector($,z.name,x.name),z.botToken!==Q)this.channels.updateDiscordConnector($,x.name,{botToken:Q});return{id:z.id,name:x.name,changed:!0}}return{id:this.channels.addConnector($,{type:"discord",name:x.name,botToken:Q}).id,name:x.name,changed:!0}}ensureGh($,x){let Y=this.channels.getConnector($,x.name);if(Y&&Y.type!=="gh")throw Error(`connector "${x.name}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "gh"`);if(Y&&Y.type==="gh"){if(x.pollInterval!==void 0&&Y.pollInterval!==x.pollInterval)return this.channels.updateGhConnector($,x.name,{pollInterval:x.pollInterval}),{id:Y.id,name:x.name,changed:!0};return{id:Y.id,name:x.name,changed:!1}}return{id:this.channels.addConnector($,{type:"gh",name:x.name,...x.pollInterval!==void 0?{pollInterval:x.pollInterval}:{}}).id,name:x.name,changed:!0}}ensureSchedule($,x){let Y=this.channels.getConnector($,x.name);if(Y&&Y.type!=="schedule")throw Error(`connector "${x.name}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "schedule"`);if(Y&&Y.type==="schedule")return{id:Y.id,name:x.name,changed:!1};return{id:this.channels.addConnector($,{type:"schedule",name:x.name}).id,name:x.name,changed:!0}}findExistingSlack($,x){let Y=this.channels.getConnector($,x);if(!Y)return null;if(Y.type!=="slack")throw Error(`connector "${x}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "slack"`);return Y}findExistingDiscord($,x){let Y=this.channels.getConnector($,x);if(!Y)return null;if(Y.type!=="discord")throw Error(`connector "${x}" exists in channel "${$}" with type "${Y.type}", funnel.json declares "discord"`);return Y}findSlackByToken($,x){let Y=this.channels.get($);if(!Y)return null;for(let X of Y.connectors){if(X.type!=="slack")continue;if(x.includes(X.botToken)||x.includes(X.appToken))return X}return null}findDiscordByToken($,x){let Y=this.channels.get($);if(!Y)return null;for(let X of Y.connectors){if(X.type!=="discord")continue;if(X.botToken===x)return X}return null}removeExtras($,x){let Y=this.channels.get($);if(!Y)return[];let X=Y.connectors.filter((Q)=>!x.has(Q.id));for(let Q of X)this.channels.removeConnector($,Q.name);return X.map((Q)=>Q.name)}async resolveField($){if($.literal!==void 0&&$.envVar!==void 0)throw Error(`${$.label} is set both as a literal and as env.${$.label.split(".").pop()}; pick one`);if($.literal!==void 0&&$.literal!=="")return $.literal;if($.envVar!==void 0&&$.envVar!==""){let x=this.env[$.envVar];if(x)return x;let Y=$.dotenv[$.envVar];if(Y)return Y;throw Error(`${$.label} references env var "${$.envVar}" but it is not set in process env or .env.local`)}if($.existing)return $.existing;return await this.prompter.promptSecret($.label)}}class tC extends jQ{file=null;entries=[];info($,x){this.entries.push({level:"info",message:$,meta:x})}warn($,x){this.entries.push({level:"warn",message:$,meta:x})}error($,x){this.entries.push({level:"error",message:$,meta:x})}clear(){this.entries.length=0}}import{join as Bc1}from"path";var Dc1="funnel",$t0="funnel",xt0=u.object({command:u.string().optional(),args:u.array(u.string()).optional()}),Yt0=u.object({mcpServers:u.record(u.string(),xt0).optional()}),Qt0=new _8;class eC{fs;constructor($={}){this.fs=$.fs??Qt0,Object.freeze(this)}install($){if(!this.fs.existsSync($))throw Error(`repository does not exist: ${$}`);let x=this.readConfig($),Y=x.mcpServers??{},Q=this.findServerName(Y)??$t0;Y[Q]={command:Dc1,args:["mcp"]},this.writeConfig($,{...x,mcpServers:Y})}uninstall($){if(!this.fs.existsSync($))return;let x=this.readConfig($),Y=x.mcpServers??{},X=this.findServerName(Y);if(!X)return;let Q={...Y};delete Q[X],this.writeConfig($,{...x,mcpServers:Q})}findInstalledName($){let x=this.readConfig($);return this.findServerName(x.mcpServers??{})}findServerName($){for(let x of Object.entries($)){let Y=x[0];if(x[1]?.command===Dc1)return Y}return null}readConfig($){let x=Bc1($,".mcp.json");if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x).trim();if(!Y)return{};let X;try{X=JSON.parse(Y)}catch(z){throw Error(`invalid .mcp.json (${x}): ${z instanceof Error?z.message:String(z)}`)}let Q=Yt0.safeParse(X);if(!Q.success)throw Error(`invalid .mcp.json (${x}): ${Q.error.message}`);return Q.data}writeConfig($,x){let Y=Bc1($,".mcp.json");this.fs.writeFileSync(Y,`${JSON.stringify(x,null,2)}
|
|
551
551
|
`)}}var Fc1={exitCode:0,stdout:"",stderr:""};class $u extends GK{calls=[];killed=[];handler=()=>Fc1;syncHandler=()=>Fc1;aliveStub=null;listStub=null;on($){return this.handler=$,this}onSync($){return this.syncHandler=$,this}onIsAlive($){return this.aliveStub=$,this}onListProcessesContaining($){return this.listStub=$,this}async run($,x={}){this.calls.push({kind:"run",command:$,options:x});let Y=await this.handler($);return{exitCode:Y.exitCode??0,stdout:Y.stdout??"",stderr:Y.stderr??""}}runSync($){this.calls.push({kind:"runSync",command:$});let x=this.syncHandler($);return{exitCode:x.exitCode??0,stdout:x.stdout??"",stderr:x.stderr??""}}async attach($,x={}){if(this.calls.push({kind:"attach",command:$,options:x}),x.onSpawned)x.onSpawned(1);return(await this.handler($)).exitCode??0}detach($,x={}){this.calls.push({kind:"detach",command:$,options:x})}kill($,x="SIGTERM"){this.calls.push({kind:"kill",command:[String($),x]}),this.killed.push({pid:$,signal:x})}isAlive($){if(this.aliveStub)return this.aliveStub($);let x=this.syncHandler(["ps","-p",String($),"-o","state="]);if((x.exitCode??0)!==0)return!1;let Y=(x.stdout??"").trim();if(!Y)return!1;return!Y.startsWith("Z")}listProcessesContaining($){if(this.listStub)return this.listStub($);return[]}}class xu{store;constructor($){this.store=$.store,Object.freeze(this)}list(){return this.store.read().profiles}get($){return this.list().find((x)=>x.name===$)??null}getDefault(){return this.list()[0]??null}add($){let x=this.store.read();if(x.profiles.some((Y)=>Y.name===$.name))throw Error(`profile "${$.name}" already exists`);if(!x.channels.some((Y)=>Y.id===$.channelId))throw Error(`channel id "${$.channelId}" not found`);x.profiles.push({name:$.name,path:$.path,channelId:$.channelId,options:$.options??[],env:$.env??{},resume:$.resume??!0}),this.store.write(x)}remove($){let x=this.store.read(),Y=x.profiles.findIndex((X)=>X.name===$);if(Y<0)throw Error(`profile "${$}" not found`);x.profiles.splice(Y,1),this.store.write(x)}rename($,x){let Y=this.store.read(),X=Y.profiles.find((Q)=>Q.name===$);if(!X)throw Error(`profile "${$}" not found`);if(Y.profiles.some((Q)=>Q.name===x))throw Error(`profile "${x}" already exists`);X.name=x,this.store.write(Y)}asDefault($){let x=this.store.read(),Y=x.profiles.findIndex((Q)=>Q.name===$);if(Y<0)throw Error(`profile "${$}" not found`);if(Y===0)return;let[X]=x.profiles.splice(Y,1);if(!X)return;x.profiles.unshift(X),this.store.write(x)}hasChannelRef($){return this.store.read().profiles.some((x)=>x.channelId===$)}update($,x){let Y=this.store.read(),X=Y.profiles.find((Q)=>Q.name===$);if(!X)throw Error(`profile "${$}" not found`);if(x.channelId!==void 0){if(!Y.channels.some((Q)=>Q.id===x.channelId))throw Error(`channel id "${x.channelId}" not found`);X.channelId=x.channelId}if(x.path!==void 0)X.path=x.path;if(x.options!==void 0)X.options=x.options;if(x.env!==void 0)X.env=x.env;if(x.resume!==void 0)X.resume=x.resume;this.store.write(Y)}}import{join as Lc1}from"path";var Xt0=u.record(u.string(),u.string());class Yu{fs;idGenerator;dir;constructor($){this.fs=$.fs,this.idGenerator=$.idGenerator,this.dir=$.dir,Object.freeze(this)}get($,x){return this.readMap($)[x]??null}create($,x){let Y=this.readMap($),X=this.idGenerator.generate();return Y[x]=X,this.writeMap($,Y),X}clear($,x){let Y=this.readMap($);if(!(x in Y))return;delete Y[x],this.writeMap($,Y)}clearAll($){let x=this.pathFor($);if(this.fs.existsSync(x))this.fs.unlink(x)}readMap($){let x=this.pathFor($);if(!this.fs.existsSync(x))return{};let Y=this.fs.readFileSync(x);try{let X=Xt0.safeParse(JSON.parse(Y));return X.success?X.data:{}}catch{return{}}}writeMap($,x){let Y=this.pathFor($),X=this.channelDir($);if(!this.fs.existsSync(X))this.fs.mkdirSync(X,{recursive:!0});this.fs.writeFileSync(Y,`${JSON.stringify(x,null,2)}
|
|
552
552
|
`)}channelDir($){return Lc1(this.dir,"channels",$)}pathFor($){return Lc1(this.channelDir($),"sessions.json")}}import{stderr as UF,stdin as e7}from"process";class Qu{}var zt0="*",Zt0="\r",Nc1=`
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { i as FunnelDiscordAdapter, n as FunnelDiscordListener, t as discordConn
|
|
|
2
2
|
import { i as FunnelConnectorListener, n as funnelTmpDir, r as FunnelLogger, t as NodeFunnelLogger } from "./node-logger-B97ZiGwj.js";
|
|
3
3
|
import { a as FunnelProcessRunner, i as NodeFunnelProcessRunner, n as FunnelGhListener, r as FunnelGhAdapter, t as ghConnectorSchema } from "./gh-connector-schema-CAC24s0r.js";
|
|
4
4
|
import { a as ScheduleStateStore, i as FunnelScheduleListener, n as scheduleConnectorSchema, o as NodeFunnelFileSystem, r as scheduleEntrySchema, s as FunnelFileSystem, t as scheduleCatchupPolicySchema } from "./schedule-connector-schema-BZpH6ZmR.js";
|
|
5
|
-
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "./slack-connector-schema-
|
|
5
|
+
import { i as FunnelSlackAdapter, n as FunnelSlackListener, r as FunnelSlackEventProcessor, t as slackConnectorSchema } from "./slack-connector-schema-Dhlnfp0g.js";
|
|
6
6
|
import { dirname, join, resolve } from "node:path";
|
|
7
7
|
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
8
8
|
import { homedir } from "node:os";
|
|
@@ -222,7 +222,10 @@ var FunnelSlackListener = class extends FunnelConnectorListener {
|
|
|
222
222
|
const preprocess = this.preprocessEvent;
|
|
223
223
|
app.use(async (args) => {
|
|
224
224
|
const parsed = middlewareArgsSchema.safeParse(args);
|
|
225
|
-
if (!parsed.success || !parsed.data.event)
|
|
225
|
+
if (!parsed.success || !parsed.data.event) {
|
|
226
|
+
await args.next();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
226
229
|
const rawEvent = parsed.data.event;
|
|
227
230
|
const event = preprocess ? preprocess(rawEvent) : rawEvent;
|
|
228
231
|
if (event === null) return;
|
package/package.json
CHANGED