@interactive-inc/claude-funnel 0.39.0 → 0.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2 -2
- package/dist/gateway/daemon.js +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +2 -1
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -481,7 +481,7 @@ Since you have not provided a token or authorize, you might be missing one or mo
|
|
|
481
481
|
* Copyright(c) 2013 Roman Shtylman
|
|
482
482
|
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
|
483
483
|
* MIT Licensed
|
|
484
|
-
*/var UI=pr1(),hL6=v("events").EventEmitter,Ze1=lr1(),Ke1=as1(),We1=Vl(),Ve1=It1(),He1=Qe1();i7=Ge1.exports=gL6;function gL6(){var $=function(Y,Q,X){$.handle(Y,Q,X)};return Ze1($,hL6.prototype,!1),Ze1($,Ke1,!1),$.request=Object.create(Ve1,{app:{configurable:!0,enumerable:!0,writable:!0,value:$}}),$.response=Object.create(He1,{app:{configurable:!0,enumerable:!0,writable:!0,value:$}}),$.init(),$}i7.application=Ke1;i7.request=Ve1;i7.response=He1;i7.Route=We1.Route;i7.Router=We1;i7.json=UI.json;i7.raw=UI.raw;i7.static=ze1();i7.text=UI.text;i7.urlencoded=UI.urlencoded});var je1=x((Q8)=>{var mL6=Q8&&Q8.__createBinding||(Object.create?function($,Y,Q,X){if(X===void 0)X=Q;var z=Object.getOwnPropertyDescriptor(Y,Q);if(!z||("get"in z?!Y.__esModule:z.writable||z.configurable))z={enumerable:!0,get:function(){return Y[Q]}};Object.defineProperty($,X,z)}:function($,Y,Q,X){if(X===void 0)X=Q;$[X]=Y[Q]}),pL6=Q8&&Q8.__setModuleDefault||(Object.create?function($,Y){Object.defineProperty($,"default",{enumerable:!0,value:Y})}:function($,Y){$.default=Y}),xe1=Q8&&Q8.__importStar||function($){if($&&$.__esModule)return $;var Y={};if($!=null){for(var Q in $)if(Q!=="default"&&Object.prototype.hasOwnProperty.call($,Q))mL6(Y,$,Q)}return pL6(Y,$),Y},xI=Q8&&Q8.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(Q8,"__esModule",{value:!0});Q8.buildBodyParserMiddleware=Q8.verifySignatureAndParseBody=Q8.verifySignatureAndParseRawBody=Q8.respondToUrlVerification=Q8.respondToSslCheck=void 0;var iL6=xI(v("crypto")),lL6=v("http"),nL6=v("https"),dL6=xI(v("querystring")),we1=L$(),aL6=fw(),Ue1=xe1(Je1()),oL6=xI(_P()),rL6=xI(RP()),qQ=P$(),v2=xe1(pw()),sL6=kP(),tL6=fP(),eL6=["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"],bl="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",$N6=($,Y,Q)=>{if($.body?.ssl_check){Y.send();return}Q()};Q8.respondToSslCheck=$N6;var YN6=($,Y,Q)=>{if($.body?.type&&$.body.type==="url_verification"){Y.json({challenge:$.body.challenge});return}Q()};Q8.respondToUrlVerification=YN6;class Be1{app;server;bolt;logger;processBeforeResponse;signatureVerification;router;installer=void 0;installerOptions;customPropertiesExtractor;dispatchErrorHandler;processEventErrorHandler;unhandledRequestHandler;unhandledRequestTimeoutMillis;constructor({signingSecret:$="",logger:Y=void 0,logLevel:Q=we1.LogLevel.INFO,endpoints:X={events:"/slack/events"},processBeforeResponse:z=!1,signatureVerification:Z=!0,clientId:K=void 0,clientSecret:W=void 0,stateSecret:V=void 0,redirectUri:H=void 0,installationStore:G=void 0,scopes:J=void 0,installerOptions:w={},app:U=void 0,router:B=void 0,customPropertiesExtractor:D=(I)=>({}),dispatchErrorHandler:q=v2.defaultAsyncDispatchErrorHandler,processEventErrorHandler:F=v2.defaultProcessEventErrorHandler,unhandledRequestHandler:P=v2.defaultUnhandledRequestHandler,unhandledRequestTimeoutMillis:L=3001}){if(this.app=U!==void 0?U:(0,Ue1.default)(),typeof Y<"u")this.logger=Y;else this.logger=new we1.ConsoleLogger,this.logger.setLevel(Q);this.signatureVerification=Z;let O=[this.signatureVerification?qe1(this.logger,$):Fe1(this.logger),Q8.respondToSslCheck,Q8.respondToUrlVerification,this.requestHandler.bind(this)];this.processBeforeResponse=z;let m=typeof X==="string"?[X]:Object.values(X);this.router=B!==void 0?B:(0,Ue1.Router)();for(let H1 of m)this.router.post(H1,...O);if(this.customPropertiesExtractor=D,this.dispatchErrorHandler=q,this.processEventErrorHandler=F,this.unhandledRequestHandler=P,this.unhandledRequestTimeoutMillis=L,(0,tL6.verifyRedirectOpts)({redirectUri:H,redirectUriPath:w.redirectUriPath}),K!==void 0&&W!==void 0&&(w.stateVerification===!1||V!==void 0||w.stateStore!==void 0))this.installer=new aL6.InstallProvider({clientId:K,clientSecret:W,stateSecret:V,installationStore:G,logLevel:Q,logger:Y,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 V1={metadata:w.metadata,scopes:J??[],userScopes:w.userScopes,redirectUri:H};if(this.installer!==void 0){let{installer:H1}=this,p=w.redirectUriPath===void 0?"/slack/oauth_redirect":w.redirectUriPath,{callbackOptions:i,stateVerification:X1}=w;this.router.use(p,async(I1,O1)=>{try{if(X1===!1)await H1.handleCallback(I1,O1,i,V1);else await H1.handleCallback(I1,O1,i)}catch(S1){await this.dispatchErrorHandler({error:S1,logger:this.logger,request:I1,response:O1})}});let G1=w.installPath===void 0?"/slack/install":w.installPath,{installPathOptions:A1}=w;this.router.get(G1,async(I1,O1,S1)=>{try{try{await H1.handleInstallPath(I1,O1,A1,V1)}catch(f1){S1(f1)}}catch(f1){await this.dispatchErrorHandler({error:f1,logger:this.logger,request:I1,response:O1})}})}this.app.use(this.router)}async requestHandler($,Y){let Q=new sL6.HTTPResponseAck({logger:this.logger,processBeforeResponse:this.processBeforeResponse,unhandledRequestHandler:this.unhandledRequestHandler,unhandledRequestTimeoutMillis:this.unhandledRequestTimeoutMillis,httpRequest:$,httpRequestBody:$.body,httpResponse:Y}),X={body:$.body,ack:Q.bind(),retryNum:v2.extractRetryNumFromHTTPRequest($),retryReason:v2.extractRetryReasonFromHTTPRequest($),customProperties:this.customPropertiesExtractor($)};try{if(await this.bolt?.processEvent(X),Q.storedResponse!==void 0)v2.buildContentResponse(Y,Q.storedResponse),this.logger.debug("stored response sent")}catch(z){if(await this.processEventErrorHandler({error:z,logger:this.logger,request:$,response:Y,storedResponse:Q.storedResponse}))Q.ack()}}init($){this.bolt=$}start($,Y={}){let Q=lL6.createServer;if(Object.keys(Y).filter((X)=>eL6.includes(X)).length>0)Q=nL6.createServer;if(this.server!==void 0)return Promise.reject(new qQ.ReceiverInconsistentStateError("The receiver cannot be started because it was already started."));return this.server=Q(Y,this.app),new Promise((X,z)=>{if(this.server===void 0)throw new qQ.ReceiverInconsistentStateError(bl);this.server.on("error",(Z)=>{if(this.server===void 0)throw new qQ.ReceiverInconsistentStateError(bl);this.server.close(),z(Z)}),this.server.on("close",()=>{this.server=void 0}),this.server.listen($,()=>{if(this.server===void 0)return z(new qQ.ReceiverInconsistentStateError(bl));return X(this.server)})})}stop(){if(this.server===void 0)return Promise.reject(new qQ.ReceiverInconsistentStateError("The receiver cannot be stopped because it was not started."));return new Promise(($,Y)=>{this.server?.close((Q)=>{if(Q!==void 0)return Y(Q);return this.server=void 0,$()})})}}Q8.default=Be1;function QN6($,Y){return qe1($,Y)}Q8.verifySignatureAndParseRawBody=QN6;function qe1($,Y){return async(Q,X,z)=>{let Z=await Ne1(Q);try{Q.body=De1(typeof Y==="string"?Y:await Y(),Z,Q.headers)}catch(K){if(K){if(K instanceof qQ.ReceiverAuthenticityError){Al($,"Request verification failed",K),X.status(401).send();return}Al($,"Parsing request body failed",K),X.status(400).send();return}}z()}}function Al($,Y,Q){let X="code"in Q?`${Y} (code: ${Q.code}, message: ${Q.message})`:`${Y} (error: ${Q})`;$.warn(X)}function XN6($,Y,Q,X){if(Q===void 0||X===void 0)throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Some headers are missing.");let z=Number(X);if(Number.isNaN(z))throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is invalid.");let Z=Math.floor(Date.now()/1000)-300;if(z<Z)throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is too old.");let K=iL6.default.createHmac("sha256",$),[W,V]=Q.split("=");if(K.update(`${W}:${z}:${Y}`),!(0,rL6.default)(V,K.digest("hex")))throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function De1($,Y,Q){let{"x-slack-signature":X,"x-slack-request-timestamp":z,"content-type":Z}=Q;return XN6($,Y,X,z),Le1(Y,Z)}Q8.verifySignatureAndParseBody=De1;function Fe1($){return async(Y,Q,X)=>{let z=await Ne1(Y);try{let{"content-type":Z}=Y.headers;Y.body=Le1(z,Z)}catch(Z){if(Z){Al($,"Parsing request body failed",Z),Q.status(400).send();return}}X()}}Q8.buildBodyParserMiddleware=Fe1;function Le1($,Y){if(Y==="application/x-www-form-urlencoded"){let Q=dL6.default.parse($);if(typeof Q.payload==="string")return JSON.parse(Q.payload);return Q}return JSON.parse($)}async function Ne1($){if("rawBody"in $&&$.rawBody)return Promise.resolve($.rawBody.toString());return(await(0,oL6.default)($)).toString()}});var ve1=x((Me1)=>{Object.defineProperty(Me1,"__esModule",{value:!0});Me1.DefaultThreadContextStore=void 0;var Pe1=_l();class Ie1{context={};async get($){let{context:Y,client:Q,payload:X,logger:z}=$;if(z.debug("DefaultAssistantThreadStore: get method called"),this.context.channel_id)return this.context;let{channelId:Z,threadTs:K}=(0,Pe1.extractThreadInfo)(X),W=await Q.conversations.replies({channel:Z,ts:K,oldest:K,include_all_metadata:!0,limit:4});if(!W.messages)return{};let V=W.messages.find((G)=>!("subtype"in G)&&G.user===Y.botUserId);return(V?.metadata?V.metadata.event_payload:null)||{}}async save($){let{context:Y,client:Q,payload:X,logger:z}=$,{channelId:Z,threadTs:K,context:W}=(0,Pe1.extractThreadInfo)(X);z.debug("DefaultAssistantThreadStore: save method called");let V=await Q.conversations.replies({channel:Z,ts:K,oldest:K,include_all_metadata:!0,limit:4});if(!V.messages)return;let H=V.messages.find((G)=>!("subtype"in G)&&G.user===Y.botUserId);if(H?.ts){let G={channel:Z,ts:H.ts,text:H.text,blocks:H.blocks?H.blocks:[],metadata:{event_type:"assistant_thread_context",event_payload:W}};await Q.chat.update(G)}this.context=W}}Me1.DefaultThreadContextStore=Ie1});var _l=x((u8)=>{var zN6=u8&&u8.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(u8,"__esModule",{value:!0});u8.extractThreadInfo=u8.processAssistantMiddleware=u8.validate=u8.isAssistantMessage=u8.matchesConstraints=u8.isAssistantEvent=u8.enrichAssistantArgs=u8.Assistant=void 0;var ZN6=ve1(),be1=Cg(),QK=P$(),BI=Fj(),KN6=zN6(Lj()),WN6=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class Ae1{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor($){Se1($);let{threadContextStore:Y=new ZN6.DefaultThreadContextStore,threadStarted:Q,threadContextChanged:X=(Z)=>Y.save(Z),userMessage:z}=$;this.threadContextStore=Y,this.threadStarted=Array.isArray(Q)?Q:[Q],this.threadContextChanged=Array.isArray(X)?X:[X],this.userMessage=Array.isArray(z)?z:[z]}getMiddleware(){return async($)=>{if(Re1($)&&Te1($))return this.processEvent($);return $.next()}}async processEvent($){let{payload:Y}=$,Q=_e1(this.threadContextStore,$),X=this.getAssistantMiddleware(Y);return fe1(Q,X)}getAssistantMiddleware($){switch($.type){case"assistant_thread_started":return this.threadStarted;case"assistant_thread_context_changed":return this.threadContextChanged;case"message":return this.userMessage;default:return[]}}}u8.Assistant=Ae1;function _e1($,Y){let{next:Q,...X}=Y,z={...X};return z.getThreadContext=()=>$.get(Y),z.saveThreadContext=()=>$.save(Y),z.say=VN6(z),z.sayStream=HN6(z),z.setStatus=GN6(z),z.setSuggestedPrompts=JN6(z),z.setTitle=wN6(z),z}u8.enrichAssistantArgs=_e1;function Re1($){return WN6.has($.payload.type)}u8.isAssistantEvent=Re1;function Te1($){return $.payload.type==="message"?ke1($.payload):!0}u8.matchesConstraints=Te1;function ke1($){let Y="channel"in $&&"thread_ts"in $,Q="channel_type"in $&&$.channel_type==="im"&&(!("subtype"in $)||$.subtype==="file_share"||$.subtype===void 0);return Y&&Q}u8.isAssistantMessage=ke1;function Se1($){if(typeof $!=="object")throw new QK.AssistantInitializationError("Assistant expects a configuration object as the argument");let Y=["threadStarted","userMessage"],Q=[];for(let z of Y)if($[z]===void 0)Q.push(z);if(Q.length>0){let z=`Assistant is missing required keys: ${Q.join(", ")}`;throw new QK.AssistantInitializationError(z)}let X=["threadStarted","userMessage"];if("threadContextChanged"in $)X.push("threadContextChanged");for(let z of X)if(typeof $[z]!=="function"&&!Array.isArray($[z])){let Z=`Assistant ${z} property must be a function or an array of functions`;throw new QK.AssistantInitializationError(Z)}if($.threadContextStore){if(typeof $.threadContextStore!=="object")throw new QK.AssistantInitializationError("Assistant expects threadContextStore to be a configuration object");let z=["get","save"],Z=[];for(let W of z)if($.threadContextStore&&$.threadContextStore[W]===void 0)Z.push(W);if(Z.length>0){let W=`threadContextStore is missing required keys: ${Z.join(", ")}`;throw new QK.AssistantInitializationError(W)}let K=["get","save"];for(let W of K)if($.threadContextStore&&typeof $.threadContextStore[W]!=="function"){let V=`threadContextStore ${W} property must be a function`;throw new QK.AssistantInitializationError(V)}}}u8.validate=Se1;async function fe1($,Y){let{context:Q,client:X,logger:z}=$,Z=[...Y],K=Z.pop();if(K!==void 0)await(0,KN6.default)(Z,$,Q,X,z,async()=>K({...$,context:Q,client:X,logger:z}))}u8.processAssistantMiddleware=fe1;function VN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z,context:Z}=b2(Q);return async(K)=>{let W=Z.channel_id?Z:await $.getThreadContext(),V=typeof K==="string"?{text:K,channel:X,thread_ts:z}:{...K,channel:X,thread_ts:z};if(W||V.metadata)V.metadata={event_type:V.metadata?.event_type??"assistant_thread_context",event_payload:{...W,...V.metadata?.event_payload??{}}};return Y.chat.postMessage(V)}}function HN6($){let{client:Y,context:Q,payload:X}=$,{channelId:z,threadTs:Z}=b2(X);return(0,be1.createSayStream)(Y,Q,z,Z)}function GN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z}=b2(Q);return(0,be1.createSetStatus)(Y,X,z)}function JN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z}=b2(Q);return(Z)=>{let{prompts:K,title:W}=Z;return Y.assistant.threads.setSuggestedPrompts({channel_id:X,thread_ts:z,prompts:K,title:W})}}function wN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z}=b2(Q);return(Z)=>Y.assistant.threads.setTitle({channel_id:X,thread_ts:z,title:Z})}function b2($){let Y={};if("assistant_thread"in $&&(0,BI.isRecord)($.assistant_thread)){if((0,BI.isRecord)($.assistant_thread.context))Y=$.assistant_thread.context}let Q=(0,BI.extractEventChannelId)($),X=(0,BI.extractEventThreadTs)($);if(!Q||!X){let z=[];if(!Q)z.push("channel_id");if(!X)z.push("thread_ts");throw new QK.AssistantMissingPropertyError(`Assistant message event is missing required properties: ${z.join(", ")}`)}return{channelId:Q,threadTs:X,context:Y}}u8.extractThreadInfo=b2});var he1=x((a9)=>{var UN6=a9&&a9.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(a9,"__esModule",{value:!0});a9.prepareStepArgs=a9.isStepEvent=a9.processStepMiddleware=a9.validate=a9.WorkflowStep=void 0;var qI=P$(),xN6=UN6(Lj()),BN6=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class Ee1{callbackId;edit;save;execute;constructor($,Y){Ce1($,Y);let{save:Q,edit:X,execute:z}=Y;this.callbackId=$,this.save=Array.isArray(Q)?Q:[Q],this.edit=Array.isArray(X)?X:[X],this.execute=Array.isArray(z)?z:[z]}getMiddleware(){return async($)=>{if(ce1($)&&this.matchesConstraints($))return this.processEvent($);return $.next()}}matchesConstraints($){return $.payload.callback_id===this.callbackId}async processEvent($){let{payload:Y}=$,Q=ye1($),X=this.getStepMiddleware(Y);return ue1(Q,X)}getStepMiddleware($){switch($.type){case"workflow_step_edit":return this.edit;case"workflow_step":return this.save;case"workflow_step_execute":return this.execute;default:return[]}}}a9.WorkflowStep=Ee1;function Ce1($,Y){if(typeof $!=="string")throw new qI.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof Y!=="object")throw new qI.WorkflowStepInitializationError("WorkflowStep expects a configuration object as the second argument");let Q=["save","edit","execute"],X=[];for(let Z of Q)if(Y[Z]===void 0)X.push(Z);if(X.length>0){let Z=`WorkflowStep is missing required keys: ${X.join(", ")}`;throw new qI.WorkflowStepInitializationError(Z)}let z=["save","edit","execute"];for(let Z of z)if(typeof Y[Z]!=="function"&&!Array.isArray(Y[Z])){let K=`WorkflowStep ${Z} property must be a function or an array of functions`;throw new qI.WorkflowStepInitializationError(K)}}a9.validate=Ce1;async function ue1($,Y){let{context:Q,client:X,logger:z}=$,Z=[...Y],K=Z.pop();if(K!==void 0)await(0,xN6.default)(Z,$,Q,X,z,async()=>K({...$,context:Q,client:X,logger:z}))}a9.processStepMiddleware=ue1;function ce1($){return BN6.has($.payload.type)}a9.isStepEvent=ce1;function DI($){return $.botToken!==void 0?$.botToken:$.userToken}function qN6($){let{context:Y,client:Q,body:{callback_id:X,trigger_id:z}}=$,Z=DI(Y);return(K)=>Q.views.open({token:Z,trigger_id:z,view:{callback_id:X,type:"workflow_step",...K}})}function DN6($){let{context:Y,client:Q,body:{workflow_step:{workflow_step_edit_id:X}}}=$,z=DI(Y);return(Z={})=>Q.workflows.updateStep({token:z,workflow_step_edit_id:X,...Z})}function FN6($){let{context:Y,client:Q,payload:{workflow_step:{workflow_step_execute_id:X}}}=$,z=DI(Y);return(Z={})=>Q.workflows.stepCompleted({token:z,workflow_step_execute_id:X,...Z})}function LN6($){let{context:Y,client:Q,payload:{workflow_step:{workflow_step_execute_id:X}}}=$,z=DI(Y);return(Z)=>{let{error:K}=Z;return Q.workflows.stepFailed({token:z,workflow_step_execute_id:X,error:K})}}function ye1($){let{next:Y,...Q}=$,X={...Q};switch(X.payload.type){case"workflow_step_edit":X.step=X.action.workflow_step,X.configure=qN6(X);break;case"workflow_step":X.step=X.body.workflow_step,X.update=DN6(X);break;case"workflow_step_execute":X.step=X.event.workflow_step,X.complete=FN6(X),X.fail=LN6(X);break;default:break}return X}a9.prepareStepArgs=ye1});var le1=x((Q0)=>{var ge1=Q0&&Q0.__createBinding||(Object.create?function($,Y,Q,X){if(X===void 0)X=Q;var z=Object.getOwnPropertyDescriptor(Y,Q);if(!z||("get"in z?!Y.__esModule:z.writable||z.configurable))z={enumerable:!0,get:function(){return Y[Q]}};Object.defineProperty($,X,z)}:function($,Y,Q,X){if(X===void 0)X=Q;$[X]=Y[Q]}),NN6=Q0&&Q0.__setModuleDefault||(Object.create?function($,Y){Object.defineProperty($,"default",{enumerable:!0,value:Y})}:function($,Y){$.default=Y}),Rl=Q0&&Q0.__importStar||function($){if($&&$.__esModule)return $;var Y={};if($!=null){for(var Q in $)if(Q!=="default"&&Object.prototype.hasOwnProperty.call($,Q))ge1(Y,$,Q)}return NN6(Y,$),Y},Tl=Q0&&Q0.__exportStar||function($,Y){for(var Q in $)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Y,Q))ge1(Y,$,Q)},xU=Q0&&Q0.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.webApi=Q0.types=Q0.FileInstallationStore=Q0.MemoryInstallationStore=Q0.WorkflowStep=Q0.Assistant=Q0.buildReceiverRoutes=Q0.MemoryStore=Q0.defaultProcessEventErrorHandler=Q0.HTTPResponseAck=Q0.HTTPModuleFunctions=Q0.AwsLambdaReceiver=Q0.HTTPReceiver=Q0.SocketModeReceiver=Q0.ExpressReceiver=Q0.isValidSlackRequest=Q0.verifySlackRequest=Q0.App=Q0.LogLevel=void 0;var me1=xU(ji());Q0.App=me1.default;var jN6=ji();Object.defineProperty(Q0,"LogLevel",{enumerable:!0,get:function(){return jN6.LogLevel}});Q0.default=me1.default;var pe1=Wi();Object.defineProperty(Q0,"verifySlackRequest",{enumerable:!0,get:function(){return pe1.verifySlackRequest}});Object.defineProperty(Q0,"isValidSlackRequest",{enumerable:!0,get:function(){return pe1.isValidSlackRequest}});var PN6=xU(Jo1());Q0.AwsLambdaReceiver=PN6.default;var IN6=xU(je1());Q0.ExpressReceiver=IN6.default;var MN6=xU(Hi());Q0.HTTPReceiver=MN6.default;var ON6=xU(Bi());Q0.SocketModeReceiver=ON6.default;Q0.HTTPModuleFunctions=Rl(pw());var vN6=kP();Object.defineProperty(Q0,"HTTPResponseAck",{enumerable:!0,get:function(){return vN6.HTTPResponseAck}});var bN6=xi();Object.defineProperty(Q0,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return bN6.defaultProcessEventErrorHandler}});Tl(P$(),Q0);Tl(Dj(),Q0);Tl(Di(),Q0);var AN6=ug();Object.defineProperty(Q0,"MemoryStore",{enumerable:!0,get:function(){return AN6.MemoryStore}});var _N6=SP();Object.defineProperty(Q0,"buildReceiverRoutes",{enumerable:!0,get:function(){return _N6.buildReceiverRoutes}});var RN6=_l();Object.defineProperty(Q0,"Assistant",{enumerable:!0,get:function(){return RN6.Assistant}});var TN6=he1();Object.defineProperty(Q0,"WorkflowStep",{enumerable:!0,get:function(){return TN6.WorkflowStep}});var ie1=fw();Object.defineProperty(Q0,"MemoryInstallationStore",{enumerable:!0,get:function(){return ie1.MemoryInstallationStore}});Object.defineProperty(Q0,"FileInstallationStore",{enumerable:!0,get:function(){return ie1.FileInstallationStore}});Q0.types=Rl(Og());Q0.webApi=Rl(qj())});import{homedir as KP6}from"os";var Zd={name:"@interactive-inc/claude-funnel",version:"0.39.0",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"},scripts:{prepack:"make build"},dependencies:{"@hono/zod-validator":"^0.8.0","@modelcontextprotocol/sdk":"^1.29.0","@slack/bolt":"^4.7.2","@slack/web-api":"^7.16.0","discord.js":"^14.26.4",hono:"^4.12.19",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@typescript/native-preview":"^7.0.0-dev.20260516.1","vite-plus":"^0.1.21"},engines:{bun:">=1.3.0"}};var W0=class extends Error{res;status;constructor($=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=$}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 N={};s7(N,{xor:()=>ua,xid:()=>Ka,void:()=>Ta,uuidv7:()=>td,uuidv6:()=>sd,uuidv4:()=>rd,uuid:()=>od,util:()=>D1,url:()=>ed,uppercase:()=>AK,unknown:()=>NZ,union:()=>VB,undefined:()=>_a,ulid:()=>Za,uint64:()=>ba,uint32:()=>Ma,tuple:()=>MA,trim:()=>fK,treeifyError:()=>BM,transform:()=>GB,toUpperCase:()=>CK,toLowerCase:()=>EK,toJSONSchema:()=>Ex,templateLiteral:()=>sa,symbol:()=>Aa,superRefine:()=>tA,success:()=>da,stringbool:()=>Zo,stringFormat:()=>Da,string:()=>zV,strictObject:()=>Ea,startsWith:()=>RK,slugify:()=>uK,size:()=>DZ,setErrorMap:()=>h$0,set:()=>ma,safeParseAsync:()=>tb,safeParse:()=>sb,safeEncodeAsync:()=>ZA,safeEncode:()=>XA,safeDecodeAsync:()=>KA,safeDecode:()=>zA,registry:()=>Kx,regexes:()=>t9,regex:()=>vK,refine:()=>sA,record:()=>OA,readonly:()=>lA,property:()=>Tx,promise:()=>ta,prettifyError:()=>qM,preprocess:()=>Wo,prefault:()=>uA,positive:()=>bx,pipe:()=>mx,partialRecord:()=>ya,parseAsync:()=>rb,parse:()=>ob,overwrite:()=>t7,optional:()=>KV,object:()=>fa,number:()=>VA,nullish:()=>na,nullable:()=>WV,null:()=>UA,normalize:()=>SK,nonpositive:()=>_x,nonoptional:()=>cA,nonnegative:()=>Rx,never:()=>WB,negative:()=>Ax,nativeEnum:()=>pa,nanoid:()=>Qa,nan:()=>aa,multipleOf:()=>CX,minSize:()=>uY,minLength:()=>AQ,mime:()=>kK,meta:()=>Xo,maxSize:()=>uX,maxLength:()=>FZ,map:()=>ga,mac:()=>Ha,lte:()=>e9,lt:()=>EY,lowercase:()=>bK,looseRecord:()=>ha,looseObject:()=>Ca,locales:()=>$V,literal:()=>ia,length:()=>LZ,lazy:()=>aA,ksuid:()=>Wa,keyof:()=>Sa,jwt:()=>qa,json:()=>Ko,iso:()=>hK,ipv6:()=>Ga,ipv4:()=>Va,invertCodec:()=>ra,intersection:()=>PA,int64:()=>va,int32:()=>Ia,int:()=>gx,instanceof:()=>zo,includes:()=>_K,httpUrl:()=>$a,hostname:()=>Fa,hex:()=>La,hash:()=>Na,guid:()=>ad,gte:()=>r$,gt:()=>CY,globalRegistry:()=>W$,getErrorMap:()=>g$0,function:()=>ea,fromJSONSchema:()=>Ho,formatError:()=>p2,float64:()=>Pa,float32:()=>ja,flattenError:()=>m2,file:()=>la,exactOptional:()=>kA,enum:()=>HB,endsWith:()=>TK,encodeAsync:()=>YA,encode:()=>eb,emoji:()=>Ya,email:()=>dd,e164:()=>Ba,discriminatedUnion:()=>ca,describe:()=>Qo,decodeAsync:()=>QA,decode:()=>$A,date:()=>ka,custom:()=>Yo,cuid2:()=>za,cuid:()=>Xa,core:()=>_Q,config:()=>K8,coerce:()=>$_,codec:()=>oa,clone:()=>a$,cidrv6:()=>wa,cidrv4:()=>Ja,check:()=>$o,catch:()=>gA,boolean:()=>HA,bigint:()=>Oa,base64url:()=>xa,base64:()=>Ua,array:()=>JV,any:()=>Ra,_function:()=>ea,_default:()=>EA,_ZodString:()=>px,ZodXor:()=>LA,ZodXID:()=>rx,ZodVoid:()=>DA,ZodUnknown:()=>BA,ZodUnion:()=>UV,ZodUndefined:()=>JA,ZodUUID:()=>cY,ZodURL:()=>HV,ZodULID:()=>ox,ZodType:()=>N0,ZodTuple:()=>IA,ZodTransform:()=>RA,ZodTemplateLiteral:()=>nA,ZodSymbol:()=>GA,ZodSuccess:()=>yA,ZodStringFormat:()=>G6,ZodString:()=>pK,ZodSet:()=>bA,ZodRecord:()=>gK,ZodRealError:()=>O9,ZodReadonly:()=>iA,ZodPromise:()=>oA,ZodPreprocess:()=>pA,ZodPrefault:()=>CA,ZodPipe:()=>xV,ZodOptional:()=>JB,ZodObject:()=>wV,ZodNumberFormat:()=>jZ,ZodNumber:()=>lK,ZodNullable:()=>SA,ZodNull:()=>wA,ZodNonOptional:()=>wB,ZodNever:()=>qA,ZodNanoID:()=>nx,ZodNaN:()=>mA,ZodMap:()=>vA,ZodMAC:()=>WA,ZodLiteral:()=>AA,ZodLazy:()=>dA,ZodKSUID:()=>sx,ZodJWT:()=>ZB,ZodIssueCode:()=>y$0,ZodIntersection:()=>jA,ZodISOTime:()=>yx,ZodISODuration:()=>hx,ZodISODateTime:()=>ux,ZodISODate:()=>cx,ZodIPv6:()=>ex,ZodIPv4:()=>tx,ZodGUID:()=>ZV,ZodFunction:()=>rA,ZodFirstPartyTypeKind:()=>eA,ZodFile:()=>_A,ZodExactOptional:()=>TA,ZodError:()=>u$0,ZodEnum:()=>mK,ZodEmoji:()=>lx,ZodEmail:()=>ix,ZodE164:()=>zB,ZodDiscriminatedUnion:()=>NA,ZodDefault:()=>fA,ZodDate:()=>GV,ZodCustomStringFormat:()=>iK,ZodCustom:()=>qV,ZodCodec:()=>BV,ZodCatch:()=>hA,ZodCUID2:()=>ax,ZodCUID:()=>dx,ZodCIDRv6:()=>YB,ZodCIDRv4:()=>$B,ZodBoolean:()=>nK,ZodBigIntFormat:()=>KB,ZodBigInt:()=>dK,ZodBase64URL:()=>XB,ZodBase64:()=>QB,ZodArray:()=>FA,ZodAny:()=>xA,TimePrecision:()=>Mv,NEVER:()=>XM,$output:()=>Fv,$input:()=>Lv,$brand:()=>zM});var _Q={};s7(_Q,{version:()=>w3,util:()=>D1,treeifyError:()=>BM,toJSONSchema:()=>Ex,toDotPath:()=>wd,safeParseAsync:()=>FM,safeParse:()=>DM,safeEncodeAsync:()=>y60,safeEncode:()=>u60,safeDecodeAsync:()=>h60,safeDecode:()=>c60,registry:()=>Kx,regexes:()=>t9,process:()=>K6,prettifyError:()=>qM,parseAsync:()=>cU,parse:()=>uU,meta:()=>zb,locales:()=>$V,isValidJWT:()=>fd,isValidBase64URL:()=>Sd,isValidBase64:()=>f3,initializeContext:()=>cX,globalRegistry:()=>W$,globalConfig:()=>wZ,formatError:()=>p2,flattenError:()=>m2,finalize:()=>hX,extractDefs:()=>yX,encodeAsync:()=>E60,encode:()=>S60,describe:()=>Xb,decodeAsync:()=>C60,decode:()=>f60,createToJSONSchemaMethod:()=>Kb,createStandardJSONSchemaMethod:()=>yK,config:()=>K8,clone:()=>a$,_xor:()=>U$0,_xid:()=>Dx,_void:()=>av,_uuidv7:()=>Jx,_uuidv6:()=>Gx,_uuidv4:()=>Hx,_uuid:()=>Vx,_url:()=>QV,_uppercase:()=>AK,_unknown:()=>nv,_union:()=>w$0,_undefined:()=>pv,_ulid:()=>qx,_uint64:()=>gv,_uint32:()=>Ev,_tuple:()=>q$0,_trim:()=>fK,_transform:()=>I$0,_toUpperCase:()=>CK,_toLowerCase:()=>EK,_templateLiteral:()=>k$0,_symbol:()=>mv,_superRefine:()=>Qb,_success:()=>A$0,_stringbool:()=>Zb,_stringFormat:()=>cK,_string:()=>jv,_startsWith:()=>RK,_slugify:()=>uK,_size:()=>DZ,_set:()=>L$0,_safeParseAsync:()=>IK,_safeParse:()=>PK,_safeEncodeAsync:()=>lU,_safeEncode:()=>pU,_safeDecodeAsync:()=>nU,_safeDecode:()=>iU,_regex:()=>vK,_refine:()=>Yb,_record:()=>D$0,_readonly:()=>T$0,_property:()=>Tx,_promise:()=>f$0,_positive:()=>bx,_pipe:()=>R$0,_parseAsync:()=>jK,_parse:()=>NK,_overwrite:()=>t7,_optional:()=>M$0,_number:()=>_v,_nullable:()=>O$0,_null:()=>iv,_normalize:()=>SK,_nonpositive:()=>_x,_nonoptional:()=>b$0,_nonnegative:()=>Rx,_never:()=>dv,_negative:()=>Ax,_nativeEnum:()=>j$0,_nanoid:()=>Ux,_nan:()=>sv,_multipleOf:()=>CX,_minSize:()=>uY,_minLength:()=>AQ,_min:()=>r$,_mime:()=>kK,_maxSize:()=>uX,_maxLength:()=>FZ,_max:()=>e9,_map:()=>F$0,_mac:()=>Iv,_lte:()=>e9,_lt:()=>EY,_lowercase:()=>bK,_literal:()=>P$0,_length:()=>LZ,_lazy:()=>S$0,_ksuid:()=>Fx,_jwt:()=>vx,_isoTime:()=>bv,_isoDuration:()=>Av,_isoDateTime:()=>Ov,_isoDate:()=>vv,_ipv6:()=>Nx,_ipv4:()=>Lx,_intersection:()=>B$0,_int64:()=>hv,_int32:()=>fv,_int:()=>Tv,_includes:()=>_K,_guid:()=>YV,_gte:()=>r$,_gt:()=>CY,_float64:()=>Sv,_float32:()=>kv,_file:()=>ev,_enum:()=>N$0,_endsWith:()=>TK,_encodeAsync:()=>gU,_encode:()=>yU,_emoji:()=>wx,_email:()=>Wx,_e164:()=>Ox,_discriminatedUnion:()=>x$0,_default:()=>v$0,_decodeAsync:()=>mU,_decode:()=>hU,_date:()=>ov,_custom:()=>$b,_cuid2:()=>Bx,_cuid:()=>xx,_coercedString:()=>Pv,_coercedNumber:()=>Rv,_coercedDate:()=>rv,_coercedBoolean:()=>uv,_coercedBigint:()=>yv,_cidrv6:()=>Px,_cidrv4:()=>jx,_check:()=>pd,_catch:()=>_$0,_boolean:()=>Cv,_bigint:()=>cv,_base64url:()=>Mx,_base64:()=>Ix,_array:()=>tv,_any:()=>lv,TimePrecision:()=>Mv,NEVER:()=>XM,JSONSchemaGenerator:()=>ib,JSONSchema:()=>id,Doc:()=>rU,$output:()=>Fv,$input:()=>Lv,$constructor:()=>y,$brand:()=>zM,$ZodXor:()=>t3,$ZodXID:()=>I3,$ZodVoid:()=>a3,$ZodUnknown:()=>n3,$ZodUnion:()=>a2,$ZodUndefined:()=>p3,$ZodUUID:()=>B3,$ZodURL:()=>D3,$ZodULID:()=>P3,$ZodType:()=>w0,$ZodTuple:()=>Xx,$ZodTransform:()=>WO,$ZodTemplateLiteral:()=>FO,$ZodSymbol:()=>m3,$ZodSuccess:()=>UO,$ZodStringFormat:()=>H6,$ZodString:()=>qZ,$ZodSet:()=>XO,$ZodRegistry:()=>Nv,$ZodRecord:()=>YO,$ZodRealError:()=>M9,$ZodReadonly:()=>DO,$ZodPromise:()=>NO,$ZodPreprocess:()=>qO,$ZodPrefault:()=>JO,$ZodPipe:()=>Zx,$ZodOptional:()=>zx,$ZodObjectJIT:()=>s3,$ZodObject:()=>ud,$ZodNumberFormat:()=>h3,$ZodNumber:()=>Yx,$ZodNullable:()=>HO,$ZodNull:()=>i3,$ZodNonOptional:()=>wO,$ZodNever:()=>d3,$ZodNanoID:()=>L3,$ZodNaN:()=>BO,$ZodMap:()=>QO,$ZodMAC:()=>T3,$ZodLiteral:()=>ZO,$ZodLazy:()=>jO,$ZodKSUID:()=>M3,$ZodJWT:()=>c3,$ZodIntersection:()=>$O,$ZodISOTime:()=>b3,$ZodISODuration:()=>A3,$ZodISODateTime:()=>O3,$ZodISODate:()=>v3,$ZodIPv6:()=>R3,$ZodIPv4:()=>_3,$ZodGUID:()=>x3,$ZodFunction:()=>LO,$ZodFile:()=>KO,$ZodExactOptional:()=>VO,$ZodError:()=>g2,$ZodEnum:()=>zO,$ZodEncodeError:()=>UZ,$ZodEmoji:()=>F3,$ZodEmail:()=>q3,$ZodE164:()=>u3,$ZodDiscriminatedUnion:()=>e3,$ZodDefault:()=>GO,$ZodDate:()=>o3,$ZodCustomStringFormat:()=>y3,$ZodCustom:()=>PO,$ZodCodec:()=>o2,$ZodCheckUpperCase:()=>Z3,$ZodCheckStringFormat:()=>MK,$ZodCheckStartsWith:()=>W3,$ZodCheckSizeEquals:()=>eM,$ZodCheckRegex:()=>X3,$ZodCheckProperty:()=>H3,$ZodCheckOverwrite:()=>J3,$ZodCheckNumberFormat:()=>oM,$ZodCheckMultipleOf:()=>aM,$ZodCheckMinSize:()=>tM,$ZodCheckMinLength:()=>Y3,$ZodCheckMimeType:()=>G3,$ZodCheckMaxSize:()=>sM,$ZodCheckMaxLength:()=>$3,$ZodCheckLowerCase:()=>z3,$ZodCheckLessThan:()=>aU,$ZodCheckLengthEquals:()=>Q3,$ZodCheckIncludes:()=>K3,$ZodCheckGreaterThan:()=>oU,$ZodCheckEndsWith:()=>V3,$ZodCheckBigIntFormat:()=>rM,$ZodCheck:()=>q6,$ZodCatch:()=>xO,$ZodCUID2:()=>j3,$ZodCUID:()=>N3,$ZodCIDRv6:()=>S3,$ZodCIDRv4:()=>k3,$ZodBoolean:()=>d2,$ZodBigIntFormat:()=>g3,$ZodBigInt:()=>Qx,$ZodBase64URL:()=>C3,$ZodBase64:()=>E3,$ZodAsyncError:()=>fY,$ZodArray:()=>r3,$ZodAny:()=>l3});var Kd,XM=Object.freeze({status:"aborted"});function y($,Y,Q){function X(W,V){if(!W._zod)Object.defineProperty(W,"_zod",{value:{def:V,constr:K,traits:new Set},enumerable:!1});if(W._zod.traits.has($))return;W._zod.traits.add($),Y(W,V);let H=K.prototype,G=Object.keys(H);for(let J=0;J<G.length;J++){let w=G[J];if(!(w in W))W[w]=H[w].bind(W)}}let z=Q?.Parent??Object;class Z extends z{}Object.defineProperty(Z,"name",{value:$});function K(W){var V;let H=Q?.Parent?new Z:this;X(H,W),(V=H._zod).deferred??(V.deferred=[]);for(let G of H._zod.deferred)G();return H}return Object.defineProperty(K,"init",{value:X}),Object.defineProperty(K,Symbol.hasInstance,{value:(W)=>{if(Q?.Parent&&W instanceof Q.Parent)return!0;return W?._zod?.traits?.has($)}}),Object.defineProperty(K,"name",{value:$}),K}var zM=Symbol("zod_brand");class fY extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class UZ extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}(Kd=globalThis).__zod_globalConfig??(Kd.__zod_globalConfig={});var wZ=globalThis.__zod_globalConfig;function K8($){if($)Object.assign(wZ,$);return wZ}var D1={};s7(D1,{unwrapMessage:()=>E2,uint8ArrayToHex:()=>T60,uint8ArrayToBase64url:()=>_60,uint8ArrayToBase64:()=>Hd,stringifyPrimitive:()=>U1,slugify:()=>WM,shallowClone:()=>HM,safeExtend:()=>I60,required:()=>v60,randomString:()=>q60,propertyKeyTypes:()=>c2,promiseAllObject:()=>B60,primitiveTypes:()=>GM,prefixIssues:()=>I9,pick:()=>N60,partial:()=>O60,parsedType:()=>q1,optionalKeys:()=>JM,omit:()=>j60,objectClone:()=>w60,numKeys:()=>D60,nullish:()=>kX,normalizeParams:()=>j1,mergeDefs:()=>bQ,merge:()=>M60,jsonStringifyReplacer:()=>DK,joinValues:()=>n,issue:()=>LK,isPlainObject:()=>fX,isObject:()=>xZ,hexToUint8Array:()=>R60,getSizableOrigin:()=>y2,getParsedType:()=>F60,getLengthableOrigin:()=>h2,getEnumValues:()=>C2,getElementAtPath:()=>x60,floatSafeRemainder:()=>KM,finalizeIssue:()=>o$,extend:()=>P60,explicitlyAborted:()=>xM,escapeRegex:()=>B7,esc:()=>EU,defineLazy:()=>A0,createTransparentProxy:()=>L60,cloneDef:()=>U60,clone:()=>a$,cleanRegex:()=>u2,cleanEnum:()=>b60,captureStackTrace:()=>CU,cached:()=>FK,base64urlToUint8Array:()=>A60,base64ToUint8Array:()=>Vd,assignProp:()=>SX,assertNotEqual:()=>V60,assertNever:()=>G60,assertIs:()=>H60,assertEqual:()=>W60,assert:()=>J60,allowsEval:()=>VM,aborted:()=>EX,NUMBER_FORMAT_RANGES:()=>wM,Class:()=>Gd,BIGINT_FORMAT_RANGES:()=>UM});function W60($){return $}function V60($){return $}function H60($){}function G60($){throw Error("Unexpected value in exhaustive check")}function J60($){}function C2($){let Y=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,z])=>Y.indexOf(+X)===-1).map(([X,z])=>z)}function n($,Y="|"){return $.map((Q)=>U1(Q)).join(Y)}function DK($,Y){if(typeof Y==="bigint")return Y.toString();return Y}function FK($){return{get value(){{let Q=$();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function kX($){return $===null||$===void 0}function u2($){let Y=$.startsWith("^")?1:0,Q=$.endsWith("$")?$.length-1:$.length;return $.slice(Y,Q)}function KM($,Y){let Q=$/Y,X=Math.round(Q),z=Number.EPSILON*Math.max(Math.abs(Q),1);if(Math.abs(Q-X)<z)return 0;return Q-X}var Wd=Symbol("evaluating");function A0($,Y,Q){let X=void 0;Object.defineProperty($,Y,{get(){if(X===Wd)return;if(X===void 0)X=Wd,X=Q();return X},set(z){Object.defineProperty($,Y,{value:z})},configurable:!0})}function w60($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function SX($,Y,Q){Object.defineProperty($,Y,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function bQ(...$){let Y={};for(let Q of $){let X=Object.getOwnPropertyDescriptors(Q);Object.assign(Y,X)}return Object.defineProperties({},Y)}function U60($){return bQ($._zod.def)}function x60($,Y){if(!Y)return $;return Y.reduce((Q,X)=>Q?.[X],$)}function B60($){let Y=Object.keys($),Q=Y.map((X)=>$[X]);return Promise.all(Q).then((X)=>{let z={};for(let Z=0;Z<Y.length;Z++)z[Y[Z]]=X[Z];return z})}function q60($=10){let Q="";for(let X=0;X<$;X++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function EU($){return JSON.stringify($)}function WM($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var CU="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function xZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var VM=FK(()=>{if(wZ.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function fX($){if(xZ($)===!1)return!1;let Y=$.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let Q=Y.prototype;if(xZ(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function HM($){if(fX($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function D60($){let Y=0;for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))Y++;return Y}var F60=($)=>{let Y=typeof $;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},c2=new Set(["string","number","symbol"]),GM=new Set(["string","number","bigint","boolean","symbol","undefined"]);function B7($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a$($,Y,Q){let X=new $._zod.constr(Y??$._zod.def);if(!Y||Q?.parent)X._zod.parent=$;return X}function j1($){let Y=$;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function L60($){let Y;return new Proxy({},{get(Q,X,z){return Y??(Y=$()),Reflect.get(Y,X,z)},set(Q,X,z,Z){return Y??(Y=$()),Reflect.set(Y,X,z,Z)},has(Q,X){return Y??(Y=$()),Reflect.has(Y,X)},deleteProperty(Q,X){return Y??(Y=$()),Reflect.deleteProperty(Y,X)},ownKeys(Q){return Y??(Y=$()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(Q,X){return Y??(Y=$()),Reflect.getOwnPropertyDescriptor(Y,X)},defineProperty(Q,X,z){return Y??(Y=$()),Reflect.defineProperty(Y,X,z)}})}function U1($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function JM($){return Object.keys($).filter((Y)=>{return $[Y]._zod.optin==="optional"&&$[Y]._zod.optout==="optional"})}var wM={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]},UM={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function N60($,Y){let Q=$._zod.def,X=Q.checks;if(X&&X.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let Z=bQ($._zod.def,{get shape(){let K={};for(let W in Y){if(!(W in Q.shape))throw Error(`Unrecognized key: "${W}"`);if(!Y[W])continue;K[W]=Q.shape[W]}return SX(this,"shape",K),K},checks:[]});return a$($,Z)}function j60($,Y){let Q=$._zod.def,X=Q.checks;if(X&&X.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let Z=bQ($._zod.def,{get shape(){let K={...$._zod.def.shape};for(let W in Y){if(!(W in Q.shape))throw Error(`Unrecognized key: "${W}"`);if(!Y[W])continue;delete K[W]}return SX(this,"shape",K),K},checks:[]});return a$($,Z)}function P60($,Y){if(!fX(Y))throw Error("Invalid input to extend: expected a plain object");let Q=$._zod.def.checks;if(Q&&Q.length>0){let Z=$._zod.def.shape;for(let K in Y)if(Object.getOwnPropertyDescriptor(Z,K)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let z=bQ($._zod.def,{get shape(){let Z={...$._zod.def.shape,...Y};return SX(this,"shape",Z),Z}});return a$($,z)}function I60($,Y){if(!fX(Y))throw Error("Invalid input to safeExtend: expected a plain object");let Q=bQ($._zod.def,{get shape(){let X={...$._zod.def.shape,...Y};return SX(this,"shape",X),X}});return a$($,Q)}function M60($,Y){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let Q=bQ($._zod.def,{get shape(){let X={...$._zod.def.shape,...Y._zod.def.shape};return SX(this,"shape",X),X},get catchall(){return Y._zod.def.catchall},checks:Y._zod.def.checks??[]});return a$($,Q)}function O60($,Y,Q){let z=Y._zod.def.checks;if(z&&z.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let K=bQ(Y._zod.def,{get shape(){let W=Y._zod.def.shape,V={...W};if(Q)for(let H in Q){if(!(H in W))throw Error(`Unrecognized key: "${H}"`);if(!Q[H])continue;V[H]=$?new $({type:"optional",innerType:W[H]}):W[H]}else for(let H in W)V[H]=$?new $({type:"optional",innerType:W[H]}):W[H];return SX(this,"shape",V),V},checks:[]});return a$(Y,K)}function v60($,Y,Q){let X=bQ(Y._zod.def,{get shape(){let z=Y._zod.def.shape,Z={...z};if(Q)for(let K in Q){if(!(K in Z))throw Error(`Unrecognized key: "${K}"`);if(!Q[K])continue;Z[K]=new $({type:"nonoptional",innerType:z[K]})}else for(let K in z)Z[K]=new $({type:"nonoptional",innerType:z[K]});return SX(this,"shape",Z),Z}});return a$(Y,X)}function EX($,Y=0){if($.aborted===!0)return!0;for(let Q=Y;Q<$.issues.length;Q++)if($.issues[Q]?.continue!==!0)return!0;return!1}function xM($,Y=0){if($.aborted===!0)return!0;for(let Q=Y;Q<$.issues.length;Q++)if($.issues[Q]?.continue===!1)return!0;return!1}function I9($,Y){return Y.map((Q)=>{var X;return(X=Q).path??(X.path=[]),Q.path.unshift($),Q})}function E2($){return typeof $==="string"?$:$?.message}function o$($,Y,Q){let X=$.message?$.message:E2($.inst?._zod.def?.error?.($))??E2(Y?.error?.($))??E2(Q.customError?.($))??E2(Q.localeError?.($))??"Invalid input",{inst:z,continue:Z,input:K,...W}=$;if(W.path??(W.path=[]),W.message=X,Y?.reportInput)W.input=K;return W}function y2($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function h2($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function q1($){let Y=typeof $;switch(Y){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let Q=$;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return Y}function LK(...$){let[Y,Q,X]=$;if(typeof Y==="string")return{message:Y,code:"custom",input:Q,inst:X};return{...Y}}function b60($){return Object.entries($).filter(([Y,Q])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function Vd($){let Y=atob($),Q=new Uint8Array(Y.length);for(let X=0;X<Y.length;X++)Q[X]=Y.charCodeAt(X);return Q}function Hd($){let Y="";for(let Q=0;Q<$.length;Q++)Y+=String.fromCharCode($[Q]);return btoa(Y)}function A60($){let Y=$.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-Y.length%4)%4);return Vd(Y+Q)}function _60($){return Hd($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function R60($){let Y=$.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(Y.length/2);for(let X=0;X<Y.length;X+=2)Q[X/2]=Number.parseInt(Y.slice(X,X+2),16);return Q}function T60($){return Array.from($).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class Gd{constructor(...$){}}var Jd=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,DK,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},g2=y("$ZodError",Jd),M9=y("$ZodError",Jd,{Parent:Error});function m2($,Y=(Q)=>Q.message){let Q={},X=[];for(let z of $.issues)if(z.path.length>0)Q[z.path[0]]=Q[z.path[0]]||[],Q[z.path[0]].push(Y(z));else X.push(Y(z));return{formErrors:X,fieldErrors:Q}}function p2($,Y=(Q)=>Q.message){let Q={_errors:[]},X=(z,Z=[])=>{for(let K of z.issues)if(K.code==="invalid_union"&&K.errors.length)K.errors.map((W)=>X({issues:W},[...Z,...K.path]));else if(K.code==="invalid_key")X({issues:K.issues},[...Z,...K.path]);else if(K.code==="invalid_element")X({issues:K.issues},[...Z,...K.path]);else{let W=[...Z,...K.path];if(W.length===0)Q._errors.push(Y(K));else{let V=Q,H=0;while(H<W.length){let G=W[H];if(H!==W.length-1)V[G]=V[G]||{_errors:[]};else V[G]=V[G]||{_errors:[]},V[G]._errors.push(Y(K));V=V[G],H++}}}};return X($),Q}function BM($,Y=(Q)=>Q.message){let Q={errors:[]},X=(z,Z=[])=>{var K,W;for(let V of z.issues)if(V.code==="invalid_union"&&V.errors.length)V.errors.map((H)=>X({issues:H},[...Z,...V.path]));else if(V.code==="invalid_key")X({issues:V.issues},[...Z,...V.path]);else if(V.code==="invalid_element")X({issues:V.issues},[...Z,...V.path]);else{let H=[...Z,...V.path];if(H.length===0){Q.errors.push(Y(V));continue}let G=Q,J=0;while(J<H.length){let w=H[J],U=J===H.length-1;if(typeof w==="string")G.properties??(G.properties={}),(K=G.properties)[w]??(K[w]={errors:[]}),G=G.properties[w];else G.items??(G.items=[]),(W=G.items)[w]??(W[w]={errors:[]}),G=G.items[w];if(U)G.errors.push(Y(V));J++}}};return X($),Q}function wd($){let Y=[],Q=$.map((X)=>typeof X==="object"?X.key:X);for(let X of Q)if(typeof X==="number")Y.push(`[${X}]`);else if(typeof X==="symbol")Y.push(`[${JSON.stringify(String(X))}]`);else if(/[^\w$]/.test(X))Y.push(`[${JSON.stringify(X)}]`);else{if(Y.length)Y.push(".");Y.push(X)}return Y.join("")}function qM($){let Y=[],Q=[...$.issues].sort((X,z)=>(X.path??[]).length-(z.path??[]).length);for(let X of Q)if(Y.push(`\u2716 ${X.message}`),X.path?.length)Y.push(` \u2192 at ${wd(X.path)}`);return Y.join(`
|
|
484
|
+
*/var UI=pr1(),hL6=v("events").EventEmitter,Ze1=lr1(),Ke1=as1(),We1=Vl(),Ve1=It1(),He1=Qe1();i7=Ge1.exports=gL6;function gL6(){var $=function(Y,Q,X){$.handle(Y,Q,X)};return Ze1($,hL6.prototype,!1),Ze1($,Ke1,!1),$.request=Object.create(Ve1,{app:{configurable:!0,enumerable:!0,writable:!0,value:$}}),$.response=Object.create(He1,{app:{configurable:!0,enumerable:!0,writable:!0,value:$}}),$.init(),$}i7.application=Ke1;i7.request=Ve1;i7.response=He1;i7.Route=We1.Route;i7.Router=We1;i7.json=UI.json;i7.raw=UI.raw;i7.static=ze1();i7.text=UI.text;i7.urlencoded=UI.urlencoded});var je1=x((Q8)=>{var mL6=Q8&&Q8.__createBinding||(Object.create?function($,Y,Q,X){if(X===void 0)X=Q;var z=Object.getOwnPropertyDescriptor(Y,Q);if(!z||("get"in z?!Y.__esModule:z.writable||z.configurable))z={enumerable:!0,get:function(){return Y[Q]}};Object.defineProperty($,X,z)}:function($,Y,Q,X){if(X===void 0)X=Q;$[X]=Y[Q]}),pL6=Q8&&Q8.__setModuleDefault||(Object.create?function($,Y){Object.defineProperty($,"default",{enumerable:!0,value:Y})}:function($,Y){$.default=Y}),xe1=Q8&&Q8.__importStar||function($){if($&&$.__esModule)return $;var Y={};if($!=null){for(var Q in $)if(Q!=="default"&&Object.prototype.hasOwnProperty.call($,Q))mL6(Y,$,Q)}return pL6(Y,$),Y},xI=Q8&&Q8.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(Q8,"__esModule",{value:!0});Q8.buildBodyParserMiddleware=Q8.verifySignatureAndParseBody=Q8.verifySignatureAndParseRawBody=Q8.respondToUrlVerification=Q8.respondToSslCheck=void 0;var iL6=xI(v("crypto")),lL6=v("http"),nL6=v("https"),dL6=xI(v("querystring")),we1=L$(),aL6=fw(),Ue1=xe1(Je1()),oL6=xI(_P()),rL6=xI(RP()),qQ=P$(),v2=xe1(pw()),sL6=kP(),tL6=fP(),eL6=["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"],bl="The receiver cannot be started because private state was mutated. Please report this to the maintainers.",$N6=($,Y,Q)=>{if($.body?.ssl_check){Y.send();return}Q()};Q8.respondToSslCheck=$N6;var YN6=($,Y,Q)=>{if($.body?.type&&$.body.type==="url_verification"){Y.json({challenge:$.body.challenge});return}Q()};Q8.respondToUrlVerification=YN6;class Be1{app;server;bolt;logger;processBeforeResponse;signatureVerification;router;installer=void 0;installerOptions;customPropertiesExtractor;dispatchErrorHandler;processEventErrorHandler;unhandledRequestHandler;unhandledRequestTimeoutMillis;constructor({signingSecret:$="",logger:Y=void 0,logLevel:Q=we1.LogLevel.INFO,endpoints:X={events:"/slack/events"},processBeforeResponse:z=!1,signatureVerification:Z=!0,clientId:K=void 0,clientSecret:W=void 0,stateSecret:V=void 0,redirectUri:H=void 0,installationStore:G=void 0,scopes:J=void 0,installerOptions:w={},app:U=void 0,router:B=void 0,customPropertiesExtractor:D=(I)=>({}),dispatchErrorHandler:q=v2.defaultAsyncDispatchErrorHandler,processEventErrorHandler:F=v2.defaultProcessEventErrorHandler,unhandledRequestHandler:P=v2.defaultUnhandledRequestHandler,unhandledRequestTimeoutMillis:L=3001}){if(this.app=U!==void 0?U:(0,Ue1.default)(),typeof Y<"u")this.logger=Y;else this.logger=new we1.ConsoleLogger,this.logger.setLevel(Q);this.signatureVerification=Z;let O=[this.signatureVerification?qe1(this.logger,$):Fe1(this.logger),Q8.respondToSslCheck,Q8.respondToUrlVerification,this.requestHandler.bind(this)];this.processBeforeResponse=z;let m=typeof X==="string"?[X]:Object.values(X);this.router=B!==void 0?B:(0,Ue1.Router)();for(let H1 of m)this.router.post(H1,...O);if(this.customPropertiesExtractor=D,this.dispatchErrorHandler=q,this.processEventErrorHandler=F,this.unhandledRequestHandler=P,this.unhandledRequestTimeoutMillis=L,(0,tL6.verifyRedirectOpts)({redirectUri:H,redirectUriPath:w.redirectUriPath}),K!==void 0&&W!==void 0&&(w.stateVerification===!1||V!==void 0||w.stateStore!==void 0))this.installer=new aL6.InstallProvider({clientId:K,clientSecret:W,stateSecret:V,installationStore:G,logLevel:Q,logger:Y,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 V1={metadata:w.metadata,scopes:J??[],userScopes:w.userScopes,redirectUri:H};if(this.installer!==void 0){let{installer:H1}=this,p=w.redirectUriPath===void 0?"/slack/oauth_redirect":w.redirectUriPath,{callbackOptions:i,stateVerification:X1}=w;this.router.use(p,async(I1,O1)=>{try{if(X1===!1)await H1.handleCallback(I1,O1,i,V1);else await H1.handleCallback(I1,O1,i)}catch(S1){await this.dispatchErrorHandler({error:S1,logger:this.logger,request:I1,response:O1})}});let G1=w.installPath===void 0?"/slack/install":w.installPath,{installPathOptions:A1}=w;this.router.get(G1,async(I1,O1,S1)=>{try{try{await H1.handleInstallPath(I1,O1,A1,V1)}catch(f1){S1(f1)}}catch(f1){await this.dispatchErrorHandler({error:f1,logger:this.logger,request:I1,response:O1})}})}this.app.use(this.router)}async requestHandler($,Y){let Q=new sL6.HTTPResponseAck({logger:this.logger,processBeforeResponse:this.processBeforeResponse,unhandledRequestHandler:this.unhandledRequestHandler,unhandledRequestTimeoutMillis:this.unhandledRequestTimeoutMillis,httpRequest:$,httpRequestBody:$.body,httpResponse:Y}),X={body:$.body,ack:Q.bind(),retryNum:v2.extractRetryNumFromHTTPRequest($),retryReason:v2.extractRetryReasonFromHTTPRequest($),customProperties:this.customPropertiesExtractor($)};try{if(await this.bolt?.processEvent(X),Q.storedResponse!==void 0)v2.buildContentResponse(Y,Q.storedResponse),this.logger.debug("stored response sent")}catch(z){if(await this.processEventErrorHandler({error:z,logger:this.logger,request:$,response:Y,storedResponse:Q.storedResponse}))Q.ack()}}init($){this.bolt=$}start($,Y={}){let Q=lL6.createServer;if(Object.keys(Y).filter((X)=>eL6.includes(X)).length>0)Q=nL6.createServer;if(this.server!==void 0)return Promise.reject(new qQ.ReceiverInconsistentStateError("The receiver cannot be started because it was already started."));return this.server=Q(Y,this.app),new Promise((X,z)=>{if(this.server===void 0)throw new qQ.ReceiverInconsistentStateError(bl);this.server.on("error",(Z)=>{if(this.server===void 0)throw new qQ.ReceiverInconsistentStateError(bl);this.server.close(),z(Z)}),this.server.on("close",()=>{this.server=void 0}),this.server.listen($,()=>{if(this.server===void 0)return z(new qQ.ReceiverInconsistentStateError(bl));return X(this.server)})})}stop(){if(this.server===void 0)return Promise.reject(new qQ.ReceiverInconsistentStateError("The receiver cannot be stopped because it was not started."));return new Promise(($,Y)=>{this.server?.close((Q)=>{if(Q!==void 0)return Y(Q);return this.server=void 0,$()})})}}Q8.default=Be1;function QN6($,Y){return qe1($,Y)}Q8.verifySignatureAndParseRawBody=QN6;function qe1($,Y){return async(Q,X,z)=>{let Z=await Ne1(Q);try{Q.body=De1(typeof Y==="string"?Y:await Y(),Z,Q.headers)}catch(K){if(K){if(K instanceof qQ.ReceiverAuthenticityError){Al($,"Request verification failed",K),X.status(401).send();return}Al($,"Parsing request body failed",K),X.status(400).send();return}}z()}}function Al($,Y,Q){let X="code"in Q?`${Y} (code: ${Q.code}, message: ${Q.message})`:`${Y} (error: ${Q})`;$.warn(X)}function XN6($,Y,Q,X){if(Q===void 0||X===void 0)throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Some headers are missing.");let z=Number(X);if(Number.isNaN(z))throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is invalid.");let Z=Math.floor(Date.now()/1000)-300;if(z<Z)throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Timestamp is too old.");let K=iL6.default.createHmac("sha256",$),[W,V]=Q.split("=");if(K.update(`${W}:${z}:${Y}`),!(0,rL6.default)(V,K.digest("hex")))throw new qQ.ReceiverAuthenticityError("Slack request signing verification failed. Signature mismatch.")}function De1($,Y,Q){let{"x-slack-signature":X,"x-slack-request-timestamp":z,"content-type":Z}=Q;return XN6($,Y,X,z),Le1(Y,Z)}Q8.verifySignatureAndParseBody=De1;function Fe1($){return async(Y,Q,X)=>{let z=await Ne1(Y);try{let{"content-type":Z}=Y.headers;Y.body=Le1(z,Z)}catch(Z){if(Z){Al($,"Parsing request body failed",Z),Q.status(400).send();return}}X()}}Q8.buildBodyParserMiddleware=Fe1;function Le1($,Y){if(Y==="application/x-www-form-urlencoded"){let Q=dL6.default.parse($);if(typeof Q.payload==="string")return JSON.parse(Q.payload);return Q}return JSON.parse($)}async function Ne1($){if("rawBody"in $&&$.rawBody)return Promise.resolve($.rawBody.toString());return(await(0,oL6.default)($)).toString()}});var ve1=x((Me1)=>{Object.defineProperty(Me1,"__esModule",{value:!0});Me1.DefaultThreadContextStore=void 0;var Pe1=_l();class Ie1{context={};async get($){let{context:Y,client:Q,payload:X,logger:z}=$;if(z.debug("DefaultAssistantThreadStore: get method called"),this.context.channel_id)return this.context;let{channelId:Z,threadTs:K}=(0,Pe1.extractThreadInfo)(X),W=await Q.conversations.replies({channel:Z,ts:K,oldest:K,include_all_metadata:!0,limit:4});if(!W.messages)return{};let V=W.messages.find((G)=>!("subtype"in G)&&G.user===Y.botUserId);return(V?.metadata?V.metadata.event_payload:null)||{}}async save($){let{context:Y,client:Q,payload:X,logger:z}=$,{channelId:Z,threadTs:K,context:W}=(0,Pe1.extractThreadInfo)(X);z.debug("DefaultAssistantThreadStore: save method called");let V=await Q.conversations.replies({channel:Z,ts:K,oldest:K,include_all_metadata:!0,limit:4});if(!V.messages)return;let H=V.messages.find((G)=>!("subtype"in G)&&G.user===Y.botUserId);if(H?.ts){let G={channel:Z,ts:H.ts,text:H.text,blocks:H.blocks?H.blocks:[],metadata:{event_type:"assistant_thread_context",event_payload:W}};await Q.chat.update(G)}this.context=W}}Me1.DefaultThreadContextStore=Ie1});var _l=x((u8)=>{var zN6=u8&&u8.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(u8,"__esModule",{value:!0});u8.extractThreadInfo=u8.processAssistantMiddleware=u8.validate=u8.isAssistantMessage=u8.matchesConstraints=u8.isAssistantEvent=u8.enrichAssistantArgs=u8.Assistant=void 0;var ZN6=ve1(),be1=Cg(),QK=P$(),BI=Fj(),KN6=zN6(Lj()),WN6=new Set(["assistant_thread_started","assistant_thread_context_changed","message"]);class Ae1{threadContextStore;threadStarted;threadContextChanged;userMessage;constructor($){Se1($);let{threadContextStore:Y=new ZN6.DefaultThreadContextStore,threadStarted:Q,threadContextChanged:X=(Z)=>Y.save(Z),userMessage:z}=$;this.threadContextStore=Y,this.threadStarted=Array.isArray(Q)?Q:[Q],this.threadContextChanged=Array.isArray(X)?X:[X],this.userMessage=Array.isArray(z)?z:[z]}getMiddleware(){return async($)=>{if(Re1($)&&Te1($))return this.processEvent($);return $.next()}}async processEvent($){let{payload:Y}=$,Q=_e1(this.threadContextStore,$),X=this.getAssistantMiddleware(Y);return fe1(Q,X)}getAssistantMiddleware($){switch($.type){case"assistant_thread_started":return this.threadStarted;case"assistant_thread_context_changed":return this.threadContextChanged;case"message":return this.userMessage;default:return[]}}}u8.Assistant=Ae1;function _e1($,Y){let{next:Q,...X}=Y,z={...X};return z.getThreadContext=()=>$.get(Y),z.saveThreadContext=()=>$.save(Y),z.say=VN6(z),z.sayStream=HN6(z),z.setStatus=GN6(z),z.setSuggestedPrompts=JN6(z),z.setTitle=wN6(z),z}u8.enrichAssistantArgs=_e1;function Re1($){return WN6.has($.payload.type)}u8.isAssistantEvent=Re1;function Te1($){return $.payload.type==="message"?ke1($.payload):!0}u8.matchesConstraints=Te1;function ke1($){let Y="channel"in $&&"thread_ts"in $,Q="channel_type"in $&&$.channel_type==="im"&&(!("subtype"in $)||$.subtype==="file_share"||$.subtype===void 0);return Y&&Q}u8.isAssistantMessage=ke1;function Se1($){if(typeof $!=="object")throw new QK.AssistantInitializationError("Assistant expects a configuration object as the argument");let Y=["threadStarted","userMessage"],Q=[];for(let z of Y)if($[z]===void 0)Q.push(z);if(Q.length>0){let z=`Assistant is missing required keys: ${Q.join(", ")}`;throw new QK.AssistantInitializationError(z)}let X=["threadStarted","userMessage"];if("threadContextChanged"in $)X.push("threadContextChanged");for(let z of X)if(typeof $[z]!=="function"&&!Array.isArray($[z])){let Z=`Assistant ${z} property must be a function or an array of functions`;throw new QK.AssistantInitializationError(Z)}if($.threadContextStore){if(typeof $.threadContextStore!=="object")throw new QK.AssistantInitializationError("Assistant expects threadContextStore to be a configuration object");let z=["get","save"],Z=[];for(let W of z)if($.threadContextStore&&$.threadContextStore[W]===void 0)Z.push(W);if(Z.length>0){let W=`threadContextStore is missing required keys: ${Z.join(", ")}`;throw new QK.AssistantInitializationError(W)}let K=["get","save"];for(let W of K)if($.threadContextStore&&typeof $.threadContextStore[W]!=="function"){let V=`threadContextStore ${W} property must be a function`;throw new QK.AssistantInitializationError(V)}}}u8.validate=Se1;async function fe1($,Y){let{context:Q,client:X,logger:z}=$,Z=[...Y],K=Z.pop();if(K!==void 0)await(0,KN6.default)(Z,$,Q,X,z,async()=>K({...$,context:Q,client:X,logger:z}))}u8.processAssistantMiddleware=fe1;function VN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z,context:Z}=b2(Q);return async(K)=>{let W=Z.channel_id?Z:await $.getThreadContext(),V=typeof K==="string"?{text:K,channel:X,thread_ts:z}:{...K,channel:X,thread_ts:z};if(W||V.metadata)V.metadata={event_type:V.metadata?.event_type??"assistant_thread_context",event_payload:{...W,...V.metadata?.event_payload??{}}};return Y.chat.postMessage(V)}}function HN6($){let{client:Y,context:Q,payload:X}=$,{channelId:z,threadTs:Z}=b2(X);return(0,be1.createSayStream)(Y,Q,z,Z)}function GN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z}=b2(Q);return(0,be1.createSetStatus)(Y,X,z)}function JN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z}=b2(Q);return(Z)=>{let{prompts:K,title:W}=Z;return Y.assistant.threads.setSuggestedPrompts({channel_id:X,thread_ts:z,prompts:K,title:W})}}function wN6($){let{client:Y,payload:Q}=$,{channelId:X,threadTs:z}=b2(Q);return(Z)=>Y.assistant.threads.setTitle({channel_id:X,thread_ts:z,title:Z})}function b2($){let Y={};if("assistant_thread"in $&&(0,BI.isRecord)($.assistant_thread)){if((0,BI.isRecord)($.assistant_thread.context))Y=$.assistant_thread.context}let Q=(0,BI.extractEventChannelId)($),X=(0,BI.extractEventThreadTs)($);if(!Q||!X){let z=[];if(!Q)z.push("channel_id");if(!X)z.push("thread_ts");throw new QK.AssistantMissingPropertyError(`Assistant message event is missing required properties: ${z.join(", ")}`)}return{channelId:Q,threadTs:X,context:Y}}u8.extractThreadInfo=b2});var he1=x((a9)=>{var UN6=a9&&a9.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(a9,"__esModule",{value:!0});a9.prepareStepArgs=a9.isStepEvent=a9.processStepMiddleware=a9.validate=a9.WorkflowStep=void 0;var qI=P$(),xN6=UN6(Lj()),BN6=new Set(["workflow_step_edit","workflow_step","workflow_step_execute"]);class Ee1{callbackId;edit;save;execute;constructor($,Y){Ce1($,Y);let{save:Q,edit:X,execute:z}=Y;this.callbackId=$,this.save=Array.isArray(Q)?Q:[Q],this.edit=Array.isArray(X)?X:[X],this.execute=Array.isArray(z)?z:[z]}getMiddleware(){return async($)=>{if(ce1($)&&this.matchesConstraints($))return this.processEvent($);return $.next()}}matchesConstraints($){return $.payload.callback_id===this.callbackId}async processEvent($){let{payload:Y}=$,Q=ye1($),X=this.getStepMiddleware(Y);return ue1(Q,X)}getStepMiddleware($){switch($.type){case"workflow_step_edit":return this.edit;case"workflow_step":return this.save;case"workflow_step_execute":return this.execute;default:return[]}}}a9.WorkflowStep=Ee1;function Ce1($,Y){if(typeof $!=="string")throw new qI.WorkflowStepInitializationError("WorkflowStep expects a callback_id as the first argument");if(typeof Y!=="object")throw new qI.WorkflowStepInitializationError("WorkflowStep expects a configuration object as the second argument");let Q=["save","edit","execute"],X=[];for(let Z of Q)if(Y[Z]===void 0)X.push(Z);if(X.length>0){let Z=`WorkflowStep is missing required keys: ${X.join(", ")}`;throw new qI.WorkflowStepInitializationError(Z)}let z=["save","edit","execute"];for(let Z of z)if(typeof Y[Z]!=="function"&&!Array.isArray(Y[Z])){let K=`WorkflowStep ${Z} property must be a function or an array of functions`;throw new qI.WorkflowStepInitializationError(K)}}a9.validate=Ce1;async function ue1($,Y){let{context:Q,client:X,logger:z}=$,Z=[...Y],K=Z.pop();if(K!==void 0)await(0,xN6.default)(Z,$,Q,X,z,async()=>K({...$,context:Q,client:X,logger:z}))}a9.processStepMiddleware=ue1;function ce1($){return BN6.has($.payload.type)}a9.isStepEvent=ce1;function DI($){return $.botToken!==void 0?$.botToken:$.userToken}function qN6($){let{context:Y,client:Q,body:{callback_id:X,trigger_id:z}}=$,Z=DI(Y);return(K)=>Q.views.open({token:Z,trigger_id:z,view:{callback_id:X,type:"workflow_step",...K}})}function DN6($){let{context:Y,client:Q,body:{workflow_step:{workflow_step_edit_id:X}}}=$,z=DI(Y);return(Z={})=>Q.workflows.updateStep({token:z,workflow_step_edit_id:X,...Z})}function FN6($){let{context:Y,client:Q,payload:{workflow_step:{workflow_step_execute_id:X}}}=$,z=DI(Y);return(Z={})=>Q.workflows.stepCompleted({token:z,workflow_step_execute_id:X,...Z})}function LN6($){let{context:Y,client:Q,payload:{workflow_step:{workflow_step_execute_id:X}}}=$,z=DI(Y);return(Z)=>{let{error:K}=Z;return Q.workflows.stepFailed({token:z,workflow_step_execute_id:X,error:K})}}function ye1($){let{next:Y,...Q}=$,X={...Q};switch(X.payload.type){case"workflow_step_edit":X.step=X.action.workflow_step,X.configure=qN6(X);break;case"workflow_step":X.step=X.body.workflow_step,X.update=DN6(X);break;case"workflow_step_execute":X.step=X.event.workflow_step,X.complete=FN6(X),X.fail=LN6(X);break;default:break}return X}a9.prepareStepArgs=ye1});var le1=x((Q0)=>{var ge1=Q0&&Q0.__createBinding||(Object.create?function($,Y,Q,X){if(X===void 0)X=Q;var z=Object.getOwnPropertyDescriptor(Y,Q);if(!z||("get"in z?!Y.__esModule:z.writable||z.configurable))z={enumerable:!0,get:function(){return Y[Q]}};Object.defineProperty($,X,z)}:function($,Y,Q,X){if(X===void 0)X=Q;$[X]=Y[Q]}),NN6=Q0&&Q0.__setModuleDefault||(Object.create?function($,Y){Object.defineProperty($,"default",{enumerable:!0,value:Y})}:function($,Y){$.default=Y}),Rl=Q0&&Q0.__importStar||function($){if($&&$.__esModule)return $;var Y={};if($!=null){for(var Q in $)if(Q!=="default"&&Object.prototype.hasOwnProperty.call($,Q))ge1(Y,$,Q)}return NN6(Y,$),Y},Tl=Q0&&Q0.__exportStar||function($,Y){for(var Q in $)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Y,Q))ge1(Y,$,Q)},xU=Q0&&Q0.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.webApi=Q0.types=Q0.FileInstallationStore=Q0.MemoryInstallationStore=Q0.WorkflowStep=Q0.Assistant=Q0.buildReceiverRoutes=Q0.MemoryStore=Q0.defaultProcessEventErrorHandler=Q0.HTTPResponseAck=Q0.HTTPModuleFunctions=Q0.AwsLambdaReceiver=Q0.HTTPReceiver=Q0.SocketModeReceiver=Q0.ExpressReceiver=Q0.isValidSlackRequest=Q0.verifySlackRequest=Q0.App=Q0.LogLevel=void 0;var me1=xU(ji());Q0.App=me1.default;var jN6=ji();Object.defineProperty(Q0,"LogLevel",{enumerable:!0,get:function(){return jN6.LogLevel}});Q0.default=me1.default;var pe1=Wi();Object.defineProperty(Q0,"verifySlackRequest",{enumerable:!0,get:function(){return pe1.verifySlackRequest}});Object.defineProperty(Q0,"isValidSlackRequest",{enumerable:!0,get:function(){return pe1.isValidSlackRequest}});var PN6=xU(Jo1());Q0.AwsLambdaReceiver=PN6.default;var IN6=xU(je1());Q0.ExpressReceiver=IN6.default;var MN6=xU(Hi());Q0.HTTPReceiver=MN6.default;var ON6=xU(Bi());Q0.SocketModeReceiver=ON6.default;Q0.HTTPModuleFunctions=Rl(pw());var vN6=kP();Object.defineProperty(Q0,"HTTPResponseAck",{enumerable:!0,get:function(){return vN6.HTTPResponseAck}});var bN6=xi();Object.defineProperty(Q0,"defaultProcessEventErrorHandler",{enumerable:!0,get:function(){return bN6.defaultProcessEventErrorHandler}});Tl(P$(),Q0);Tl(Dj(),Q0);Tl(Di(),Q0);var AN6=ug();Object.defineProperty(Q0,"MemoryStore",{enumerable:!0,get:function(){return AN6.MemoryStore}});var _N6=SP();Object.defineProperty(Q0,"buildReceiverRoutes",{enumerable:!0,get:function(){return _N6.buildReceiverRoutes}});var RN6=_l();Object.defineProperty(Q0,"Assistant",{enumerable:!0,get:function(){return RN6.Assistant}});var TN6=he1();Object.defineProperty(Q0,"WorkflowStep",{enumerable:!0,get:function(){return TN6.WorkflowStep}});var ie1=fw();Object.defineProperty(Q0,"MemoryInstallationStore",{enumerable:!0,get:function(){return ie1.MemoryInstallationStore}});Object.defineProperty(Q0,"FileInstallationStore",{enumerable:!0,get:function(){return ie1.FileInstallationStore}});Q0.types=Rl(Og());Q0.webApi=Rl(qj())});import{homedir as KP6}from"os";var Zd={name:"@interactive-inc/claude-funnel",version:"0.41.0",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"},scripts:{prepack:"make build"},dependencies:{"@hono/zod-validator":"^0.8.0","@modelcontextprotocol/sdk":"^1.29.0","@slack/bolt":"^4.7.2","@slack/web-api":"^7.16.0","discord.js":"^14.26.4",hono:"^4.12.19",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@typescript/native-preview":"^7.0.0-dev.20260516.1","vite-plus":"^0.1.21"},engines:{bun:">=1.3.0"}};var W0=class extends Error{res;status;constructor($=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=$}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 N={};s7(N,{xor:()=>ua,xid:()=>Ka,void:()=>Ta,uuidv7:()=>td,uuidv6:()=>sd,uuidv4:()=>rd,uuid:()=>od,util:()=>D1,url:()=>ed,uppercase:()=>AK,unknown:()=>NZ,union:()=>VB,undefined:()=>_a,ulid:()=>Za,uint64:()=>ba,uint32:()=>Ma,tuple:()=>MA,trim:()=>fK,treeifyError:()=>BM,transform:()=>GB,toUpperCase:()=>CK,toLowerCase:()=>EK,toJSONSchema:()=>Ex,templateLiteral:()=>sa,symbol:()=>Aa,superRefine:()=>tA,success:()=>da,stringbool:()=>Zo,stringFormat:()=>Da,string:()=>zV,strictObject:()=>Ea,startsWith:()=>RK,slugify:()=>uK,size:()=>DZ,setErrorMap:()=>h$0,set:()=>ma,safeParseAsync:()=>tb,safeParse:()=>sb,safeEncodeAsync:()=>ZA,safeEncode:()=>XA,safeDecodeAsync:()=>KA,safeDecode:()=>zA,registry:()=>Kx,regexes:()=>t9,regex:()=>vK,refine:()=>sA,record:()=>OA,readonly:()=>lA,property:()=>Tx,promise:()=>ta,prettifyError:()=>qM,preprocess:()=>Wo,prefault:()=>uA,positive:()=>bx,pipe:()=>mx,partialRecord:()=>ya,parseAsync:()=>rb,parse:()=>ob,overwrite:()=>t7,optional:()=>KV,object:()=>fa,number:()=>VA,nullish:()=>na,nullable:()=>WV,null:()=>UA,normalize:()=>SK,nonpositive:()=>_x,nonoptional:()=>cA,nonnegative:()=>Rx,never:()=>WB,negative:()=>Ax,nativeEnum:()=>pa,nanoid:()=>Qa,nan:()=>aa,multipleOf:()=>CX,minSize:()=>uY,minLength:()=>AQ,mime:()=>kK,meta:()=>Xo,maxSize:()=>uX,maxLength:()=>FZ,map:()=>ga,mac:()=>Ha,lte:()=>e9,lt:()=>EY,lowercase:()=>bK,looseRecord:()=>ha,looseObject:()=>Ca,locales:()=>$V,literal:()=>ia,length:()=>LZ,lazy:()=>aA,ksuid:()=>Wa,keyof:()=>Sa,jwt:()=>qa,json:()=>Ko,iso:()=>hK,ipv6:()=>Ga,ipv4:()=>Va,invertCodec:()=>ra,intersection:()=>PA,int64:()=>va,int32:()=>Ia,int:()=>gx,instanceof:()=>zo,includes:()=>_K,httpUrl:()=>$a,hostname:()=>Fa,hex:()=>La,hash:()=>Na,guid:()=>ad,gte:()=>r$,gt:()=>CY,globalRegistry:()=>W$,getErrorMap:()=>g$0,function:()=>ea,fromJSONSchema:()=>Ho,formatError:()=>p2,float64:()=>Pa,float32:()=>ja,flattenError:()=>m2,file:()=>la,exactOptional:()=>kA,enum:()=>HB,endsWith:()=>TK,encodeAsync:()=>YA,encode:()=>eb,emoji:()=>Ya,email:()=>dd,e164:()=>Ba,discriminatedUnion:()=>ca,describe:()=>Qo,decodeAsync:()=>QA,decode:()=>$A,date:()=>ka,custom:()=>Yo,cuid2:()=>za,cuid:()=>Xa,core:()=>_Q,config:()=>K8,coerce:()=>$_,codec:()=>oa,clone:()=>a$,cidrv6:()=>wa,cidrv4:()=>Ja,check:()=>$o,catch:()=>gA,boolean:()=>HA,bigint:()=>Oa,base64url:()=>xa,base64:()=>Ua,array:()=>JV,any:()=>Ra,_function:()=>ea,_default:()=>EA,_ZodString:()=>px,ZodXor:()=>LA,ZodXID:()=>rx,ZodVoid:()=>DA,ZodUnknown:()=>BA,ZodUnion:()=>UV,ZodUndefined:()=>JA,ZodUUID:()=>cY,ZodURL:()=>HV,ZodULID:()=>ox,ZodType:()=>N0,ZodTuple:()=>IA,ZodTransform:()=>RA,ZodTemplateLiteral:()=>nA,ZodSymbol:()=>GA,ZodSuccess:()=>yA,ZodStringFormat:()=>G6,ZodString:()=>pK,ZodSet:()=>bA,ZodRecord:()=>gK,ZodRealError:()=>O9,ZodReadonly:()=>iA,ZodPromise:()=>oA,ZodPreprocess:()=>pA,ZodPrefault:()=>CA,ZodPipe:()=>xV,ZodOptional:()=>JB,ZodObject:()=>wV,ZodNumberFormat:()=>jZ,ZodNumber:()=>lK,ZodNullable:()=>SA,ZodNull:()=>wA,ZodNonOptional:()=>wB,ZodNever:()=>qA,ZodNanoID:()=>nx,ZodNaN:()=>mA,ZodMap:()=>vA,ZodMAC:()=>WA,ZodLiteral:()=>AA,ZodLazy:()=>dA,ZodKSUID:()=>sx,ZodJWT:()=>ZB,ZodIssueCode:()=>y$0,ZodIntersection:()=>jA,ZodISOTime:()=>yx,ZodISODuration:()=>hx,ZodISODateTime:()=>ux,ZodISODate:()=>cx,ZodIPv6:()=>ex,ZodIPv4:()=>tx,ZodGUID:()=>ZV,ZodFunction:()=>rA,ZodFirstPartyTypeKind:()=>eA,ZodFile:()=>_A,ZodExactOptional:()=>TA,ZodError:()=>u$0,ZodEnum:()=>mK,ZodEmoji:()=>lx,ZodEmail:()=>ix,ZodE164:()=>zB,ZodDiscriminatedUnion:()=>NA,ZodDefault:()=>fA,ZodDate:()=>GV,ZodCustomStringFormat:()=>iK,ZodCustom:()=>qV,ZodCodec:()=>BV,ZodCatch:()=>hA,ZodCUID2:()=>ax,ZodCUID:()=>dx,ZodCIDRv6:()=>YB,ZodCIDRv4:()=>$B,ZodBoolean:()=>nK,ZodBigIntFormat:()=>KB,ZodBigInt:()=>dK,ZodBase64URL:()=>XB,ZodBase64:()=>QB,ZodArray:()=>FA,ZodAny:()=>xA,TimePrecision:()=>Mv,NEVER:()=>XM,$output:()=>Fv,$input:()=>Lv,$brand:()=>zM});var _Q={};s7(_Q,{version:()=>w3,util:()=>D1,treeifyError:()=>BM,toJSONSchema:()=>Ex,toDotPath:()=>wd,safeParseAsync:()=>FM,safeParse:()=>DM,safeEncodeAsync:()=>y60,safeEncode:()=>u60,safeDecodeAsync:()=>h60,safeDecode:()=>c60,registry:()=>Kx,regexes:()=>t9,process:()=>K6,prettifyError:()=>qM,parseAsync:()=>cU,parse:()=>uU,meta:()=>zb,locales:()=>$V,isValidJWT:()=>fd,isValidBase64URL:()=>Sd,isValidBase64:()=>f3,initializeContext:()=>cX,globalRegistry:()=>W$,globalConfig:()=>wZ,formatError:()=>p2,flattenError:()=>m2,finalize:()=>hX,extractDefs:()=>yX,encodeAsync:()=>E60,encode:()=>S60,describe:()=>Xb,decodeAsync:()=>C60,decode:()=>f60,createToJSONSchemaMethod:()=>Kb,createStandardJSONSchemaMethod:()=>yK,config:()=>K8,clone:()=>a$,_xor:()=>U$0,_xid:()=>Dx,_void:()=>av,_uuidv7:()=>Jx,_uuidv6:()=>Gx,_uuidv4:()=>Hx,_uuid:()=>Vx,_url:()=>QV,_uppercase:()=>AK,_unknown:()=>nv,_union:()=>w$0,_undefined:()=>pv,_ulid:()=>qx,_uint64:()=>gv,_uint32:()=>Ev,_tuple:()=>q$0,_trim:()=>fK,_transform:()=>I$0,_toUpperCase:()=>CK,_toLowerCase:()=>EK,_templateLiteral:()=>k$0,_symbol:()=>mv,_superRefine:()=>Qb,_success:()=>A$0,_stringbool:()=>Zb,_stringFormat:()=>cK,_string:()=>jv,_startsWith:()=>RK,_slugify:()=>uK,_size:()=>DZ,_set:()=>L$0,_safeParseAsync:()=>IK,_safeParse:()=>PK,_safeEncodeAsync:()=>lU,_safeEncode:()=>pU,_safeDecodeAsync:()=>nU,_safeDecode:()=>iU,_regex:()=>vK,_refine:()=>Yb,_record:()=>D$0,_readonly:()=>T$0,_property:()=>Tx,_promise:()=>f$0,_positive:()=>bx,_pipe:()=>R$0,_parseAsync:()=>jK,_parse:()=>NK,_overwrite:()=>t7,_optional:()=>M$0,_number:()=>_v,_nullable:()=>O$0,_null:()=>iv,_normalize:()=>SK,_nonpositive:()=>_x,_nonoptional:()=>b$0,_nonnegative:()=>Rx,_never:()=>dv,_negative:()=>Ax,_nativeEnum:()=>j$0,_nanoid:()=>Ux,_nan:()=>sv,_multipleOf:()=>CX,_minSize:()=>uY,_minLength:()=>AQ,_min:()=>r$,_mime:()=>kK,_maxSize:()=>uX,_maxLength:()=>FZ,_max:()=>e9,_map:()=>F$0,_mac:()=>Iv,_lte:()=>e9,_lt:()=>EY,_lowercase:()=>bK,_literal:()=>P$0,_length:()=>LZ,_lazy:()=>S$0,_ksuid:()=>Fx,_jwt:()=>vx,_isoTime:()=>bv,_isoDuration:()=>Av,_isoDateTime:()=>Ov,_isoDate:()=>vv,_ipv6:()=>Nx,_ipv4:()=>Lx,_intersection:()=>B$0,_int64:()=>hv,_int32:()=>fv,_int:()=>Tv,_includes:()=>_K,_guid:()=>YV,_gte:()=>r$,_gt:()=>CY,_float64:()=>Sv,_float32:()=>kv,_file:()=>ev,_enum:()=>N$0,_endsWith:()=>TK,_encodeAsync:()=>gU,_encode:()=>yU,_emoji:()=>wx,_email:()=>Wx,_e164:()=>Ox,_discriminatedUnion:()=>x$0,_default:()=>v$0,_decodeAsync:()=>mU,_decode:()=>hU,_date:()=>ov,_custom:()=>$b,_cuid2:()=>Bx,_cuid:()=>xx,_coercedString:()=>Pv,_coercedNumber:()=>Rv,_coercedDate:()=>rv,_coercedBoolean:()=>uv,_coercedBigint:()=>yv,_cidrv6:()=>Px,_cidrv4:()=>jx,_check:()=>pd,_catch:()=>_$0,_boolean:()=>Cv,_bigint:()=>cv,_base64url:()=>Mx,_base64:()=>Ix,_array:()=>tv,_any:()=>lv,TimePrecision:()=>Mv,NEVER:()=>XM,JSONSchemaGenerator:()=>ib,JSONSchema:()=>id,Doc:()=>rU,$output:()=>Fv,$input:()=>Lv,$constructor:()=>y,$brand:()=>zM,$ZodXor:()=>t3,$ZodXID:()=>I3,$ZodVoid:()=>a3,$ZodUnknown:()=>n3,$ZodUnion:()=>a2,$ZodUndefined:()=>p3,$ZodUUID:()=>B3,$ZodURL:()=>D3,$ZodULID:()=>P3,$ZodType:()=>w0,$ZodTuple:()=>Xx,$ZodTransform:()=>WO,$ZodTemplateLiteral:()=>FO,$ZodSymbol:()=>m3,$ZodSuccess:()=>UO,$ZodStringFormat:()=>H6,$ZodString:()=>qZ,$ZodSet:()=>XO,$ZodRegistry:()=>Nv,$ZodRecord:()=>YO,$ZodRealError:()=>M9,$ZodReadonly:()=>DO,$ZodPromise:()=>NO,$ZodPreprocess:()=>qO,$ZodPrefault:()=>JO,$ZodPipe:()=>Zx,$ZodOptional:()=>zx,$ZodObjectJIT:()=>s3,$ZodObject:()=>ud,$ZodNumberFormat:()=>h3,$ZodNumber:()=>Yx,$ZodNullable:()=>HO,$ZodNull:()=>i3,$ZodNonOptional:()=>wO,$ZodNever:()=>d3,$ZodNanoID:()=>L3,$ZodNaN:()=>BO,$ZodMap:()=>QO,$ZodMAC:()=>T3,$ZodLiteral:()=>ZO,$ZodLazy:()=>jO,$ZodKSUID:()=>M3,$ZodJWT:()=>c3,$ZodIntersection:()=>$O,$ZodISOTime:()=>b3,$ZodISODuration:()=>A3,$ZodISODateTime:()=>O3,$ZodISODate:()=>v3,$ZodIPv6:()=>R3,$ZodIPv4:()=>_3,$ZodGUID:()=>x3,$ZodFunction:()=>LO,$ZodFile:()=>KO,$ZodExactOptional:()=>VO,$ZodError:()=>g2,$ZodEnum:()=>zO,$ZodEncodeError:()=>UZ,$ZodEmoji:()=>F3,$ZodEmail:()=>q3,$ZodE164:()=>u3,$ZodDiscriminatedUnion:()=>e3,$ZodDefault:()=>GO,$ZodDate:()=>o3,$ZodCustomStringFormat:()=>y3,$ZodCustom:()=>PO,$ZodCodec:()=>o2,$ZodCheckUpperCase:()=>Z3,$ZodCheckStringFormat:()=>MK,$ZodCheckStartsWith:()=>W3,$ZodCheckSizeEquals:()=>eM,$ZodCheckRegex:()=>X3,$ZodCheckProperty:()=>H3,$ZodCheckOverwrite:()=>J3,$ZodCheckNumberFormat:()=>oM,$ZodCheckMultipleOf:()=>aM,$ZodCheckMinSize:()=>tM,$ZodCheckMinLength:()=>Y3,$ZodCheckMimeType:()=>G3,$ZodCheckMaxSize:()=>sM,$ZodCheckMaxLength:()=>$3,$ZodCheckLowerCase:()=>z3,$ZodCheckLessThan:()=>aU,$ZodCheckLengthEquals:()=>Q3,$ZodCheckIncludes:()=>K3,$ZodCheckGreaterThan:()=>oU,$ZodCheckEndsWith:()=>V3,$ZodCheckBigIntFormat:()=>rM,$ZodCheck:()=>q6,$ZodCatch:()=>xO,$ZodCUID2:()=>j3,$ZodCUID:()=>N3,$ZodCIDRv6:()=>S3,$ZodCIDRv4:()=>k3,$ZodBoolean:()=>d2,$ZodBigIntFormat:()=>g3,$ZodBigInt:()=>Qx,$ZodBase64URL:()=>C3,$ZodBase64:()=>E3,$ZodAsyncError:()=>fY,$ZodArray:()=>r3,$ZodAny:()=>l3});var Kd,XM=Object.freeze({status:"aborted"});function y($,Y,Q){function X(W,V){if(!W._zod)Object.defineProperty(W,"_zod",{value:{def:V,constr:K,traits:new Set},enumerable:!1});if(W._zod.traits.has($))return;W._zod.traits.add($),Y(W,V);let H=K.prototype,G=Object.keys(H);for(let J=0;J<G.length;J++){let w=G[J];if(!(w in W))W[w]=H[w].bind(W)}}let z=Q?.Parent??Object;class Z extends z{}Object.defineProperty(Z,"name",{value:$});function K(W){var V;let H=Q?.Parent?new Z:this;X(H,W),(V=H._zod).deferred??(V.deferred=[]);for(let G of H._zod.deferred)G();return H}return Object.defineProperty(K,"init",{value:X}),Object.defineProperty(K,Symbol.hasInstance,{value:(W)=>{if(Q?.Parent&&W instanceof Q.Parent)return!0;return W?._zod?.traits?.has($)}}),Object.defineProperty(K,"name",{value:$}),K}var zM=Symbol("zod_brand");class fY extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class UZ extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}(Kd=globalThis).__zod_globalConfig??(Kd.__zod_globalConfig={});var wZ=globalThis.__zod_globalConfig;function K8($){if($)Object.assign(wZ,$);return wZ}var D1={};s7(D1,{unwrapMessage:()=>E2,uint8ArrayToHex:()=>T60,uint8ArrayToBase64url:()=>_60,uint8ArrayToBase64:()=>Hd,stringifyPrimitive:()=>U1,slugify:()=>WM,shallowClone:()=>HM,safeExtend:()=>I60,required:()=>v60,randomString:()=>q60,propertyKeyTypes:()=>c2,promiseAllObject:()=>B60,primitiveTypes:()=>GM,prefixIssues:()=>I9,pick:()=>N60,partial:()=>O60,parsedType:()=>q1,optionalKeys:()=>JM,omit:()=>j60,objectClone:()=>w60,numKeys:()=>D60,nullish:()=>kX,normalizeParams:()=>j1,mergeDefs:()=>bQ,merge:()=>M60,jsonStringifyReplacer:()=>DK,joinValues:()=>n,issue:()=>LK,isPlainObject:()=>fX,isObject:()=>xZ,hexToUint8Array:()=>R60,getSizableOrigin:()=>y2,getParsedType:()=>F60,getLengthableOrigin:()=>h2,getEnumValues:()=>C2,getElementAtPath:()=>x60,floatSafeRemainder:()=>KM,finalizeIssue:()=>o$,extend:()=>P60,explicitlyAborted:()=>xM,escapeRegex:()=>B7,esc:()=>EU,defineLazy:()=>A0,createTransparentProxy:()=>L60,cloneDef:()=>U60,clone:()=>a$,cleanRegex:()=>u2,cleanEnum:()=>b60,captureStackTrace:()=>CU,cached:()=>FK,base64urlToUint8Array:()=>A60,base64ToUint8Array:()=>Vd,assignProp:()=>SX,assertNotEqual:()=>V60,assertNever:()=>G60,assertIs:()=>H60,assertEqual:()=>W60,assert:()=>J60,allowsEval:()=>VM,aborted:()=>EX,NUMBER_FORMAT_RANGES:()=>wM,Class:()=>Gd,BIGINT_FORMAT_RANGES:()=>UM});function W60($){return $}function V60($){return $}function H60($){}function G60($){throw Error("Unexpected value in exhaustive check")}function J60($){}function C2($){let Y=Object.values($).filter((X)=>typeof X==="number");return Object.entries($).filter(([X,z])=>Y.indexOf(+X)===-1).map(([X,z])=>z)}function n($,Y="|"){return $.map((Q)=>U1(Q)).join(Y)}function DK($,Y){if(typeof Y==="bigint")return Y.toString();return Y}function FK($){return{get value(){{let Q=$();return Object.defineProperty(this,"value",{value:Q}),Q}throw Error("cached value already set")}}}function kX($){return $===null||$===void 0}function u2($){let Y=$.startsWith("^")?1:0,Q=$.endsWith("$")?$.length-1:$.length;return $.slice(Y,Q)}function KM($,Y){let Q=$/Y,X=Math.round(Q),z=Number.EPSILON*Math.max(Math.abs(Q),1);if(Math.abs(Q-X)<z)return 0;return Q-X}var Wd=Symbol("evaluating");function A0($,Y,Q){let X=void 0;Object.defineProperty($,Y,{get(){if(X===Wd)return;if(X===void 0)X=Wd,X=Q();return X},set(z){Object.defineProperty($,Y,{value:z})},configurable:!0})}function w60($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function SX($,Y,Q){Object.defineProperty($,Y,{value:Q,writable:!0,enumerable:!0,configurable:!0})}function bQ(...$){let Y={};for(let Q of $){let X=Object.getOwnPropertyDescriptors(Q);Object.assign(Y,X)}return Object.defineProperties({},Y)}function U60($){return bQ($._zod.def)}function x60($,Y){if(!Y)return $;return Y.reduce((Q,X)=>Q?.[X],$)}function B60($){let Y=Object.keys($),Q=Y.map((X)=>$[X]);return Promise.all(Q).then((X)=>{let z={};for(let Z=0;Z<Y.length;Z++)z[Y[Z]]=X[Z];return z})}function q60($=10){let Q="";for(let X=0;X<$;X++)Q+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return Q}function EU($){return JSON.stringify($)}function WM($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var CU="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function xZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var VM=FK(()=>{if(wZ.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function fX($){if(xZ($)===!1)return!1;let Y=$.constructor;if(Y===void 0)return!0;if(typeof Y!=="function")return!0;let Q=Y.prototype;if(xZ(Q)===!1)return!1;if(Object.prototype.hasOwnProperty.call(Q,"isPrototypeOf")===!1)return!1;return!0}function HM($){if(fX($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function D60($){let Y=0;for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))Y++;return Y}var F60=($)=>{let Y=typeof $;switch(Y){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${Y}`)}},c2=new Set(["string","number","symbol"]),GM=new Set(["string","number","bigint","boolean","symbol","undefined"]);function B7($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a$($,Y,Q){let X=new $._zod.constr(Y??$._zod.def);if(!Y||Q?.parent)X._zod.parent=$;return X}function j1($){let Y=$;if(!Y)return{};if(typeof Y==="string")return{error:()=>Y};if(Y?.message!==void 0){if(Y?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");Y.error=Y.message}if(delete Y.message,typeof Y.error==="string")return{...Y,error:()=>Y.error};return Y}function L60($){let Y;return new Proxy({},{get(Q,X,z){return Y??(Y=$()),Reflect.get(Y,X,z)},set(Q,X,z,Z){return Y??(Y=$()),Reflect.set(Y,X,z,Z)},has(Q,X){return Y??(Y=$()),Reflect.has(Y,X)},deleteProperty(Q,X){return Y??(Y=$()),Reflect.deleteProperty(Y,X)},ownKeys(Q){return Y??(Y=$()),Reflect.ownKeys(Y)},getOwnPropertyDescriptor(Q,X){return Y??(Y=$()),Reflect.getOwnPropertyDescriptor(Y,X)},defineProperty(Q,X,z){return Y??(Y=$()),Reflect.defineProperty(Y,X,z)}})}function U1($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function JM($){return Object.keys($).filter((Y)=>{return $[Y]._zod.optin==="optional"&&$[Y]._zod.optout==="optional"})}var wM={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]},UM={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function N60($,Y){let Q=$._zod.def,X=Q.checks;if(X&&X.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let Z=bQ($._zod.def,{get shape(){let K={};for(let W in Y){if(!(W in Q.shape))throw Error(`Unrecognized key: "${W}"`);if(!Y[W])continue;K[W]=Q.shape[W]}return SX(this,"shape",K),K},checks:[]});return a$($,Z)}function j60($,Y){let Q=$._zod.def,X=Q.checks;if(X&&X.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let Z=bQ($._zod.def,{get shape(){let K={...$._zod.def.shape};for(let W in Y){if(!(W in Q.shape))throw Error(`Unrecognized key: "${W}"`);if(!Y[W])continue;delete K[W]}return SX(this,"shape",K),K},checks:[]});return a$($,Z)}function P60($,Y){if(!fX(Y))throw Error("Invalid input to extend: expected a plain object");let Q=$._zod.def.checks;if(Q&&Q.length>0){let Z=$._zod.def.shape;for(let K in Y)if(Object.getOwnPropertyDescriptor(Z,K)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let z=bQ($._zod.def,{get shape(){let Z={...$._zod.def.shape,...Y};return SX(this,"shape",Z),Z}});return a$($,z)}function I60($,Y){if(!fX(Y))throw Error("Invalid input to safeExtend: expected a plain object");let Q=bQ($._zod.def,{get shape(){let X={...$._zod.def.shape,...Y};return SX(this,"shape",X),X}});return a$($,Q)}function M60($,Y){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let Q=bQ($._zod.def,{get shape(){let X={...$._zod.def.shape,...Y._zod.def.shape};return SX(this,"shape",X),X},get catchall(){return Y._zod.def.catchall},checks:Y._zod.def.checks??[]});return a$($,Q)}function O60($,Y,Q){let z=Y._zod.def.checks;if(z&&z.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let K=bQ(Y._zod.def,{get shape(){let W=Y._zod.def.shape,V={...W};if(Q)for(let H in Q){if(!(H in W))throw Error(`Unrecognized key: "${H}"`);if(!Q[H])continue;V[H]=$?new $({type:"optional",innerType:W[H]}):W[H]}else for(let H in W)V[H]=$?new $({type:"optional",innerType:W[H]}):W[H];return SX(this,"shape",V),V},checks:[]});return a$(Y,K)}function v60($,Y,Q){let X=bQ(Y._zod.def,{get shape(){let z=Y._zod.def.shape,Z={...z};if(Q)for(let K in Q){if(!(K in Z))throw Error(`Unrecognized key: "${K}"`);if(!Q[K])continue;Z[K]=new $({type:"nonoptional",innerType:z[K]})}else for(let K in z)Z[K]=new $({type:"nonoptional",innerType:z[K]});return SX(this,"shape",Z),Z}});return a$(Y,X)}function EX($,Y=0){if($.aborted===!0)return!0;for(let Q=Y;Q<$.issues.length;Q++)if($.issues[Q]?.continue!==!0)return!0;return!1}function xM($,Y=0){if($.aborted===!0)return!0;for(let Q=Y;Q<$.issues.length;Q++)if($.issues[Q]?.continue===!1)return!0;return!1}function I9($,Y){return Y.map((Q)=>{var X;return(X=Q).path??(X.path=[]),Q.path.unshift($),Q})}function E2($){return typeof $==="string"?$:$?.message}function o$($,Y,Q){let X=$.message?$.message:E2($.inst?._zod.def?.error?.($))??E2(Y?.error?.($))??E2(Q.customError?.($))??E2(Q.localeError?.($))??"Invalid input",{inst:z,continue:Z,input:K,...W}=$;if(W.path??(W.path=[]),W.message=X,Y?.reportInput)W.input=K;return W}function y2($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function h2($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function q1($){let Y=typeof $;switch(Y){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let Q=$;if(Q&&Object.getPrototypeOf(Q)!==Object.prototype&&"constructor"in Q&&Q.constructor)return Q.constructor.name}}return Y}function LK(...$){let[Y,Q,X]=$;if(typeof Y==="string")return{message:Y,code:"custom",input:Q,inst:X};return{...Y}}function b60($){return Object.entries($).filter(([Y,Q])=>{return Number.isNaN(Number.parseInt(Y,10))}).map((Y)=>Y[1])}function Vd($){let Y=atob($),Q=new Uint8Array(Y.length);for(let X=0;X<Y.length;X++)Q[X]=Y.charCodeAt(X);return Q}function Hd($){let Y="";for(let Q=0;Q<$.length;Q++)Y+=String.fromCharCode($[Q]);return btoa(Y)}function A60($){let Y=$.replace(/-/g,"+").replace(/_/g,"/"),Q="=".repeat((4-Y.length%4)%4);return Vd(Y+Q)}function _60($){return Hd($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function R60($){let Y=$.replace(/^0x/,"");if(Y.length%2!==0)throw Error("Invalid hex string length");let Q=new Uint8Array(Y.length/2);for(let X=0;X<Y.length;X+=2)Q[X/2]=Number.parseInt(Y.slice(X,X+2),16);return Q}function T60($){return Array.from($).map((Y)=>Y.toString(16).padStart(2,"0")).join("")}class Gd{constructor(...$){}}var Jd=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,DK,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},g2=y("$ZodError",Jd),M9=y("$ZodError",Jd,{Parent:Error});function m2($,Y=(Q)=>Q.message){let Q={},X=[];for(let z of $.issues)if(z.path.length>0)Q[z.path[0]]=Q[z.path[0]]||[],Q[z.path[0]].push(Y(z));else X.push(Y(z));return{formErrors:X,fieldErrors:Q}}function p2($,Y=(Q)=>Q.message){let Q={_errors:[]},X=(z,Z=[])=>{for(let K of z.issues)if(K.code==="invalid_union"&&K.errors.length)K.errors.map((W)=>X({issues:W},[...Z,...K.path]));else if(K.code==="invalid_key")X({issues:K.issues},[...Z,...K.path]);else if(K.code==="invalid_element")X({issues:K.issues},[...Z,...K.path]);else{let W=[...Z,...K.path];if(W.length===0)Q._errors.push(Y(K));else{let V=Q,H=0;while(H<W.length){let G=W[H];if(H!==W.length-1)V[G]=V[G]||{_errors:[]};else V[G]=V[G]||{_errors:[]},V[G]._errors.push(Y(K));V=V[G],H++}}}};return X($),Q}function BM($,Y=(Q)=>Q.message){let Q={errors:[]},X=(z,Z=[])=>{var K,W;for(let V of z.issues)if(V.code==="invalid_union"&&V.errors.length)V.errors.map((H)=>X({issues:H},[...Z,...V.path]));else if(V.code==="invalid_key")X({issues:V.issues},[...Z,...V.path]);else if(V.code==="invalid_element")X({issues:V.issues},[...Z,...V.path]);else{let H=[...Z,...V.path];if(H.length===0){Q.errors.push(Y(V));continue}let G=Q,J=0;while(J<H.length){let w=H[J],U=J===H.length-1;if(typeof w==="string")G.properties??(G.properties={}),(K=G.properties)[w]??(K[w]={errors:[]}),G=G.properties[w];else G.items??(G.items=[]),(W=G.items)[w]??(W[w]={errors:[]}),G=G.items[w];if(U)G.errors.push(Y(V));J++}}};return X($),Q}function wd($){let Y=[],Q=$.map((X)=>typeof X==="object"?X.key:X);for(let X of Q)if(typeof X==="number")Y.push(`[${X}]`);else if(typeof X==="symbol")Y.push(`[${JSON.stringify(String(X))}]`);else if(/[^\w$]/.test(X))Y.push(`[${JSON.stringify(X)}]`);else{if(Y.length)Y.push(".");Y.push(X)}return Y.join("")}function qM($){let Y=[],Q=[...$.issues].sort((X,z)=>(X.path??[]).length-(z.path??[]).length);for(let X of Q)if(Y.push(`\u2716 ${X.message}`),X.path?.length)Y.push(` \u2192 at ${wd(X.path)}`);return Y.join(`
|
|
485
485
|
`)}var NK=($)=>(Y,Q,X,z)=>{let Z=X?{...X,async:!1}:{async:!1},K=Y._zod.run({value:Q,issues:[]},Z);if(K instanceof Promise)throw new fY;if(K.issues.length){let W=new(z?.Err??$)(K.issues.map((V)=>o$(V,Z,K8())));throw CU(W,z?.callee),W}return K.value},uU=NK(M9),jK=($)=>async(Y,Q,X,z)=>{let Z=X?{...X,async:!0}:{async:!0},K=Y._zod.run({value:Q,issues:[]},Z);if(K instanceof Promise)K=await K;if(K.issues.length){let W=new(z?.Err??$)(K.issues.map((V)=>o$(V,Z,K8())));throw CU(W,z?.callee),W}return K.value},cU=jK(M9),PK=($)=>(Y,Q,X)=>{let z=X?{...X,async:!1}:{async:!1},Z=Y._zod.run({value:Q,issues:[]},z);if(Z instanceof Promise)throw new fY;return Z.issues.length?{success:!1,error:new($??g2)(Z.issues.map((K)=>o$(K,z,K8())))}:{success:!0,data:Z.value}},DM=PK(M9),IK=($)=>async(Y,Q,X)=>{let z=X?{...X,async:!0}:{async:!0},Z=Y._zod.run({value:Q,issues:[]},z);if(Z instanceof Promise)Z=await Z;return Z.issues.length?{success:!1,error:new $(Z.issues.map((K)=>o$(K,z,K8())))}:{success:!0,data:Z.value}},FM=IK(M9),yU=($)=>(Y,Q,X)=>{let z=X?{...X,direction:"backward"}:{direction:"backward"};return NK($)(Y,Q,z)},S60=yU(M9),hU=($)=>(Y,Q,X)=>{return NK($)(Y,Q,X)},f60=hU(M9),gU=($)=>async(Y,Q,X)=>{let z=X?{...X,direction:"backward"}:{direction:"backward"};return jK($)(Y,Q,z)},E60=gU(M9),mU=($)=>async(Y,Q,X)=>{return jK($)(Y,Q,X)},C60=mU(M9),pU=($)=>(Y,Q,X)=>{let z=X?{...X,direction:"backward"}:{direction:"backward"};return PK($)(Y,Q,z)},u60=pU(M9),iU=($)=>(Y,Q,X)=>{return PK($)(Y,Q,X)},c60=iU(M9),lU=($)=>async(Y,Q,X)=>{let z=X?{...X,direction:"backward"}:{direction:"backward"};return IK($)(Y,Q,z)},y60=lU(M9),nU=($)=>async(Y,Q,X)=>{return IK($)(Y,Q,X)},h60=nU(M9);var t9={};s7(t9,{xid:()=>PM,uuid7:()=>i60,uuid6:()=>p60,uuid4:()=>m60,uuid:()=>BZ,uppercase:()=>dM,unicodeEmail:()=>Ud,undefined:()=>lM,ulid:()=>jM,time:()=>cM,string:()=>hM,sha512_hex:()=>J80,sha512_base64url:()=>U80,sha512_base64:()=>w80,sha384_hex:()=>V80,sha384_base64url:()=>G80,sha384_base64:()=>H80,sha256_hex:()=>Z80,sha256_base64url:()=>W80,sha256_base64:()=>K80,sha1_hex:()=>Q80,sha1_base64url:()=>z80,sha1_base64:()=>X80,rfc5322Email:()=>n60,number:()=>i2,null:()=>iM,nanoid:()=>MM,md5_hex:()=>e60,md5_base64url:()=>Y80,md5_base64:()=>$80,mac:()=>TM,lowercase:()=>nM,ksuid:()=>IM,ipv6:()=>RM,ipv4:()=>_M,integer:()=>mM,idnEmail:()=>d60,httpProtocol:()=>EM,html5Email:()=>l60,hostname:()=>r60,hex:()=>t60,guid:()=>vM,extendedDuration:()=>g60,emoji:()=>AM,email:()=>bM,e164:()=>CM,duration:()=>OM,domain:()=>s60,datetime:()=>yM,date:()=>uM,cuid2:()=>NM,cuid:()=>LM,cidrv6:()=>SM,cidrv4:()=>kM,browserEmail:()=>a60,boolean:()=>pM,bigint:()=>gM,base64url:()=>dU,base64:()=>fM});var LM=/^[cC][0-9a-z]{6,}$/,NM=/^[0-9a-z]+$/,jM=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,PM=/^[0-9a-vA-V]{20}$/,IM=/^[A-Za-z0-9]{27}$/,MM=/^[a-zA-Z0-9_-]{21}$/,OM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,g60=/^[-+]?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)?)??$/,vM=/^([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})$/,BZ=($)=>{if(!$)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}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},m60=BZ(4),p60=BZ(6),i60=BZ(7),bM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,l60=/^[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])?)*$/,n60=/^(([^<>()\[\]\\.,;:\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,}))$/,Ud=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,d60=Ud,a60=/^[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])?)*$/,o60="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function AM(){return new RegExp(o60,"u")}var _M=/^(?:(?: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])$/,RM=/^(([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}|:))$/,TM=($)=>{let Y=B7($??":");return new RegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},kM=/^((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])$/,SM=/^(([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])$/,fM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,dU=/^[A-Za-z0-9_-]*$/,r60=/^(?=.{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])?)*\.?$/,s60=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,EM=/^https?$/,CM=/^\+[1-9]\d{6,14}$/,xd="(?:(?:\\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])))",uM=new RegExp(`^${xd}$`);function Bd($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.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{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function cM($){return new RegExp(`^${Bd($)}$`)}function yM($){let Y=Bd({precision:$.precision}),Q=["Z"];if($.local)Q.push("");if($.offset)Q.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let X=`${Y}(?:${Q.join("|")})`;return new RegExp(`^${xd}T(?:${X})$`)}var hM=($)=>{let Y=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},gM=/^-?\d+n?$/,mM=/^-?\d+$/,i2=/^-?\d+(?:\.\d+)?$/,pM=/^(?:true|false)$/i,iM=/^null$/i;var lM=/^undefined$/i;var nM=/^[^A-Z]*$/,dM=/^[^a-z]*$/,t60=/^[0-9a-fA-F]*$/;function l2($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function n2($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var e60=/^[0-9a-fA-F]{32}$/,$80=l2(22,"=="),Y80=n2(22),Q80=/^[0-9a-fA-F]{40}$/,X80=l2(27,"="),z80=n2(27),Z80=/^[0-9a-fA-F]{64}$/,K80=l2(43,"="),W80=n2(43),V80=/^[0-9a-fA-F]{96}$/,H80=l2(64,""),G80=n2(64),J80=/^[0-9a-fA-F]{128}$/,w80=l2(86,"=="),U80=n2(86);var q6=y("$ZodCheck",($,Y)=>{var Q;$._zod??($._zod={}),$._zod.def=Y,(Q=$._zod).onattach??(Q.onattach=[])}),Dd={number:"number",bigint:"bigint",object:"date"},aU=y("$ZodCheckLessThan",($,Y)=>{q6.init($,Y);let Q=Dd[typeof Y.value];$._zod.onattach.push((X)=>{let z=X._zod.bag,Z=(Y.inclusive?z.maximum:z.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(Y.value<Z)if(Y.inclusive)z.maximum=Y.value;else z.exclusiveMaximum=Y.value}),$._zod.check=(X)=>{if(Y.inclusive?X.value<=Y.value:X.value<Y.value)return;X.issues.push({origin:Q,code:"too_big",maximum:typeof Y.value==="object"?Y.value.getTime():Y.value,input:X.value,inclusive:Y.inclusive,inst:$,continue:!Y.abort})}}),oU=y("$ZodCheckGreaterThan",($,Y)=>{q6.init($,Y);let Q=Dd[typeof Y.value];$._zod.onattach.push((X)=>{let z=X._zod.bag,Z=(Y.inclusive?z.minimum:z.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(Y.value>Z)if(Y.inclusive)z.minimum=Y.value;else z.exclusiveMinimum=Y.value}),$._zod.check=(X)=>{if(Y.inclusive?X.value>=Y.value:X.value>Y.value)return;X.issues.push({origin:Q,code:"too_small",minimum:typeof Y.value==="object"?Y.value.getTime():Y.value,input:X.value,inclusive:Y.inclusive,inst:$,continue:!Y.abort})}}),aM=y("$ZodCheckMultipleOf",($,Y)=>{q6.init($,Y),$._zod.onattach.push((Q)=>{var X;(X=Q._zod.bag).multipleOf??(X.multipleOf=Y.value)}),$._zod.check=(Q)=>{if(typeof Q.value!==typeof Y.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof Q.value==="bigint"?Q.value%Y.value===BigInt(0):KM(Q.value,Y.value)===0)return;Q.issues.push({origin:typeof Q.value,code:"not_multiple_of",divisor:Y.value,input:Q.value,inst:$,continue:!Y.abort})}}),oM=y("$ZodCheckNumberFormat",($,Y)=>{q6.init($,Y),Y.format=Y.format||"float64";let Q=Y.format?.includes("int"),X=Q?"int":"number",[z,Z]=wM[Y.format];$._zod.onattach.push((K)=>{let W=K._zod.bag;if(W.format=Y.format,W.minimum=z,W.maximum=Z,Q)W.pattern=mM}),$._zod.check=(K)=>{let W=K.value;if(Q){if(!Number.isInteger(W)){K.issues.push({expected:X,format:Y.format,code:"invalid_type",continue:!1,input:W,inst:$});return}if(!Number.isSafeInteger(W)){if(W>0)K.issues.push({input:W,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,inclusive:!0,continue:!Y.abort});else K.issues.push({input:W,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:X,inclusive:!0,continue:!Y.abort});return}}if(W<z)K.issues.push({origin:"number",input:W,code:"too_small",minimum:z,inclusive:!0,inst:$,continue:!Y.abort});if(W>Z)K.issues.push({origin:"number",input:W,code:"too_big",maximum:Z,inclusive:!0,inst:$,continue:!Y.abort})}}),rM=y("$ZodCheckBigIntFormat",($,Y)=>{q6.init($,Y);let[Q,X]=UM[Y.format];$._zod.onattach.push((z)=>{let Z=z._zod.bag;Z.format=Y.format,Z.minimum=Q,Z.maximum=X}),$._zod.check=(z)=>{let Z=z.value;if(Z<Q)z.issues.push({origin:"bigint",input:Z,code:"too_small",minimum:Q,inclusive:!0,inst:$,continue:!Y.abort});if(Z>X)z.issues.push({origin:"bigint",input:Z,code:"too_big",maximum:X,inclusive:!0,inst:$,continue:!Y.abort})}}),sM=y("$ZodCheckMaxSize",($,Y)=>{var Q;q6.init($,Y),(Q=$._zod.def).when??(Q.when=(X)=>{let z=X.value;return!kX(z)&&z.size!==void 0}),$._zod.onattach.push((X)=>{let z=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<z)X._zod.bag.maximum=Y.maximum}),$._zod.check=(X)=>{let z=X.value;if(z.size<=Y.maximum)return;X.issues.push({origin:y2(z),code:"too_big",maximum:Y.maximum,inclusive:!0,input:z,inst:$,continue:!Y.abort})}}),tM=y("$ZodCheckMinSize",($,Y)=>{var Q;q6.init($,Y),(Q=$._zod.def).when??(Q.when=(X)=>{let z=X.value;return!kX(z)&&z.size!==void 0}),$._zod.onattach.push((X)=>{let z=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>z)X._zod.bag.minimum=Y.minimum}),$._zod.check=(X)=>{let z=X.value;if(z.size>=Y.minimum)return;X.issues.push({origin:y2(z),code:"too_small",minimum:Y.minimum,inclusive:!0,input:z,inst:$,continue:!Y.abort})}}),eM=y("$ZodCheckSizeEquals",($,Y)=>{var Q;q6.init($,Y),(Q=$._zod.def).when??(Q.when=(X)=>{let z=X.value;return!kX(z)&&z.size!==void 0}),$._zod.onattach.push((X)=>{let z=X._zod.bag;z.minimum=Y.size,z.maximum=Y.size,z.size=Y.size}),$._zod.check=(X)=>{let z=X.value,Z=z.size;if(Z===Y.size)return;let K=Z>Y.size;X.issues.push({origin:y2(z),...K?{code:"too_big",maximum:Y.size}:{code:"too_small",minimum:Y.size},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!Y.abort})}}),$3=y("$ZodCheckMaxLength",($,Y)=>{var Q;q6.init($,Y),(Q=$._zod.def).when??(Q.when=(X)=>{let z=X.value;return!kX(z)&&z.length!==void 0}),$._zod.onattach.push((X)=>{let z=X._zod.bag.maximum??Number.POSITIVE_INFINITY;if(Y.maximum<z)X._zod.bag.maximum=Y.maximum}),$._zod.check=(X)=>{let z=X.value;if(z.length<=Y.maximum)return;let K=h2(z);X.issues.push({origin:K,code:"too_big",maximum:Y.maximum,inclusive:!0,input:z,inst:$,continue:!Y.abort})}}),Y3=y("$ZodCheckMinLength",($,Y)=>{var Q;q6.init($,Y),(Q=$._zod.def).when??(Q.when=(X)=>{let z=X.value;return!kX(z)&&z.length!==void 0}),$._zod.onattach.push((X)=>{let z=X._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(Y.minimum>z)X._zod.bag.minimum=Y.minimum}),$._zod.check=(X)=>{let z=X.value;if(z.length>=Y.minimum)return;let K=h2(z);X.issues.push({origin:K,code:"too_small",minimum:Y.minimum,inclusive:!0,input:z,inst:$,continue:!Y.abort})}}),Q3=y("$ZodCheckLengthEquals",($,Y)=>{var Q;q6.init($,Y),(Q=$._zod.def).when??(Q.when=(X)=>{let z=X.value;return!kX(z)&&z.length!==void 0}),$._zod.onattach.push((X)=>{let z=X._zod.bag;z.minimum=Y.length,z.maximum=Y.length,z.length=Y.length}),$._zod.check=(X)=>{let z=X.value,Z=z.length;if(Z===Y.length)return;let K=h2(z),W=Z>Y.length;X.issues.push({origin:K,...W?{code:"too_big",maximum:Y.length}:{code:"too_small",minimum:Y.length},inclusive:!0,exact:!0,input:X.value,inst:$,continue:!Y.abort})}}),MK=y("$ZodCheckStringFormat",($,Y)=>{var Q,X;if(q6.init($,Y),$._zod.onattach.push((z)=>{let Z=z._zod.bag;if(Z.format=Y.format,Y.pattern)Z.patterns??(Z.patterns=new Set),Z.patterns.add(Y.pattern)}),Y.pattern)(Q=$._zod).check??(Q.check=(z)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(z.value))return;z.issues.push({origin:"string",code:"invalid_format",format:Y.format,input:z.value,...Y.pattern?{pattern:Y.pattern.toString()}:{},inst:$,continue:!Y.abort})});else(X=$._zod).check??(X.check=()=>{})}),X3=y("$ZodCheckRegex",($,Y)=>{MK.init($,Y),$._zod.check=(Q)=>{if(Y.pattern.lastIndex=0,Y.pattern.test(Q.value))return;Q.issues.push({origin:"string",code:"invalid_format",format:"regex",input:Q.value,pattern:Y.pattern.toString(),inst:$,continue:!Y.abort})}}),z3=y("$ZodCheckLowerCase",($,Y)=>{Y.pattern??(Y.pattern=nM),MK.init($,Y)}),Z3=y("$ZodCheckUpperCase",($,Y)=>{Y.pattern??(Y.pattern=dM),MK.init($,Y)}),K3=y("$ZodCheckIncludes",($,Y)=>{q6.init($,Y);let Q=B7(Y.includes),X=new RegExp(typeof Y.position==="number"?`^.{${Y.position}}${Q}`:Q);Y.pattern=X,$._zod.onattach.push((z)=>{let Z=z._zod.bag;Z.patterns??(Z.patterns=new Set),Z.patterns.add(X)}),$._zod.check=(z)=>{if(z.value.includes(Y.includes,Y.position))return;z.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:Y.includes,input:z.value,inst:$,continue:!Y.abort})}}),W3=y("$ZodCheckStartsWith",($,Y)=>{q6.init($,Y);let Q=new RegExp(`^${B7(Y.prefix)}.*`);Y.pattern??(Y.pattern=Q),$._zod.onattach.push((X)=>{let z=X._zod.bag;z.patterns??(z.patterns=new Set),z.patterns.add(Q)}),$._zod.check=(X)=>{if(X.value.startsWith(Y.prefix))return;X.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:Y.prefix,input:X.value,inst:$,continue:!Y.abort})}}),V3=y("$ZodCheckEndsWith",($,Y)=>{q6.init($,Y);let Q=new RegExp(`.*${B7(Y.suffix)}$`);Y.pattern??(Y.pattern=Q),$._zod.onattach.push((X)=>{let z=X._zod.bag;z.patterns??(z.patterns=new Set),z.patterns.add(Q)}),$._zod.check=(X)=>{if(X.value.endsWith(Y.suffix))return;X.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:Y.suffix,input:X.value,inst:$,continue:!Y.abort})}});function qd($,Y,Q){if($.issues.length)Y.issues.push(...I9(Q,$.issues))}var H3=y("$ZodCheckProperty",($,Y)=>{q6.init($,Y),$._zod.check=(Q)=>{let X=Y.schema._zod.run({value:Q.value[Y.property],issues:[]},{});if(X instanceof Promise)return X.then((z)=>qd(z,Q,Y.property));qd(X,Q,Y.property);return}}),G3=y("$ZodCheckMimeType",($,Y)=>{q6.init($,Y);let Q=new Set(Y.mime);$._zod.onattach.push((X)=>{X._zod.bag.mime=Y.mime}),$._zod.check=(X)=>{if(Q.has(X.value.type))return;X.issues.push({code:"invalid_value",values:Y.mime,input:X.value.type,inst:$,continue:!Y.abort})}}),J3=y("$ZodCheckOverwrite",($,Y)=>{q6.init($,Y),$._zod.check=(Q)=>{Q.value=Y.tx(Q.value)}});class rU{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let Q=$.split(`
|
|
486
486
|
`).filter((Z)=>Z),X=Math.min(...Q.map((Z)=>Z.length-Z.trimStart().length)),z=Q.map((Z)=>Z.slice(X)).map((Z)=>" ".repeat(this.indent*2)+Z);for(let Z of z)this.content.push(Z)}compile(){let $=Function,Y=this?.args,X=[...(this?.content??[""]).map((z)=>` ${z}`)];return new $(...Y,X.join(`
|
|
487
487
|
`))}}var w3={major:4,minor:4,patch:3};var w0=y("$ZodType",($,Y)=>{var Q;$??($={}),$._zod.def=Y,$._zod.bag=$._zod.bag||{},$._zod.version=w3;let X=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))X.unshift($);for(let z of X)for(let Z of z._zod.onattach)Z($);if(X.length===0)(Q=$._zod).deferred??(Q.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let z=(K,W,V)=>{let H=EX(K),G;for(let J of W){if(J._zod.def.when){if(xM(K))continue;if(!J._zod.def.when(K))continue}else if(H)continue;let w=K.issues.length,U=J._zod.check(K);if(U instanceof Promise&&V?.async===!1)throw new fY;if(G||U instanceof Promise)G=(G??Promise.resolve()).then(async()=>{if(await U,K.issues.length===w)return;if(!H)H=EX(K,w)});else{if(K.issues.length===w)continue;if(!H)H=EX(K,w)}}if(G)return G.then(()=>{return K});return K},Z=(K,W,V)=>{if(EX(K))return K.aborted=!0,K;let H=z(W,X,V);if(H instanceof Promise){if(V.async===!1)throw new fY;return H.then((G)=>$._zod.parse(G,V))}return $._zod.parse(H,V)};$._zod.run=(K,W)=>{if(W.skipChecks)return $._zod.parse(K,W);if(W.direction==="backward"){let H=$._zod.parse({value:K.value,issues:[]},{...W,skipChecks:!0});if(H instanceof Promise)return H.then((G)=>{return Z(G,K,W)});return Z(H,K,W)}let V=$._zod.parse(K,W);if(V instanceof Promise){if(W.async===!1)throw new fY;return V.then((H)=>z(H,X,W))}return z(V,X,W)}}A0($,"~standard",()=>({validate:(z)=>{try{let Z=DM($,z);return Z.success?{value:Z.data}:{issues:Z.error?.issues}}catch(Z){return FM($,z).then((K)=>K.success?{value:K.data}:{issues:K.error?.issues})}},vendor:"zod",version:1}))}),qZ=y("$ZodString",($,Y)=>{w0.init($,Y),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??hM($._zod.bag),$._zod.parse=(Q,X)=>{if(Y.coerce)try{Q.value=String(Q.value)}catch(z){}if(typeof Q.value==="string")return Q;return Q.issues.push({expected:"string",code:"invalid_type",input:Q.value,inst:$}),Q}}),H6=y("$ZodStringFormat",($,Y)=>{MK.init($,Y),qZ.init($,Y)}),x3=y("$ZodGUID",($,Y)=>{Y.pattern??(Y.pattern=vM),H6.init($,Y)}),B3=y("$ZodUUID",($,Y)=>{if(Y.version){let X={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[Y.version];if(X===void 0)throw Error(`Invalid UUID version: "${Y.version}"`);Y.pattern??(Y.pattern=BZ(X))}else Y.pattern??(Y.pattern=BZ());H6.init($,Y)}),q3=y("$ZodEmail",($,Y)=>{Y.pattern??(Y.pattern=bM),H6.init($,Y)}),D3=y("$ZodURL",($,Y)=>{H6.init($,Y),$._zod.check=(Q)=>{try{let X=Q.value.trim();if(!Y.normalize&&Y.protocol?.source===EM.source){if(!/^https?:\/\//i.test(X)){Q.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:Q.value,inst:$,continue:!Y.abort});return}}let z=new URL(X);if(Y.hostname){if(Y.hostname.lastIndex=0,!Y.hostname.test(z.hostname))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Y.hostname.source,input:Q.value,inst:$,continue:!Y.abort})}if(Y.protocol){if(Y.protocol.lastIndex=0,!Y.protocol.test(z.protocol.endsWith(":")?z.protocol.slice(0,-1):z.protocol))Q.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:Y.protocol.source,input:Q.value,inst:$,continue:!Y.abort})}if(Y.normalize)Q.value=z.href;else Q.value=X;return}catch(X){Q.issues.push({code:"invalid_format",format:"url",input:Q.value,inst:$,continue:!Y.abort})}}}),F3=y("$ZodEmoji",($,Y)=>{Y.pattern??(Y.pattern=AM()),H6.init($,Y)}),L3=y("$ZodNanoID",($,Y)=>{Y.pattern??(Y.pattern=MM),H6.init($,Y)}),N3=y("$ZodCUID",($,Y)=>{Y.pattern??(Y.pattern=LM),H6.init($,Y)}),j3=y("$ZodCUID2",($,Y)=>{Y.pattern??(Y.pattern=NM),H6.init($,Y)}),P3=y("$ZodULID",($,Y)=>{Y.pattern??(Y.pattern=jM),H6.init($,Y)}),I3=y("$ZodXID",($,Y)=>{Y.pattern??(Y.pattern=PM),H6.init($,Y)}),M3=y("$ZodKSUID",($,Y)=>{Y.pattern??(Y.pattern=IM),H6.init($,Y)}),O3=y("$ZodISODateTime",($,Y)=>{Y.pattern??(Y.pattern=yM(Y)),H6.init($,Y)}),v3=y("$ZodISODate",($,Y)=>{Y.pattern??(Y.pattern=uM),H6.init($,Y)}),b3=y("$ZodISOTime",($,Y)=>{Y.pattern??(Y.pattern=cM(Y)),H6.init($,Y)}),A3=y("$ZodISODuration",($,Y)=>{Y.pattern??(Y.pattern=OM),H6.init($,Y)}),_3=y("$ZodIPv4",($,Y)=>{Y.pattern??(Y.pattern=_M),H6.init($,Y),$._zod.bag.format="ipv4"}),R3=y("$ZodIPv6",($,Y)=>{Y.pattern??(Y.pattern=RM),H6.init($,Y),$._zod.bag.format="ipv6",$._zod.check=(Q)=>{try{new URL(`http://[${Q.value}]`)}catch{Q.issues.push({code:"invalid_format",format:"ipv6",input:Q.value,inst:$,continue:!Y.abort})}}}),T3=y("$ZodMAC",($,Y)=>{Y.pattern??(Y.pattern=TM(Y.delimiter)),H6.init($,Y),$._zod.bag.format="mac"}),k3=y("$ZodCIDRv4",($,Y)=>{Y.pattern??(Y.pattern=kM),H6.init($,Y)}),S3=y("$ZodCIDRv6",($,Y)=>{Y.pattern??(Y.pattern=SM),H6.init($,Y),$._zod.check=(Q)=>{let X=Q.value.split("/");try{if(X.length!==2)throw Error();let[z,Z]=X;if(!Z)throw Error();let K=Number(Z);if(`${K}`!==Z)throw Error();if(K<0||K>128)throw Error();new URL(`http://[${z}]`)}catch{Q.issues.push({code:"invalid_format",format:"cidrv6",input:Q.value,inst:$,continue:!Y.abort})}}});function f3($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var E3=y("$ZodBase64",($,Y)=>{Y.pattern??(Y.pattern=fM),H6.init($,Y),$._zod.bag.contentEncoding="base64",$._zod.check=(Q)=>{if(f3(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64",input:Q.value,inst:$,continue:!Y.abort})}});function Sd($){if(!dU.test($))return!1;let Y=$.replace(/[-_]/g,(X)=>X==="-"?"+":"/"),Q=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return f3(Q)}var C3=y("$ZodBase64URL",($,Y)=>{Y.pattern??(Y.pattern=dU),H6.init($,Y),$._zod.bag.contentEncoding="base64url",$._zod.check=(Q)=>{if(Sd(Q.value))return;Q.issues.push({code:"invalid_format",format:"base64url",input:Q.value,inst:$,continue:!Y.abort})}}),u3=y("$ZodE164",($,Y)=>{Y.pattern??(Y.pattern=CM),H6.init($,Y)});function fd($,Y=null){try{let Q=$.split(".");if(Q.length!==3)return!1;let[X]=Q;if(!X)return!1;let z=JSON.parse(atob(X));if("typ"in z&&z?.typ!=="JWT")return!1;if(!z.alg)return!1;if(Y&&(!("alg"in z)||z.alg!==Y))return!1;return!0}catch{return!1}}var c3=y("$ZodJWT",($,Y)=>{H6.init($,Y),$._zod.check=(Q)=>{if(fd(Q.value,Y.alg))return;Q.issues.push({code:"invalid_format",format:"jwt",input:Q.value,inst:$,continue:!Y.abort})}}),y3=y("$ZodCustomStringFormat",($,Y)=>{H6.init($,Y),$._zod.check=(Q)=>{if(Y.fn(Q.value))return;Q.issues.push({code:"invalid_format",format:Y.format,input:Q.value,inst:$,continue:!Y.abort})}}),Yx=y("$ZodNumber",($,Y)=>{w0.init($,Y),$._zod.pattern=$._zod.bag.pattern??i2,$._zod.parse=(Q,X)=>{if(Y.coerce)try{Q.value=Number(Q.value)}catch(K){}let z=Q.value;if(typeof z==="number"&&!Number.isNaN(z)&&Number.isFinite(z))return Q;let Z=typeof z==="number"?Number.isNaN(z)?"NaN":!Number.isFinite(z)?"Infinity":void 0:void 0;return Q.issues.push({expected:"number",code:"invalid_type",input:z,inst:$,...Z?{received:Z}:{}}),Q}}),h3=y("$ZodNumberFormat",($,Y)=>{oM.init($,Y),Yx.init($,Y)}),d2=y("$ZodBoolean",($,Y)=>{w0.init($,Y),$._zod.pattern=pM,$._zod.parse=(Q,X)=>{if(Y.coerce)try{Q.value=Boolean(Q.value)}catch(Z){}let z=Q.value;if(typeof z==="boolean")return Q;return Q.issues.push({expected:"boolean",code:"invalid_type",input:z,inst:$}),Q}}),Qx=y("$ZodBigInt",($,Y)=>{w0.init($,Y),$._zod.pattern=gM,$._zod.parse=(Q,X)=>{if(Y.coerce)try{Q.value=BigInt(Q.value)}catch(z){}if(typeof Q.value==="bigint")return Q;return Q.issues.push({expected:"bigint",code:"invalid_type",input:Q.value,inst:$}),Q}}),g3=y("$ZodBigIntFormat",($,Y)=>{rM.init($,Y),Qx.init($,Y)}),m3=y("$ZodSymbol",($,Y)=>{w0.init($,Y),$._zod.parse=(Q,X)=>{let z=Q.value;if(typeof z==="symbol")return Q;return Q.issues.push({expected:"symbol",code:"invalid_type",input:z,inst:$}),Q}}),p3=y("$ZodUndefined",($,Y)=>{w0.init($,Y),$._zod.pattern=lM,$._zod.values=new Set([void 0]),$._zod.parse=(Q,X)=>{let z=Q.value;if(typeof z>"u")return Q;return Q.issues.push({expected:"undefined",code:"invalid_type",input:z,inst:$}),Q}}),i3=y("$ZodNull",($,Y)=>{w0.init($,Y),$._zod.pattern=iM,$._zod.values=new Set([null]),$._zod.parse=(Q,X)=>{let z=Q.value;if(z===null)return Q;return Q.issues.push({expected:"null",code:"invalid_type",input:z,inst:$}),Q}}),l3=y("$ZodAny",($,Y)=>{w0.init($,Y),$._zod.parse=(Q)=>Q}),n3=y("$ZodUnknown",($,Y)=>{w0.init($,Y),$._zod.parse=(Q)=>Q}),d3=y("$ZodNever",($,Y)=>{w0.init($,Y),$._zod.parse=(Q,X)=>{return Q.issues.push({expected:"never",code:"invalid_type",input:Q.value,inst:$}),Q}}),a3=y("$ZodVoid",($,Y)=>{w0.init($,Y),$._zod.parse=(Q,X)=>{let z=Q.value;if(typeof z>"u")return Q;return Q.issues.push({expected:"void",code:"invalid_type",input:z,inst:$}),Q}}),o3=y("$ZodDate",($,Y)=>{w0.init($,Y),$._zod.parse=(Q,X)=>{if(Y.coerce)try{Q.value=new Date(Q.value)}catch(W){}let z=Q.value,Z=z instanceof Date;if(Z&&!Number.isNaN(z.getTime()))return Q;return Q.issues.push({expected:"date",code:"invalid_type",input:z,...Z?{received:"Invalid Date"}:{},inst:$}),Q}});function Ld($,Y,Q){if($.issues.length)Y.issues.push(...I9(Q,$.issues));Y.value[Q]=$.value}var r3=y("$ZodArray",($,Y)=>{w0.init($,Y),$._zod.parse=(Q,X)=>{let z=Q.value;if(!Array.isArray(z))return Q.issues.push({expected:"array",code:"invalid_type",input:z,inst:$}),Q;Q.value=Array(z.length);let Z=[];for(let K=0;K<z.length;K++){let W=z[K],V=Y.element._zod.run({value:W,issues:[]},X);if(V instanceof Promise)Z.push(V.then((H)=>Ld(H,Q,K)));else Ld(V,Q,K)}if(Z.length)return Promise.all(Z).then(()=>Q);return Q}});function $x($,Y,Q,X,z,Z){let K=Q in X;if($.issues.length){if(z&&Z&&!K)return;Y.issues.push(...I9(Q,$.issues))}if(!K&&!z){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[Q]});return}if($.value===void 0){if(K)Y.value[Q]=void 0}else Y.value[Q]=$.value}function Ed($){let Y=Object.keys($.shape);for(let X of Y)if(!$.shape?.[X]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${X}": expected a Zod schema`);let Q=JM($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(Q)}}function Cd($,Y,Q,X,z,Z){let K=[],W=z.keySet,V=z.catchall._zod,H=V.def.type,G=V.optin==="optional",J=V.optout==="optional";for(let w in Y){if(w==="__proto__")continue;if(W.has(w))continue;if(H==="never"){K.push(w);continue}let U=V.run({value:Y[w],issues:[]},X);if(U instanceof Promise)$.push(U.then((B)=>$x(B,Q,w,Y,G,J)));else $x(U,Q,w,Y,G,J)}if(K.length)Q.issues.push({code:"unrecognized_keys",keys:K,input:Y,inst:Z});if(!$.length)return Q;return Promise.all($).then(()=>{return Q})}var ud=y("$ZodObject",($,Y)=>{if(w0.init($,Y),!Object.getOwnPropertyDescriptor(Y,"shape")?.get){let W=Y.shape;Object.defineProperty(Y,"shape",{get:()=>{let V={...W};return Object.defineProperty(Y,"shape",{value:V}),V}})}let X=FK(()=>Ed(Y));A0($._zod,"propValues",()=>{let W=Y.shape,V={};for(let H in W){let G=W[H]._zod;if(G.values){V[H]??(V[H]=new Set);for(let J of G.values)V[H].add(J)}}return V});let z=xZ,Z=Y.catchall,K;$._zod.parse=(W,V)=>{K??(K=X.value);let H=W.value;if(!z(H))return W.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),W;W.value={};let G=[],J=K.shape;for(let w of K.keys){let U=J[w],B=U._zod.optin==="optional",D=U._zod.optout==="optional",q=U._zod.run({value:H[w],issues:[]},V);if(q instanceof Promise)G.push(q.then((F)=>$x(F,W,w,H,B,D)));else $x(q,W,w,H,B,D)}if(!Z)return G.length?Promise.all(G).then(()=>W):W;return Cd(G,H,W,V,X.value,$)}}),s3=y("$ZodObjectJIT",($,Y)=>{ud.init($,Y);let Q=$._zod.parse,X=FK(()=>Ed(Y)),z=(w)=>{let U=new rU(["shape","payload","ctx"]),B=X.value,D=(L)=>{let I=EU(L);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};U.write("const input = payload.value;");let q=Object.create(null),F=0;for(let L of B.keys)q[L]=`key_${F++}`;U.write("const newResult = {};");for(let L of B.keys){let I=q[L],O=EU(L),m=w[L],V1=m?._zod?.optin==="optional",H1=m?._zod?.optout==="optional";if(U.write(`const ${I} = ${D(L)};`),V1&&H1)U.write(`
|
|
@@ -1115,7 +1115,7 @@ Runs "bun i -g @interactive-inc/claude-funnel".`,G71="@interactive-inc/claude-fu
|
|
|
1115
1115
|
`)},hN6=($)=>{if(!FI($))return $;let Y=kl($,fN6),Q=$.blocks;if(Array.isArray(Q)){let X=yN6(Q),z=typeof Y.text==="string"?Y.text:"";Y.text=z?`${z}
|
|
1116
1116
|
${X}`:X,Y._funnel_omitted=["blocks"]}return Y},ne1=($)=>{let Y=kl($,kN6);if(Array.isArray(Y.files))Y.files=Y.files.map(CN6);if(Array.isArray(Y.attachments))Y.attachments=Y.attachments.map(hN6);return Y};var gN6=new Set(["message","app_mention"]),mN6=new Set([void 0,"thread_broadcast","bot_message","file_share"]),pN6=1e4,_Y=($,Y)=>{let Q=$[Y];return typeof Q==="string"?Q:void 0};class fl{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 Y=_Y($,"type");if(!Y||!gN6.has(Y))return{skip:!0,reason:"skip:type"};let Q=_Y($,"subtype");if(!mN6.has(Q))return{skip:!0,reason:"skip:subtype"};let X=_Y($,"channel")??"",z=_Y($,"event_ts")??_Y($,"ts")??"",Z=`${X}:${z}`,K=this.now();if(this.dedup.has(Z))return{skip:!0,reason:"skip:dedup"};this.dedup.set(Z,K);for(let U of this.dedup.keys())if((this.dedup.get(U)??0)<K-pN6)this.dedup.delete(U);let W=_Y($,"user"),V=_Y($,"bot_id");if(W===this.ownBotUserId)return{skip:!0,reason:"skip:self-user"};if(V===this.ownBotId)return{skip:!0,reason:"skip:self-bot"};let G=(_Y($,"text")??"").includes(`<@${this.ownBotUserId}>`),J=_Y($,"thread_ts")??_Y($,"ts")??"",w=this.minify?ne1($):$;return{skip:!1,content:JSON.stringify(w),meta:{event_type:"slack",channel_id:X,user_id:W??"",mentioned:String(G),thread_ts:J},shouldReact:G,channel:X,timestamp:_Y($,"ts")??""}}}var iN6=N.object({event:N.record(N.string(),N.unknown()).optional()});class El extends ZX{config;channelId;env;logger;diagnosticLog;onAppCreated;preprocessEvent;app=null;constructor($){super();this.config=$.config,this.channelId=$.channelId??null,this.env=$.env??process.env,this.logger=$.logger,this.diagnosticLog=$.diagnosticLog,this.onAppCreated=$.onAppCreated??null,this.preprocessEvent=$.preprocessEvent??null}async start($){this.recordConnection("started","");let Y=gQ({literal:this.config.botToken,envVar:this.config.botTokenEnv,env:this.env,label:`${this.config.name}.botToken`}),Q=gQ({literal:this.config.appToken,envVar:this.config.appTokenEnv,env:this.env,label:`${this.config.name}.appToken`}),X=new LI.App({token:Y,appToken:Q,socketMode:!0,logLevel:LI.LogLevel.ERROR}),z;try{z=await X.client.auth.test({token:Y})}catch(W){throw this.recordConnection("auth-failed",BU(W)),W}let Z=new fl({ownBotUserId:z.user_id??"",ownBotId:z.bot_id??"",minify:this.config.minify}),K=this.preprocessEvent;if(X.use(async(W)=>{let V=iN6.safeParse(W);if(!V.success||!V.data.event){await W.next();return}let H=V.data.event,G=crypto.randomUUID();this.recordRaw(G,H);let J=K?K(H):H;if(J===null){this.recordProcessed(G,H,"skip:preprocess","");return}let w=Z.process(J);if(w.skip){this.recordProcessed(G,J,w.reason,"");return}try{await $(w.content,w.meta)}catch(U){throw this.recordProcessed(G,J,"emitted:delivery-failed",w.content),U}if(this.recordProcessed(G,J,"emitted",w.content),w.shouldReact)try{await X.client.reactions.add({token:Y,channel:w.channel,timestamp:w.timestamp,name:"eyes"})}catch{}}),X.error(async(W)=>{let V=BU(W);this.recordConnection("error",V),this.logger?.error("Slack error",{error:V})}),this.onAppCreated)await this.onAppCreated(X);try{await X.start()}catch(W){throw this.recordConnection("error",BU(W)),W}this.app=X,this.recordConnection("connected","")}async stop(){if(!this.app)return;try{await this.app.stop(),this.recordConnection("disconnected","")}catch($){this.recordConnection("error",BU($)),this.logger?.error("Slack stop error",{error:BU($)})}finally{this.app=null,this.recordConnection("stopped","")}}isAlive(){return this.app!==null}recordRaw($,Y){this.diagnosticLog?.recordRaw({eventId:$,type:"slack",connectorId:this.config.id,channelId:this.channelId,payload:JSON.stringify(Y)})}recordProcessed($,Y,Q,X){this.diagnosticLog?.recordProcessed({eventId:$,type:"slack",connectorId:this.config.id,channelId:this.channelId,outcome:Q,payload:X||JSON.stringify(Y)})}recordConnection($,Y){this.diagnosticLog?.recordConnection({type:"slack",connectorId:this.config.id,channelId:this.channelId,status:$,detail:Y})}}var BU=($)=>{return $ instanceof Error?$.message:String($)};import{join as Cl}from"path";var lN6=new h8,nN6=new x$;class ul{fs;process;logger;diagnosticLog;dir;slackListenerOptions;scheduleListenerOptions;constructor($={}){this.fs=$.fs??lN6,this.process=$.process??nN6,this.logger=$.logger,this.diagnosticLog=$.diagnosticLog,this.dir=$.dir??VY,this.slackListenerOptions=$.slackListenerOptions??{},this.scheduleListenerOptions=$.scheduleListenerOptions??{},Object.freeze(this)}createListener($,Y){if(Y.type==="slack")return new El({config:Y,channelId:$,logger:this.logger,diagnosticLog:this.diagnosticLog,onAppCreated:this.slackListenerOptions.onAppCreated,preprocessEvent:this.slackListenerOptions.preprocessEvent});if(Y.type==="gh")return new tc({config:Y,channelId:$,process:this.process,logger:this.logger,diagnosticLog:this.diagnosticLog});if(Y.type==="discord")return new rc({config:Y,channelId:$,logger:this.logger,diagnosticLog:this.diagnosticLog});let Q=new $y({path:Cl(this.connectorDir($,Y.id),"state.json"),fs:this.fs});return new ec({config:Y,lastFiredStore:Q,channelId:$,logger:this.logger,diagnosticLog:this.diagnosticLog,onFired:this.scheduleListenerOptions.onFired})}createAdapter($){if($.type==="slack")return new _h({config:$});if($.type==="gh")return new sc({process:this.process});if($.type==="discord")return new Yk({config:$});return null}connectorDir($,Y){return Cl(this.dir,"channels",$,"connectors",Y)}channelDir($){return Cl(this.dir,"channels",$)}}function cl($){switch($.type){case"slack":return[$.botToken,$.appToken].filter((Y)=>Y!==void 0);case"discord":return[$.botToken].filter((Y)=>Y!==void 0);case"gh":case"schedule":return[]}}function dN6($,Y){return $.type===Y}function XK($,Y,Q){let X=$.connectors.find((z)=>z.name===Y);if(!X)throw Error(`connector "${Y}" not found in channel "${$.name}"`);if(!dN6(X,Q))throw Error(`connector "${Y}" is type "${X.type}", not "${Q}"`);return X}class qU{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class zK extends qU{now(){return new Date}}var yl=($,Y,Q,X)=>{let z=Q[$];if(z!==void 0)return{[$]:z};let Z=Q[Y];if(Z!==void 0)return{[Y]:Z};let K={},W=X[$],V=X[Y];if(typeof W==="string")K[$]=W;if(typeof V==="string")K[Y]=V;return K},aN6=new zK,oN6=new WY;class hl{store;factory;profileChecker;clock;idGenerator;constructor($){this.store=$.store,this.factory=$.factory,this.profileChecker=$.profileChecker,this.clock=$.clock??aN6,this.idGenerator=$.idGenerator??oN6,Object.freeze(this)}list(){return this.store.read().channels}get($){return this.list().find((Y)=>Y.name===$)??null}getById($){return this.list().find((Y)=>Y.id===$)??null}add($){let Y=this.store.read();if(Y.channels.some((X)=>X.name===$.name))throw Error(`channel "${$.name}" already exists`);let Q={id:this.idGenerator.generate(),name:$.name,delivery:$.delivery??"fanout",connectors:[]};return Y.channels.push(Q),this.store.write(Y),Q}setDelivery($,Y){let Q=this.store.read(),X=this.requireChannel(Q,$);X.delivery=Y,this.store.write(Q)}remove($){let Y=this.store.read(),Q=Y.channels.findIndex((z)=>z.name===$);if(Q<0)throw Error(`channel "${$}" not found`);let X=Y.channels[Q];if(X&&this.profileChecker.hasChannelRef(X.id))throw Error(`channel "${$}" is referenced by a profile`);Y.channels.splice(Q,1),this.store.write(Y)}rename($,Y){let Q=this.store.read(),X=Q.channels.find((z)=>z.name===$);if(!X)throw Error(`channel "${$}" not found`);if(Q.channels.some((z)=>z.name===Y))throw Error(`channel "${Y}" already exists`);X.name=Y,this.store.write(Q)}listConnectors($){return this.requireChannel(this.store.read(),$).connectors}getConnector($,Y){let Q=this.get($);if(!Q)return null;return Q.connectors.find((X)=>X.name===Y)??null}listAllConnectors(){let $=[];for(let Y of this.list())for(let Q of Y.connectors)$.push({...Q,channelId:Y.id,channelName:Y.name});return $}addConnector($,Y){let Q=this.store.read(),X=this.requireChannel(Q,$);if(X.connectors.some((Z)=>Z.name===Y.name))throw Error(`connector "${Y.name}" already exists in channel "${$}"`);let z=this.fromInput(Y);return this.assertNoTokenCollision(Q,z),X.connectors.push(z),this.store.write(Q),z}fromInput($){let Y=this.idGenerator.generate(),Q=this.clock.iso(),X=Q,z=Q;switch($.type){case"slack":return{id:Y,type:"slack",name:$.name,...$.botToken!==void 0?{botToken:$.botToken}:{},...$.appToken!==void 0?{appToken:$.appToken}:{},...$.botTokenEnv!==void 0?{botTokenEnv:$.botTokenEnv}:{},...$.appTokenEnv!==void 0?{appTokenEnv:$.appTokenEnv}:{},minify:$.minify??!0,createdAt:X,updatedAt:z};case"gh":return{id:Y,type:"gh",name:$.name,...$.pollInterval!==void 0?{pollInterval:$.pollInterval}:{},createdAt:X,updatedAt:z};case"discord":return{id:Y,type:"discord",name:$.name,...$.botToken!==void 0?{botToken:$.botToken}:{},...$.botTokenEnv!==void 0?{botTokenEnv:$.botTokenEnv}:{},createdAt:X,updatedAt:z};case"schedule":return{id:Y,type:"schedule",name:$.name,entries:$.entries??[],createdAt:X,updatedAt:z}}}removeConnector($,Y){let Q=this.store.read(),X=this.requireChannel(Q,$),z=X.connectors.findIndex((Z)=>Z.name===Y);if(z<0)throw Error(`connector "${Y}" not found in channel "${$}"`);X.connectors.splice(z,1),this.store.write(Q)}renameConnector($,Y,Q){let X=this.store.read(),z=this.requireChannel(X,$),Z=z.connectors.find((K)=>K.name===Y);if(!Z)throw Error(`connector "${Y}" not found in channel "${$}"`);if(z.connectors.some((K)=>K.name===Q))throw Error(`connector "${Q}" already exists in channel "${$}"`);Z.name=Q,Z.updatedAt=this.clock.iso(),this.store.write(X)}updateSlackConnector($,Y,Q){let X=this.store.read(),z=this.requireChannel(X,$),Z=XK(z,Y,"slack"),K={id:Z.id,name:Z.name,type:"slack",minify:Z.minify,createdAt:Z.createdAt,updatedAt:this.clock.iso(),...yl("botToken","botTokenEnv",Q,Z),...yl("appToken","appTokenEnv",Q,Z)};this.assertNoTokenCollision(X,K),this.replaceConnector(z,Z.name,K),this.store.write(X)}updateGhConnector($,Y,Q){let X=this.store.read(),z=this.requireChannel(X,$),Z=XK(z,Y,"gh");if(Q.pollInterval!==void 0)Z.pollInterval=Q.pollInterval;Z.updatedAt=this.clock.iso(),this.store.write(X)}updateDiscordConnector($,Y,Q){let X=this.store.read(),z=this.requireChannel(X,$),Z=XK(z,Y,"discord"),K={id:Z.id,name:Z.name,type:"discord",createdAt:Z.createdAt,updatedAt:this.clock.iso(),...yl("botToken","botTokenEnv",Q,Z)};this.assertNoTokenCollision(X,K),this.replaceConnector(z,Z.name,K),this.store.write(X)}listScheduleEntries($,Y){let Q=this.requireChannel(this.store.read(),$);return XK(Q,Y,"schedule").entries}addScheduleEntry($,Y,Q){let X=this.store.read(),z=this.requireChannel(X,$),Z=XK(z,Y,"schedule"),K={id:Q.id??this.idGenerator.generate(),cron:Q.cron,prompt:Q.prompt,enabled:Q.enabled??!0,catchupPolicy:Q.catchupPolicy??"latest"};return Z.entries.push(K),Z.updatedAt=this.clock.iso(),this.store.write(X),K}removeScheduleEntry($,Y,Q){let X=this.store.read(),z=this.requireChannel(X,$),Z=XK(z,Y,"schedule"),K=Z.entries.findIndex((W)=>W.id===Q);if(K<0)throw Error(`schedule entry "${Q}" not found`);Z.entries.splice(K,1),Z.updatedAt=this.clock.iso(),this.store.write(X)}async call($,Y,Q){let X=this.getConnector($,Y);if(!X)throw Error(`connector "${Y}" not found in channel "${$}"`);let z=this.factory.createAdapter(X);if(!z)throw Error(`connector type "${X.type}" does not support outbound calls`);return await z.call(Q)}createListener($,Y){let Q=this.get($);if(!Q)return null;let X=Q.connectors.find((z)=>z.name===Y);if(!X)return null;return{config:X,channelId:Q.id,listener:this.factory.createListener(Q.id,X)}}createAllListeners(){let $=[];for(let Y of this.list())for(let Q of Y.connectors)$.push({config:Q,channelId:Y.id,channelName:Y.name,listener:this.factory.createListener(Y.id,Q)});return $}requireChannel($,Y){let Q=$.channels.find((X)=>X.name===Y);if(!Q)throw Error(`channel "${Y}" not found`);return Q}replaceConnector($,Y,Q){let X=$.connectors.findIndex((z)=>z.name===Y);if(X<0)throw Error(`connector "${Y}" not found in channel "${$.name}"`);$.connectors[X]=Q}assertNoTokenCollision($,Y){let Q=cl(Y);if(Q.length===0)return;for(let X of $.channels)for(let z of X.connectors){if(z.id===Y.id)continue;for(let Z of cl(z))if(Q.includes(Z))throw Error(`token already in use by connector "${z.name}" in channel "${X.name}"`)}}}import{homedir as rN6}from"os";import{join as NI}from"path";var sN6=new x$,tN6=new h8,eN6=new WY;class gl{channels;mcp;gateway;profiles;process;fs;idGenerator;logger;pidDir;constructor($){this.channels=$.channels,this.mcp=$.mcp,this.gateway=$.gateway,this.profiles=$.profiles,this.process=$.process??sN6,this.fs=$.fs??tN6,this.idGenerator=$.idGenerator??eN6,this.logger=$.logger,this.pidDir=NI($.dir??VY,"claude"),Object.freeze(this)}async launch($){let Y=this.channels.get($.channel)??this.channels.getById($.channel);if(!Y)throw Error(`channel "${$.channel}" not found`);if($.profileId&&this.isRunning($.profileId))throw Error(`profile "${$.profileId}" is already running`);let Q=$.cwd??globalThis.process.cwd();if(($.installMcp??!0)&&!this.mcp.findInstalledName(Q))this.mcp.install(Q),this.logger?.info("added funnel MCP to .mcp.json",{cwd:Q});if(!this.gateway.isRunning())this.logger?.info("starting gateway automatically"),await this.gateway.start();if($.profileId)this.writePidFile($.profileId),this.installCleanup($.profileId);let Z=($.resume??!1)&&$.profileId?this.resolveSession($.profileId,Q,$.userArgs??[],$.env??{}):null,K=this.buildArgs($.options??[],$.userArgs??[],Q,Z),W=this.buildEnv(Y.id,$.env??{});this.logger?.info("claude launch",{channel:$.channel,channelId:Y.id,cwd:Q});try{return await this.process.attach(["claude",...K],{cwd:Q,env:W,onSpawned:$.onSpawned})}finally{if($.profileId)this.removePidFile($.profileId)}}isRunning($){let Y=this.readPid($);if(!Y)return!1;return this.isProcessAlive(Y)}pidPath($){return NI(this.pidDir,`${$}.pid`)}readPid($){let Y=this.pidPath($);if(!this.fs.existsSync(Y))return null;try{let Q=this.fs.readFileSync(Y).trim(),X=Number(Q);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 Y=this.pidPath($);if(this.fs.existsSync(Y))this.fs.unlink(Y)}installCleanup($){globalThis.process.once("exit",()=>this.removePidFile($))}isProcessAlive($){return this.process.isAlive($)}buildArgs($,Y,Q,X){let z=[...$,...Y];if(X!==null)if(X.mode==="resume")z.push("--resume",X.id);else z.push("--session-id",X.id);let Z=this.mcp.findInstalledName(Q);if(Z&&!z.includes("--dangerously-load-development-channels")&&!z.includes("--channels"))z.push("--dangerously-load-development-channels",`server:${Z}`);return z}resolveSession($,Y,Q,X){for(let K of Q){if(K==="-c"||K==="--continue")return null;if(K==="--resume"||K.startsWith("--resume="))return null;if(K==="--session-id"||K.startsWith("--session-id="))return null}let z=this.profiles.getSessionId($);if(z!==null&&this.sessionFileExists(Y,z,X))return{id:z,mode:"resume"};let Z=this.idGenerator.generate();return this.profiles.setSessionId($,Z),{id:Z,mode:"new"}}sessionFileExists($,Y,Q){let X=Q.CLAUDE_CONFIG_DIR??globalThis.process.env.CLAUDE_CONFIG_DIR??NI(rN6(),".claude"),z=$.replace(/\//g,"-"),Z=NI(X,"projects",z,`${Y}.jsonl`);if(!this.fs.existsSync(Z))return!1;return this.fs.readFileSync(Z).trim().length>0}buildEnv($,Y){let Q={};for(let[X,z]of Object.entries(Y))Q[X]=z;for(let[X,z]of Object.entries(globalThis.process.env))if(typeof z==="string")Q[X]=z;return Q.FUNNEL_CHANNEL_ID=$,Q.FUNNEL_PORT=String(Yz()),Q}}var $j6=384;class ml extends NH{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($,Y){this.files.set($,Y),this.touch($)}writeSecretFileSync($,Y){this.files.set($,Y),this.modes.set($,$j6),this.touch($)}appendFileSync($,Y){let Q=this.files.get($)??"";this.files.set($,Q+Y),this.touch($)}unlink($){this.files.delete($),this.mtimes.delete($),this.modes.delete($)}mkdirSync($,Y){this.dirs.add($)}readdirSync($){let Y=$.endsWith("/")?$:`${$}/`,Q=[];for(let X of this.files.keys()){if(!X.startsWith(Y))continue;let z=X.slice(Y.length);if(!z.includes("/"))Q.push(z)}return Q}statSync($){let Y=this.mtimes.get($);if(Y===void 0)throw Error(`not found: ${$}`);return{mtimeMs:Y,mode:this.modes.get($)??null}}setMtime($,Y){this.mtimes.set($,Y)}setMode($,Y){this.modes.set($,Y)}touch($){if(!this.mtimes.has($))this.mtimes.set($,this.now());else this.mtimes.set($,this.now())}}class pl extends PH{counter=0;prefix;constructor($={}){super();this.prefix=$.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}class il{channels;prompter;constructor($){this.channels=$.channels,this.prompter=$.prompter,Object.freeze(this)}async ensure($){if(!this.channels.get($.name))this.channels.add({name:$.name});if($.connectors===void 0)return{touched:[],removed:[]};let Q=[],X=new Set;for(let Z of $.connectors){let K=await this.ensureConnector($.name,Z);Q.push({name:K.name,changed:K.changed}),X.add(K.id)}let z=this.removeExtras($.name,X);return{touched:Q,removed:z}}async ensureConnector($,Y){if(Y.type==="slack")return await this.ensureSlack($,Y);if(Y.type==="discord")return await this.ensureDiscord($,Y);if(Y.type==="gh")return this.ensureGh($,Y);return this.ensureSchedule($,Y)}async ensureSlack($,Y){let Q=this.findExistingSlack($,Y.name),X=await this.resolveSlot({label:`${Y.name}.botToken`,existingLiteral:Q?.botToken,existingEnv:Q?.botTokenEnv}),z=await this.resolveSlot({label:`${Y.name}.appToken`,existingLiteral:Q?.appToken,existingEnv:Q?.appTokenEnv}),Z={botToken:X.token,botTokenEnv:X.tokenEnv,appToken:z.token,appTokenEnv:z.tokenEnv};if(Q){if(!(Q.botToken===X.token&&Q.botTokenEnv===X.tokenEnv&&Q.appToken===z.token&&Q.appTokenEnv===z.tokenEnv))return this.channels.updateSlackConnector($,Y.name,Z),{id:Q.id,name:Y.name,changed:!0};return{id:Q.id,name:Y.name,changed:!1}}return{id:this.channels.addConnector($,{type:"slack",name:Y.name,...Z,...Y.minify!==void 0?{minify:Y.minify}:{}}).id,name:Y.name,changed:!0}}async ensureDiscord($,Y){let Q=this.findExistingDiscord($,Y.name),X=await this.resolveSlot({label:`${Y.name}.botToken`,existingLiteral:Q?.botToken,existingEnv:Q?.botTokenEnv}),z={botToken:X.token,botTokenEnv:X.tokenEnv};if(Q){if(Q.botToken!==X.token||Q.botTokenEnv!==X.tokenEnv)return this.channels.updateDiscordConnector($,Y.name,z),{id:Q.id,name:Y.name,changed:!0};return{id:Q.id,name:Y.name,changed:!1}}return{id:this.channels.addConnector($,{type:"discord",name:Y.name,...z}).id,name:Y.name,changed:!0}}ensureGh($,Y){let Q=this.channels.getConnector($,Y.name);if(Q&&Q.type!=="gh")throw Error(`connector "${Y.name}" exists in channel "${$}" with type "${Q.type}", funnel.json declares "gh"`);if(Q&&Q.type==="gh"){if(Y.pollInterval!==void 0&&Q.pollInterval!==Y.pollInterval)return this.channels.updateGhConnector($,Y.name,{pollInterval:Y.pollInterval}),{id:Q.id,name:Y.name,changed:!0};return{id:Q.id,name:Y.name,changed:!1}}return{id:this.channels.addConnector($,{type:"gh",name:Y.name,...Y.pollInterval!==void 0?{pollInterval:Y.pollInterval}:{}}).id,name:Y.name,changed:!0}}ensureSchedule($,Y){let Q=this.channels.getConnector($,Y.name);if(Q&&Q.type!=="schedule")throw Error(`connector "${Y.name}" exists in channel "${$}" with type "${Q.type}", funnel.json declares "schedule"`);if(Q&&Q.type==="schedule")return{id:Q.id,name:Y.name,changed:!1};return{id:this.channels.addConnector($,{type:"schedule",name:Y.name}).id,name:Y.name,changed:!0}}findExistingSlack($,Y){let Q=this.channels.getConnector($,Y);if(!Q)return null;if(Q.type!=="slack")throw Error(`connector "${Y}" exists in channel "${$}" with type "${Q.type}", funnel.json declares "slack"`);return Q}findExistingDiscord($,Y){let Q=this.channels.getConnector($,Y);if(!Q)return null;if(Q.type!=="discord")throw Error(`connector "${Y}" exists in channel "${$}" with type "${Q.type}", funnel.json declares "discord"`);return Q}removeExtras($,Y){let Q=this.channels.get($);if(!Q)return[];let X=Q.connectors.filter((z)=>!Y.has(z.id));for(let z of X)this.channels.removeConnector($,z.name);return X.map((z)=>z.name)}async resolveSlot($){if($.existingEnv!==void 0)return{token:void 0,tokenEnv:$.existingEnv};if($.existingLiteral!==void 0)return{token:$.existingLiteral,tokenEnv:void 0};return{token:await this.prompter.promptSecret($.label),tokenEnv:void 0}}}class ll extends vH{file=null;entries=[];info($,Y){this.entries.push({level:"info",message:$,meta:Y})}warn($,Y){this.entries.push({level:"warn",message:$,meta:Y})}error($,Y){this.entries.push({level:"error",message:$,meta:Y})}clear(){this.entries.length=0}}var de1={exitCode:0,stdout:"",stderr:""};class nl extends AH{calls=[];killed=[];handler=()=>de1;syncHandler=()=>de1;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($,Y={}){this.calls.push({kind:"run",command:$,options:Y});let Q=await this.handler($);return{exitCode:Q.exitCode??0,stdout:Q.stdout??"",stderr:Q.stderr??""}}runSync($){this.calls.push({kind:"runSync",command:$});let Y=this.syncHandler($);return{exitCode:Y.exitCode??0,stdout:Y.stdout??"",stderr:Y.stderr??""}}async attach($,Y={}){if(this.calls.push({kind:"attach",command:$,options:Y}),Y.onSpawned)Y.onSpawned(1);return(await this.handler($)).exitCode??0}detach($,Y={}){this.calls.push({kind:"detach",command:$,options:Y})}kill($,Y="SIGTERM"){this.calls.push({kind:"kill",command:[String($),Y]}),this.killed.push({pid:$,signal:Y})}isAlive($){if(this.aliveStub)return this.aliveStub($);let Y=this.syncHandler(["ps","-p",String($),"-o","state="]);if((Y.exitCode??0)!==0)return!1;let Q=(Y.stdout??"").trim();if(!Q)return!1;return!Q.startsWith("Z")}listProcessesContaining($){if(this.listStub)return this.listStub($);return[]}}class dl{store;idGenerator;constructor($){this.store=$.store,this.idGenerator=$.idGenerator,Object.freeze(this)}list(){return this.store.read().profiles}get($){return this.list().find((Y)=>Y.name===$)??null}getById($){return this.list().find((Y)=>Y.id===$)??null}getDefault(){return this.list()[0]??null}add($){let Y=this.store.read();if(Y.profiles.some((Q)=>Q.name===$.name))throw Error(`profile "${$.name}" already exists`);if(!Y.channels.some((Q)=>Q.id===$.channelId))throw Error(`channel id "${$.channelId}" not found`);Y.profiles.push({id:this.idGenerator.generate(),name:$.name,path:$.path,channelId:$.channelId,options:$.options??[],env:$.env??{},resume:$.resume??!0}),this.store.write(Y)}remove($){let Y=this.store.read(),Q=Y.profiles.findIndex((X)=>X.name===$);if(Q<0)throw Error(`profile "${$}" not found`);Y.profiles.splice(Q,1),this.store.write(Y)}rename($,Y){let Q=this.store.read(),X=Q.profiles.find((z)=>z.name===$);if(!X)throw Error(`profile "${$}" not found`);if(Q.profiles.some((z)=>z.name===Y))throw Error(`profile "${Y}" already exists`);X.name=Y,this.store.write(Q)}asDefault($){let Y=this.store.read(),Q=Y.profiles.findIndex((z)=>z.name===$);if(Q<0)throw Error(`profile "${$}" not found`);if(Q===0)return;let[X]=Y.profiles.splice(Q,1);if(!X)return;Y.profiles.unshift(X),this.store.write(Y)}hasChannelRef($){return this.store.read().profiles.some((Y)=>Y.channelId===$)}getSessionId($){return this.getById($)?.sessionId??null}setSessionId($,Y){let Q=this.store.read(),X=Q.profiles.find((z)=>z.id===$);if(!X)throw Error(`profile id "${$}" not found`);X.sessionId=Y,this.store.write(Q)}update($,Y){let Q=this.store.read(),X=Q.profiles.find((z)=>z.name===$);if(!X)throw Error(`profile "${$}" not found`);if(Y.channelId!==void 0){if(!Q.channels.some((z)=>z.id===Y.channelId))throw Error(`channel id "${Y.channelId}" not found`);X.channelId=Y.channelId}if(Y.path!==void 0)X.path=Y.path;if(Y.options!==void 0)X.options=Y.options;if(Y.env!==void 0)X.env=Y.env;if(Y.resume!==void 0)X.resume=Y.resume;this.store.write(Q)}}import{stderr as jI,stdin as DQ}from"process";class al{}var Yj6="*",Qj6="\r",ae1=`
|
|
1117
1117
|
`,Xj6=String.fromCharCode(8),zj6=String.fromCharCode(127),Zj6=String.fromCharCode(3),Kj6=String.fromCharCode(4);class ol extends al{async promptSecret($){if(!DQ.isTTY)throw Error(`cannot prompt for "${$}": stdin is not a TTY. Set the matching env var or run \`fnl channels <ch> connectors add ...\` first.`);jI.write(`${$}: `);let Y=DQ.isRaw;DQ.setRawMode(!0),DQ.resume();try{return await this.readSecret()}finally{DQ.setRawMode(Y),DQ.pause(),jI.write(ae1)}}readSecret(){return new Promise(($,Y)=>{let Q="",X=(z)=>{for(let Z of z){let K=String.fromCharCode(Z);if(K===ae1||K===Qj6){DQ.off("data",X),$(Q);return}if(K===Zj6){DQ.off("data",X),Y(Error("prompt cancelled"));return}if(K===Kj6){if(DQ.off("data",X),Q.length===0)Y(Error("prompt cancelled"));else $(Q);return}if(K===Xj6||K===zj6){if(Q.length>0)Q=Q.slice(0,-1),jI.write("\b \b");continue}Q+=K,jI.write(Yj6)}};DQ.on("data",X)})}}var Wj6=($={})=>({version:hQ,channels:[],profiles:[],...$});class rl extends IH{state;constructor($){super();this.state=Wj6($)}read(){return this.state}write($){this.state=$}}class sl extends qU{current;constructor($={}){super();this.current=$.start??new Date(0)}now(){return new Date(this.current.getTime())}set($){this.current=$}advance($){this.current=new Date(this.current.getTime()+$)}}var oe1=N.object({content:N.string().min(1),meta:N.record(N.string(),N.string()).optional(),connector:N.string().min(1).optional(),target:N.string().min(1).optional()}),re1=N.object({ok:N.literal(!0),offset:N.number().int().nonnegative()});var Vj6={state:"offline"};class tl{port;isDaemonRunning;getToken;constructor($){this.port=$.port,this.isDaemonRunning=$.isDaemonRunning,this.getToken=$.getToken??(()=>null),Object.freeze(this)}async publish($,Y){if(!this.isDaemonRunning())return Vj6;try{let Q=`http://127.0.0.1:${this.port}/channels/${encodeURIComponent($)}/publish`,X=await fetch(Q,{method:"POST",headers:{...this.authHeaders(),"content-type":"application/json"},body:JSON.stringify(Y)});if(!X.ok)return{state:"error",reason:await X.text()||`HTTP ${X.status}`};let z=re1.safeParse(await X.json());if(!z.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",offset:z.data.offset}}catch(Q){return{state:"error",reason:Q instanceof Error?Q.message:String(Q)}}}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}}import{join as se1}from"path";var Hj6=5000,Gj6=2000,te1=100,Jj6=200,wj6=new x$,Uj6=new h8,xj6=new zK,Bj6=($)=>new Promise((Y)=>{setTimeout(Y,$)});class el{process;fs;clock;dir;pidFile;gatewayLog;tmpDir;port;sleep;constructor($={}){this.process=$.process??wj6,this.fs=$.fs??Uj6,this.clock=$.clock??xj6,this.dir=$.dir??VY,this.tmpDir=$.tmpDir??o8(),this.pidFile=se1(this.dir,"gateway.pid"),this.gatewayLog=se1(this.tmpDir,"gateway.log"),this.port=$.port??Yz(),this.sleep=$.sleep??Bj6,Object.freeze(this)}isRunning(){let $=this.readPid();if(!$)return!1;return this.isProcessAlive($)}getStatus(){let $=this.readPid(),Y=$!==null&&this.isProcessAlive($);return{running:Y,pid:Y?$:null,port:this.port}}async start($={}){if(this.isRunning())return!0;this.fs.mkdirSync(this.tmpDir,{recursive:!0});let Y=dq(),Q=this.buildStartCommand(Y,$);this.process.detach(Q,{env:{FUNNEL_DIR:this.dir},stdoutFile:this.gatewayLog,stderrFile:this.gatewayLog});let X=this.clock.millis()+Hj6;while(this.clock.millis()<X){if(this.isRunning())return!0;await this.sleep(te1)}return this.isRunning()}buildStartCommand($,Y={}){let Q=`funnel-gateway[${this.dir}]`;if(Y.caffeinate!==!1&&globalThis.process.platform==="darwin")return["caffeinate","-is","bun",$,Q];return["bun",$,Q]}async stop(){let $=this.readPid();if(!$)return!0;if(!this.isProcessAlive($))return this.removePid(),!0;try{this.process.kill($,"SIGTERM")}catch{return!1}let Y=this.clock.millis()+Gj6;while(this.clock.millis()<Y){if(!this.isProcessAlive($))return this.removePid(),!0;await this.sleep(te1)}try{this.process.kill($,"SIGKILL")}catch{}return await this.sleep(Jj6),this.removePid(),!this.isProcessAlive($)}async restart($={}){let Y=this.isRunning();if($.onlyIfRunning&&!Y)return{ok:!0,wasRunning:!1,stopped:!1,started:!1};let Q=Y?await this.stop():!0;if(!Q)return{ok:!1,wasRunning:Y,stopped:!1,started:!1};let X=await this.start({caffeinate:$.caffeinate});return{ok:X,wasRunning:Y,stopped:Q,started:X}}getGatewayLog(){return this.gatewayLog}getPort(){return this.port}readPid(){if(!this.fs.existsSync(this.pidFile))return null;try{let $=this.fs.readFileSync(this.pidFile).trim(),Y=Number($);if(!Y||Y<=0)return null;return Y}catch{return null}}removePid(){this.fs.unlink(this.pidFile)}isProcessAlive($){return this.process.isAlive($)}}import{existsSync as yj6,mkdirSync as hj6}from"fs";import{dirname as gj6,join as mj6}from"path";import{timingSafeEqual as qj6}from"crypto";var DU=($)=>{return async(Y,Q)=>{let Z=(Y.req.header("authorization")??"").match(/^Bearer\s+(.+)$/i)?.[1]??"";if(!PI(Z,$.expected))return Y.text("unauthorized",401);return await Q()}},PI=($,Y)=>{let Q=Buffer.from($,"utf-8"),X=Buffer.from(Y,"utf-8"),z=Math.max(Q.length,X.length,1),Z=Buffer.alloc(z),K=Buffer.alloc(z);return Q.copy(Z),X.copy(K),qj6(Z,K)&&Q.length===X.length};var U8=jB();var ee1=($)=>{let Y=Buffer.byteLength($.content,"utf-8");if($.meta)for(let[Q,X]of Object.entries($.meta))Y+=Buffer.byteLength(Q,"utf-8")+Buffer.byteLength(X,"utf-8");return Y},Dj6=1048576,Fj6=200,Lj6=4194304,Nj6=()=>{};class $n{clients=new Map;subscribers=new Set;logger;onError;maxBufferedBytes;now;replayBufferSize;replayBufferMaxBytes;replayBuffer=[];persistentReplay;exclusiveCursor=new Map;replayBufferBytes=0;eventsBroadcast=0;droppedSlowClients=0;lastBroadcastAt=null;latestOffset=0;constructor($={}){this.logger=$.logger,this.onError=$.onError??Nj6,this.maxBufferedBytes=$.maxBufferedBytes??Dj6,this.now=$.now??(()=>Date.now()),this.replayBufferSize=Math.max(0,$.replayBufferSize??Fj6),this.replayBufferMaxBytes=Math.max(0,$.replayBufferMaxBytes??Lj6),this.persistentReplay=$.persistentReplay??null}getMetrics(){return{clients:this.clients.size,subscribers:this.subscribers.size,eventsBroadcast:this.eventsBroadcast,droppedSlowClients:this.droppedSlowClients,lastBroadcastAt:this.lastBroadcastAt?new Date(this.lastBroadcastAt).toISOString():null,latestOffset:this.latestOffset,oldestReplayableOffset:this.replayBuffer[0]?.offset??null}}replaySince($,Y){let Q=this.replayBuffer[0]?.offset,X=this.persistentReplay&&(Q===void 0||$<Q-1),z=this.replayBuffer.filter((V)=>V.offset>$&&this.matchesClient(V,Y));if(!X)return z;let Z=this.persistentReplay?this.persistentReplay.loadSince($).filter((V)=>this.matchesClient(V,Y)):[],K=Q??Number.POSITIVE_INFINITY;return[...Z.filter((V)=>V.offset<K),...z]}matchesClient($,Y){if(Y.tapAll)return!0;let Q=$.meta?.target;if(Q&&Q!==Y.subscriberId)return!1;let X=$.meta?.channelId;if(X&&X!==Y.channel)return!1;let z=$.meta?.connector;if(!z)return!0;return Y.connectors.includes(z)}pickRecipients($){let Y=new Map,Q=[];for(let[X,z]of this.clients){if(!this.matchesClient($,z))continue;if(z.tapAll){Q.push(X);continue}if(z.delivery==="exclusive"){let Z=Y.get(z.channel)??[];Z.push(X),Y.set(z.channel,Z);continue}Q.push(X)}for(let[X,z]of Y){if(z.length===0)continue;let Z=this.exclusiveCursor.get(X)??0,K=z[Z%z.length];if(K)Q.push(K);this.exclusiveCursor.set(X,Z+1)}return Q}addClient($,Y){this.clients.set($,Y)}removeClient($){this.clients.delete($)}getClientCount(){return this.clients.size}listChannels(){return[...this.clients.values()].map(($)=>({...$}))}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}broadcast($,Y){this.latestOffset+=1;let Q={content:$,meta:Y,offset:this.latestOffset},X=JSON.stringify(Q),z=Y?.connector;if(this.eventsBroadcast+=1,this.lastBroadcastAt=this.now(),this.replayBufferSize>0){let K=ee1(Q);this.replayBuffer.push(Q),this.replayBufferBytes+=K;while((this.replayBuffer.length>this.replayBufferSize||this.replayBufferBytes>this.replayBufferMaxBytes)&&this.replayBuffer.length>0){let W=this.replayBuffer.shift();if(W)this.replayBufferBytes-=ee1(W)}}let Z=this.pickRecipients(Q);for(let K of Z){let W=K.getBufferedAmount();if(W>this.maxBufferedBytes){let V=this.clients.get(K);this.logger?.warn("dropping slow WS client (backpressure)",{channel:V?.channel,buffered:W,max:this.maxBufferedBytes});try{K.close(1009,"backpressure")}catch{}this.clients.delete(K),this.droppedSlowClients+=1;continue}K.send(X)}for(let K of this.subscribers)try{K(Q)}catch(W){let V=W instanceof Error?W:Error(String(W));this.logger?.error("broadcast subscriber threw",{error:V.message}),this.onError(V,{component:"broadcaster.subscriber",offset:Q.offset,connector:Q.meta?.connector??null,channel:Q.meta?.channel??null})}return Q}seedLatestOffset($){if($>this.latestOffset)this.latestOffset=$}}var KX8=N.object({type:N.string(),content:N.string(),channel_id:N.string().nullable(),connector_id:N.string().nullable(),meta:N.record(N.string(),N.string()).nullable()});class Yn{}import{Database as jj6}from"bun:sqlite";var Pj6=/^[a-z_][a-z0-9_]*$/,Ij6=500,Mj6=new Set(["seq","ts","type","event"]),$10=[["CREATE TABLE IF NOT EXISTS leuco_log (seq INTEGER PRIMARY KEY, ts INTEGER NOT NULL, type TEXT, event TEXT NOT NULL)","CREATE INDEX IF NOT EXISTS idx_leuco_log_ts ON leuco_log (ts)","CREATE INDEX IF NOT EXISTS idx_leuco_log_type ON leuco_log (type)"]];class Qn{db;maxRows;maxAgeMs;maxBytes;targetBytes;now;indexes;extractIndexes;insertStmt;insertWithSeqStmt;maxSeqStmt;countStmt;trimRowsStmt;trimAgeStmt;trimOldestStmt;insertsSinceByteCheck=0;constructor($){if(this.db=new jj6($.path),this.db.run("PRAGMA journal_mode = WAL"),this.migrate(),this.maxRows=$.maxRows??null,this.maxAgeMs=$.maxAgeMs??null,this.maxBytes=$.maxBytes??null,this.targetBytes=$.targetBytes??($.maxBytes!==void 0?Math.floor($.maxBytes/4):null),this.now=$.now??(()=>Date.now()),this.indexes=$.indexes??[],this.indexes.length>0)Oj6(this.indexes),this.extractIndexes=$.extractIndexes??null,this.syncIndexColumns();else this.extractIndexes=null;let Y=["ts","type","event",...this.indexes],Q=Y.map(()=>"?").join(", ");this.insertStmt=this.db.prepare(`INSERT INTO leuco_log (${Y.join(", ")}) VALUES (${Q})`);let X=["seq",...Y],z=X.map(()=>"?").join(", ");this.insertWithSeqStmt=this.db.prepare(`INSERT INTO leuco_log (${X.join(", ")}) VALUES (${z})`),this.maxSeqStmt=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max FROM leuco_log"),this.countStmt=this.db.prepare("SELECT COUNT(*) AS n FROM leuco_log"),this.trimRowsStmt=this.db.prepare("DELETE FROM leuco_log WHERE seq <= (SELECT seq FROM leuco_log ORDER BY seq DESC LIMIT 1 OFFSET ?)"),this.trimAgeStmt=this.db.prepare("DELETE FROM leuco_log WHERE ts < ?"),this.trimOldestStmt=this.db.prepare("DELETE FROM leuco_log WHERE seq IN (SELECT seq FROM leuco_log ORDER BY seq ASC LIMIT ?)")}insert($){try{let Y=this.buildInsertParams($.ts,$.event),Q=this.insertStmt.run(...Y),X=Number(Q.lastInsertRowid);return this.trim(),{seq:X,ts:$.ts,event:$.event}}catch(Y){return Y instanceof Error?Y:Error(String(Y))}}insertMany($){if($.length===0)return[];try{let Y=[];return this.db.transaction((X)=>{for(let z of X){let Z=this.buildInsertParams(z.ts,z.event),K=this.insertStmt.run(...Z);Y.push({seq:Number(K.lastInsertRowid),ts:z.ts,event:z.event})}})($),this.trim(),Y}catch(Y){return Y instanceof Error?Y:Error(String(Y))}}write($){try{let Y=[$.seq,...this.buildInsertParams($.ts,$.event)];this.insertWithSeqStmt.run(...Y),this.trim()}catch(Y){return Y instanceof Error?Y:Error(String(Y))}}getMaxSeq(){let $=this.maxSeqStmt.get();return $?$.max:0}getRecords($={}){let Y=["seq > ?"],Q=[$.sinceSeq??0];if(typeof $.type==="string")Y.push("type = ?"),Q.push($.type);if($.where)this.appendWhereConditions($.where,Y,Q);let X=$.limit??1000;Q.push(X);let z=$.order==="desc"?"DESC":"ASC",Z=`SELECT seq, ts, type, event FROM leuco_log WHERE ${Y.join(" AND ")} ORDER BY seq ${z} LIMIT ?`,W=this.db.prepare(Z).all(...Q);if(z==="DESC")W.reverse();return W.map(bj6)}getSchemaVersion(){return this.db.prepare("PRAGMA user_version").get()?.user_version??0}close(){this.db.close()}buildInsertParams($,Y){let Q=vj6(Y),X=JSON.stringify(Y);if(this.indexes.length===0)return[$,Q,X];let z=this.extractIndexes?this.extractIndexes(Y):null,Z=this.indexes.map((K)=>z?.[K]??null);return[$,Q,X,...Z]}appendWhereConditions($,Y,Q){let X=$;for(let z of this.indexes){let Z=X[z];if(Z===void 0)continue;if(Z===null)Y.push(`${z} IS NULL`);else Y.push(`${z} = ?`),Q.push(Z)}}trim(){if(this.maxRows!==null){let $=this.countStmt.get();if($&&$.n>this.maxRows)this.trimRowsStmt.run(this.maxRows)}if(this.maxAgeMs!==null)this.trimAgeStmt.run(this.now()-this.maxAgeMs);this.maybeTrimBytes()}maybeTrimBytes(){if(this.maxBytes===null||this.targetBytes===null)return;if(this.insertsSinceByteCheck+=1,this.insertsSinceByteCheck<Ij6)return;this.insertsSinceByteCheck=0;let $=this.byteSize();if($<=this.maxBytes)return;let Y=this.countStmt.get()?.n??0;if(Y===0)return;let Q=$-this.targetBytes,X=$/Y,z=Math.min(Y,Math.ceil(Q/X));this.trimOldestStmt.run(z),this.db.run("VACUUM")}byteSize(){let $=this.db.prepare("PRAGMA page_count").get()?.n??0,Y=this.db.prepare("PRAGMA page_size").get()?.n??0;return $*Y}clear(){this.db.run("DELETE FROM leuco_log"),this.db.run("VACUUM"),this.insertsSinceByteCheck=0}syncIndexColumns(){let $=new Set(this.db.prepare("PRAGMA table_info(leuco_log)").all().map((Y)=>Y.name));for(let Y of this.indexes){if(!$.has(Y))this.db.run(`ALTER TABLE leuco_log ADD COLUMN ${Y} TEXT`);this.db.run(`CREATE INDEX IF NOT EXISTS idx_leuco_log_${Y} ON leuco_log (${Y})`)}}migrate(){let Y=this.db.prepare("PRAGMA user_version").get()?.user_version??0;if(Y>=$10.length)return;let Q=$10.slice(Y),X=Y;for(let z of Q)X+=1,this.db.transaction(()=>{for(let K of z)this.db.run(K);this.db.run(`PRAGMA user_version = ${X}`)})()}}function Oj6($){for(let Y of $){if(!Pj6.test(Y))throw Error(`invalid index column name: ${Y}`);if(Mj6.has(Y))throw Error(`reserved index column name: ${Y}`)}}function vj6($){if(typeof $!=="object"||$===null)return null;if(!("type"in $))return null;let Y=$.type;return typeof Y==="string"?Y:null}function bj6($){return{seq:$.seq,ts:$.ts,event:JSON.parse($.event)}}var Y10=2000;class Xn extends Yn{sink;now;constructor($){super();this.now=$.now??(()=>Date.now()),this.sink=new Qn({path:$.path,indexes:["channel_id","connector_id"],extractIndexes:(Y)=>({channel_id:Y.channel_id,connector_id:Y.connector_id}),now:this.now,...$.maxRows!==void 0?{maxRows:$.maxRows}:{},...$.maxAgeMs!==void 0?{maxAgeMs:$.maxAgeMs}:{},...$.maxBytes!==void 0?{maxBytes:$.maxBytes}:{},...$.targetBytes!==void 0?{targetBytes:$.targetBytes}:{}})}record($){let Y={type:$.meta?.event_type??"unknown",content:Aj6($.content),channel_id:$.channelId,connector_id:$.connectorId,meta:$.meta};this.sink.write({seq:$.offset,ts:this.now(),event:Y})}loadSince($){let Y=this.sink.getRecords({sinceSeq:$}),Q=[];for(let X of Y)Q.push({content:X.event.content,meta:X.event.meta??void 0,offset:X.seq});return Q}loadForChannel($){let Y={channel_id:$.channelId};if($.connectorId!==void 0)Y.connector_id=$.connectorId;let Q=this.sink.getRecords({where:Y,...$.sinceSeq!==void 0?{sinceSeq:$.sinceSeq}:{},...$.limit!==void 0?{limit:$.limit}:{}}),X=[];for(let z of Q)X.push({content:z.event.content,meta:z.event.meta??void 0,offset:z.seq});return X}findMaxOffset(){return this.sink.getMaxSeq()}clear(){this.sink.clear()}close(){this.sink.close()}}function Aj6($){if($.length<=Y10)return $;return`${$.slice(0,Y10)}...`}var _j6=()=>{},Rj6=30000,Tj6=60000,kj6=($)=>new Promise((Y)=>{setTimeout(Y,$)});class ZK{channels;notify;logger;onError;running=new Map;failureCounts=new Map;stats=new Map;healthCheckIntervalMs;maxBackoffMs;sleep;now;healthCheckTimer=null;healthCheckInFlight=!1;constructor($){this.channels=$.channels,this.notify=$.notify,this.logger=$.logger,this.onError=$.onError??_j6,this.healthCheckIntervalMs=$.healthCheckIntervalMs??Rj6,this.maxBackoffMs=$.maxBackoffMs??Tj6,this.sleep=$.sleep??kj6,this.now=$.now??(()=>Date.now())}static keyOf($,Y){return`${$}/${Y}`}isRunning($,Y){return this.running.has(ZK.keyOf($,Y))}list(){return[...this.running.entries()].map(([$,Y])=>{let Q=this.stats.get($);return{channelName:Y.channelName,channelId:Y.channelId,name:Y.config.name,type:Y.config.type,alive:Y.listener.isAlive(),events:Q?.events??0,errors:Q?.errors??0,failureCount:this.failureCounts.get($)??0,lastEventAt:Q?.lastEventAt??null}})}async start($,Y){let Q=ZK.keyOf($,Y);if(this.running.has(Q))return{ok:!0,reason:"already running"};let X=this.channels.createListener($,Y);if(!X)return{ok:!1,reason:`connector "${Y}" not found in channel "${$}"`};let z=async(Z,K)=>{try{await this.notify($,Y,Z,K),this.recordEvent(Q)}catch(W){throw this.recordError(Q),W}};try{return await X.listener.start(z),this.running.set(Q,{config:X.config,channelName:$,channelId:X.channelId,listener:X.listener}),this.ensureStats(Q),this.logger?.info(`${X.config.type} listener started`,{channel:$,connector:Y}),{ok:!0}}catch(Z){let K=Z instanceof Error?Z:Error(String(Z));return this.logger?.error(`${X.config.type} listener failed to start`,{channel:$,connector:Y,error:K.message}),this.onError(K,{component:"listener-supervisor.start",channel:$,connector:Y,type:X.config.type}),{ok:!1,reason:K.message}}}async stop($,Y){let Q=ZK.keyOf($,Y),X=this.running.get(Q);if(!X)return{ok:!0,reason:"not running"};try{return await X.listener.stop(),this.running.delete(Q),this.failureCounts.delete(Q),this.logger?.info(`${X.config.type} listener stopped`,{channel:$,connector:Y}),{ok:!0}}catch(z){let Z=z instanceof Error?z:Error(String(z));return this.logger?.error(`${X.config.type} listener failed to stop`,{channel:$,connector:Y,error:Z.message}),this.onError(Z,{component:"listener-supervisor.stop",channel:$,connector:Y,type:X.config.type}),{ok:!1,reason:Z.message}}}async restart($,Y){let Q=await this.stop($,Y);if(!Q.ok)return Q;return await this.start($,Y)}async startAll(){let $=this.channels.listAllConnectors();for(let Y of $)await this.start(Y.channelName,Y.name);this.startHealthCheck()}async stopAll(){this.stopHealthCheck();for(let[,$]of[...this.running.entries()])await this.stop($.channelName,$.config.name)}ensureStats($){let Y=this.stats.get($);if(Y)return Y;let Q={events:0,errors:0,failureCount:0,lastEventAt:null};return this.stats.set($,Q),Q}recordEvent($){let Y=this.ensureStats($);Y.events+=1,Y.lastEventAt=new Date(this.now()).toISOString()}recordError($){this.ensureStats($).errors+=1}startHealthCheck(){if(this.healthCheckTimer)return;this.healthCheckTimer=setInterval(()=>{this.runHealthCheck()},this.healthCheckIntervalMs),this.healthCheckTimer.unref()}stopHealthCheck(){if(!this.healthCheckTimer)return;clearInterval(this.healthCheckTimer),this.healthCheckTimer=null}async runHealthCheck(){if(this.healthCheckInFlight)return;this.healthCheckInFlight=!0;try{for(let[$,Y]of[...this.running.entries()]){if(Y.listener.isAlive()){this.failureCounts.delete($);continue}await this.recoverDead(Y.channelName,Y.config.name,Y.config.type)}}finally{this.healthCheckInFlight=!1}}async recoverDead($,Y,Q){let X=ZK.keyOf($,Y),z=this.failureCounts.get(X)??0,Z=Math.min(1000*2**z,this.maxBackoffMs);if(this.logger?.warn(`${Q} listener unhealthy, restarting`,{channel:$,connector:Y,attempt:z+1,backoffMs:Z}),await this.stop($,Y),await this.sleep(Z),(await this.start($,Y)).ok)this.failureCounts.delete(X),this.logger?.info(`${Q} listener recovered`,{channel:$,connector:Y});else this.failureCounts.set(X,z+1)}}var Sj6=new x$,fj6=($)=>`funnel-gateway[${$}]`,Q10=async($)=>{let Y=$.process??Sj6,Q=$.logger,X=fj6($.dir),z=Y.listProcessesContaining(X),Z=[];for(let K of z){if(K.pid===$.selfPid)continue;Y.kill(K.pid,"SIGTERM"),Z.push(K.pid),Q?.info("killed competing Slack gateway process",{pid:K.pid,args:K.command.slice(0,160)})}return Z};var FQ=($)=>rK("param",$,(Y,Q)=>{if(Y.success)return;let X=Y.error.issues[0],z=X?`${X.path.join(".")}: ${X.message}`:"invalid request";return Q.json({ok:!1,reason:z},400)});var Ej6=N.object({method:N.string().min(1),path:N.string().min(1),body:N.unknown().optional()}),X10=U8.createHandlers(FQ(N.object({channel:N.string().min(1),connector:N.string().min(1)})),async($)=>{let Y=$.req.valid("param"),Q=await $.req.json().catch(()=>null),X=Ej6.safeParse(Q);if(!X.success)throw new W0(400,{message:X.error.issues[0]?.message??"invalid body"});let z=await $.var.deps.channels.call(Y.channel,Y.connector,{method:X.data.method,path:X.data.path,body:X.data.body??{}});return $.json({ok:!0,result:z})});var z10=U8.createHandlers(FQ(N.object({channel:N.string().min(1)})),rK("json",oe1,($,Y)=>{if($.success)return;let Q=$.error.issues[0],X=Q?`${Q.path.join(".")}: ${Q.message}`:"invalid body";return Y.json({ok:!1,reason:X},400)}),($)=>{let Y=$.req.valid("param"),Q=$.req.valid("json"),X=Q.target?{...Q.meta,target:Q.target}:Q.meta,Z={ok:!0,offset:$.var.deps.emit({channel:Y.channel,connector:Q.connector,content:Q.content,meta:X}).offset};return $.json(Z)});import{existsSync as zn}from"fs";import{join as Zn}from"path";var Cj6=($)=>{if(typeof $!=="string"||$.length===0)return null;try{let Y=JSON.parse($);if(Y!==null&&typeof Y==="object"&&"text"in Y){let Q=String(Y.text);return Q.length>80?`${Q.slice(0,80)}\u2026`:Q}}catch{return $.length>80?`${$.slice(0,80)}\u2026`:$}return $.length>80?`${$.slice(0,80)}\u2026`:$},uj6=($)=>{let Q=($.connectionErrors[$.connectionErrors.length-1]??null)?.detail??null;if($.connectors.length===0)return{status:"warn",message:"no connectors configured on this channel",nextActions:[`fnl channels ${$.name} connectors add <name> --type=slack ...`],rootCause:null};if(!$.listener)return{status:"error",message:"no listener running for this channel",nextActions:["fnl gateway restart"],rootCause:Q};if(!$.listener.alive)return{status:"error",message:"listener is dead",nextActions:["fnl gateway logs","fnl gateway restart"],rootCause:Q};if($.claudeClients===0)return{status:"warn",message:"no Claude connected to this channel",nextActions:[`fnl claude --channel ${$.name}`],rootCause:null};if($.listener.errors>0)return{status:"warn",message:"listener has errors",nextActions:["fnl gateway logs"],rootCause:Q};return{status:"ok",message:"healthy",nextActions:[],rootCause:null}},Z10=U8.createHandlers(async($)=>{let Y=$.var.deps,Q=$.req.query("channel")??null,X=Y.channels.list(),z=Q?X.filter((B)=>B.name===Q||B.id===Q):X,Z=Y.supervisor.list(),K=Y.broadcaster.listChannels(),W=Y.broadcaster.getMetrics(),V=o8(),H=Zn(V,"connector-raw.db"),G=Zn(V,"connector-processed.db"),J=Zn(V,"connector-connection.db"),w=zn(H)&&zn(G)&&zn(J),U=z.map((B)=>{let D=Z.find((O)=>O.channelName===B.name)??null,q=D?{alive:D.alive,events:D.events,errors:D.errors,lastEventAt:D.lastEventAt}:null,F=K.filter((O)=>O.channel===B.id||O.channel===B.name).length,P=[],L=[];if(w){let O=new U$({rawPath:H,processedPath:G,connectionPath:J}),m=(()=>{try{return O.query("SELECT seq, ts, type, outcome, payload FROM processed WHERE channel_id = ? ORDER BY seq DESC LIMIT 10",[B.id])}finally{O.close()}})();if(!(m instanceof Error))for(let H1 of[...m].reverse()){let p=typeof H1.payload==="string"?H1.payload:null,i=null;if(p)try{let X1=JSON.parse(p);if(X1!==null&&typeof X1==="object"&&!Array.isArray(X1))i=X1}catch{i=null}P.push({seq:typeof H1.seq==="number"?H1.seq:null,ts:typeof H1.ts==="number"?H1.ts:null,type:typeof H1.type==="string"?H1.type:"?",outcome:typeof H1.outcome==="string"?H1.outcome:"?",payload:p,payloadParsed:i,preview:Cj6(H1.payload)})}if(q&&(!q.alive||q.errors>0)||!q){let H1=new U$({rawPath:H,processedPath:G,connectionPath:J}),p=(()=>{try{return H1.query("SELECT ts, type, status, detail FROM connection WHERE channel_id = ? AND status IN ('auth-failed','error') ORDER BY seq DESC LIMIT 3",[B.id])}finally{H1.close()}})();if(!(p instanceof Error))for(let i of[...p].reverse())L.push({ts:typeof i.ts==="number"?i.ts:null,type:typeof i.type==="string"?i.type:"?",status:typeof i.status==="string"?i.status:"?",detail:typeof i.detail==="string"&&i.detail.length>0?i.detail:null})}}let I={id:B.id,name:B.name,connectors:B.connectors.map((O)=>O.name),listener:q,claudeClients:F,recentEvents:P,connectionErrors:L};return{...I,diagnosis:uj6(I)}});return $.json({pid:Y.selfPid,uptimeMs:Y.uptimeMs(),eventsBroadcast:W.eventsBroadcast,channels:U})});var K10=U8.createHandlers(($)=>{let Y=$.var.deps;return $.json({ok:!0,pid:Y.selfPid,clients:Y.broadcaster.getClientCount(),listeners:Y.supervisor.list()})});var W10=U8.createHandlers(($)=>{return $.json({listeners:$.var.deps.supervisor.list()})});var V10=U8.createHandlers(FQ(N.object({channel:N.string().min(1),connector:N.string().min(1)})),async($)=>{let Y=$.req.valid("param"),Q=await $.var.deps.supervisor.restart(Y.channel,Y.connector);return $.json(Q,Q.ok?200:400)});var H10=U8.createHandlers(FQ(N.object({channel:N.string().min(1),connector:N.string().min(1)})),async($)=>{let Y=$.req.valid("param"),Q=await $.var.deps.supervisor.start(Y.channel,Y.connector);return $.json(Q,Q.ok?200:400)});var G10=U8.createHandlers(FQ(N.object({channel:N.string().min(1),connector:N.string().min(1)})),async($)=>{let Y=$.req.valid("param"),Q=await $.var.deps.supervisor.stop(Y.channel,Y.connector);return $.json(Q,Q.ok?200:400)});var J10=U8.createHandlers(($)=>{let Y=$.var.deps;return $.json({ok:!0,pid:Y.selfPid,uptimeMs:Y.uptimeMs(),clients:Y.broadcaster.listChannels(),listeners:Y.supervisor.list(),broadcaster:Y.broadcaster.getMetrics()})});function cj6(){return U8.createApp().get("/health",...K10).get("/status",...J10).get("/debug",...Z10).get("/listeners",...W10).post("/listeners/:channel/:connector/start",...H10).delete("/listeners/:channel/:connector",...G10).post("/listeners/:channel/:connector/restart",...V10).post("/channels/:channel/connectors/:connector/call",...X10).post("/channels/:channel/publish",...z10)}var w10=cj6();var pj6="127.0.0.1",ij6=new Set(["127.0.0.1","localhost","::1","::ffff:127.0.0.1"]),lj6=()=>mj6(o8(),"events.db"),nj6=()=>{};class Kn{channels;settings;port;hostname;dbPath;process;logger;onError;selfPid;dir;killCompetingSlack;token;broadcaster;eventLog;supervisor;nowMs;extraRoutes;startedAt=null;server=null;constructor($){this.channels=$.channels,this.settings=$.settings,this.port=$.port??Yz(),this.hostname=$.hostname??pj6,this.dbPath=$.dbPath??lj6(),this.process=$.process,this.logger=$.logger,this.onError=$.onError??nj6,this.selfPid=$.selfPid??globalThis.process.pid,this.dir=$.dir??VY,this.killCompetingSlack=$.killCompetingSlack??!0,this.token=$.token??"",this.extraRoutes=$.extraRoutes??null;let Y=$.clock;if(this.nowMs=Y?()=>Y.millis():()=>Date.now(),$.eventLog)this.eventLog=$.eventLog;else{let Q=gj6(this.dbPath);if(!yj6(Q))hj6(Q,{recursive:!0});this.eventLog=new Xn({path:this.dbPath,now:this.nowMs})}this.broadcaster=new $n({logger:this.logger,onError:this.onError,now:this.nowMs,persistentReplay:this.eventLog}),this.broadcaster.seedLatestOffset(this.eventLog.findMaxOffset()),this.supervisor=new ZK({channels:this.channels,logger:this.logger,onError:this.onError,notify:async(Q,X,z,Z)=>{this.emit({channel:Q,connector:X,content:z,meta:Z})},now:this.nowMs})}async start(){if(this.server)return this.server;if(!this.token&&!ij6.has(this.hostname))this.logger?.warn("gateway auth is disabled on a non-loopback bind \u2014 every endpoint is reachable without a token",{hostname:this.hostname});let $=this.buildApp();return this.startedAt=this.nowMs(),this.server=Bun.serve({port:this.port,hostname:this.hostname,development:!1,fetch:(Y,Q)=>this.handleFetch(Y,Q,$),websocket:{open:(Y)=>this.handleWsOpen(Y),close:(Y)=>this.handleWsClose(Y),message(){}}}),this.logServerStarted(),await this.bootListeners(),this.server}async stop(){if(await this.supervisor.stopAll(),this.server)this.server.stop(),this.server=null}getStatus(){return{clients:this.broadcaster.getClientCount(),channels:this.broadcaster.listChannels()}}getBroadcaster(){return this.broadcaster}getSupervisor(){return this.supervisor}getEventLog(){return this.eventLog}onEvent($){return this.broadcaster.subscribe($)}handleFetch($,Y,Q){let X=new URL($.url);if(X.pathname==="/ws"&&$.headers.get("upgrade")==="websocket"){if(this.token&&!this.tokenMatchesUpgrade($))return new Response("unauthorized",{status:401});let z=X.searchParams.get("tap")==="all",Z=z?"":X.searchParams.get("channel")??"",K=!z&&Z?this.resolveChannel(Z):null,W=z?"":K?.id??Z,V=z?null:K?.name??null,H=K?.connectors??[],G=K?.delivery??"fanout",J=X.searchParams.get("since"),w=J===null?Number.NaN:Number.parseInt(J,10),U=Number.isFinite(w)&&w>=0?w:void 0,B=X.searchParams.get("id")??void 0;if(Y.upgrade($,{data:{channel:W,channelName:V,connectors:H,tapAll:z,delivery:G,subscriberId:B,since:U}}))return;return new Response("WebSocket upgrade failed",{status:400})}return Q.fetch($)}handleWsOpen($){if(typeof $.data.since==="number"){let Y=this.broadcaster.replaySince($.data.since,$.data);for(let Q of Y)$.send(JSON.stringify(Q))}if(this.broadcaster.addClient($,$.data),$.data.channelName){let Y={event_type:"system",action:"channel_connect",channel:$.data.channelName,channelId:$.data.channel,connectors:$.data.connectors.join(","),total:String(this.broadcaster.getClientCount())};this.logger?.info("channel connected",Y)}else this.logger?.info("tap-all client connected",{event_type:"system",action:"tap_connect",total:String(this.broadcaster.getClientCount())})}handleWsClose($){if(this.broadcaster.removeClient($),$.data.channelName)this.logger?.info("channel disconnected",{event_type:"system",action:"channel_disconnect",channel:$.data.channelName,channelId:$.data.channel,total:String(this.broadcaster.getClientCount())});else this.logger?.info("tap-all client disconnected",{event_type:"system",action:"tap_disconnect",total:String(this.broadcaster.getClientCount())})}logServerStarted(){this.logger?.info("gateway started",{event_type:"system",action:"gateway_start",port:String(this.port),pid:String(this.selfPid)}),this.logger?.info("funnel gateway listening",{url:`http://localhost:${this.port}`,websocket:`ws://localhost:${this.port}/ws`,health:`http://localhost:${this.port}/health`})}buildApp(){let $=U8.createApp();if($.use((Q,X)=>{return Q.set("deps",{selfPid:this.selfPid,broadcaster:this.broadcaster,supervisor:this.supervisor,channels:this.channels,uptimeMs:()=>this.startedAt?this.nowMs()-this.startedAt:0,emit:(z)=>this.emit(z)}),X()}),this.token)$.use("/listeners/*",DU({expected:this.token})),$.use("/status",DU({expected:this.token})),$.use("/debug",DU({expected:this.token})),$.use("/channels/*",DU({expected:this.token}));return(this.extraRoutes?$.route("/",this.extraRoutes):$).route("/",w10)}tokenMatchesUpgrade($){let Y=($.headers.get("sec-websocket-protocol")??"").split(",").map((z)=>z.trim()).filter((z)=>z.length>0);for(let z of Y)if(z.startsWith("funnel.token.")&&PI(z.slice(13),this.token))return!0;let X=($.headers.get("authorization")??"").match(/^Bearer\s+(.+)$/i);if(X&&PI(X[1]??"",this.token))return!0;return!1}resolveChannel($){let Q=this.settings.read()?.channels.find((X)=>X.id===$||X.name===$);if(!Q)return null;return{id:Q.id,name:Q.name,connectors:Q.connectors.map((X)=>X.name),delivery:Q.delivery}}async bootListeners(){let $=this.channels.listAllConnectors();if(this.killCompetingSlack&&$.some((Y)=>Y.type==="slack")){let Y=await Q10({selfPid:this.selfPid,dir:this.dir,process:this.process,logger:this.logger});if(Y.length>0)this.logger?.info("killed competing Slack gateway processes",{event_type:"system",action:"kill_competing",pids:Y.join(",")})}await this.supervisor.startAll();for(let Y of this.supervisor.list())this.logger?.info(`${Y.type} listener started: ${Y.name}`,{event_type:"system",action:`${Y.type}_connect`,channel:Y.channelName,connector:Y.name});this.logger?.info(`event store: ${this.dbPath}`),this.logger?.info("funnel gateway running")}emit($){let Y=this.lookupChannelId($.channel),Q=Y&&$.connector?this.lookupConnectorId(Y,$.connector):null,X={...$.meta,channel:$.channel};if($.connector)X.connector=$.connector;if(Y)X.channelId=Y;if(Q)X.connectorId=Q;let z=this.broadcaster.broadcast($.content,X);return this.eventLog.record({content:$.content,channelId:Y??null,connectorId:Q??null,meta:X,offset:z.offset}),{offset:z.offset}}lookupChannelId($){return this.settings.read().channels.find((Q)=>Q.name===$)?.id??null}lookupConnectorId($,Y){return this.settings.read().channels.find((z)=>z.id===$)?.connectors.find((z)=>z.name===Y)?.id??null}}import{homedir as dj6}from"os";import{dirname as aj6,join as U10}from"path";var x10="gateway.token",oj6=32,rj6=new h8,sj6=()=>{let $=new Uint8Array(oj6);return crypto.getRandomValues($),[...$].map((Y)=>Y.toString(16).padStart(2,"0")).join("")};class Wn{fs;path;generate;constructor($={}){this.fs=$.fs??rj6,this.path=U10($.dir??VY,x10),this.generate=$.generate??sj6,Object.freeze(this)}read(){if(!this.fs.existsSync(this.path))return null;let $=this.fs.readFileSync(this.path).trim();return $.length>0?$:null}ensure(){let $=this.read();if($)return $;let Y=this.generate();return this.fs.mkdirSync(aj6(this.path),{recursive:!0}),this.fs.writeSecretFileSync(this.path,`${Y}
|
|
1118
|
-
`),Y}getPath(){return this.path}}var vz8=U10(dj6(),".funnel",x10);var tj6=N.object({channelName:N.string(),channelId:N.string(),name:N.string(),type:N.string(),alive:N.boolean()}),ej6=N.object({listeners:N.array(tj6)}),$P6=N.object({reason:N.string().optional()}),Vn={state:"offline"};class Hn{port;isDaemonRunning;getToken;constructor($){this.port=$.port,this.isDaemonRunning=$.isDaemonRunning,this.getToken=$.getToken??(()=>null),Object.freeze(this)}async list(){if(!this.isDaemonRunning())return{state:"offline"};try{let $=await fetch(`http://127.0.0.1:${this.port}/listeners`,{headers:this.authHeaders()});if(!$.ok)return{state:"error",reason:`HTTP ${$.status}`};let Y=ej6.safeParse(await $.json());if(!Y.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",listeners:Y.data.listeners}}catch($){return{state:"error",reason:$ instanceof Error?$.message:String($)}}}async start($,Y){if(!this.isDaemonRunning())return Vn;return await this.call("POST",`/listeners/${this.path($,Y)}/start`)}async stop($,Y){if(!this.isDaemonRunning())return Vn;return await this.call("DELETE",`/listeners/${this.path($,Y)}`)}async restart($,Y){if(!this.isDaemonRunning())return Vn;return await this.call("POST",`/listeners/${this.path($,Y)}/restart`)}path($,Y){return`${encodeURIComponent($)}/${encodeURIComponent(Y)}`}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}async call($,Y){try{let Q=await fetch(`http://127.0.0.1:${this.port}${Y}`,{method:$,headers:this.authHeaders()});if(!Q.ok){let X=$P6.safeParse(await Q.json().catch(()=>null));return{state:"error",reason:(X.success?X.data.reason:void 0)??`HTTP ${Q.status}`}}return{state:"ok"}}catch(Q){return{state:"error",reason:Q instanceof Error?Q.message:String(Q)}}}}import{existsSync as Gn}from"fs";import{join as Jn}from"path";var YP6=($)=>{if($===null||typeof $!=="object")return!1;if(!("clients"in $)||!Array.isArray($.clients))return!1;if(!("listeners"in $)||!Array.isArray($.listeners))return!1;return!0},B10=async($,Y)=>{let Q=$.gateway.getStatus(),X={gateway:{running:Q.running,pid:Q.pid,port:Q.running?Q.port:null,uptimeMs:null},channels:[],recentEvents:null},z=$.channels.list(),Z=Y?z.filter((G)=>G.name===Y):z,K=null;if(Q.running){let G=await fetch(`http://127.0.0.1:${Q.port}/status`).catch(()=>null);if(G&&G.ok){let J=await G.json();if(YP6(J))K=J,X.gateway.uptimeMs=J.uptimeMs}}for(let G of Z){let J=K?.listeners.find((B)=>B.channelName===G.name)??null,w=J?{alive:J.alive,events:J.events,errors:J.errors,lastEventAt:J.lastEventAt}:null,U=(K?.clients??[]).filter((B)=>!B.tapAll&&(B.channelName===G.name||B.channel===G.name));X.channels.push({name:G.name,connectors:G.connectors.map((B)=>B.name),listener:w,claudeConnected:U.length>0,claudeClientCount:U.length})}let W=Jn($.tmpDir,"connector-raw.db"),V=Jn($.tmpDir,"connector-processed.db"),H=Jn($.tmpDir,"connector-connection.db");if(Gn(W)&&Gn(V)&&Gn(H)){let G=new U$({rawPath:W,processedPath:V,connectionPath:H}),J=Y?z.find((D)=>D.name===Y)?.id??null:null,w=J?"SELECT ts, outcome, payload FROM processed WHERE channel_id = ? ORDER BY seq DESC LIMIT 20":"SELECT ts, outcome, payload FROM processed ORDER BY seq DESC LIMIT 20",U=J?[J]:[],B=G.query(w,U);if(G.close(),!(B instanceof Error))X.recentEvents=B.map((D)=>{let q=typeof D.ts==="number"?D.ts:0,F=typeof D.outcome==="string"?D.outcome:"",P=typeof D.payload==="string"?D.payload:null,L=P?P.slice(0,120):null;return{ts:q,outcome:F,payload:P,preview:L}})}return X};var XP6="/sandbox/.funnel",zP6="/sandbox/tmp",ZP6=()=>{};class II{props;memos={};constructor($={}){this.props=$;Object.freeze(this)}static inMemory($={}){return new II({store:$.store??new rl,fs:$.fs??new ml,process:$.process??new nl,logger:$.logger??new ll,clock:$.clock??new sl,idGenerator:$.idGenerator??new pl,dir:$.dir??XP6,tmpDir:$.tmpDir??zP6})}get paths(){let $=this.props.dir??r$1(),Y=this.props.tmpDir??o8();return{dir:$,tmpDir:Y,settings:QP6($,"settings.json")}}get fs(){if(!this.memos.fs)this.memos.fs=this.props.fs??new h8;return this.memos.fs}get process(){if(!this.memos.process)this.memos.process=this.props.process??new x$;return this.memos.process}get logger(){return this.props.logger}get clock(){if(!this.memos.clock)this.memos.clock=this.props.clock??new zK;return this.memos.clock}get onError(){return this.props.onError??ZP6}get idGenerator(){if(!this.memos.idGenerator)this.memos.idGenerator=this.props.idGenerator??new WY;return this.memos.idGenerator}get store(){if(!this.memos.store)this.memos.store=this.props.store??new ST({path:this.paths.settings,fs:this.fs,idGenerator:this.idGenerator});return this.memos.store}get factory(){if(!this.memos.factory)this.memos.factory=new ul({fs:this.fs,process:this.process,logger:this.logger,diagnosticLog:this.props.diagnosticLog,dir:this.paths.dir,slackListenerOptions:this.props.slackListenerOptions,scheduleListenerOptions:this.props.scheduleListenerOptions});return this.memos.factory}get channels(){if(!this.memos.channels)this.memos.channels=new hl({store:this.store,factory:this.factory,profileChecker:this.profiles,clock:this.clock,idGenerator:this.idGenerator});return this.memos.channels}get profiles(){if(!this.memos.profiles)this.memos.profiles=new dl({store:this.store,idGenerator:this.idGenerator});return this.memos.profiles}get localConfig(){if(!this.memos.localConfig)this.memos.localConfig=new _H({fs:this.fs});return this.memos.localConfig}get localConfigWriter(){if(!this.memos.localConfigWriter)this.memos.localConfigWriter=new RH({fs:this.fs});return this.memos.localConfigWriter}get tokenPrompter(){if(!this.memos.tokenPrompter)this.memos.tokenPrompter=this.props.tokenPrompter??new ol;return this.memos.tokenPrompter}get localConfigSync(){if(!this.memos.localConfigSync)this.memos.localConfigSync=new il({channels:this.channels,prompter:this.tokenPrompter});return this.memos.localConfigSync}get mcp(){if(!this.memos.mcp)this.memos.mcp=new RT({fs:this.fs});return this.memos.mcp}get claude(){if(!this.memos.claude)this.memos.claude=new gl({channels:this.channels,mcp:this.mcp,gateway:this.gateway,profiles:this.profiles,fs:this.fs,process:this.process,idGenerator:this.idGenerator,logger:this.logger,dir:this.paths.dir});return this.memos.claude}get gateway(){if(!this.memos.gateway)this.memos.gateway=new el({fs:this.fs,process:this.process,clock:this.clock,dir:this.paths.dir,tmpDir:this.paths.tmpDir});return this.memos.gateway}get gatewayToken(){if(!this.memos.gatewayToken)this.memos.gatewayToken=new Wn({fs:this.fs,dir:this.paths.dir});return this.memos.gatewayToken}get publisher(){if(!this.memos.publisher){let $=this.gateway,Y=this.gatewayToken;this.memos.publisher=new tl({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>Y.read()})}return this.memos.publisher}get listeners(){if(!this.memos.listeners){let $=this.gateway,Y=this.gatewayToken;this.memos.listeners=new Hn({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>Y.read()})}return this.memos.listeners}gatewayServer($={}){return new Kn({channels:this.channels,settings:this.store,port:$.port,hostname:$.hostname,dbPath:$.dbPath,eventLog:$.eventLog,process:this.process,clock:this.clock,logger:this.logger,onError:this.onError,dir:this.paths.dir,killCompetingSlack:$.killCompetingSlack,token:$.token??this.gatewayToken.ensure(),extraRoutes:$.extraRoutes})}async debug($){return B10({gateway:this.gateway,channels:this.channels,tmpDir:this.paths.tmpDir},$??null)}gatewayClient(){let{port:$}=this.gateway.getStatus();return tT(`http://127.0.0.1:${$}`)}}process.title="funnel";var WP6=9743;if(!process.env.FUNNEL_PORT)process.env.FUNNEL_PORT=String(WP6);var q10=new h8,D10=mo({localConfig:new _H({fs:q10}),writer:new RH({fs:q10}),idGenerator:new WY,home:KP6()},process.cwd());if(D10)process.env.FUNNEL_DIR=D10;var Un=new II({logger:new bH}),F10={funnel:Un},wn=`funnel \u2014 Open Claude Funnel
|
|
1118
|
+
`),Y}getPath(){return this.path}}var vz8=U10(dj6(),".funnel",x10);var tj6=N.object({channelName:N.string(),channelId:N.string(),name:N.string(),type:N.string(),alive:N.boolean()}),ej6=N.object({listeners:N.array(tj6)}),$P6=N.object({reason:N.string().optional()}),Vn={state:"offline"};class Hn{port;isDaemonRunning;getToken;constructor($){this.port=$.port,this.isDaemonRunning=$.isDaemonRunning,this.getToken=$.getToken??(()=>null),Object.freeze(this)}async list(){if(!this.isDaemonRunning())return{state:"offline"};try{let $=await fetch(`http://127.0.0.1:${this.port}/listeners`,{headers:this.authHeaders()});if(!$.ok)return{state:"error",reason:`HTTP ${$.status}`};let Y=ej6.safeParse(await $.json());if(!Y.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",listeners:Y.data.listeners}}catch($){return{state:"error",reason:$ instanceof Error?$.message:String($)}}}async start($,Y){if(!this.isDaemonRunning())return Vn;return await this.call("POST",`/listeners/${this.path($,Y)}/start`)}async stop($,Y){if(!this.isDaemonRunning())return Vn;return await this.call("DELETE",`/listeners/${this.path($,Y)}`)}async restart($,Y){if(!this.isDaemonRunning())return Vn;return await this.call("POST",`/listeners/${this.path($,Y)}/restart`)}path($,Y){return`${encodeURIComponent($)}/${encodeURIComponent(Y)}`}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}async call($,Y){try{let Q=await fetch(`http://127.0.0.1:${this.port}${Y}`,{method:$,headers:this.authHeaders()});if(!Q.ok){let X=$P6.safeParse(await Q.json().catch(()=>null));return{state:"error",reason:(X.success?X.data.reason:void 0)??`HTTP ${Q.status}`}}return{state:"ok"}}catch(Q){return{state:"error",reason:Q instanceof Error?Q.message:String(Q)}}}}import{existsSync as Gn}from"fs";import{join as Jn}from"path";var YP6=($)=>{if($===null||typeof $!=="object")return!1;if(!("clients"in $)||!Array.isArray($.clients))return!1;if(!("listeners"in $)||!Array.isArray($.listeners))return!1;return!0},B10=async($,Y)=>{let Q=$.gateway.getStatus(),X={gateway:{running:Q.running,pid:Q.pid,port:Q.running?Q.port:null,uptimeMs:null},channels:[],recentEvents:null},z=$.channels.list(),Z=Y?z.filter((G)=>G.name===Y):z,K=null;if(Q.running){let G=await fetch(`http://127.0.0.1:${Q.port}/status`).catch(()=>null);if(G&&G.ok){let J=await G.json();if(YP6(J))K=J,X.gateway.uptimeMs=J.uptimeMs}}for(let G of Z){let J=K?.listeners.find((B)=>B.channelName===G.name)??null,w=J?{alive:J.alive,events:J.events,errors:J.errors,lastEventAt:J.lastEventAt}:null,U=(K?.clients??[]).filter((B)=>!B.tapAll&&(B.channelName===G.name||B.channel===G.name));X.channels.push({name:G.name,connectors:G.connectors.map((B)=>B.name),listener:w,claudeConnected:U.length>0,claudeClientCount:U.length})}let W=Jn($.tmpDir,"connector-raw.db"),V=Jn($.tmpDir,"connector-processed.db"),H=Jn($.tmpDir,"connector-connection.db");if(Gn(W)&&Gn(V)&&Gn(H)){let G=new U$({rawPath:W,processedPath:V,connectionPath:H}),J=Y?z.find((D)=>D.name===Y)?.id??null:null,w=J?"SELECT ts, outcome, payload FROM processed WHERE channel_id = ? ORDER BY seq DESC LIMIT 20":"SELECT ts, outcome, payload FROM processed ORDER BY seq DESC LIMIT 20",U=J?[J]:[],B=G.query(w,U);if(G.close(),!(B instanceof Error))X.recentEvents=B.map((D)=>{let q=typeof D.ts==="number"?D.ts:0,F=typeof D.outcome==="string"?D.outcome:"",P=typeof D.payload==="string"?D.payload:null,L=P?P.slice(0,120):null;return{ts:q,outcome:F,payload:P,preview:L}})}return X};var XP6="/sandbox/.funnel",zP6="/sandbox/tmp",ZP6=()=>{};class II{props;memos={};constructor($={}){this.props=$;Object.freeze(this)}static inMemory($={}){return new II({store:$.store??new rl,fs:$.fs??new ml,process:$.process??new nl,logger:$.logger??new ll,clock:$.clock??new sl,idGenerator:$.idGenerator??new pl,dir:$.dir??XP6,tmpDir:$.tmpDir??zP6})}get paths(){let $=this.props.dir??r$1(),Y=this.props.tmpDir??o8();return{dir:$,tmpDir:Y,settings:QP6($,"settings.json")}}get fs(){if(!this.memos.fs)this.memos.fs=this.props.fs??new h8;return this.memos.fs}get process(){if(!this.memos.process)this.memos.process=this.props.process??new x$;return this.memos.process}get logger(){return this.props.logger}get clock(){if(!this.memos.clock)this.memos.clock=this.props.clock??new zK;return this.memos.clock}get onError(){return this.props.onError??ZP6}get idGenerator(){if(!this.memos.idGenerator)this.memos.idGenerator=this.props.idGenerator??new WY;return this.memos.idGenerator}get store(){if(!this.memos.store)this.memos.store=this.props.store??new ST({path:this.paths.settings,fs:this.fs,idGenerator:this.idGenerator});return this.memos.store}get factory(){if(!this.memos.factory)this.memos.factory=new ul({fs:this.fs,process:this.process,logger:this.logger,diagnosticLog:this.props.diagnosticLog,dir:this.paths.dir,slackListenerOptions:this.props.slackListenerOptions,scheduleListenerOptions:this.props.scheduleListenerOptions});return this.memos.factory}get channels(){if(!this.memos.channels)this.memos.channels=new hl({store:this.store,factory:this.factory,profileChecker:this.profiles,clock:this.clock,idGenerator:this.idGenerator});return this.memos.channels}get profiles(){if(!this.memos.profiles)this.memos.profiles=new dl({store:this.store,idGenerator:this.idGenerator});return this.memos.profiles}get localConfig(){if(!this.memos.localConfig)this.memos.localConfig=new _H({fs:this.fs});return this.memos.localConfig}get localConfigWriter(){if(!this.memos.localConfigWriter)this.memos.localConfigWriter=new RH({fs:this.fs});return this.memos.localConfigWriter}get tokenPrompter(){if(!this.memos.tokenPrompter)this.memos.tokenPrompter=this.props.tokenPrompter??new ol;return this.memos.tokenPrompter}get localConfigSync(){if(!this.memos.localConfigSync)this.memos.localConfigSync=new il({channels:this.channels,prompter:this.tokenPrompter});return this.memos.localConfigSync}get mcp(){if(!this.memos.mcp)this.memos.mcp=new RT({fs:this.fs});return this.memos.mcp}get claude(){if(!this.memos.claude)this.memos.claude=new gl({channels:this.channels,mcp:this.mcp,gateway:this.gateway,profiles:this.profiles,fs:this.fs,process:this.process,idGenerator:this.idGenerator,logger:this.logger,dir:this.paths.dir});return this.memos.claude}get gateway(){if(!this.memos.gateway)this.memos.gateway=new el({fs:this.fs,process:this.process,clock:this.clock,dir:this.paths.dir,tmpDir:this.paths.tmpDir,port:this.props.port});return this.memos.gateway}get gatewayToken(){if(!this.memos.gatewayToken)this.memos.gatewayToken=new Wn({fs:this.fs,dir:this.paths.dir});return this.memos.gatewayToken}get publisher(){if(!this.memos.publisher){let $=this.gateway,Y=this.gatewayToken;this.memos.publisher=new tl({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>Y.read()})}return this.memos.publisher}get listeners(){if(!this.memos.listeners){let $=this.gateway,Y=this.gatewayToken;this.memos.listeners=new Hn({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>Y.read()})}return this.memos.listeners}gatewayServer($={}){return new Kn({channels:this.channels,settings:this.store,port:$.port,hostname:$.hostname,dbPath:$.dbPath,eventLog:$.eventLog,process:this.process,clock:this.clock,logger:this.logger,onError:this.onError,dir:this.paths.dir,killCompetingSlack:$.killCompetingSlack,token:$.token??this.gatewayToken.ensure(),extraRoutes:$.extraRoutes})}async debug($){return B10({gateway:this.gateway,channels:this.channels,tmpDir:this.paths.tmpDir},$??null)}gatewayClient(){let{port:$}=this.gateway.getStatus();return tT(`http://127.0.0.1:${$}`)}}process.title="funnel";var WP6=9743;if(!process.env.FUNNEL_PORT)process.env.FUNNEL_PORT=String(WP6);var q10=new h8,D10=mo({localConfig:new _H({fs:q10}),writer:new RH({fs:q10}),idGenerator:new WY,home:KP6()},process.cwd());if(D10)process.env.FUNNEL_DIR=D10;var Un=new II({logger:new bH}),F10={funnel:Un},wn=`funnel \u2014 Open Claude Funnel
|
|
1119
1119
|
|
|
1120
1120
|
usage: funnel [command]
|
|
1121
1121
|
|
package/dist/gateway/daemon.js
CHANGED
|
@@ -574,5 +574,5 @@ FROM processeddb.leuco_log`,ge0=`CREATE TEMP VIEW connection AS SELECT
|
|
|
574
574
|
json_extract(event, '$.status') AS status,
|
|
575
575
|
json_extract(event, '$.detail') AS detail
|
|
576
576
|
FROM connectiondb.leuco_log`;var pe0=($)=>{if(typeof $!=="string"||$.length===0)return null;try{let x=JSON.parse($);if(x!==null&&typeof x==="object"&&"text"in x){let Y=String(x.text);return Y.length>80?`${Y.slice(0,80)}\u2026`:Y}}catch{return $.length>80?`${$.slice(0,80)}\u2026`:$}return $.length>80?`${$.slice(0,80)}\u2026`:$},ie0=($)=>{let Y=($.connectionErrors[$.connectionErrors.length-1]??null)?.detail??null;if($.connectors.length===0)return{status:"warn",message:"no connectors configured on this channel",nextActions:[`fnl channels ${$.name} connectors add <name> --type=slack ...`],rootCause:null};if(!$.listener)return{status:"error",message:"no listener running for this channel",nextActions:["fnl gateway restart"],rootCause:Y};if(!$.listener.alive)return{status:"error",message:"listener is dead",nextActions:["fnl gateway logs","fnl gateway restart"],rootCause:Y};if($.claudeClients===0)return{status:"warn",message:"no Claude connected to this channel",nextActions:[`fnl claude --channel ${$.name}`],rootCause:null};if($.listener.errors>0)return{status:"warn",message:"listener has errors",nextActions:["fnl gateway logs"],rootCause:Y};return{status:"ok",message:"healthy",nextActions:[],rootCause:null}},fE1=E6.createHandlers(async($)=>{let x=$.var.deps,Y=$.req.query("channel")??null,Q=x.channels.list(),X=Y?Q.filter((q)=>q.name===Y||q.id===Y):Q,Z=x.supervisor.list(),z=x.broadcaster.listChannels(),K=x.broadcaster.getMetrics(),W=B9(),V=mu(W,"connector-raw.db"),U=mu(W,"connector-processed.db"),w=mu(W,"connector-connection.db"),H=yu(V)&&yu(U)&&yu(w),J=X.map((q)=>{let D=Z.find((C)=>C.channelName===q.name)??null,B=D?{alive:D.alive,events:D.events,errors:D.errors,lastEventAt:D.lastEventAt}:null,F=z.filter((C)=>C.channel===q.id||C.channel===q.name).length,j=[],N=[];if(H){let C=new wK({rawPath:V,processedPath:U,connectionPath:w}),l=(()=>{try{return C.query("SELECT seq, ts, type, outcome, payload FROM processed WHERE channel_id = ? ORDER BY seq DESC LIMIT 10",[q.id])}finally{C.close()}})();if(!(l instanceof Error))for(let U1 of[...l].reverse()){let g=typeof U1.payload==="string"?U1.payload:null,p=null;if(g)try{let x1=JSON.parse(g);if(x1!==null&&typeof x1==="object"&&!Array.isArray(x1))p=x1}catch{p=null}j.push({seq:typeof U1.seq==="number"?U1.seq:null,ts:typeof U1.ts==="number"?U1.ts:null,type:typeof U1.type==="string"?U1.type:"?",outcome:typeof U1.outcome==="string"?U1.outcome:"?",payload:g,payloadParsed:p,preview:pe0(U1.payload)})}if(B&&(!B.alive||B.errors>0)||!B){let U1=new wK({rawPath:V,processedPath:U,connectionPath:w}),g=(()=>{try{return U1.query("SELECT ts, type, status, detail FROM connection WHERE channel_id = ? AND status IN ('auth-failed','error') ORDER BY seq DESC LIMIT 3",[q.id])}finally{U1.close()}})();if(!(g instanceof Error))for(let p of[...g].reverse())N.push({ts:typeof p.ts==="number"?p.ts:null,type:typeof p.type==="string"?p.type:"?",status:typeof p.status==="string"?p.status:"?",detail:typeof p.detail==="string"&&p.detail.length>0?p.detail:null})}}let b={id:q.id,name:q.name,connectors:q.connectors.map((C)=>C.name),listener:B,claudeClients:F,recentEvents:j,connectionErrors:N};return{...b,diagnosis:ie0(b)}});return $.json({pid:x.selfPid,uptimeMs:x.uptimeMs(),eventsBroadcast:K.eventsBroadcast,channels:J})});var kE1=E6.createHandlers(($)=>{let x=$.var.deps;return $.json({ok:!0,pid:x.selfPid,clients:x.broadcaster.getClientCount(),listeners:x.supervisor.list()})});var TE1=E6.createHandlers(($)=>{return $.json({listeners:$.var.deps.supervisor.list()})});var SE1=E6.createHandlers($2(E.object({channel:E.string().min(1),connector:E.string().min(1)})),async($)=>{let x=$.req.valid("param"),Y=await $.var.deps.supervisor.restart(x.channel,x.connector);return $.json(Y,Y.ok?200:400)});var cE1=E6.createHandlers($2(E.object({channel:E.string().min(1),connector:E.string().min(1)})),async($)=>{let x=$.req.valid("param"),Y=await $.var.deps.supervisor.start(x.channel,x.connector);return $.json(Y,Y.ok?200:400)});var EE1=E6.createHandlers($2(E.object({channel:E.string().min(1),connector:E.string().min(1)})),async($)=>{let x=$.req.valid("param"),Y=await $.var.deps.supervisor.stop(x.channel,x.connector);return $.json(Y,Y.ok?200:400)});var CE1=E6.createHandlers(($)=>{let x=$.var.deps;return $.json({ok:!0,pid:x.selfPid,uptimeMs:x.uptimeMs(),clients:x.broadcaster.listChannels(),listeners:x.supervisor.list(),broadcaster:x.broadcaster.getMetrics()})});function le0(){return E6.createApp().get("/health",...kE1).get("/status",...CE1).get("/debug",...fE1).get("/listeners",...TE1).post("/listeners/:channel/:connector/start",...cE1).delete("/listeners/:channel/:connector",...EE1).post("/listeners/:channel/:connector/restart",...SE1).post("/channels/:channel/connectors/:connector/call",...AE1).post("/channels/:channel/publish",...RE1)}var uE1=le0();var oe0="127.0.0.1",re0=new Set(["127.0.0.1","localhost","::1","::ffff:127.0.0.1"]),te0=()=>se0(B9(),"events.db"),ee0=()=>{};class hu{channels;settings;port;hostname;dbPath;process;logger;onError;selfPid;dir;killCompetingSlack;token;broadcaster;eventLog;supervisor;nowMs;extraRoutes;startedAt=null;server=null;constructor($){this.channels=$.channels,this.settings=$.settings,this.port=$.port??Jx(),this.hostname=$.hostname??oe0,this.dbPath=$.dbPath??te0(),this.process=$.process,this.logger=$.logger,this.onError=$.onError??ee0,this.selfPid=$.selfPid??globalThis.process.pid,this.dir=$.dir??d9,this.killCompetingSlack=$.killCompetingSlack??!0,this.token=$.token??"",this.extraRoutes=$.extraRoutes??null;let x=$.clock;if(this.nowMs=x?()=>x.millis():()=>Date.now(),$.eventLog)this.eventLog=$.eventLog;else{let Y=ae0(this.dbPath);if(!ne0(Y))de0(Y,{recursive:!0});this.eventLog=new Cu({path:this.dbPath,now:this.nowMs})}this.broadcaster=new cu({logger:this.logger,onError:this.onError,now:this.nowMs,persistentReplay:this.eventLog}),this.broadcaster.seedLatestOffset(this.eventLog.findMaxOffset()),this.supervisor=new UX({channels:this.channels,logger:this.logger,onError:this.onError,notify:async(Y,Q,X,Z)=>{this.emit({channel:Y,connector:Q,content:X,meta:Z})},now:this.nowMs})}async start(){if(this.server)return this.server;if(!this.token&&!re0.has(this.hostname))this.logger?.warn("gateway auth is disabled on a non-loopback bind \u2014 every endpoint is reachable without a token",{hostname:this.hostname});let $=this.buildApp();return this.startedAt=this.nowMs(),this.server=Bun.serve({port:this.port,hostname:this.hostname,development:!1,fetch:(x,Y)=>this.handleFetch(x,Y,$),websocket:{open:(x)=>this.handleWsOpen(x),close:(x)=>this.handleWsClose(x),message(){}}}),this.logServerStarted(),await this.bootListeners(),this.server}async stop(){if(await this.supervisor.stopAll(),this.server)this.server.stop(),this.server=null}getStatus(){return{clients:this.broadcaster.getClientCount(),channels:this.broadcaster.listChannels()}}getBroadcaster(){return this.broadcaster}getSupervisor(){return this.supervisor}getEventLog(){return this.eventLog}onEvent($){return this.broadcaster.subscribe($)}handleFetch($,x,Y){let Q=new URL($.url);if(Q.pathname==="/ws"&&$.headers.get("upgrade")==="websocket"){if(this.token&&!this.tokenMatchesUpgrade($))return new Response("unauthorized",{status:401});let X=Q.searchParams.get("tap")==="all",Z=X?"":Q.searchParams.get("channel")??"",z=!X&&Z?this.resolveChannel(Z):null,K=X?"":z?.id??Z,W=X?null:z?.name??null,V=z?.connectors??[],U=z?.delivery??"fanout",w=Q.searchParams.get("since"),H=w===null?Number.NaN:Number.parseInt(w,10),J=Number.isFinite(H)&&H>=0?H:void 0,q=Q.searchParams.get("id")??void 0;if(x.upgrade($,{data:{channel:K,channelName:W,connectors:V,tapAll:X,delivery:U,subscriberId:q,since:J}}))return;return new Response("WebSocket upgrade failed",{status:400})}return Y.fetch($)}handleWsOpen($){if(typeof $.data.since==="number"){let x=this.broadcaster.replaySince($.data.since,$.data);for(let Y of x)$.send(JSON.stringify(Y))}if(this.broadcaster.addClient($,$.data),$.data.channelName){let x={event_type:"system",action:"channel_connect",channel:$.data.channelName,channelId:$.data.channel,connectors:$.data.connectors.join(","),total:String(this.broadcaster.getClientCount())};this.logger?.info("channel connected",x)}else this.logger?.info("tap-all client connected",{event_type:"system",action:"tap_connect",total:String(this.broadcaster.getClientCount())})}handleWsClose($){if(this.broadcaster.removeClient($),$.data.channelName)this.logger?.info("channel disconnected",{event_type:"system",action:"channel_disconnect",channel:$.data.channelName,channelId:$.data.channel,total:String(this.broadcaster.getClientCount())});else this.logger?.info("tap-all client disconnected",{event_type:"system",action:"tap_disconnect",total:String(this.broadcaster.getClientCount())})}logServerStarted(){this.logger?.info("gateway started",{event_type:"system",action:"gateway_start",port:String(this.port),pid:String(this.selfPid)}),this.logger?.info("funnel gateway listening",{url:`http://localhost:${this.port}`,websocket:`ws://localhost:${this.port}/ws`,health:`http://localhost:${this.port}/health`})}buildApp(){let $=E6.createApp();if($.use((Y,Q)=>{return Y.set("deps",{selfPid:this.selfPid,broadcaster:this.broadcaster,supervisor:this.supervisor,channels:this.channels,uptimeMs:()=>this.startedAt?this.nowMs()-this.startedAt:0,emit:(X)=>this.emit(X)}),Q()}),this.token)$.use("/listeners/*",dV({expected:this.token})),$.use("/status",dV({expected:this.token})),$.use("/debug",dV({expected:this.token})),$.use("/channels/*",dV({expected:this.token}));return(this.extraRoutes?$.route("/",this.extraRoutes):$).route("/",uE1)}tokenMatchesUpgrade($){let x=($.headers.get("sec-websocket-protocol")??"").split(",").map((X)=>X.trim()).filter((X)=>X.length>0);for(let X of x)if(X.startsWith("funnel.token.")&&IF(X.slice(13),this.token))return!0;let Q=($.headers.get("authorization")??"").match(/^Bearer\s+(.+)$/i);if(Q&&IF(Q[1]??"",this.token))return!0;return!1}resolveChannel($){let Y=this.settings.read()?.channels.find((Q)=>Q.id===$||Q.name===$);if(!Y)return null;return{id:Y.id,name:Y.name,connectors:Y.connectors.map((Q)=>Q.name),delivery:Y.delivery}}async bootListeners(){let $=this.channels.listAllConnectors();if(this.killCompetingSlack&&$.some((x)=>x.type==="slack")){let x=await _E1({selfPid:this.selfPid,dir:this.dir,process:this.process,logger:this.logger});if(x.length>0)this.logger?.info("killed competing Slack gateway processes",{event_type:"system",action:"kill_competing",pids:x.join(",")})}await this.supervisor.startAll();for(let x of this.supervisor.list())this.logger?.info(`${x.type} listener started: ${x.name}`,{event_type:"system",action:`${x.type}_connect`,channel:x.channelName,connector:x.name});this.logger?.info(`event store: ${this.dbPath}`),this.logger?.info("funnel gateway running")}emit($){let x=this.lookupChannelId($.channel),Y=x&&$.connector?this.lookupConnectorId(x,$.connector):null,Q={...$.meta,channel:$.channel};if($.connector)Q.connector=$.connector;if(x)Q.channelId=x;if(Y)Q.connectorId=Y;let X=this.broadcaster.broadcast($.content,Q);return this.eventLog.record({content:$.content,channelId:x??null,connectorId:Y??null,meta:Q,offset:X.offset}),{offset:X.offset}}lookupChannelId($){return this.settings.read().channels.find((Y)=>Y.name===$)?.id??null}lookupConnectorId($,x){return this.settings.read().channels.find((X)=>X.id===$)?.connectors.find((X)=>X.name===x)?.id??null}}import{homedir as $16}from"os";import{dirname as x16,join as yE1}from"path";var mE1="gateway.token",Y16=32,Q16=new M8,X16=()=>{let $=new Uint8Array(Y16);return crypto.getRandomValues($),[...$].map((x)=>x.toString(16).padStart(2,"0")).join("")};class gu{fs;path;generate;constructor($={}){this.fs=$.fs??Q16,this.path=yE1($.dir??d9,mE1),this.generate=$.generate??X16,Object.freeze(this)}read(){if(!this.fs.existsSync(this.path))return null;let $=this.fs.readFileSync(this.path).trim();return $.length>0?$:null}ensure(){let $=this.read();if($)return $;let x=this.generate();return this.fs.mkdirSync(x16(this.path),{recursive:!0}),this.fs.writeSecretFileSync(this.path,`${x}
|
|
577
|
-
`),x}getPath(){return this.path}}var ON6=yE1($16(),".funnel",mE1);var Z16=E.object({channelName:E.string(),channelId:E.string(),name:E.string(),type:E.string(),alive:E.boolean()}),z16=E.object({listeners:E.array(Z16)}),K16=E.object({reason:E.string().optional()}),pu={state:"offline"};class iu{port;isDaemonRunning;getToken;constructor($){this.port=$.port,this.isDaemonRunning=$.isDaemonRunning,this.getToken=$.getToken??(()=>null),Object.freeze(this)}async list(){if(!this.isDaemonRunning())return{state:"offline"};try{let $=await fetch(`http://127.0.0.1:${this.port}/listeners`,{headers:this.authHeaders()});if(!$.ok)return{state:"error",reason:`HTTP ${$.status}`};let x=z16.safeParse(await $.json());if(!x.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",listeners:x.data.listeners}}catch($){return{state:"error",reason:$ instanceof Error?$.message:String($)}}}async start($,x){if(!this.isDaemonRunning())return pu;return await this.call("POST",`/listeners/${this.path($,x)}/start`)}async stop($,x){if(!this.isDaemonRunning())return pu;return await this.call("DELETE",`/listeners/${this.path($,x)}`)}async restart($,x){if(!this.isDaemonRunning())return pu;return await this.call("POST",`/listeners/${this.path($,x)}/restart`)}path($,x){return`${encodeURIComponent($)}/${encodeURIComponent(x)}`}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}async call($,x){try{let Y=await fetch(`http://127.0.0.1:${this.port}${x}`,{method:$,headers:this.authHeaders()});if(!Y.ok){let Q=K16.safeParse(await Y.json().catch(()=>null));return{state:"error",reason:(Q.success?Q.data.reason:void 0)??`HTTP ${Y.status}`}}return{state:"ok"}}catch(Y){return{state:"error",reason:Y instanceof Error?Y.message:String(Y)}}}}import{existsSync as lu}from"fs";import{join as nu}from"path";var W16=($)=>{if($===null||typeof $!=="object")return!1;if(!("clients"in $)||!Array.isArray($.clients))return!1;if(!("listeners"in $)||!Array.isArray($.listeners))return!1;return!0},hE1=async($,x)=>{let Y=$.gateway.getStatus(),Q={gateway:{running:Y.running,pid:Y.pid,port:Y.running?Y.port:null,uptimeMs:null},channels:[],recentEvents:null},X=$.channels.list(),Z=x?X.filter((U)=>U.name===x):X,z=null;if(Y.running){let U=await fetch(`http://127.0.0.1:${Y.port}/status`).catch(()=>null);if(U&&U.ok){let w=await U.json();if(W16(w))z=w,Q.gateway.uptimeMs=w.uptimeMs}}for(let U of Z){let w=z?.listeners.find((q)=>q.channelName===U.name)??null,H=w?{alive:w.alive,events:w.events,errors:w.errors,lastEventAt:w.lastEventAt}:null,J=(z?.clients??[]).filter((q)=>!q.tapAll&&(q.channelName===U.name||q.channel===U.name));Q.channels.push({name:U.name,connectors:U.connectors.map((q)=>q.name),listener:H,claudeConnected:J.length>0,claudeClientCount:J.length})}let K=nu($.tmpDir,"connector-raw.db"),W=nu($.tmpDir,"connector-processed.db"),V=nu($.tmpDir,"connector-connection.db");if(lu(K)&&lu(W)&&lu(V)){let U=new wK({rawPath:K,processedPath:W,connectionPath:V}),w=x?X.find((D)=>D.name===x)?.id??null:null,H=w?"SELECT ts, outcome, payload FROM processed WHERE channel_id = ? ORDER BY seq DESC LIMIT 20":"SELECT ts, outcome, payload FROM processed ORDER BY seq DESC LIMIT 20",J=w?[w]:[],q=U.query(H,J);if(U.close(),!(q instanceof Error))Q.recentEvents=q.map((D)=>{let B=typeof D.ts==="number"?D.ts:0,F=typeof D.outcome==="string"?D.outcome:"",j=typeof D.payload==="string"?D.payload:null,N=j?j.slice(0,120):null;return{ts:B,outcome:F,payload:j,preview:N}})}return Q};var U16="/sandbox/.funnel",w16="/sandbox/tmp",H16=()=>{};class fF{props;memos={};constructor($={}){this.props=$;Object.freeze(this)}static inMemory($={}){return new fF({store:$.store??new Mu,fs:$.fs??new Ju,process:$.process??new ju,logger:$.logger??new Lu,clock:$.clock??new _u,idGenerator:$.idGenerator??new qu,dir:$.dir??U16,tmpDir:$.tmpDir??w16})}get paths(){let $=this.props.dir??aw(),x=this.props.tmpDir??B9();return{dir:$,tmpDir:x,settings:V16($,"settings.json")}}get fs(){if(!this.memos.fs)this.memos.fs=this.props.fs??new M8;return this.memos.fs}get process(){if(!this.memos.process)this.memos.process=this.props.process??new v8;return this.memos.process}get logger(){return this.props.logger}get clock(){if(!this.memos.clock)this.memos.clock=this.props.clock??new KX;return this.memos.clock}get onError(){return this.props.onError??H16}get idGenerator(){if(!this.memos.idGenerator)this.memos.idGenerator=this.props.idGenerator??new U2;return this.memos.idGenerator}get store(){if(!this.memos.store)this.memos.store=this.props.store??new BM({path:this.paths.settings,fs:this.fs,idGenerator:this.idGenerator});return this.memos.store}get factory(){if(!this.memos.factory)this.memos.factory=new Vu({fs:this.fs,process:this.process,logger:this.logger,diagnosticLog:this.props.diagnosticLog,dir:this.paths.dir,slackListenerOptions:this.props.slackListenerOptions,scheduleListenerOptions:this.props.scheduleListenerOptions});return this.memos.factory}get channels(){if(!this.memos.channels)this.memos.channels=new Hu({store:this.store,factory:this.factory,profileChecker:this.profiles,clock:this.clock,idGenerator:this.idGenerator});return this.memos.channels}get profiles(){if(!this.memos.profiles)this.memos.profiles=new Pu({store:this.store,idGenerator:this.idGenerator});return this.memos.profiles}get localConfig(){if(!this.memos.localConfig)this.memos.localConfig=new Bu({fs:this.fs});return this.memos.localConfig}get localConfigWriter(){if(!this.memos.localConfigWriter)this.memos.localConfigWriter=new Fu({fs:this.fs});return this.memos.localConfigWriter}get tokenPrompter(){if(!this.memos.tokenPrompter)this.memos.tokenPrompter=this.props.tokenPrompter??new vu;return this.memos.tokenPrompter}get localConfigSync(){if(!this.memos.localConfigSync)this.memos.localConfigSync=new Du({channels:this.channels,prompter:this.tokenPrompter});return this.memos.localConfigSync}get mcp(){if(!this.memos.mcp)this.memos.mcp=new Nu({fs:this.fs});return this.memos.mcp}get claude(){if(!this.memos.claude)this.memos.claude=new Gu({channels:this.channels,mcp:this.mcp,gateway:this.gateway,profiles:this.profiles,fs:this.fs,process:this.process,idGenerator:this.idGenerator,logger:this.logger,dir:this.paths.dir});return this.memos.claude}get gateway(){if(!this.memos.gateway)this.memos.gateway=new Au({fs:this.fs,process:this.process,clock:this.clock,dir:this.paths.dir,tmpDir:this.paths.tmpDir});return this.memos.gateway}get gatewayToken(){if(!this.memos.gatewayToken)this.memos.gatewayToken=new gu({fs:this.fs,dir:this.paths.dir});return this.memos.gatewayToken}get publisher(){if(!this.memos.publisher){let $=this.gateway,x=this.gatewayToken;this.memos.publisher=new Ou({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>x.read()})}return this.memos.publisher}get listeners(){if(!this.memos.listeners){let $=this.gateway,x=this.gatewayToken;this.memos.listeners=new iu({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>x.read()})}return this.memos.listeners}gatewayServer($={}){return new hu({channels:this.channels,settings:this.store,port:$.port,hostname:$.hostname,dbPath:$.dbPath,eventLog:$.eventLog,process:this.process,clock:this.clock,logger:this.logger,onError:this.onError,dir:this.paths.dir,killCompetingSlack:$.killCompetingSlack,token:$.token??this.gatewayToken.ensure(),extraRoutes:$.extraRoutes})}async debug($){return hE1({gateway:this.gateway,channels:this.channels,tmpDir:this.paths.tmpDir},$??null)}gatewayClient(){let{port:$}=this.gateway.getStatus();return vM(`http://127.0.0.1:${$}`)}}import{appendFileSync as G16,mkdirSync as J16}from"fs";import{dirname as q16,join as B16}from"path";var D16=()=>B16(B9(),"funnel.log");class du extends nV{file;now;constructor($={}){super();this.file=$.file??D16(),this.now=$.now??(()=>new Date),Object.freeze(this)}info($,x){this.write("info",$,x)}warn($,x){this.write("warn",$,x)}error($,x){this.write("error",$,x)}write($,x,Y){J16(q16(this.file),{recursive:!0});let Q={time:this.now().toISOString(),level:$,message:x,...Y?{meta:Y}:{}};G16(this.file,`${JSON.stringify(Q)}
|
|
577
|
+
`),x}getPath(){return this.path}}var ON6=yE1($16(),".funnel",mE1);var Z16=E.object({channelName:E.string(),channelId:E.string(),name:E.string(),type:E.string(),alive:E.boolean()}),z16=E.object({listeners:E.array(Z16)}),K16=E.object({reason:E.string().optional()}),pu={state:"offline"};class iu{port;isDaemonRunning;getToken;constructor($){this.port=$.port,this.isDaemonRunning=$.isDaemonRunning,this.getToken=$.getToken??(()=>null),Object.freeze(this)}async list(){if(!this.isDaemonRunning())return{state:"offline"};try{let $=await fetch(`http://127.0.0.1:${this.port}/listeners`,{headers:this.authHeaders()});if(!$.ok)return{state:"error",reason:`HTTP ${$.status}`};let x=z16.safeParse(await $.json());if(!x.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",listeners:x.data.listeners}}catch($){return{state:"error",reason:$ instanceof Error?$.message:String($)}}}async start($,x){if(!this.isDaemonRunning())return pu;return await this.call("POST",`/listeners/${this.path($,x)}/start`)}async stop($,x){if(!this.isDaemonRunning())return pu;return await this.call("DELETE",`/listeners/${this.path($,x)}`)}async restart($,x){if(!this.isDaemonRunning())return pu;return await this.call("POST",`/listeners/${this.path($,x)}/restart`)}path($,x){return`${encodeURIComponent($)}/${encodeURIComponent(x)}`}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}async call($,x){try{let Y=await fetch(`http://127.0.0.1:${this.port}${x}`,{method:$,headers:this.authHeaders()});if(!Y.ok){let Q=K16.safeParse(await Y.json().catch(()=>null));return{state:"error",reason:(Q.success?Q.data.reason:void 0)??`HTTP ${Y.status}`}}return{state:"ok"}}catch(Y){return{state:"error",reason:Y instanceof Error?Y.message:String(Y)}}}}import{existsSync as lu}from"fs";import{join as nu}from"path";var W16=($)=>{if($===null||typeof $!=="object")return!1;if(!("clients"in $)||!Array.isArray($.clients))return!1;if(!("listeners"in $)||!Array.isArray($.listeners))return!1;return!0},hE1=async($,x)=>{let Y=$.gateway.getStatus(),Q={gateway:{running:Y.running,pid:Y.pid,port:Y.running?Y.port:null,uptimeMs:null},channels:[],recentEvents:null},X=$.channels.list(),Z=x?X.filter((U)=>U.name===x):X,z=null;if(Y.running){let U=await fetch(`http://127.0.0.1:${Y.port}/status`).catch(()=>null);if(U&&U.ok){let w=await U.json();if(W16(w))z=w,Q.gateway.uptimeMs=w.uptimeMs}}for(let U of Z){let w=z?.listeners.find((q)=>q.channelName===U.name)??null,H=w?{alive:w.alive,events:w.events,errors:w.errors,lastEventAt:w.lastEventAt}:null,J=(z?.clients??[]).filter((q)=>!q.tapAll&&(q.channelName===U.name||q.channel===U.name));Q.channels.push({name:U.name,connectors:U.connectors.map((q)=>q.name),listener:H,claudeConnected:J.length>0,claudeClientCount:J.length})}let K=nu($.tmpDir,"connector-raw.db"),W=nu($.tmpDir,"connector-processed.db"),V=nu($.tmpDir,"connector-connection.db");if(lu(K)&&lu(W)&&lu(V)){let U=new wK({rawPath:K,processedPath:W,connectionPath:V}),w=x?X.find((D)=>D.name===x)?.id??null:null,H=w?"SELECT ts, outcome, payload FROM processed WHERE channel_id = ? ORDER BY seq DESC LIMIT 20":"SELECT ts, outcome, payload FROM processed ORDER BY seq DESC LIMIT 20",J=w?[w]:[],q=U.query(H,J);if(U.close(),!(q instanceof Error))Q.recentEvents=q.map((D)=>{let B=typeof D.ts==="number"?D.ts:0,F=typeof D.outcome==="string"?D.outcome:"",j=typeof D.payload==="string"?D.payload:null,N=j?j.slice(0,120):null;return{ts:B,outcome:F,payload:j,preview:N}})}return Q};var U16="/sandbox/.funnel",w16="/sandbox/tmp",H16=()=>{};class fF{props;memos={};constructor($={}){this.props=$;Object.freeze(this)}static inMemory($={}){return new fF({store:$.store??new Mu,fs:$.fs??new Ju,process:$.process??new ju,logger:$.logger??new Lu,clock:$.clock??new _u,idGenerator:$.idGenerator??new qu,dir:$.dir??U16,tmpDir:$.tmpDir??w16})}get paths(){let $=this.props.dir??aw(),x=this.props.tmpDir??B9();return{dir:$,tmpDir:x,settings:V16($,"settings.json")}}get fs(){if(!this.memos.fs)this.memos.fs=this.props.fs??new M8;return this.memos.fs}get process(){if(!this.memos.process)this.memos.process=this.props.process??new v8;return this.memos.process}get logger(){return this.props.logger}get clock(){if(!this.memos.clock)this.memos.clock=this.props.clock??new KX;return this.memos.clock}get onError(){return this.props.onError??H16}get idGenerator(){if(!this.memos.idGenerator)this.memos.idGenerator=this.props.idGenerator??new U2;return this.memos.idGenerator}get store(){if(!this.memos.store)this.memos.store=this.props.store??new BM({path:this.paths.settings,fs:this.fs,idGenerator:this.idGenerator});return this.memos.store}get factory(){if(!this.memos.factory)this.memos.factory=new Vu({fs:this.fs,process:this.process,logger:this.logger,diagnosticLog:this.props.diagnosticLog,dir:this.paths.dir,slackListenerOptions:this.props.slackListenerOptions,scheduleListenerOptions:this.props.scheduleListenerOptions});return this.memos.factory}get channels(){if(!this.memos.channels)this.memos.channels=new Hu({store:this.store,factory:this.factory,profileChecker:this.profiles,clock:this.clock,idGenerator:this.idGenerator});return this.memos.channels}get profiles(){if(!this.memos.profiles)this.memos.profiles=new Pu({store:this.store,idGenerator:this.idGenerator});return this.memos.profiles}get localConfig(){if(!this.memos.localConfig)this.memos.localConfig=new Bu({fs:this.fs});return this.memos.localConfig}get localConfigWriter(){if(!this.memos.localConfigWriter)this.memos.localConfigWriter=new Fu({fs:this.fs});return this.memos.localConfigWriter}get tokenPrompter(){if(!this.memos.tokenPrompter)this.memos.tokenPrompter=this.props.tokenPrompter??new vu;return this.memos.tokenPrompter}get localConfigSync(){if(!this.memos.localConfigSync)this.memos.localConfigSync=new Du({channels:this.channels,prompter:this.tokenPrompter});return this.memos.localConfigSync}get mcp(){if(!this.memos.mcp)this.memos.mcp=new Nu({fs:this.fs});return this.memos.mcp}get claude(){if(!this.memos.claude)this.memos.claude=new Gu({channels:this.channels,mcp:this.mcp,gateway:this.gateway,profiles:this.profiles,fs:this.fs,process:this.process,idGenerator:this.idGenerator,logger:this.logger,dir:this.paths.dir});return this.memos.claude}get gateway(){if(!this.memos.gateway)this.memos.gateway=new Au({fs:this.fs,process:this.process,clock:this.clock,dir:this.paths.dir,tmpDir:this.paths.tmpDir,port:this.props.port});return this.memos.gateway}get gatewayToken(){if(!this.memos.gatewayToken)this.memos.gatewayToken=new gu({fs:this.fs,dir:this.paths.dir});return this.memos.gatewayToken}get publisher(){if(!this.memos.publisher){let $=this.gateway,x=this.gatewayToken;this.memos.publisher=new Ou({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>x.read()})}return this.memos.publisher}get listeners(){if(!this.memos.listeners){let $=this.gateway,x=this.gatewayToken;this.memos.listeners=new iu({port:$.getPort(),isDaemonRunning:()=>$.isRunning(),getToken:()=>x.read()})}return this.memos.listeners}gatewayServer($={}){return new hu({channels:this.channels,settings:this.store,port:$.port,hostname:$.hostname,dbPath:$.dbPath,eventLog:$.eventLog,process:this.process,clock:this.clock,logger:this.logger,onError:this.onError,dir:this.paths.dir,killCompetingSlack:$.killCompetingSlack,token:$.token??this.gatewayToken.ensure(),extraRoutes:$.extraRoutes})}async debug($){return hE1({gateway:this.gateway,channels:this.channels,tmpDir:this.paths.tmpDir},$??null)}gatewayClient(){let{port:$}=this.gateway.getStatus();return vM(`http://127.0.0.1:${$}`)}}import{appendFileSync as G16,mkdirSync as J16}from"fs";import{dirname as q16,join as B16}from"path";var D16=()=>B16(B9(),"funnel.log");class du extends nV{file;now;constructor($={}){super();this.file=$.file??D16(),this.now=$.now??(()=>new Date),Object.freeze(this)}info($,x){this.write("info",$,x)}warn($,x){this.write("warn",$,x)}error($,x){this.write("error",$,x)}write($,x,Y){J16(q16(this.file),{recursive:!0});let Q={time:this.now().toISOString(),level:$,message:x,...Y?{meta:Y}:{}};G16(this.file,`${JSON.stringify(Q)}
|
|
578
578
|
`)}}import{chmodSync as L16}from"fs";var F16=["started","connected","disconnected","auth-failed","stopped","error"],Dj6=E.object({event_id:E.string(),type:E.string(),connector_id:E.string().nullable(),channel_id:E.string().nullable(),payload:E.string()}),Fj6=E.object({event_id:E.string(),type:E.string(),connector_id:E.string().nullable(),channel_id:E.string().nullable(),outcome:E.string(),payload:E.string()}),gE1=E.object({type:E.string(),connector_id:E.string().nullable(),channel_id:E.string().nullable(),status:E.enum(F16),detail:E.string()});class au{}var N16=262144;class ru extends au{raw;processed;connection;now;logger;constructor($){super();this.now=$.now??(()=>Date.now()),this.logger=$.logger;let x=$.maxAgeMs!==void 0?{maxAgeMs:$.maxAgeMs}:{},Y={now:this.now,...x,...$.maxRows!==void 0?{maxRows:$.maxRows}:{}},Q=$.rawMaxRows??$.maxRows,X={now:this.now,...x,...Q!==void 0?{maxRows:Q}:{}};this.raw=new VX({path:$.rawPath,indexes:["event_id","connector_id","channel_id"],extractIndexes:(Z)=>({event_id:Z.event_id,connector_id:Z.connector_id,channel_id:Z.channel_id}),...X}),this.processed=new VX({path:$.processedPath,indexes:["event_id","connector_id","channel_id","outcome"],extractIndexes:(Z)=>({event_id:Z.event_id,connector_id:Z.connector_id,channel_id:Z.channel_id,outcome:Z.outcome}),...Y}),this.connection=new VX({path:$.connectionPath,indexes:["connector_id","channel_id","status"],extractIndexes:(Z)=>({connector_id:Z.connector_id,channel_id:Z.channel_id,status:Z.status}),...Y}),su($.rawPath),su($.processedPath),su($.connectionPath),Object.freeze(this)}recordRaw($){let x={event_id:$.eventId,type:$.type,connector_id:$.connectorId,channel_id:$.channelId,payload:I16($.payload,$.type)};this.report("raw",this.raw.insert({ts:this.now(),event:x}))}recordProcessed($){let x={event_id:$.eventId,type:$.type,connector_id:$.connectorId,channel_id:$.channelId,outcome:$.outcome,payload:$.payload};this.report("processed",this.processed.insert({ts:this.now(),event:x}))}recordConnection($){let x={type:$.type,connector_id:$.connectorId,channel_id:$.channelId,status:$.status,detail:$.detail};this.report("connection",this.connection.insert({ts:this.now(),event:x}))}report($,x){if(x instanceof Error)this.logger?.error("diagnostic log insert failed",{table:$,error:x.message})}queryRaw($){return this.raw.getRecords({...$.type!==void 0?{type:$.type}:{},...$.limit!==void 0?{limit:$.limit}:{},where:ou($),order:"desc"}).map((Y)=>({seq:Y.seq,ts:Y.ts,eventId:Y.event.event_id,type:Y.event.type,connectorId:Y.event.connector_id,channelId:Y.event.channel_id,payload:Y.event.payload}))}queryProcessed($){let x=ou($);if($.outcome!==void 0)x.outcome=$.outcome;return this.processed.getRecords({...$.type!==void 0?{type:$.type}:{},...$.limit!==void 0?{limit:$.limit}:{},where:x,order:"desc"}).map((Q)=>({seq:Q.seq,ts:Q.ts,eventId:Q.event.event_id,type:Q.event.type,connectorId:Q.event.connector_id,channelId:Q.event.channel_id,outcome:Q.event.outcome,payload:Q.event.payload}))}queryConnection($){let x=ou($);if($.status!==void 0)x.status=$.status;return this.connection.getRecords({...$.type!==void 0?{type:$.type}:{},...$.limit!==void 0?{limit:$.limit}:{},where:x,order:"desc"}).map((Q)=>({seq:Q.seq,ts:Q.ts,type:Q.event.type,connectorId:Q.event.connector_id,channelId:Q.event.channel_id,status:P16(Q.event.status),detail:Q.event.detail}))}clear(){this.raw.clear(),this.processed.clear(),this.connection.clear()}close(){this.raw.close(),this.processed.close(),this.connection.close()}}var su=($)=>{if($===":memory:")return;for(let x of["","-wal","-shm"])try{L16(`${$}${x}`,384)}catch{}},ou=($)=>{let x={};if($.connectorId!==void 0)x.connector_id=$.connectorId;if($.channelId!==void 0)x.channel_id=$.channelId;return x},j16=gE1.shape.status,P16=($)=>{let x=j16.safeParse($);return x.success?x.data:"error"},I16=($,x)=>{let Y=Buffer.byteLength($,"utf8");if(Y<=N16)return $;return JSON.stringify({...M16($),_funnel_oversized:Y,_funnel_type:x})},v16=["type","subtype","ts","channel","channel_type","user","bot_id"],M16=($)=>{try{let x=JSON.parse($);if(typeof x!=="object"||x===null)return{};let Y=x,Q={};for(let X of v16)if(Y[X]!==void 0)Q[X]=Y[X];return Q}catch{return{}}};var R16=5000,f16=50000,k16=604800000,T16=Jx(),S16=process.env.FUNNEL_HOST||"127.0.0.1",cF=aw(),SF=kF(cF,"gateway.pid");process.title=`funnel-gateway[${cF}]`;var tu=new du,c16=new v8;iE1(cF,{recursive:!0});if(_16(SF)){let $=Number(O16(SF,"utf-8").trim());if($>0&&c16.isAlive($))tu.error("funnel gateway already running",{pid:$}),process.exit(1)}A16(SF,String(process.pid));process.on("exit",()=>{try{b16(SF)}catch{}});var TF=B9();iE1(TF,{recursive:!0});var lE1=new ru({rawPath:kF(TF,"connector-raw.db"),processedPath:kF(TF,"connector-processed.db"),connectionPath:kF(TF,"connector-connection.db"),rawMaxRows:R16,maxRows:f16,maxAgeMs:k16,logger:tu});process.on("exit",()=>{try{lE1.close()}catch{}});var E16=new fF({logger:tu,diagnosticLog:lE1,dir:cF}),nE1=E16.gatewayServer({port:T16,hostname:S16});await nE1.start();var pE1=!1,dE1=async($)=>{if(pE1)return;pE1=!0;try{await Promise.race([nE1.stop(),new Promise((x)=>setTimeout(x,3000))])}catch{}process.exit($)};process.on("SIGINT",()=>{dE1(130)});process.on("SIGTERM",()=>{dE1(143)});
|
package/dist/index.d.ts
CHANGED
|
@@ -1725,6 +1725,11 @@ type Props$8 = {
|
|
|
1725
1725
|
* `Sentry.captureException` from the host to surface these. Defaults to no-op.
|
|
1726
1726
|
*/
|
|
1727
1727
|
onError?: OnFunnelError;
|
|
1728
|
+
/**
|
|
1729
|
+
* Gateway daemon port. Passed directly to FunnelGateway so hosts can override
|
|
1730
|
+
* the default (9742) without setting FUNNEL_PORT in the environment.
|
|
1731
|
+
*/
|
|
1732
|
+
port?: number;
|
|
1728
1733
|
};
|
|
1729
1734
|
/**
|
|
1730
1735
|
* Facade exposing every funnel facet as a getter.
|
|
@@ -2372,7 +2377,7 @@ declare const routes: _$hono_hono_base0.HonoBase<Env, {
|
|
|
2372
2377
|
connectors: {
|
|
2373
2378
|
id: string;
|
|
2374
2379
|
name: string;
|
|
2375
|
-
type: "discord" | "
|
|
2380
|
+
type: "discord" | "slack" | "gh" | "schedule";
|
|
2376
2381
|
}[];
|
|
2377
2382
|
}[];
|
|
2378
2383
|
outputFormat: "json";
|
package/dist/index.js
CHANGED
|
@@ -4042,7 +4042,8 @@ var Funnel = class Funnel {
|
|
|
4042
4042
|
process: this.process,
|
|
4043
4043
|
clock: this.clock,
|
|
4044
4044
|
dir: this.paths.dir,
|
|
4045
|
-
tmpDir: this.paths.tmpDir
|
|
4045
|
+
tmpDir: this.paths.tmpDir,
|
|
4046
|
+
port: this.props.port
|
|
4046
4047
|
});
|
|
4047
4048
|
return this.memos.gateway;
|
|
4048
4049
|
}
|
package/package.json
CHANGED