@interactive-inc/claude-funnel 0.68.1 → 0.68.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +3 -3
- package/dist/diagnostics.js +1 -1
- package/dist/{funnel-diagnostics-7rV3HxY3.js → funnel-diagnostics-DremV1of.js} +1 -7
- package/dist/gateway/daemon.js +2 -2
- package/dist/gateway.js +1 -1
- package/dist/index.js +2 -2
- package/dist/{sqlite-diagnostic-log-Qs4cf9I_.js → sqlite-diagnostic-log-B4p3bdCq.js} +3 -9
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -145,7 +145,7 @@ ${b.comment}`:b.comment}this.doc.range[2]=b.offset;break}default:this.errors.pus
|
|
|
145
145
|
`)+1;while(b!==0)this.onNewLine(this.offset+b),b=this.source.indexOf(`
|
|
146
146
|
`,b)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap($){let b=$.items[$.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,b.value){let U="end"in b.value?b.value.end:void 0;if((Array.isArray(U)?U[U.length-1]:void 0)?.type==="comment")U?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else if(b.sep)b.sep.push(this.sourceToken);else b.start.push(this.sourceToken);return;case"space":case"comment":if(b.value)$.items.push({start:[this.sourceToken]});else if(b.sep)b.sep.push(this.sourceToken);else{if(this.atIndentedComment(b.start,$.indent)){let J=$.items[$.items.length-2]?.value?.end;if(Array.isArray(J)){eI(J,b.start),J.push(this.sourceToken),$.items.pop();return}}b.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let U=!this.onKeyLine&&this.indent===$.indent,J=U&&(b.sep||b.explicitKey)&&this.type!=="seq-item-ind",D=[];if(J&&b.sep&&!b.value){let I=[];for(let X=0;X<b.sep.length;++X){let H=b.sep[X];switch(H.type){case"newline":I.push(X);break;case"space":break;case"comment":if(H.indent>$.indent)I.length=0;break;default:I.length=0}}if(I.length>=2)D=b.sep.splice(I[1])}switch(this.type){case"anchor":case"tag":if(J||b.value)D.push(this.sourceToken),$.items.push({start:D}),this.onKeyLine=!0;else if(b.sep)b.sep.push(this.sourceToken);else b.start.push(this.sourceToken);return;case"explicit-key-ind":if(!b.sep&&!b.explicitKey)b.start.push(this.sourceToken),b.explicitKey=!0;else if(J||b.value)D.push(this.sourceToken),$.items.push({start:D,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(b.explicitKey)if(!b.sep)if(d6(b.start,"newline"))Object.assign(b,{key:null,sep:[this.sourceToken]});else{let I=ib(b.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:I,key:null,sep:[this.sourceToken]}]})}else if(b.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(d6(b.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:D,key:null,sep:[this.sourceToken]}]});else if(jq(b.key)&&!d6(b.sep,"newline")){let I=ib(b.start),X=b.key,H=b.sep;H.push(this.sourceToken),delete b.key,delete b.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:I,key:X,sep:H}]})}else if(D.length>0)b.sep=b.sep.concat(D,this.sourceToken);else b.sep.push(this.sourceToken);else if(!b.sep)Object.assign(b,{key:null,sep:[this.sourceToken]});else if(b.value||J)$.items.push({start:D,key:null,sep:[this.sourceToken]});else if(d6(b.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else b.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let I=this.flowScalar(this.type);if(J||b.value)$.items.push({start:D,key:I,sep:[]}),this.onKeyLine=!0;else if(b.sep)this.stack.push(I);else Object.assign(b,{key:I,sep:[]}),this.onKeyLine=!0;return}default:{let I=this.startBlockValue($);if(I){if(I.type==="block-seq"){if(!b.explicitKey&&b.sep&&!d6(b.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(U)$.items.push({start:D});this.stack.push(I);return}}}}yield*this.pop(),yield*this.step()}*blockSequence($){let b=$.items[$.items.length-1];switch(this.type){case"newline":if(b.value){let U="end"in b.value?b.value.end:void 0;if((Array.isArray(U)?U[U.length-1]:void 0)?.type==="comment")U?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else b.start.push(this.sourceToken);return;case"space":case"comment":if(b.value)$.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(b.start,$.indent)){let J=$.items[$.items.length-2]?.value?.end;if(Array.isArray(J)){eI(J,b.start),J.push(this.sourceToken),$.items.pop();return}}b.start.push(this.sourceToken)}return;case"anchor":case"tag":if(b.value||this.indent<=$.indent)break;b.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==$.indent)break;if(b.value||d6(b.start,"seq-item-ind"))$.items.push({start:[this.sourceToken]});else b.start.push(this.sourceToken);return}if(this.indent>$.indent){let U=this.startBlockValue($);if(U){this.stack.push(U);return}}yield*this.pop(),yield*this.step()}*flowCollection($){let b=$.items[$.items.length-1];if(this.type==="flow-error-end"){let U;do yield*this.pop(),U=this.peek(1);while(U?.type==="flow-collection")}else if($.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!b||b.sep)$.items.push({start:[this.sourceToken]});else b.start.push(this.sourceToken);return;case"map-value-ind":if(!b||b.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(b.sep)b.sep.push(this.sourceToken);else Object.assign(b,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!b||b.value)$.items.push({start:[this.sourceToken]});else if(b.sep)b.sep.push(this.sourceToken);else b.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let J=this.flowScalar(this.type);if(!b||b.value)$.items.push({start:[],key:J,sep:[]});else if(b.sep)this.stack.push(J);else Object.assign(b,{key:J,sep:[]});return}case"flow-map-end":case"flow-seq-end":$.end.push(this.sourceToken);return}let U=this.startBlockValue($);if(U)this.stack.push(U);else yield*this.pop(),yield*this.step()}else{let U=this.peek(2);if(U.type==="block-map"&&(this.type==="map-value-ind"&&U.indent===$.indent||this.type==="newline"&&!U.items[U.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&U.type!=="flow-collection"){let J=sI(U),D=ib(J);Kq($);let I=$.end.splice(1,$.end.length);I.push(this.sourceToken);let X={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:D,key:$,sep:I}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=X}else yield*this.lineEnd($)}}flowScalar($){if(this.onNewLine){let b=this.source.indexOf(`
|
|
147
147
|
`)+1;while(b!==0)this.onNewLine(this.offset+b),b=this.source.indexOf(`
|
|
148
|
-
`,b)+1}return{type:$,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue($){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let b=sI($),U=ib(b);return U.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:U,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let b=sI($),U=ib(b);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:U,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,b){if(this.type!=="comment")return!1;if(this.indent<=b)return!1;return $.every((U)=>U.type==="newline"||U.type==="space")}*documentEnd($){if(this.type!=="doc-mode"){if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd($){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}xo.Parser=Lq});var Fq=L((oo)=>{var Aq=BY(),no=cU(),sU=dU(),io=M7(),yo=D$(),ho=MY(),qq=uY();function Pq($){let b=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||b&&new ho.LineCounter||null,prettyErrors:b}}function mo($,b={}){let{lineCounter:U,prettyErrors:J}=Pq(b),D=new qq.Parser(U?.addNewLine),I=new Aq.Composer(b),X=Array.from(I.compose(D.parse($)));if(J&&U)for(let H of X)H.errors.forEach(sU.prettifyError($,U)),H.warnings.forEach(sU.prettifyError($,U));if(X.length>0)return X;return Object.assign([],{empty:!0},I.streamInfo())}function Tq($,b={}){let{lineCounter:U,prettyErrors:J}=Pq(b),D=new qq.Parser(U?.addNewLine),I=new Aq.Composer(b),X=null;for(let H of I.compose(D.parse($),!0,$.length))if(!X)X=H;else if(X.options.logLevel!=="silent"){X.errors.push(new sU.YAMLParseError(H.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(J&&U)X.errors.forEach(sU.prettifyError($,U)),X.warnings.forEach(sU.prettifyError($,U));return X}function ro($,b,U){let J=void 0;if(typeof b==="function")J=b;else if(U===void 0&&b&&typeof b==="object")U=b;let D=Tq($,U);if(!D)return null;if(D.warnings.forEach((I)=>io.warn(D.options.logLevel,I)),D.errors.length>0)if(D.options.logLevel!=="silent")throw D.errors[0];else D.errors=[];return D.toJS(Object.assign({reviver:J},U))}function co($,b,U){let J=null;if(typeof b==="function"||Array.isArray(b))J=b;else if(U===void 0&&b)U=b;if(typeof U==="string")U=U.length;if(typeof U==="number"){let D=Math.round(U);U=D<1?void 0:D>8?{indent:8}:{indent:D}}if($===void 0){let{keepUndefined:D}=U??b??{};if(!D)return}if(yo.isDocument($)&&!J)return $.toString(U);return new no.Document($,J,U).toString(U)}oo.parse=ro;oo.parseAllDocuments=mo;oo.parseDocument=Tq;oo.stringify=co});import{homedir as ee}from"os";var iO={name:"@interactive-inc/claude-funnel",version:"0.68.1",description:"Hub CLI that routes external events (Slack / GitHub / Discord) to Claude Code agents through subscription channels over MCP.",keywords:["bun","claude","claude-code","cli","discord","github","mcp","slack"],homepage:"https://github.com/interactive-inc/open-claude-funnel#readme",bugs:{url:"https://github.com/interactive-inc/open-claude-funnel/issues"},license:"MIT",author:"Interactive Inc.",repository:{type:"git",url:"git+https://github.com/interactive-inc/open-claude-funnel.git"},bin:{fnl:"dist/bin.js",funnel:"dist/bin.js"},files:["dist/**/*","funnel.schema.json","README.md","LICENSE"],type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./claude":{types:"./dist/claude.d.ts",import:"./dist/claude.js",default:"./dist/claude.js"},"./gateway":{types:"./dist/gateway.d.ts",import:"./dist/gateway.js",default:"./dist/gateway.js"},"./profiles":{types:"./dist/profiles.d.ts",import:"./dist/profiles.js",default:"./dist/profiles.js"},"./local-config":{types:"./dist/local-config.d.ts",import:"./dist/local-config.js",default:"./dist/local-config.js"},"./diagnostics":{types:"./dist/diagnostics.d.ts",import:"./dist/diagnostics.js",default:"./dist/diagnostics.js"},"./recovery":{types:"./dist/recovery.d.ts",import:"./dist/recovery.js",default:"./dist/recovery.js"},"./doctor":{types:"./dist/doctor.d.ts",import:"./dist/doctor.js",default:"./dist/doctor.js"},"./docs":{types:"./dist/docs.d.ts",import:"./dist/docs.js",default:"./dist/docs.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"},"./event-log":{types:"./dist/event-log.d.ts",import:"./dist/event-log.js",default:"./dist/event-log.js"},"./logger":{types:"./dist/logger.d.ts",import:"./dist/logger.js",default:"./dist/logger.js"},"./channel":{types:"./dist/channel.d.ts",import:"./dist/channel.js",default:"./dist/channel.js"},"./bin":"./dist/bin.js","./package.json":"./package.json"},publishConfig:{access:"public"},scripts:{prepack:"make build"},dependencies:{"@hono/zod-validator":"0.9.0","@interactive-inc/flume":"^0.10.1","@modelcontextprotocol/sdk":"^1.30.0",hono:"^4.12.32",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@typescript/native-preview":"^7.0.0-dev.20260707.2","vite-plus":"^0.2.6",vitest:"^4.1.10"},overrides:{"@hono/node-server":"2.0.12","body-parser":"2.3.0","fast-uri":"4.1.1","ip-address":"10.3.1",postcss:"8.5.23",qs:"6.15.3",vite:"8.1.5",ws:"8.21.1"},engines:{bun:">=1.3.0"}};var h=class extends Error{res;status;constructor($=500,b){super(b?.message,{cause:b?.cause});this.res=b?.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 Y={};d4(Y,{xor:()=>TV,xid:()=>p3,void:()=>LV,uuidv7:()=>y3,uuidv6:()=>i3,uuidv4:()=>n3,uuid:()=>l3,util:()=>S,url:()=>h3,uppercase:()=>i0,unknown:()=>Y$,union:()=>O$,undefined:()=>KV,ulid:()=>t3,uint64:()=>BV,uint32:()=>VV,tuple:()=>SW,trim:()=>d0,treeifyError:()=>uX,transform:()=>i9,toUpperCase:()=>t0,toLowerCase:()=>o0,toJSONSchema:()=>V9,templateLiteral:()=>CV,symbol:()=>zV,superRefine:()=>JQ,success:()=>RV,stringbool:()=>mV,stringFormat:()=>HV,string:()=>A,strictObject:()=>PV,startsWith:()=>h0,slugify:()=>p0,size:()=>U0,setErrorMap:()=>hu,set:()=>NV,safeParseAsync:()=>GW,safeParse:()=>wW,safeEncodeAsync:()=>ZW,safeEncode:()=>VW,safeDecodeAsync:()=>BW,safeDecode:()=>vW,registry:()=>lD,regexes:()=>G4,regex:()=>l0,refine:()=>DQ,record:()=>w$,readonly:()=>aW,property:()=>W9,promise:()=>xV,prettifyError:()=>NX,preprocess:()=>f1,prefault:()=>hW,positive:()=>X9,pipe:()=>L9,partialRecord:()=>FV,parseAsync:()=>HW,parse:()=>XW,overwrite:()=>L4,optional:()=>B$,object:()=>E,number:()=>J$,nullish:()=>gV,nullable:()=>K1,null:()=>A1,normalize:()=>c0,nonpositive:()=>w9,nonoptional:()=>mW,nonnegative:()=>G9,never:()=>n9,negative:()=>H9,nativeEnum:()=>fV,nanoid:()=>c3,nan:()=>_V,multipleOf:()=>L6,minSize:()=>x4,minLength:()=>t4,mime:()=>r0,meta:()=>yV,maxSize:()=>A6,maxLength:()=>D0,map:()=>uV,mac:()=>e3,lte:()=>W4,lt:()=>E4,lowercase:()=>n0,looseRecord:()=>MV,looseObject:()=>k$,locales:()=>V1,literal:()=>l,length:()=>J0,lazy:()=>$Q,ksuid:()=>a3,keyof:()=>qV,jwt:()=>XV,json:()=>rV,iso:()=>F6,ipv6:()=>$V,ipv4:()=>s3,invertCodec:()=>EV,intersection:()=>Xb,int64:()=>ZV,int32:()=>OV,int:()=>j9,instanceof:()=>hV,includes:()=>y0,httpUrl:()=>m3,hostname:()=>wV,hex:()=>GV,hash:()=>WV,guid:()=>x3,gte:()=>t$,gt:()=>C4,globalRegistry:()=>_$,getErrorMap:()=>mu,function:()=>lV,fromJSONSchema:()=>dV,formatError:()=>$1,float64:()=>YV,float32:()=>QV,flattenError:()=>eb,file:()=>SV,exactOptional:()=>xW,enum:()=>E$,endsWith:()=>m0,encodeAsync:()=>YW,encode:()=>WW,emoji:()=>r3,email:()=>C3,e164:()=>IV,discriminatedUnion:()=>F1,describe:()=>iV,decodeAsync:()=>OW,decode:()=>QW,date:()=>AV,custom:()=>m9,cuid2:()=>o3,cuid:()=>d3,core:()=>p4,config:()=>q$,coerce:()=>XQ,codec:()=>kV,clone:()=>d$,cidrv6:()=>UV,cidrv4:()=>bV,check:()=>nV,catch:()=>dW,boolean:()=>T$,bigint:()=>vV,base64url:()=>JV,base64:()=>DV,array:()=>s,any:()=>jV,_function:()=>lV,_default:()=>iW,_ZodString:()=>A9,ZodXor:()=>MW,ZodXID:()=>N9,ZodVoid:()=>TW,ZodUnknown:()=>qW,ZodUnion:()=>T1,ZodUndefined:()=>jW,ZodUUID:()=>l4,ZodURL:()=>L1,ZodULID:()=>u9,ZodType:()=>c,ZodTuple:()=>fW,ZodTransform:()=>EW,ZodTemplateLiteral:()=>sW,ZodSymbol:()=>KW,ZodSuccess:()=>rW,ZodStringFormat:()=>Q$,ZodString:()=>bb,ZodSet:()=>RW,ZodRecord:()=>e0,ZodRealError:()=>U4,ZodReadonly:()=>pW,ZodPromise:()=>bQ,ZodPreprocess:()=>tW,ZodPrefault:()=>yW,ZodPipe:()=>M1,ZodOptional:()=>y9,ZodObject:()=>P1,ZodNumberFormat:()=>I0,ZodNumber:()=>Db,ZodNullable:()=>lW,ZodNull:()=>LW,ZodNonOptional:()=>h9,ZodNever:()=>PW,ZodNanoID:()=>T9,ZodNaN:()=>oW,ZodMap:()=>gW,ZodMAC:()=>zW,ZodLiteral:()=>_W,ZodLazy:()=>eW,ZodKSUID:()=>f9,ZodJWT:()=>x9,ZodIssueCode:()=>yu,ZodIntersection:()=>NW,ZodISOTime:()=>z9,ZodISODuration:()=>K9,ZodISODateTime:()=>Z9,ZodISODate:()=>B9,ZodIPv6:()=>g9,ZodIPv4:()=>S9,ZodGUID:()=>z1,ZodFunction:()=>UQ,ZodFirstPartyTypeKind:()=>IQ,ZodFile:()=>kW,ZodExactOptional:()=>CW,ZodError:()=>nu,ZodEnum:()=>$b,ZodEmoji:()=>P9,ZodEmail:()=>q9,ZodE164:()=>C9,ZodDiscriminatedUnion:()=>uW,ZodDefault:()=>nW,ZodDate:()=>q1,ZodCustomStringFormat:()=>Ub,ZodCustom:()=>N1,ZodCodec:()=>u1,ZodCatch:()=>cW,ZodCUID2:()=>M9,ZodCUID:()=>F9,ZodCIDRv6:()=>_9,ZodCIDRv4:()=>R9,ZodBoolean:()=>Jb,ZodBigIntFormat:()=>l9,ZodBigInt:()=>Ib,ZodBase64URL:()=>E9,ZodBase64:()=>k9,ZodArray:()=>FW,ZodAny:()=>AW,TimePrecision:()=>kw,NEVER:()=>ZX,$output:()=>Nw,$input:()=>fw,$brand:()=>BX});var p4={};d4(p4,{version:()=>q8,util:()=>S,treeifyError:()=>uX,toJSONSchema:()=>V9,toDotPath:()=>oO,safeParseAsync:()=>D1,safeParse:()=>k0,safeEncodeAsync:()=>b3,safeEncode:()=>eO,safeDecodeAsync:()=>U3,safeDecode:()=>$3,registry:()=>lD,regexes:()=>G4,process:()=>I$,prettifyError:()=>NX,parseAsync:()=>U1,parse:()=>b1,meta:()=>vG,locales:()=>V1,isValidJWT:()=>P3,isValidBase64URL:()=>q3,isValidBase64:()=>r8,initializeContext:()=>q6,globalRegistry:()=>_$,globalConfig:()=>a6,formatError:()=>$1,flattenError:()=>eb,finalize:()=>T6,extractDefs:()=>P6,encodeAsync:()=>aO,encode:()=>tO,describe:()=>VG,decodeAsync:()=>sO,decode:()=>pO,createToJSONSchemaMethod:()=>BG,createStandardJSONSchemaMethod:()=>s0,config:()=>q$,clone:()=>d$,_xor:()=>Zu,_xid:()=>pD,_void:()=>IG,_uuidv7:()=>mD,_uuidv6:()=>hD,_uuidv4:()=>yD,_uuid:()=>iD,_url:()=>Z1,_uppercase:()=>i0,_unknown:()=>DG,_union:()=>vu,_undefined:()=>$G,_ulid:()=>tD,_uint64:()=>sw,_uint32:()=>cw,_tuple:()=>Ku,_trim:()=>d0,_transform:()=>Fu,_toUpperCase:()=>t0,_toLowerCase:()=>o0,_templateLiteral:()=>ku,_symbol:()=>ew,_superRefine:()=>OG,_success:()=>Su,_stringbool:()=>ZG,_stringFormat:()=>a0,_string:()=>gw,_startsWith:()=>h0,_slugify:()=>p0,_size:()=>U0,_set:()=>Au,_safeParseAsync:()=>E0,_safeParse:()=>_0,_safeEncodeAsync:()=>PD,_safeEncode:()=>AD,_safeDecodeAsync:()=>TD,_safeDecode:()=>qD,_regex:()=>l0,_refine:()=>YG,_record:()=>ju,_readonly:()=>_u,_property:()=>W9,_promise:()=>Cu,_positive:()=>X9,_pipe:()=>Ru,_parseAsync:()=>R0,_parse:()=>g0,_overwrite:()=>L4,_optional:()=>Mu,_number:()=>nw,_nullable:()=>uu,_null:()=>bG,_normalize:()=>c0,_nonpositive:()=>w9,_nonoptional:()=>fu,_nonnegative:()=>G9,_never:()=>JG,_negative:()=>H9,_nativeEnum:()=>Pu,_nanoid:()=>cD,_nan:()=>wG,_multipleOf:()=>L6,_minSize:()=>x4,_minLength:()=>t4,_min:()=>t$,_mime:()=>r0,_maxSize:()=>A6,_maxLength:()=>D0,_max:()=>W4,_map:()=>Lu,_mac:()=>_w,_lte:()=>W4,_lt:()=>E4,_lowercase:()=>n0,_literal:()=>Tu,_length:()=>J0,_lazy:()=>Eu,_ksuid:()=>aD,_jwt:()=>I9,_isoTime:()=>xw,_isoDuration:()=>lw,_isoDateTime:()=>Ew,_isoDate:()=>Cw,_ipv6:()=>eD,_ipv4:()=>sD,_intersection:()=>zu,_int64:()=>aw,_int32:()=>rw,_int:()=>yw,_includes:()=>y0,_guid:()=>v1,_gte:()=>t$,_gt:()=>C4,_float64:()=>mw,_float32:()=>hw,_file:()=>WG,_enum:()=>qu,_endsWith:()=>m0,_encodeAsync:()=>jD,_encode:()=>zD,_emoji:()=>rD,_email:()=>nD,_e164:()=>J9,_discriminatedUnion:()=>Bu,_default:()=>Nu,_decodeAsync:()=>LD,_decode:()=>KD,_date:()=>XG,_custom:()=>QG,_cuid2:()=>oD,_cuid:()=>dD,_coercedString:()=>Rw,_coercedNumber:()=>iw,_coercedDate:()=>HG,_coercedBoolean:()=>ow,_coercedBigint:()=>pw,_cidrv6:()=>b9,_cidrv4:()=>$9,_check:()=>R3,_catch:()=>gu,_boolean:()=>dw,_bigint:()=>tw,_base64url:()=>D9,_base64:()=>U9,_array:()=>GG,_any:()=>UG,TimePrecision:()=>kw,NEVER:()=>ZX,JSONSchemaGenerator:()=>bW,JSONSchema:()=>_3,Doc:()=>ND,$output:()=>Nw,$input:()=>fw,$constructor:()=>z,$brand:()=>BX,$ZodXor:()=>GH,$ZodXID:()=>_8,$ZodVoid:()=>IH,$ZodUnknown:()=>DH,$ZodUnion:()=>w1,$ZodUndefined:()=>$H,$ZodUUID:()=>F8,$ZodURL:()=>u8,$ZodULID:()=>R8,$ZodType:()=>m,$ZodTuple:()=>ED,$ZodTransform:()=>zH,$ZodTemplateLiteral:()=>NH,$ZodSymbol:()=>e8,$ZodSuccess:()=>PH,$ZodStringFormat:()=>W$,$ZodString:()=>b0,$ZodSet:()=>VH,$ZodRegistry:()=>Sw,$ZodRecord:()=>YH,$ZodRealError:()=>b4,$ZodReadonly:()=>uH,$ZodPromise:()=>SH,$ZodPreprocess:()=>MH,$ZodPrefault:()=>AH,$ZodPipe:()=>xD,$ZodOptional:()=>CD,$ZodObjectJIT:()=>wH,$ZodObject:()=>M3,$ZodNumberFormat:()=>a8,$ZodNumber:()=>_D,$ZodNullable:()=>jH,$ZodNull:()=>bH,$ZodNonOptional:()=>qH,$ZodNever:()=>JH,$ZodNanoID:()=>f8,$ZodNaN:()=>FH,$ZodMap:()=>OH,$ZodMAC:()=>y8,$ZodLiteral:()=>ZH,$ZodLazy:()=>gH,$ZodKSUID:()=>k8,$ZodJWT:()=>t8,$ZodIntersection:()=>QH,$ZodISOTime:()=>x8,$ZodISODuration:()=>l8,$ZodISODateTime:()=>E8,$ZodISODate:()=>C8,$ZodIPv6:()=>i8,$ZodIPv4:()=>n8,$ZodGUID:()=>T8,$ZodFunction:()=>fH,$ZodFile:()=>BH,$ZodExactOptional:()=>KH,$ZodError:()=>sb,$ZodEnum:()=>vH,$ZodEncodeError:()=>s6,$ZodEmoji:()=>N8,$ZodEmail:()=>M8,$ZodE164:()=>o8,$ZodDiscriminatedUnion:()=>WH,$ZodDefault:()=>LH,$ZodDate:()=>XH,$ZodCustomStringFormat:()=>p8,$ZodCustom:()=>RH,$ZodCodec:()=>G1,$ZodCheckUpperCase:()=>Z8,$ZodCheckStringFormat:()=>C0,$ZodCheckStartsWith:()=>z8,$ZodCheckSizeEquals:()=>W8,$ZodCheckRegex:()=>V8,$ZodCheckProperty:()=>j8,$ZodCheckOverwrite:()=>A8,$ZodCheckNumberFormat:()=>X8,$ZodCheckMultipleOf:()=>I8,$ZodCheckMinSize:()=>G8,$ZodCheckMinLength:()=>Y8,$ZodCheckMimeType:()=>L8,$ZodCheckMaxSize:()=>w8,$ZodCheckMaxLength:()=>Q8,$ZodCheckLowerCase:()=>v8,$ZodCheckLessThan:()=>MD,$ZodCheckLengthEquals:()=>O8,$ZodCheckIncludes:()=>B8,$ZodCheckGreaterThan:()=>uD,$ZodCheckEndsWith:()=>K8,$ZodCheckBigIntFormat:()=>H8,$ZodCheck:()=>Z$,$ZodCatch:()=>TH,$ZodCUID2:()=>g8,$ZodCUID:()=>S8,$ZodCIDRv6:()=>m8,$ZodCIDRv4:()=>h8,$ZodBoolean:()=>H1,$ZodBigIntFormat:()=>s8,$ZodBigInt:()=>kD,$ZodBase64URL:()=>d8,$ZodBase64:()=>c8,$ZodAsyncError:()=>k4,$ZodArray:()=>HH,$ZodAny:()=>UH});var yO,ZX=Object.freeze({status:"aborted"});function z($,b,U){function J(H,w){if(!H._zod)Object.defineProperty(H,"_zod",{value:{def:w,constr:X,traits:new Set},enumerable:!1});if(H._zod.traits.has($))return;H._zod.traits.add($),b(H,w);let G=X.prototype,W=Object.keys(G);for(let Q=0;Q<W.length;Q++){let O=W[Q];if(!(O in H))H[O]=G[O].bind(H)}}let D=U?.Parent??Object;class I extends D{}Object.defineProperty(I,"name",{value:$});function X(H){var w;let G=U?.Parent?new I:this;J(G,H),(w=G._zod).deferred??(w.deferred=[]);for(let W of G._zod.deferred)W();return G}return Object.defineProperty(X,"init",{value:J}),Object.defineProperty(X,Symbol.hasInstance,{value:(H)=>{if(U?.Parent&&H instanceof U.Parent)return!0;return H?._zod?.traits?.has($)}}),Object.defineProperty(X,"name",{value:$}),X}var BX=Symbol("zod_brand");class k4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class s6 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}(yO=globalThis).__zod_globalConfig??(yO.__zod_globalConfig={});var a6=globalThis.__zod_globalConfig;function q$($){if($)Object.assign(a6,$);return a6}var S={};d4(S,{unwrapMessage:()=>cb,uint8ArrayToHex:()=>yF,uint8ArrayToBase64url:()=>nF,uint8ArrayToBase64:()=>rO,stringifyPrimitive:()=>u,slugify:()=>jX,shallowClone:()=>AX,safeExtend:()=>_F,required:()=>CF,randomString:()=>MF,propertyKeyTypes:()=>tb,promiseAllObject:()=>FF,primitiveTypes:()=>qX,prefixIssues:()=>$4,pick:()=>SF,partial:()=>EF,parsedType:()=>N,optionalKeys:()=>PX,omit:()=>gF,objectClone:()=>qF,numKeys:()=>uF,nullish:()=>B6,normalizeParams:()=>g,mergeDefs:()=>o4,merge:()=>kF,jsonStringifyReplacer:()=>N0,joinValues:()=>j,issue:()=>S0,isPlainObject:()=>K6,isObject:()=>e6,hexToUint8Array:()=>iF,getSizableOrigin:()=>pb,getParsedType:()=>NF,getLengthableOrigin:()=>ab,getEnumValues:()=>db,getElementAtPath:()=>TF,floatSafeRemainder:()=>KX,finalizeIssue:()=>o$,extend:()=>RF,explicitlyAborted:()=>MX,escapeRegex:()=>O4,esc:()=>ZD,defineLazy:()=>a,createTransparentProxy:()=>fF,cloneDef:()=>PF,clone:()=>d$,cleanRegex:()=>ob,cleanEnum:()=>xF,captureStackTrace:()=>BD,cached:()=>f0,base64urlToUint8Array:()=>lF,base64ToUint8Array:()=>mO,assignProp:()=>z6,assertNotEqual:()=>KF,assertNever:()=>LF,assertIs:()=>jF,assertEqual:()=>zF,assert:()=>AF,allowsEval:()=>LX,aborted:()=>j6,NUMBER_FORMAT_RANGES:()=>TX,Class:()=>cO,BIGINT_FORMAT_RANGES:()=>FX});function zF($){return $}function KF($){return $}function jF($){}function LF($){throw Error("Unexpected value in exhaustive check")}function AF($){}function db($){let b=Object.values($).filter((J)=>typeof J==="number");return Object.entries($).filter(([J,D])=>b.indexOf(+J)===-1).map(([J,D])=>D)}function j($,b="|"){return $.map((U)=>u(U)).join(b)}function N0($,b){if(typeof b==="bigint")return b.toString();return b}function f0($){return{get value(){{let U=$();return Object.defineProperty(this,"value",{value:U}),U}throw Error("cached value already set")}}}function B6($){return $===null||$===void 0}function ob($){let b=$.startsWith("^")?1:0,U=$.endsWith("$")?$.length-1:$.length;return $.slice(b,U)}function KX($,b){let U=$/b,J=Math.round(U),D=Number.EPSILON*Math.max(Math.abs(U),1);if(Math.abs(U-J)<D)return 0;return U-J}var hO=Symbol("evaluating");function a($,b,U){let J=void 0;Object.defineProperty($,b,{get(){if(J===hO)return;if(J===void 0)J=hO,J=U();return J},set(D){Object.defineProperty($,b,{value:D})},configurable:!0})}function qF($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function z6($,b,U){Object.defineProperty($,b,{value:U,writable:!0,enumerable:!0,configurable:!0})}function o4(...$){let b={};for(let U of $){let J=Object.getOwnPropertyDescriptors(U);Object.assign(b,J)}return Object.defineProperties({},b)}function PF($){return o4($._zod.def)}function TF($,b){if(!b)return $;return b.reduce((U,J)=>U?.[J],$)}function FF($){let b=Object.keys($),U=b.map((J)=>$[J]);return Promise.all(U).then((J)=>{let D={};for(let I=0;I<b.length;I++)D[b[I]]=J[I];return D})}function MF($=10){let U="";for(let J=0;J<$;J++)U+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return U}function ZD($){return JSON.stringify($)}function jX($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var BD="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function e6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var LX=f0(()=>{if(a6.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function K6($){if(e6($)===!1)return!1;let b=$.constructor;if(b===void 0)return!0;if(typeof b!=="function")return!0;let U=b.prototype;if(e6(U)===!1)return!1;if(Object.prototype.hasOwnProperty.call(U,"isPrototypeOf")===!1)return!1;return!0}function AX($){if(K6($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function uF($){let b=0;for(let U in $)if(Object.prototype.hasOwnProperty.call($,U))b++;return b}var NF=($)=>{let b=typeof $;switch(b){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: ${b}`)}},tb=new Set(["string","number","symbol"]),qX=new Set(["string","number","bigint","boolean","symbol","undefined"]);function O4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d$($,b,U){let J=new $._zod.constr(b??$._zod.def);if(!b||U?.parent)J._zod.parent=$;return J}function g($){let b=$;if(!b)return{};if(typeof b==="string")return{error:()=>b};if(b?.message!==void 0){if(b?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");b.error=b.message}if(delete b.message,typeof b.error==="string")return{...b,error:()=>b.error};return b}function fF($){let b;return new Proxy({},{get(U,J,D){return b??(b=$()),Reflect.get(b,J,D)},set(U,J,D,I){return b??(b=$()),Reflect.set(b,J,D,I)},has(U,J){return b??(b=$()),Reflect.has(b,J)},deleteProperty(U,J){return b??(b=$()),Reflect.deleteProperty(b,J)},ownKeys(U){return b??(b=$()),Reflect.ownKeys(b)},getOwnPropertyDescriptor(U,J){return b??(b=$()),Reflect.getOwnPropertyDescriptor(b,J)},defineProperty(U,J,D){return b??(b=$()),Reflect.defineProperty(b,J,D)}})}function u($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function PX($){return Object.keys($).filter((b)=>{return $[b]._zod.optin==="optional"&&$[b]._zod.optout==="optional"})}var TX={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]},FX={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function SF($,b){let U=$._zod.def,J=U.checks;if(J&&J.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let I=o4($._zod.def,{get shape(){let X={};for(let H in b){if(!(H in U.shape))throw Error(`Unrecognized key: "${H}"`);if(!b[H])continue;X[H]=U.shape[H]}return z6(this,"shape",X),X},checks:[]});return d$($,I)}function gF($,b){let U=$._zod.def,J=U.checks;if(J&&J.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let I=o4($._zod.def,{get shape(){let X={...$._zod.def.shape};for(let H in b){if(!(H in U.shape))throw Error(`Unrecognized key: "${H}"`);if(!b[H])continue;delete X[H]}return z6(this,"shape",X),X},checks:[]});return d$($,I)}function RF($,b){if(!K6(b))throw Error("Invalid input to extend: expected a plain object");let U=$._zod.def.checks;if(U&&U.length>0){let I=$._zod.def.shape;for(let X in b)if(Object.getOwnPropertyDescriptor(I,X)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let D=o4($._zod.def,{get shape(){let I={...$._zod.def.shape,...b};return z6(this,"shape",I),I}});return d$($,D)}function _F($,b){if(!K6(b))throw Error("Invalid input to safeExtend: expected a plain object");let U=o4($._zod.def,{get shape(){let J={...$._zod.def.shape,...b};return z6(this,"shape",J),J}});return d$($,U)}function kF($,b){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let U=o4($._zod.def,{get shape(){let J={...$._zod.def.shape,...b._zod.def.shape};return z6(this,"shape",J),J},get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return d$($,U)}function EF($,b,U){let D=b._zod.def.checks;if(D&&D.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let X=o4(b._zod.def,{get shape(){let H=b._zod.def.shape,w={...H};if(U)for(let G in U){if(!(G in H))throw Error(`Unrecognized key: "${G}"`);if(!U[G])continue;w[G]=$?new $({type:"optional",innerType:H[G]}):H[G]}else for(let G in H)w[G]=$?new $({type:"optional",innerType:H[G]}):H[G];return z6(this,"shape",w),w},checks:[]});return d$(b,X)}function CF($,b,U){let J=o4(b._zod.def,{get shape(){let D=b._zod.def.shape,I={...D};if(U)for(let X in U){if(!(X in I))throw Error(`Unrecognized key: "${X}"`);if(!U[X])continue;I[X]=new $({type:"nonoptional",innerType:D[X]})}else for(let X in D)I[X]=new $({type:"nonoptional",innerType:D[X]});return z6(this,"shape",I),I}});return d$(b,J)}function j6($,b=0){if($.aborted===!0)return!0;for(let U=b;U<$.issues.length;U++)if($.issues[U]?.continue!==!0)return!0;return!1}function MX($,b=0){if($.aborted===!0)return!0;for(let U=b;U<$.issues.length;U++)if($.issues[U]?.continue===!1)return!0;return!1}function $4($,b){return b.map((U)=>{var J;return(J=U).path??(J.path=[]),U.path.unshift($),U})}function cb($){return typeof $==="string"?$:$?.message}function o$($,b,U){let J=$.message?$.message:cb($.inst?._zod.def?.error?.($))??cb(b?.error?.($))??cb(U.customError?.($))??cb(U.localeError?.($))??"Invalid input",{inst:D,continue:I,input:X,...H}=$;if(H.path??(H.path=[]),H.message=J,b?.reportInput)H.input=X;return H}function pb($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function ab($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function N($){let b=typeof $;switch(b){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let U=$;if(U&&Object.getPrototypeOf(U)!==Object.prototype&&"constructor"in U&&U.constructor)return U.constructor.name}}return b}function S0(...$){let[b,U,J]=$;if(typeof b==="string")return{message:b,code:"custom",input:U,inst:J};return{...b}}function xF($){return Object.entries($).filter(([b,U])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function mO($){let b=atob($),U=new Uint8Array(b.length);for(let J=0;J<b.length;J++)U[J]=b.charCodeAt(J);return U}function rO($){let b="";for(let U=0;U<$.length;U++)b+=String.fromCharCode($[U]);return btoa(b)}function lF($){let b=$.replace(/-/g,"+").replace(/_/g,"/"),U="=".repeat((4-b.length%4)%4);return mO(b+U)}function nF($){return rO($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function iF($){let b=$.replace(/^0x/,"");if(b.length%2!==0)throw Error("Invalid hex string length");let U=new Uint8Array(b.length/2);for(let J=0;J<b.length;J+=2)U[J/2]=Number.parseInt(b.slice(J,J+2),16);return U}function yF($){return Array.from($).map((b)=>b.toString(16).padStart(2,"0")).join("")}class cO{constructor(...$){}}var dO=($,b)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:b,enumerable:!1}),$.message=JSON.stringify(b,N0,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},sb=z("$ZodError",dO),b4=z("$ZodError",dO,{Parent:Error});function eb($,b=(U)=>U.message){let U={},J=[];for(let D of $.issues)if(D.path.length>0)U[D.path[0]]=U[D.path[0]]||[],U[D.path[0]].push(b(D));else J.push(b(D));return{formErrors:J,fieldErrors:U}}function $1($,b=(U)=>U.message){let U={_errors:[]},J=(D,I=[])=>{for(let X of D.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((H)=>J({issues:H},[...I,...X.path]));else if(X.code==="invalid_key")J({issues:X.issues},[...I,...X.path]);else if(X.code==="invalid_element")J({issues:X.issues},[...I,...X.path]);else{let H=[...I,...X.path];if(H.length===0)U._errors.push(b(X));else{let w=U,G=0;while(G<H.length){let W=H[G];if(G!==H.length-1)w[W]=w[W]||{_errors:[]};else w[W]=w[W]||{_errors:[]},w[W]._errors.push(b(X));w=w[W],G++}}}};return J($),U}function uX($,b=(U)=>U.message){let U={errors:[]},J=(D,I=[])=>{var X,H;for(let w of D.issues)if(w.code==="invalid_union"&&w.errors.length)w.errors.map((G)=>J({issues:G},[...I,...w.path]));else if(w.code==="invalid_key")J({issues:w.issues},[...I,...w.path]);else if(w.code==="invalid_element")J({issues:w.issues},[...I,...w.path]);else{let G=[...I,...w.path];if(G.length===0){U.errors.push(b(w));continue}let W=U,Q=0;while(Q<G.length){let O=G[Q],V=Q===G.length-1;if(typeof O==="string")W.properties??(W.properties={}),(X=W.properties)[O]??(X[O]={errors:[]}),W=W.properties[O];else W.items??(W.items=[]),(H=W.items)[O]??(H[O]={errors:[]}),W=W.items[O];if(V)W.errors.push(b(w));Q++}}};return J($),U}function oO($){let b=[],U=$.map((J)=>typeof J==="object"?J.key:J);for(let J of U)if(typeof J==="number")b.push(`[${J}]`);else if(typeof J==="symbol")b.push(`[${JSON.stringify(String(J))}]`);else if(/[^\w$]/.test(J))b.push(`[${JSON.stringify(J)}]`);else{if(b.length)b.push(".");b.push(J)}return b.join("")}function NX($){let b=[],U=[...$.issues].sort((J,D)=>(J.path??[]).length-(D.path??[]).length);for(let J of U)if(b.push(`\u2716 ${J.message}`),J.path?.length)b.push(` \u2192 at ${oO(J.path)}`);return b.join(`
|
|
148
|
+
`,b)+1}return{type:$,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue($){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let b=sI($),U=ib(b);return U.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:U,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let b=sI($),U=ib(b);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:U,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,b){if(this.type!=="comment")return!1;if(this.indent<=b)return!1;return $.every((U)=>U.type==="newline"||U.type==="space")}*documentEnd($){if(this.type!=="doc-mode"){if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd($){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}xo.Parser=Lq});var Fq=L((oo)=>{var Aq=BY(),no=cU(),sU=dU(),io=M7(),yo=D$(),ho=MY(),qq=uY();function Pq($){let b=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||b&&new ho.LineCounter||null,prettyErrors:b}}function mo($,b={}){let{lineCounter:U,prettyErrors:J}=Pq(b),D=new qq.Parser(U?.addNewLine),I=new Aq.Composer(b),X=Array.from(I.compose(D.parse($)));if(J&&U)for(let H of X)H.errors.forEach(sU.prettifyError($,U)),H.warnings.forEach(sU.prettifyError($,U));if(X.length>0)return X;return Object.assign([],{empty:!0},I.streamInfo())}function Tq($,b={}){let{lineCounter:U,prettyErrors:J}=Pq(b),D=new qq.Parser(U?.addNewLine),I=new Aq.Composer(b),X=null;for(let H of I.compose(D.parse($),!0,$.length))if(!X)X=H;else if(X.options.logLevel!=="silent"){X.errors.push(new sU.YAMLParseError(H.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(J&&U)X.errors.forEach(sU.prettifyError($,U)),X.warnings.forEach(sU.prettifyError($,U));return X}function ro($,b,U){let J=void 0;if(typeof b==="function")J=b;else if(U===void 0&&b&&typeof b==="object")U=b;let D=Tq($,U);if(!D)return null;if(D.warnings.forEach((I)=>io.warn(D.options.logLevel,I)),D.errors.length>0)if(D.options.logLevel!=="silent")throw D.errors[0];else D.errors=[];return D.toJS(Object.assign({reviver:J},U))}function co($,b,U){let J=null;if(typeof b==="function"||Array.isArray(b))J=b;else if(U===void 0&&b)U=b;if(typeof U==="string")U=U.length;if(typeof U==="number"){let D=Math.round(U);U=D<1?void 0:D>8?{indent:8}:{indent:D}}if($===void 0){let{keepUndefined:D}=U??b??{};if(!D)return}if(yo.isDocument($)&&!J)return $.toString(U);return new no.Document($,J,U).toString(U)}oo.parse=ro;oo.parseAllDocuments=mo;oo.parseDocument=Tq;oo.stringify=co});import{homedir as ee}from"os";var iO={name:"@interactive-inc/claude-funnel",version:"0.68.2",description:"Hub CLI that routes external events (Slack / GitHub / Discord) to Claude Code agents through subscription channels over MCP.",keywords:["bun","claude","claude-code","cli","discord","github","mcp","slack"],homepage:"https://github.com/interactive-inc/open-claude-funnel#readme",bugs:{url:"https://github.com/interactive-inc/open-claude-funnel/issues"},license:"MIT",author:"Interactive Inc.",repository:{type:"git",url:"git+https://github.com/interactive-inc/open-claude-funnel.git"},bin:{fnl:"dist/bin.js",funnel:"dist/bin.js"},files:["dist/**/*","funnel.schema.json","README.md","LICENSE"],type:"module",main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./claude":{types:"./dist/claude.d.ts",import:"./dist/claude.js",default:"./dist/claude.js"},"./gateway":{types:"./dist/gateway.d.ts",import:"./dist/gateway.js",default:"./dist/gateway.js"},"./profiles":{types:"./dist/profiles.d.ts",import:"./dist/profiles.js",default:"./dist/profiles.js"},"./local-config":{types:"./dist/local-config.d.ts",import:"./dist/local-config.js",default:"./dist/local-config.js"},"./diagnostics":{types:"./dist/diagnostics.d.ts",import:"./dist/diagnostics.js",default:"./dist/diagnostics.js"},"./recovery":{types:"./dist/recovery.d.ts",import:"./dist/recovery.js",default:"./dist/recovery.js"},"./doctor":{types:"./dist/doctor.d.ts",import:"./dist/doctor.js",default:"./dist/doctor.js"},"./docs":{types:"./dist/docs.d.ts",import:"./dist/docs.js",default:"./dist/docs.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"},"./event-log":{types:"./dist/event-log.d.ts",import:"./dist/event-log.js",default:"./dist/event-log.js"},"./logger":{types:"./dist/logger.d.ts",import:"./dist/logger.js",default:"./dist/logger.js"},"./channel":{types:"./dist/channel.d.ts",import:"./dist/channel.js",default:"./dist/channel.js"},"./bin":"./dist/bin.js","./package.json":"./package.json"},publishConfig:{access:"public"},scripts:{prepack:"make build"},dependencies:{"@hono/zod-validator":"0.9.0","@interactive-inc/flume":"^0.10.1","@modelcontextprotocol/sdk":"^1.30.0",hono:"^4.12.32",yaml:"^2.9.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"^1.3.14","@typescript/native-preview":"^7.0.0-dev.20260707.2","vite-plus":"^0.2.6",vitest:"^4.1.10"},overrides:{"@hono/node-server":"2.0.12","body-parser":"2.3.0","fast-uri":"4.1.1","ip-address":"10.3.1",postcss:"8.5.23",qs:"6.15.3",vite:"8.1.5",ws:"8.21.1"},engines:{bun:">=1.3.0"}};var h=class extends Error{res;status;constructor($=500,b){super(b?.message,{cause:b?.cause});this.res=b?.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 Y={};d4(Y,{xor:()=>TV,xid:()=>p3,void:()=>LV,uuidv7:()=>y3,uuidv6:()=>i3,uuidv4:()=>n3,uuid:()=>l3,util:()=>S,url:()=>h3,uppercase:()=>i0,unknown:()=>Y$,union:()=>O$,undefined:()=>KV,ulid:()=>t3,uint64:()=>BV,uint32:()=>VV,tuple:()=>SW,trim:()=>d0,treeifyError:()=>uX,transform:()=>i9,toUpperCase:()=>t0,toLowerCase:()=>o0,toJSONSchema:()=>V9,templateLiteral:()=>CV,symbol:()=>zV,superRefine:()=>JQ,success:()=>RV,stringbool:()=>mV,stringFormat:()=>HV,string:()=>A,strictObject:()=>PV,startsWith:()=>h0,slugify:()=>p0,size:()=>U0,setErrorMap:()=>hu,set:()=>NV,safeParseAsync:()=>GW,safeParse:()=>wW,safeEncodeAsync:()=>ZW,safeEncode:()=>VW,safeDecodeAsync:()=>BW,safeDecode:()=>vW,registry:()=>lD,regexes:()=>G4,regex:()=>l0,refine:()=>DQ,record:()=>w$,readonly:()=>aW,property:()=>W9,promise:()=>xV,prettifyError:()=>NX,preprocess:()=>f1,prefault:()=>hW,positive:()=>X9,pipe:()=>L9,partialRecord:()=>FV,parseAsync:()=>HW,parse:()=>XW,overwrite:()=>L4,optional:()=>B$,object:()=>E,number:()=>J$,nullish:()=>gV,nullable:()=>K1,null:()=>A1,normalize:()=>c0,nonpositive:()=>w9,nonoptional:()=>mW,nonnegative:()=>G9,never:()=>n9,negative:()=>H9,nativeEnum:()=>fV,nanoid:()=>c3,nan:()=>_V,multipleOf:()=>L6,minSize:()=>x4,minLength:()=>t4,mime:()=>r0,meta:()=>yV,maxSize:()=>A6,maxLength:()=>D0,map:()=>uV,mac:()=>e3,lte:()=>W4,lt:()=>E4,lowercase:()=>n0,looseRecord:()=>MV,looseObject:()=>k$,locales:()=>V1,literal:()=>l,length:()=>J0,lazy:()=>$Q,ksuid:()=>a3,keyof:()=>qV,jwt:()=>XV,json:()=>rV,iso:()=>F6,ipv6:()=>$V,ipv4:()=>s3,invertCodec:()=>EV,intersection:()=>Xb,int64:()=>ZV,int32:()=>OV,int:()=>j9,instanceof:()=>hV,includes:()=>y0,httpUrl:()=>m3,hostname:()=>wV,hex:()=>GV,hash:()=>WV,guid:()=>x3,gte:()=>t$,gt:()=>C4,globalRegistry:()=>_$,getErrorMap:()=>mu,function:()=>lV,fromJSONSchema:()=>dV,formatError:()=>$1,float64:()=>YV,float32:()=>QV,flattenError:()=>eb,file:()=>SV,exactOptional:()=>xW,enum:()=>E$,endsWith:()=>m0,encodeAsync:()=>YW,encode:()=>WW,emoji:()=>r3,email:()=>C3,e164:()=>IV,discriminatedUnion:()=>F1,describe:()=>iV,decodeAsync:()=>OW,decode:()=>QW,date:()=>AV,custom:()=>m9,cuid2:()=>o3,cuid:()=>d3,core:()=>p4,config:()=>q$,coerce:()=>XQ,codec:()=>kV,clone:()=>d$,cidrv6:()=>UV,cidrv4:()=>bV,check:()=>nV,catch:()=>dW,boolean:()=>T$,bigint:()=>vV,base64url:()=>JV,base64:()=>DV,array:()=>s,any:()=>jV,_function:()=>lV,_default:()=>iW,_ZodString:()=>A9,ZodXor:()=>MW,ZodXID:()=>N9,ZodVoid:()=>TW,ZodUnknown:()=>qW,ZodUnion:()=>T1,ZodUndefined:()=>jW,ZodUUID:()=>l4,ZodURL:()=>L1,ZodULID:()=>u9,ZodType:()=>c,ZodTuple:()=>fW,ZodTransform:()=>EW,ZodTemplateLiteral:()=>sW,ZodSymbol:()=>KW,ZodSuccess:()=>rW,ZodStringFormat:()=>Q$,ZodString:()=>bb,ZodSet:()=>RW,ZodRecord:()=>e0,ZodRealError:()=>U4,ZodReadonly:()=>pW,ZodPromise:()=>bQ,ZodPreprocess:()=>tW,ZodPrefault:()=>yW,ZodPipe:()=>M1,ZodOptional:()=>y9,ZodObject:()=>P1,ZodNumberFormat:()=>I0,ZodNumber:()=>Db,ZodNullable:()=>lW,ZodNull:()=>LW,ZodNonOptional:()=>h9,ZodNever:()=>PW,ZodNanoID:()=>T9,ZodNaN:()=>oW,ZodMap:()=>gW,ZodMAC:()=>zW,ZodLiteral:()=>_W,ZodLazy:()=>eW,ZodKSUID:()=>f9,ZodJWT:()=>x9,ZodIssueCode:()=>yu,ZodIntersection:()=>NW,ZodISOTime:()=>z9,ZodISODuration:()=>K9,ZodISODateTime:()=>Z9,ZodISODate:()=>B9,ZodIPv6:()=>g9,ZodIPv4:()=>S9,ZodGUID:()=>z1,ZodFunction:()=>UQ,ZodFirstPartyTypeKind:()=>IQ,ZodFile:()=>kW,ZodExactOptional:()=>CW,ZodError:()=>nu,ZodEnum:()=>$b,ZodEmoji:()=>P9,ZodEmail:()=>q9,ZodE164:()=>C9,ZodDiscriminatedUnion:()=>uW,ZodDefault:()=>nW,ZodDate:()=>q1,ZodCustomStringFormat:()=>Ub,ZodCustom:()=>N1,ZodCodec:()=>u1,ZodCatch:()=>cW,ZodCUID2:()=>M9,ZodCUID:()=>F9,ZodCIDRv6:()=>_9,ZodCIDRv4:()=>R9,ZodBoolean:()=>Jb,ZodBigIntFormat:()=>l9,ZodBigInt:()=>Ib,ZodBase64URL:()=>E9,ZodBase64:()=>k9,ZodArray:()=>FW,ZodAny:()=>AW,TimePrecision:()=>kw,NEVER:()=>ZX,$output:()=>Nw,$input:()=>fw,$brand:()=>BX});var p4={};d4(p4,{version:()=>q8,util:()=>S,treeifyError:()=>uX,toJSONSchema:()=>V9,toDotPath:()=>oO,safeParseAsync:()=>D1,safeParse:()=>k0,safeEncodeAsync:()=>b3,safeEncode:()=>eO,safeDecodeAsync:()=>U3,safeDecode:()=>$3,registry:()=>lD,regexes:()=>G4,process:()=>I$,prettifyError:()=>NX,parseAsync:()=>U1,parse:()=>b1,meta:()=>vG,locales:()=>V1,isValidJWT:()=>P3,isValidBase64URL:()=>q3,isValidBase64:()=>r8,initializeContext:()=>q6,globalRegistry:()=>_$,globalConfig:()=>a6,formatError:()=>$1,flattenError:()=>eb,finalize:()=>T6,extractDefs:()=>P6,encodeAsync:()=>aO,encode:()=>tO,describe:()=>VG,decodeAsync:()=>sO,decode:()=>pO,createToJSONSchemaMethod:()=>BG,createStandardJSONSchemaMethod:()=>s0,config:()=>q$,clone:()=>d$,_xor:()=>Zu,_xid:()=>pD,_void:()=>IG,_uuidv7:()=>mD,_uuidv6:()=>hD,_uuidv4:()=>yD,_uuid:()=>iD,_url:()=>Z1,_uppercase:()=>i0,_unknown:()=>DG,_union:()=>vu,_undefined:()=>$G,_ulid:()=>tD,_uint64:()=>sw,_uint32:()=>cw,_tuple:()=>Ku,_trim:()=>d0,_transform:()=>Fu,_toUpperCase:()=>t0,_toLowerCase:()=>o0,_templateLiteral:()=>ku,_symbol:()=>ew,_superRefine:()=>OG,_success:()=>Su,_stringbool:()=>ZG,_stringFormat:()=>a0,_string:()=>gw,_startsWith:()=>h0,_slugify:()=>p0,_size:()=>U0,_set:()=>Au,_safeParseAsync:()=>E0,_safeParse:()=>_0,_safeEncodeAsync:()=>PD,_safeEncode:()=>AD,_safeDecodeAsync:()=>TD,_safeDecode:()=>qD,_regex:()=>l0,_refine:()=>YG,_record:()=>ju,_readonly:()=>_u,_property:()=>W9,_promise:()=>Cu,_positive:()=>X9,_pipe:()=>Ru,_parseAsync:()=>R0,_parse:()=>g0,_overwrite:()=>L4,_optional:()=>Mu,_number:()=>nw,_nullable:()=>uu,_null:()=>bG,_normalize:()=>c0,_nonpositive:()=>w9,_nonoptional:()=>fu,_nonnegative:()=>G9,_never:()=>JG,_negative:()=>H9,_nativeEnum:()=>Pu,_nanoid:()=>cD,_nan:()=>wG,_multipleOf:()=>L6,_minSize:()=>x4,_minLength:()=>t4,_min:()=>t$,_mime:()=>r0,_maxSize:()=>A6,_maxLength:()=>D0,_max:()=>W4,_map:()=>Lu,_mac:()=>_w,_lte:()=>W4,_lt:()=>E4,_lowercase:()=>n0,_literal:()=>Tu,_length:()=>J0,_lazy:()=>Eu,_ksuid:()=>aD,_jwt:()=>I9,_isoTime:()=>xw,_isoDuration:()=>lw,_isoDateTime:()=>Ew,_isoDate:()=>Cw,_ipv6:()=>eD,_ipv4:()=>sD,_intersection:()=>zu,_int64:()=>aw,_int32:()=>rw,_int:()=>yw,_includes:()=>y0,_guid:()=>v1,_gte:()=>t$,_gt:()=>C4,_float64:()=>mw,_float32:()=>hw,_file:()=>WG,_enum:()=>qu,_endsWith:()=>m0,_encodeAsync:()=>jD,_encode:()=>zD,_emoji:()=>rD,_email:()=>nD,_e164:()=>J9,_discriminatedUnion:()=>Bu,_default:()=>Nu,_decodeAsync:()=>LD,_decode:()=>KD,_date:()=>XG,_custom:()=>QG,_cuid2:()=>oD,_cuid:()=>dD,_coercedString:()=>Rw,_coercedNumber:()=>iw,_coercedDate:()=>HG,_coercedBoolean:()=>ow,_coercedBigint:()=>pw,_cidrv6:()=>b9,_cidrv4:()=>$9,_check:()=>R3,_catch:()=>gu,_boolean:()=>dw,_bigint:()=>tw,_base64url:()=>D9,_base64:()=>U9,_array:()=>GG,_any:()=>UG,TimePrecision:()=>kw,NEVER:()=>ZX,JSONSchemaGenerator:()=>bW,JSONSchema:()=>_3,Doc:()=>ND,$output:()=>Nw,$input:()=>fw,$constructor:()=>z,$brand:()=>BX,$ZodXor:()=>GH,$ZodXID:()=>_8,$ZodVoid:()=>IH,$ZodUnknown:()=>DH,$ZodUnion:()=>w1,$ZodUndefined:()=>$H,$ZodUUID:()=>F8,$ZodURL:()=>u8,$ZodULID:()=>R8,$ZodType:()=>m,$ZodTuple:()=>ED,$ZodTransform:()=>zH,$ZodTemplateLiteral:()=>NH,$ZodSymbol:()=>e8,$ZodSuccess:()=>PH,$ZodStringFormat:()=>W$,$ZodString:()=>b0,$ZodSet:()=>VH,$ZodRegistry:()=>Sw,$ZodRecord:()=>YH,$ZodRealError:()=>b4,$ZodReadonly:()=>uH,$ZodPromise:()=>SH,$ZodPreprocess:()=>MH,$ZodPrefault:()=>AH,$ZodPipe:()=>xD,$ZodOptional:()=>CD,$ZodObjectJIT:()=>wH,$ZodObject:()=>M3,$ZodNumberFormat:()=>a8,$ZodNumber:()=>_D,$ZodNullable:()=>jH,$ZodNull:()=>bH,$ZodNonOptional:()=>qH,$ZodNever:()=>JH,$ZodNanoID:()=>f8,$ZodNaN:()=>FH,$ZodMap:()=>OH,$ZodMAC:()=>y8,$ZodLiteral:()=>ZH,$ZodLazy:()=>gH,$ZodKSUID:()=>k8,$ZodJWT:()=>t8,$ZodIntersection:()=>QH,$ZodISOTime:()=>x8,$ZodISODuration:()=>l8,$ZodISODateTime:()=>E8,$ZodISODate:()=>C8,$ZodIPv6:()=>i8,$ZodIPv4:()=>n8,$ZodGUID:()=>T8,$ZodFunction:()=>fH,$ZodFile:()=>BH,$ZodExactOptional:()=>KH,$ZodError:()=>sb,$ZodEnum:()=>vH,$ZodEncodeError:()=>s6,$ZodEmoji:()=>N8,$ZodEmail:()=>M8,$ZodE164:()=>o8,$ZodDiscriminatedUnion:()=>WH,$ZodDefault:()=>LH,$ZodDate:()=>XH,$ZodCustomStringFormat:()=>p8,$ZodCustom:()=>RH,$ZodCodec:()=>G1,$ZodCheckUpperCase:()=>Z8,$ZodCheckStringFormat:()=>C0,$ZodCheckStartsWith:()=>z8,$ZodCheckSizeEquals:()=>W8,$ZodCheckRegex:()=>V8,$ZodCheckProperty:()=>j8,$ZodCheckOverwrite:()=>A8,$ZodCheckNumberFormat:()=>X8,$ZodCheckMultipleOf:()=>I8,$ZodCheckMinSize:()=>G8,$ZodCheckMinLength:()=>Y8,$ZodCheckMimeType:()=>L8,$ZodCheckMaxSize:()=>w8,$ZodCheckMaxLength:()=>Q8,$ZodCheckLowerCase:()=>v8,$ZodCheckLessThan:()=>MD,$ZodCheckLengthEquals:()=>O8,$ZodCheckIncludes:()=>B8,$ZodCheckGreaterThan:()=>uD,$ZodCheckEndsWith:()=>K8,$ZodCheckBigIntFormat:()=>H8,$ZodCheck:()=>Z$,$ZodCatch:()=>TH,$ZodCUID2:()=>g8,$ZodCUID:()=>S8,$ZodCIDRv6:()=>m8,$ZodCIDRv4:()=>h8,$ZodBoolean:()=>H1,$ZodBigIntFormat:()=>s8,$ZodBigInt:()=>kD,$ZodBase64URL:()=>d8,$ZodBase64:()=>c8,$ZodAsyncError:()=>k4,$ZodArray:()=>HH,$ZodAny:()=>UH});var yO,ZX=Object.freeze({status:"aborted"});function z($,b,U){function J(H,w){if(!H._zod)Object.defineProperty(H,"_zod",{value:{def:w,constr:X,traits:new Set},enumerable:!1});if(H._zod.traits.has($))return;H._zod.traits.add($),b(H,w);let G=X.prototype,W=Object.keys(G);for(let Q=0;Q<W.length;Q++){let O=W[Q];if(!(O in H))H[O]=G[O].bind(H)}}let D=U?.Parent??Object;class I extends D{}Object.defineProperty(I,"name",{value:$});function X(H){var w;let G=U?.Parent?new I:this;J(G,H),(w=G._zod).deferred??(w.deferred=[]);for(let W of G._zod.deferred)W();return G}return Object.defineProperty(X,"init",{value:J}),Object.defineProperty(X,Symbol.hasInstance,{value:(H)=>{if(U?.Parent&&H instanceof U.Parent)return!0;return H?._zod?.traits?.has($)}}),Object.defineProperty(X,"name",{value:$}),X}var BX=Symbol("zod_brand");class k4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class s6 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}(yO=globalThis).__zod_globalConfig??(yO.__zod_globalConfig={});var a6=globalThis.__zod_globalConfig;function q$($){if($)Object.assign(a6,$);return a6}var S={};d4(S,{unwrapMessage:()=>cb,uint8ArrayToHex:()=>yF,uint8ArrayToBase64url:()=>nF,uint8ArrayToBase64:()=>rO,stringifyPrimitive:()=>u,slugify:()=>jX,shallowClone:()=>AX,safeExtend:()=>_F,required:()=>CF,randomString:()=>MF,propertyKeyTypes:()=>tb,promiseAllObject:()=>FF,primitiveTypes:()=>qX,prefixIssues:()=>$4,pick:()=>SF,partial:()=>EF,parsedType:()=>N,optionalKeys:()=>PX,omit:()=>gF,objectClone:()=>qF,numKeys:()=>uF,nullish:()=>B6,normalizeParams:()=>g,mergeDefs:()=>o4,merge:()=>kF,jsonStringifyReplacer:()=>N0,joinValues:()=>j,issue:()=>S0,isPlainObject:()=>K6,isObject:()=>e6,hexToUint8Array:()=>iF,getSizableOrigin:()=>pb,getParsedType:()=>NF,getLengthableOrigin:()=>ab,getEnumValues:()=>db,getElementAtPath:()=>TF,floatSafeRemainder:()=>KX,finalizeIssue:()=>o$,extend:()=>RF,explicitlyAborted:()=>MX,escapeRegex:()=>O4,esc:()=>ZD,defineLazy:()=>a,createTransparentProxy:()=>fF,cloneDef:()=>PF,clone:()=>d$,cleanRegex:()=>ob,cleanEnum:()=>xF,captureStackTrace:()=>BD,cached:()=>f0,base64urlToUint8Array:()=>lF,base64ToUint8Array:()=>mO,assignProp:()=>z6,assertNotEqual:()=>KF,assertNever:()=>LF,assertIs:()=>jF,assertEqual:()=>zF,assert:()=>AF,allowsEval:()=>LX,aborted:()=>j6,NUMBER_FORMAT_RANGES:()=>TX,Class:()=>cO,BIGINT_FORMAT_RANGES:()=>FX});function zF($){return $}function KF($){return $}function jF($){}function LF($){throw Error("Unexpected value in exhaustive check")}function AF($){}function db($){let b=Object.values($).filter((J)=>typeof J==="number");return Object.entries($).filter(([J,D])=>b.indexOf(+J)===-1).map(([J,D])=>D)}function j($,b="|"){return $.map((U)=>u(U)).join(b)}function N0($,b){if(typeof b==="bigint")return b.toString();return b}function f0($){return{get value(){{let U=$();return Object.defineProperty(this,"value",{value:U}),U}throw Error("cached value already set")}}}function B6($){return $===null||$===void 0}function ob($){let b=$.startsWith("^")?1:0,U=$.endsWith("$")?$.length-1:$.length;return $.slice(b,U)}function KX($,b){let U=$/b,J=Math.round(U),D=Number.EPSILON*Math.max(Math.abs(U),1);if(Math.abs(U-J)<D)return 0;return U-J}var hO=Symbol("evaluating");function a($,b,U){let J=void 0;Object.defineProperty($,b,{get(){if(J===hO)return;if(J===void 0)J=hO,J=U();return J},set(D){Object.defineProperty($,b,{value:D})},configurable:!0})}function qF($){return Object.create(Object.getPrototypeOf($),Object.getOwnPropertyDescriptors($))}function z6($,b,U){Object.defineProperty($,b,{value:U,writable:!0,enumerable:!0,configurable:!0})}function o4(...$){let b={};for(let U of $){let J=Object.getOwnPropertyDescriptors(U);Object.assign(b,J)}return Object.defineProperties({},b)}function PF($){return o4($._zod.def)}function TF($,b){if(!b)return $;return b.reduce((U,J)=>U?.[J],$)}function FF($){let b=Object.keys($),U=b.map((J)=>$[J]);return Promise.all(U).then((J)=>{let D={};for(let I=0;I<b.length;I++)D[b[I]]=J[I];return D})}function MF($=10){let U="";for(let J=0;J<$;J++)U+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return U}function ZD($){return JSON.stringify($)}function jX($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var BD="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};function e6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var LX=f0(()=>{if(a6.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function K6($){if(e6($)===!1)return!1;let b=$.constructor;if(b===void 0)return!0;if(typeof b!=="function")return!0;let U=b.prototype;if(e6(U)===!1)return!1;if(Object.prototype.hasOwnProperty.call(U,"isPrototypeOf")===!1)return!1;return!0}function AX($){if(K6($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function uF($){let b=0;for(let U in $)if(Object.prototype.hasOwnProperty.call($,U))b++;return b}var NF=($)=>{let b=typeof $;switch(b){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: ${b}`)}},tb=new Set(["string","number","symbol"]),qX=new Set(["string","number","bigint","boolean","symbol","undefined"]);function O4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d$($,b,U){let J=new $._zod.constr(b??$._zod.def);if(!b||U?.parent)J._zod.parent=$;return J}function g($){let b=$;if(!b)return{};if(typeof b==="string")return{error:()=>b};if(b?.message!==void 0){if(b?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");b.error=b.message}if(delete b.message,typeof b.error==="string")return{...b,error:()=>b.error};return b}function fF($){let b;return new Proxy({},{get(U,J,D){return b??(b=$()),Reflect.get(b,J,D)},set(U,J,D,I){return b??(b=$()),Reflect.set(b,J,D,I)},has(U,J){return b??(b=$()),Reflect.has(b,J)},deleteProperty(U,J){return b??(b=$()),Reflect.deleteProperty(b,J)},ownKeys(U){return b??(b=$()),Reflect.ownKeys(b)},getOwnPropertyDescriptor(U,J){return b??(b=$()),Reflect.getOwnPropertyDescriptor(b,J)},defineProperty(U,J,D){return b??(b=$()),Reflect.defineProperty(b,J,D)}})}function u($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function PX($){return Object.keys($).filter((b)=>{return $[b]._zod.optin==="optional"&&$[b]._zod.optout==="optional"})}var TX={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]},FX={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function SF($,b){let U=$._zod.def,J=U.checks;if(J&&J.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let I=o4($._zod.def,{get shape(){let X={};for(let H in b){if(!(H in U.shape))throw Error(`Unrecognized key: "${H}"`);if(!b[H])continue;X[H]=U.shape[H]}return z6(this,"shape",X),X},checks:[]});return d$($,I)}function gF($,b){let U=$._zod.def,J=U.checks;if(J&&J.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let I=o4($._zod.def,{get shape(){let X={...$._zod.def.shape};for(let H in b){if(!(H in U.shape))throw Error(`Unrecognized key: "${H}"`);if(!b[H])continue;delete X[H]}return z6(this,"shape",X),X},checks:[]});return d$($,I)}function RF($,b){if(!K6(b))throw Error("Invalid input to extend: expected a plain object");let U=$._zod.def.checks;if(U&&U.length>0){let I=$._zod.def.shape;for(let X in b)if(Object.getOwnPropertyDescriptor(I,X)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let D=o4($._zod.def,{get shape(){let I={...$._zod.def.shape,...b};return z6(this,"shape",I),I}});return d$($,D)}function _F($,b){if(!K6(b))throw Error("Invalid input to safeExtend: expected a plain object");let U=o4($._zod.def,{get shape(){let J={...$._zod.def.shape,...b};return z6(this,"shape",J),J}});return d$($,U)}function kF($,b){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let U=o4($._zod.def,{get shape(){let J={...$._zod.def.shape,...b._zod.def.shape};return z6(this,"shape",J),J},get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return d$($,U)}function EF($,b,U){let D=b._zod.def.checks;if(D&&D.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let X=o4(b._zod.def,{get shape(){let H=b._zod.def.shape,w={...H};if(U)for(let G in U){if(!(G in H))throw Error(`Unrecognized key: "${G}"`);if(!U[G])continue;w[G]=$?new $({type:"optional",innerType:H[G]}):H[G]}else for(let G in H)w[G]=$?new $({type:"optional",innerType:H[G]}):H[G];return z6(this,"shape",w),w},checks:[]});return d$(b,X)}function CF($,b,U){let J=o4(b._zod.def,{get shape(){let D=b._zod.def.shape,I={...D};if(U)for(let X in U){if(!(X in I))throw Error(`Unrecognized key: "${X}"`);if(!U[X])continue;I[X]=new $({type:"nonoptional",innerType:D[X]})}else for(let X in D)I[X]=new $({type:"nonoptional",innerType:D[X]});return z6(this,"shape",I),I}});return d$(b,J)}function j6($,b=0){if($.aborted===!0)return!0;for(let U=b;U<$.issues.length;U++)if($.issues[U]?.continue!==!0)return!0;return!1}function MX($,b=0){if($.aborted===!0)return!0;for(let U=b;U<$.issues.length;U++)if($.issues[U]?.continue===!1)return!0;return!1}function $4($,b){return b.map((U)=>{var J;return(J=U).path??(J.path=[]),U.path.unshift($),U})}function cb($){return typeof $==="string"?$:$?.message}function o$($,b,U){let J=$.message?$.message:cb($.inst?._zod.def?.error?.($))??cb(b?.error?.($))??cb(U.customError?.($))??cb(U.localeError?.($))??"Invalid input",{inst:D,continue:I,input:X,...H}=$;if(H.path??(H.path=[]),H.message=J,b?.reportInput)H.input=X;return H}function pb($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function ab($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function N($){let b=typeof $;switch(b){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let U=$;if(U&&Object.getPrototypeOf(U)!==Object.prototype&&"constructor"in U&&U.constructor)return U.constructor.name}}return b}function S0(...$){let[b,U,J]=$;if(typeof b==="string")return{message:b,code:"custom",input:U,inst:J};return{...b}}function xF($){return Object.entries($).filter(([b,U])=>{return Number.isNaN(Number.parseInt(b,10))}).map((b)=>b[1])}function mO($){let b=atob($),U=new Uint8Array(b.length);for(let J=0;J<b.length;J++)U[J]=b.charCodeAt(J);return U}function rO($){let b="";for(let U=0;U<$.length;U++)b+=String.fromCharCode($[U]);return btoa(b)}function lF($){let b=$.replace(/-/g,"+").replace(/_/g,"/"),U="=".repeat((4-b.length%4)%4);return mO(b+U)}function nF($){return rO($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function iF($){let b=$.replace(/^0x/,"");if(b.length%2!==0)throw Error("Invalid hex string length");let U=new Uint8Array(b.length/2);for(let J=0;J<b.length;J+=2)U[J/2]=Number.parseInt(b.slice(J,J+2),16);return U}function yF($){return Array.from($).map((b)=>b.toString(16).padStart(2,"0")).join("")}class cO{constructor(...$){}}var dO=($,b)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:b,enumerable:!1}),$.message=JSON.stringify(b,N0,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},sb=z("$ZodError",dO),b4=z("$ZodError",dO,{Parent:Error});function eb($,b=(U)=>U.message){let U={},J=[];for(let D of $.issues)if(D.path.length>0)U[D.path[0]]=U[D.path[0]]||[],U[D.path[0]].push(b(D));else J.push(b(D));return{formErrors:J,fieldErrors:U}}function $1($,b=(U)=>U.message){let U={_errors:[]},J=(D,I=[])=>{for(let X of D.issues)if(X.code==="invalid_union"&&X.errors.length)X.errors.map((H)=>J({issues:H},[...I,...X.path]));else if(X.code==="invalid_key")J({issues:X.issues},[...I,...X.path]);else if(X.code==="invalid_element")J({issues:X.issues},[...I,...X.path]);else{let H=[...I,...X.path];if(H.length===0)U._errors.push(b(X));else{let w=U,G=0;while(G<H.length){let W=H[G];if(G!==H.length-1)w[W]=w[W]||{_errors:[]};else w[W]=w[W]||{_errors:[]},w[W]._errors.push(b(X));w=w[W],G++}}}};return J($),U}function uX($,b=(U)=>U.message){let U={errors:[]},J=(D,I=[])=>{var X,H;for(let w of D.issues)if(w.code==="invalid_union"&&w.errors.length)w.errors.map((G)=>J({issues:G},[...I,...w.path]));else if(w.code==="invalid_key")J({issues:w.issues},[...I,...w.path]);else if(w.code==="invalid_element")J({issues:w.issues},[...I,...w.path]);else{let G=[...I,...w.path];if(G.length===0){U.errors.push(b(w));continue}let W=U,Q=0;while(Q<G.length){let O=G[Q],V=Q===G.length-1;if(typeof O==="string")W.properties??(W.properties={}),(X=W.properties)[O]??(X[O]={errors:[]}),W=W.properties[O];else W.items??(W.items=[]),(H=W.items)[O]??(H[O]={errors:[]}),W=W.items[O];if(V)W.errors.push(b(w));Q++}}};return J($),U}function oO($){let b=[],U=$.map((J)=>typeof J==="object"?J.key:J);for(let J of U)if(typeof J==="number")b.push(`[${J}]`);else if(typeof J==="symbol")b.push(`[${JSON.stringify(String(J))}]`);else if(/[^\w$]/.test(J))b.push(`[${JSON.stringify(J)}]`);else{if(b.length)b.push(".");b.push(J)}return b.join("")}function NX($){let b=[],U=[...$.issues].sort((J,D)=>(J.path??[]).length-(D.path??[]).length);for(let J of U)if(b.push(`\u2716 ${J.message}`),J.path?.length)b.push(` \u2192 at ${oO(J.path)}`);return b.join(`
|
|
149
149
|
`)}var g0=($)=>(b,U,J,D)=>{let I=J?{...J,async:!1}:{async:!1},X=b._zod.run({value:U,issues:[]},I);if(X instanceof Promise)throw new k4;if(X.issues.length){let H=new(D?.Err??$)(X.issues.map((w)=>o$(w,I,q$())));throw BD(H,D?.callee),H}return X.value},b1=g0(b4),R0=($)=>async(b,U,J,D)=>{let I=J?{...J,async:!0}:{async:!0},X=b._zod.run({value:U,issues:[]},I);if(X instanceof Promise)X=await X;if(X.issues.length){let H=new(D?.Err??$)(X.issues.map((w)=>o$(w,I,q$())));throw BD(H,D?.callee),H}return X.value},U1=R0(b4),_0=($)=>(b,U,J)=>{let D=J?{...J,async:!1}:{async:!1},I=b._zod.run({value:U,issues:[]},D);if(I instanceof Promise)throw new k4;return I.issues.length?{success:!1,error:new($??sb)(I.issues.map((X)=>o$(X,D,q$())))}:{success:!0,data:I.value}},k0=_0(b4),E0=($)=>async(b,U,J)=>{let D=J?{...J,async:!0}:{async:!0},I=b._zod.run({value:U,issues:[]},D);if(I instanceof Promise)I=await I;return I.issues.length?{success:!1,error:new $(I.issues.map((X)=>o$(X,D,q$())))}:{success:!0,data:I.value}},D1=E0(b4),zD=($)=>(b,U,J)=>{let D=J?{...J,direction:"backward"}:{direction:"backward"};return g0($)(b,U,D)},tO=zD(b4),KD=($)=>(b,U,J)=>{return g0($)(b,U,J)},pO=KD(b4),jD=($)=>async(b,U,J)=>{let D=J?{...J,direction:"backward"}:{direction:"backward"};return R0($)(b,U,D)},aO=jD(b4),LD=($)=>async(b,U,J)=>{return R0($)(b,U,J)},sO=LD(b4),AD=($)=>(b,U,J)=>{let D=J?{...J,direction:"backward"}:{direction:"backward"};return _0($)(b,U,D)},eO=AD(b4),qD=($)=>(b,U,J)=>{return _0($)(b,U,J)},$3=qD(b4),PD=($)=>async(b,U,J)=>{let D=J?{...J,direction:"backward"}:{direction:"backward"};return E0($)(b,U,D)},b3=PD(b4),TD=($)=>async(b,U,J)=>{return E0($)(b,U,J)},U3=TD(b4);var G4={};d4(G4,{xid:()=>RX,uuid7:()=>dF,uuid6:()=>cF,uuid4:()=>rF,uuid:()=>$0,uppercase:()=>J8,unicodeEmail:()=>D3,undefined:()=>U8,ulid:()=>gX,time:()=>tX,string:()=>aX,sha512_hex:()=>VM,sha512_base64url:()=>ZM,sha512_base64:()=>vM,sha384_hex:()=>QM,sha384_base64url:()=>OM,sha384_base64:()=>YM,sha256_hex:()=>wM,sha256_base64url:()=>WM,sha256_base64:()=>GM,sha1_hex:()=>IM,sha1_base64url:()=>HM,sha1_base64:()=>XM,rfc5322Email:()=>tF,number:()=>J1,null:()=>b8,nanoid:()=>kX,md5_hex:()=>UM,md5_base64url:()=>JM,md5_base64:()=>DM,mac:()=>yX,lowercase:()=>D8,ksuid:()=>_X,ipv6:()=>iX,ipv4:()=>nX,integer:()=>eX,idnEmail:()=>pF,httpProtocol:()=>cX,html5Email:()=>oF,hostname:()=>eF,hex:()=>bM,guid:()=>CX,extendedDuration:()=>mF,emoji:()=>lX,email:()=>xX,e164:()=>dX,duration:()=>EX,domain:()=>$M,datetime:()=>pX,date:()=>oX,cuid2:()=>SX,cuid:()=>fX,cidrv6:()=>mX,cidrv4:()=>hX,browserEmail:()=>aF,boolean:()=>$8,bigint:()=>sX,base64url:()=>FD,base64:()=>rX});var fX=/^[cC][0-9a-z]{6,}$/,SX=/^[0-9a-z]+$/,gX=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,RX=/^[0-9a-vA-V]{20}$/,_X=/^[A-Za-z0-9]{27}$/,kX=/^[a-zA-Z0-9_-]{21}$/,EX=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,mF=/^[-+]?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)?)??$/,CX=/^([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})$/,$0=($)=>{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})$`)},rF=$0(4),cF=$0(6),dF=$0(7),xX=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,oF=/^[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])?)*$/,tF=/^(([^<>()\[\]\\.,;:\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,}))$/,D3=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,pF=D3,aF=/^[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])?)*$/,sF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function lX(){return new RegExp(sF,"u")}var nX=/^(?:(?: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])$/,iX=/^(([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}|:))$/,yX=($)=>{let b=O4($??":");return new RegExp(`^(?:[0-9A-F]{2}${b}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${b}){5}[0-9a-f]{2}$`)},hX=/^((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])$/,mX=/^(([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])$/,rX=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,FD=/^[A-Za-z0-9_-]*$/,eF=/^(?=.{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])?)*\.?$/,$M=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,cX=/^https?$/,dX=/^\+[1-9]\d{6,14}$/,J3="(?:(?:\\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])))",oX=new RegExp(`^${J3}$`);function I3($){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 tX($){return new RegExp(`^${I3($)}$`)}function pX($){let b=I3({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let J=`${b}(?:${U.join("|")})`;return new RegExp(`^${J3}T(?:${J})$`)}var aX=($)=>{let b=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${b}$`)},sX=/^-?\d+n?$/,eX=/^-?\d+$/,J1=/^-?\d+(?:\.\d+)?$/,$8=/^(?:true|false)$/i,b8=/^null$/i;var U8=/^undefined$/i;var D8=/^[^A-Z]*$/,J8=/^[^a-z]*$/,bM=/^[0-9a-fA-F]*$/;function I1($,b){return new RegExp(`^[A-Za-z0-9+/]{${$}}${b}$`)}function X1($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var UM=/^[0-9a-fA-F]{32}$/,DM=I1(22,"=="),JM=X1(22),IM=/^[0-9a-fA-F]{40}$/,XM=I1(27,"="),HM=X1(27),wM=/^[0-9a-fA-F]{64}$/,GM=I1(43,"="),WM=X1(43),QM=/^[0-9a-fA-F]{96}$/,YM=I1(64,""),OM=X1(64),VM=/^[0-9a-fA-F]{128}$/,vM=I1(86,"=="),ZM=X1(86);var Z$=z("$ZodCheck",($,b)=>{var U;$._zod??($._zod={}),$._zod.def=b,(U=$._zod).onattach??(U.onattach=[])}),H3={number:"number",bigint:"bigint",object:"date"},MD=z("$ZodCheckLessThan",($,b)=>{Z$.init($,b);let U=H3[typeof b.value];$._zod.onattach.push((J)=>{let D=J._zod.bag,I=(b.inclusive?D.maximum:D.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(b.value<I)if(b.inclusive)D.maximum=b.value;else D.exclusiveMaximum=b.value}),$._zod.check=(J)=>{if(b.inclusive?J.value<=b.value:J.value<b.value)return;J.issues.push({origin:U,code:"too_big",maximum:typeof b.value==="object"?b.value.getTime():b.value,input:J.value,inclusive:b.inclusive,inst:$,continue:!b.abort})}}),uD=z("$ZodCheckGreaterThan",($,b)=>{Z$.init($,b);let U=H3[typeof b.value];$._zod.onattach.push((J)=>{let D=J._zod.bag,I=(b.inclusive?D.minimum:D.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(b.value>I)if(b.inclusive)D.minimum=b.value;else D.exclusiveMinimum=b.value}),$._zod.check=(J)=>{if(b.inclusive?J.value>=b.value:J.value>b.value)return;J.issues.push({origin:U,code:"too_small",minimum:typeof b.value==="object"?b.value.getTime():b.value,input:J.value,inclusive:b.inclusive,inst:$,continue:!b.abort})}}),I8=z("$ZodCheckMultipleOf",($,b)=>{Z$.init($,b),$._zod.onattach.push((U)=>{var J;(J=U._zod.bag).multipleOf??(J.multipleOf=b.value)}),$._zod.check=(U)=>{if(typeof U.value!==typeof b.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof U.value==="bigint"?U.value%b.value===BigInt(0):KX(U.value,b.value)===0)return;U.issues.push({origin:typeof U.value,code:"not_multiple_of",divisor:b.value,input:U.value,inst:$,continue:!b.abort})}}),X8=z("$ZodCheckNumberFormat",($,b)=>{Z$.init($,b),b.format=b.format||"float64";let U=b.format?.includes("int"),J=U?"int":"number",[D,I]=TX[b.format];$._zod.onattach.push((X)=>{let H=X._zod.bag;if(H.format=b.format,H.minimum=D,H.maximum=I,U)H.pattern=eX}),$._zod.check=(X)=>{let H=X.value;if(U){if(!Number.isInteger(H)){X.issues.push({expected:J,format:b.format,code:"invalid_type",continue:!1,input:H,inst:$});return}if(!Number.isSafeInteger(H)){if(H>0)X.issues.push({input:H,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:J,inclusive:!0,continue:!b.abort});else X.issues.push({input:H,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:J,inclusive:!0,continue:!b.abort});return}}if(H<D)X.issues.push({origin:"number",input:H,code:"too_small",minimum:D,inclusive:!0,inst:$,continue:!b.abort});if(H>I)X.issues.push({origin:"number",input:H,code:"too_big",maximum:I,inclusive:!0,inst:$,continue:!b.abort})}}),H8=z("$ZodCheckBigIntFormat",($,b)=>{Z$.init($,b);let[U,J]=FX[b.format];$._zod.onattach.push((D)=>{let I=D._zod.bag;I.format=b.format,I.minimum=U,I.maximum=J}),$._zod.check=(D)=>{let I=D.value;if(I<U)D.issues.push({origin:"bigint",input:I,code:"too_small",minimum:U,inclusive:!0,inst:$,continue:!b.abort});if(I>J)D.issues.push({origin:"bigint",input:I,code:"too_big",maximum:J,inclusive:!0,inst:$,continue:!b.abort})}}),w8=z("$ZodCheckMaxSize",($,b)=>{var U;Z$.init($,b),(U=$._zod.def).when??(U.when=(J)=>{let D=J.value;return!B6(D)&&D.size!==void 0}),$._zod.onattach.push((J)=>{let D=J._zod.bag.maximum??Number.POSITIVE_INFINITY;if(b.maximum<D)J._zod.bag.maximum=b.maximum}),$._zod.check=(J)=>{let D=J.value;if(D.size<=b.maximum)return;J.issues.push({origin:pb(D),code:"too_big",maximum:b.maximum,inclusive:!0,input:D,inst:$,continue:!b.abort})}}),G8=z("$ZodCheckMinSize",($,b)=>{var U;Z$.init($,b),(U=$._zod.def).when??(U.when=(J)=>{let D=J.value;return!B6(D)&&D.size!==void 0}),$._zod.onattach.push((J)=>{let D=J._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(b.minimum>D)J._zod.bag.minimum=b.minimum}),$._zod.check=(J)=>{let D=J.value;if(D.size>=b.minimum)return;J.issues.push({origin:pb(D),code:"too_small",minimum:b.minimum,inclusive:!0,input:D,inst:$,continue:!b.abort})}}),W8=z("$ZodCheckSizeEquals",($,b)=>{var U;Z$.init($,b),(U=$._zod.def).when??(U.when=(J)=>{let D=J.value;return!B6(D)&&D.size!==void 0}),$._zod.onattach.push((J)=>{let D=J._zod.bag;D.minimum=b.size,D.maximum=b.size,D.size=b.size}),$._zod.check=(J)=>{let D=J.value,I=D.size;if(I===b.size)return;let X=I>b.size;J.issues.push({origin:pb(D),...X?{code:"too_big",maximum:b.size}:{code:"too_small",minimum:b.size},inclusive:!0,exact:!0,input:J.value,inst:$,continue:!b.abort})}}),Q8=z("$ZodCheckMaxLength",($,b)=>{var U;Z$.init($,b),(U=$._zod.def).when??(U.when=(J)=>{let D=J.value;return!B6(D)&&D.length!==void 0}),$._zod.onattach.push((J)=>{let D=J._zod.bag.maximum??Number.POSITIVE_INFINITY;if(b.maximum<D)J._zod.bag.maximum=b.maximum}),$._zod.check=(J)=>{let D=J.value;if(D.length<=b.maximum)return;let X=ab(D);J.issues.push({origin:X,code:"too_big",maximum:b.maximum,inclusive:!0,input:D,inst:$,continue:!b.abort})}}),Y8=z("$ZodCheckMinLength",($,b)=>{var U;Z$.init($,b),(U=$._zod.def).when??(U.when=(J)=>{let D=J.value;return!B6(D)&&D.length!==void 0}),$._zod.onattach.push((J)=>{let D=J._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(b.minimum>D)J._zod.bag.minimum=b.minimum}),$._zod.check=(J)=>{let D=J.value;if(D.length>=b.minimum)return;let X=ab(D);J.issues.push({origin:X,code:"too_small",minimum:b.minimum,inclusive:!0,input:D,inst:$,continue:!b.abort})}}),O8=z("$ZodCheckLengthEquals",($,b)=>{var U;Z$.init($,b),(U=$._zod.def).when??(U.when=(J)=>{let D=J.value;return!B6(D)&&D.length!==void 0}),$._zod.onattach.push((J)=>{let D=J._zod.bag;D.minimum=b.length,D.maximum=b.length,D.length=b.length}),$._zod.check=(J)=>{let D=J.value,I=D.length;if(I===b.length)return;let X=ab(D),H=I>b.length;J.issues.push({origin:X,...H?{code:"too_big",maximum:b.length}:{code:"too_small",minimum:b.length},inclusive:!0,exact:!0,input:J.value,inst:$,continue:!b.abort})}}),C0=z("$ZodCheckStringFormat",($,b)=>{var U,J;if(Z$.init($,b),$._zod.onattach.push((D)=>{let I=D._zod.bag;if(I.format=b.format,b.pattern)I.patterns??(I.patterns=new Set),I.patterns.add(b.pattern)}),b.pattern)(U=$._zod).check??(U.check=(D)=>{if(b.pattern.lastIndex=0,b.pattern.test(D.value))return;D.issues.push({origin:"string",code:"invalid_format",format:b.format,input:D.value,...b.pattern?{pattern:b.pattern.toString()}:{},inst:$,continue:!b.abort})});else(J=$._zod).check??(J.check=()=>{})}),V8=z("$ZodCheckRegex",($,b)=>{C0.init($,b),$._zod.check=(U)=>{if(b.pattern.lastIndex=0,b.pattern.test(U.value))return;U.issues.push({origin:"string",code:"invalid_format",format:"regex",input:U.value,pattern:b.pattern.toString(),inst:$,continue:!b.abort})}}),v8=z("$ZodCheckLowerCase",($,b)=>{b.pattern??(b.pattern=D8),C0.init($,b)}),Z8=z("$ZodCheckUpperCase",($,b)=>{b.pattern??(b.pattern=J8),C0.init($,b)}),B8=z("$ZodCheckIncludes",($,b)=>{Z$.init($,b);let U=O4(b.includes),J=new RegExp(typeof b.position==="number"?`^.{${b.position}}${U}`:U);b.pattern=J,$._zod.onattach.push((D)=>{let I=D._zod.bag;I.patterns??(I.patterns=new Set),I.patterns.add(J)}),$._zod.check=(D)=>{if(D.value.includes(b.includes,b.position))return;D.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:b.includes,input:D.value,inst:$,continue:!b.abort})}}),z8=z("$ZodCheckStartsWith",($,b)=>{Z$.init($,b);let U=new RegExp(`^${O4(b.prefix)}.*`);b.pattern??(b.pattern=U),$._zod.onattach.push((J)=>{let D=J._zod.bag;D.patterns??(D.patterns=new Set),D.patterns.add(U)}),$._zod.check=(J)=>{if(J.value.startsWith(b.prefix))return;J.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:b.prefix,input:J.value,inst:$,continue:!b.abort})}}),K8=z("$ZodCheckEndsWith",($,b)=>{Z$.init($,b);let U=new RegExp(`.*${O4(b.suffix)}$`);b.pattern??(b.pattern=U),$._zod.onattach.push((J)=>{let D=J._zod.bag;D.patterns??(D.patterns=new Set),D.patterns.add(U)}),$._zod.check=(J)=>{if(J.value.endsWith(b.suffix))return;J.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:b.suffix,input:J.value,inst:$,continue:!b.abort})}});function X3($,b,U){if($.issues.length)b.issues.push(...$4(U,$.issues))}var j8=z("$ZodCheckProperty",($,b)=>{Z$.init($,b),$._zod.check=(U)=>{let J=b.schema._zod.run({value:U.value[b.property],issues:[]},{});if(J instanceof Promise)return J.then((D)=>X3(D,U,b.property));X3(J,U,b.property);return}}),L8=z("$ZodCheckMimeType",($,b)=>{Z$.init($,b);let U=new Set(b.mime);$._zod.onattach.push((J)=>{J._zod.bag.mime=b.mime}),$._zod.check=(J)=>{if(U.has(J.value.type))return;J.issues.push({code:"invalid_value",values:b.mime,input:J.value.type,inst:$,continue:!b.abort})}}),A8=z("$ZodCheckOverwrite",($,b)=>{Z$.init($,b),$._zod.check=(U)=>{U.value=b.tx(U.value)}});class ND{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 U=$.split(`
|
|
150
150
|
`).filter((I)=>I),J=Math.min(...U.map((I)=>I.length-I.trimStart().length)),D=U.map((I)=>I.slice(J)).map((I)=>" ".repeat(this.indent*2)+I);for(let I of D)this.content.push(I)}compile(){let $=Function,b=this?.args,J=[...(this?.content??[""]).map((D)=>` ${D}`)];return new $(...b,J.join(`
|
|
151
151
|
`))}}var q8={major:4,minor:4,patch:3};var m=z("$ZodType",($,b)=>{var U;$??($={}),$._zod.def=b,$._zod.bag=$._zod.bag||{},$._zod.version=q8;let J=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))J.unshift($);for(let D of J)for(let I of D._zod.onattach)I($);if(J.length===0)(U=$._zod).deferred??(U.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let D=(X,H,w)=>{let G=j6(X),W;for(let Q of H){if(Q._zod.def.when){if(MX(X))continue;if(!Q._zod.def.when(X))continue}else if(G)continue;let O=X.issues.length,V=Q._zod.check(X);if(V instanceof Promise&&w?.async===!1)throw new k4;if(W||V instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await V,X.issues.length===O)return;if(!G)G=j6(X,O)});else{if(X.issues.length===O)continue;if(!G)G=j6(X,O)}}if(W)return W.then(()=>{return X});return X},I=(X,H,w)=>{if(j6(X))return X.aborted=!0,X;let G=D(H,J,w);if(G instanceof Promise){if(w.async===!1)throw new k4;return G.then((W)=>$._zod.parse(W,w))}return $._zod.parse(G,w)};$._zod.run=(X,H)=>{if(H.skipChecks)return $._zod.parse(X,H);if(H.direction==="backward"){let G=$._zod.parse({value:X.value,issues:[]},{...H,skipChecks:!0});if(G instanceof Promise)return G.then((W)=>{return I(W,X,H)});return I(G,X,H)}let w=$._zod.parse(X,H);if(w instanceof Promise){if(H.async===!1)throw new k4;return w.then((G)=>D(G,J,H))}return D(w,J,H)}}a($,"~standard",()=>({validate:(D)=>{try{let I=k0($,D);return I.success?{value:I.data}:{issues:I.error?.issues}}catch(I){return D1($,D).then((X)=>X.success?{value:X.data}:{issues:X.error?.issues})}},vendor:"zod",version:1}))}),b0=z("$ZodString",($,b)=>{m.init($,b),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??aX($._zod.bag),$._zod.parse=(U,J)=>{if(b.coerce)try{U.value=String(U.value)}catch(D){}if(typeof U.value==="string")return U;return U.issues.push({expected:"string",code:"invalid_type",input:U.value,inst:$}),U}}),W$=z("$ZodStringFormat",($,b)=>{C0.init($,b),b0.init($,b)}),T8=z("$ZodGUID",($,b)=>{b.pattern??(b.pattern=CX),W$.init($,b)}),F8=z("$ZodUUID",($,b)=>{if(b.version){let J={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[b.version];if(J===void 0)throw Error(`Invalid UUID version: "${b.version}"`);b.pattern??(b.pattern=$0(J))}else b.pattern??(b.pattern=$0());W$.init($,b)}),M8=z("$ZodEmail",($,b)=>{b.pattern??(b.pattern=xX),W$.init($,b)}),u8=z("$ZodURL",($,b)=>{W$.init($,b),$._zod.check=(U)=>{try{let J=U.value.trim();if(!b.normalize&&b.protocol?.source===cX.source){if(!/^https?:\/\//i.test(J)){U.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:U.value,inst:$,continue:!b.abort});return}}let D=new URL(J);if(b.hostname){if(b.hostname.lastIndex=0,!b.hostname.test(D.hostname))U.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:b.hostname.source,input:U.value,inst:$,continue:!b.abort})}if(b.protocol){if(b.protocol.lastIndex=0,!b.protocol.test(D.protocol.endsWith(":")?D.protocol.slice(0,-1):D.protocol))U.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:b.protocol.source,input:U.value,inst:$,continue:!b.abort})}if(b.normalize)U.value=D.href;else U.value=J;return}catch(J){U.issues.push({code:"invalid_format",format:"url",input:U.value,inst:$,continue:!b.abort})}}}),N8=z("$ZodEmoji",($,b)=>{b.pattern??(b.pattern=lX()),W$.init($,b)}),f8=z("$ZodNanoID",($,b)=>{b.pattern??(b.pattern=kX),W$.init($,b)}),S8=z("$ZodCUID",($,b)=>{b.pattern??(b.pattern=fX),W$.init($,b)}),g8=z("$ZodCUID2",($,b)=>{b.pattern??(b.pattern=SX),W$.init($,b)}),R8=z("$ZodULID",($,b)=>{b.pattern??(b.pattern=gX),W$.init($,b)}),_8=z("$ZodXID",($,b)=>{b.pattern??(b.pattern=RX),W$.init($,b)}),k8=z("$ZodKSUID",($,b)=>{b.pattern??(b.pattern=_X),W$.init($,b)}),E8=z("$ZodISODateTime",($,b)=>{b.pattern??(b.pattern=pX(b)),W$.init($,b)}),C8=z("$ZodISODate",($,b)=>{b.pattern??(b.pattern=oX),W$.init($,b)}),x8=z("$ZodISOTime",($,b)=>{b.pattern??(b.pattern=tX(b)),W$.init($,b)}),l8=z("$ZodISODuration",($,b)=>{b.pattern??(b.pattern=EX),W$.init($,b)}),n8=z("$ZodIPv4",($,b)=>{b.pattern??(b.pattern=nX),W$.init($,b),$._zod.bag.format="ipv4"}),i8=z("$ZodIPv6",($,b)=>{b.pattern??(b.pattern=iX),W$.init($,b),$._zod.bag.format="ipv6",$._zod.check=(U)=>{try{new URL(`http://[${U.value}]`)}catch{U.issues.push({code:"invalid_format",format:"ipv6",input:U.value,inst:$,continue:!b.abort})}}}),y8=z("$ZodMAC",($,b)=>{b.pattern??(b.pattern=yX(b.delimiter)),W$.init($,b),$._zod.bag.format="mac"}),h8=z("$ZodCIDRv4",($,b)=>{b.pattern??(b.pattern=hX),W$.init($,b)}),m8=z("$ZodCIDRv6",($,b)=>{b.pattern??(b.pattern=mX),W$.init($,b),$._zod.check=(U)=>{let J=U.value.split("/");try{if(J.length!==2)throw Error();let[D,I]=J;if(!I)throw Error();let X=Number(I);if(`${X}`!==I)throw Error();if(X<0||X>128)throw Error();new URL(`http://[${D}]`)}catch{U.issues.push({code:"invalid_format",format:"cidrv6",input:U.value,inst:$,continue:!b.abort})}}});function r8($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var c8=z("$ZodBase64",($,b)=>{b.pattern??(b.pattern=rX),W$.init($,b),$._zod.bag.contentEncoding="base64",$._zod.check=(U)=>{if(r8(U.value))return;U.issues.push({code:"invalid_format",format:"base64",input:U.value,inst:$,continue:!b.abort})}});function q3($){if(!FD.test($))return!1;let b=$.replace(/[-_]/g,(J)=>J==="-"?"+":"/"),U=b.padEnd(Math.ceil(b.length/4)*4,"=");return r8(U)}var d8=z("$ZodBase64URL",($,b)=>{b.pattern??(b.pattern=FD),W$.init($,b),$._zod.bag.contentEncoding="base64url",$._zod.check=(U)=>{if(q3(U.value))return;U.issues.push({code:"invalid_format",format:"base64url",input:U.value,inst:$,continue:!b.abort})}}),o8=z("$ZodE164",($,b)=>{b.pattern??(b.pattern=dX),W$.init($,b)});function P3($,b=null){try{let U=$.split(".");if(U.length!==3)return!1;let[J]=U;if(!J)return!1;let D=JSON.parse(atob(J));if("typ"in D&&D?.typ!=="JWT")return!1;if(!D.alg)return!1;if(b&&(!("alg"in D)||D.alg!==b))return!1;return!0}catch{return!1}}var t8=z("$ZodJWT",($,b)=>{W$.init($,b),$._zod.check=(U)=>{if(P3(U.value,b.alg))return;U.issues.push({code:"invalid_format",format:"jwt",input:U.value,inst:$,continue:!b.abort})}}),p8=z("$ZodCustomStringFormat",($,b)=>{W$.init($,b),$._zod.check=(U)=>{if(b.fn(U.value))return;U.issues.push({code:"invalid_format",format:b.format,input:U.value,inst:$,continue:!b.abort})}}),_D=z("$ZodNumber",($,b)=>{m.init($,b),$._zod.pattern=$._zod.bag.pattern??J1,$._zod.parse=(U,J)=>{if(b.coerce)try{U.value=Number(U.value)}catch(X){}let D=U.value;if(typeof D==="number"&&!Number.isNaN(D)&&Number.isFinite(D))return U;let I=typeof D==="number"?Number.isNaN(D)?"NaN":!Number.isFinite(D)?"Infinity":void 0:void 0;return U.issues.push({expected:"number",code:"invalid_type",input:D,inst:$,...I?{received:I}:{}}),U}}),a8=z("$ZodNumberFormat",($,b)=>{X8.init($,b),_D.init($,b)}),H1=z("$ZodBoolean",($,b)=>{m.init($,b),$._zod.pattern=$8,$._zod.parse=(U,J)=>{if(b.coerce)try{U.value=Boolean(U.value)}catch(I){}let D=U.value;if(typeof D==="boolean")return U;return U.issues.push({expected:"boolean",code:"invalid_type",input:D,inst:$}),U}}),kD=z("$ZodBigInt",($,b)=>{m.init($,b),$._zod.pattern=sX,$._zod.parse=(U,J)=>{if(b.coerce)try{U.value=BigInt(U.value)}catch(D){}if(typeof U.value==="bigint")return U;return U.issues.push({expected:"bigint",code:"invalid_type",input:U.value,inst:$}),U}}),s8=z("$ZodBigIntFormat",($,b)=>{H8.init($,b),kD.init($,b)}),e8=z("$ZodSymbol",($,b)=>{m.init($,b),$._zod.parse=(U,J)=>{let D=U.value;if(typeof D==="symbol")return U;return U.issues.push({expected:"symbol",code:"invalid_type",input:D,inst:$}),U}}),$H=z("$ZodUndefined",($,b)=>{m.init($,b),$._zod.pattern=U8,$._zod.values=new Set([void 0]),$._zod.parse=(U,J)=>{let D=U.value;if(typeof D>"u")return U;return U.issues.push({expected:"undefined",code:"invalid_type",input:D,inst:$}),U}}),bH=z("$ZodNull",($,b)=>{m.init($,b),$._zod.pattern=b8,$._zod.values=new Set([null]),$._zod.parse=(U,J)=>{let D=U.value;if(D===null)return U;return U.issues.push({expected:"null",code:"invalid_type",input:D,inst:$}),U}}),UH=z("$ZodAny",($,b)=>{m.init($,b),$._zod.parse=(U)=>U}),DH=z("$ZodUnknown",($,b)=>{m.init($,b),$._zod.parse=(U)=>U}),JH=z("$ZodNever",($,b)=>{m.init($,b),$._zod.parse=(U,J)=>{return U.issues.push({expected:"never",code:"invalid_type",input:U.value,inst:$}),U}}),IH=z("$ZodVoid",($,b)=>{m.init($,b),$._zod.parse=(U,J)=>{let D=U.value;if(typeof D>"u")return U;return U.issues.push({expected:"void",code:"invalid_type",input:D,inst:$}),U}}),XH=z("$ZodDate",($,b)=>{m.init($,b),$._zod.parse=(U,J)=>{if(b.coerce)try{U.value=new Date(U.value)}catch(H){}let D=U.value,I=D instanceof Date;if(I&&!Number.isNaN(D.getTime()))return U;return U.issues.push({expected:"date",code:"invalid_type",input:D,...I?{received:"Invalid Date"}:{},inst:$}),U}});function G3($,b,U){if($.issues.length)b.issues.push(...$4(U,$.issues));b.value[U]=$.value}var HH=z("$ZodArray",($,b)=>{m.init($,b),$._zod.parse=(U,J)=>{let D=U.value;if(!Array.isArray(D))return U.issues.push({expected:"array",code:"invalid_type",input:D,inst:$}),U;U.value=Array(D.length);let I=[];for(let X=0;X<D.length;X++){let H=D[X],w=b.element._zod.run({value:H,issues:[]},J);if(w instanceof Promise)I.push(w.then((G)=>G3(G,U,X)));else G3(w,U,X)}if(I.length)return Promise.all(I).then(()=>U);return U}});function RD($,b,U,J,D,I){let X=U in J;if($.issues.length){if(D&&I&&!X)return;b.issues.push(...$4(U,$.issues))}if(!X&&!D){if(!$.issues.length)b.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[U]});return}if($.value===void 0){if(X)b.value[U]=void 0}else b.value[U]=$.value}function T3($){let b=Object.keys($.shape);for(let J of b)if(!$.shape?.[J]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${J}": expected a Zod schema`);let U=PX($.shape);return{...$,keys:b,keySet:new Set(b),numKeys:b.length,optionalKeys:new Set(U)}}function F3($,b,U,J,D,I){let X=[],H=D.keySet,w=D.catchall._zod,G=w.def.type,W=w.optin==="optional",Q=w.optout==="optional";for(let O in b){if(O==="__proto__")continue;if(H.has(O))continue;if(G==="never"){X.push(O);continue}let V=w.run({value:b[O],issues:[]},J);if(V instanceof Promise)$.push(V.then((Z)=>RD(Z,U,O,b,W,Q)));else RD(V,U,O,b,W,Q)}if(X.length)U.issues.push({code:"unrecognized_keys",keys:X,input:b,inst:I});if(!$.length)return U;return Promise.all($).then(()=>{return U})}var M3=z("$ZodObject",($,b)=>{if(m.init($,b),!Object.getOwnPropertyDescriptor(b,"shape")?.get){let H=b.shape;Object.defineProperty(b,"shape",{get:()=>{let w={...H};return Object.defineProperty(b,"shape",{value:w}),w}})}let J=f0(()=>T3(b));a($._zod,"propValues",()=>{let H=b.shape,w={};for(let G in H){let W=H[G]._zod;if(W.values){w[G]??(w[G]=new Set);for(let Q of W.values)w[G].add(Q)}}return w});let D=e6,I=b.catchall,X;$._zod.parse=(H,w)=>{X??(X=J.value);let G=H.value;if(!D(G))return H.issues.push({expected:"object",code:"invalid_type",input:G,inst:$}),H;H.value={};let W=[],Q=X.shape;for(let O of X.keys){let V=Q[O],Z=V._zod.optin==="optional",v=V._zod.optout==="optional",B=V._zod.run({value:G[O],issues:[]},w);if(B instanceof Promise)W.push(B.then((K)=>RD(K,H,O,G,Z,v)));else RD(B,H,O,G,Z,v)}if(!I)return W.length?Promise.all(W).then(()=>H):H;return F3(W,G,H,w,J.value,$)}}),wH=z("$ZodObjectJIT",($,b)=>{M3.init($,b);let U=$._zod.parse,J=f0(()=>T3(b)),D=(O)=>{let V=new ND(["shape","payload","ctx"]),Z=J.value,v=(M)=>{let f=ZD(M);return`shape[${f}]._zod.run({ value: input[${f}], issues: [] }, ctx)`};V.write("const input = payload.value;");let B=Object.create(null),K=0;for(let M of Z.keys)B[M]=`key_${K++}`;V.write("const newResult = {};");for(let M of Z.keys){let f=B[M],F=ZD(M),x=O[M],t=x?._zod?.optin==="optional",C=x?._zod?.optout==="optional";if(V.write(`const ${f} = ${v(M)};`),t&&C)V.write(`
|
|
@@ -1591,9 +1591,9 @@ Runs "bun i -g @interactive-inc/claude-funnel".
|
|
|
1591
1591
|
This command has no programmable equivalent \u2014 package management belongs to
|
|
1592
1592
|
the host (npm / bun / yarn install in the host's own way).`,vT="@interactive-inc/claude-funnel",ZT=q.createHandlers(n(ta),async($)=>{let U=await new N$().attach(["bun","i","-g",vT]);if(U!==0)throw new h(500,{message:`update failed (exit ${U})`});return $.text(`updated ${vT}`)});var pY=q.createApp().onError(($,b)=>{if($ instanceof h)return b.text($.message,$.status);return b.text(`error: ${$ instanceof Error?$.message:String($)}`,400)}).get("/claude",...Lv).get("/channels",...NP).post("/channels/add",...DP).post("/channels/add/:channel",...JP).post("/channels/remove",...qP).post("/channels/remove/:channel",...PP).post("/channels/rename/:channel/:newName",...yY).post("/channels/:channel/rename/:newName",...yY).post("/channels/rename",...TP).post("/channels/:channel/rename",...FP).post("/channels/:channel/set/delivery/:mode",...MP).post("/channels/publish",...LP).post("/channels/:channel/publish",...AP).get("/channels/:channel/validate",...SP).get("/channels/validate",...fP).get("/channels/:channel",...uP).get("/channels/:channel/connectors",...IP).post("/channels/:channel/connectors/add",...XP).post("/channels/:channel/connectors/add/:connector",...HP).post("/channels/:channel/connectors/remove",...wP).post("/channels/:channel/connectors/remove/:connector",...GP).post("/channels/:channel/connectors/set",...WP).post("/channels/:channel/connectors/set/:connector",...QP).post("/channels/:channel/connectors/rename/:connector/:newName",...nY).post("/channels/:channel/connectors/:connector/rename/:newName",...nY).post("/channels/:channel/connectors/rename",...OP).post("/channels/:channel/connectors/:connector/rename",...VP).post("/channels/:channel/connectors/:connector/request",...vP).get("/channels/:channel/connectors/:connector",...YP).get("/channels/:channel/connectors/:connector/schedules",...ZP).post("/channels/:channel/connectors/:connector/schedules/add",...BP).post("/channels/:channel/connectors/:connector/schedules/add/:id",...zP).post("/channels/:channel/connectors/:connector/schedules/remove",...KP).post("/channels/:channel/connectors/:connector/schedules/remove/:id",...jP).get("/profiles",...WT).post("/profiles/add",...bT).post("/profiles/add/:profile",...UT).post("/profiles/set",...wT).post("/profiles/set/:profile",...GT).post("/profiles/remove",...XT).post("/profiles/remove/:profile",...HT).post("/profiles/rename/:profile/:newName",...oY).post("/profiles/:profile/rename/:newName",...oY).post("/profiles/rename",...JT).post("/profiles/:profile/rename",...IT).post("/profiles/:profile/as-default",...DT).get("/profiles/:profile/run",...tY).get("/profiles/:profile",...tY).get("/gateway",...hP).get("/gateway/status",...eP).get("/gateway/start",...sP).get("/gateway/stop",...$T).get("/gateway/restart",...tP).get("/gateway/run",...pP).get("/gateway/logs",...cP).get("/gateway/sql",...oP).get("/gateway/listeners",...mP).get("/debug",...gP).get("/debug/events",...RP).get("/debug/dropped",..._P).get("/debug/errors",...kP).get("/debug/replay",...EP).get("/debug/raw",...CP).get("/debug/connection",...xP).get("/debug/logs",...lP).get("/docs",...nP).get("/docs/:topic",...iP).get("/doctor",...yP).get("/schema",...YT).get("/status",...VT).get("/update",...ZT);import{join as pa}from"path";class GD{fs;constructor($){this.fs=$.fs,Object.freeze(this)}read($){let b=pa($,t6);if(!this.fs.existsSync(b))return null;let U=this.fs.readFileSync(b),J=(()=>{try{return JSON.parse(U)}catch(I){let X=I instanceof Error?I.message:String(I);throw Error(`${t6} is not valid JSON: ${X}`)}})(),D=IX.safeParse(J);if(!D.success)throw Error(`${t6} is invalid: ${D.error.message}`);return this.assertProfilesValid(D.data),D.data}assertProfilesValid($){let b=$.profiles??[];if(b.length===0)return;let U=new Set($.channels.map((D)=>D.name)),J=new Set;for(let D of b){if(!U.has(D.channel))throw Error(`${t6} is invalid: profile "${D.name}" binds channel "${D.channel}", which is not declared in channels[]`);if(J.has(D.name))throw Error(`${t6} is invalid: more than one profile is named "${D.name}" \u2014 names must be unique`);J.add(D.name)}}}import{join as aa}from"path";var sa=($)=>{return typeof $==="object"&&$!==null&&!Array.isArray($)},ea=($,b)=>{let U={};if($.$schema!==void 0)U.$schema=$.$schema;U.id=b;for(let J of Object.keys($)){if(J==="$schema"||J==="id")continue;U[J]=$[J]}return U};class aY{fs;constructor($){this.fs=$.fs,Object.freeze(this)}ensureId($,b){let U=aa($,t6);if(!this.fs.existsSync(U))return null;return this.fs.withFileLock(`${U}.lock`,()=>{let J=JSON.parse(this.fs.readFileSync(U));if(!sa(J))return null;if(typeof J.id==="string"&&J.id!=="")return J.id;let D=ea(J,b);return this.fs.writeFileSync(U,`${JSON.stringify(D,null,2)}
|
|
1593
1593
|
`),b})}}import{join as ye}from"path";var BT=($,b)=>{return $=$.replace(/\/+$/,""),$=$+"/",b=b.replace(/^\/+/,""),$+b},HX=($,b)=>{for(let[U,J]of Object.entries(b)){let D=new RegExp("/:"+U+"(?:{[^/]+})?\\??(?=/|$)");$=$.replace(D,J?`/${J}`:"")}return $},zT=($)=>{let b=new URLSearchParams;for(let[U,J]of Object.entries($)){if(J===void 0)continue;if(Array.isArray(J))for(let D of J)b.append(U,D);else b.set(U,J)}return b},KT=($,b)=>{switch(b){case"ws":return $.replace(/^http/,"ws");case"http":return $.replace(/^ws/,"http")}},sY=($)=>{if(/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test($))return $.replace(/\/index(?=\?|$)/,"/");return $.replace(/\/index(?=\?|$)/,"")};function XX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function eY($,b){if(!XX($)&&!XX(b))return b;let U={...$};for(let J in b){let D=b[J];if(XX(U[J])&&XX(D))U[J]=eY(U[J],D);else U[J]=D}return U}var jT=($,b)=>{return new Proxy(()=>{},{get(J,D){if(typeof D!=="string"||D==="then")return;return jT($,[...b,D])},apply(J,D,I){return $({path:b,args:I})}})},bs=class{url;method;buildSearchParams;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor($,b,U){this.url=$,this.method=b,this.buildSearchParams=U.buildSearchParams}fetch=async($,b)=>{if($){if($.query)this.queryParams=this.buildSearchParams($.query);if($.form){let H=new FormData;for(let[w,G]of Object.entries($.form)){if(G===void 0)continue;if(Array.isArray(G))for(let W of G)H.append(w,W);else H.append(w,G)}this.rBody=H}if($.json)this.rBody=JSON.stringify($.json),this.cType="application/json";if($.param)this.pathParams=$.param}let U=this.method.toUpperCase(),J={...$?.header,...typeof b?.headers==="function"?await b.headers():b?.headers};if($?.cookie){let H=[];for(let[w,G]of Object.entries($.cookie))H.push(ZQ(w,G,{path:"/"}));J.Cookie=H.join(",")}if(this.cType)J["Content-Type"]=this.cType;let D=new Headers(J??void 0),I=this.url;if(I=sY(I),I=HX(I,this.pathParams),this.queryParams)I=I+"?"+this.queryParams.toString();U=this.method.toUpperCase();let X=!(U==="GET"||U==="HEAD");return(b?.fetch||fetch)(I,{body:X?this.rBody:void 0,method:U,headers:D,...b?.init})}},$O=($,b)=>jT(function U(J){let D=b?.buildSearchParams??zT,I=[...J.path],X=I.slice(-3).reverse();if(X[0]==="toString"){if(X[1]==="name")return X[2]||"";return U.toString()}if(X[0]==="valueOf"){if(X[1]==="name")return X[2]||"";return U}let H="";if(/^\$/.test(X[0])){let Q=I.pop();if(Q)H=Q.replace(/^\$/,"")}let w=I.join("/"),G=BT($,w);if(H==="url"||H==="path"){let Q=G;if(J.args[0]){if(J.args[0].param)Q=HX(G,J.args[0].param);if(J.args[0].query)Q=Q+"?"+D(J.args[0].query).toString()}if(Q=sY(Q),H==="url")return new URL(Q);return Q.slice($.replace(/\/+$/,"").length).replace(/^\/?/,"/")}if(H==="ws"){let Q=KT(J.args[0]&&J.args[0].param?HX(G,J.args[0].param):G,"ws"),O=new URL(Q),V=J.args[0]?.query;if(V)Object.entries(V).forEach(([v,B])=>{if(Array.isArray(B))B.forEach((K)=>O.searchParams.append(v,K));else O.searchParams.set(v,B)});return((...v)=>{if(b?.webSocket!==void 0&&typeof b.webSocket==="function")return b.webSocket(...v);return new WebSocket(...v)})(O.toString())}let W=new bs(G,H,{buildSearchParams:D});if(H){b??={};let Q={...J.args[1]},O=b.headers,V=Q.headers;if(O&&V)Q.headers=async()=>({...typeof O==="function"?await O():O,...typeof V==="function"?await V():V});let Z=eY(b,Q);return W.fetch(J.args[0],Z)}return W},[]);import{join as LT}from"path";class WD{millis(){return this.now().getTime()}iso(){return this.now().toISOString()}}class V6 extends WD{now(){return new Date}}var Us=new F$,Ds=new N$,Js=new A4,Is=new V6;class bO{descriptors;fs;process;http;clock;logger;diagnosticLog;signal;dir;constructor($){this.descriptors=new Map($.descriptors.map((b)=>[b.type,b])),this.fs=$.fs??Us,this.process=$.process??Ds,this.http=$.http??Js,this.clock=$.clock??Is,this.logger=$.logger,this.diagnosticLog=$.diagnosticLog,this.signal=$.signal,this.dir=$.dir??R4,Object.freeze(this)}has($){return this.descriptors.has($)}types(){return[...this.descriptors.keys()]}createListener($,b){return this.require(b.type).createListener(b,this.listenerDeps($))}createAdapter($){let b=this.require($.type);if(!b.createAdapter)return null;return b.createAdapter($,this.adapterDeps())}secretTokens($){return this.require($.type).secretTokens($)}buildConfig($,b){let U=typeof $.type==="string"?$.type:"";return this.require(U).buildConfig($,b)}applyUpdate($,b,U){return this.require($.type).applyUpdate($,b,U)}runOperation($,b,U,J){let I=this.require($.type).operations[b];if(!I)throw Error(`connector type "${$.type}" has no operation "${b}"`);return I({config:$,args:U,context:J})}connectorDir($,b){return LT(this.dir,"channels",$,"connectors",b)}channelDir($){return LT(this.dir,"channels",$)}require($){let b=this.descriptors.get($);if(!b)throw Error(`unknown connector type "${$}". Pass its descriptor to new Funnel({ connectors: [...] }).`);return b}listenerDeps($){return{channelId:$,fs:this.fs,process:this.process,http:this.http,clock:this.clock,logger:this.logger,diagnosticLog:this.diagnosticLog,signal:this.signal,connectorDir:(b,U)=>this.connectorDir(b,U)}}adapterDeps(){return{fs:this.fs,process:this.process,http:this.http,logger:this.logger}}}var Xs=new V6,Hs=new g4;class UO{store;registry;profileChecker;clock;idGenerator;constructor($){this.store=$.store,this.registry=$.registry,this.profileChecker=$.profileChecker??null,this.clock=$.clock??Xs,this.idGenerator=$.idGenerator??Hs,Object.freeze(this)}list(){return this.store.read().channels}get($){return this.list().find((b)=>b.name===$)??null}getById($){return this.list().find((b)=>b.id===$)??null}add($){return this.store.update((b)=>{if(b.channels.some((J)=>J.name===$.name))throw new GJ($.name);let U={id:this.idGenerator.generate(),name:$.name,delivery:$.delivery??"fanout",connectors:[]};return b.channels.push(U),U})}setDelivery($,b){this.store.update((U)=>{let J=this.requireChannel(U,$);J.delivery=b})}remove($){this.store.update((b)=>{let U=b.channels.findIndex((D)=>D.name===$);if(U<0)throw new d1($);let J=b.channels[U];if(J&&this.profileChecker?.hasChannelRef(J.id))throw Error(`channel "${$}" is referenced by a profile`);b.channels.splice(U,1)})}rename($,b){this.store.update((U)=>{let J=U.channels.find((D)=>D.name===$);if(!J)throw new d1($);if(U.channels.some((D)=>D.name===b))throw new GJ(b);J.name=b})}listConnectors($){return this.requireChannel(this.store.read(),$).connectors}getConnector($,b){let U=this.get($);if(!U)return null;return U.connectors.find((J)=>J.name===b)??null}listAllConnectors(){let $=[];for(let b of this.list())for(let U of b.connectors)$.push({...U,channelId:b.id,channelName:b.name});return $}addConnector($,b){return this.store.update((U)=>{let J=this.requireChannel(U,$);if(J.connectors.some((I)=>I.name===b.name))throw Error(`connector "${b.name}" already exists in channel "${$}"`);let D=this.registry.buildConfig(b,{id:this.idGenerator.generate(),now:this.clock.iso()});return this.assertNoTokenCollision(U,D),J.connectors.push(D),D})}removeConnector($,b){this.store.update((U)=>{let J=this.requireChannel(U,$),D=J.connectors.findIndex((I)=>I.name===b);if(D<0)throw new Ob($,b);J.connectors.splice(D,1)})}renameConnector($,b,U){this.store.update((J)=>{let D=this.requireChannel(J,$),I=D.connectors.find((X)=>X.name===b);if(!I)throw Error(`connector "${b}" not found in channel "${$}"`);if(D.connectors.some((X)=>X.name===U))throw Error(`connector "${U}" already exists in channel "${$}"`);I.name=U,I.updatedAt=this.clock.iso()})}updateConnector($,b,U){this.store.update((J)=>{let D=this.requireChannel(J,$),I=D.connectors.find((H)=>H.name===b);if(!I)throw new Ob($,b);let X=this.registry.applyUpdate(I,U,{now:this.clock.iso()});this.assertNoTokenCollision(J,X),this.replaceConnector(D,I.name,X)})}updateSlackConnector($,b,U){this.updateConnector($,b,U)}updateGhConnector($,b,U){this.updateConnector($,b,U)}updateDiscordConnector($,b,U){this.updateConnector($,b,U)}connectorOp($,b,U,J){return this.store.update((D)=>{let I=this.requireChannel(D,$),X=I.connectors.find((w)=>w.name===b);if(!X)throw new Ob($,b);let H=this.registry.runOperation(X,U,J,{generateId:()=>this.idGenerator.generate(),now:this.clock.iso()});if(H.config!==X)this.replaceConnector(I,X.name,H.config);return H.result})}async call($,b,U){let J=this.getConnector($,b);if(!J)throw new Ob($,b);let D=this.registry.createAdapter(J);if(!D)throw Error(`connector type "${J.type}" does not support outbound calls`);return await D.call(U)}createListener($,b){let U=this.get($);if(!U)return null;let J=U.connectors.find((D)=>D.name===b);if(!J)return null;return{config:J,channelId:U.id,listener:this.registry.createListener(U.id,J)}}createAllListeners(){let $=[];for(let b of this.list())for(let U of b.connectors)$.push({config:U,channelId:b.id,channelName:b.name,listener:this.registry.createListener(b.id,U)});return $}requireChannel($,b){let U=$.channels.find((J)=>J.name===b);if(!U)throw new d1(b);return U}replaceConnector($,b,U){let J=$.connectors.findIndex((D)=>D.name===b);if(J<0)throw Error(`connector "${b}" not found in channel "${$.name}"`);$.connectors[J]=U}assertNoTokenCollision($,b){let U=this.registry.secretTokens(b);if(U.length===0)return;for(let J of $.channels)for(let D of J.connectors){if(D.id===b.id)continue;for(let I of this.registry.secretTokens(D))if(U.includes(I))throw Error(`token already in use by connector "${D.name}" in channel "${J.name}"`)}}}var ws=new N$,Gs=new g4;class DO{channels;mcp;gateway;sessions;guard;process;idGenerator;logger;dir;constructor($){this.channels=$.channels,this.mcp=$.mcp,this.gateway=$.gateway,this.sessions=$.sessions,this.guard=$.guard,this.process=$.process??ws,this.idGenerator=$.idGenerator??Gs,this.logger=$.logger,this.dir=$.dir,Object.freeze(this)}async launch($){let b=this.channels.get($.channel)??this.channels.getById($.channel);if(!b)throw Error(`channel "${$.channel}" not found`);if($.profileId&&this.guard.isRunning($.profileId))throw Error(`profile "${$.profileId}" is already running`);let U=$.cwd??globalThis.process.cwd();if(($.installMcp??!0)&&!this.mcp.findInstalledName(U))this.mcp.install(U),this.logger?.info("added funnel MCP to .mcp.json",{cwd:U});if(!this.gateway.isRunning()){if(this.logger?.info("starting gateway automatically"),!await this.gateway.start())throw Error(`gateway failed to start on port ${Y6()}; another funnel daemon (a different repo/scope) may already hold it. See 'fnl gateway logs' and 'ps -o pid,args= | grep funnel-gateway'.`)}if($.profileId)this.guard.acquire($.profileId);let I=($.resume??!1)&&$.profileId?this.resolveSession($.profileId,U,$.userArgs??[],$.env??{}):null,X=this.buildArgs($.options??[],$.userArgs??[],U,I),H=this.buildEnv(b.id,$.env??{});this.logger?.info("claude launch",{channel:$.channel,channelId:b.id,cwd:U});try{return await this.process.attach(["claude",...X],{cwd:U,env:H,onSpawned:$.onSpawned})}finally{if($.profileId)this.guard.release($.profileId)}}buildArgs($,b,U,J){let D=[...$,...b];if(J!==null)if(J.mode==="resume")D.push("--resume",J.id);else D.push("--session-id",J.id);let I=this.mcp.findInstalledName(U);if(I&&!D.includes("--dangerously-load-development-channels")&&!D.includes("--channels"))D.push("--dangerously-load-development-channels",`server:${I}`);return D}resolveSession($,b,U,J){for(let X of U){if(X==="-c"||X==="--continue")return null;if(X==="--resume"||X.startsWith("--resume="))return null;if(X==="--session-id"||X.startsWith("--session-id="))return null}let D=this.sessions.getSessionId($);if(D!==null&&this.sessions.sessionFileExists(b,D,J))return{id:D,mode:"resume"};let I=this.idGenerator.generate();return this.sessions.setSessionId($,I),{id:I,mode:"new"}}buildEnv($,b){let U={};for(let[J,D]of Object.entries(b))U[J]=D;for(let[J,D]of Object.entries(globalThis.process.env))if(typeof D==="string")U[J]=D;if(U.FUNNEL_CHANNEL_ID=$,U.FUNNEL_PORT=String(Y6()),this.dir!==void 0)U.FUNNEL_DIR=this.dir;return U}}import{join as AT}from"path";var Ws=new F$,Qs=new N$;class wX{fs;process;pidDir;constructor($={}){this.fs=$.fs??Ws,this.process=$.process??Qs,this.pidDir=AT($.dir??R4,"claude"),Object.freeze(this)}isRunning($){let b=this.readRecord($);if(!b)return!1;if(!this.process.isAlive(b.pid))return this.release($),!1;if(b.startTime!==null){let U=this.process.getStartTime(b.pid);if(U===null)return this.release($),!1;if(U!==b.startTime)return this.release($),!1}return!0}acquire($){this.fs.mkdirSync(this.pidDir,{recursive:!0});let b=globalThis.process.pid,U=this.process.getStartTime(b),J={pid:b,startTime:U};this.fs.writeFileSync(this.pidPath($),JSON.stringify(J)),globalThis.process.once("exit",()=>this.release($))}release($){let b=this.pidPath($);if(this.fs.existsSync(b))this.fs.unlink(b)}pidPath($){return AT(this.pidDir,`${$}.pid`)}readRecord($){let b=this.pidPath($);if(!this.fs.existsSync(b))return null;try{let U=this.fs.readFileSync(b).trim();if(!U)return null;if(U.startsWith("{")){let D=JSON.parse(U),I=typeof D.pid==="number"?D.pid:Number(D.pid);if(!Number.isInteger(I)||I<=0)return null;let X=typeof D.startTime==="string"?D.startTime:null;return{pid:I,startTime:X}}let J=Number(U);if(!J||J<=0)return null;return{pid:J,startTime:null}}catch{return null}}}import{dirname as PT,join as Os}from"path";import{homedir as Ys}from"os";import{join as qT}from"path";function GX($){let b=$.env.CLAUDE_CONFIG_DIR??globalThis.process.env.CLAUDE_CONFIG_DIR??qT(Ys(),".claude"),U=$.cwd.replace(/\//g,"-"),J=qT(b,"projects",U,`${$.sessionId}.jsonl`);if(!$.fs.existsSync(J))return!1;return $.fs.readFileSync(J).trim().length>0}var Vs=Y.record(Y.string(),Y.string());class JO{fs;path;constructor($){this.fs=$.fs,this.path=Os($.dir,"claude","local-sessions.json"),Object.freeze(this)}getSessionId($){return this.fs.mkdirSync(PT(this.path),{recursive:!0}),this.fs.withFileLock(`${this.path}.lock`,()=>this.read()[$]??null)}setSessionId($,b){this.fs.mkdirSync(PT(this.path),{recursive:!0}),this.fs.withFileLock(`${this.path}.lock`,()=>{let U=this.read();U[$]=b,this.fs.writeFileSync(this.path,`${JSON.stringify(U,null,2)}
|
|
1594
|
-
`)})}sessionFileExists($,b,U){return GX({fs:this.fs,cwd:$,sessionId:b,env:U})}read(){if(!this.fs.existsSync(this.path))return{};let $=JSON.parse(this.fs.readFileSync(this.path)),b=Vs.safeParse($);if(!b.success)throw Error(`invalid local profile session store (${this.path})`);return b.data}}class IO{global;local;constructor($){this.global=$.global,this.local=$.local,Object.freeze(this)}getSessionId($){return this.storeFor($).getSessionId($)}setSessionId($,b){this.storeFor($).setSessionId($,b)}sessionFileExists($,b,U){return this.global.sessionFileExists($,b,U)}storeFor($){return $.startsWith("local-")?this.local:this.global}}import{existsSync as Zs,readFileSync as Bs}from"fs";import{join as zs}from"path";var QD=($)=>typeof $==="string"&&$.length>0?$:null;var vs=($)=>$!==null&&typeof $==="object"&&!Array.isArray($),XO=($)=>{if($===null)return null;try{let b=JSON.parse($);if(vs(b))return b}catch{return null}return null},TT=($,b)=>$.length<=b?$:`${$.slice(0,b)}\u2026`,FT=($)=>{if(typeof $!=="string"||$.length===0)return null;let b=XO($);if(b!==null&&"text"in b)return TT(String(b.text),60);return TT($,60)};var rb=($)=>({seq:$.seq,ts:$.ts,type:$.type,outcome:$.outcome,eventId:$.eventId,payload:QD($.payload),payloadParsed:XO(QD($.payload)),preview:FT($.payload)}),MT=($)=>({seq:$.seq,ts:$.ts,type:$.type,outcome:"",eventId:$.eventId,payload:QD($.payload),payloadParsed:XO(QD($.payload)),preview:FT($.payload)}),M0=($)=>({seq:$.seq,ts:$.ts,type:$.type,status:$.status,detail:QD($.detail)});var Ks=($)=>{if($===null||typeof $!=="object")return!1;if(!("clients"in $)||!Array.isArray($.clients))return!1;if(!("listeners"in $)||!Array.isArray($.listeners))return!1;return!0},js=($,b)=>{if(b===null)return;return $.connectors?.find((U)=>U.id===b)?.name},uT=3,Ls=100,NT=($)=>`${$.type}\x00${$.connectorId??""}`,As=($)=>{let b=new Map;return $.forEach((U,J)=>{if(U.status==="connected")b.set(NT(U),J)}),$.filter((U,J)=>{if(U.status!=="auth-failed"&&U.status!=="error")return!1;return(b.get(NT(U))??-1)<J})},qs=($,b=$.connectionErrors)=>{let J=(b[b.length-1]??null)?.detail??null,D=$.channel;if(!$.gateway.running)return{status:"error",message:"gateway is not running",nextActions:["fnl gateway start"],rootCause:null};if($.gateway.statusError!==null)return{status:"error",message:`gateway running but status probe failed: ${$.gateway.statusError}`,nextActions:["fnl gateway restart"],rootCause:$.gateway.statusError};if($.configuredConnectors>$.listeners.length)return{status:"error",message:`${$.configuredConnectors} connector(s) configured but ${$.listeners.length} registered with supervisor`,nextActions:["fnl gateway restart"],rootCause:"supervisor missing listeners declared in settings.json"};
|
|
1594
|
+
`)})}sessionFileExists($,b,U){return GX({fs:this.fs,cwd:$,sessionId:b,env:U})}read(){if(!this.fs.existsSync(this.path))return{};let $=JSON.parse(this.fs.readFileSync(this.path)),b=Vs.safeParse($);if(!b.success)throw Error(`invalid local profile session store (${this.path})`);return b.data}}class IO{global;local;constructor($){this.global=$.global,this.local=$.local,Object.freeze(this)}getSessionId($){return this.storeFor($).getSessionId($)}setSessionId($,b){this.storeFor($).setSessionId($,b)}sessionFileExists($,b,U){return this.global.sessionFileExists($,b,U)}storeFor($){return $.startsWith("local-")?this.local:this.global}}import{existsSync as Zs,readFileSync as Bs}from"fs";import{join as zs}from"path";var QD=($)=>typeof $==="string"&&$.length>0?$:null;var vs=($)=>$!==null&&typeof $==="object"&&!Array.isArray($),XO=($)=>{if($===null)return null;try{let b=JSON.parse($);if(vs(b))return b}catch{return null}return null},TT=($,b)=>$.length<=b?$:`${$.slice(0,b)}\u2026`,FT=($)=>{if(typeof $!=="string"||$.length===0)return null;let b=XO($);if(b!==null&&"text"in b)return TT(String(b.text),60);return TT($,60)};var rb=($)=>({seq:$.seq,ts:$.ts,type:$.type,outcome:$.outcome,eventId:$.eventId,payload:QD($.payload),payloadParsed:XO(QD($.payload)),preview:FT($.payload)}),MT=($)=>({seq:$.seq,ts:$.ts,type:$.type,outcome:"",eventId:$.eventId,payload:QD($.payload),payloadParsed:XO(QD($.payload)),preview:FT($.payload)}),M0=($)=>({seq:$.seq,ts:$.ts,type:$.type,status:$.status,detail:QD($.detail)});var Ks=($)=>{if($===null||typeof $!=="object")return!1;if(!("clients"in $)||!Array.isArray($.clients))return!1;if(!("listeners"in $)||!Array.isArray($.listeners))return!1;return!0},js=($,b)=>{if(b===null)return;return $.connectors?.find((U)=>U.id===b)?.name},uT=3,Ls=100,NT=($)=>`${$.type}\x00${$.connectorId??""}`,As=($)=>{let b=new Map;return $.forEach((U,J)=>{if(U.status==="connected")b.set(NT(U),J)}),$.filter((U,J)=>{if(U.status!=="auth-failed"&&U.status!=="error")return!1;return(b.get(NT(U))??-1)<J})},qs=($,b=$.connectionErrors)=>{let J=(b[b.length-1]??null)?.detail??null,D=$.channel;if(!$.gateway.running)return{status:"error",message:"gateway is not running",nextActions:["fnl gateway start"],rootCause:null};if($.gateway.statusError!==null)return{status:"error",message:`gateway running but status probe failed: ${$.gateway.statusError}`,nextActions:["fnl gateway restart"],rootCause:$.gateway.statusError};if($.configuredConnectors>$.listeners.length)return{status:"error",message:`${$.configuredConnectors} connector(s) configured but ${$.listeners.length} registered with supervisor`,nextActions:["fnl gateway restart"],rootCause:"supervisor missing listeners declared in settings.json"};let I=b.filter((Q)=>Q.status==="auth-failed");if(I.length>0){let Q=I[I.length-1]?.detail??null;return{status:"error",message:"connector credentials rejected (auth-failed)",nextActions:[`fnl channels ${D} connectors set <connector> --bot-token=<new>`,"fnl gateway restart"],rootCause:Q??"token rejected by upstream auth.test"}}let X=$.listeners.length>0&&$.listeners.every((Q)=>!Q.alive),H=$.listeners.some((Q)=>!Q.alive);if(X)return{status:"error",message:"all listeners are dead",nextActions:["fnl doctor --fix","fnl doctor --fix --aggressive"],rootCause:J};if(H)return{status:"warn",message:"some listeners are dead",nextActions:["fnl doctor --fix"],rootCause:J};let w=$.listeners.filter((Q)=>Q.errors>=uT);if(w.length>0)return{status:"warn",message:`listener(s) flapping (\u2265${uT} errors): ${w.map((Q)=>Q.name).join(", ")}`,nextActions:["fnl gateway logs"],rootCause:J};if($.claudeClients===0)return{status:"warn",message:"no Claude connected to this channel",nextActions:[`fnl claude --channel ${D}`],rootCause:null};if($.listeners.some((Q)=>Q.errors>0))return{status:"warn",message:"listeners have errors",nextActions:["fnl gateway logs"],rootCause:J};let W=Ps($);if(W!==null)return W;return{status:"ok",message:"everything looks healthy",nextActions:[],rootCause:null}},Ps=($)=>{if(!$.listeners.some((I)=>I.type==="slack")||$.recentEvents.length===0)return null;let U=$.recentEvents.filter((I)=>I.type==="slack").map((I)=>I.payloadParsed?.type);if(U.length===0)return null;let J=U.includes("app_mention"),D=U.includes("message");if(!J||D)return null;return{status:"warn",message:"Slack is only delivering app_mention events; unmentioned thread replies may not arrive",nextActions:["Add Slack bot events: message.channels, message.groups, message.im, message.mpim; reinstall the app; then restart the gateway"],rootCause:"Slack Event Subscriptions likely omit message.* events"}};class HO{props;constructor($){this.props=$;Object.freeze(this)}async diagnose($){let b=this.props.channels.list(),U=$?b.find((D)=>D.name===$)??null:b[0]??null;if(!U)return null;let J=await this.fetchGatewayStatus();return this.buildChannelDiagnosis(U,J,5)}async diagnoseAll(){let $=this.props.channels.list(),b=await this.fetchGatewayStatus(),U=await Promise.all($.map((H)=>this.buildChannelDiagnosis(H,b,5))),J=U.filter((H)=>H.diagnosis.status==="error").map((H)=>H.channel),D=U.filter((H)=>H.diagnosis.status==="warn").map((H)=>H.channel),I=U.filter((H)=>H.diagnosis.status==="ok").map((H)=>H.channel),X=[...new Set(U.flatMap((H)=>H.diagnosis.nextActions))];return{summary:{total:U.length,ok:I.length,warn:D.length,error:J.length,criticalChannels:J,warnChannels:D,suggestedActions:X},channels:U}}async recentEvents($,b={}){let U=b.limit??20,J=this.resolveScope($,b.connector);if(J===null)return[];return this.queryLog((D)=>D.queryProcessed({...J,limit:U})).map(rb)}async droppedEvents($,b={}){let U=b.limit??20,J=this.resolveScope($,b.connector);if(J===null)return[];return this.queryLog((D)=>D.queryProcessed({...J,outcomePrefix:"skip:",limit:U})).map(rb)}async rawEvents($,b={}){let U=b.limit??20,J=this.resolveScope($,b.connector);if(J===null)return[];return this.queryLog((D)=>D.queryRaw({...J,limit:U})).map(MT)}async connectionErrors($,b={}){let U=b.limit??20,J=this.resolveScope($,b.connector);if(J===null)return[];return this.queryLog((D)=>D.queryConnection({...J,statuses:["auth-failed","error"],limit:U})).map(M0)}async connectionTimeline($,b={}){let U=b.limit??20,J=this.resolveScope($,b.connector);if(J===null)return[];return this.queryLog((D)=>D.queryConnection({...J,limit:U})).map(M0)}async recentLogs($={}){let b=$.limit??200,U=zs(this.props.tmpDir,"funnel.log");if(!Zs(U))return{lines:[],path:null,truncated:!1};let J;try{J=Bs(U,"utf-8")}catch(G){return{lines:[`(read failed: ${V$(G)})`],path:U,truncated:!1}}let D=J.split(`
|
|
1595
1595
|
`).filter((G)=>G.length>0),I=$.grep?.toLowerCase(),X=I?D.filter((G)=>G.toLowerCase().includes(I)):D,H=X.length>b;return{lines:H?X.slice(X.length-b):X,path:U,truncated:H}}async replay($,b){let J=this.props.channels.list().find((Z)=>Z.name===$);if(!J)return{state:"not-found"};if(!this.props.diagnosticLog)return{state:"error",reason:"no diagnostic log configured"};let D=this.queryLogResult((Z)=>Z.queryProcessed({channelId:J.id,...b!==void 0?{seq:b}:{outcomePrefix:"emitted"},limit:1}));if(D instanceof Error)return{state:"error",reason:D.message};let I=D[0];if(!I)return{state:"not-found"};let{seq:X,eventId:H,connectorId:w}=I,G=I.payload.length>0?I.payload:null,W=G===null?this.queryLog((Z)=>Z.queryRaw({eventId:H,limit:1}))[0]?.payload??null:null,Q=G??W;if(!Q)return{state:"error",reason:"event has no payload to replay"};let O=js(J,w),V=await this.props.publisher.publish(J.name,{content:Q,connector:O});if(V.state==="offline")return{state:"offline"};if(V.state==="error")return{state:"error",reason:V.reason};return{state:"ok",seq:X,offset:V.offset,preview:Q.slice(0,60)}}resolveScope($,b){if(!$)return{};let J=this.props.channels.list().find((I)=>I.name===$)??null;if(!J)return null;if(!b)return{channelId:J.id};let D=J.connectors?.find((I)=>I.name===b)?.id??null;if(!D)return null;return{channelId:J.id,connectorId:D}}queryLog($){let b=this.queryLogResult($);return b instanceof Error?[]:b}queryLogResult($){let b=this.props.diagnosticLog;if(!b)return Error("no diagnostic log configured");try{return $(b)}catch(U){return Error(V$(U))}}async fetchGatewayStatus(){let $=this.props.gateway.getStatus();if(!$.running)return{body:null,error:null};let b=this.props.gatewayToken.read(),U=b?{Authorization:`Bearer ${b}`}:{},J=null;try{J=await r$(`${i$($.port)}/status`,{headers:U})}catch(I){return{body:null,error:`fetch failed: ${V$(I)}`}}if(!J.ok)return{body:null,error:`gateway /status returned ${J.status}`};let D;try{D=await J.json()}catch(I){return{body:null,error:`gateway /status body parse failed: ${V$(I)}`}}if(!Ks(D))return{body:null,error:"gateway /status returned an unrecognized shape"};return{body:D,error:null}}async buildChannelDiagnosis($,b,U){let J=this.props.gateway.getStatus(),D=$.name,I=b.body,X={channel:D,channelId:$.id,gateway:{running:J.running,pid:J.pid,port:J.running?J.port:null,uptimeMs:I?.uptimeMs??null,statusError:b.error},configuredConnectors:$.connectors?.length??0,listeners:[],claudeClients:0,recentEvents:[],connectionErrors:[]};if(I)X.listeners=I.listeners.filter((w)=>w.channelName===D).map((w)=>({name:w.name,type:w.type,alive:w.alive,events:w.events,errors:w.errors,lastEventAt:w.lastEventAt})),X.claudeClients=I.clients.filter((w)=>w.channelName===D).length;let H=[];if(this.props.diagnosticLog){let w=this.queryLog((Q)=>Q.queryProcessed({channelId:$.id,limit:U}));X.recentEvents=w.map(rb);let G=this.queryLog((Q)=>Q.queryConnection({channelId:$.id,limit:Ls})),W=G.filter((Q)=>Q.status==="auth-failed"||Q.status==="error").slice(-3);X.connectionErrors=W.map(M0),H=As(G).map(M0)}return{...X,diagnosis:qs(X,H)}}}class wO{props;constructor($){this.props=$;Object.freeze(this)}async run($="off"){if($==="off"){let H=await this.props.diagnostics.diagnoseAll();return this.buildReport({before:null,after:H,appliedActions:[],fixFailed:!1})}let b=await this.props.diagnostics.diagnoseAll(),U=[],J=!1;if(b.channels.some((H)=>H.diagnosis.status==="error"&&!H.gateway.running)){let H=await this.props.recovery.ensureGatewayRunning();if(U.push(...H.actions),!H.ok)J=!0}if(b.channels.some((H)=>H.listeners.some((w)=>!w.alive))){let H=await this.props.recovery.restartAllDeadListeners();if(U.push(...H.actions),!H.ok&&H.actions.length===0)J=!0}if($==="aggressive"){if((await this.props.diagnostics.diagnoseAll()).channels.some((G)=>G.diagnosis.status==="error")){let G=await this.props.recovery.restartGateway();if(U.push(...G.actions),!G.ok)J=!0}}let X=await this.props.diagnostics.diagnoseAll();return this.buildReport({before:b,after:X,appliedActions:U,fixFailed:J})}buildReport($){let b=$.after.channels.filter((D)=>D.diagnosis.status!=="ok").map((D)=>({channel:D.channel,diagnosis:D.diagnosis})),U=$.fixFailed?"error":b.length===0?"ok":"warn",J=Ts({mode:$.before===null?"off":"fix",status:U,appliedCount:$.appliedActions.length,remainingCount:b.length});return{status:U,message:J,before:$.before,after:$.after,appliedActions:$.appliedActions,remainingIssues:b}}}var Ts=($)=>{if($.mode==="off"){if($.remainingCount===0)return"all channels healthy";return`${$.remainingCount} channel(s) need attention \u2014 run \`fnl doctor --fix\` to apply suggested fixes`}if($.status==="error")return"one or more fix steps failed \u2014 check fnl gateway logs";if($.status==="ok")return`applied ${$.appliedCount} fix(es), all channels healthy`;return`applied ${$.appliedCount} fix(es), ${$.remainingCount} channel(s) still need attention`};function GO($){if($.env!==void 0)return{botTokenEnv:$.env};if($.literal!==void 0)return{botToken:$.literal};return{}}function fT($){if($.env!==void 0)return{appTokenEnv:$.env};if($.literal!==void 0)return{appToken:$.literal};return{}}class WO{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 U=[],J=new Set;for(let I of $.connectors){let X=await this.ensureConnector($.name,I);U.push({name:X.name,changed:X.changed}),J.add(X.id)}let D=this.removeExtras($.name,J);return{touched:U,removed:D}}async ensureConnector($,b){if(b.type==="slack")return await this.ensureSlack($,b);if(b.type==="discord")return await this.ensureDiscord($,b);if(b.type==="gh")return this.ensureGh($,b);return this.ensureSchedule($,b)}async ensureSlack($,b){let U=this.findExistingSlack($,b.name),J=await this.resolveSlot({label:`${b.name}.botToken`,existingLiteral:U?.botToken,existingEnv:U?.botTokenEnv}),D=await this.resolveSlot({label:`${b.name}.appToken`,existingLiteral:U?.appToken,existingEnv:U?.appTokenEnv}),I={botToken:J.token,botTokenEnv:J.tokenEnv,appToken:D.token,appTokenEnv:D.tokenEnv};if(U){if(!(U.botToken===J.token&&U.botTokenEnv===J.tokenEnv&&U.appToken===D.token&&U.appTokenEnv===D.tokenEnv))return this.channels.updateSlackConnector($,b.name,I),{id:U.id,name:b.name,changed:!0};return{id:U.id,name:b.name,changed:!1}}return{id:this.channels.addConnector($,{type:"slack",name:b.name,...GO({literal:J.token,env:J.tokenEnv}),...fT({literal:D.token,env:D.tokenEnv}),...b.minify!==void 0?{minify:b.minify}:{}}).id,name:b.name,changed:!0}}async ensureDiscord($,b){let U=this.findExistingDiscord($,b.name),J=await this.resolveSlot({label:`${b.name}.botToken`,existingLiteral:U?.botToken,existingEnv:U?.botTokenEnv}),D={botToken:J.token,botTokenEnv:J.tokenEnv};if(U){if(U.botToken!==J.token||U.botTokenEnv!==J.tokenEnv)return this.channels.updateDiscordConnector($,b.name,D),{id:U.id,name:b.name,changed:!0};return{id:U.id,name:b.name,changed:!1}}return{id:this.channels.addConnector($,{type:"discord",name:b.name,...GO({literal:J.token,env:J.tokenEnv})}).id,name:b.name,changed:!0}}ensureGh($,b){let U=this.channels.getConnector($,b.name);if(U&&U.type!=="gh")throw Error(`connector "${b.name}" exists in channel "${$}" with type "${U.type}", funnel.json declares "gh"`);if(U&&U.type==="gh"){let D=b6.parse(U);if(b.pollInterval!==void 0&&D.pollInterval!==b.pollInterval)return this.channels.updateGhConnector($,b.name,{pollInterval:b.pollInterval}),{id:D.id,name:b.name,changed:!0};return{id:D.id,name:b.name,changed:!1}}return{id:this.channels.addConnector($,{type:"gh",name:b.name,...b.pollInterval!==void 0?{pollInterval:b.pollInterval}:{}}).id,name:b.name,changed:!0}}ensureSchedule($,b){let U=this.channels.getConnector($,b.name);if(U&&U.type!=="schedule")throw Error(`connector "${b.name}" exists in channel "${$}" with type "${U.type}", funnel.json declares "schedule"`);if(U&&U.type==="schedule")return{id:U.id,name:b.name,changed:!1};return{id:this.channels.addConnector($,{type:"schedule",name:b.name}).id,name:b.name,changed:!0}}findExistingSlack($,b){let U=this.channels.getConnector($,b);if(!U)return null;if(U.type!=="slack")throw Error(`connector "${b}" exists in channel "${$}" with type "${U.type}", funnel.json declares "slack"`);return U6.parse(U)}findExistingDiscord($,b){let U=this.channels.getConnector($,b);if(!U)return null;if(U.type!=="discord")throw Error(`connector "${b}" exists in channel "${$}" with type "${U.type}", funnel.json declares "discord"`);return s4.parse(U)}removeExtras($,b){let U=this.channels.get($);if(!U)return[];let J=U.connectors.filter((D)=>!b.has(D.id));for(let D of J)this.channels.removeConnector($,D.name);return J.map((D)=>D.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}}}var Fs=new F$;class QO{store;idGenerator;fs;constructor($){this.store=$.store,this.idGenerator=$.idGenerator,this.fs=$.fs??Fs,Object.freeze(this)}list(){return this.store.read().profiles}get($){return this.list().find((b)=>b.name===$)??null}getById($){return this.list().find((b)=>b.id===$)??null}getDefault(){return this.list()[0]??null}add($){this.store.update((b)=>{if(b.profiles.some((U)=>U.name===$.name))throw Error(`profile "${$.name}" already exists`);if(!b.channels.some((U)=>U.id===$.channelId))throw Error(`channel id "${$.channelId}" not found`);b.profiles.push({id:this.idGenerator.generate(),name:$.name,path:$.path,channelId:$.channelId,options:$.options??[],env:$.env??{},resume:$.resume??!0})})}remove($){this.store.update((b)=>{let U=b.profiles.findIndex((J)=>J.name===$);if(U<0)throw Error(`profile "${$}" not found`);b.profiles.splice(U,1)})}rename($,b){this.store.update((U)=>{let J=U.profiles.find((D)=>D.name===$);if(!J)throw Error(`profile "${$}" not found`);if(U.profiles.some((D)=>D.name===b))throw Error(`profile "${b}" already exists`);J.name=b})}asDefault($){this.store.update((b)=>{let U=b.profiles.findIndex((D)=>D.name===$);if(U<0)throw Error(`profile "${$}" not found`);if(U===0)return;let[J]=b.profiles.splice(U,1);if(!J)return;b.profiles.unshift(J)})}hasChannelRef($){return this.store.read().profiles.some((b)=>b.channelId===$)}getSessionId($){return this.getById($)?.sessionId??null}setSessionId($,b){this.store.update((U)=>{let J=U.profiles.find((D)=>D.id===$);if(!J)throw Error(`profile id "${$}" not found`);J.sessionId=b})}sessionFileExists($,b,U){return GX({fs:this.fs,cwd:$,sessionId:b,env:U})}update($,b){this.store.update((U)=>{let J=U.profiles.find((D)=>D.name===$);if(!J)throw Error(`profile "${$}" not found`);if(b.channelId!==void 0){if(!U.channels.some((D)=>D.id===b.channelId))throw Error(`channel id "${b.channelId}" not found`);J.channelId=b.channelId}if(b.path!==void 0)J.path=b.path;if(b.options!==void 0)J.options=b.options;if(b.env!==void 0)J.env=b.env;if(b.resume!==void 0)J.resume=b.resume})}}class YO{props;constructor($){this.props=$;Object.freeze(this)}async ensureGatewayRunning(){if(this.props.gateway.isRunning())return{ok:!0,actions:[{kind:"gateway:already-running"}],message:"gateway is already running"};if(!await this.props.gateway.start())return{ok:!1,actions:[],message:"gateway failed to start \u2014 check `fnl gateway logs`"};return{ok:!0,actions:[{kind:"gateway:started"}],message:"gateway started"}}async restartGateway(){if(!(await this.props.gateway.restart()).ok)return{ok:!1,actions:[],message:"gateway restart failed \u2014 check `fnl gateway logs`"};return{ok:!0,actions:[{kind:"gateway:restarted"}],message:"gateway restarted"}}async restartListener($,b){let U=await this.props.listeners.restart($,b);if(U.state==="offline")return{ok:!1,actions:[],message:"gateway is not running \u2014 call ensureGatewayRunning() first"};if(U.state==="not-found")return{ok:!1,actions:[{kind:"listener:skipped",channel:$,connector:b,reason:"not-found"}],message:`listener not found: ${$}/${b}`};if(U.state==="error")return{ok:!1,actions:[{kind:"listener:skipped",channel:$,connector:b,reason:U.reason}],message:`listener restart failed: ${U.reason}`};return{ok:!0,actions:[{kind:"listener:restarted",channel:$,connector:b}],message:`restarted ${$}/${b}`}}async restartAllDeadListeners(){let $=await this.props.listeners.list();if($.state==="offline")return{ok:!1,actions:[],message:"gateway is not running \u2014 call ensureGatewayRunning() first"};if($.state==="error")return{ok:!1,actions:[],message:`could not list listeners: ${$.reason}`};let b=$.listeners.filter((D)=>!D.alive);if(b.length===0)return{ok:!0,actions:[],message:"no dead listeners found"};let U=[];for(let D of b){let I=await this.props.listeners.restart(D.channelName,D.name);if(I.state==="ok")U.push({kind:"listener:restarted",channel:D.channelName,connector:D.name});else{let X=I.state==="error"?I.reason:I.state;U.push({kind:"listener:skipped",channel:D.channelName,connector:D.name,reason:X})}}let J=U.filter((D)=>D.kind==="listener:restarted").length;return{ok:J>0,actions:U,message:`restarted ${J}/${b.length} dead listener(s)`}}}import{stderr as WX,stdin as r4}from"process";class YD{}var Ms="*",us="\r",ST=`
|
|
1596
|
-
`,Ns=String.fromCharCode(8),fs=String.fromCharCode(127),Ss=String.fromCharCode(3),gs=String.fromCharCode(4);class OO extends YD{async promptSecret($){if(!r4.isTTY)throw Error(`cannot prompt for "${$}": stdin is not a TTY. Set the matching env var or run \`fnl channels <ch> connectors add ...\` first.`);WX.write(`${$}: `);let b=r4.isRaw;r4.setRawMode(!0),r4.resume();try{return await this.readSecret()}finally{r4.setRawMode(b),r4.pause(),WX.write(ST)}}readSecret(){return new Promise(($,b)=>{let U="",J=(D)=>{for(let I of D){let X=String.fromCharCode(I);if(X===ST||X===us){r4.off("data",J),$(U);return}if(X===Ss){r4.off("data",J),b(Error("prompt cancelled"));return}if(X===gs){if(r4.off("data",J),U.length===0)b(Error("prompt cancelled"));else $(U);return}if(X===Ns||X===fs){if(U.length>0)U=U.slice(0,-1),WX.write("\b \b");continue}U+=X,WX.write(Ms)}};r4.on("data",J)})}}var Rs=384;class VO extends m1{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($,b){this.files.set($,b),this.touch($)}writeSecretFileSync($,b){this.files.set($,b),this.modes.set($,Rs),this.touch($)}appendFileSync($,b){let U=this.files.get($)??"";this.files.set($,U+b),this.touch($)}unlink($){this.files.delete($),this.mtimes.delete($),this.modes.delete($)}mkdirSync($,b){this.dirs.add($)}readdirSync($){let b=$.endsWith("/")?$:`${$}/`,U=[];for(let J of this.files.keys()){if(!J.startsWith(b))continue;let D=J.slice(b.length);if(!D.includes("/"))U.push(D)}return U}statSync($){let b=this.mtimes.get($);if(b===void 0)throw Error(`not found: ${$}`);return{mtimeMs:b,mode:this.modes.get($)??null}}withFileLock($,b){return b()}setMtime($,b){this.mtimes.set($,b)}setMode($,b){this.modes.set($,b)}touch($){if(!this.mtimes.has($))this.mtimes.set($,this.now());else this.mtimes.set($,this.now())}}class vO extends JD{counter=0;prefix;constructor($={}){super();this.prefix=$.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}class ZO extends HD{file=null;entries=[];info($,b){this.entries.push({level:"info",message:$,meta:b})}warn($,b){this.entries.push({level:"warn",message:$,meta:b})}error($,b){this.entries.push({level:"error",message:$,meta:b})}clear(){this.entries.length=0}}var gT={exitCode:0,stdout:"",stderr:""};class BO extends i1{calls=[];killed=[];handler=()=>gT;syncHandler=()=>gT;aliveStub=null;listStub=null;startTimeStub=null;on($){return this.handler=$,this}onSync($){return this.syncHandler=$,this}onIsAlive($){return this.aliveStub=$,this}onListProcessesContaining($){return this.listStub=$,this}onGetStartTime($){return this.startTimeStub=$,this}async run($,b={}){this.calls.push({kind:"run",command:$,options:b});let U=await this.handler($);return{exitCode:U.exitCode??0,stdout:U.stdout??"",stderr:U.stderr??""}}runSync($){this.calls.push({kind:"runSync",command:$});let b=this.syncHandler($);return{exitCode:b.exitCode??0,stdout:b.stdout??"",stderr:b.stderr??""}}async attach($,b={}){if(this.calls.push({kind:"attach",command:$,options:b}),b.onSpawned)b.onSpawned(1);return(await this.handler($)).exitCode??0}detach($,b={}){this.calls.push({kind:"detach",command:$,options:b})}kill($,b="SIGTERM"){this.calls.push({kind:"kill",command:[String($),b]}),this.killed.push({pid:$,signal:b})}isAlive($){if(this.aliveStub)return this.aliveStub($);let b=this.syncHandler(["ps","-p",String($),"-o","state="]);if((b.exitCode??0)!==0)return!1;let U=(b.stdout??"").trim();if(!U)return!1;return!U.startsWith("Z")}listProcessesContaining($){if(this.listStub)return this.listStub($);return[]}getStartTime($){if(this.startTimeStub)return this.startTimeStub($);return null}}var _s=($={})=>({version:Q6,channels:[],profiles:[],...$});class zO extends ID{state;constructor($){super();this.state=_s($)}read(){return this.state}write($){this.state=$}update($){return $(this.state)}}class KO extends WD{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()+$)}}class jO extends x1{calls=[];handler=()=>({status:200,body:""});on($){return this.handler=$,this}async fetch($){this.calls.push($);let b=await this.handler($),U=b.status??200,J=b.body??"";return{status:U,ok:U>=200&&U<300,text:async()=>J,json:async()=>JSON.parse(J)}}}class LO extends YD{answers;asked=[];constructor($={}){super();this.answers=new Map(Object.entries($.answers??{}))}async promptSecret($){this.asked.push($);let b=this.answers.get($);if(b===void 0)throw Error(`no answer seeded for prompt "${$}"`);return b}}var ks=["started","connected","disconnected","auth-failed","stopped","error"],uZ$=Y.object({event_id:Y.string(),type:Y.string(),connector_id:Y.string().nullable(),channel_id:Y.string().nullable(),payload:Y.string()}),NZ$=Y.object({event_id:Y.string(),type:Y.string(),connector_id:Y.string().nullable(),channel_id:Y.string().nullable(),outcome:Y.string(),payload:Y.string()}),RT=Y.object({type:Y.string(),connector_id:Y.string().nullable(),channel_id:Y.string().nullable(),status:Y.enum(ks),detail:Y.string()});class OD{}class PO extends OD{now;raws=[];processeds=[];connections=[];constructor($=()=>Date.now()){super();this.now=$;Object.freeze(this)}recordRaw($){this.raws.push({...$,seq:this.raws.length+1,ts:this.now()})}recordProcessed($){this.processeds.push({...$,seq:this.processeds.length+1,ts:this.now()})}recordConnection($){this.connections.push({...$,seq:this.connections.length+1,ts:this.now()})}queryRaw($){let b=this.raws.filter((U)=>{if(!AO(U,$))return!1;if($.eventId!==void 0&&U.eventId!==$.eventId)return!1;return!0});return qO(b,$.limit)}queryProcessed($){let b=this.processeds.filter((U)=>{if(!AO(U,$))return!1;if($.eventId!==void 0&&U.eventId!==$.eventId)return!1;if($.outcome!==void 0&&U.outcome!==$.outcome)return!1;if($.outcomePrefix!==void 0&&!U.outcome.startsWith($.outcomePrefix))return!1;return!0});return qO(b,$.limit)}queryConnection($){let b=this.connections.filter((U)=>{if(!AO(U,$))return!1;if($.status!==void 0&&U.status!==$.status)return!1;if($.statuses!==void 0&&!$.statuses.includes(U.status))return!1;return!0});return qO(b,$.limit)}clear(){this.raws.length=0,this.processeds.length=0,this.connections.length=0}close(){}}var AO=($,b)=>{if(b.type!==void 0&&$.type!==b.type)return!1;if(b.connectorId!==void 0&&$.connectorId!==b.connectorId)return!1;if(b.channelId!==void 0&&$.channelId!==b.channelId)return!1;if("seq"in $&&b.seq!==void 0&&$.seq!==b.seq)return!1;return!0},qO=($,b)=>{if(b===void 0)return $;if(b<=0)return[];return $.slice(-b)};var _T=Y.object({content:Y.string().min(1),meta:Y.record(Y.string(),Y.string()).optional(),connector:Y.string().min(1).optional(),target:Y.string().min(1).optional()}),kT=Y.object({ok:Y.literal(!0),offset:Y.number().int().nonnegative()});var Es={state:"offline"};class TO{port;isDaemonRunning;getToken;constructor($){this.port=$.port,this.isDaemonRunning=$.isDaemonRunning,this.getToken=$.getToken??(()=>null),Object.freeze(this)}async publish($,b){if(!this.isDaemonRunning())return Es;try{let U=`${i$(this.port)}/channels/${encodeURIComponent($)}/publish`,J=await r$(U,{method:"POST",headers:{...this.authHeaders(),"content-type":"application/json"},body:JSON.stringify(b)});if(!J.ok)return{state:"error",reason:await J.text()||`HTTP ${J.status}`};let D=kT.safeParse(await J.json());if(!D.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",offset:D.data.offset}}catch(U){return{state:"error",reason:U instanceof Error?U.message:String(U)}}}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}}import{join as ET}from"path";import{existsSync as Cs}from"fs";import{dirname as xs,resolve as FO}from"path";import{fileURLToPath as ls}from"url";var QX=()=>{let $=xs(ls(import.meta.url)),b=[FO($,"./daemon.ts"),FO($,"./daemon.js"),FO($,"./gateway/daemon.js")];for(let U of b)if(Cs(U))return U;throw Error(`daemon script not found (looked in ${b.join(", ")})`)};var ns=5000,is=2000,CT=100,ys=200,hs=new N$,ms=new F$,rs=new V6,cs=($)=>new Promise((b)=>{setTimeout(b,$)});class MO{process;fs;clock;dir;pidFile;gatewayLog;tmpDir;port;sleep;constructor($={}){this.process=$.process??hs,this.fs=$.fs??ms,this.clock=$.clock??rs,this.dir=$.dir??R4,this.tmpDir=$.tmpDir??c$(),this.pidFile=ET(this.dir,"gateway.pid"),this.gatewayLog=ET(this.tmpDir,"gateway.log"),this.port=$.port??Y6(),this.sleep=$.sleep??cs,Object.freeze(this)}isRunning(){let $=this.readPid();if(!$)return!1;return this.isProcessAlive($)}getStatus(){let $=this.readPid(),b=$!==null&&this.isProcessAlive($);return{running:b,pid:b?$:null,port:this.port}}async start($={}){if(this.isRunning())return!0;this.fs.mkdirSync(this.tmpDir,{recursive:!0});let b=QX(),U=this.buildStartCommand(b,$);this.process.detach(U,{env:{FUNNEL_DIR:this.dir,FUNNEL_PORT:String(this.port),FUNNEL_TMP_DIR:this.tmpDir},stdoutFile:this.gatewayLog,stderrFile:this.gatewayLog});let J=this.clock.millis()+ns;while(this.clock.millis()<J){if(this.isRunning())return!0;await this.sleep(CT)}return this.isRunning()}buildStartCommand($,b={}){let U=`funnel-gateway[${this.dir}]`;if(b.caffeinate!==!1&&globalThis.process.platform==="darwin")return["caffeinate","-is","bun",$,U];return["bun",$,U]}async stop(){let $=this.readPid();if(!$)return!0;if(!this.isProcessAlive($))return this.removePid(),!0;try{this.process.kill($,"SIGTERM")}catch{return!1}let b=this.clock.millis()+is;while(this.clock.millis()<b){if(!this.isProcessAlive($))return this.removePid(),!0;await this.sleep(CT)}try{this.process.kill($,"SIGKILL")}catch{}return await this.sleep(ys),this.removePid(),!this.isProcessAlive($)}async restart($={}){let b=this.isRunning();if($.onlyIfRunning&&!b)return{ok:!0,wasRunning:!1,stopped:!1,started:!1};let U=b?await this.stop():!0;if(!U)return{ok:!1,wasRunning:b,stopped:!1,started:!1};let J=await this.start({caffeinate:$.caffeinate});return{ok:J,wasRunning:b,stopped:U,started:J}}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(),b=Number($);if(!b||b<=0)return null;return b}catch{return null}}removePid(){this.fs.unlink(this.pidFile)}isProcessAlive($){return this.process.isAlive($)}}import{existsSync as ue,mkdirSync as Ne}from"fs";import{dirname as fe}from"path";import{timingSafeEqual as ds}from"crypto";var VD=($)=>{return async(b,U)=>{let I=(b.req.header("authorization")??"").match(/^Bearer\s+(.+)$/i)?.[1]??"";if(!YX(I,$.expected))return b.text("unauthorized",401);return await U()}},YX=($,b)=>{let U=Buffer.from($,"utf-8"),J=Buffer.from(b,"utf-8"),D=Math.max(U.length,J.length,1),I=Buffer.alloc(D),X=Buffer.alloc(D);return U.copy(I),J.copy(X),ds(I,X)&&U.length===J.length};var P$=$J();var xT=($)=>{let b=Buffer.byteLength($.content,"utf-8");if($.meta)for(let[U,J]of Object.entries($.meta))b+=Buffer.byteLength(U,"utf-8")+Buffer.byteLength(J,"utf-8");return b},os=1048576,ts=200,ps=4194304,as=()=>{};class uO{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??as,this.maxBufferedBytes=$.maxBufferedBytes??os,this.now=$.now??(()=>Date.now()),this.replayBufferSize=Math.max(0,$.replayBufferSize??ts),this.replayBufferMaxBytes=Math.max(0,$.replayBufferMaxBytes??ps),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($,b){let U=this.replayBuffer[0]?.offset,J=this.persistentReplay&&(U===void 0||$<U-1),D=this.replayBuffer.filter((w)=>w.offset>$&&this.matchesClient(w,b));if(!J)return D;let I=this.persistentReplay?this.persistentReplay.loadSince($).filter((w)=>this.matchesClient(w,b)):[],X=U??Number.POSITIVE_INFINITY;return[...I.filter((w)=>w.offset<X),...D]}matchesClient($,b){let U=$.meta?.target;if(U&&U!==b.subscriberId)return!1;let J=$.meta?.channelId;if(J&&J!==b.channel)return!1;let D=$.meta?.connector;if(!D)return!0;return b.connectors.includes(D)}pickRecipients($){let b=new Map,U=[];for(let[J,D]of this.clients){if(!this.matchesClient($,D))continue;if(D.delivery==="exclusive"){let I=b.get(D.channel)??[];I.push(J),b.set(D.channel,I);continue}U.push(J)}for(let[J,D]of b){if(D.length===0)continue;let I=this.exclusiveCursor.get(J)??0,X=D[I%D.length];if(X)U.push(X);this.exclusiveCursor.set(J,I+1)}return U}addClient($,b){this.clients.set($,b)}removeClient($){this.clients.delete($)}getClientCount(){return this.clients.size}listChannels(){return[...this.clients.values()].map(($)=>({...$}))}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}broadcast($,b){this.latestOffset+=1;let U={content:$,meta:b,offset:this.latestOffset},J=JSON.stringify(U);if(this.eventsBroadcast+=1,this.lastBroadcastAt=this.now(),this.replayBufferSize>0){let I=xT(U);this.replayBuffer.push(U),this.replayBufferBytes+=I;while((this.replayBuffer.length>this.replayBufferSize||this.replayBufferBytes>this.replayBufferMaxBytes)&&this.replayBuffer.length>0){let X=this.replayBuffer.shift();if(X)this.replayBufferBytes-=xT(X)}}let D=this.pickRecipients(U);for(let I of D){let X=I.getBufferedAmount();if(X>this.maxBufferedBytes){let H=this.clients.get(I);this.logger?.warn("dropping slow WS client (backpressure)",{channel:H?.channel,buffered:X,max:this.maxBufferedBytes});try{I.close(1009,"backpressure")}catch{}this.clients.delete(I),this.droppedSlowClients+=1;continue}try{I.send(J)}catch(H){let w=H instanceof Error?H:Error(String(H)),G=this.clients.get(I);this.logger?.warn("ws.send failed; dropping client",{channel:G?.channel,error:w.message}),this.clients.delete(I)}}for(let I of this.subscribers){let X=(H)=>{let w=H instanceof Error?H:Error(String(H));this.logger?.error("broadcast subscriber threw",{error:w.message}),this.onError(w,{component:"broadcaster.subscriber",offset:U.offset,connector:U.meta?.connector??null,channel:U.meta?.channel??null})};try{let H=I(U);if(H instanceof Promise)H.catch(X)}catch(H){X(H)}}return U}seedLatestOffset($){if($>this.latestOffset)this.latestOffset=$}}var DB$=Y.object({type:Y.string(),content:Y.string(),channel_id:Y.string().nullable(),connector_id:Y.string().nullable(),meta:Y.record(Y.string(),Y.string()).nullable()});class NO{}import{Database as ss}from"bun:sqlite";import{existsSync as es,mkdirSync as $e}from"fs";import{dirname as be}from"path";var Ue=/^[a-z_][a-z0-9_]*$/,De=500,Je=new Set(["seq","ts","type","event"]),lT=[["CREATE TABLE IF NOT EXISTS logs (seq INTEGER PRIMARY KEY, ts INTEGER NOT NULL, type TEXT, event TEXT NOT NULL)","CREATE INDEX IF NOT EXISTS idx_logs_ts ON logs (ts)","CREATE INDEX IF NOT EXISTS idx_logs_type ON logs (type)"],["DROP TABLE IF EXISTS leuco_log","CREATE TABLE IF NOT EXISTS logs (seq INTEGER PRIMARY KEY, ts INTEGER NOT NULL, type TEXT, event TEXT NOT NULL)","CREATE INDEX IF NOT EXISTS idx_logs_ts ON logs (ts)","CREATE INDEX IF NOT EXISTS idx_logs_type ON logs (type)"]];class u0{db;maxRows;maxAgeMs;maxBytes;targetBytes;now;indexes;extractIndexes;insertStmt;insertWithSeqStmt;maxSeqStmt;countStmt;trimRowsStmt;trimAgeStmt;trimOldestStmt;insertsSinceByteCheck=0;constructor($){if($.path!==":memory:"){let I=be($.path);if(!es(I))$e(I,{recursive:!0})}if(this.db=new ss($.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)Xe(this.indexes),this.extractIndexes=$.extractIndexes??null,this.syncIndexColumns();else this.extractIndexes=null;let b=["ts","type","event",...this.indexes],U=b.map(()=>"?").join(", ");this.insertStmt=this.db.prepare(`INSERT INTO logs (${b.join(", ")}) VALUES (${U})`);let J=["seq",...b],D=J.map(()=>"?").join(", ");this.insertWithSeqStmt=this.db.prepare(`INSERT INTO logs (${J.join(", ")}) VALUES (${D})`),this.maxSeqStmt=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max FROM logs"),this.countStmt=this.db.prepare("SELECT COUNT(*) AS n FROM logs"),this.trimRowsStmt=this.db.prepare("DELETE FROM logs WHERE seq <= (SELECT seq FROM logs ORDER BY seq DESC LIMIT 1 OFFSET ?)"),this.trimAgeStmt=this.db.prepare("DELETE FROM logs WHERE ts < ?"),this.trimOldestStmt=this.db.prepare("DELETE FROM logs WHERE seq IN (SELECT seq FROM logs ORDER BY seq ASC LIMIT ?)")}insert($){try{let b=this.buildInsertParams($.ts,$.event),U=this.insertStmt.run(...b),J=Number(U.lastInsertRowid);return this.trim(),{seq:J,ts:$.ts,event:$.event}}catch(b){return b instanceof Error?b:Error(String(b))}}insertMany($){if($.length===0)return[];try{let b=[];return this.db.transaction((J)=>{for(let D of J){let I=this.buildInsertParams(D.ts,D.event),X=this.insertStmt.run(...I);b.push({seq:Number(X.lastInsertRowid),ts:D.ts,event:D.event})}})($),this.trim(),b}catch(b){return b instanceof Error?b:Error(String(b))}}write($){try{let b=[$.seq,...this.buildInsertParams($.ts,$.event)];this.insertWithSeqStmt.run(...b),this.trim()}catch(b){return b instanceof Error?b:Error(String(b))}}getMaxSeq(){let $=this.maxSeqStmt.get();return $?$.max:0}query($={}){let b=[],U=[];if($.seq!==void 0)b.push("seq = ?"),U.push($.seq);else b.push("seq > ?"),U.push($.sinceSeq??0);if(typeof $.type==="string")b.push("type = ?"),U.push($.type);if($.where)this.appendWhereConditions($.where,b,U);if($.wherePrefix)this.appendPrefixConditions($.wherePrefix,b,U);if($.whereIn)this.appendSetConditions($.whereIn,b,U);let J=$.limit??1000;U.push(J);let D=$.order==="desc"?"DESC":"ASC",I=`SELECT seq, ts, type, event FROM logs WHERE ${b.join(" AND ")} ORDER BY seq ${D} LIMIT ?`,H=this.db.prepare(I).all(...U);if(D==="DESC")H.reverse();return H.map(we)}getSchemaVersion(){return this.db.prepare("PRAGMA user_version").get()?.user_version??0}close(){this.db.close()}buildInsertParams($,b){let U=He(b),J=JSON.stringify(b);if(this.indexes.length===0)return[$,U,J];let D=this.extractIndexes?this.extractIndexes(b):null,I=this.indexes.map((X)=>D?.[X]??null);return[$,U,J,...I]}appendWhereConditions($,b,U){for(let J of this.indexKeys()){let D=$[J];if(D===void 0)continue;if(D===null)b.push(`${J} IS NULL`);else b.push(`${J} = ?`),U.push(D)}}appendPrefixConditions($,b,U){for(let J of this.indexKeys()){let D=$[J];if(D===void 0)continue;b.push(`${J} LIKE ? ESCAPE '\\'`),U.push(`${Ie(D)}%`)}}appendSetConditions($,b,U){for(let J of this.indexKeys()){let D=$[J];if(D===void 0)continue;if(D.length===0){b.push("1 = 0");continue}let I=D.filter((w)=>w!==null),X=I.length!==D.length,H=[];if(I.length>0)H.push(`${J} IN (${I.map(()=>"?").join(", ")})`),U.push(...I);if(X)H.push(`${J} IS NULL`);b.push(`(${H.join(" OR ")})`)}}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()}indexKeys(){return this.indexes}maybeTrimBytes(){if(this.maxBytes===null||this.targetBytes===null)return;if(this.insertsSinceByteCheck+=1,this.insertsSinceByteCheck<De)return;this.insertsSinceByteCheck=0;let $=this.byteSize();if($<=this.maxBytes)return;let b=this.countStmt.get()?.n??0;if(b===0)return;let U=$-this.targetBytes,J=$/b,D=Math.min(b,Math.ceil(U/J));this.trimOldestStmt.run(D),this.db.run("VACUUM")}byteSize(){let $=this.db.prepare("PRAGMA page_count").get()?.n??0,b=this.db.prepare("PRAGMA page_size").get()?.n??0;return $*b}clear(){this.db.run("DELETE FROM logs"),this.db.run("VACUUM"),this.insertsSinceByteCheck=0}syncIndexColumns(){let $=new Set(this.db.prepare("PRAGMA table_info(logs)").all().map((b)=>b.name));for(let b of this.indexes){if(!$.has(b))this.db.run(`ALTER TABLE logs ADD COLUMN ${b} TEXT`);this.db.run(`CREATE INDEX IF NOT EXISTS idx_logs_${b} ON logs (${b})`)}}migrate(){let b=this.db.prepare("PRAGMA user_version").get()?.user_version??0;if(b>=lT.length)return;let U=lT.slice(b),J=b;for(let D of U)J+=1,this.db.transaction(()=>{for(let X of D)this.db.run(X);this.db.run(`PRAGMA user_version = ${J}`)})()}}function Ie($){return $.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function Xe($){for(let b of $){if(!Ue.test(b))throw Error(`invalid index column name: ${b}`);if(Je.has(b))throw Error(`reserved index column name: ${b}`)}}function He($){if(typeof $!=="object"||$===null)return null;if(!("type"in $))return null;let b=$.type;return typeof b==="string"?b:null}function we($){return{seq:$.seq,ts:$.ts,event:JSON.parse($.event)}}var nT=2000;class fO extends NO{sink;now;logger;onError;constructor($){super();this.now=$.now??(()=>Date.now()),this.logger=$.logger,this.onError=$.onError,this.sink=new u0({path:$.path,indexes:["channel_id","connector_id"],extractIndexes:(b)=>({channel_id:b.channel_id,connector_id:b.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 b={type:$.meta?.event_type??"unknown",content:Ge($.content),channel_id:$.channelId,connector_id:$.connectorId,meta:$.meta},U=this.sink.write({seq:$.offset,ts:this.now(),event:b});if(U instanceof Error)this.logger?.error("event log write failed",{offset:$.offset,error:U.message}),this.onError?.(U,{component:"sqlite-event-log",op:"record",offset:$.offset,channelId:$.channelId,connectorId:$.connectorId})}loadSince($){let b=this.sink.query({sinceSeq:$,limit:Number.MAX_SAFE_INTEGER}),U=[];for(let J of b)U.push({content:J.event.content,meta:J.event.meta??void 0,offset:J.seq});return U}loadForChannel($){let b={channel_id:$.channelId};if($.connectorId!==void 0)b.connector_id=$.connectorId;let U=this.sink.query({where:b,...$.sinceSeq!==void 0?{sinceSeq:$.sinceSeq}:{},...$.limit!==void 0?{limit:$.limit}:{}}),J=[];for(let D of U)J.push({content:D.event.content,meta:D.event.meta??void 0,offset:D.seq});return J}findMaxOffset(){return this.sink.getMaxSeq()}clear(){this.sink.clear()}close(){this.sink.close()}}function Ge($){if($.length<=nT)return $;return`${$.slice(0,nT)}...`}var We=()=>{},Qe=30000,Ye=60000,Oe=30000,Ve=($)=>new Promise((b)=>{setTimeout(b,$)});class v6{channels;notify;logger;onError;running=new Map;failureCounts=new Map;starting=new Set;stats=new Map;healthCheckIntervalMs;maxBackoffMs;startTimeoutMs;sleep;now;healthCheckTimer=null;healthCheckInFlight=!1;pendingRetry=new Map;constructor($){this.channels=$.channels,this.notify=$.notify,this.logger=$.logger,this.onError=$.onError??We,this.healthCheckIntervalMs=$.healthCheckIntervalMs??Qe,this.maxBackoffMs=$.maxBackoffMs??Ye,this.startTimeoutMs=$.startTimeoutMs??Oe,this.sleep=$.sleep??Ve,this.now=$.now??(()=>Date.now())}static keyOf($,b){return`${$}/${b}`}isRunning($,b){return this.running.has(v6.keyOf($,b))}list(){return[...this.running.entries()].map(([$,b])=>{let U=this.stats.get($);return{channelName:b.channelName,channelId:b.channelId,name:b.config.name,type:b.config.type,alive:b.listener.isAlive(),events:U?.events??0,errors:U?.errors??0,failureCount:this.failureCounts.get($)??0,lastEventAt:U?.lastEventAt??null}})}async start($,b){let U=v6.keyOf($,b);if(this.running.has(U))return{ok:!0,reason:"already running"};if(this.starting.has(U))return{ok:!1,reason:"already starting",retriable:!0};this.starting.add(U);try{return await this.startLocked($,b,U)}finally{this.starting.delete(U)}}async startLocked($,b,U){let J=this.channels.createListener($,b);if(!J)return{ok:!1,reason:`connector "${b}" not found in channel "${$}"`};let D=async(I,X)=>{try{await this.notify($,b,I,X),this.recordEvent(U)}catch(H){throw this.recordError(U),H}};try{return await Promise.race([J.listener.start(D),this.sleep(this.startTimeoutMs).then(()=>{throw Error(`listener start timed out after ${this.startTimeoutMs}ms`)})]),this.running.set(U,{config:J.config,channelName:$,channelId:J.channelId,listener:J.listener}),this.pendingRetry.delete(U),this.ensureStats(U),this.logger?.info(`${J.config.type} listener started`,{channel:$,connector:b}),{ok:!0}}catch(I){let X=I instanceof Error?I:Error(String(I));try{await J.listener.stop()}catch{}this.logger?.error(`${J.config.type} listener failed to start`,{channel:$,connector:b,error:X.message}),this.onError(X,{component:"listener-registry.start",channel:$,connector:b,type:J.config.type});let H=!(X instanceof o1);return{ok:!1,reason:X.message,retriable:H}}}async stop($,b){let U=v6.keyOf($,b),J=this.running.get(U);if(!J)return{ok:!0,reason:"not running"};try{return await J.listener.stop(),this.logger?.info(`${J.config.type} listener stopped`,{channel:$,connector:b}),{ok:!0}}catch(D){let I=D instanceof Error?D:Error(String(D));return this.logger?.error(`${J.config.type} listener failed to stop`,{channel:$,connector:b,error:I.message}),this.onError(I,{component:"listener-registry.stop",channel:$,connector:b,type:J.config.type}),{ok:!1,reason:I.message}}finally{this.running.delete(U),this.failureCounts.delete(U)}}async restart($,b){let U=await this.stop($,b);if(!U.ok)return U;return await this.start($,b)}async startAll(){let $=this.channels.listAllConnectors(),b=await Promise.allSettled($.map((U)=>this.start(U.channelName,U.name)));for(let U=0;U<b.length;U++){let J=b[U],D=$[U];if(J.status==="rejected"){let I=v6.keyOf(D.channelName,D.name);this.pendingRetry.set(I,{channelName:D.channelName,connectorName:D.name});continue}if(J.status==="fulfilled"&&!J.value.ok){if(J.value.retriable===!1)continue;let I=v6.keyOf(D.channelName,D.name);this.pendingRetry.set(I,{channelName:D.channelName,connectorName:D.name})}}this.startHealthCheck()}async stopAll(){this.stopHealthCheck(),this.pendingRetry.clear();for(let[,$]of this.running.entries())await this.stop($.channelName,$.config.name)}ensureStats($){let b=this.stats.get($);if(b)return b;let U={events:0,errors:0,failureCount:0,lastEventAt:null};return this.stats.set($,U),U}recordEvent($){let b=this.ensureStats($);b.events+=1,b.lastEventAt=new Date(this.now()).toISOString()}recordError($){this.ensureStats($).errors+=1}startHealthCheck(){if(this.healthCheckTimer)return;this.healthCheckTimer=setInterval(()=>{this.runHealthCheck().catch(($)=>{let b=$ instanceof Error?$:Error(String($));this.logger?.error("health check pass failed",{error:b.message}),this.onError(b,{component:"listener-registry.health-check"})})},this.healthCheckIntervalMs),this.healthCheckTimer.unref()}stopHealthCheck(){if(!this.healthCheckTimer)return;clearInterval(this.healthCheckTimer),this.healthCheckTimer=null}async runHealthCheckForTest(){await this.runHealthCheck()}async runHealthCheck(){if(this.healthCheckInFlight)return;this.healthCheckInFlight=!0;try{let $=[];for(let[U,J]of this.running.entries()){if(J.listener.isAlive()){this.failureCounts.delete(U);continue}$.push({channelName:J.channelName,connectorName:J.config.name,type:J.config.type})}await Promise.all($.map((U)=>this.recoverDead(U.channelName,U.connectorName,U.type)));let b=[];for(let[U,J]of this.pendingRetry.entries()){if(this.running.has(U)){this.pendingRetry.delete(U);continue}b.push({key:U,channelName:J.channelName,connectorName:J.connectorName})}await Promise.all(b.map((U)=>this.attemptRetry(U)))}finally{this.healthCheckInFlight=!1}}async attemptRetry($){this.logger?.info("retrying failed listener",{channel:$.channelName,connector:$.connectorName});let b=this.failureCounts.get($.key)??0,U=Math.min(1000*2**b,this.maxBackoffMs);await this.sleep(U);let J=await this.start($.channelName,$.connectorName);if(J.ok){this.pendingRetry.delete($.key),this.failureCounts.delete($.key);return}if(J.retriable===!1){this.pendingRetry.delete($.key),this.failureCounts.delete($.key),this.logger?.warn("dropping listener from retry queue (non-retriable)",{channel:$.channelName,connector:$.connectorName,reason:J.reason});return}this.failureCounts.set($.key,b+1)}async recoverDead($,b,U){let J=v6.keyOf($,b),D=this.failureCounts.get(J)??0,I=Math.min(1000*2**D,this.maxBackoffMs);this.logger?.warn(`${U} listener unhealthy, restarting`,{channel:$,connector:b,attempt:D+1,backoffMs:I}),await this.stop($,b),await this.sleep(I);let X=await this.start($,b);if(X.ok)this.failureCounts.delete(J),this.logger?.info(`${U} listener recovered`,{channel:$,connector:b});else if(X.retriable===!1)this.failureCounts.delete(J),this.logger?.warn(`${U} listener cannot recover (non-retriable)`,{channel:$,connector:b,reason:X.reason});else this.failureCounts.set(J,D+1)}}var ve=new N$,Ze=3000,Be=100,ze=200,Ke=($)=>new Promise((b)=>{setTimeout(b,$)}),je=($)=>`funnel-gateway[${$}]`,Le=async($)=>{let b=$.now()+Ze;while($.now()<b){if($.pids.every((U)=>!$.runner.isAlive(U)))return;await $.sleep(Be)}for(let U of $.pids){if(!$.runner.isAlive(U))continue;try{$.runner.kill(U,"SIGKILL")}catch{}}await $.sleep(ze)},iT=async($)=>{let b=$.process??ve,U=$.logger,J=je($.dir),D=b.listProcessesContaining(J),I=[];for(let X of D){if(X.pid===$.selfPid)continue;b.kill(X.pid,"SIGTERM"),I.push(X.pid),U?.info("killed competing Slack gateway process",{pid:X.pid,args:X.command.slice(0,160)})}if(I.length===0)return I;return await Le({runner:b,pids:I,sleep:$.sleep??Ke,now:$.now??(()=>Date.now())}),I};var c4=($)=>Gb("param",$,(b,U)=>{if(b.success)return;let J=b.error.issues[0],D=J?`${J.path.join(".")}: ${J.message}`:"invalid request";return U.json({ok:!1,reason:D},400)});var SO=Y.lazy(()=>Y.union([Y.string(),Y.number(),Y.boolean(),Y.null(),Y.array(SO),Y.record(Y.string(),SO)])),Ae=Y.object({method:Y.string().min(1),path:Y.string().min(1),body:SO.optional()}),yT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=null;try{U=await $.req.json()}catch{U=null}let J=Ae.safeParse(U);if(!J.success)throw new h(400,{message:J.error.issues[0]?.message??"invalid body"});let D=await $.var.deps.channels.call(b.channel,b.connector,{method:J.data.method,path:J.data.path,body:J.data.body});return $.json({ok:!0,result:D})});var hT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1)})),Gb("json",_T,($,b)=>{if($.success)return;let U=$.error.issues[0],J=U?`${U.path.join(".")}: ${U.message}`:"invalid body";return b.json({ok:!1,reason:J},400)}),($)=>{let b=$.req.valid("param"),U=$.req.valid("json"),J=U.target?{...U.meta,target:U.target}:U.meta,I={ok:!0,offset:$.var.deps.emit({channel:b.channel,connector:U.connector,content:U.content,meta:J}).offset};return $.json(I)});var qe=($)=>{let U=($.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:U};if(!$.listener.alive)return{status:"error",message:"listener is dead",nextActions:["fnl gateway logs","fnl gateway restart"],rootCause:U};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:U};return{status:"ok",message:"healthy",nextActions:[],rootCause:null}},mT=P$.createHandlers(async($)=>{let b=$.var.deps,U=$.req.query("channel")??null,J=b.channels.list(),D=U?J.filter((G)=>G.name===U||G.id===U):J,I=b.registry.list(),X=b.broadcaster.listChannels(),H=b.broadcaster.getMetrics(),w=D.map((G)=>{let W=I.find((K)=>K.channelName===G.name)??null,Q=W?{alive:W.alive,events:W.events,errors:W.errors,lastEventAt:W.lastEventAt}:null,O=X.filter((K)=>K.channel===G.id||K.channel===G.name).length,V=(()=>{if(!b.diagnosticLog)return[];try{return b.diagnosticLog.queryProcessed({channelId:G.id,limit:10}).map(rb)}catch{return[]}})(),Z=Q&&(!Q.alive||Q.errors>0)||!Q,v=(()=>{if(!Z||!b.diagnosticLog)return[];try{return b.diagnosticLog.queryConnection({channelId:G.id,statuses:["auth-failed","error"],limit:3}).map(M0)}catch{return[]}})(),B={id:G.id,name:G.name,connectors:G.connectors.map((K)=>K.name),listener:Q,claudeClients:O,recentEvents:V,connectionErrors:v};return{...B,diagnosis:qe(B)}});return $.json({pid:b.selfPid,uptimeMs:b.uptimeMs(),eventsBroadcast:H.eventsBroadcast,channels:w})});var rT=P$.createHandlers(($)=>{let b=$.var.deps;return $.json({ok:!0,pid:b.selfPid,funnelDir:b.dir,clients:b.broadcaster.getClientCount(),listeners:b.registry.list()})});var cT=P$.createHandlers(($)=>{return $.json({listeners:$.var.deps.registry.list()})});var dT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=await $.var.deps.registry.restart(b.channel,b.connector);return $.json(U,U.ok?200:400)});var oT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=await $.var.deps.registry.start(b.channel,b.connector);return $.json(U,U.ok?200:400)});var tT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=await $.var.deps.registry.stop(b.channel,b.connector);return $.json(U,U.ok?200:400)});var pT=P$.createHandlers(($)=>{let b=$.var.deps;return $.json({ok:!0,pid:b.selfPid,funnelDir:b.dir,uptimeMs:b.uptimeMs(),clients:b.broadcaster.listChannels(),listeners:b.registry.list(),broadcaster:b.broadcaster.getMetrics()})});function Pe(){return P$.createApp().onError(($,b)=>{if($ instanceof h)return $.getResponse();let U=$ instanceof Error?$.message:String($);return b.json({error:U},500)}).get("/health",...rT).get("/status",...pT).get("/debug",...mT).get("/listeners",...cT).post("/listeners/:channel/:connector/start",...oT).delete("/listeners/:channel/:connector",...tT).post("/listeners/:channel/:connector/restart",...dT).post("/channels/:channel/connectors/:connector/call",...yT).post("/channels/:channel/publish",...hT)}var aT=Pe();import{createHash as Te,randomUUID as Fe}from"crypto";import{join as Me}from"path";function sT($){let b=$.port===0?Fe():String($.port),U=Te("sha256").update(`${$.funnelDir}\x00${b}`).digest("hex").slice(0,20);return Me($.tmpDir,"events",`${U}.db`)}var Se="127.0.0.1",ge=new Set(["127.0.0.1","localhost","::1","::ffff:127.0.0.1"]),Re=()=>{};class gO{channels;configuredPort;configuredHostname;dbPath;process;logger;onError;selfPid;dir;killCompetingSlack;token;allowInsecureHost;broadcaster;eventLog;registry;nowMs;extraRoutes;ownsEventLog;diagnosticLog;startedAt=null;server=null;disposed=!1;constructor($){this.channels=$.channels,this.configuredPort=$.port??Y6(),this.configuredHostname=$.hostname??Se,this.dir=$.dir??R4,this.dbPath=$.dbPath??sT({tmpDir:$.tmpDir??c$(),funnelDir:this.dir,port:this.configuredPort}),this.process=$.process,this.logger=$.logger,this.onError=$.onError??Re,this.selfPid=$.selfPid??globalThis.process.pid,this.killCompetingSlack=$.killCompetingSlack??!0,this.token=$.token??"",this.allowInsecureHost=$.allowInsecureHost??!1,this.extraRoutes=$.extraRoutes??null,this.diagnosticLog=$.diagnosticLog;let b=$.clock;if(this.nowMs=b?()=>b.millis():()=>Date.now(),$.eventLog)this.eventLog=$.eventLog,this.ownsEventLog=!1;else{let U=fe(this.dbPath);if(!ue(U))Ne(U,{recursive:!0});this.eventLog=new fO({path:this.dbPath,now:this.nowMs,logger:this.logger,onError:this.onError}),this.ownsEventLog=!0}this.broadcaster=new uO({logger:this.logger,onError:this.onError,now:this.nowMs,persistentReplay:this.eventLog}),this.broadcaster.seedLatestOffset(this.eventLog.findMaxOffset()),this.registry=new v6({channels:this.channels,logger:this.logger,onError:this.onError,notify:async(U,J,D,I)=>{this.emit({channel:U,connector:J,content:D,meta:I})},now:this.nowMs})}get port(){return this.server?.port??this.configuredPort}get hostname(){return this.server?.hostname??this.configuredHostname}async start(){if(this.disposed)throw Error("FunnelGatewayServer is single-use: construct a new instance to start again");if(this.server)return;if(!this.token&&!ge.has(this.configuredHostname)&&!this.allowInsecureHost)throw Error(`refusing to start gateway: hostname "${this.configuredHostname}" is reachable off-box but no token is set. Set a token, bind to loopback (127.0.0.1), or pass allowInsecureHost: true.`);let $=this.buildApp();await this.killCompetingSlackIfNeeded(),this.startedAt=this.nowMs(),this.server=Bun.serve({port:this.configuredPort,hostname:this.configuredHostname,development:!1,fetch:(b,U)=>this.handleFetch(b,U,$),websocket:{open:(b)=>this.handleWsOpen(b),close:(b)=>this.handleWsClose(b),message(){}}}),this.logServerStarted();try{await this.bootListeners()}catch(b){throw this.server.stop(),this.server=null,b}}async stop(){if(await this.registry.stopAll(),this.server)this.server.stop(),this.server=null;if(this.ownsEventLog)this.eventLog.close();this.disposed=!0}getStatus(){return{clients:this.broadcaster.getClientCount(),channels:this.broadcaster.listChannels()}}getBroadcaster(){return this.broadcaster}getRegistry(){return this.registry}getEventLog(){return this.eventLog}onEvent($){return this.broadcaster.subscribe($)}handleFetch($,b,U){let J=new URL($.url);if(J.pathname==="/ws"&&$.headers.get("upgrade")==="websocket"){if(this.token&&!this.tokenMatchesUpgrade($))return new Response("unauthorized",{status:401});let D=J.searchParams.get("channel")??"",I=D?this.resolveChannel(D):null;if(D&&!I)return new Response(`unknown channel "${D}"`,{status:404});let X=I?.id??D,H=I?.name??null,w=I?.connectors??[],G=I?.delivery??"fanout",W=J.searchParams.get("since"),Q=W===null?Number.NaN:Number.parseInt(W,10),O=Number.isFinite(Q)&&Q>=0?Q:void 0,V=J.searchParams.get("id")??void 0;if(b.upgrade($,{data:{channel:X,channelName:H,connectors:w,delivery:G,subscriberId:V,since:O}}))return;return new Response("WebSocket upgrade failed",{status:400})}return U.fetch($)}handleWsOpen($){if(typeof $.data.since==="number"){let b=this.broadcaster.replaySince($.data.since,$.data);try{for(let U of b)$.send(JSON.stringify(U))}catch(U){let J=U instanceof Error?U:Error(String(U));this.logger?.warn("replay send failed during ws.open",{error:J.message}),this.onError(J,{component:"gateway-server.replay"});return}}this.broadcaster.addClient($,$.data),this.logger?.info("channel connected",{event_type:"system",action:"channel_connect",channel:$.data.channelName??"",channelId:$.data.channel,connectors:$.data.connectors.join(","),total:String(this.broadcaster.getClientCount())})}handleWsClose($){this.broadcaster.removeClient($),this.logger?.info("channel disconnected",{event_type:"system",action:"channel_disconnect",channel:$.data.channelName??"",channelId:$.data.channel,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 $=P$.createApp();if($.use((U,J)=>{return U.set("deps",{selfPid:this.selfPid,dir:this.dir,broadcaster:this.broadcaster,registry:this.registry,channels:this.channels,uptimeMs:()=>this.startedAt?this.nowMs()-this.startedAt:0,emit:(D)=>this.emit(D),diagnosticLog:this.diagnosticLog}),J()}),this.token)$.use("/listeners/*",VD({expected:this.token})),$.use("/status",VD({expected:this.token})),$.use("/debug",VD({expected:this.token})),$.use("/channels/*",VD({expected:this.token}));return(this.extraRoutes?$.route("/",this.extraRoutes):$).route("/",aT)}tokenMatchesUpgrade($){let b=($.headers.get("sec-websocket-protocol")??"").split(",").map((D)=>D.trim()).filter((D)=>D.length>0);for(let D of b)if(D.startsWith("funnel.token.")&&YX(D.slice(13),this.token))return!0;let J=($.headers.get("authorization")??"").match(/^Bearer\s+(.+)$/i);if(J&&YX(J[1]??"",this.token))return!0;return!1}resolveChannel($){let b=this.channels.get($)??this.channels.getById($);if(!b)return null;return{id:b.id,name:b.name,connectors:b.connectors.map((U)=>U.name),delivery:b.delivery}}async killCompetingSlackIfNeeded(){if(!this.killCompetingSlack)return;if(!this.channels.listAllConnectors().some((U)=>U.type==="slack"))return;let b=await iT({selfPid:this.selfPid,dir:this.dir,process:this.process,logger:this.logger});if(b.length>0)this.logger?.info("killed competing Slack gateway processes",{event_type:"system",action:"kill_competing",pids:b.join(",")})}async bootListeners(){await this.registry.startAll();for(let $ of this.registry.list())this.logger?.info(`${$.type} listener started: ${$.name}`,{event_type:"system",action:`${$.type}_connect`,channel:$.channelName,connector:$.name});this.logger?.info(`event store: ${this.dbPath}`),this.logger?.info("funnel gateway running")}emit($){let b=this.lookupChannelId($.channel),U=b&&$.connector?this.lookupConnectorId(b,$.connector):null,J={...$.meta,channel:$.channel};if($.connector)J.connector=$.connector;if(b)J.channelId=b;if(U)J.connectorId=U;let D=this.broadcaster.broadcast($.content,J);return this.eventLog.record({content:$.content,channelId:b??null,connectorId:U??null,meta:J,offset:D.offset}),{offset:D.offset}}lookupChannelId($){return this.channels.get($)?.id??this.channels.getById($)?.id??null}lookupConnectorId($,b){return this.channels.getById($)?.connectors.find((J)=>J.name===b)?.id??null}}import{homedir as _e}from"os";import{dirname as ke,join as eT}from"path";var $F="gateway.token",Ee=32,Ce=new F$,xe=()=>{let $=new Uint8Array(Ee);return crypto.getRandomValues($),[...$].map((b)=>b.toString(16).padStart(2,"0")).join("")};class RO{fs;path;generate;constructor($={}){this.fs=$.fs??Ce,this.path=eT($.dir??R4,$F),this.generate=$.generate??xe,Object.freeze(this)}read(){if(!this.fs.existsSync(this.path))return null;let $=this.fs.readFileSync(this.path).trim();return $.length>0?$:null}ensure(){return this.fs.mkdirSync(ke(this.path),{recursive:!0}),this.fs.withFileLock(`${this.path}.lock`,()=>{let $=this.read();if($)return $;let b=this.generate();return this.fs.writeSecretFileSync(this.path,`${b}
|
|
1596
|
+
`,Ns=String.fromCharCode(8),fs=String.fromCharCode(127),Ss=String.fromCharCode(3),gs=String.fromCharCode(4);class OO extends YD{async promptSecret($){if(!r4.isTTY)throw Error(`cannot prompt for "${$}": stdin is not a TTY. Set the matching env var or run \`fnl channels <ch> connectors add ...\` first.`);WX.write(`${$}: `);let b=r4.isRaw;r4.setRawMode(!0),r4.resume();try{return await this.readSecret()}finally{r4.setRawMode(b),r4.pause(),WX.write(ST)}}readSecret(){return new Promise(($,b)=>{let U="",J=(D)=>{for(let I of D){let X=String.fromCharCode(I);if(X===ST||X===us){r4.off("data",J),$(U);return}if(X===Ss){r4.off("data",J),b(Error("prompt cancelled"));return}if(X===gs){if(r4.off("data",J),U.length===0)b(Error("prompt cancelled"));else $(U);return}if(X===Ns||X===fs){if(U.length>0)U=U.slice(0,-1),WX.write("\b \b");continue}U+=X,WX.write(Ms)}};r4.on("data",J)})}}var Rs=384;class VO extends m1{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($,b){this.files.set($,b),this.touch($)}writeSecretFileSync($,b){this.files.set($,b),this.modes.set($,Rs),this.touch($)}appendFileSync($,b){let U=this.files.get($)??"";this.files.set($,U+b),this.touch($)}unlink($){this.files.delete($),this.mtimes.delete($),this.modes.delete($)}mkdirSync($,b){this.dirs.add($)}readdirSync($){let b=$.endsWith("/")?$:`${$}/`,U=[];for(let J of this.files.keys()){if(!J.startsWith(b))continue;let D=J.slice(b.length);if(!D.includes("/"))U.push(D)}return U}statSync($){let b=this.mtimes.get($);if(b===void 0)throw Error(`not found: ${$}`);return{mtimeMs:b,mode:this.modes.get($)??null}}withFileLock($,b){return b()}setMtime($,b){this.mtimes.set($,b)}setMode($,b){this.modes.set($,b)}touch($){if(!this.mtimes.has($))this.mtimes.set($,this.now());else this.mtimes.set($,this.now())}}class vO extends JD{counter=0;prefix;constructor($={}){super();this.prefix=$.prefix??"id"}generate(){return this.counter++,`${this.prefix}-${this.counter}`}}class ZO extends HD{file=null;entries=[];info($,b){this.entries.push({level:"info",message:$,meta:b})}warn($,b){this.entries.push({level:"warn",message:$,meta:b})}error($,b){this.entries.push({level:"error",message:$,meta:b})}clear(){this.entries.length=0}}var gT={exitCode:0,stdout:"",stderr:""};class BO extends i1{calls=[];killed=[];handler=()=>gT;syncHandler=()=>gT;aliveStub=null;listStub=null;startTimeStub=null;on($){return this.handler=$,this}onSync($){return this.syncHandler=$,this}onIsAlive($){return this.aliveStub=$,this}onListProcessesContaining($){return this.listStub=$,this}onGetStartTime($){return this.startTimeStub=$,this}async run($,b={}){this.calls.push({kind:"run",command:$,options:b});let U=await this.handler($);return{exitCode:U.exitCode??0,stdout:U.stdout??"",stderr:U.stderr??""}}runSync($){this.calls.push({kind:"runSync",command:$});let b=this.syncHandler($);return{exitCode:b.exitCode??0,stdout:b.stdout??"",stderr:b.stderr??""}}async attach($,b={}){if(this.calls.push({kind:"attach",command:$,options:b}),b.onSpawned)b.onSpawned(1);return(await this.handler($)).exitCode??0}detach($,b={}){this.calls.push({kind:"detach",command:$,options:b})}kill($,b="SIGTERM"){this.calls.push({kind:"kill",command:[String($),b]}),this.killed.push({pid:$,signal:b})}isAlive($){if(this.aliveStub)return this.aliveStub($);let b=this.syncHandler(["ps","-p",String($),"-o","state="]);if((b.exitCode??0)!==0)return!1;let U=(b.stdout??"").trim();if(!U)return!1;return!U.startsWith("Z")}listProcessesContaining($){if(this.listStub)return this.listStub($);return[]}getStartTime($){if(this.startTimeStub)return this.startTimeStub($);return null}}var _s=($={})=>({version:Q6,channels:[],profiles:[],...$});class zO extends ID{state;constructor($){super();this.state=_s($)}read(){return this.state}write($){this.state=$}update($){return $(this.state)}}class KO extends WD{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()+$)}}class jO extends x1{calls=[];handler=()=>({status:200,body:""});on($){return this.handler=$,this}async fetch($){this.calls.push($);let b=await this.handler($),U=b.status??200,J=b.body??"";return{status:U,ok:U>=200&&U<300,text:async()=>J,json:async()=>JSON.parse(J)}}}class LO extends YD{answers;asked=[];constructor($={}){super();this.answers=new Map(Object.entries($.answers??{}))}async promptSecret($){this.asked.push($);let b=this.answers.get($);if(b===void 0)throw Error(`no answer seeded for prompt "${$}"`);return b}}var ks=["started","connected","disconnected","auth-failed","stopped","error"],uZ$=Y.object({event_id:Y.string(),type:Y.string(),connector_id:Y.string().nullable(),channel_id:Y.string().nullable(),payload:Y.string()}),NZ$=Y.object({event_id:Y.string(),type:Y.string(),connector_id:Y.string().nullable(),channel_id:Y.string().nullable(),outcome:Y.string(),payload:Y.string()}),RT=Y.object({type:Y.string(),connector_id:Y.string().nullable(),channel_id:Y.string().nullable(),status:Y.enum(ks),detail:Y.string()});class OD{}class PO extends OD{now;raws=[];processeds=[];connections=[];constructor($=()=>Date.now()){super();this.now=$;Object.freeze(this)}recordRaw($){this.raws.push({...$,seq:this.raws.length+1,ts:this.now()})}recordProcessed($){this.processeds.push({...$,seq:this.processeds.length+1,ts:this.now()})}recordConnection($){this.connections.push({...$,seq:this.connections.length+1,ts:this.now()})}queryRaw($){let b=this.raws.filter((U)=>{if(!AO(U,$))return!1;if($.eventId!==void 0&&U.eventId!==$.eventId)return!1;return!0});return qO(b,$.limit)}queryProcessed($){let b=this.processeds.filter((U)=>{if(!AO(U,$))return!1;if($.eventId!==void 0&&U.eventId!==$.eventId)return!1;if($.outcome!==void 0&&U.outcome!==$.outcome)return!1;if($.outcomePrefix!==void 0&&!U.outcome.startsWith($.outcomePrefix))return!1;return!0});return qO(b,$.limit)}queryConnection($){let b=this.connections.filter((U)=>{if(!AO(U,$))return!1;if($.status!==void 0&&U.status!==$.status)return!1;if($.statuses!==void 0&&!$.statuses.includes(U.status))return!1;return!0});return qO(b,$.limit)}clear(){this.raws.length=0,this.processeds.length=0,this.connections.length=0}close(){}}var AO=($,b)=>{if(b.type!==void 0&&$.type!==b.type)return!1;if(b.connectorId!==void 0&&$.connectorId!==b.connectorId)return!1;if(b.channelId!==void 0&&$.channelId!==b.channelId)return!1;if("seq"in $&&b.seq!==void 0&&$.seq!==b.seq)return!1;return!0},qO=($,b)=>{if(b===void 0)return $;if(b<=0)return[];return $.slice(-b)};var _T=Y.object({content:Y.string().min(1),meta:Y.record(Y.string(),Y.string()).optional(),connector:Y.string().min(1).optional(),target:Y.string().min(1).optional()}),kT=Y.object({ok:Y.literal(!0),offset:Y.number().int().nonnegative()});var Es={state:"offline"};class TO{port;isDaemonRunning;getToken;constructor($){this.port=$.port,this.isDaemonRunning=$.isDaemonRunning,this.getToken=$.getToken??(()=>null),Object.freeze(this)}async publish($,b){if(!this.isDaemonRunning())return Es;try{let U=`${i$(this.port)}/channels/${encodeURIComponent($)}/publish`,J=await r$(U,{method:"POST",headers:{...this.authHeaders(),"content-type":"application/json"},body:JSON.stringify(b)});if(!J.ok)return{state:"error",reason:await J.text()||`HTTP ${J.status}`};let D=kT.safeParse(await J.json());if(!D.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",offset:D.data.offset}}catch(U){return{state:"error",reason:U instanceof Error?U.message:String(U)}}}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}}import{join as ET}from"path";import{existsSync as Cs}from"fs";import{dirname as xs,resolve as FO}from"path";import{fileURLToPath as ls}from"url";var QX=()=>{let $=xs(ls(import.meta.url)),b=[FO($,"./daemon.ts"),FO($,"./daemon.js"),FO($,"./gateway/daemon.js")];for(let U of b)if(Cs(U))return U;throw Error(`daemon script not found (looked in ${b.join(", ")})`)};var ns=5000,is=2000,CT=100,ys=200,hs=new N$,ms=new F$,rs=new V6,cs=($)=>new Promise((b)=>{setTimeout(b,$)});class MO{process;fs;clock;dir;pidFile;gatewayLog;tmpDir;port;sleep;constructor($={}){this.process=$.process??hs,this.fs=$.fs??ms,this.clock=$.clock??rs,this.dir=$.dir??R4,this.tmpDir=$.tmpDir??c$(),this.pidFile=ET(this.dir,"gateway.pid"),this.gatewayLog=ET(this.tmpDir,"gateway.log"),this.port=$.port??Y6(),this.sleep=$.sleep??cs,Object.freeze(this)}isRunning(){let $=this.readPid();if(!$)return!1;return this.isProcessAlive($)}getStatus(){let $=this.readPid(),b=$!==null&&this.isProcessAlive($);return{running:b,pid:b?$:null,port:this.port}}async start($={}){if(this.isRunning())return!0;this.fs.mkdirSync(this.tmpDir,{recursive:!0});let b=QX(),U=this.buildStartCommand(b,$);this.process.detach(U,{env:{FUNNEL_DIR:this.dir,FUNNEL_PORT:String(this.port),FUNNEL_TMP_DIR:this.tmpDir},stdoutFile:this.gatewayLog,stderrFile:this.gatewayLog});let J=this.clock.millis()+ns;while(this.clock.millis()<J){if(this.isRunning())return!0;await this.sleep(CT)}return this.isRunning()}buildStartCommand($,b={}){let U=`funnel-gateway[${this.dir}]`;if(b.caffeinate!==!1&&globalThis.process.platform==="darwin")return["caffeinate","-is","bun",$,U];return["bun",$,U]}async stop(){let $=this.readPid();if(!$)return!0;if(!this.isProcessAlive($))return this.removePid(),!0;try{this.process.kill($,"SIGTERM")}catch{return!1}let b=this.clock.millis()+is;while(this.clock.millis()<b){if(!this.isProcessAlive($))return this.removePid(),!0;await this.sleep(CT)}try{this.process.kill($,"SIGKILL")}catch{}return await this.sleep(ys),this.removePid(),!this.isProcessAlive($)}async restart($={}){let b=this.isRunning();if($.onlyIfRunning&&!b)return{ok:!0,wasRunning:!1,stopped:!1,started:!1};let U=b?await this.stop():!0;if(!U)return{ok:!1,wasRunning:b,stopped:!1,started:!1};let J=await this.start({caffeinate:$.caffeinate});return{ok:J,wasRunning:b,stopped:U,started:J}}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(),b=Number($);if(!b||b<=0)return null;return b}catch{return null}}removePid(){this.fs.unlink(this.pidFile)}isProcessAlive($){return this.process.isAlive($)}}import{existsSync as ue,mkdirSync as Ne}from"fs";import{dirname as fe}from"path";import{timingSafeEqual as ds}from"crypto";var VD=($)=>{return async(b,U)=>{let I=(b.req.header("authorization")??"").match(/^Bearer\s+(.+)$/i)?.[1]??"";if(!YX(I,$.expected))return b.text("unauthorized",401);return await U()}},YX=($,b)=>{let U=Buffer.from($,"utf-8"),J=Buffer.from(b,"utf-8"),D=Math.max(U.length,J.length,1),I=Buffer.alloc(D),X=Buffer.alloc(D);return U.copy(I),J.copy(X),ds(I,X)&&U.length===J.length};var P$=$J();var xT=($)=>{let b=Buffer.byteLength($.content,"utf-8");if($.meta)for(let[U,J]of Object.entries($.meta))b+=Buffer.byteLength(U,"utf-8")+Buffer.byteLength(J,"utf-8");return b},os=1048576,ts=200,ps=4194304,as=()=>{};class uO{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??as,this.maxBufferedBytes=$.maxBufferedBytes??os,this.now=$.now??(()=>Date.now()),this.replayBufferSize=Math.max(0,$.replayBufferSize??ts),this.replayBufferMaxBytes=Math.max(0,$.replayBufferMaxBytes??ps),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($,b){let U=this.replayBuffer[0]?.offset,J=this.persistentReplay&&(U===void 0||$<U-1),D=this.replayBuffer.filter((w)=>w.offset>$&&this.matchesClient(w,b));if(!J)return D;let I=this.persistentReplay?this.persistentReplay.loadSince($).filter((w)=>this.matchesClient(w,b)):[],X=U??Number.POSITIVE_INFINITY;return[...I.filter((w)=>w.offset<X),...D]}matchesClient($,b){let U=$.meta?.target;if(U&&U!==b.subscriberId)return!1;let J=$.meta?.channelId;if(J&&J!==b.channel)return!1;let D=$.meta?.connector;if(!D)return!0;return b.connectors.includes(D)}pickRecipients($){let b=new Map,U=[];for(let[J,D]of this.clients){if(!this.matchesClient($,D))continue;if(D.delivery==="exclusive"){let I=b.get(D.channel)??[];I.push(J),b.set(D.channel,I);continue}U.push(J)}for(let[J,D]of b){if(D.length===0)continue;let I=this.exclusiveCursor.get(J)??0,X=D[I%D.length];if(X)U.push(X);this.exclusiveCursor.set(J,I+1)}return U}addClient($,b){this.clients.set($,b)}removeClient($){this.clients.delete($)}getClientCount(){return this.clients.size}listChannels(){return[...this.clients.values()].map(($)=>({...$}))}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}broadcast($,b){this.latestOffset+=1;let U={content:$,meta:b,offset:this.latestOffset},J=JSON.stringify(U);if(this.eventsBroadcast+=1,this.lastBroadcastAt=this.now(),this.replayBufferSize>0){let I=xT(U);this.replayBuffer.push(U),this.replayBufferBytes+=I;while((this.replayBuffer.length>this.replayBufferSize||this.replayBufferBytes>this.replayBufferMaxBytes)&&this.replayBuffer.length>0){let X=this.replayBuffer.shift();if(X)this.replayBufferBytes-=xT(X)}}let D=this.pickRecipients(U);for(let I of D){let X=I.getBufferedAmount();if(X>this.maxBufferedBytes){let H=this.clients.get(I);this.logger?.warn("dropping slow WS client (backpressure)",{channel:H?.channel,buffered:X,max:this.maxBufferedBytes});try{I.close(1009,"backpressure")}catch{}this.clients.delete(I),this.droppedSlowClients+=1;continue}try{I.send(J)}catch(H){let w=H instanceof Error?H:Error(String(H)),G=this.clients.get(I);this.logger?.warn("ws.send failed; dropping client",{channel:G?.channel,error:w.message}),this.clients.delete(I)}}for(let I of this.subscribers){let X=(H)=>{let w=H instanceof Error?H:Error(String(H));this.logger?.error("broadcast subscriber threw",{error:w.message}),this.onError(w,{component:"broadcaster.subscriber",offset:U.offset,connector:U.meta?.connector??null,channel:U.meta?.channel??null})};try{let H=I(U);if(H instanceof Promise)H.catch(X)}catch(H){X(H)}}return U}seedLatestOffset($){if($>this.latestOffset)this.latestOffset=$}}var DB$=Y.object({type:Y.string(),content:Y.string(),channel_id:Y.string().nullable(),connector_id:Y.string().nullable(),meta:Y.record(Y.string(),Y.string()).nullable()});class NO{}import{Database as ss}from"bun:sqlite";import{existsSync as es,mkdirSync as $e}from"fs";import{dirname as be}from"path";var Ue=/^[a-z_][a-z0-9_]*$/,De=500,Je=new Set(["seq","ts","type","event"]),lT=[["CREATE TABLE IF NOT EXISTS logs (seq INTEGER PRIMARY KEY, ts INTEGER NOT NULL, type TEXT, event TEXT NOT NULL)","CREATE INDEX IF NOT EXISTS idx_logs_ts ON logs (ts)","CREATE INDEX IF NOT EXISTS idx_logs_type ON logs (type)"],["DROP TABLE IF EXISTS leuco_log","CREATE TABLE IF NOT EXISTS logs (seq INTEGER PRIMARY KEY, ts INTEGER NOT NULL, type TEXT, event TEXT NOT NULL)","CREATE INDEX IF NOT EXISTS idx_logs_ts ON logs (ts)","CREATE INDEX IF NOT EXISTS idx_logs_type ON logs (type)"]];class u0{db;maxRows;maxAgeMs;maxBytes;targetBytes;now;indexes;extractIndexes;insertStmt;insertWithSeqStmt;maxSeqStmt;countStmt;trimRowsStmt;trimAgeStmt;trimOldestStmt;insertsSinceByteCheck=0;constructor($){if($.path!==":memory:"){let I=be($.path);if(!es(I))$e(I,{recursive:!0})}if(this.db=new ss($.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)Xe(this.indexes),this.extractIndexes=$.extractIndexes??null,this.syncIndexColumns();else this.extractIndexes=null;let b=["ts","type","event",...this.indexes],U=b.map(()=>"?").join(", ");this.insertStmt=this.db.prepare(`INSERT INTO logs (${b.join(", ")}) VALUES (${U})`);let J=["seq",...b],D=J.map(()=>"?").join(", ");this.insertWithSeqStmt=this.db.prepare(`INSERT INTO logs (${J.join(", ")}) VALUES (${D})`),this.maxSeqStmt=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max FROM logs"),this.countStmt=this.db.prepare("SELECT COUNT(*) AS n FROM logs"),this.trimRowsStmt=this.db.prepare("DELETE FROM logs WHERE seq <= (SELECT seq FROM logs ORDER BY seq DESC LIMIT 1 OFFSET ?)"),this.trimAgeStmt=this.db.prepare("DELETE FROM logs WHERE ts < ?"),this.trimOldestStmt=this.db.prepare("DELETE FROM logs WHERE seq IN (SELECT seq FROM logs ORDER BY seq ASC LIMIT ?)")}insert($){try{let b=this.buildInsertParams($.ts,$.event),U=this.insertStmt.run(...b),J=Number(U.lastInsertRowid);return this.trim(),{seq:J,ts:$.ts,event:$.event}}catch(b){return b instanceof Error?b:Error(String(b))}}insertMany($){if($.length===0)return[];try{let b=[];return this.db.transaction((J)=>{for(let D of J){let I=this.buildInsertParams(D.ts,D.event),X=this.insertStmt.run(...I);b.push({seq:Number(X.lastInsertRowid),ts:D.ts,event:D.event})}})($),this.trim(),b}catch(b){return b instanceof Error?b:Error(String(b))}}write($){try{let b=[$.seq,...this.buildInsertParams($.ts,$.event)];this.insertWithSeqStmt.run(...b),this.trim()}catch(b){return b instanceof Error?b:Error(String(b))}}getMaxSeq(){let $=this.maxSeqStmt.get();return $?$.max:0}query($={}){let b=[],U=[];if($.seq!==void 0)b.push("seq = ?"),U.push($.seq);else b.push("seq > ?"),U.push($.sinceSeq??0);if(typeof $.type==="string")b.push("type = ?"),U.push($.type);if($.where)this.appendWhereConditions($.where,b,U);if($.wherePrefix)this.appendPrefixConditions($.wherePrefix,b,U);if($.whereIn)this.appendSetConditions($.whereIn,b,U);let J=$.limit??1000;U.push(J);let D=$.order==="desc"?"DESC":"ASC",I=`SELECT seq, ts, type, event FROM logs WHERE ${b.join(" AND ")} ORDER BY seq ${D} LIMIT ?`,H=this.db.prepare(I).all(...U);if(D==="DESC")H.reverse();return H.map(we)}getSchemaVersion(){return this.db.prepare("PRAGMA user_version").get()?.user_version??0}close(){this.db.close()}buildInsertParams($,b){let U=He(b),J=JSON.stringify(b);if(this.indexes.length===0)return[$,U,J];let D=this.extractIndexes?this.extractIndexes(b):null,I=this.indexes.map((X)=>D?.[X]??null);return[$,U,J,...I]}appendWhereConditions($,b,U){for(let J of this.indexKeys()){let D=$[J];if(D===void 0)continue;if(D===null)b.push(`${J} IS NULL`);else b.push(`${J} = ?`),U.push(D)}}appendPrefixConditions($,b,U){for(let J of this.indexKeys()){let D=$[J];if(D===void 0)continue;b.push(`${J} LIKE ? ESCAPE '\\'`),U.push(`${Ie(D)}%`)}}appendSetConditions($,b,U){for(let J of this.indexKeys()){let D=$[J];if(D===void 0)continue;if(D.length===0){b.push("1 = 0");continue}let I=D.filter((w)=>w!==null),X=I.length!==D.length,H=[];if(I.length>0)H.push(`${J} IN (${I.map(()=>"?").join(", ")})`),U.push(...I);if(X)H.push(`${J} IS NULL`);b.push(`(${H.join(" OR ")})`)}}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()}indexKeys(){return this.indexes}maybeTrimBytes(){if(this.maxBytes===null||this.targetBytes===null)return;if(this.insertsSinceByteCheck+=1,this.insertsSinceByteCheck<De)return;this.insertsSinceByteCheck=0;let $=this.byteSize();if($<=this.maxBytes)return;let b=this.countStmt.get()?.n??0;if(b===0)return;let U=$-this.targetBytes,J=$/b,D=Math.min(b,Math.ceil(U/J));this.trimOldestStmt.run(D),this.db.run("VACUUM")}byteSize(){let $=this.db.prepare("PRAGMA page_count").get()?.n??0,b=this.db.prepare("PRAGMA page_size").get()?.n??0;return $*b}clear(){this.db.run("DELETE FROM logs"),this.db.run("VACUUM"),this.insertsSinceByteCheck=0}syncIndexColumns(){let $=new Set(this.db.prepare("PRAGMA table_info(logs)").all().map((b)=>b.name));for(let b of this.indexes){if(!$.has(b))this.db.run(`ALTER TABLE logs ADD COLUMN ${b} TEXT`);this.db.run(`CREATE INDEX IF NOT EXISTS idx_logs_${b} ON logs (${b})`)}}migrate(){let b=this.db.prepare("PRAGMA user_version").get()?.user_version??0;if(b>=lT.length)return;let U=lT.slice(b),J=b;for(let D of U)J+=1,this.db.transaction(()=>{for(let X of D)this.db.run(X);this.db.run(`PRAGMA user_version = ${J}`)})()}}function Ie($){return $.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function Xe($){for(let b of $){if(!Ue.test(b))throw Error(`invalid index column name: ${b}`);if(Je.has(b))throw Error(`reserved index column name: ${b}`)}}function He($){if(typeof $!=="object"||$===null)return null;if(!("type"in $))return null;let b=$.type;return typeof b==="string"?b:null}function we($){return{seq:$.seq,ts:$.ts,event:JSON.parse($.event)}}var nT=2000;class fO extends NO{sink;now;logger;onError;constructor($){super();this.now=$.now??(()=>Date.now()),this.logger=$.logger,this.onError=$.onError,this.sink=new u0({path:$.path,indexes:["channel_id","connector_id"],extractIndexes:(b)=>({channel_id:b.channel_id,connector_id:b.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 b={type:$.meta?.event_type??"unknown",content:Ge($.content),channel_id:$.channelId,connector_id:$.connectorId,meta:$.meta},U=this.sink.write({seq:$.offset,ts:this.now(),event:b});if(U instanceof Error)this.logger?.error("event log write failed",{offset:$.offset,error:U.message}),this.onError?.(U,{component:"sqlite-event-log",op:"record",offset:$.offset,channelId:$.channelId,connectorId:$.connectorId})}loadSince($){let b=this.sink.query({sinceSeq:$,limit:Number.MAX_SAFE_INTEGER}),U=[];for(let J of b)U.push({content:J.event.content,meta:J.event.meta??void 0,offset:J.seq});return U}loadForChannel($){let b={channel_id:$.channelId};if($.connectorId!==void 0)b.connector_id=$.connectorId;let U=this.sink.query({where:b,...$.sinceSeq!==void 0?{sinceSeq:$.sinceSeq}:{},...$.limit!==void 0?{limit:$.limit}:{}}),J=[];for(let D of U)J.push({content:D.event.content,meta:D.event.meta??void 0,offset:D.seq});return J}findMaxOffset(){return this.sink.getMaxSeq()}clear(){this.sink.clear()}close(){this.sink.close()}}function Ge($){if($.length<=nT)return $;return`${$.slice(0,nT)}...`}var We=()=>{},Qe=30000,Ye=60000,Oe=30000,Ve=($)=>new Promise((b)=>{setTimeout(b,$)});class v6{channels;notify;logger;onError;running=new Map;failureCounts=new Map;starting=new Set;stats=new Map;healthCheckIntervalMs;maxBackoffMs;startTimeoutMs;sleep;now;healthCheckTimer=null;healthCheckInFlight=!1;pendingRetry=new Map;constructor($){this.channels=$.channels,this.notify=$.notify,this.logger=$.logger,this.onError=$.onError??We,this.healthCheckIntervalMs=$.healthCheckIntervalMs??Qe,this.maxBackoffMs=$.maxBackoffMs??Ye,this.startTimeoutMs=$.startTimeoutMs??Oe,this.sleep=$.sleep??Ve,this.now=$.now??(()=>Date.now())}static keyOf($,b){return`${$}/${b}`}isRunning($,b){return this.running.has(v6.keyOf($,b))}list(){return[...this.running.entries()].map(([$,b])=>{let U=this.stats.get($);return{channelName:b.channelName,channelId:b.channelId,name:b.config.name,type:b.config.type,alive:b.listener.isAlive(),events:U?.events??0,errors:U?.errors??0,failureCount:this.failureCounts.get($)??0,lastEventAt:U?.lastEventAt??null}})}async start($,b){let U=v6.keyOf($,b);if(this.running.has(U))return{ok:!0,reason:"already running"};if(this.starting.has(U))return{ok:!1,reason:"already starting",retriable:!0};this.starting.add(U);try{return await this.startLocked($,b,U)}finally{this.starting.delete(U)}}async startLocked($,b,U){let J=this.channels.createListener($,b);if(!J)return{ok:!1,reason:`connector "${b}" not found in channel "${$}"`};let D=async(I,X)=>{try{await this.notify($,b,I,X),this.recordEvent(U)}catch(H){throw this.recordError(U),H}};try{return await Promise.race([J.listener.start(D),this.sleep(this.startTimeoutMs).then(()=>{throw Error(`listener start timed out after ${this.startTimeoutMs}ms`)})]),this.running.set(U,{config:J.config,channelName:$,channelId:J.channelId,listener:J.listener}),this.pendingRetry.delete(U),this.ensureStats(U),this.logger?.info(`${J.config.type} listener started`,{channel:$,connector:b}),{ok:!0}}catch(I){let X=I instanceof Error?I:Error(String(I));try{await J.listener.stop()}catch{}this.logger?.error(`${J.config.type} listener failed to start`,{channel:$,connector:b,error:X.message}),this.onError(X,{component:"listener-registry.start",channel:$,connector:b,type:J.config.type});let H=!(X instanceof o1);return{ok:!1,reason:X.message,retriable:H}}}async stop($,b){let U=v6.keyOf($,b),J=this.running.get(U);if(!J)return{ok:!0,reason:"not running"};try{return await J.listener.stop(),this.logger?.info(`${J.config.type} listener stopped`,{channel:$,connector:b}),{ok:!0}}catch(D){let I=D instanceof Error?D:Error(String(D));return this.logger?.error(`${J.config.type} listener failed to stop`,{channel:$,connector:b,error:I.message}),this.onError(I,{component:"listener-registry.stop",channel:$,connector:b,type:J.config.type}),{ok:!1,reason:I.message}}finally{this.running.delete(U),this.failureCounts.delete(U)}}async restart($,b){let U=await this.stop($,b);if(!U.ok)return U;return await this.start($,b)}async startAll(){let $=this.channels.listAllConnectors(),b=await Promise.allSettled($.map((U)=>this.start(U.channelName,U.name)));for(let U=0;U<b.length;U++){let J=b[U],D=$[U];if(J.status==="rejected"){let I=v6.keyOf(D.channelName,D.name);this.pendingRetry.set(I,{channelName:D.channelName,connectorName:D.name});continue}if(J.status==="fulfilled"&&!J.value.ok){if(J.value.retriable===!1)continue;let I=v6.keyOf(D.channelName,D.name);this.pendingRetry.set(I,{channelName:D.channelName,connectorName:D.name})}}this.startHealthCheck()}async stopAll(){this.stopHealthCheck(),this.pendingRetry.clear();for(let[,$]of this.running.entries())await this.stop($.channelName,$.config.name)}ensureStats($){let b=this.stats.get($);if(b)return b;let U={events:0,errors:0,failureCount:0,lastEventAt:null};return this.stats.set($,U),U}recordEvent($){let b=this.ensureStats($);b.events+=1,b.lastEventAt=new Date(this.now()).toISOString()}recordError($){this.ensureStats($).errors+=1}startHealthCheck(){if(this.healthCheckTimer)return;this.healthCheckTimer=setInterval(()=>{this.runHealthCheck().catch(($)=>{let b=$ instanceof Error?$:Error(String($));this.logger?.error("health check pass failed",{error:b.message}),this.onError(b,{component:"listener-registry.health-check"})})},this.healthCheckIntervalMs),this.healthCheckTimer.unref()}stopHealthCheck(){if(!this.healthCheckTimer)return;clearInterval(this.healthCheckTimer),this.healthCheckTimer=null}async runHealthCheckForTest(){await this.runHealthCheck()}async runHealthCheck(){if(this.healthCheckInFlight)return;this.healthCheckInFlight=!0;try{let $=[];for(let[U,J]of this.running.entries()){if(J.listener.isAlive()){this.failureCounts.delete(U);continue}$.push({channelName:J.channelName,connectorName:J.config.name,type:J.config.type})}await Promise.all($.map((U)=>this.recoverDead(U.channelName,U.connectorName,U.type)));let b=[];for(let[U,J]of this.pendingRetry.entries()){if(this.running.has(U)){this.pendingRetry.delete(U);continue}b.push({key:U,channelName:J.channelName,connectorName:J.connectorName})}await Promise.all(b.map((U)=>this.attemptRetry(U)))}finally{this.healthCheckInFlight=!1}}async attemptRetry($){this.logger?.info("retrying failed listener",{channel:$.channelName,connector:$.connectorName});let b=this.failureCounts.get($.key)??0,U=Math.min(1000*2**b,this.maxBackoffMs);await this.sleep(U);let J=await this.start($.channelName,$.connectorName);if(J.ok){this.pendingRetry.delete($.key),this.failureCounts.delete($.key);return}if(J.retriable===!1){this.pendingRetry.delete($.key),this.failureCounts.delete($.key),this.logger?.warn("dropping listener from retry queue (non-retriable)",{channel:$.channelName,connector:$.connectorName,reason:J.reason});return}this.failureCounts.set($.key,b+1)}async recoverDead($,b,U){let J=v6.keyOf($,b),D=this.failureCounts.get(J)??0,I=Math.min(1000*2**D,this.maxBackoffMs);this.logger?.warn(`${U} listener unhealthy, restarting`,{channel:$,connector:b,attempt:D+1,backoffMs:I}),await this.stop($,b),await this.sleep(I);let X=await this.start($,b);if(X.ok)this.failureCounts.delete(J),this.logger?.info(`${U} listener recovered`,{channel:$,connector:b});else if(X.retriable===!1)this.failureCounts.delete(J),this.logger?.warn(`${U} listener cannot recover (non-retriable)`,{channel:$,connector:b,reason:X.reason});else this.failureCounts.set(J,D+1)}}var ve=new N$,Ze=3000,Be=100,ze=200,Ke=($)=>new Promise((b)=>{setTimeout(b,$)}),je=($)=>`funnel-gateway[${$}]`,Le=async($)=>{let b=$.now()+Ze;while($.now()<b){if($.pids.every((U)=>!$.runner.isAlive(U)))return;await $.sleep(Be)}for(let U of $.pids){if(!$.runner.isAlive(U))continue;try{$.runner.kill(U,"SIGKILL")}catch{}}await $.sleep(ze)},iT=async($)=>{let b=$.process??ve,U=$.logger,J=je($.dir),D=b.listProcessesContaining(J),I=[];for(let X of D){if(X.pid===$.selfPid)continue;b.kill(X.pid,"SIGTERM"),I.push(X.pid),U?.info("killed competing Slack gateway process",{pid:X.pid,args:X.command.slice(0,160)})}if(I.length===0)return I;return await Le({runner:b,pids:I,sleep:$.sleep??Ke,now:$.now??(()=>Date.now())}),I};var c4=($)=>Gb("param",$,(b,U)=>{if(b.success)return;let J=b.error.issues[0],D=J?`${J.path.join(".")}: ${J.message}`:"invalid request";return U.json({ok:!1,reason:D},400)});var SO=Y.lazy(()=>Y.union([Y.string(),Y.number(),Y.boolean(),Y.null(),Y.array(SO),Y.record(Y.string(),SO)])),Ae=Y.object({method:Y.string().min(1),path:Y.string().min(1),body:SO.optional()}),yT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=null;try{U=await $.req.json()}catch{U=null}let J=Ae.safeParse(U);if(!J.success)throw new h(400,{message:J.error.issues[0]?.message??"invalid body"});let D=await $.var.deps.channels.call(b.channel,b.connector,{method:J.data.method,path:J.data.path,body:J.data.body});return $.json({ok:!0,result:D})});var hT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1)})),Gb("json",_T,($,b)=>{if($.success)return;let U=$.error.issues[0],J=U?`${U.path.join(".")}: ${U.message}`:"invalid body";return b.json({ok:!1,reason:J},400)}),($)=>{let b=$.req.valid("param"),U=$.req.valid("json"),J=U.target?{...U.meta,target:U.target}:U.meta,I={ok:!0,offset:$.var.deps.emit({channel:b.channel,connector:U.connector,content:U.content,meta:J}).offset};return $.json(I)});var qe=($)=>{let U=($.connectionErrors[$.connectionErrors.length-1]??null)?.detail??null;if($.connectors.length>0&&!$.listener)return{status:"error",message:"no listener running for this channel",nextActions:["fnl gateway restart"],rootCause:U};if($.listener&&!$.listener.alive)return{status:"error",message:"listener is dead",nextActions:["fnl gateway logs","fnl gateway restart"],rootCause:U};if($.claudeClients===0)return{status:"warn",message:"no Claude connected to this channel",nextActions:[`fnl claude --channel ${$.name}`],rootCause:null};if($.listener&&$.listener.errors>0)return{status:"warn",message:"listener has errors",nextActions:["fnl gateway logs"],rootCause:U};return{status:"ok",message:"healthy",nextActions:[],rootCause:null}},mT=P$.createHandlers(async($)=>{let b=$.var.deps,U=$.req.query("channel")??null,J=b.channels.list(),D=U?J.filter((G)=>G.name===U||G.id===U):J,I=b.registry.list(),X=b.broadcaster.listChannels(),H=b.broadcaster.getMetrics(),w=D.map((G)=>{let W=I.find((K)=>K.channelName===G.name)??null,Q=W?{alive:W.alive,events:W.events,errors:W.errors,lastEventAt:W.lastEventAt}:null,O=X.filter((K)=>K.channel===G.id||K.channel===G.name).length,V=(()=>{if(!b.diagnosticLog)return[];try{return b.diagnosticLog.queryProcessed({channelId:G.id,limit:10}).map(rb)}catch{return[]}})(),Z=Q&&(!Q.alive||Q.errors>0)||!Q,v=(()=>{if(!Z||!b.diagnosticLog)return[];try{return b.diagnosticLog.queryConnection({channelId:G.id,statuses:["auth-failed","error"],limit:3}).map(M0)}catch{return[]}})(),B={id:G.id,name:G.name,connectors:G.connectors.map((K)=>K.name),listener:Q,claudeClients:O,recentEvents:V,connectionErrors:v};return{...B,diagnosis:qe(B)}});return $.json({pid:b.selfPid,uptimeMs:b.uptimeMs(),eventsBroadcast:H.eventsBroadcast,channels:w})});var rT=P$.createHandlers(($)=>{let b=$.var.deps;return $.json({ok:!0,pid:b.selfPid,funnelDir:b.dir,clients:b.broadcaster.getClientCount(),listeners:b.registry.list()})});var cT=P$.createHandlers(($)=>{return $.json({listeners:$.var.deps.registry.list()})});var dT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=await $.var.deps.registry.restart(b.channel,b.connector);return $.json(U,U.ok?200:400)});var oT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=await $.var.deps.registry.start(b.channel,b.connector);return $.json(U,U.ok?200:400)});var tT=P$.createHandlers(c4(Y.object({channel:Y.string().min(1),connector:Y.string().min(1)})),async($)=>{let b=$.req.valid("param"),U=await $.var.deps.registry.stop(b.channel,b.connector);return $.json(U,U.ok?200:400)});var pT=P$.createHandlers(($)=>{let b=$.var.deps;return $.json({ok:!0,pid:b.selfPid,funnelDir:b.dir,uptimeMs:b.uptimeMs(),clients:b.broadcaster.listChannels(),listeners:b.registry.list(),broadcaster:b.broadcaster.getMetrics()})});function Pe(){return P$.createApp().onError(($,b)=>{if($ instanceof h)return $.getResponse();let U=$ instanceof Error?$.message:String($);return b.json({error:U},500)}).get("/health",...rT).get("/status",...pT).get("/debug",...mT).get("/listeners",...cT).post("/listeners/:channel/:connector/start",...oT).delete("/listeners/:channel/:connector",...tT).post("/listeners/:channel/:connector/restart",...dT).post("/channels/:channel/connectors/:connector/call",...yT).post("/channels/:channel/publish",...hT)}var aT=Pe();import{createHash as Te,randomUUID as Fe}from"crypto";import{join as Me}from"path";function sT($){let b=$.port===0?Fe():String($.port),U=Te("sha256").update(`${$.funnelDir}\x00${b}`).digest("hex").slice(0,20);return Me($.tmpDir,"events",`${U}.db`)}var Se="127.0.0.1",ge=new Set(["127.0.0.1","localhost","::1","::ffff:127.0.0.1"]),Re=()=>{};class gO{channels;configuredPort;configuredHostname;dbPath;process;logger;onError;selfPid;dir;killCompetingSlack;token;allowInsecureHost;broadcaster;eventLog;registry;nowMs;extraRoutes;ownsEventLog;diagnosticLog;startedAt=null;server=null;disposed=!1;constructor($){this.channels=$.channels,this.configuredPort=$.port??Y6(),this.configuredHostname=$.hostname??Se,this.dir=$.dir??R4,this.dbPath=$.dbPath??sT({tmpDir:$.tmpDir??c$(),funnelDir:this.dir,port:this.configuredPort}),this.process=$.process,this.logger=$.logger,this.onError=$.onError??Re,this.selfPid=$.selfPid??globalThis.process.pid,this.killCompetingSlack=$.killCompetingSlack??!0,this.token=$.token??"",this.allowInsecureHost=$.allowInsecureHost??!1,this.extraRoutes=$.extraRoutes??null,this.diagnosticLog=$.diagnosticLog;let b=$.clock;if(this.nowMs=b?()=>b.millis():()=>Date.now(),$.eventLog)this.eventLog=$.eventLog,this.ownsEventLog=!1;else{let U=fe(this.dbPath);if(!ue(U))Ne(U,{recursive:!0});this.eventLog=new fO({path:this.dbPath,now:this.nowMs,logger:this.logger,onError:this.onError}),this.ownsEventLog=!0}this.broadcaster=new uO({logger:this.logger,onError:this.onError,now:this.nowMs,persistentReplay:this.eventLog}),this.broadcaster.seedLatestOffset(this.eventLog.findMaxOffset()),this.registry=new v6({channels:this.channels,logger:this.logger,onError:this.onError,notify:async(U,J,D,I)=>{this.emit({channel:U,connector:J,content:D,meta:I})},now:this.nowMs})}get port(){return this.server?.port??this.configuredPort}get hostname(){return this.server?.hostname??this.configuredHostname}async start(){if(this.disposed)throw Error("FunnelGatewayServer is single-use: construct a new instance to start again");if(this.server)return;if(!this.token&&!ge.has(this.configuredHostname)&&!this.allowInsecureHost)throw Error(`refusing to start gateway: hostname "${this.configuredHostname}" is reachable off-box but no token is set. Set a token, bind to loopback (127.0.0.1), or pass allowInsecureHost: true.`);let $=this.buildApp();await this.killCompetingSlackIfNeeded(),this.startedAt=this.nowMs(),this.server=Bun.serve({port:this.configuredPort,hostname:this.configuredHostname,development:!1,fetch:(b,U)=>this.handleFetch(b,U,$),websocket:{open:(b)=>this.handleWsOpen(b),close:(b)=>this.handleWsClose(b),message(){}}}),this.logServerStarted();try{await this.bootListeners()}catch(b){throw this.server.stop(),this.server=null,b}}async stop(){if(await this.registry.stopAll(),this.server)this.server.stop(),this.server=null;if(this.ownsEventLog)this.eventLog.close();this.disposed=!0}getStatus(){return{clients:this.broadcaster.getClientCount(),channels:this.broadcaster.listChannels()}}getBroadcaster(){return this.broadcaster}getRegistry(){return this.registry}getEventLog(){return this.eventLog}onEvent($){return this.broadcaster.subscribe($)}handleFetch($,b,U){let J=new URL($.url);if(J.pathname==="/ws"&&$.headers.get("upgrade")==="websocket"){if(this.token&&!this.tokenMatchesUpgrade($))return new Response("unauthorized",{status:401});let D=J.searchParams.get("channel")??"",I=D?this.resolveChannel(D):null;if(D&&!I)return new Response(`unknown channel "${D}"`,{status:404});let X=I?.id??D,H=I?.name??null,w=I?.connectors??[],G=I?.delivery??"fanout",W=J.searchParams.get("since"),Q=W===null?Number.NaN:Number.parseInt(W,10),O=Number.isFinite(Q)&&Q>=0?Q:void 0,V=J.searchParams.get("id")??void 0;if(b.upgrade($,{data:{channel:X,channelName:H,connectors:w,delivery:G,subscriberId:V,since:O}}))return;return new Response("WebSocket upgrade failed",{status:400})}return U.fetch($)}handleWsOpen($){if(typeof $.data.since==="number"){let b=this.broadcaster.replaySince($.data.since,$.data);try{for(let U of b)$.send(JSON.stringify(U))}catch(U){let J=U instanceof Error?U:Error(String(U));this.logger?.warn("replay send failed during ws.open",{error:J.message}),this.onError(J,{component:"gateway-server.replay"});return}}this.broadcaster.addClient($,$.data),this.logger?.info("channel connected",{event_type:"system",action:"channel_connect",channel:$.data.channelName??"",channelId:$.data.channel,connectors:$.data.connectors.join(","),total:String(this.broadcaster.getClientCount())})}handleWsClose($){this.broadcaster.removeClient($),this.logger?.info("channel disconnected",{event_type:"system",action:"channel_disconnect",channel:$.data.channelName??"",channelId:$.data.channel,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 $=P$.createApp();if($.use((U,J)=>{return U.set("deps",{selfPid:this.selfPid,dir:this.dir,broadcaster:this.broadcaster,registry:this.registry,channels:this.channels,uptimeMs:()=>this.startedAt?this.nowMs()-this.startedAt:0,emit:(D)=>this.emit(D),diagnosticLog:this.diagnosticLog}),J()}),this.token)$.use("/listeners/*",VD({expected:this.token})),$.use("/status",VD({expected:this.token})),$.use("/debug",VD({expected:this.token})),$.use("/channels/*",VD({expected:this.token}));return(this.extraRoutes?$.route("/",this.extraRoutes):$).route("/",aT)}tokenMatchesUpgrade($){let b=($.headers.get("sec-websocket-protocol")??"").split(",").map((D)=>D.trim()).filter((D)=>D.length>0);for(let D of b)if(D.startsWith("funnel.token.")&&YX(D.slice(13),this.token))return!0;let J=($.headers.get("authorization")??"").match(/^Bearer\s+(.+)$/i);if(J&&YX(J[1]??"",this.token))return!0;return!1}resolveChannel($){let b=this.channels.get($)??this.channels.getById($);if(!b)return null;return{id:b.id,name:b.name,connectors:b.connectors.map((U)=>U.name),delivery:b.delivery}}async killCompetingSlackIfNeeded(){if(!this.killCompetingSlack)return;if(!this.channels.listAllConnectors().some((U)=>U.type==="slack"))return;let b=await iT({selfPid:this.selfPid,dir:this.dir,process:this.process,logger:this.logger});if(b.length>0)this.logger?.info("killed competing Slack gateway processes",{event_type:"system",action:"kill_competing",pids:b.join(",")})}async bootListeners(){await this.registry.startAll();for(let $ of this.registry.list())this.logger?.info(`${$.type} listener started: ${$.name}`,{event_type:"system",action:`${$.type}_connect`,channel:$.channelName,connector:$.name});this.logger?.info(`event store: ${this.dbPath}`),this.logger?.info("funnel gateway running")}emit($){let b=this.lookupChannelId($.channel),U=b&&$.connector?this.lookupConnectorId(b,$.connector):null,J={...$.meta,channel:$.channel};if($.connector)J.connector=$.connector;if(b)J.channelId=b;if(U)J.connectorId=U;let D=this.broadcaster.broadcast($.content,J);return this.eventLog.record({content:$.content,channelId:b??null,connectorId:U??null,meta:J,offset:D.offset}),{offset:D.offset}}lookupChannelId($){return this.channels.get($)?.id??this.channels.getById($)?.id??null}lookupConnectorId($,b){return this.channels.getById($)?.connectors.find((J)=>J.name===b)?.id??null}}import{homedir as _e}from"os";import{dirname as ke,join as eT}from"path";var $F="gateway.token",Ee=32,Ce=new F$,xe=()=>{let $=new Uint8Array(Ee);return crypto.getRandomValues($),[...$].map((b)=>b.toString(16).padStart(2,"0")).join("")};class RO{fs;path;generate;constructor($={}){this.fs=$.fs??Ce,this.path=eT($.dir??R4,$F),this.generate=$.generate??xe,Object.freeze(this)}read(){if(!this.fs.existsSync(this.path))return null;let $=this.fs.readFileSync(this.path).trim();return $.length>0?$:null}ensure(){return this.fs.mkdirSync(ke(this.path),{recursive:!0}),this.fs.withFileLock(`${this.path}.lock`,()=>{let $=this.read();if($)return $;let b=this.generate();return this.fs.writeSecretFileSync(this.path,`${b}
|
|
1597
1597
|
`),b})}getPath(){return this.path}}var uz$=eT(_e(),".funnel",$F);var le=Y.object({channelName:Y.string(),channelId:Y.string(),name:Y.string(),type:Y.string(),alive:Y.boolean()}),ne=Y.object({listeners:Y.array(le)}),ie=Y.object({reason:Y.string().optional()}),_O={state:"offline"};class kO{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 r$(`${i$(this.port)}/listeners`,{headers:this.authHeaders()});if(!$.ok)return{state:"error",reason:`HTTP ${$.status}`};let b=ne.safeParse(await $.json());if(!b.success)return{state:"error",reason:"malformed daemon response"};return{state:"ok",listeners:b.data.listeners}}catch($){return{state:"error",reason:$ instanceof Error?$.message:String($)}}}async start($,b){if(!this.isDaemonRunning())return _O;return await this.call("POST",`/listeners/${this.path($,b)}/start`)}async stop($,b){if(!this.isDaemonRunning())return _O;return await this.call("DELETE",`/listeners/${this.path($,b)}`)}async restart($,b){if(!this.isDaemonRunning())return _O;return await this.call("POST",`/listeners/${this.path($,b)}/restart`)}path($,b){return`${encodeURIComponent($)}/${encodeURIComponent(b)}`}authHeaders(){let $=this.getToken();return $?{authorization:`Bearer ${$}`}:{}}async call($,b){try{let U=await r$(`${i$(this.port)}${b}`,{method:$,headers:this.authHeaders()},30000);if(!U.ok){let J=null;try{J=await U.json()}catch{J=null}let D=ie.safeParse(J);return{state:"error",reason:(D.success?D.data.reason:void 0)??`HTTP ${U.status}`}}return{state:"ok"}}catch(U){return{state:"error",reason:U instanceof Error?U.message:String(U)}}}}var he="/sandbox/.funnel",me="/sandbox/tmp",re=()=>{};class OX{paths;channels;gateway;gatewayToken;publisher;listeners;claude;profiles;localConfig;localConfigSync;diagnostics;recovery;doctor;docs;fs;process;logger;clock;http;onError;diagnosticLog;constructor($={}){let b=$.dir??eq(),U=$.tmpDir??c$(),J=$.fs??new F$,D=$.process??new N$,I=$.clock??new V6,X=$.idGenerator??new g4,H=$.http??new A4;this.paths={dir:b,tmpDir:U,settings:ye(b,"settings.json")},this.fs=J,this.process=D,this.logger=$.logger,this.clock=I,this.http=H,this.onError=$.onError??re,this.diagnosticLog=$.diagnosticLog;let w=$.store??new lY({path:this.paths.settings,fs:J,idGenerator:X}),G=new bO({descriptors:$.connectors??[],fs:J,process:D,http:H,clock:I,logger:this.logger,diagnosticLog:this.diagnosticLog,signal:$.signal,dir:b});this.profiles=new QO({store:w,idGenerator:X,fs:J}),this.channels=new UO({store:w,registry:G,clock:I,idGenerator:X,profileChecker:this.profiles}),this.gateway=new MO({fs:J,process:D,clock:I,dir:b,tmpDir:U,port:$.port}),this.gatewayToken=new RO({fs:J,dir:b}),this.publisher=new TO({port:this.gateway.getPort(),isDaemonRunning:()=>this.gateway.isRunning(),getToken:()=>this.gatewayToken.read()}),this.listeners=new kO({port:this.gateway.getPort(),isDaemonRunning:()=>this.gateway.isRunning(),getToken:()=>this.gatewayToken.read()});let W=new EY({fs:J});this.localConfig=new GD({fs:J}),this.localConfigSync=new WO({channels:this.channels,prompter:$.tokenPrompter??new OO});let Q=new IO({global:this.profiles,local:new JO({fs:J,dir:b})});this.claude=new DO({channels:this.channels,mcp:W,gateway:this.gateway,sessions:Q,guard:new wX({fs:J,process:D,dir:b}),process:D,logger:this.logger,dir:b}),this.diagnostics=new HO({gateway:this.gateway,gatewayToken:this.gatewayToken,channels:this.channels,publisher:this.publisher,diagnosticLog:this.diagnosticLog,tmpDir:U}),this.recovery=new YO({gateway:this.gateway,listeners:this.listeners,channels:this.channels}),this.doctor=new wO({diagnostics:this.diagnostics,recovery:this.recovery}),this.docs=new $D,Object.freeze(this)}static inMemory($={}){return new OX({...$,store:$.store??new zO,fs:$.fs??new VO,process:$.process??new BO,logger:$.logger??new ZO,clock:$.clock??new KO,idGenerator:$.idGenerator??new vO,http:$.http??new jO,tokenPrompter:$.tokenPrompter??new LO,diagnosticLog:$.diagnosticLog??new PO,dir:$.dir??he,tmpDir:$.tmpDir??me})}gatewayServer($={}){return new gO({channels:this.channels,port:$.port,hostname:$.hostname,...$.eventLog?{eventLog:$.eventLog}:{dbPath:$.dbPath},process:this.process,clock:this.clock,logger:this.logger,onError:this.onError,dir:this.paths.dir,tmpDir:this.paths.tmpDir,killCompetingSlack:$.killCompetingSlack,token:$.token??this.gatewayToken.ensure(),allowInsecureHost:$.allowInsecureHost,extraRoutes:$.extraRoutes,diagnosticLog:this.diagnosticLog})}createProcessGuard(){return new wX({fs:this.fs,process:this.process,dir:this.paths.dir})}async runGatewayForeground($={}){let b=QX(),J=$.caffeinate!==!1&&globalThis.process.platform==="darwin"?["caffeinate","-is","bun",b]:["bun",b];return this.process.attach(J,{env:{FUNNEL_DIR:this.paths.dir,FUNNEL_PORT:String(this.gateway.getPort()),FUNNEL_TMP_DIR:this.paths.tmpDir}})}gatewayClient(){let{port:$}=this.gateway.getStatus();return $O(i$($))}}import{chmodSync as ce}from"fs";var de=262144;class xO extends OD{raw;processed;connection;now;logger;constructor($){super();this.now=$.now??(()=>Date.now()),this.logger=$.logger;let b=$.maxAgeMs!==void 0?{maxAgeMs:$.maxAgeMs}:{},U={now:this.now,...b,...$.maxRows!==void 0?{maxRows:$.maxRows}:{}},J=$.rawMaxRows??$.maxRows,D={now:this.now,...b,...J!==void 0?{maxRows:J}:{}};this.raw=new u0({path:$.rawPath,indexes:["event_id","connector_id","channel_id"],extractIndexes:(I)=>({event_id:I.event_id,connector_id:I.connector_id,channel_id:I.channel_id}),...D}),this.processed=new u0({path:$.processedPath,indexes:["event_id","connector_id","channel_id","outcome"],extractIndexes:(I)=>({event_id:I.event_id,connector_id:I.connector_id,channel_id:I.channel_id,outcome:I.outcome}),...U}),this.connection=new u0({path:$.connectionPath,indexes:["connector_id","channel_id","status"],extractIndexes:(I)=>({connector_id:I.connector_id,channel_id:I.channel_id,status:I.status}),...U}),EO($.rawPath),EO($.processedPath),EO($.connectionPath),Object.freeze(this)}recordRaw($){let b={event_id:$.eventId,type:$.type,connector_id:$.connectorId,channel_id:$.channelId,payload:pe($.payload,$.type)};this.report("raw",this.raw.insert({ts:this.now(),event:b}))}recordProcessed($){let b={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:b}))}recordConnection($){let b={type:$.type,connector_id:$.connectorId,channel_id:$.channelId,status:$.status,detail:$.detail};this.report("connection",this.connection.insert({ts:this.now(),event:b}))}report($,b){if(b instanceof Error)this.logger?.error("diagnostic log insert failed",{table:$,error:b.message})}queryRaw($){let b=CO($);if($.eventId!==void 0)b.event_id=$.eventId;return this.raw.query({...$.type!==void 0?{type:$.type}:{},...$.seq!==void 0?{seq:$.seq}:{},...$.limit!==void 0?{limit:$.limit}:{},where:b,order:"desc"}).map((J)=>({seq:J.seq,ts:J.ts,eventId:J.event.event_id,type:J.event.type,connectorId:J.event.connector_id,channelId:J.event.channel_id,payload:J.event.payload}))}queryProcessed($){let b=CO($);if($.eventId!==void 0)b.event_id=$.eventId;if($.outcome!==void 0)b.outcome=$.outcome;return this.processed.query({...$.type!==void 0?{type:$.type}:{},...$.seq!==void 0?{seq:$.seq}:{},...$.limit!==void 0?{limit:$.limit}:{},where:b,...$.outcomePrefix!==void 0?{wherePrefix:{outcome:$.outcomePrefix}}:{},order:"desc"}).map((J)=>({seq:J.seq,ts:J.ts,eventId:J.event.event_id,type:J.event.type,connectorId:J.event.connector_id,channelId:J.event.channel_id,outcome:J.event.outcome,payload:J.event.payload}))}queryConnection($){let b=CO($);if($.status!==void 0)b.status=$.status;return this.connection.query({...$.type!==void 0?{type:$.type}:{},...$.seq!==void 0?{seq:$.seq}:{},...$.limit!==void 0?{limit:$.limit}:{},where:b,...$.statuses!==void 0?{whereIn:{status:$.statuses}}:{},order:"desc"}).map((J)=>({seq:J.seq,ts:J.ts,type:J.event.type,connectorId:J.event.connector_id,channelId:J.event.channel_id,status:te(J.event.status),detail:J.event.detail}))}clear(){this.raw.clear(),this.processed.clear(),this.connection.clear()}close(){this.raw.close(),this.processed.close(),this.connection.close()}}var EO=($)=>{if($===":memory:")return;for(let b of["","-wal","-shm"])try{ce(`${$}${b}`,384)}catch{}},CO=($)=>{let b={};if($.connectorId!==void 0)b.connector_id=$.connectorId;if($.channelId!==void 0)b.channel_id=$.channelId;return b},oe=RT.shape.status,te=($)=>{let b=oe.safeParse($);return b.success?b.data:"error"},pe=($,b)=>{let U=Buffer.byteLength($,"utf8");if(U<=de)return $;return JSON.stringify({...se($),_funnel_oversized:U,_funnel_type:b})},ae=["type","subtype","ts","channel","channel_type","user","bot_id"],se=($)=>{try{let b=JSON.parse($);if(typeof b!=="object"||b===null)return{};let U=b,J={};for(let D of ae)if(U[D]!==void 0)J[D]=U[D];return J}catch{return{}}};var $$$=9743;if(!process.env.FUNNEL_PORT)process.env.FUNNEL_PORT=String($$$);var bF=new F$,UF=uv({localConfig:new GD({fs:bF}),writer:new aY({fs:bF}),idGenerator:new g4,home:ee()},process.cwd());if(UF)process.env.FUNNEL_DIR=UF;var b$$=c$(),U$$=new xO({...DX(b$$)}),VX=new OX({logger:new wD,connectors:QJ(),diagnosticLog:U$$}),{claude:JF,profiles:IF,localConfig:XF,localConfigSync:HF}=VX,DF={funnel:VX,claude:JF,profiles:IF,localConfig:XF,localConfigSync:HF},lO=`funnel / Open Claude Funnel
|
|
1598
1598
|
|
|
1599
1599
|
usage / funnel [command]
|