@callbag-recharge/callbag-recharge 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
- "use strict";var Ae=Object.create;var G=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Ie=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},de=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $e(t))!We.call(e,o)&&o!==n&&G(e,o,{get:()=>t[o],enumerable:!(r=Me(t,o))||r.enumerable});return e};var je=(e,t,n)=>(n=e!=null?Ae(Ie(e)):{},de(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),Fe=e=>de(G({},"__esModule",{value:!0}),e);var Ze={};Ne(Ze,{fromHTTP:()=>xe,fromLLM:()=>De,fromMCP:()=>Re,fromWebSocket:()=>Oe,fromWebhook:()=>Ce,toSSE:()=>Pe,toWebSocket:()=>Le});module.exports=Fe(Ze);var W=Symbol("DIRTY"),ee=Symbol("RESOLVED"),pe=Symbol("SINGLE_DEP"),ge=0,me=1,he=2,Se=3,Te=4,ye=5,N=7,ie=7<<N,He=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function be(e){return He[(e&ie)>>>N]}var C=0,A=1,D=2,M=3,J=0,Q=[],se=!1;function P(e){J++;try{return e()}finally{if(J--,J===0&&!se){se=!0;for(let t=0;t<Q.length;t++)Q[t]();Q.length=0,se=!1}}}function te(){return J>0}function ne(e){Q.push(e)}var X=0,Z=[];function _e(){X++}function ke(){if(X--,X===0){for(let e=0;e<Z.length;e++)Z[e]();Z.length=0}}function ve(e){X>0?Z.push(e):e()}var R=class e{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(e._explicitEnabled!==null)return e._explicitEnabled;if(e._cachedDefault!==null)return e._cachedDefault;try{e._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{e._cachedDefault=!0}return e._cachedDefault}static set enabled(t){e._explicitEnabled=t}static _depSuffix(t){if(!t?.length)return;let r=t.map(o=>e._names.get(o)??"?").join(",");return r.length>40?`${r.slice(0,37)}...`:r}static _resolveKey(t){let n=e._keys.get(t)??e._names.get(t);if(n)return n;let r=`anonymous_${e._nextId++}`;return e._keys.set(t,r),r}static register(t,n){if(!e.enabled)return;n?.name&&e._names.set(t,n.name),n?.kind&&e._kinds.set(t,n.kind);let r=e._nextId++,o=n?.name;if(!(o&&!e._usedKeys.has(o)))if(o){let u=e._depSuffix(n?.deps);o=u?`${o}(${u})`:`${o}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}else{let u=n?.kind??"store",a=e._depSuffix(n?.deps);o=a?`${u}(${a})`:`${u}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}e._usedKeys.add(o),e._keys.set(t,o),e._stores.add(new WeakRef(t))}static registerEdge(t,n){if(!e.enabled)return;let r=e._resolveKey(t),o=e._resolveKey(n),u=e._edges.get(r);u?u.includes(o)||u.push(o):e._edges.set(r,[o])}static getEdges(){return new Map(e._edges)}static getName(t){if(e.enabled)return e._names.get(t)}static getKind(t){return e._kinds.get(t)}static inspect(t){return{name:e._names.get(t),kind:e._kinds.get(t)??"unknown",value:typeof t.get=="function"?t.get():void 0,status:t._status}}static graph(){let t=new Map,n=new Set;for(let r of e._stores){let o=r.deref();if(!o){e._stores.delete(r);continue}let u=e._resolveKey(o);n.add(u),t.set(u,e.inspect(o))}for(let[r,o]of e._edges){if(!n.has(r)){e._edges.delete(r),e._usedKeys.delete(r);continue}let u=o.filter(a=>n.has(a));u.length===0?e._edges.delete(r):u.length!==o.length&&e._edges.set(r,u)}return t}static trace(t,n){let r=null,o=t.get();return t.source(C,(u,a)=>{if(u===C&&(r=a),u===D){r=null;return}if(u===1){let i=a;if(!Object.is(i,o)){let c=o;o=i,n(i,c)}}}),()=>r?.(D)}static dumpGraph(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let[a,i]of n)for(let c of i){let f=r.get(c);f?f.includes(a)||f.push(a):r.set(c,[a])}let o=[];for(let[a,i]of t){let c=r.get(a),f=n.get(a),s=c?.length?` \u2190 [${c.join(", ")}]`:"",l=f?.length?` \u2192 [${f.join(", ")}]`:"";o.push(` ${a} (${i.kind}) = ${JSON.stringify(i.value)} [${i.status??"?"}]${s}${l}`)}return[`Store Graph (${t.size} nodes):`,...o].join(`
2
- `)}static _observe(t,n,r){let o=null,u=n??e.getName(t),a={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:u,dispose:()=>o?.(D)};return t.source(C,(i,c)=>{if(i===C){o=c;return}i===A?(a.values.push(c),a.events.push({type:"data",data:c}),r&&r(`[${u}] DATA:`,c)):i===M?(a.signals.push(c),a.events.push({type:"signal",data:c}),c===W?a.dirtyCount++:c===ee&&a.resolvedCount++,r&&r(`[${u}] STATE:`,c)):i===D&&(a.ended=!0,a.endError=c,a.events.push({type:"end",data:c}),r&&r(`[${u}] END`,c!==void 0?c:""),o=null)}),a}static observe(t){return e._observe(t)}static tap(t,n){let r=n??`tap(${e.getName(t)??"anon"})`,o={get:()=>t.get(),source:t.source};return e.register(o,{name:r,kind:"tap"}),e.registerEdge(t,o),o}static spy(t,n){let r=n?.name??e.getName(t)??"spy",o=n?.log??console.log;return e._observe(t,r,o)}static snapshot(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let a of e._stores){let i=a.deref();if(!i)continue;let c=e._annotations.get(i);c!==void 0&&r.set(e._resolveKey(i),c)}let o=[];for(let[a,i]of t){let c={name:a,kind:i.kind,value:i.value,status:i.status},f=r.get(a);f!==void 0&&(c.annotation=f),o.push(c)}let u=[];for(let[a,i]of n)for(let c of i)u.push({from:a,to:c});return{nodes:o,edges:u,trace:e.traceLog()}}static toMermaid(t){let n=t?.direction??"TD",r=e.snapshot(),o=[`graph ${n}`],u={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function i(s){let l=s.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(l);return h===void 0?(a.set(l,1),l):(a.set(l,h+1),`${l}__${h}`)}let c=new Map;function f(s){let l=JSON.stringify(s);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let s of r.nodes){let l=i(s.name);c.set(s.name,l);let h=`${s.name} (${s.kind}) = ${f(s.value)}`,T=u[s.status??""]??"";o.push(` ${l}["${h}"]${T}`)}for(let s of r.edges){let l=c.get(s.from)??i(s.from),h=c.get(s.to)??i(s.to);o.push(` ${l} --> ${h}`)}return o.push(""),o.push(" classDef settled fill:#d4edda,stroke:#28a745"),o.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),o.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),o.push(" classDef completed fill:#cce5ff,stroke:#007bff"),o.join(`
3
- `)}static toD2(t){let n=t?.direction??"down",r=e.snapshot(),o=[`direction: ${n}`,""],u={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function i(s){let l=s.replace(/[^a-zA-Z0-9_]/g,"_"),h=a.get(l);return h===void 0?(a.set(l,1),l):(a.set(l,h+1),`${l}__${h}`)}let c=new Map;function f(s){let l=JSON.stringify(s);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let s of r.nodes){let l=i(s.name);c.set(s.name,l);let h=u[s.kind]??"rectangle",T=`${s.name} (${s.kind}) = ${f(s.value)}`,g=s.status?` [${s.status}]`:"";o.push(`${l}: "${T}${g}" { shape: ${h} }`)}r.edges.length>0&&o.push("");for(let s of r.edges){let l=c.get(s.from)??i(s.from),h=c.get(s.to)??i(s.to);o.push(`${l} -> ${h}`)}return o.join(`
4
- `)}static annotate(t,n){if(!e.enabled)return;e._annotations.set(t,n);let r={node:e._resolveKey(t),reason:n,timestamp:Date.now()},o=e.maxTraceEntries;o<=0||(e._traceLog.length<o?e._traceLog.push(r):(e._traceLog[e._traceHead]=r,e._traceFull=!0),e._traceHead=(e._traceHead+1)%o)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var re=1,O=64,L=2,K=4,we=8,Ee=16,H=32,$=1024,x=ie,U=me<<N,V=he<<N,oe=ge<<N,Be=Te<<N,Ke=ye<<N,Ue=Se<<N,Y=class{_value;_output=null;_flags;get _status(){return be(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(t,n){this._value=n?.initial,this._fn=t,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let r=0;n?.autoDirty!==!1&&(r|=K),n?.resetOnTeardown&&(r|=we),n?.resubscribable&&(r|=Ee),this._flags=r,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||R.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,n){let r=this._output;if(r)if(this._flags&O)for(let o of r)o(t,n);else r(t,n)}emit(t){this._flags&L||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(te()?this._flags&H||(this._flags|=H,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(M,W)),ne(()=>{this._flags&=~H,this._flags=this._flags&~x|V,this._dispatch(A,this._value)})):(this._flags&K&&!(this._flags&$)&&(this._flags=this._flags&~x|U,this._dispatch(M,W)),this._flags=this._flags&~x|V,this._dispatch(A,this._value))))}signal(t){this._flags&L||!this._output||(t===W?this._flags=this._flags&~x|U:t===ee&&(this._flags=this._flags&~x|Ue),this._dispatch(M,t))}complete(){if(this._flags&L)return;this._flags=(this._flags|L)&~x|Be;let t=this._output,n=this._flags&O;if(this._output=null,this._flags&=~(O|$),this._singleDepCount=0,this._stop(),t)if(n)for(let r of t)r(D);else t(D)}error(t){if(this._flags&L)return;this._flags=(this._flags|L)&~x|Ke;let n=this._output,r=this._flags&O;if(this._output=null,this._flags&=~(O|$),this._singleDepCount=0,this._stop(),n)if(r)for(let o of n)o(D,t);else n(D,t)}_start(){if(this._flags&re||!this._fn)return;this._flags|=re;let t=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&re&&(this._flags&=~re,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&we&&(this._value=this._initial),this._flags&L||(this._flags=this._flags&~x|oe))}source(t,n){if(t===C){let r=n;if(this._flags&L)if(this._flags&Ee&&this._output===null)this._flags=this._flags&~(L|x)|oe;else{r(C,u=>{}),r(D);return}if(this._output===null)this._output=r;else if(this._flags&O)this._output.add(r);else{let u=new Set;u.add(this._output),u.add(r),this._output=u,this._flags=(this._flags|O)&~$}let o=!1;r(C,(u,a)=>{if(u===A&&r(A,this._value),u===M&&a===pe&&!o&&(o=!0,this._singleDepCount++,this._flags&O||(this._flags|=$)),u===D){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&O){let i=this._output;i.delete(r),i.size===1?(this._output=i.values().next().value,this._flags&=~O,this._singleDepCount>0&&(this._flags|=$)):i.size===0&&(this._output=null,this._flags&=~(O|$),this._singleDepCount=0,this._flags=this._flags&~x|oe,this._stop())}else this._output===r&&(this._output=null,this._flags&=~$,this._singleDepCount=0,this._flags=this._flags&~x|oe,this._stop())}}),ve(()=>this._start())}}};function j(e,t){return new Y(e,t)}var ae=class extends Y{constructor(t,n){super(void 0,{initial:t,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),R.register(this,{kind:"state",...n})}get(){return this._value}set(t){this._flags&L||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(te()?this._flags&H||(this._flags|=H,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(M,W)),ne(()=>{this._flags&=~H,this._flags=this._flags&~x|V,this._dispatch(A,this._value)})):(this._flags&K&&!(this._flags&$)&&(this._flags=this._flags&~x|U,this._dispatch(M,W)),this._flags=this._flags&~x|V,this._dispatch(A,this._value))))}update(t){this.set(t(this._value))}};function k(e,t){return new ae(e,t)}function z(e,t,n){let r=null;_e(),e.source(C,(u,a)=>{if(u===C&&(r=a),u===D){r=null,n?.onEnd?.(a);return}if(u===1){let i=a,c=o;o=i,t(i,c)}});let o;try{o=e.get()}catch{}return ke(),()=>r?.(D)}function q(e,t){let n=t?.initialStatus??"pending",r=k(n,{name:"withStatus:status",equals:Object.is}),o=k(void 0,{name:"withStatus:error",equals:Object.is}),u=j(({emit:a,complete:i,error:c})=>{r.set(n),o.set(void 0);let f=z(e,s=>{r.get()==="errored"?P(()=>{o.set(void 0),r.set("active")}):r.set("active"),a(s)},{onEnd:s=>{if(s!==void 0){let l=s instanceof Error?s:new Error(String(s));P(()=>{o.set(l),r.set("errored")}),c(s)}else r.set("completed"),i()}});return()=>{f()}},{initial:e.get(),resubscribable:!0});return R.register(u,{kind:"withStatus"}),{get:()=>e.get(),source:(a,i)=>u.source(a,i),status:r,error:o}}function xe(e,t){let n=t?.name??"http",r=t?.method??"GET",o=t?.headers,u=t?.body,a=t?.poll??0,i=t?.transform??(y=>y.json()),c=t?.timeout??3e4,f=k(0,{name:`${n}:fetchCount`}),s=null,l=null,h=null,T=null,g=null,p=!1;async function v(){if(!p||!s)return;g=new AbortController;let y=[g.signal];t?.signal&&y.push(t.signal);let b=new AbortController;for(let _ of y){if(_.aborted){b.abort(_.reason);break}_.addEventListener("abort",()=>b.abort(_.reason),{once:!0})}let E=setTimeout(()=>b.abort(new Error("Request timeout")),c);try{let _=u!==void 0?typeof u=="string"?u:JSON.stringify(u):void 0,I=await fetch(e,{method:r,headers:o,body:_,signal:b.signal});if(!p)return;if(!I.ok)throw new Error(`HTTP ${I.status}: ${I.statusText}`);let F=await i(I);if(!p)return;P(()=>{f.update(B=>B+1),s?.(F)})}catch(_){if(!p||_?.name==="AbortError")return;l?.(_)}finally{clearTimeout(E),g=null}}function w(){!p||a<=0||(T=setTimeout(()=>{T=null,v().then(()=>{p&&w()}).catch(()=>{})},a))}let m=null,d=j(({emit:y,error:b,complete:E})=>(s=y,l=b,h=E,p=!0,m=()=>{v()},v().then(()=>{p&&w()}),()=>{p=!1,s=null,l=null,h=null,m=null,g?.abort(),g=null,T!==null&&(clearTimeout(T),T=null)}),{name:n,kind:"http"}),S=q(d);return{get:()=>S.get(),source:(y,b)=>S.source(y,b),status:S.status,error:S.error,fetchCount:f,refetch(){m?.()},stop(){p=!1,g?.abort(),g=null,T!==null&&(clearTimeout(T),T=null),h?.()}}}function ze(e){switch(e){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function qe(e,t){switch(e){case"openai":case"custom":return`${t}/chat/completions`;case"ollama":return`${t}/api/chat`;default:return`${t}/chat/completions`}}function Ve(e,t,n,r){let o={model:t,messages:n,stream:!0};return r?.temperature!==void 0&&(o.temperature=r.temperature),r?.maxTokens!==void 0&&(e==="ollama"?o.options={num_predict:r.maxTokens}:o.max_tokens=r.maxTokens),r?.stop&&(o.stop=r.stop),o}function Ye(e,t){let n={"Content-Type":"application/json"};return t&&(n.Authorization=`Bearer ${t}`),n}function De(e){let t=e.name??"llm",n=e.provider,r=e.baseURL??ze(n),o=e.model??"",u=e.fetch??globalThis.fetch,a=k("",{name:`${t}.store`}),i=k({},{name:`${t}.tokens`}),c=k("pending",{name:`${t}.status`}),f=k(void 0,{name:`${t}.error`}),s=null;function l(){s&&(s.abort(),s=null),c.get()==="active"&&c.set("pending")}function h(g,p){l(),s=new AbortController;let v=p?.signal?Qe(s.signal,p.signal):s.signal;P(()=>{a.set(""),i.set({}),f.set(void 0),c.set("active")});let w=qe(n,r),m=Ve(n,o,g,p),d=Ye(n,e.apiKey);T(w,d,m,v).catch(()=>{})}async function T(g,p,v,w){try{let m=await u(g,{method:"POST",headers:p,body:JSON.stringify(v),signal:w});if(!m.ok){let E=await m.text().catch(()=>"");throw new Error(`LLM API error ${m.status}: ${E}`)}let d=m.body?.getReader();if(!d)throw new Error("No response body");let S=new TextDecoder,y="",b="";for(;;){if(w.aborted)return;let{done:E,value:_}=await d.read();if(E)break;b+=S.decode(_,{stream:!0});let I=b.split(`
5
- `);b=I.pop()??"";for(let F of I){if(w.aborted)return;let B=F.trim();if(!B||B.startsWith(":")||!B.startsWith("data: "))continue;let ue=B.slice(6);if(ue!=="[DONE]")try{let ce=JSON.parse(ue),le=Ge(n,ce);le&&(y+=le,a.set(y));let fe=Je(n,ce);fe&&i.set(fe)}catch{}}}if(S.decode(),w.aborted)return;c.set("completed"),s=null}catch(m){if(w.aborted)return;P(()=>{f.set(m),c.set("errored")}),s=null}finally{w._cleanup?.()}}return{store:a,tokens:i,status:c,error:f,generate:h,abort:l}}function Ge(e,t){return e==="ollama"?t?.message?.content:t?.choices?.[0]?.delta?.content}function Je(e,t){let n=e==="ollama"?t:t?.usage;if(n){if(e==="ollama")return t.eval_count!==void 0||t.prompt_eval_count!==void 0?{promptTokens:t.prompt_eval_count,completionTokens:t.eval_count,totalTokens:(t.prompt_eval_count??0)+(t.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Qe(e,t){let n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o)},o=()=>{n.abort(),r()};e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",o,{once:!0});let u=n.signal;return u._cleanup=r,u}function Re(e){let t=e.name??"mcp",n=e.client,r=k([],{name:`${t}.tools`}),o=k([],{name:`${t}.resources`}),u=k(void 0,{name:`${t}.refreshError`});function a(f){u.set(f);let s=e.onRefreshError;if(s==="warn")console.warn(`[${t}] refresh error:`,f);else{if(s==="error")throw f;typeof s=="function"&&s(f)}}async function i(){if(u.set(void 0),n.listTools)try{let f=await n.listTools();r.set(f.tools)}catch(f){a(f)}if(n.listResources)try{let f=await n.listResources();o.set(f.resources)}catch(f){a(f)}}function c(f){let s=`${t}:${f}`,l=k(void 0,{name:`${s}.result`}),h=k("idle",{name:`${s}.status`}),T=k(void 0,{name:`${s}.error`}),g=k(void 0,{name:`${s}.lastArgs`}),p=k(void 0,{name:`${s}.duration`}),v=!1;async function w(m){if(v)return;v=!0,P(()=>{g.set(m),T.set(void 0),h.set("active")});let d=Date.now();try{let S=await n.callTool({name:f,arguments:m}),y=Date.now()-d;if(S.isError){let _=S.content.filter(F=>F.type==="text").map(F=>F.text??"").join(`
6
- `),I=new Error(_||"MCP tool returned error");P(()=>{p.set(y),T.set(I),h.set("errored")});return}let b=S.content.filter(_=>_.type==="text"),E;if(b.length===1){let _=b[0].text;if(_!==void 0)try{E=JSON.parse(_)}catch{E=_}}else b.length>1?E=b.map(_=>_.text??""):E=S.content;P(()=>{p.set(y),l.set(E),h.set("completed")})}catch(S){let y=Date.now()-d;P(()=>{p.set(y),T.set(S),h.set("errored")})}finally{v=!1}}return{store:l,status:h,error:T,call:w,lastArgs:g,duration:p}}return{tool:c,tools:r,resources:o,refresh:i,refreshError:u}}function Pe(e,t){let n=t?.path??"/",r=t?.name??"sse",o=t?.hostname??"0.0.0.0",u=t?.serialize??JSON.stringify,a=t?.eventName??"message",i=t?.pingInterval??3e4,c=k(0,{name:`${r}:connections`}),f=new Set,s=new Map,l=null;function h(){l||(l=z(e,m=>{let d=u(m),S=`event: ${a}
1
+ "use strict";var Ae=Object.create;var Z=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},de=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $e(t))!Ie.call(e,o)&&o!==n&&Z(e,o,{get:()=>t[o],enumerable:!(r=Me(t,o))||r.enumerable});return e};var je=(e,t,n)=>(n=e!=null?Ae(We(e)):{},de(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),He=e=>de(Z({},"__esModule",{value:!0}),e);var Ze={};Ne(Ze,{fromHTTP:()=>xe,fromLLM:()=>Re,fromMCP:()=>De,fromWebSocket:()=>Oe,fromWebhook:()=>Pe,toSSE:()=>Ce,toWebSocket:()=>Le});module.exports=He(Ze);var j=Symbol("DIRTY"),re=Symbol("RESOLVED"),pe=Symbol("SINGLE_DEP"),ge=0,me=1,he=2,Se=3,Te=4,be=5,H=7,ce=7<<H,Fe=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ye(e){return Fe[(e&ce)>>>H]}var L=0,W=1,D=2,I=3,X=0,ee=[],ue=!1;function O(e){X++;try{return e()}finally{if(X--,X===0&&!ue){ue=!0;for(let t=0;t<ee.length;t++)ee[t]();ee.length=0,ue=!1}}}function oe(){return X>0}function se(e){ee.push(e)}var ne=0,te=[];function _e(){ne++}function ke(){if(ne--,ne===0){for(let e=0;e<te.length;e++)te[e]();te.length=0}}function ve(e){ne>0?te.push(e):e()}var C=class e{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(e._explicitEnabled!==null)return e._explicitEnabled;if(e._cachedDefault!==null)return e._cachedDefault;try{e._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{e._cachedDefault=!0}return e._cachedDefault}static set enabled(t){e._explicitEnabled=t}static _depSuffix(t){if(!t?.length)return;let r=t.map(o=>e._names.get(o)??"?").join(",");return r.length>40?`${r.slice(0,37)}...`:r}static _resolveKey(t){let n=e._keys.get(t)??e._names.get(t);if(n)return n;let r=`anonymous_${e._nextId++}`;return e._keys.set(t,r),r}static register(t,n){if(!e.enabled)return;n?.name&&e._names.set(t,n.name),n?.kind&&e._kinds.set(t,n.kind);let r=e._nextId++,o=n?.name;if(!(o&&!e._usedKeys.has(o)))if(o){let u=e._depSuffix(n?.deps);o=u?`${o}(${u})`:`${o}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}else{let u=n?.kind??"store",a=e._depSuffix(n?.deps);o=a?`${u}(${a})`:`${u}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}e._usedKeys.add(o),e._keys.set(t,o),e._stores.add(new WeakRef(t))}static registerEdge(t,n){if(!e.enabled)return;let r=e._resolveKey(t),o=e._resolveKey(n),u=e._edges.get(r);u?u.includes(o)||u.push(o):e._edges.set(r,[o])}static getEdges(){return new Map(e._edges)}static getName(t){if(e.enabled)return e._names.get(t)}static getKind(t){return e._kinds.get(t)}static inspect(t){return{name:e._names.get(t),kind:e._kinds.get(t)??"unknown",value:typeof t.get=="function"?t.get():void 0,status:t._status}}static graph(){let t=new Map,n=new Set;for(let r of e._stores){let o=r.deref();if(!o){e._stores.delete(r);continue}let u=e._resolveKey(o);n.add(u),t.set(u,e.inspect(o))}for(let[r,o]of e._edges){if(!n.has(r)){e._edges.delete(r),e._usedKeys.delete(r);continue}let u=o.filter(a=>n.has(a));u.length===0?e._edges.delete(r):u.length!==o.length&&e._edges.set(r,u)}return t}static trace(t,n){let r=null,o=t.get();return t.source(L,(u,a)=>{if(u===L&&(r=a),u===D){r=null;return}if(u===1){let i=a;if(!Object.is(i,o)){let l=o;o=i,n(i,l)}}}),()=>r?.(D)}static dumpGraph(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let[a,i]of n)for(let l of i){let f=r.get(l);f?f.includes(a)||f.push(a):r.set(l,[a])}let o=[];for(let[a,i]of t){let l=r.get(a),f=n.get(a),s=l?.length?` \u2190 [${l.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";o.push(` ${a} (${i.kind}) = ${JSON.stringify(i.value)} [${i.status??"?"}]${s}${c}`)}return[`Store Graph (${t.size} nodes):`,...o].join(`
2
+ `)}static _observe(t,n,r){let o=null,u=n??e.getName(t),a={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:u,dispose:()=>o?.(D)};return t.source(L,(i,l)=>{if(i===L){o=l;return}i===W?(a.values.push(l),a.events.push({type:"data",data:l}),r&&r(`[${u}] DATA:`,l)):i===I?(a.signals.push(l),a.events.push({type:"signal",data:l}),l===j?a.dirtyCount++:l===re&&a.resolvedCount++,r&&r(`[${u}] STATE:`,l)):i===D&&(a.ended=!0,a.endError=l,a.events.push({type:"end",data:l}),r&&r(`[${u}] END`,l!==void 0?l:""),o=null)}),a}static observe(t){return e._observe(t)}static tap(t,n){let r=n??`tap(${e.getName(t)??"anon"})`,o={get:()=>t.get(),source:t.source};return e.register(o,{name:r,kind:"tap"}),e.registerEdge(t,o),o}static spy(t,n){let r=n?.name??e.getName(t)??"spy",o=n?.log??console.log;return e._observe(t,r,o)}static snapshot(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let a of e._stores){let i=a.deref();if(!i)continue;let l=e._annotations.get(i);l!==void 0&&r.set(e._resolveKey(i),l)}let o=[];for(let[a,i]of t){let l={name:a,kind:i.kind,value:i.value,status:i.status},f=r.get(a);f!==void 0&&(l.annotation=f),o.push(l)}let u=[];for(let[a,i]of n)for(let l of i)u.push({from:a,to:l});return{nodes:o,edges:u,trace:e.traceLog()}}static toMermaid(t){let n=t?.direction??"TD",r=e.snapshot(),o=[`graph ${n}`],u={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function i(s){let c=s.replace(/[^a-zA-Z0-9_]/g,"_"),p=a.get(c);return p===void 0?(a.set(c,1),c):(a.set(c,p+1),`${c}__${p}`)}let l=new Map;function f(s){let c=JSON.stringify(s);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let s of r.nodes){let c=i(s.name);l.set(s.name,c);let p=`${s.name} (${s.kind}) = ${f(s.value)}`,y=u[s.status??""]??"";o.push(` ${c}["${p}"]${y}`)}for(let s of r.edges){let c=l.get(s.from)??i(s.from),p=l.get(s.to)??i(s.to);o.push(` ${c} --> ${p}`)}return o.push(""),o.push(" classDef settled fill:#d4edda,stroke:#28a745"),o.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),o.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),o.push(" classDef completed fill:#cce5ff,stroke:#007bff"),o.join(`
3
+ `)}static toD2(t){let n=t?.direction??"down",r=e.snapshot(),o=[`direction: ${n}`,""],u={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function i(s){let c=s.replace(/[^a-zA-Z0-9_]/g,"_"),p=a.get(c);return p===void 0?(a.set(c,1),c):(a.set(c,p+1),`${c}__${p}`)}let l=new Map;function f(s){let c=JSON.stringify(s);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let s of r.nodes){let c=i(s.name);l.set(s.name,c);let p=u[s.kind]??"rectangle",y=`${s.name} (${s.kind}) = ${f(s.value)}`,_=s.status?` [${s.status}]`:"";o.push(`${c}: "${y}${_}" { shape: ${p} }`)}r.edges.length>0&&o.push("");for(let s of r.edges){let c=l.get(s.from)??i(s.from),p=l.get(s.to)??i(s.to);o.push(`${c} -> ${p}`)}return o.join(`
4
+ `)}static annotate(t,n){if(!e.enabled)return;e._annotations.set(t,n);let r={node:e._resolveKey(t),reason:n,timestamp:Date.now()},o=e.maxTraceEntries;o<=0||(e._traceLog.length<o?e._traceLog.push(r):(e._traceLog[e._traceHead]=r,e._traceFull=!0),e._traceHead=(e._traceHead+1)%o)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var ie=1,M=64,$=2,K=4,we=8,Ee=16,q=32,N=1024,x=ce,U=me<<H,Y=he<<H,ae=ge<<H,qe=Te<<H,Be=be<<H,Ke=Se<<H,G=class{_value;_output=null;_flags;get _status(){return ye(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(t,n){this._value=n?.initial,this._fn=t,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let r=0;n?.autoDirty!==!1&&(r|=K),n?.resetOnTeardown&&(r|=we),n?.resubscribable&&(r|=Ee),this._flags=r,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||C.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,n){let r=this._output;if(r)if(this._flags&M)for(let o of r)o(t,n);else r(t,n)}emit(t){this._flags&$||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(oe()?this._flags&q||(this._flags|=q,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),se(()=>{this._flags&=~q,this._flags=this._flags&~x|Y,this._dispatch(W,this._value)})):(this._flags&K&&!(this._flags&N)&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),this._flags=this._flags&~x|Y,this._dispatch(W,this._value))))}signal(t){this._flags&$||!this._output||(t===j?this._flags=this._flags&~x|U:t===re&&(this._flags=this._flags&~x|Ke),this._dispatch(I,t))}complete(){if(this._flags&$)return;this._flags=(this._flags|$)&~x|qe;let t=this._output,n=this._flags&M;if(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._stop(),t)if(n)for(let r of t)r(D);else t(D)}error(t){if(this._flags&$)return;this._flags=(this._flags|$)&~x|Be;let n=this._output,r=this._flags&M;if(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._stop(),n)if(r)for(let o of n)o(D,t);else n(D,t)}_start(){if(this._flags&ie||!this._fn)return;this._flags|=ie;let t=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&ie&&(this._flags&=~ie,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&we&&(this._value=this._initial),this._flags&$||(this._flags=this._flags&~x|ae))}source(t,n){if(t===L){let r=n;if(this._flags&$)if(this._flags&Ee&&this._output===null)this._flags=this._flags&~($|x)|ae;else{r(L,u=>{}),r(D);return}if(this._output===null)this._output=r;else if(this._flags&M)this._output.add(r);else{let u=new Set;u.add(this._output),u.add(r),this._output=u,this._flags=(this._flags|M)&~N}let o=!1;r(L,(u,a)=>{if(u===W&&r(W,this._value),u===I&&a===pe&&!o&&(o=!0,this._singleDepCount++,this._flags&M||(this._flags|=N)),u===D){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&M){let i=this._output;i.delete(r),i.size===1?(this._output=i.values().next().value,this._flags&=~M,this._singleDepCount>0&&(this._flags|=N)):i.size===0&&(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._flags=this._flags&~x|ae,this._stop())}else this._output===r&&(this._output=null,this._flags&=~N,this._singleDepCount=0,this._flags=this._flags&~x|ae,this._stop())}}),ve(()=>this._start())}}};function F(e,t){return new G(e,t)}var le=class extends G{constructor(t,n){super(void 0,{initial:t,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),C.register(this,{kind:"state",...n})}get(){return this._value}set(t){this._flags&$||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(oe()?this._flags&q||(this._flags|=q,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),se(()=>{this._flags&=~q,this._flags=this._flags&~x|Y,this._dispatch(W,this._value)})):(this._flags&K&&!(this._flags&N)&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),this._flags=this._flags&~x|Y,this._dispatch(W,this._value))))}update(t){this.set(t(this._value))}};function v(e,t){return new le(e,t)}function z(e,t,n){let r=null;_e(),e.source(L,(u,a)=>{if(u===L&&(r=a),u===D){r=null,n?.onEnd?.(a);return}if(u===1){let i=a,l=o;o=i,t(i,l)}});let o;try{o=e.get()}catch{}return ke(),()=>r?.(D)}function V(e,t){let n=t?.initialStatus??"pending",r=v(n,{name:"withStatus:status",equals:Object.is}),o=v(void 0,{name:"withStatus:error",equals:Object.is}),u=F(({emit:a,complete:i,error:l})=>{r.set(n),o.set(void 0);let f=z(e,s=>{r.get()==="errored"?O(()=>{o.set(void 0),r.set("active")}):r.set("active"),a(s)},{onEnd:s=>{if(s!==void 0){let c=s instanceof Error?s:new Error(String(s));O(()=>{o.set(c),r.set("errored")}),l(s)}else r.set("completed"),i()}});return()=>{f()}},{initial:e.get(),resubscribable:!0});return C.register(u,{kind:"withStatus"}),{get:()=>e.get(),source:(a,i)=>u.source(a,i),status:r,error:o}}function xe(e,t){let n=t?.name??"http",r=t?.method??"GET",o=t?.headers,u=t?.body,a=t?.poll??0,i=t?.transform??(k=>k.json()),l=t?.timeout??3e4,f=v(0,{name:`${n}:fetchCount`}),s=null,c=null,p=null,y=null,_=null,h=!1;async function T(){if(!h||!s)return;_=new AbortController;let k=[_.signal];t?.signal&&k.push(t.signal);let E=new AbortController;for(let b of k){if(b.aborted){E.abort(b.reason);break}b.addEventListener("abort",()=>E.abort(b.reason),{once:!0})}let w=setTimeout(()=>E.abort(new Error("Request timeout")),l);try{let b=u!==void 0?typeof u=="string"?u:JSON.stringify(u):void 0,A=await fetch(e,{method:r,headers:o,body:b,signal:E.signal});if(!h)return;if(!A.ok)throw new Error(`HTTP ${A.status}: ${A.statusText}`);let P=await i(A);if(!h)return;O(()=>{f.update(R=>R+1),s?.(P)})}catch(b){if(!h||b?.name==="AbortError")return;c?.(b)}finally{clearTimeout(w),_=null}}function m(){!h||a<=0||(y=setTimeout(()=>{y=null,T().then(()=>{h&&m()}).catch(()=>{})},a))}let g=null,d=F(({emit:k,error:E,complete:w})=>(s=k,c=E,p=w,h=!0,g=()=>{T()},T().then(()=>{h&&m()}),()=>{h=!1,s=null,c=null,p=null,g=null,_?.abort(),_=null,y!==null&&(clearTimeout(y),y=null)}),{name:n,kind:"http"}),S=V(d);return{get:()=>S.get(),source:(k,E)=>S.source(k,E),status:S.status,error:S.error,fetchCount:f,refetch(){g?.()},stop(){h=!1,_?.abort(),_=null,y!==null&&(clearTimeout(y),y=null),p?.()}}}function Ue(e){switch(e){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function ze(e,t){switch(e){case"openai":case"custom":return`${t}/chat/completions`;case"ollama":return`${t}/api/chat`;default:return`${t}/chat/completions`}}function Ve(e,t,n,r){let o={model:t,messages:n,stream:!0};return r?.temperature!==void 0&&(o.temperature=r.temperature),r?.maxTokens!==void 0&&(e==="ollama"?o.options={num_predict:r.maxTokens}:o.max_tokens=r.maxTokens),r?.stop&&(o.stop=r.stop),o}function Ye(e,t){let n={"Content-Type":"application/json"};return t&&(n.Authorization=`Bearer ${t}`),n}function Re(e){let t=e.name??"llm",n=e.provider,r=e.baseURL??Ue(n),o=e.model??"",u=e.fetch??globalThis.fetch,a=v("",{name:`${t}.store`}),i=v({},{name:`${t}.tokens`}),l=v("pending",{name:`${t}.status`}),f=v(void 0,{name:`${t}.error`}),s=null;function c(){s&&(s.abort(),s=null),l.get()==="active"&&l.set("pending")}function p(_,h){c(),s=new AbortController;let T=h?.signal?Qe(s.signal,h.signal):s.signal;O(()=>{a.set(""),i.set({}),f.set(void 0),l.set("active")});let m=ze(n,r),g=Ve(n,o,_,h),d=Ye(n,e.apiKey);y(m,d,g,T).catch(()=>{})}async function y(_,h,T,m){try{let g=await u(_,{method:"POST",headers:h,body:JSON.stringify(T),signal:m});if(!g.ok){let w=await g.text().catch(()=>"");throw new Error(`LLM API error ${g.status}: ${w}`)}let d=g.body?.getReader();if(!d)throw new Error("No response body");let S=new TextDecoder,k="",E="";for(;;){if(m.aborted)return;let{done:w,value:b}=await d.read();if(w)break;E+=S.decode(b,{stream:!0});let A=E.split(`
5
+ `);E=A.pop()??"";for(let P of A){if(m.aborted)return;let R=P.trim();if(!R||R.startsWith(":")||!R.startsWith("data: "))continue;let J=R.slice(6);if(J!=="[DONE]")try{let B=JSON.parse(J),Q=Ge(n,B);Q&&(k+=Q,a.set(k));let fe=Je(n,B);fe&&i.set(fe)}catch{}}}if(S.decode(),m.aborted)return;l.set("completed"),s=null}catch(g){if(m.aborted)return;O(()=>{f.set(g),l.set("errored")}),s=null}finally{m._cleanup?.()}}return{store:a,tokens:i,status:l,error:f,generate:p,abort:c}}function Ge(e,t){return e==="ollama"?t?.message?.content:t?.choices?.[0]?.delta?.content}function Je(e,t){let n=e==="ollama"?t:t?.usage;if(n){if(e==="ollama")return t.eval_count!==void 0||t.prompt_eval_count!==void 0?{promptTokens:t.prompt_eval_count,completionTokens:t.eval_count,totalTokens:(t.prompt_eval_count??0)+(t.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Qe(e,t){let n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o)},o=()=>{n.abort(),r()};e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",o,{once:!0});let u=n.signal;return u._cleanup=r,u}function De(e){let t=e.name??"mcp",n=e.client,r=v([],{name:`${t}.tools`}),o=v([],{name:`${t}.resources`}),u=v(void 0,{name:`${t}.refreshError`});function a(f){u.set(f);let s=e.onRefreshError;if(s==="warn")console.warn(`[${t}] refresh error:`,f);else{if(s==="error")throw f;typeof s=="function"&&s(f)}}async function i(){if(u.set(void 0),n.listTools)try{let f=await n.listTools();r.set(f.tools)}catch(f){a(f)}if(n.listResources)try{let f=await n.listResources();o.set(f.resources)}catch(f){a(f)}}function l(f){let s=`${t}:${f}`,c=v(void 0,{name:`${s}.result`}),p=v("idle",{name:`${s}.status`}),y=v(void 0,{name:`${s}.error`}),_=v(void 0,{name:`${s}.lastArgs`}),h=v(void 0,{name:`${s}.duration`}),T=!1;async function m(g){if(T)return;T=!0,O(()=>{_.set(g),y.set(void 0),p.set("active")});let d=Date.now();try{let S=await n.callTool({name:f,arguments:g}),k=Date.now()-d;if(S.isError){let b=S.content.filter(P=>P.type==="text").map(P=>P.text??"").join(`
6
+ `),A=new Error(b||"MCP tool returned error");O(()=>{h.set(k),y.set(A),p.set("errored")});return}let E=S.content.filter(b=>b.type==="text"),w;if(E.length===1){let b=E[0].text;if(b!==void 0)try{w=JSON.parse(b)}catch{w=b}}else E.length>1?w=E.map(b=>b.text??""):w=S.content;O(()=>{h.set(k),c.set(w),p.set("completed")})}catch(S){let k=Date.now()-d;O(()=>{h.set(k),y.set(S),p.set("errored")})}finally{T=!1}}return{store:c,status:p,error:y,call:m,lastArgs:_,duration:h}}return{tool:l,tools:r,resources:o,refresh:i,refreshError:u}}function Ce(e,t){let n=t?.path??"/",r=t?.name??"sse",o=t?.hostname??"0.0.0.0",u=t?.serialize??JSON.stringify,a=t?.eventName??"message",i=t?.pingInterval??3e4,l=v(0,{name:`${r}:connections`}),f=new Set,s=new Map,c=null;function p(){c||(c=z(e,g=>{let d=u(g),S=`event: ${a}
7
7
  data: ${d}
8
8
 
9
- `;for(let y of f)try{y.write(S)}catch{T(y)}}))}function T(m){f.delete(m);let d=s.get(m);d&&(clearInterval(d),s.delete(m)),c.set(f.size),f.size===0&&l&&(l(),l=null)}function g(m,d){let S=m.method?.toUpperCase();if((m.url??"/").split("?")[0]!==n){d.writeHead(404,{"Content-Type":"text/plain"}),d.end("Not found");return}if(S==="OPTIONS"){d.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Cache-Control"}),d.end();return}if(S!=="GET"){d.writeHead(405,{"Content-Type":"text/plain"}),d.end("Method not allowed");return}d.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),d.write(`:ok
9
+ `;for(let k of f)try{k.write(S)}catch{y(k)}}))}function y(g){f.delete(g);let d=s.get(g);d&&(clearInterval(d),s.delete(g)),l.set(f.size),f.size===0&&c&&(c(),c=null)}function _(g,d){let S=g.method?.toUpperCase();if((g.url??"/").split("?")[0]!==n){d.writeHead(404,{"Content-Type":"text/plain"}),d.end("Not found");return}if(S==="OPTIONS"){d.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Cache-Control"}),d.end();return}if(S!=="GET"){d.writeHead(405,{"Content-Type":"text/plain"}),d.end("Method not allowed");return}d.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),d.write(`:ok
10
10
 
11
- `),f.add(d),c.set(f.size);try{let E=e.get();if(E!==void 0){let _=u(E);d.write(`event: ${a}
12
- data: ${_}
11
+ `),f.add(d),l.set(f.size);try{let w=e.get();if(w!==void 0){let b=u(w);d.write(`event: ${a}
12
+ data: ${b}
13
13
 
14
- `)}}catch{}if(i>0){let E=setInterval(()=>{try{d.write(`:ping
14
+ `)}}catch{}if(i>0){let w=setInterval(()=>{try{d.write(`:ping
15
15
 
16
- `)}catch{T(d)}},i);s.set(d,E)}m.on("close",()=>T(d)),h()}let p=null;async function v(){if(!t?.port)throw new Error("toSSE: port is required for listen()");if(p)throw new Error("toSSE: already listening. Call close() first.");let m=await import("http");return new Promise((d,S)=>{p=m.createServer(g),p.once("listening",()=>d()),p.once("error",y=>{p=null,S(y)}),p.listen(t.port,o)})}function w(){for(let m of f)try{m.end()}catch{}f.clear();for(let m of s.values())clearInterval(m);s.clear(),c.set(0),l?.(),l=null,p?.close(),p=null}return R.register(c,{kind:"sse"}),{connectionCount:c,handler:g,listen:v,close:w}}function Ce(e){let t=e?.path??"/",n=e?.parse??JSON.parse,r=e?.name??"webhook",o=e?.hostname??"0.0.0.0",u=e?.maxBodySize??1024*1024,a=k(0,{name:`${r}:count`}),i=null,c=j(({emit:g})=>(i=g,()=>{i=null}),{name:r,kind:"webhook"});R.register(c,{kind:"webhook"});let f=q(c),s=null;function l(g,p){let v=g.method?.toUpperCase(),m=(g.url??"/").split("?")[0];if(v!=="POST"||m!==t){p.writeHead(404,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:"Not found"}));return}let d=[],S=0,y=!1;g.on("error",()=>{y=!0,p.headersSent||(p.writeHead(400,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:"Request aborted"})))}),g.on("data",b=>{if(!y){if(S+=b.length,S>u){y=!0,p.writeHead(413,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:"Payload too large"})),g.destroy?.();return}d.push(b)}}),g.on("end",()=>{if(!y)try{let b=Buffer.concat(d).toString("utf-8"),E=b.length>0?n(b):void 0;a.update(_=>_+1),i?.(E),p.writeHead(200,{"Content-Type":"application/json"}),p.end(JSON.stringify({ok:!0}))}catch(b){p.writeHead(400,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:b?.message??"Parse error"}))}})}function h(){return e?.port?s?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((g,p)=>{try{s=require("http").createServer(l),s.once("listening",()=>g()),s.once("error",w=>{s=null,p(w)}),s.listen(e.port,o)}catch(v){p(v)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function T(){s?.close(),s=null}return{get:()=>f.get(),source:(g,p)=>f.source(g,p),status:f.status,error:f.error,requestCount:a,handler:l,listen:h,close:T}}function Oe(e,t){let n=t?.name??"websocket",r=t?.parse??(d=>d),o=t?.reconnect??!1,u=t?.onParseError??"warn",a=k("connecting",{name:`${n}:connectionState`,equals:()=>!1}),i=null,c=null,f=null,s=null,l=null,h=!1,T=null,g=[];function p(){for(;g.length>0&&i?.readyState===WebSocket.OPEN;)i.send(g.shift())}function v(){h=!1,a.set("connecting");try{i=new WebSocket(e,t?.protocols)}catch(d){a.set("closed"),f?.(d);return}i.onopen=()=>{a.set("open"),p()},i.onmessage=d=>{try{let S=r(d.data);c?.(S)}catch(S){u==="error"?f?.(S):u==="warn"&&console.warn(`[${n}] parse error:`,S)}},i.onerror=()=>{T=new Error(`WebSocket error on ${e}`)},i.onclose=()=>{a.set("closed"),i=null;let d=T;T=null,!h&&o!==!1?l=setTimeout(()=>{l=null,c&&v()},o):d&&!h?f?.(d):s?.()}}let w=j(({emit:d,error:S,complete:y})=>(c=d,f=S,s=y,v(),()=>{c=null,f=null,s=null,h=!0,g.length=0,l!==null&&(clearTimeout(l),l=null),i&&(i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),i=null),a.set("closed")}),{name:n,kind:"websocket"});R.register(w,{kind:"websocket"});let m=q(w);return{get:()=>m.get(),source:(d,S)=>m.source(d,S),status:m.status,error:m.error,connectionState:a,send(d){i?.readyState===WebSocket.OPEN?i.send(d):g.push(d)},close(d,S){h=!0,g.length=0,l!==null&&(clearTimeout(l),l=null),i?.close(d,S)}}}function Le(e,t,n){let r=a=>typeof a=="string"?a:JSON.stringify(a),o=n?.serialize??r,u="send"in e&&typeof e.send=="function"?e.send.bind(e):null;if(!u)throw new Error("toWebSocket: invalid WebSocket target");return z(t,a=>{try{let i=o(a);u(i)}catch{}})}0&&(module.exports={fromHTTP,fromLLM,fromMCP,fromWebSocket,fromWebhook,toSSE,toWebSocket});
16
+ `)}catch{y(d)}},i);s.set(d,w)}g.on("close",()=>y(d)),p()}let h=null;async function T(){if(!t?.port)throw new Error("toSSE: port is required for listen()");if(h)throw new Error("toSSE: already listening. Call close() first.");let g=await import("http");return new Promise((d,S)=>{h=g.createServer(_),h.once("listening",()=>d()),h.once("error",k=>{h=null,S(k)}),h.listen(t.port,o)})}function m(){for(let g of f)try{g.end()}catch{}f.clear();for(let g of s.values())clearInterval(g);s.clear(),l.set(0),c?.(),c=null,h?.close(),h=null}return C.register(l,{kind:"sse"}),{connectionCount:l,handler:_,listen:T,close:m}}function Pe(e){let t=e?.path??"/",n=e?.parse??JSON.parse,r=e?.name??"webhook",o=e?.hostname??"0.0.0.0",u=e?.maxBodySize??1024*1024,a=e?.responseTimeout??3e4,i=v(0,{name:`${r}:count`}),l=null,f=F(({emit:T})=>(l=T,()=>{l=null}),{name:r,kind:"webhook"});C.register(f,{kind:"webhook"});let s=V(f),c=null,p=new Set;function y(T,m){let g=T.method?.toUpperCase(),S=(T.url??"/").split("?")[0];if(g!=="POST"||S!==t){m.writeHead(404,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Not found"}));return}let k=[],E=0,w=!1;T.on("error",()=>{w=!0,m.headersSent||(m.writeHead(400,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Request aborted"})))}),T.on("data",b=>{if(!w){if(E+=b.length,E>u){w=!0,m.writeHead(413,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Payload too large"})),T.destroy?.();return}k.push(b)}}),T.on("end",()=>{if(!w)try{let b=Buffer.concat(k).toString("utf-8"),A=b.length>0?n(b):void 0;i.update(B=>B+1);let P=!1,R=null,J={body:A,get responded(){return P},respond(B,Q=200){P||(P=!0,R!==null&&(clearTimeout(R),p.delete(R),R=null),m.writeHead(Q,{"Content-Type":"application/json"}),m.end(JSON.stringify(B)))}};R=setTimeout(()=>{p.delete(R),R=null,P||(P=!0,m.writeHead(504,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Response timeout"})))},a),p.add(R),l?.(J)}catch(b){m.writeHead(400,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:b?.message??"Parse error"}))}})}function _(){return e?.port?c?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((T,m)=>{try{c=require("http").createServer(y),c.once("listening",()=>T()),c.once("error",d=>{c=null,m(d)}),c.listen(e.port,o)}catch(g){m(g)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function h(){for(let T of p)clearTimeout(T);p.clear(),c?.close(),c=null}return{get:()=>s.get(),source:(T,m)=>s.source(T,m),status:s.status,error:s.error,requestCount:i,handler:y,listen:_,close:h}}function Oe(e,t){let n=t?.name??"websocket",r=t?.parse??(d=>d),o=t?.reconnect??!1,u=t?.onParseError??"warn",a=v("connecting",{name:`${n}:connectionState`,equals:()=>!1}),i=null,l=null,f=null,s=null,c=null,p=!1,y=null,_=[];function h(){for(;_.length>0&&i?.readyState===WebSocket.OPEN;)i.send(_.shift())}function T(){p=!1,a.set("connecting");try{i=new WebSocket(e,t?.protocols)}catch(d){a.set("closed"),f?.(d);return}i.onopen=()=>{a.set("open"),h()},i.onmessage=d=>{try{let S=r(d.data);l?.(S)}catch(S){u==="error"?f?.(S):u==="warn"&&console.warn(`[${n}] parse error:`,S)}},i.onerror=()=>{y=new Error(`WebSocket error on ${e}`)},i.onclose=()=>{a.set("closed"),i=null;let d=y;y=null,!p&&o!==!1?c=setTimeout(()=>{c=null,l&&T()},o):d&&!p?f?.(d):s?.()}}let m=F(({emit:d,error:S,complete:k})=>(l=d,f=S,s=k,T(),()=>{l=null,f=null,s=null,p=!0,_.length=0,c!==null&&(clearTimeout(c),c=null),i&&(i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),i=null),a.set("closed")}),{name:n,kind:"websocket"});C.register(m,{kind:"websocket"});let g=V(m);return{get:()=>g.get(),source:(d,S)=>g.source(d,S),status:g.status,error:g.error,connectionState:a,send(d){i?.readyState===WebSocket.OPEN?i.send(d):_.push(d)},close(d,S){p=!0,_.length=0,c!==null&&(clearTimeout(c),c=null),i?.close(d,S)}}}function Le(e,t,n){let r=a=>typeof a=="string"?a:JSON.stringify(a),o=n?.serialize??r,u="send"in e&&typeof e.send=="function"?e.send.bind(e):null;if(!u)throw new Error("toWebSocket: invalid WebSocket target");return z(t,a=>{try{let i=o(a);u(i)}catch{}})}0&&(module.exports={fromHTTP,fromLLM,fromMCP,fromWebSocket,fromWebhook,toSSE,toWebSocket});
@@ -2,7 +2,7 @@ export { FromHTTPOptions, HTTPStore, fromHTTP } from './http.cjs';
2
2
  export { GenerateOptions, LLMMessage, LLMOptions, LLMStore, LLMTokenUsage, fromLLM } from './llm.cjs';
3
3
  export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStore, fromMCP } from './mcp.cjs';
4
4
  export { SSEOptions, SSEStore, toSSE } from './sse.cjs';
5
- export { WebhookOptions, WebhookStore, fromWebhook } from './webhook.cjs';
5
+ export { WebhookOptions, WebhookRequest, WebhookStore, fromWebhook } from './webhook.cjs';
6
6
  export { FromWebSocketOptions, ToWebSocketOptions, WebSocketConnectionState, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.cjs';
7
7
  import '../types-BwU0Zcuz.cjs';
8
8
  import '../protocol-BVxRx57r.cjs';
@@ -2,7 +2,7 @@ export { FromHTTPOptions, HTTPStore, fromHTTP } from './http.js';
2
2
  export { GenerateOptions, LLMMessage, LLMOptions, LLMStore, LLMTokenUsage, fromLLM } from './llm.js';
3
3
  export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStore, fromMCP } from './mcp.js';
4
4
  export { SSEOptions, SSEStore, toSSE } from './sse.js';
5
- export { WebhookOptions, WebhookStore, fromWebhook } from './webhook.js';
5
+ export { WebhookOptions, WebhookRequest, WebhookStore, fromWebhook } from './webhook.js';
6
6
  export { FromWebSocketOptions, ToWebSocketOptions, WebSocketConnectionState, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.js';
7
7
  import '../types-DGII6w5S.js';
8
8
  import '../protocol-BVxRx57r.js';
@@ -1 +1 @@
1
- import{a as o}from"../chunk-EEKTY7JA.js";import{a as e}from"../chunk-OXIEM5ZP.js";import{a as t}from"../chunk-W74KQTWL.js";import{a as r}from"../chunk-X6RLUCXO.js";import{a as p}from"../chunk-OGRJOWHP.js";import{a as m,b as S}from"../chunk-OHNEQFSD.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{o as fromHTTP,e as fromLLM,t as fromMCP,m as fromWebSocket,p as fromWebhook,r as toSSE,S as toWebSocket};
1
+ import{a as o}from"../chunk-EEKTY7JA.js";import{a as e}from"../chunk-OXIEM5ZP.js";import{a as t}from"../chunk-W74KQTWL.js";import{a as r}from"../chunk-X6RLUCXO.js";import{a as p}from"../chunk-6M3P6NXX.js";import{a as m,b as S}from"../chunk-OHNEQFSD.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{o as fromHTTP,e as fromLLM,t as fromMCP,m as fromWebSocket,p as fromWebhook,r as toSSE,S as toWebSocket};
@@ -1,4 +1,4 @@
1
- "use strict";var U=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var yt=Object.prototype.hasOwnProperty;var vt=(t,e)=>{for(var i in e)U(t,i,{get:e[i],enumerable:!0})},Et=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mt(e))!yt.call(t,s)&&s!==i&&U(t,s,{get:()=>e[s],enumerable:!(n=Tt(e,s))||n.enumerable});return t};var bt=t=>Et(U({},"__esModule",{value:!0}),t);var Rt={};vt(Rt,{fromWebhook:()=>Ot});module.exports=bt(Rt);var D=Symbol("DIRTY"),K=Symbol("RESOLVED"),tt=Symbol("SINGLE_DEP"),et=0,nt=1,st=2,it=3,rt=4,ot=5,k=7,B=7<<k,Dt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function at(t){return Dt[(t&B)>>>k]}var S=0,y=1,h=2,v=3,C=0,j=[],z=!1;function J(t){C++;try{return t()}finally{if(C--,C===0&&!z){z=!0;for(let e=0;e<j.length;e++)j[e]();j.length=0,z=!1}}}function F(){return C>0}function Y(t){j.push(t)}var W=0,M=[];function ut(){W++}function ct(){if(W--,W===0){for(let t=0;t<M.length;t++)M[t]();M.length=0}}function lt(t){W>0?M.push(t):t()}var E=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let n=e.map(s=>t._names.get(s)??"?").join(",");return n.length>40?`${n.slice(0,37)}...`:n}static _resolveKey(e){let i=t._keys.get(e)??t._names.get(e);if(i)return i;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,i){if(!t.enabled)return;i?.name&&t._names.set(e,i.name),i?.kind&&t._kinds.set(e,i.kind);let n=t._nextId++,s=i?.name;if(!(s&&!t._usedKeys.has(s)))if(s){let o=t._depSuffix(i?.deps);s=o?`${s}(${o})`:`${s}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let o=i?.kind??"store",r=t._depSuffix(i?.deps);s=r?`${o}(${r})`:`${o}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}t._usedKeys.add(s),t._keys.set(e,s),t._stores.add(new WeakRef(e))}static registerEdge(e,i){if(!t.enabled)return;let n=t._resolveKey(e),s=t._resolveKey(i),o=t._edges.get(n);o?o.includes(s)||o.push(s):t._edges.set(n,[s])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,i=new Set;for(let n of t._stores){let s=n.deref();if(!s){t._stores.delete(n);continue}let o=t._resolveKey(s);i.add(o),e.set(o,t.inspect(s))}for(let[n,s]of t._edges){if(!i.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let o=s.filter(r=>i.has(r));o.length===0?t._edges.delete(n):o.length!==s.length&&t._edges.set(n,o)}return e}static trace(e,i){let n=null,s=e.get();return e.source(S,(o,r)=>{if(o===S&&(n=r),o===h){n=null;return}if(o===1){let u=r;if(!Object.is(u,s)){let c=s;s=u,i(u,c)}}}),()=>n?.(h)}static dumpGraph(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let[r,u]of i)for(let c of u){let d=n.get(c);d?d.includes(r)||d.push(r):n.set(c,[r])}let s=[];for(let[r,u]of e){let c=n.get(r),d=i.get(r),a=c?.length?` \u2190 [${c.join(", ")}]`:"",l=d?.length?` \u2192 [${d.join(", ")}]`:"";s.push(` ${r} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${a}${l}`)}return[`Store Graph (${e.size} nodes):`,...s].join(`
2
- `)}static _observe(e,i,n){let s=null,o=i??t.getName(e),r={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:o,dispose:()=>s?.(h)};return e.source(S,(u,c)=>{if(u===S){s=c;return}u===y?(r.values.push(c),r.events.push({type:"data",data:c}),n&&n(`[${o}] DATA:`,c)):u===v?(r.signals.push(c),r.events.push({type:"signal",data:c}),c===D?r.dirtyCount++:c===K&&r.resolvedCount++,n&&n(`[${o}] STATE:`,c)):u===h&&(r.ended=!0,r.endError=c,r.events.push({type:"end",data:c}),n&&n(`[${o}] END`,c!==void 0?c:""),s=null)}),r}static observe(e){return t._observe(e)}static tap(e,i){let n=i??`tap(${t.getName(e)??"anon"})`,s={get:()=>e.get(),source:e.source};return t.register(s,{name:n,kind:"tap"}),t.registerEdge(e,s),s}static spy(e,i){let n=i?.name??t.getName(e)??"spy",s=i?.log??console.log;return t._observe(e,n,s)}static snapshot(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let r of t._stores){let u=r.deref();if(!u)continue;let c=t._annotations.get(u);c!==void 0&&n.set(t._resolveKey(u),c)}let s=[];for(let[r,u]of e){let c={name:r,kind:u.kind,value:u.value,status:u.status},d=n.get(r);d!==void 0&&(c.annotation=d),s.push(c)}let o=[];for(let[r,u]of i)for(let c of u)o.push({from:r,to:c});return{nodes:s,edges:o,trace:t.traceLog()}}static toMermaid(e){let i=e?.direction??"TD",n=t.snapshot(),s=[`graph ${i}`],o={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},r=new Map;function u(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=r.get(l);return f===void 0?(r.set(l,1),l):(r.set(l,f+1),`${l}__${f}`)}let c=new Map;function d(a){let l=JSON.stringify(a);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let a of n.nodes){let l=u(a.name);c.set(a.name,l);let f=`${a.name} (${a.kind}) = ${d(a.value)}`,I=o[a.status??""]??"";s.push(` ${l}["${f}"]${I}`)}for(let a of n.edges){let l=c.get(a.from)??u(a.from),f=c.get(a.to)??u(a.to);s.push(` ${l} --> ${f}`)}return s.push(""),s.push(" classDef settled fill:#d4edda,stroke:#28a745"),s.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),s.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),s.push(" classDef completed fill:#cce5ff,stroke:#007bff"),s.join(`
3
- `)}static toD2(e){let i=e?.direction??"down",n=t.snapshot(),s=[`direction: ${i}`,""],o={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},r=new Map;function u(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=r.get(l);return f===void 0?(r.set(l,1),l):(r.set(l,f+1),`${l}__${f}`)}let c=new Map;function d(a){let l=JSON.stringify(a);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let a of n.nodes){let l=u(a.name);c.set(a.name,l);let f=o[a.kind]??"rectangle",I=`${a.name} (${a.kind}) = ${d(a.value)}`,_=a.status?` [${a.status}]`:"";s.push(`${l}: "${I}${_}" { shape: ${f} }`)}n.edges.length>0&&s.push("");for(let a of n.edges){let l=c.get(a.from)??u(a.from),f=c.get(a.to)??u(a.to);s.push(`${l} -> ${f}`)}return s.join(`
4
- `)}static annotate(e,i){if(!t.enabled)return;t._annotations.set(e,i);let n={node:t._resolveKey(e),reason:i,timestamp:Date.now()},s=t.maxTraceEntries;s<=0||(t._traceLog.length<s?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%s)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var H=1,T=64,m=2,O=4,dt=8,ft=16,w=32,b=1024,p=B,R=nt<<k,$=st<<k,q=et<<k,kt=rt<<k,xt=ot<<k,wt=it<<k,P=class{_value;_output=null;_flags;get _status(){return at(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(e,i){this._value=i?.initial,this._fn=e,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let n=0;i?.autoDirty!==!1&&(n|=O),i?.resetOnTeardown&&(n|=dt),i?.resubscribable&&(n|=ft),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||E.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,i){let n=this._output;if(n)if(this._flags&T)for(let s of n)s(e,i);else n(e,i)}emit(e){this._flags&m||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(F()?this._flags&w||(this._flags|=w,this._flags&O&&(this._flags=this._flags&~p|R,this._dispatch(v,D)),Y(()=>{this._flags&=~w,this._flags=this._flags&~p|$,this._dispatch(y,this._value)})):(this._flags&O&&!(this._flags&b)&&(this._flags=this._flags&~p|R,this._dispatch(v,D)),this._flags=this._flags&~p|$,this._dispatch(y,this._value))))}signal(e){this._flags&m||!this._output||(e===D?this._flags=this._flags&~p|R:e===K&&(this._flags=this._flags&~p|wt),this._dispatch(v,e))}complete(){if(this._flags&m)return;this._flags=(this._flags|m)&~p|kt;let e=this._output,i=this._flags&T;if(this._output=null,this._flags&=~(T|b),this._singleDepCount=0,this._stop(),e)if(i)for(let n of e)n(h);else e(h)}error(e){if(this._flags&m)return;this._flags=(this._flags|m)&~p|xt;let i=this._output,n=this._flags&T;if(this._output=null,this._flags&=~(T|b),this._singleDepCount=0,this._stop(),i)if(n)for(let s of i)s(h,e);else i(h,e)}_start(){if(this._flags&H||!this._fn)return;this._flags|=H;let e=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i)});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&H&&(this._flags&=~H,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&dt&&(this._value=this._initial),this._flags&m||(this._flags=this._flags&~p|q))}source(e,i){if(e===S){let n=i;if(this._flags&m)if(this._flags&ft&&this._output===null)this._flags=this._flags&~(m|p)|q;else{n(S,o=>{}),n(h);return}if(this._output===null)this._output=n;else if(this._flags&T)this._output.add(n);else{let o=new Set;o.add(this._output),o.add(n),this._output=o,this._flags=(this._flags|T)&~b}let s=!1;n(S,(o,r)=>{if(o===y&&n(y,this._value),o===v&&r===tt&&!s&&(s=!0,this._singleDepCount++,this._flags&T||(this._flags|=b)),o===h){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&T){let u=this._output;u.delete(n),u.size===1?(this._output=u.values().next().value,this._flags&=~T,this._singleDepCount>0&&(this._flags|=b)):u.size===0&&(this._output=null,this._flags&=~(T|b),this._singleDepCount=0,this._flags=this._flags&~p|q,this._stop())}else this._output===n&&(this._output=null,this._flags&=~b,this._singleDepCount=0,this._flags=this._flags&~p|q,this._stop())}}),lt(()=>this._start())}}};function V(t,e){return new P(t,e)}var G=class extends P{constructor(e,i){super(void 0,{initial:e,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),E.register(this,{kind:"state",...i})}get(){return this._value}set(e){this._flags&m||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(F()?this._flags&w||(this._flags|=w,this._flags&O&&(this._flags=this._flags&~p|R,this._dispatch(v,D)),Y(()=>{this._flags&=~w,this._flags=this._flags&~p|$,this._dispatch(y,this._value)})):(this._flags&O&&!(this._flags&b)&&(this._flags=this._flags&~p|R,this._dispatch(v,D)),this._flags=this._flags&~p|$,this._dispatch(y,this._value))))}update(e){this.set(e(this._value))}};function N(t,e){return new G(t,e)}function pt(t,e,i){let n=null;ut(),t.source(S,(o,r)=>{if(o===S&&(n=r),o===h){n=null,i?.onEnd?.(r);return}if(o===1){let u=r,c=s;s=u,e(u,c)}});let s;try{s=t.get()}catch{}return ct(),()=>n?.(h)}function gt(t,e){let i=e?.initialStatus??"pending",n=N(i,{name:"withStatus:status",equals:Object.is}),s=N(void 0,{name:"withStatus:error",equals:Object.is}),o=V(({emit:r,complete:u,error:c})=>{n.set(i),s.set(void 0);let d=pt(t,a=>{n.get()==="errored"?J(()=>{s.set(void 0),n.set("active")}):n.set("active"),r(a)},{onEnd:a=>{if(a!==void 0){let l=a instanceof Error?a:new Error(String(a));J(()=>{s.set(l),n.set("errored")}),c(a)}else n.set("completed"),u()}});return()=>{d()}},{initial:t.get(),resubscribable:!0});return E.register(o,{kind:"withStatus"}),{get:()=>t.get(),source:(r,u)=>o.source(r,u),status:n,error:s}}function Ot(t){let e=t?.path??"/",i=t?.parse??JSON.parse,n=t?.name??"webhook",s=t?.hostname??"0.0.0.0",o=t?.maxBodySize??1024*1024,r=N(0,{name:`${n}:count`}),u=null,c=V(({emit:_})=>(u=_,()=>{u=null}),{name:n,kind:"webhook"});E.register(c,{kind:"webhook"});let d=gt(c),a=null;function l(_,g){let A=_.method?.toUpperCase(),ht=(_.url??"/").split("?")[0];if(A!=="POST"||ht!==e){g.writeHead(404,{"Content-Type":"application/json"}),g.end(JSON.stringify({error:"Not found"}));return}let Q=[],X=0,L=!1;_.on("error",()=>{L=!0,g.headersSent||(g.writeHead(400,{"Content-Type":"application/json"}),g.end(JSON.stringify({error:"Request aborted"})))}),_.on("data",x=>{if(!L){if(X+=x.length,X>o){L=!0,g.writeHead(413,{"Content-Type":"application/json"}),g.end(JSON.stringify({error:"Payload too large"})),_.destroy?.();return}Q.push(x)}}),_.on("end",()=>{if(!L)try{let x=Buffer.concat(Q).toString("utf-8"),_t=x.length>0?i(x):void 0;r.update(St=>St+1),u?.(_t),g.writeHead(200,{"Content-Type":"application/json"}),g.end(JSON.stringify({ok:!0}))}catch(x){g.writeHead(400,{"Content-Type":"application/json"}),g.end(JSON.stringify({error:x?.message??"Parse error"}))}})}function f(){return t?.port?a?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((_,g)=>{try{a=require("http").createServer(l),a.once("listening",()=>_()),a.once("error",Z=>{a=null,g(Z)}),a.listen(t.port,s)}catch(A){g(A)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function I(){a?.close(),a=null}return{get:()=>d.get(),source:(_,g)=>d.source(_,g),status:d.status,error:d.error,requestCount:r,handler:l,listen:f,close:I}}0&&(module.exports={fromWebhook});
1
+ "use strict";var G=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var xe=Object.prototype.hasOwnProperty;var we=(e,t)=>{for(var i in t)G(e,i,{get:t[i],enumerable:!0})},Re=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ke(t))!xe.call(e,s)&&s!==i&&G(e,s,{get:()=>t[s],enumerable:!(n=De(t,s))||n.enumerable});return e};var Oe=e=>Re(G({},"__esModule",{value:!0}),e);var Ce={};we(Ce,{fromWebhook:()=>Ae});module.exports=Oe(Ce);var D=Symbol("DIRTY"),q=Symbol("RESOLVED"),ie=Symbol("SINGLE_DEP"),re=0,oe=1,ae=2,ue=3,ce=4,le=5,k=7,Q=7<<k,Ie=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function de(e){return Ie[(e&Q)>>>k]}var T=0,y=1,h=2,b=3,M=0,W=[],Z=!1;function X(e){M++;try{return e()}finally{if(M--,M===0&&!Z){Z=!0;for(let t=0;t<W.length;t++)W[t]();W.length=0,Z=!1}}}function H(){return M>0}function Y(e){W.push(e)}var F=0,K=[];function fe(){F++}function pe(){if(F--,F===0){for(let e=0;e<K.length;e++)K[e]();K.length=0}}function ge(e){F>0?K.push(e):e()}var v=class e{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(e._explicitEnabled!==null)return e._explicitEnabled;if(e._cachedDefault!==null)return e._cachedDefault;try{e._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{e._cachedDefault=!0}return e._cachedDefault}static set enabled(t){e._explicitEnabled=t}static _depSuffix(t){if(!t?.length)return;let n=t.map(s=>e._names.get(s)??"?").join(",");return n.length>40?`${n.slice(0,37)}...`:n}static _resolveKey(t){let i=e._keys.get(t)??e._names.get(t);if(i)return i;let n=`anonymous_${e._nextId++}`;return e._keys.set(t,n),n}static register(t,i){if(!e.enabled)return;i?.name&&e._names.set(t,i.name),i?.kind&&e._kinds.set(t,i.kind);let n=e._nextId++,s=i?.name;if(!(s&&!e._usedKeys.has(s)))if(s){let o=e._depSuffix(i?.deps);s=o?`${s}(${o})`:`${s}_${n}`,e._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let o=i?.kind??"store",r=e._depSuffix(i?.deps);s=r?`${o}(${r})`:`${o}_${n}`,e._usedKeys.has(s)&&(s=`${s}_${n}`)}e._usedKeys.add(s),e._keys.set(t,s),e._stores.add(new WeakRef(t))}static registerEdge(t,i){if(!e.enabled)return;let n=e._resolveKey(t),s=e._resolveKey(i),o=e._edges.get(n);o?o.includes(s)||o.push(s):e._edges.set(n,[s])}static getEdges(){return new Map(e._edges)}static getName(t){if(e.enabled)return e._names.get(t)}static getKind(t){return e._kinds.get(t)}static inspect(t){return{name:e._names.get(t),kind:e._kinds.get(t)??"unknown",value:typeof t.get=="function"?t.get():void 0,status:t._status}}static graph(){let t=new Map,i=new Set;for(let n of e._stores){let s=n.deref();if(!s){e._stores.delete(n);continue}let o=e._resolveKey(s);i.add(o),t.set(o,e.inspect(s))}for(let[n,s]of e._edges){if(!i.has(n)){e._edges.delete(n),e._usedKeys.delete(n);continue}let o=s.filter(r=>i.has(r));o.length===0?e._edges.delete(n):o.length!==s.length&&e._edges.set(n,o)}return t}static trace(t,i){let n=null,s=t.get();return t.source(T,(o,r)=>{if(o===T&&(n=r),o===h){n=null;return}if(o===1){let u=r;if(!Object.is(u,s)){let c=s;s=u,i(u,c)}}}),()=>n?.(h)}static dumpGraph(){let t=e.graph(),i=e.getEdges(),n=new Map;for(let[r,u]of i)for(let c of u){let f=n.get(c);f?f.includes(r)||f.push(r):n.set(c,[r])}let s=[];for(let[r,u]of t){let c=n.get(r),f=i.get(r),a=c?.length?` \u2190 [${c.join(", ")}]`:"",l=f?.length?` \u2192 [${f.join(", ")}]`:"";s.push(` ${r} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${a}${l}`)}return[`Store Graph (${t.size} nodes):`,...s].join(`
2
+ `)}static _observe(t,i,n){let s=null,o=i??e.getName(t),r={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:o,dispose:()=>s?.(h)};return t.source(T,(u,c)=>{if(u===T){s=c;return}u===y?(r.values.push(c),r.events.push({type:"data",data:c}),n&&n(`[${o}] DATA:`,c)):u===b?(r.signals.push(c),r.events.push({type:"signal",data:c}),c===D?r.dirtyCount++:c===q&&r.resolvedCount++,n&&n(`[${o}] STATE:`,c)):u===h&&(r.ended=!0,r.endError=c,r.events.push({type:"end",data:c}),n&&n(`[${o}] END`,c!==void 0?c:""),s=null)}),r}static observe(t){return e._observe(t)}static tap(t,i){let n=i??`tap(${e.getName(t)??"anon"})`,s={get:()=>t.get(),source:t.source};return e.register(s,{name:n,kind:"tap"}),e.registerEdge(t,s),s}static spy(t,i){let n=i?.name??e.getName(t)??"spy",s=i?.log??console.log;return e._observe(t,n,s)}static snapshot(){let t=e.graph(),i=e.getEdges(),n=new Map;for(let r of e._stores){let u=r.deref();if(!u)continue;let c=e._annotations.get(u);c!==void 0&&n.set(e._resolveKey(u),c)}let s=[];for(let[r,u]of t){let c={name:r,kind:u.kind,value:u.value,status:u.status},f=n.get(r);f!==void 0&&(c.annotation=f),s.push(c)}let o=[];for(let[r,u]of i)for(let c of u)o.push({from:r,to:c});return{nodes:s,edges:o,trace:e.traceLog()}}static toMermaid(t){let i=t?.direction??"TD",n=e.snapshot(),s=[`graph ${i}`],o={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},r=new Map;function u(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),d=r.get(l);return d===void 0?(r.set(l,1),l):(r.set(l,d+1),`${l}__${d}`)}let c=new Map;function f(a){let l=JSON.stringify(a);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let a of n.nodes){let l=u(a.name);c.set(a.name,l);let d=`${a.name} (${a.kind}) = ${f(a.value)}`,O=o[a.status??""]??"";s.push(` ${l}["${d}"]${O}`)}for(let a of n.edges){let l=c.get(a.from)??u(a.from),d=c.get(a.to)??u(a.to);s.push(` ${l} --> ${d}`)}return s.push(""),s.push(" classDef settled fill:#d4edda,stroke:#28a745"),s.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),s.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),s.push(" classDef completed fill:#cce5ff,stroke:#007bff"),s.join(`
3
+ `)}static toD2(t){let i=t?.direction??"down",n=e.snapshot(),s=[`direction: ${i}`,""],o={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},r=new Map;function u(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),d=r.get(l);return d===void 0?(r.set(l,1),l):(r.set(l,d+1),`${l}__${d}`)}let c=new Map;function f(a){let l=JSON.stringify(a);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let a of n.nodes){let l=u(a.name);c.set(a.name,l);let d=o[a.kind]??"rectangle",O=`${a.name} (${a.kind}) = ${f(a.value)}`,B=a.status?` [${a.status}]`:"";s.push(`${l}: "${O}${B}" { shape: ${d} }`)}n.edges.length>0&&s.push("");for(let a of n.edges){let l=c.get(a.from)??u(a.from),d=c.get(a.to)??u(a.to);s.push(`${l} -> ${d}`)}return s.join(`
4
+ `)}static annotate(t,i){if(!e.enabled)return;e._annotations.set(t,i);let n={node:e._resolveKey(t),reason:i,timestamp:Date.now()},s=e.maxTraceEntries;s<=0||(e._traceLog.length<s?e._traceLog.push(n):(e._traceLog[e._traceHead]=n,e._traceFull=!0),e._traceHead=(e._traceHead+1)%s)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var V=1,S=64,m=2,I=4,he=8,_e=16,R=32,E=1024,g=Q,$=oe<<k,N=ae<<k,U=re<<k,$e=ce<<k,Pe=le<<k,Ne=ue<<k,A=class{_value;_output=null;_flags;get _status(){return de(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(t,i){this._value=i?.initial,this._fn=t,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let n=0;i?.autoDirty!==!1&&(n|=I),i?.resetOnTeardown&&(n|=he),i?.resubscribable&&(n|=_e),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||v.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,i){let n=this._output;if(n)if(this._flags&S)for(let s of n)s(t,i);else n(t,i)}emit(t){this._flags&m||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(H()?this._flags&R||(this._flags|=R,this._flags&I&&(this._flags=this._flags&~g|$,this._dispatch(b,D)),Y(()=>{this._flags&=~R,this._flags=this._flags&~g|N,this._dispatch(y,this._value)})):(this._flags&I&&!(this._flags&E)&&(this._flags=this._flags&~g|$,this._dispatch(b,D)),this._flags=this._flags&~g|N,this._dispatch(y,this._value))))}signal(t){this._flags&m||!this._output||(t===D?this._flags=this._flags&~g|$:t===q&&(this._flags=this._flags&~g|Ne),this._dispatch(b,t))}complete(){if(this._flags&m)return;this._flags=(this._flags|m)&~g|$e;let t=this._output,i=this._flags&S;if(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._stop(),t)if(i)for(let n of t)n(h);else t(h)}error(t){if(this._flags&m)return;this._flags=(this._flags|m)&~g|Pe;let i=this._output,n=this._flags&S;if(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._stop(),i)if(n)for(let s of i)s(h,t);else i(h,t)}_start(){if(this._flags&V||!this._fn)return;this._flags|=V;let t=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i)});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&V&&(this._flags&=~V,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&he&&(this._value=this._initial),this._flags&m||(this._flags=this._flags&~g|U))}source(t,i){if(t===T){let n=i;if(this._flags&m)if(this._flags&_e&&this._output===null)this._flags=this._flags&~(m|g)|U;else{n(T,o=>{}),n(h);return}if(this._output===null)this._output=n;else if(this._flags&S)this._output.add(n);else{let o=new Set;o.add(this._output),o.add(n),this._output=o,this._flags=(this._flags|S)&~E}let s=!1;n(T,(o,r)=>{if(o===y&&n(y,this._value),o===b&&r===ie&&!s&&(s=!0,this._singleDepCount++,this._flags&S||(this._flags|=E)),o===h){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&S){let u=this._output;u.delete(n),u.size===1?(this._output=u.values().next().value,this._flags&=~S,this._singleDepCount>0&&(this._flags|=E)):u.size===0&&(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._flags=this._flags&~g|U,this._stop())}else this._output===n&&(this._output=null,this._flags&=~E,this._singleDepCount=0,this._flags=this._flags&~g|U,this._stop())}}),ge(()=>this._start())}}};function z(e,t){return new A(e,t)}var ee=class extends A{constructor(t,i){super(void 0,{initial:t,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),v.register(this,{kind:"state",...i})}get(){return this._value}set(t){this._flags&m||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(H()?this._flags&R||(this._flags|=R,this._flags&I&&(this._flags=this._flags&~g|$,this._dispatch(b,D)),Y(()=>{this._flags&=~R,this._flags=this._flags&~g|N,this._dispatch(y,this._value)})):(this._flags&I&&!(this._flags&E)&&(this._flags=this._flags&~g|$,this._dispatch(b,D)),this._flags=this._flags&~g|N,this._dispatch(y,this._value))))}update(t){this.set(t(this._value))}};function C(e,t){return new ee(e,t)}function Te(e,t,i){let n=null;fe(),e.source(T,(o,r)=>{if(o===T&&(n=r),o===h){n=null,i?.onEnd?.(r);return}if(o===1){let u=r,c=s;s=u,t(u,c)}});let s;try{s=e.get()}catch{}return pe(),()=>n?.(h)}function Se(e,t){let i=t?.initialStatus??"pending",n=C(i,{name:"withStatus:status",equals:Object.is}),s=C(void 0,{name:"withStatus:error",equals:Object.is}),o=z(({emit:r,complete:u,error:c})=>{n.set(i),s.set(void 0);let f=Te(e,a=>{n.get()==="errored"?X(()=>{s.set(void 0),n.set("active")}):n.set("active"),r(a)},{onEnd:a=>{if(a!==void 0){let l=a instanceof Error?a:new Error(String(a));X(()=>{s.set(l),n.set("errored")}),c(a)}else n.set("completed"),u()}});return()=>{f()}},{initial:e.get(),resubscribable:!0});return v.register(o,{kind:"withStatus"}),{get:()=>e.get(),source:(r,u)=>o.source(r,u),status:n,error:s}}function Ae(e){let t=e?.path??"/",i=e?.parse??JSON.parse,n=e?.name??"webhook",s=e?.hostname??"0.0.0.0",o=e?.maxBodySize??1024*1024,r=e?.responseTimeout??3e4,u=C(0,{name:`${n}:count`}),c=null,f=z(({emit:_})=>(c=_,()=>{c=null}),{name:n,kind:"webhook"});v.register(f,{kind:"webhook"});let a=Se(f),l=null,d=new Set;function O(_,p){let L=_.method?.toUpperCase(),ye=(_.url??"/").split("?")[0];if(L!=="POST"||ye!==t){p.writeHead(404,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:"Not found"}));return}let ne=[],se=0,j=!1;_.on("error",()=>{j=!0,p.headersSent||(p.writeHead(400,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:"Request aborted"})))}),_.on("data",w=>{if(!j){if(se+=w.length,se>o){j=!0,p.writeHead(413,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:"Payload too large"})),_.destroy?.();return}ne.push(w)}}),_.on("end",()=>{if(!j)try{let w=Buffer.concat(ne).toString("utf-8"),be=w.length>0?i(w):void 0;u.update(J=>J+1);let P=!1,x=null,ve={body:be,get responded(){return P},respond(J,Ee=200){P||(P=!0,x!==null&&(clearTimeout(x),d.delete(x),x=null),p.writeHead(Ee,{"Content-Type":"application/json"}),p.end(JSON.stringify(J)))}};x=setTimeout(()=>{d.delete(x),x=null,P||(P=!0,p.writeHead(504,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:"Response timeout"})))},r),d.add(x),c?.(ve)}catch(w){p.writeHead(400,{"Content-Type":"application/json"}),p.end(JSON.stringify({error:w?.message??"Parse error"}))}})}function B(){return e?.port?l?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((_,p)=>{try{l=require("http").createServer(O),l.once("listening",()=>_()),l.once("error",te=>{l=null,p(te)}),l.listen(e.port,s)}catch(L){p(L)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function me(){for(let _ of d)clearTimeout(_);d.clear(),l?.close(),l=null}return{get:()=>a.get(),source:(_,p)=>a.source(_,p),status:a.status,error:a.error,requestCount:u,handler:O,listen:B,close:me}}0&&(module.exports={fromWebhook});
@@ -18,8 +18,27 @@ interface WebhookOptions {
18
18
  hostname?: string;
19
19
  /** Maximum request body size in bytes. Default: 1MB. Rejects with 413 if exceeded. */
20
20
  maxBodySize?: number;
21
+ /**
22
+ * Response timeout in milliseconds. If `respond()` is not called within this
23
+ * window, the server auto-responds with 504 Gateway Timeout.
24
+ * Default: 30000 (30s).
25
+ */
26
+ responseTimeout?: number;
21
27
  }
22
- interface WebhookStore<T = unknown> extends Store<T | undefined> {
28
+ /** A webhook request with body and response control. */
29
+ interface WebhookRequest<T = unknown> {
30
+ /** Parsed request body. */
31
+ body: T;
32
+ /**
33
+ * Send the HTTP response. May only be called once.
34
+ * @param data - Response body (JSON-serialized).
35
+ * @param statusCode - HTTP status code. Default: 200.
36
+ */
37
+ respond(data: unknown, statusCode?: number): void;
38
+ /** Whether a response has already been sent. */
39
+ responded: boolean;
40
+ }
41
+ interface WebhookStore<T = unknown> extends Store<WebhookRequest<T> | undefined> {
23
42
  /** Lifecycle status: pending → active → completed/errored. */
24
43
  status: Store<WithStatusStatus>;
25
44
  /** Last error, if any. */
@@ -38,16 +57,33 @@ interface WebhookStore<T = unknown> extends Store<T | undefined> {
38
57
  close(): void;
39
58
  }
40
59
  /**
41
- * Creates an HTTP trigger source. Emits parsed POST bodies as reactive values (Tier 2).
60
+ * Creates an HTTP trigger source. Emits `WebhookRequest<T>` objects with parsed body
61
+ * and a `respond()` method so pipelines can wire output back as the HTTP response.
42
62
  *
43
63
  * @param opts - Configuration for the webhook server.
44
64
  *
45
- * @returns `WebhookStore<T>` — reactive store with status, error, request count, handler, and lifecycle.
65
+ * @returns `WebhookStore<T>` — reactive store emitting request objects with response control.
46
66
  *
67
+ * @remarks **Request-response:** Each emitted request has a `respond(data, statusCode?)` method.
68
+ * Call it to send the HTTP response. If not called within `responseTimeout` (default 30s),
69
+ * the server auto-responds with 504 Gateway Timeout.
47
70
  * @remarks **Status:** Uses withStatus() for lifecycle tracking (pending → active → completed/errored).
48
71
  *
72
+ * @example
73
+ * ```ts
74
+ * import { fromWebhook } from 'callbag-recharge/adapters';
75
+ * import { subscribe } from 'callbag-recharge';
76
+ *
77
+ * const webhook = fromWebhook<{ input: string }>({ port: 3000, path: "/process" });
78
+ * subscribe(webhook, (req) => {
79
+ * const result = transform(req.body);
80
+ * req.respond({ output: result });
81
+ * });
82
+ * await webhook.listen();
83
+ * ```
84
+ *
49
85
  * @category adapters
50
86
  */
51
87
  declare function fromWebhook<T = unknown>(opts?: WebhookOptions): WebhookStore<T>;
52
88
 
53
- export { type WebhookOptions, type WebhookStore, fromWebhook };
89
+ export { type WebhookOptions, type WebhookRequest, type WebhookStore, fromWebhook };
@@ -18,8 +18,27 @@ interface WebhookOptions {
18
18
  hostname?: string;
19
19
  /** Maximum request body size in bytes. Default: 1MB. Rejects with 413 if exceeded. */
20
20
  maxBodySize?: number;
21
+ /**
22
+ * Response timeout in milliseconds. If `respond()` is not called within this
23
+ * window, the server auto-responds with 504 Gateway Timeout.
24
+ * Default: 30000 (30s).
25
+ */
26
+ responseTimeout?: number;
21
27
  }
22
- interface WebhookStore<T = unknown> extends Store<T | undefined> {
28
+ /** A webhook request with body and response control. */
29
+ interface WebhookRequest<T = unknown> {
30
+ /** Parsed request body. */
31
+ body: T;
32
+ /**
33
+ * Send the HTTP response. May only be called once.
34
+ * @param data - Response body (JSON-serialized).
35
+ * @param statusCode - HTTP status code. Default: 200.
36
+ */
37
+ respond(data: unknown, statusCode?: number): void;
38
+ /** Whether a response has already been sent. */
39
+ responded: boolean;
40
+ }
41
+ interface WebhookStore<T = unknown> extends Store<WebhookRequest<T> | undefined> {
23
42
  /** Lifecycle status: pending → active → completed/errored. */
24
43
  status: Store<WithStatusStatus>;
25
44
  /** Last error, if any. */
@@ -38,16 +57,33 @@ interface WebhookStore<T = unknown> extends Store<T | undefined> {
38
57
  close(): void;
39
58
  }
40
59
  /**
41
- * Creates an HTTP trigger source. Emits parsed POST bodies as reactive values (Tier 2).
60
+ * Creates an HTTP trigger source. Emits `WebhookRequest<T>` objects with parsed body
61
+ * and a `respond()` method so pipelines can wire output back as the HTTP response.
42
62
  *
43
63
  * @param opts - Configuration for the webhook server.
44
64
  *
45
- * @returns `WebhookStore<T>` — reactive store with status, error, request count, handler, and lifecycle.
65
+ * @returns `WebhookStore<T>` — reactive store emitting request objects with response control.
46
66
  *
67
+ * @remarks **Request-response:** Each emitted request has a `respond(data, statusCode?)` method.
68
+ * Call it to send the HTTP response. If not called within `responseTimeout` (default 30s),
69
+ * the server auto-responds with 504 Gateway Timeout.
47
70
  * @remarks **Status:** Uses withStatus() for lifecycle tracking (pending → active → completed/errored).
48
71
  *
72
+ * @example
73
+ * ```ts
74
+ * import { fromWebhook } from 'callbag-recharge/adapters';
75
+ * import { subscribe } from 'callbag-recharge';
76
+ *
77
+ * const webhook = fromWebhook<{ input: string }>({ port: 3000, path: "/process" });
78
+ * subscribe(webhook, (req) => {
79
+ * const result = transform(req.body);
80
+ * req.respond({ output: result });
81
+ * });
82
+ * await webhook.listen();
83
+ * ```
84
+ *
49
85
  * @category adapters
50
86
  */
51
87
  declare function fromWebhook<T = unknown>(opts?: WebhookOptions): WebhookStore<T>;
52
88
 
53
- export { type WebhookOptions, type WebhookStore, fromWebhook };
89
+ export { type WebhookOptions, type WebhookRequest, type WebhookStore, fromWebhook };
@@ -1 +1 @@
1
- import{a}from"../chunk-OGRJOWHP.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{a as fromWebhook};
1
+ import{a}from"../chunk-6M3P6NXX.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{a as fromWebhook};
@@ -0,0 +1 @@
1
+ import{a as W}from"./chunk-RX5LWE4X.js";import{a as g}from"./chunk-P5MXN4AF.js";import{i as w}from"./chunk-YN4VWXAF.js";import{a as k}from"./chunk-M76W372U.js";import{a as H}from"./chunk-I7AUKTXE.js";function U(o){let C=o?.path??"/",R=o?.parse??JSON.parse,m=o?.name??"webhook",q=o?.hostname??"0.0.0.0",v=o?.maxBodySize??1024*1024,O=o?.responseTimeout??3e4,f=g(0,{name:`${m}:count`}),p=null,h=w(({emit:t})=>(p=t,()=>{p=null}),{name:m,kind:"webhook"});k.register(h,{kind:"webhook"});let a=W(h),n=null,s=new Set;function y(t,e){let l=t.method?.toUpperCase(),x=(t.url??"/").split("?")[0];if(l!=="POST"||x!==C){e.writeHead(404,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Not found"}));return}let S=[],T=0,d=!1;t.on("error",()=>{d=!0,e.headersSent||(e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Request aborted"})))}),t.on("data",i=>{if(!d){if(T+=i.length,T>v){d=!0,e.writeHead(413,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Payload too large"})),t.destroy?.();return}S.push(i)}}),t.on("end",()=>{if(!d)try{let i=Buffer.concat(S).toString("utf-8"),j=i.length>0?R(i):void 0;f.update(c=>c+1);let u=!1,r=null,J={body:j,get responded(){return u},respond(c,B=200){u||(u=!0,r!==null&&(clearTimeout(r),s.delete(r),r=null),e.writeHead(B,{"Content-Type":"application/json"}),e.end(JSON.stringify(c)))}};r=setTimeout(()=>{s.delete(r),r=null,u||(u=!0,e.writeHead(504,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Response timeout"})))},O),s.add(r),p?.(J)}catch(i){e.writeHead(400,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:i?.message??"Parse error"}))}})}function N(){return o?.port?n?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((t,e)=>{try{n=H("http").createServer(y),n.once("listening",()=>t()),n.once("error",b=>{n=null,e(b)}),n.listen(o.port,q)}catch(l){e(l)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function P(){for(let t of s)clearTimeout(t);s.clear(),n?.close(),n=null}return{get:()=>a.get(),source:(t,e)=>a.source(t,e),status:a.status,error:a.error,requestCount:f,handler:y,listen:N,close:P}}export{U as a};
@@ -0,0 +1 @@
1
+ import{a as u}from"./chunk-P5MXN4AF.js";function w(R,m){let g=Math.max(1,m?.concurrency??1),T=m?.strategy??"fifo",s=m?.name??"asyncQueue",c=u(0,{name:`${s}.size`}),a=u(0,{name:`${s}.running`}),l=u(0,{name:`${s}.completed`}),p=u(0,{name:`${s}.failed`}),d=u(!1,{name:`${s}.paused`}),t=[],r=0,o=!1;function Q(n,e){o||(r--,a.set(r),l.update(i=>i+1),n.resolve(e),f())}function y(n,e){o||(r--,a.set(r),p.update(i=>i+1),n.reject(e),f())}function f(){if(!(o||d.get()))for(;r<g&&t.length>0;){let n=T==="lifo"?t.pop():t.shift();c.set(t.length),r++,a.set(r);try{R(n.task).then(e=>Q(n,e),e=>y(n,e))}catch(e){y(n,e)}}}function b(n){return o?Promise.reject(new Error("Queue is disposed")):new Promise((e,i)=>{t.push({task:n,resolve:e,reject:i}),c.set(t.length),f()})}function S(){d.set(!0)}function h(){d.set(!1),f()}function v(){let n=t.splice(0,t.length);c.set(0);for(let e of n)e.reject(new Error("Queue cleared"))}function k(){o||(o=!0,v())}return{enqueue:b,size:c,running:a,completed:l,failed:p,pause:S,resume:h,paused:d,clear:v,dispose:k}}export{w as a};