@callbag-recharge/callbag-recharge 0.15.0 → 0.16.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,4 +1,6 @@
1
- "use strict";var Ze=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var Rt=Object.prototype.hasOwnProperty;var Mt=(t,e)=>{for(var r in e)Ze(t,r,{get:e[r],enumerable:!0})},wt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lt(e))!Rt.call(t,s)&&s!==r&&Ze(t,s,{get:()=>e[s],enumerable:!(n=xt(e,s))||n.enumerable});return t};var It=t=>wt(Ze({},"__esModule",{value:!0}),t);var Bt={};Mt(Bt,{repeatPublish:()=>dt,subscription:()=>Tt,topic:()=>vt});module.exports=It(Bt);var L=Symbol("DIRTY"),A=Symbol("RESOLVED"),oe=Symbol("SINGLE_DEP"),ee=Symbol("RESET"),ae=Symbol("PAUSE"),ue=Symbol("RESUME"),X=Symbol("TEARDOWN");function le(t){return t===ee||t===ae||t===ue||t===X}var Ce=0,$e=1,Pe=2,Ne=3,Ve=4,qe=5,C=7,Se=7<<C,Ot=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function je(t){return Ot[(t&Se)>>>C]}var E=0,M=1,m=2,_=3,we=0,Ie=[],Xe=!1;function K(t){we++;try{return t()}finally{if(we--,we===0&&!Xe){Xe=!0;for(let e=0;e<Ie.length;e++)Ie[e]();Ie.length=0,Xe=!1}}}function Ke(){return we>0}function Fe(t){Ie.push(t)}var Ae=0,Oe=[];function fe(){Ae++}function de(){if(Ae--,Ae===0){for(let t=0;t<Oe.length;t++)Oe[t]();Oe.length=0}}function at(t){Ae>0?Oe.push(t):t()}function I(t){let e=t;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var N=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 r=t._keys.get(e)??t._names.get(e);if(r)return r;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,r){if(!t.enabled)return;r?.name&&t._names.set(e,r.name),r?.kind&&t._kinds.set(e,r.kind);let n=t._nextId++,s=r?.name;if(!(s&&!t._usedKeys.has(s)))if(s){let i=t._depSuffix(r?.deps);s=i?`${s}(${i})`:`${s}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let i=r?.kind??"store",o=t._depSuffix(r?.deps);s=o?`${i}(${o})`:`${i}_${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,r){if(!t.enabled)return;let n=t._resolveKey(e),s=t._resolveKey(r),i=t._edges.get(n);i?i.includes(s)||i.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,r=new Set;for(let n of t._stores){let s=n.deref();if(!s){t._stores.delete(n);continue}let i=t._resolveKey(s);r.add(i),e.set(i,t.inspect(s))}for(let[n,s]of t._edges){if(!r.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let i=s.filter(o=>r.has(o));i.length===0?t._edges.delete(n):i.length!==s.length&&t._edges.set(n,i)}return e}static trace(e,r){let n=null,s=e.get();return e.source(E,(i,o)=>{if(i===E&&(n=o),i===m){n=null;return}if(i===1){let a=o;if(!Object.is(a,s)){let u=s;s=a,r(a,u)}}}),()=>n?.(m)}static dumpGraph(){let e=t.graph(),r=t.getEdges(),n=new Map;for(let[o,a]of r)for(let u of a){let f=n.get(u);f?f.includes(o)||f.push(o):n.set(u,[o])}let s=[];for(let[o,a]of e){let u=n.get(o),f=r.get(o),c=u?.length?` \u2190 [${u.join(", ")}]`:"",l=f?.length?` \u2192 [${f.join(", ")}]`:"";s.push(` ${o} (${a.kind}) = ${JSON.stringify(a.value)} [${a.status??"?"}]${c}${l}`)}return[`Store Graph (${e.size} nodes):`,...s].join(`
2
- `)}static _signalLabel(e){return e===L?"DIRTY":e===A?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,r,n){let s=null,i=!1,o=r??t.getName(e),a=[],u={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return u.ended&&!i},get errored(){return u.ended&&i},dirtyCount:0,resolvedCount:0,name:o,get eventLog(){return a},dispose:()=>s?.(m),reconnect:()=>(s?.(m),t._observe(e,r,n))};return e.source(E,(f,c)=>{if(f===E){s=c;return}f===M?(u.values.push(c),u.events.push({type:"data",data:c}),a.push(c),n&&n(`[${o}] DATA:`,c)):f===_?(u.signals.push(c),u.events.push({type:"signal",data:c}),a.push(t._signalLabel(c)),c===L?u.dirtyCount++:c===A&&u.resolvedCount++,n&&n(`[${o}] STATE:`,c)):f===m&&(u.ended=!0,u.endError=c,i=c!==void 0,u.events.push({type:"end",data:c}),a.push(i?["END",c]:"END"),n&&n(`[${o}] END`,c!==void 0?c:""),s=null)}),u}static observe(e){return t._observe(e)}static activate(e){let r=null;return e.source(E,(n,s)=>{n===E&&(r=s),n===m&&(r=null)}),()=>r?.(m)}static tap(e,r){let n=r??`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,r){let n=r?.name??t.getName(e)??"spy",s=r?.log??console.log;return t._observe(e,n,s)}static snapshot(){let e=t.graph(),r=t.getEdges(),n=new Map;for(let o of t._stores){let a=o.deref();if(!a)continue;let u=t._annotations.get(a);u!==void 0&&n.set(t._resolveKey(a),u)}let s=[];for(let[o,a]of e){let u={name:o,kind:a.kind,value:a.value,status:a.status},f=n.get(o);f!==void 0&&(u.annotation=f),s.push(u)}let i=[];for(let[o,a]of r)for(let u of a)i.push({from:o,to:u});return{nodes:s,edges:i,trace:t.traceLog()}}static toMermaid(e){let r=e?.direction??"TD",n=t.snapshot(),s=[`graph ${r}`],i={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function a(c){let l=c.replace(/[^a-zA-Z0-9_]/g,"_"),d=o.get(l);return d===void 0?(o.set(l,1),l):(o.set(l,d+1),`${l}__${d}`)}let u=new Map;function f(c){let l=JSON.stringify(c);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let c of n.nodes){let l=a(c.name);u.set(c.name,l);let d=`${c.name} (${c.kind}) = ${f(c.value)}`,p=i[c.status??""]??"";s.push(` ${l}["${d}"]${p}`)}for(let c of n.edges){let l=u.get(c.from)??a(c.from),d=u.get(c.to)??a(c.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(e){let r=e?.direction??"down",n=t.snapshot(),s=[`direction: ${r}`,""],i={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function a(c){let l=c.replace(/[^a-zA-Z0-9_]/g,"_"),d=o.get(l);return d===void 0?(o.set(l,1),l):(o.set(l,d+1),`${l}__${d}`)}let u=new Map;function f(c){let l=JSON.stringify(c);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let c of n.nodes){let l=a(c.name);u.set(c.name,l);let d=i[c.kind]??"rectangle",p=`${c.name} (${c.kind}) = ${f(c.value)}`,k=c.status?` [${c.status}]`:"";s.push(`${l}: "${p}${k}" { shape: ${d} }`)}n.edges.length>0&&s.push("");for(let c of n.edges){let l=u.get(c.from)??a(c.from),d=u.get(c.to)??a(c.to);s.push(`${l} -> ${d}`)}return s.join(`
4
- `)}static annotate(e,r){if(!t.enabled)return;t._annotations.set(e,r);let n={node:t._resolveKey(e),reason:r,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 Ue=1,F=64,V=2,pe=4,ut=8,ct=16,te=32,G=1024,O=Se,he=$e<<C,be=Pe<<C,Ye=Ce<<C,At=Ve<<C,Ct=qe<<C,$t=Ne<<C,ve=class{_value;_output=null;_flags;get _status(){return je(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,r){this._value=r?.initial,this._fn=e,this._eqFn=r?.equals,this._getterFn=r?.getter,this._initial=r?.initial;let n=0;r?.autoDirty!==!1&&(n|=pe),r?.resetOnTeardown&&(n|=ut),r?.resubscribable&&(n|=ct),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),r?._skipInspect||N.register(this,{kind:"producer",...r})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,r){let n=this._output;if(n)if(this._flags&F)for(let s of n)s(e,r);else n(e,r)}emit(e){this._flags&V||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(Ke()?this._flags&te||(this._flags|=te,this._flags&pe&&(this._flags=this._flags&~O|he,this._dispatch(_,L)),Fe(()=>{this._flags&=~te,this._flags=this._flags&~O|be,this._dispatch(M,this._value)})):(this._flags&pe&&!(this._flags&G)&&(this._flags=this._flags&~O|he,this._dispatch(_,L)),this._flags=this._flags&~O|be,this._dispatch(M,this._value))))}signal(e){this._flags&V||!this._output||(e===L?this._flags=this._flags&~O|he:e===A&&(this._flags=this._flags&~O|$t),this._dispatch(_,e))}complete(){if(this._flags&V)return;this._flags=(this._flags|V)&~O|At;let e=this._output,r=this._flags&F;if(this._output=null,this._flags&=~(F|G),this._singleDepCount=0,this._stop(),e)if(r)for(let n of e)n(m);else e(m)}error(e){if(this._flags&V)return;this._flags=(this._flags|V)&~O|Ct;let r=this._output,n=this._flags&F;if(this._output=null,this._flags&=~(F|G),this._singleDepCount=0,this._stop(),r)if(n)for(let s of r)s(m,e);else r(m,e)}_start(){if(this._flags&Ue||!this._fn)return;this._flags|=Ue,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:r=>this.signal(r),complete:()=>this.complete(),error:r=>this.error(r),onSignal:r=>{this._onLifecycleSignal=r}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&Ue&&(this._flags&=~Ue,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&ut&&(this._value=this._initial),this._flags&V||(this._flags=this._flags&~O|Ye))}_handleLifecycleSignal(e){if(!(this._flags&V)){if(e===X){this._onLifecycleSignal?.(e),this.complete();return}e===ee&&(this._value=this._initial,this._flags&=~te),this._onLifecycleSignal?.(e),e===ee&&this.emit(this._initial)}}source(e,r){if(e===E){let n=r;if(this._flags&V)if(this._flags&ct&&this._output===null)this._flags=this._flags&~(V|O)|Ye;else{n(E,i=>{}),n(m);return}if(this._output===null)this._output=n;else if(this._flags&F)this._output.add(n);else{let i=new Set;i.add(this._output),i.add(n),this._output=i,this._flags=(this._flags|F)&~G}let s=!1;n(E,(i,o)=>{if(i===M&&n(M,this._value),i===_){o===oe&&!s?(s=!0,this._singleDepCount++,this._flags&F||(this._flags|=G)):le(o)&&this._handleLifecycleSignal(o);return}if(i===m){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&F){let a=this._output;a.delete(n),a.size===1?(this._output=a.values().next().value,this._flags&=~F,this._singleDepCount>0&&(this._flags|=G)):a.size===0&&(this._output=null,this._flags&=~(F|G),this._singleDepCount=0,this._flags=this._flags&~O|Ye,this._stop())}else this._output===n&&(this._output=null,this._flags&=~G,this._singleDepCount=0,this._flags=this._flags&~O|Ye,this._stop())}}),at(()=>this._start())}}};function ge(t,e){return new ve(t,e)}var et=class extends ve{constructor(e,r){super(void 0,{initial:e,autoDirty:!0,equals:r?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),N.register(this,{kind:"state",...r})}get(){return this._value}set(e){this._flags&V||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(Ke()?this._flags&te||(this._flags|=te,this._flags&pe&&(this._flags=this._flags&~O|he,this._dispatch(_,L)),Fe(()=>{this._flags&=~te,this._flags=this._flags&~O|be,this._dispatch(M,this._value)})):(this._flags&pe&&!(this._flags&G)&&(this._flags=this._flags&~O|he,this._dispatch(_,L)),this._flags=this._flags&~O|be,this._dispatch(M,this._value))))}update(e){this.set(e(this._value))}};function U(t,e){return new et(t,e)}function Ee(t,e,r){let n=new Set;for(let s of t.split(",")){let[i,o]=s.split("/"),a=o?Number.parseInt(o,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${s}`);let u,f;if(i==="*")u=e,f=r;else if(i.includes("-")){let[c,l]=i.split("-");u=Number.parseInt(c,10),f=Number.parseInt(l,10)}else u=Number.parseInt(i,10),f=u;if(Number.isNaN(u)||Number.isNaN(f))throw new Error(`Invalid cron field: ${t}`);if(u<e||f>r)throw new Error(`Cron field out of range: ${t} (${e}-${r})`);if(u>f)throw new Error(`Invalid cron range: ${u}-${f} in ${t}`);for(let c=u;c<=f;c+=a)n.add(c)}return n}function lt(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Ee(e[0],0,59),hours:Ee(e[1],0,23),daysOfMonth:Ee(e[2],1,31),months:Ee(e[3],1,12),daysOfWeek:Ee(e[4],0,6)}}function ft(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var Pt=0;function dt(t,e,r){let n=`repeat-${++Pt}`,s=r.limit??0,i=!0,o,a=U(0,{name:`${n}:count`}),u={key:r.key,headers:r.headers,dedupKey:r.dedupKey};function f(){return typeof e=="function"?e():e}function c(){if(!i)return;if(s>0&&a.get()>=s){l();return}let p={...u};r.dedupKey&&(p.dedupKey=`${r.dedupKey}:${a.get()}`),t.publish(f(),p),a.update(k=>k+1),s>0&&a.get()>=s&&l()}function l(){i&&(i=!1,o!==void 0&&(clearInterval(o),o=void 0),I(a))}if(r.every&&r.every>0)o=setInterval(c,r.every),o&&typeof o=="object"&&"unref"in o&&o.unref();else if(r.cron){let x=function(){if(!i)return;let D=new Date,h=D.getFullYear()*1e8+(D.getMonth()+1)*1e6+D.getDate()*1e4+D.getHours()*100+D.getMinutes();h!==k&&ft(p,D)&&(k=h,c())};var d=x;let p=lt(r.cron),k=0;o=setInterval(x,6e4),o&&typeof o=="object"&&"unref"in o&&o.unref(),x()}return{cancel:l,get count(){return a},get active(){return i}}}var _e=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let r=this._w;if(r===null)this._v|=1<<e;else{let n=e>>>5,s=1<<(e&31);r[n]&s||(r[n]|=s,this._v++)}}clear(e){let r=this._w;if(r===null)this._v&=~(1<<e);else{let n=e>>>5,s=1<<(e&31);r[n]&s&&(r[n]&=~s,this._v--)}}test(e){let r=this._w;return r===null?(this._v&1<<e)!==0:(r[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var ce=1,me=2,ye=4,q=8,ne=32,pt=64,Nt=Ce<<C,Te=$e<<C,tt=Pe<<C,De=Ne<<C,Vt=Ve<<C,Ge=qe<<C,w=Se,We=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return je(this._flags)}constructor(e,r,n,s){this._deps=e,this._fn=r,this._eqFn=n?.equals,this._flags=s?pt:0,this._dirtyDeps=new _e(e.length),this.source=this.source.bind(this),N.register(this,{kind:"derived",...n,deps:e});for(let i of e)N.registerEdge(i,this)}_dispatch(e,r){let n=this._output;if(n)if(this._flags&ne)for(let s of n)s(e,r);else n(e,r)}_recompute(){let e;try{e=this._fn()}catch(r){this._handleEnd(r);return}if(this._eqFn&&this._flags&ce&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~w|De,this._dispatch(_,A);return}this._cachedValue=e,this._flags=(this._flags|ce)&~w|tt,this._dispatch(M,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&q)){if(this._eqFn&&this._flags&ce&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~w|De,this._dispatch(_,A);return}this._cachedValue=e,this._flags=(this._flags|ce)&~w|tt,this._dispatch(M,e)}}_lazyConnect(){if(!(this._flags&(me|q))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|ce)&~w|tt,fe(),this._connectUpstream(),this._flags&q||(this._flags|=me),de()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&pt?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(E,(r,n)=>{if(r===E){this._upstreamTalkbacks.push(n),n(_,oe);return}if(!(this._flags&q))if(r===_)if(n===L){if(e)return;e=!0,this._flags=this._flags&~w|Te,this._dispatch(_,L)}else n===A?e&&(e=!1,this._flags=this._flags&~w|De,this._dispatch(_,A)):this._dispatch(_,n);else r===M?e?(e=!1,this._recompute()):(this._flags=this._flags&~w|Te,this._dispatch(_,L),this._recompute()):r===m&&this._handleEnd(n)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(E,(r,n)=>{if(r===E){this._upstreamTalkbacks.push(n),n(_,oe);return}this._flags&q||(r===_?n===L?(e=!0,this._flags=this._flags&~w|Te,this._dispatch(_,L)):n===A?e&&(e=!1,this._flags=this._flags&~w|De,this._dispatch(_,A)):this._dispatch(_,n):r===M?e?(e=!1,this._recomputeIdentity(n)):(this._flags=this._flags&~w|Te,this._dispatch(_,L),this._recomputeIdentity(n)):r===m&&this._handleEnd(n))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&q);e++){let r=e;this._deps[r].source(E,(n,s)=>{if(n===E){this._upstreamTalkbacks.push(s);return}if(!(this._flags&q))if(n===_)if(s===L){let i=this._dirtyDeps.empty();this._dirtyDeps.set(r),i&&(this._flags&=~ye,this._flags=this._flags&~w|Te,this._dispatch(_,L))}else s===A?this._dirtyDeps.test(r)&&(this._dirtyDeps.clear(r),this._dirtyDeps.empty()&&(this._flags&ye?this._recompute():(this._flags=this._flags&~w|De,this._dispatch(_,A)))):this._dispatch(_,s);else n===M?this._dirtyDeps.test(r)?(this._dirtyDeps.clear(r),this._flags|=ye,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~w|Te,this._dispatch(_,L),this._recompute()):this._flags|=ye:n===m&&this._handleEnd(s)})}}_handleEnd(e){this._flags|=q,this._flags=this._flags&~w|(e!==void 0?Ge:Vt),e!==void 0&&(this._cachedValue=e);for(let s of this._upstreamTalkbacks)s(m);this._upstreamTalkbacks=[],this._flags&=~me,this._dirtyDeps.reset();let r=this._output,n=this._flags&ne;if(this._output=null,this._flags&=~ne,r)if(n)for(let s of r)try{e!==void 0?s(m,e):s(m)}catch{}else e!==void 0?r(m,e):r(m)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(m);this._upstreamTalkbacks.length=0,this._flags&=~(me|ye),this._flags=this._flags&~w|Nt,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&q)){if(e===X){for(let r of this._upstreamTalkbacks)r(_,X);this._handleEnd(void 0);return}e===ee&&(this._flags&=~(ce|ye),this._dirtyDeps.reset());for(let r of this._upstreamTalkbacks)r(_,e)}}get(){if(this._flags&me)return this._cachedValue;if(this._flags&q){if((this._flags&w)===Ge)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=ce,e}source(e,r){if(e===E){let n=r;if(this._flags&q){let s=(this._flags&w)===Ge;n(E,i=>{}),s?n(m,this._cachedValue):n(m);return}if(!(this._flags&me)&&(this._lazyConnect(),this._flags&q)){let s=(this._flags&w)===Ge;n(E,i=>{}),s?n(m,this._cachedValue):n(m);return}if(this._output===null)this._output=n;else if(this._flags&ne)this._output.add(n);else{let s=new Set;s.add(this._output),s.add(n),this._output=s,this._flags|=ne}n(E,(s,i)=>{if(s===M&&n(M,this._cachedValue),s===_&&le(i)){this._handleLifecycleSignal(i);return}if(s===m){if(this._output===null)return;if(this._flags&ne){let o=this._output;o.delete(n),o.size===1?(this._output=o.values().next().value,this._flags&=~ne):o.size===0&&(this._output=null,this._flags&=~ne,this._disconnectUpstream())}else this._output===n&&(this._output=null,this._disconnectUpstream())}})}}};function W(t,e,r){return new We(t,e,r)}(e=>{function t(r,n){return new We([r],()=>r.get(),n,!0)}e.from=t})(W||={});function ht(t,e,r){let n,s=[],i=!1,o=new _e(t.length),a=!1;function u(){i||(n&&n(),n=e())}let f=0;function c(d){if(!i){if(d===X){for(let p of s)p(_,X);s.length=0,i=!0,n&&n(),n=void 0;return}d===ee&&(f++,o.reset(),a=!1,u());for(let p of s)p(_,d)}}fe(),u();for(let d=0;d<t.length&&!i;d++){let p=d,k=f;t[p].source(E,(x,D)=>{if(x===E){s.push(D),t.length===1&&D(_,oe);return}if(!i){if(x===_){if(le(D)){c(D),k=f;return}if(k!==f)return;D===L?(o.empty()&&(a=!1),o.set(p)):D===A&&o.test(p)&&(o.clear(p),o.empty()&&a&&u())}if(x===M){if(k!==f)return;o.test(p)?(o.clear(p),a=!0,o.empty()&&u()):o.empty()?u():a=!0}if(x===m){i=!0,n&&n(),n=void 0;for(let h of s)h(m);s.length=0}}})}de();let l=()=>{if(!i){i=!0,n&&n(),n=void 0;for(let d of s)d(m);s.length=0}};l.signal=d=>c(d),N.register(l,{kind:"effect",...r,deps:t});for(let d of t)N.registerEdge(d,l);return l}function qt(t){return t!=null&&typeof t.then=="function"}function jt(t){return t!=null&&typeof t.subscribe=="function"}function Kt(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}function Ft(t){return t!=null&&typeof t[Symbol.iterator]=="function"}function gt(t){return qt(t)?ge(({emit:e,complete:r,error:n})=>{let s=!1;return t.then(i=>{s||(e(i),r())},i=>{s||n(i)}),()=>{s=!0}}):jt(t)?ge(({emit:e,complete:r,error:n})=>{let s=!1,i=t.subscribe({next:o=>{s||e(o)},error:o=>{s||n(o)},complete:()=>{s||r()}});return()=>{s=!0,i.unsubscribe()}}):Kt(t)?ge(({emit:e,complete:r,error:n})=>{let s=new AbortController,i=s.signal,o=!1,a=t[Symbol.asyncIterator]();async function u(){try{for(;!o&&!i.aborted;){let f=await a.next();if(o||i.aborted)break;if(f.done){r();return}e(f.value)}}catch(f){!o&&!i.aborted&&n(f)}}return u(),()=>{o=!0,s.abort(),Promise.resolve(a.return?.()).catch(()=>{})}},{resubscribable:!0}):typeof t!="string"&&Ft(t)?ge(({emit:e,complete:r})=>{for(let n of t)e(n);r()}):ge(({emit:e,complete:r})=>{e(t),r()})}function mt(t){let e=t?.base??100,r=t?.factor??2,n=t?.maxDelay??3e4,s=t?.jitter??"none";return i=>{let o=Math.min(e*r**i,n);return Ut(o,s)}}function Ut(t,e){switch(e){case"none":return t;case"full":return _t(0,t);case"equal":return t/2+_t(0,t/2)}}function _t(t,e){return t+Math.random()*(e-t)}var Yt=Symbol.for("callbag-recharge:topic-internal"),Gt=Symbol.for("callbag-recharge:topic-log"),Wt=0;function yt(t){return{seq:t.seq,value:t.value.value,timestamp:t.value.timestamp,key:t.value.key,priority:t.value.priority,headers:t.value.headers}}function Tt(t,e){let r=`sub-${++Wt}`,n=e?.name??r,s=e?.mode??"exclusive",i=e?.batchSize??1,o=e?.ackTimeout??3e4,a=t[Yt],u=t[Gt],f,c=s==="shared"||s==="failover"||s==="key_shared",l;c?(l=a.getOrCreateGroup(n),l.consumers.add(r),l.consumers.size===1&&(l.cursor=d()),f=l.cursor):f=d();function d(){return e?.initialPosition==="earliest"?u.headSeq>0?u.headSeq:1:typeof e?.initialPosition=="number"?e.initialPosition:u.tailSeq+1}let p=new Map,k=new Map,x=[],D=e?.retry?.maxRetries??3,h=e?.retry?.backoff??mt(),S=e?.deadLetterTopic,R=!1,z=!1,j=U(f,{name:`${n}:pos`}),$=U(0,{name:`${n}:pending`}),se=W([u.lengthStore,u.events,j],()=>{let g=u.tailSeq,y=j.get(),v=u.headSeq,Q=v>0?Math.max(y,v):y;return Math.max(0,g-Q+1)},{name:`${n}:backlog`}),H=e?.persistence;function B(){H&&Promise.resolve(H.save(`${n}:cursor`,f)).catch(()=>{})}function T(){return s!=="failover"||!l?!0:l.consumers.values().next().value===r}function b(g){let y=0;for(let v=0;v<g.length;v++)y=(y<<5)-y+g.charCodeAt(v)|0;return Math.abs(y)}function re(g){if(s!=="key_shared"||!l||!g)return!0;let y=Array.from(l.consumers),v=b(g)%y.length;return y[v]===r}function ke(g){if(R||z)return[];if(!T())return[];let y=g??i,v=[],Q=Date.now(),ie=[],xe=[];for(let Y of x)Y.readyAt<=Q&&ie.length<y?ie.push(Y):xe.push(Y);x.length=0,x.push(...xe);for(let Y of ie){let Re=u.get(Y.seq);if(Re){let Me=yt(Re);v.push(Me),Be(Y.seq)}}let it=y-v.length,Le=-1;if(it>0){let Y=c&&l?l.cursor:f,Re=u.tailSeq,Me=0;for(let Z=Y;Z<=Re&&Me<it;Z++){let Qe=u.get(Z);if(!Qe||s==="key_shared"&&!re(Qe.value.key))continue;if(s==="shared"&&l&&l.consumers.size>1){let ot=Array.from(l.consumers),kt=l.roundRobinIndex%ot.length;if(ot[kt]!==r)continue;l.roundRobinIndex++}let Dt=yt(Qe);v.push(Dt),Be(Z),Z>Le&&(Le=Z),Me++}if(Le>=0){let Z=Le+1;c&&l&&(l.cursor=Math.max(l.cursor,Z)),f=c&&l?l.cursor:Z}}return v.length>0&&K(()=>{j.set(f),$.update(Y=>Y+v.length)}),v}function Be(g){let y;o>0&&(y=setTimeout(()=>{p.has(g)&&nt(g)},o)),p.set(g,{timer:y})}function J(g){let y=p.get(g);y&&(y.timer&&clearTimeout(y.timer),p.delete(g),k.delete(g),$.update(v=>Math.max(0,v-1)),B())}function P(g,y){if(S){let v=u.get(g);v&&S.publish(v.value.value,{key:v.value.key,headers:{...v.value.headers,"x-original-topic":t.name,"x-retry-count":String(y),"x-original-seq":String(g)}})}k.delete(g)}function nt(g){let y=p.get(g);if(!y)return;y.timer&&clearTimeout(y.timer),p.delete(g),$.update(xe=>Math.max(0,xe-1));let v=k.get(g)??{attempts:0},Q=v.attempts+1;if(Q>D){P(g,Q);return}let ie=h(Q-1,void 0,v.prevDelay);if(ie===null){P(g,Q);return}k.set(g,{attempts:Q,prevDelay:ie}),x.push({seq:g,readyAt:Date.now()+ie})}function st(g){if(z)return;let y;g==="earliest"?y=u.headSeq>0?u.headSeq:1:g==="latest"?y=u.tailSeq+1:y=g,f=y,c&&l&&(l.cursor=y),j.set(y);for(let v of p.values())v.timer&&clearTimeout(v.timer);p.clear(),$.set(0),x.length=0,k.clear(),B()}let rt,Je;if(H){let g=gt(H.load(`${n}:cursor`));Je=g,rt=ht([g],()=>{let y=g.get();typeof y=="number"&&st(y)})}function Et(){if(!z){z=!0,rt?.(),Je&&I(Je);for(let g of p.values())g.timer&&clearTimeout(g.timer);p.clear(),x.length=0,k.clear(),l&&(l.consumers.delete(r),l.consumers.size===0&&a.removeGroup(n)),K(()=>{I(j),I($),I(se)})}}return{get name(){return n},get mode(){return s},pull:ke,ack:J,nack:nt,seek:st,position:j,backlog:se,pending:$,pause(){R||(R=!0,j.signal(ae),$.signal(ae))},resume(){R&&(R=!1,j.signal(ue),$.signal(ue))},get isPaused(){return R},destroy:Et}}function St(t,e,r){let n=null;fe(),t.source(E,(i,o)=>{if(i===E&&(n=o),i===m){n=null,r?.onEnd?.(o);return}if(i===1){let a=o,u=s;s=a,e(a,u)}});let s;try{s=t.get()}catch{}return de(),{unsubscribe(){n?.(m),n=null},signal(i){n?.(_,i)}}}function bt(t,e,r){let n=r?.threshold??0,s=null,i=!1;function o(){if(i)return 0;let a=t.toArray();if(a.length===0)return 0;let u=new Map,f=[];for(let d of a){let p=e(d.value);u.has(p)||f.push(p),u.set(p,d.value)}let c=f.map(d=>u.get(d)),l=a.length-c.length;if(l===0)return 0;i=!0;try{t.clear(),t.appendMany(c)}finally{i=!1}return l}return n>0&&(s=St(t.events,a=>{a?.type==="append"&&t.length>=n&&o()})),{compact:o,destroy(){s?.unsubscribe(),s=null}}}var zt=0;ze.from=function(e,r){let n=ze({...r,id:e.id});for(let s of e.entries)n.append(s.value);return n};function ze(t){let e=++zt,r=t?.id??`rlog-${e}`,n=t?.maxSize??0,s=n>0,i=[],o=0,a=0,u=0,f=1,c=U(0,{name:`${r}:ver`}),l=U(void 0,{name:`${r}:events`,equals:()=>!1}),d=new Map,p=!1;function k(){if(!s)return i.slice();if(a===0)return[];let h=new Array(a);for(let S=0;S<a;S++)h[S]=i[(o+S)%n];return h}function x(h){if(!s)return i[h];if(!(h<0||h>=a))return i[(o+h)%n]}let D={get id(){return r},get version(){return c.get()},append(h){if(p)return-1;let S=++u,R={seq:S,value:h};return s?(a<n?(i[(o+a)%n]=R,a++):(i[o]=R,o=(o+1)%n),f=u-a+1):(i.push(R),f=i.length>0?i[0].seq:1),c.update(z=>z+1),l.set({type:"append",seq:S,value:h}),S},appendMany(h){if(p||h.length===0)return[];let S=[];return K(()=>{for(let R of h)S.push(D.append(R))}),S},get(h){if(s)return h<f||h>u||a===0?void 0:x(h-f);let S=h-f;if(!(S<0||S>=i.length))return i[S]},slice(h,S){let R=h??f,z=S??u;if((s?a:i.length)===0)return[];let $=Math.max(R,f),se=Math.min(z,u);if($>se)return[];let H=$-f,B=se-f;if(!s)return i.slice(H,B+1);let T=[];for(let b=H;b<=B;b++)T.push(i[(o+b)%n]);return T},toArray(){return k()},get length(){return s?a:i.length},get headSeq(){return(s?a:i.length)>0?f:0},get tailSeq(){return u},clear(){(s?a:i.length)!==0&&K(()=>{s?(a=0,o=0):i.length=0,f=u+1,c.update(S=>S+1),l.set({type:"clear"})})},lengthStore:W([c],()=>s?a:i.length,{name:`${r}:length`}),latest:W([c],()=>{if((s?a:i.length)!==0)return s?i[(o+a-1)%n]:i[i.length-1]},{name:`${r}:latest`}),tail(h){let S=d.get(h);return S||(S=W([c],()=>{let R=k();return h===void 0||h>=R.length?R:R.slice(-h)},{name:`${r}:tail${h??""}`}),d.set(h,S),S)},events:l,snapshot(){return{type:"reactiveLog",id:r,version:c.get(),entries:k().map(h=>({seq:h.seq,value:h.value})),headSeq:(s?a:i.length)>0?f:0,tailSeq:u}},destroy(){p||(p=!0,K(()=>{for(let h of d.values())I(h);d.clear(),I(D.lengthStore),I(D.latest),I(l),I(c),i.length=0,a=0}))}};return D}var Ht=0;function He(t){return{seq:t.seq,value:t.value.value,timestamp:t.value.timestamp,key:t.value.key,priority:t.value.priority,headers:t.value.headers}}function vt(t,e){let r=++Ht,n=e?.namespace,s=n?n.prefix(t):t,i=`topic-${s}-${r}`,o=ze({id:`${i}:log`,maxSize:e?.maxSize}),a;if(e?.compaction){let T=e.compaction.keyFn;a=bt(o,b=>T(b.value),{threshold:e.compaction.threshold})}let u=e?.dedup?.windowMs??6e4,f=new Map,c;u>0&&(c=setInterval(()=>{let T=Date.now();for(let[b,re]of f)T-re>=u&&f.delete(b)},Math.min(u,3e4)),c&&typeof c=="object"&&"unref"in c&&c.unref());let l=!1,d=!1,p=new Set,k=new Map,x=U(0,{name:`${i}:pubCount`}),D=U(0,{name:`${i}:ver`}),h=o.lengthStore,S=W([o.latest],()=>{let T=o.latest.get();return T?He(T):void 0},{name:`${i}:latest`}),R=e?.schema,z=e?.persistence?n?n.checkpoint(e.persistence):e.persistence:void 0,j={getOrCreateGroup(T){let b=k.get(T);return b||(b={cursor:o.tailSeq+1,roundRobinIndex:0,consumers:new Set},k.set(T,b)),b},removeGroup(T){k.delete(T)}};function $(T,b){if(d||l)return-1;R&&(T=R.parse(T));let re=b?.dedupKey;if(re){let J=Date.now(),P=f.get(re);if(P!==void 0&&J-P<u)return-1;f.set(re,J)}let ke={value:T,timestamp:Date.now(),key:b?.key,priority:b?.priority,headers:b?.headers};if(b?.delay&&b.delay>0){let J=setTimeout(()=>{p.delete(J),!d&&!l&&K(()=>{o.append(ke),x.update(P=>P+1),D.update(P=>P+1)})},b.delay);return p.add(J),-1}return K(()=>{let J=o.append(ke);return x.update(P=>P+1),D.update(P=>P+1),J})}function se(T){let b=o.get(T);return b?He(b):void 0}function H(T,b){return o.slice(T,b).map(He)}let B={get id(){return i},get version(){return D.get()},get name(){return s},publish:$,get(T){return se(T)},slice(T,b){return H(T,b)},get headSeq(){return o.headSeq},get tailSeq(){return o.tailSeq},depth:h,latest:S,publishCount:x,peek(){if(o.length===0)return;let T=o.get(o.headSeq);return T?He(T):void 0},pause(){if(!l){l=!0;for(let T of p)clearTimeout(T);p.clear(),x.signal(ae),D.signal(ae)}},resume(){l&&(l=!1,x.signal(ue),D.signal(ue))},get paused(){return l},destroy(){if(!d){d=!0;for(let T of p)clearTimeout(T);p.clear(),c&&clearInterval(c),f.clear(),a?.destroy(),K(()=>{I(x),I(D),I(S),o.destroy()}),k.clear()}}};return B[Symbol.for("callbag-recharge:topic-internal")]=j,B[Symbol.for("callbag-recharge:topic-log")]=o,B}0&&(module.exports={repeatPublish,subscription,topic});
1
+ "use strict";var st=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var At=Object.prototype.hasOwnProperty;var Ot=(t,e)=>{for(var r in e)st(t,r,{get:e[r],enumerable:!0})},$t=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of It(e))!At.call(t,s)&&s!==r&&st(t,s,{get:()=>e[s],enumerable:!(n=Mt(e,s))||n.enumerable});return t};var Ct=t=>$t(st({},"__esModule",{value:!0}),t);var Xt={};Ot(Xt,{jobFlow:()=>dt,jobQueue:()=>Et,repeatPublish:()=>wt,subscription:()=>Ze,topic:()=>tt});module.exports=Ct(Xt);function dt(t,e,r){let n=r?.name??"jobFlow",s=[];for(let u of e){if(!t[u.from])throw new Error(`jobFlow: source queue "${u.from}" not found`);if(!t[u.to])throw new Error(`jobFlow: destination queue "${u.to}" not found`)}for(let u of e){let f=t[u.from],a=t[u.to],l=f.on("completed",p=>{let h=u.transform?u.transform(p.result):p.result;a.add(h)});s.push(l)}function i(){let u=[];u.push("graph LR");let f=Object.keys(t);for(let a of f)u.push(` ${c(a)}["${a}"]`);for(let a of e){let l=a.transform?"transform":"",p=c(a.from),h=c(a.to);l?u.push(` ${p} -->|${l}| ${h}`):u.push(` ${p} --> ${h}`)}return u.join(`
2
+ `)}function o(){let u=[],f=Object.keys(t);for(let a of f)u.push(`${c(a)}: ${a}`);for(let a of e){let l=c(a.from),p=c(a.to),h=a.transform?": transform":"";u.push(`${l} -> ${p}${h}`)}return u.join(`
3
+ `)}function c(u){return u.replace(/[^a-zA-Z0-9_]/g,"_")}return{get name(){return n},queues:t,toMermaid:i,toD2:o,destroy(){for(let u of s)u();s.length=0}}}var A=Symbol("DIRTY"),J=Symbol("RESOLVED"),fe=Symbol("SINGLE_DEP"),ie=Symbol("RESET"),de=Symbol("PAUSE"),pe=Symbol("RESUME"),re=Symbol("TEARDOWN");function ge(t){return t===ie||t===de||t===pe||t===re}var Ne=0,Ve=1,qe=2,Je=3,je=4,Fe=5,j=7,De=7<<j,Pt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Ke(t){return Pt[(t&De)>>>j]}var x=0,O=1,T=2,y=3,Oe=0,$e=[],it=!1;function N(t){Oe++;try{return t()}finally{if(Oe--,Oe===0&&!it){it=!0;for(let e=0;e<$e.length;e++)$e[e]();$e.length=0,it=!1}}}function Ue(){return Oe>0}function Ye(t){$e.push(t)}var Pe=0,Ce=[];function me(){Pe++}function _e(){if(Pe--,Pe===0){for(let t=0;t<Ce.length;t++)Ce[t]();Ce.length=0}}function pt(t){Pe>0?Ce.push(t):t()}function M(t){let e=t;typeof e.complete=="function"?e.complete():typeof e._handleEnd=="function"&&e._handleEnd(void 0)}var Y=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 r=t._keys.get(e)??t._names.get(e);if(r)return r;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,r){if(!t.enabled)return;r?.name&&t._names.set(e,r.name),r?.kind&&t._kinds.set(e,r.kind);let n=t._nextId++,s=r?.name;if(!(s&&!t._usedKeys.has(s)))if(s){let i=t._depSuffix(r?.deps);s=i?`${s}(${i})`:`${s}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let i=r?.kind??"store",o=t._depSuffix(r?.deps);s=o?`${i}(${o})`:`${i}_${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,r){if(!t.enabled)return;let n=t._resolveKey(e),s=t._resolveKey(r),i=t._edges.get(n);i?i.includes(s)||i.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,r=new Set;for(let n of t._stores){let s=n.deref();if(!s){t._stores.delete(n);continue}let i=t._resolveKey(s);r.add(i),e.set(i,t.inspect(s))}for(let[n,s]of t._edges){if(!r.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let i=s.filter(o=>r.has(o));i.length===0?t._edges.delete(n):i.length!==s.length&&t._edges.set(n,i)}return e}static trace(e,r){let n=null,s=e.get();return e.source(x,(i,o)=>{if(i===x&&(n=o),i===T){n=null;return}if(i===1){let c=o;if(!Object.is(c,s)){let u=s;s=c,r(c,u)}}}),()=>n?.(T)}static dumpGraph(){let e=t.graph(),r=t.getEdges(),n=new Map;for(let[o,c]of r)for(let u of c){let f=n.get(u);f?f.includes(o)||f.push(o):n.set(u,[o])}let s=[];for(let[o,c]of e){let u=n.get(o),f=r.get(o),a=u?.length?` \u2190 [${u.join(", ")}]`:"",l=f?.length?` \u2192 [${f.join(", ")}]`:"";s.push(` ${o} (${c.kind}) = ${JSON.stringify(c.value)} [${c.status??"?"}]${a}${l}`)}return[`Store Graph (${e.size} nodes):`,...s].join(`
4
+ `)}static _signalLabel(e){return e===A?"DIRTY":e===J?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,r,n){let s=null,i=!1,o=r??t.getName(e),c=[],u={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return u.ended&&!i},get errored(){return u.ended&&i},dirtyCount:0,resolvedCount:0,name:o,get eventLog(){return c},dispose:()=>s?.(T),reconnect:()=>(s?.(T),t._observe(e,r,n))};return e.source(x,(f,a)=>{if(f===x){s=a;return}f===O?(u.values.push(a),u.events.push({type:"data",data:a}),c.push(a),n&&n(`[${o}] DATA:`,a)):f===y?(u.signals.push(a),u.events.push({type:"signal",data:a}),c.push(t._signalLabel(a)),a===A?u.dirtyCount++:a===J&&u.resolvedCount++,n&&n(`[${o}] STATE:`,a)):f===T&&(u.ended=!0,u.endError=a,i=a!==void 0,u.events.push({type:"end",data:a}),c.push(i?["END",a]:"END"),n&&n(`[${o}] END`,a!==void 0?a:""),s=null)}),u}static observe(e){return t._observe(e)}static activate(e){let r=null;return e.source(x,(n,s)=>{n===x&&(r=s),n===T&&(r=null)}),()=>r?.(T)}static tap(e,r){let n=r??`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,r){let n=r?.name??t.getName(e)??"spy",s=r?.log??console.log;return t._observe(e,n,s)}static snapshot(){let e=t.graph(),r=t.getEdges(),n=new Map;for(let o of t._stores){let c=o.deref();if(!c)continue;let u=t._annotations.get(c);u!==void 0&&n.set(t._resolveKey(c),u)}let s=[];for(let[o,c]of e){let u={name:o,kind:c.kind,value:c.value,status:c.status},f=n.get(o);f!==void 0&&(u.annotation=f),s.push(u)}let i=[];for(let[o,c]of r)for(let u of c)i.push({from:o,to:u});return{nodes:s,edges:i,trace:t.traceLog()}}static toMermaid(e){let r=e?.direction??"TD",n=t.snapshot(),s=[`graph ${r}`],i={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function c(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),p=o.get(l);return p===void 0?(o.set(l,1),l):(o.set(l,p+1),`${l}__${p}`)}let u=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=c(a.name);u.set(a.name,l);let p=`${a.name} (${a.kind}) = ${f(a.value)}`,h=i[a.status??""]??"";s.push(` ${l}["${p}"]${h}`)}for(let a of n.edges){let l=u.get(a.from)??c(a.from),p=u.get(a.to)??c(a.to);s.push(` ${l} --> ${p}`)}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(`
5
+ `)}static toD2(e){let r=e?.direction??"down",n=t.snapshot(),s=[`direction: ${r}`,""],i={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function c(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),p=o.get(l);return p===void 0?(o.set(l,1),l):(o.set(l,p+1),`${l}__${p}`)}let u=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=c(a.name);u.set(a.name,l);let p=i[a.kind]??"rectangle",h=`${a.name} (${a.kind}) = ${f(a.value)}`,k=a.status?` [${a.status}]`:"";s.push(`${l}: "${h}${k}" { shape: ${p} }`)}n.edges.length>0&&s.push("");for(let a of n.edges){let l=u.get(a.from)??c(a.from),p=u.get(a.to)??c(a.to);s.push(`${l} -> ${p}`)}return s.join(`
6
+ `)}static annotate(e,r){if(!t.enabled)return;t._annotations.set(e,r);let n={node:t._resolveKey(e),reason:r,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 We=1,B=64,W=2,ye=4,ht=8,gt=16,oe=32,Z=1024,V=De,be=Ve<<j,ke=qe<<j,Ge=Ne<<j,Nt=je<<j,Vt=Fe<<j,qt=Je<<j,we=class{_value;_output=null;_flags;get _status(){return Ke(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(e,r){this._value=r?.initial,this._fn=e,this._eqFn=r?.equals,this._getterFn=r?.getter,this._initial=r?.initial;let n=0;r?.autoDirty!==!1&&(n|=ye),r?.resetOnTeardown&&(n|=ht),r?.resubscribable&&(n|=gt),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),r?._skipInspect||Y.register(this,{kind:"producer",...r})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,r){let n=this._output;if(n)if(this._flags&B)for(let s of n)s(e,r);else n(e,r)}emit(e){this._flags&W||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(Ue()?this._flags&oe||(this._flags|=oe,this._flags&ye&&(this._flags=this._flags&~V|be,this._dispatch(y,A)),Ye(()=>{this._flags&=~oe,this._flags=this._flags&~V|ke,this._dispatch(O,this._value)})):(this._flags&ye&&!(this._flags&Z)&&(this._flags=this._flags&~V|be,this._dispatch(y,A)),this._flags=this._flags&~V|ke,this._dispatch(O,this._value))))}signal(e){this._flags&W||!this._output||(e===A?this._flags=this._flags&~V|be:e===J&&(this._flags=this._flags&~V|qt),this._dispatch(y,e))}complete(){if(this._flags&W)return;this._flags=(this._flags|W)&~V|Nt;let e=this._output,r=this._flags&B;if(this._output=null,this._flags&=~(B|Z),this._singleDepCount=0,this._stop(),e)if(r)for(let n of e)n(T);else e(T)}error(e){if(this._flags&W)return;this._flags=(this._flags|W)&~V|Vt;let r=this._output,n=this._flags&B;if(this._output=null,this._flags&=~(B|Z),this._singleDepCount=0,this._stop(),r)if(n)for(let s of r)s(T,e);else r(T,e)}_start(){if(this._flags&We||!this._fn)return;this._flags|=We,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:r=>this.signal(r),complete:()=>this.complete(),error:r=>this.error(r),onSignal:r=>{this._onLifecycleSignal=r}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&We&&(this._flags&=~We,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&ht&&(this._value=this._initial),this._flags&W||(this._flags=this._flags&~V|Ge))}_handleLifecycleSignal(e){if(!(this._flags&W)){if(e===re){this._onLifecycleSignal?.(e),this.complete();return}e===ie&&(this._value=this._initial,this._flags&=~oe),this._onLifecycleSignal?.(e),e===ie&&this.emit(this._initial)}}source(e,r){if(e===x){let n=r;if(this._flags&W)if(this._flags&gt&&this._output===null)this._flags=this._flags&~(W|V)|Ge;else{n(x,i=>{}),n(T);return}if(this._output===null)this._output=n;else if(this._flags&B)this._output.add(n);else{let i=new Set;i.add(this._output),i.add(n),this._output=i,this._flags=(this._flags|B)&~Z}let s=!1;n(x,(i,o)=>{if(i===O&&n(O,this._value),i===y){o===fe&&!s?(s=!0,this._singleDepCount++,this._flags&B||(this._flags|=Z)):ge(o)&&this._handleLifecycleSignal(o);return}if(i===T){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&B){let c=this._output;c.delete(n),c.size===1?(this._output=c.values().next().value,this._flags&=~B,this._singleDepCount>0&&(this._flags|=Z)):c.size===0&&(this._output=null,this._flags&=~(B|Z),this._singleDepCount=0,this._flags=this._flags&~V|Ge,this._stop())}else this._output===n&&(this._output=null,this._flags&=~Z,this._singleDepCount=0,this._flags=this._flags&~V|Ge,this._stop())}}),pt(()=>this._start())}}};function ae(t,e){return new we(t,e)}var ot=class extends we{constructor(e,r){super(void 0,{initial:e,autoDirty:!0,equals:r?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),Y.register(this,{kind:"state",...r})}get(){return this._value}set(e){this._flags&W||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(Ue()?this._flags&oe||(this._flags|=oe,this._flags&ye&&(this._flags=this._flags&~V|be,this._dispatch(y,A)),Ye(()=>{this._flags&=~oe,this._flags=this._flags&~V|ke,this._dispatch(O,this._value)})):(this._flags&ye&&!(this._flags&Z)&&(this._flags=this._flags&~V|be,this._dispatch(y,A)),this._flags=this._flags&~V|ke,this._dispatch(O,this._value))))}update(e){this.set(e(this._value))}};function q(t,e){return new ot(t,e)}function ze(t,e,r){let n=null;me(),t.source(x,(i,o)=>{if(i===x&&(n=o),i===T){n=null,r?.onEnd?.(o);return}if(i===1){let c=o,u=s;s=c,e(c,u)}});let s;try{s=t.get()}catch{}return _e(),{unsubscribe(){n?.(T),n=null},signal(i){n?.(y,i)}}}function at(t,e){return new Promise((r,n)=>{let s=t.get();if(!e||e(s)){r(s);return}let i=ze(t,o=>{(!e||e(o))&&(i.unsubscribe(),r(o))},{onEnd:o=>{n(o??new Error("source completed without matching value"))}})})}function mt(t,e){return ae(({emit:r,complete:n})=>{if(e?.aborted){r(void 0),n();return}let s=!1,i=setTimeout(()=>{s||(s=!0,c(),r(void 0),n())},t);function o(){s||(s=!0,clearTimeout(i),r(void 0),n())}e?.addEventListener("abort",o,{once:!0});function c(){e?.removeEventListener("abort",o)}return()=>{s||(s=!0,clearTimeout(i),c())}})}function He(t){let e=t?.base??100,r=t?.factor??2,n=t?.maxDelay??3e4,s=t?.jitter??"none";return i=>{let o=Math.min(e*r**i,n);return Jt(o,s)}}function Jt(t,e){switch(e){case"none":return t;case"full":return _t(0,t);case"equal":return t/2+_t(0,t/2)}}function _t(t,e){return t+Math.random()*(e-t)}var Te=class{_v;_w;constructor(e){this._v=0,this._w=e>32?new Uint32Array((e-1>>>5)+1):null}set(e){let r=this._w;if(r===null)this._v|=1<<e;else{let n=e>>>5,s=1<<(e&31);r[n]&s||(r[n]|=s,this._v++)}}clear(e){let r=this._w;if(r===null)this._v&=~(1<<e);else{let n=e>>>5,s=1<<(e&31);r[n]&s&&(r[n]&=~s,this._v--)}}test(e){let r=this._w;return r===null?(this._v&1<<e)!==0:(r[e>>>5]&1<<(e&31))!==0}empty(){return this._v===0}reset(){this._v=0,this._w?.fill(0)}};var he=1,Se=2,ve=4,G=8,ue=32,yt=64,jt=Ne<<j,Ee=Ve<<j,ut=qe<<j,Re=Je<<j,Ft=je<<j,Be=Fe<<j,$=De,Qe=class{_output=null;_upstreamTalkbacks=[];_cachedValue;_flags;_dirtyDeps;_eqFn;_deps;_fn;get _status(){return Ke(this._flags)}constructor(e,r,n,s){this._deps=e,this._fn=r,this._eqFn=n?.equals,this._flags=s?yt:0,this._dirtyDeps=new Te(e.length),this.source=this.source.bind(this),Y.register(this,{kind:"derived",...n,deps:e});for(let i of e)Y.registerEdge(i,this)}_dispatch(e,r){let n=this._output;if(n)if(this._flags&ue)for(let s of n)s(e,r);else n(e,r)}_recompute(){let e;try{e=this._fn()}catch(r){this._handleEnd(r);return}if(this._eqFn&&this._flags&he&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~$|Re,this._dispatch(y,J);return}this._cachedValue=e,this._flags=(this._flags|he)&~$|ut,this._dispatch(O,this._cachedValue)}_recomputeIdentity(e){if(!(this._flags&G)){if(this._eqFn&&this._flags&he&&this._eqFn(this._cachedValue,e)){this._flags=this._flags&~$|Re,this._dispatch(y,J);return}this._cachedValue=e,this._flags=(this._flags|he)&~$|ut,this._dispatch(O,e)}}_lazyConnect(){if(!(this._flags&(Se|G))){try{this._cachedValue=this._fn()}catch(e){this._handleEnd(e);return}this._flags=(this._flags|he)&~$|ut,me(),this._connectUpstream(),this._flags&G||(this._flags|=Se),_e()}}_connectUpstream(){this._upstreamTalkbacks.length=0,this._deps.length===1?this._flags&yt?this._connectSingleDepIdentity():this._connectSingleDep():this._connectMultiDep()}_connectSingleDep(){let e=!1;this._deps[0].source(x,(r,n)=>{if(r===x){this._upstreamTalkbacks.push(n),n(y,fe);return}if(!(this._flags&G))if(r===y)if(n===A){if(e)return;e=!0,this._flags=this._flags&~$|Ee,this._dispatch(y,A)}else n===J?e&&(e=!1,this._flags=this._flags&~$|Re,this._dispatch(y,J)):this._dispatch(y,n);else r===O?e?(e=!1,this._recompute()):(this._flags=this._flags&~$|Ee,this._dispatch(y,A),this._recompute()):r===T&&this._handleEnd(n)})}_connectSingleDepIdentity(){let e=!1;this._deps[0].source(x,(r,n)=>{if(r===x){this._upstreamTalkbacks.push(n),n(y,fe);return}this._flags&G||(r===y?n===A?(e=!0,this._flags=this._flags&~$|Ee,this._dispatch(y,A)):n===J?e&&(e=!1,this._flags=this._flags&~$|Re,this._dispatch(y,J)):this._dispatch(y,n):r===O?e?(e=!1,this._recomputeIdentity(n)):(this._flags=this._flags&~$|Ee,this._dispatch(y,A),this._recomputeIdentity(n)):r===T&&this._handleEnd(n))})}_connectMultiDep(){for(let e=0;e<this._deps.length&&!(this._flags&G);e++){let r=e;this._deps[r].source(x,(n,s)=>{if(n===x){this._upstreamTalkbacks.push(s);return}if(!(this._flags&G))if(n===y)if(s===A){let i=this._dirtyDeps.empty();this._dirtyDeps.set(r),i&&(this._flags&=~ve,this._flags=this._flags&~$|Ee,this._dispatch(y,A))}else s===J?this._dirtyDeps.test(r)&&(this._dirtyDeps.clear(r),this._dirtyDeps.empty()&&(this._flags&ve?this._recompute():(this._flags=this._flags&~$|Re,this._dispatch(y,J)))):this._dispatch(y,s);else n===O?this._dirtyDeps.test(r)?(this._dirtyDeps.clear(r),this._flags|=ve,this._dirtyDeps.empty()&&this._recompute()):this._dirtyDeps.empty()?(this._flags=this._flags&~$|Ee,this._dispatch(y,A),this._recompute()):this._flags|=ve:n===T&&this._handleEnd(s)})}}_handleEnd(e){this._flags|=G,this._flags=this._flags&~$|(e!==void 0?Be:Ft),e!==void 0&&(this._cachedValue=e);for(let s of this._upstreamTalkbacks)s(T);this._upstreamTalkbacks=[],this._flags&=~Se,this._dirtyDeps.reset();let r=this._output,n=this._flags&ue;if(this._output=null,this._flags&=~ue,r)if(n)for(let s of r)try{e!==void 0?s(T,e):s(T)}catch{}else e!==void 0?r(T,e):r(T)}_disconnectUpstream(){for(let e of this._upstreamTalkbacks)e(T);this._upstreamTalkbacks.length=0,this._flags&=~(Se|ve),this._flags=this._flags&~$|jt,this._dirtyDeps.reset()}_handleLifecycleSignal(e){if(!(this._flags&G)){if(e===re){for(let r of this._upstreamTalkbacks)r(y,re);this._handleEnd(void 0);return}e===ie&&(this._flags&=~(he|ve),this._dirtyDeps.reset());for(let r of this._upstreamTalkbacks)r(y,e)}}get(){if(this._flags&Se)return this._cachedValue;if(this._flags&G){if((this._flags&$)===Be)throw this._cachedValue;return this._cachedValue}let e=this._fn();return this._cachedValue=e,this._flags|=he,e}source(e,r){if(e===x){let n=r;if(this._flags&G){let s=(this._flags&$)===Be;n(x,i=>{}),s?n(T,this._cachedValue):n(T);return}if(!(this._flags&Se)&&(this._lazyConnect(),this._flags&G)){let s=(this._flags&$)===Be;n(x,i=>{}),s?n(T,this._cachedValue):n(T);return}if(this._output===null)this._output=n;else if(this._flags&ue)this._output.add(n);else{let s=new Set;s.add(this._output),s.add(n),this._output=s,this._flags|=ue}n(x,(s,i)=>{if(s===O&&n(O,this._cachedValue),s===y&&ge(i)){this._handleLifecycleSignal(i);return}if(s===T){if(this._output===null)return;if(this._flags&ue){let o=this._output;o.delete(n),o.size===1?(this._output=o.values().next().value,this._flags&=~ue):o.size===0&&(this._output=null,this._flags&=~ue,this._disconnectUpstream())}else this._output===n&&(this._output=null,this._disconnectUpstream())}})}}};function X(t,e,r){return new Qe(t,e,r)}(e=>{function t(r,n){return new Qe([r],()=>r.get(),n,!0)}e.from=t})(X||={});function bt(t,e,r){let n,s=[],i=!1,o=new Te(t.length),c=!1;function u(){i||(n&&n(),n=e())}let f=0;function a(p){if(!i){if(p===re){for(let h of s)h(y,re);s.length=0,i=!0,n&&n(),n=void 0;return}p===ie&&(f++,o.reset(),c=!1,u());for(let h of s)h(y,p)}}me(),u();for(let p=0;p<t.length&&!i;p++){let h=p,k=f;t[h].source(x,(w,D)=>{if(w===x){s.push(D),t.length===1&&D(y,fe);return}if(!i){if(w===y){if(ge(D)){a(D),k=f;return}if(k!==f)return;D===A?(o.empty()&&(c=!1),o.set(h)):D===J&&o.test(h)&&(o.clear(h),o.empty()&&c&&u())}if(w===O){if(k!==f)return;o.test(h)?(o.clear(h),c=!0,o.empty()&&u()):o.empty()?u():c=!0}if(w===T){i=!0,n&&n(),n=void 0;for(let g of s)g(T);s.length=0}}})}_e();let l=()=>{if(!i){i=!0,n&&n(),n=void 0;for(let p of s)p(T);s.length=0}};l.signal=p=>a(p),Y.register(l,{kind:"effect",...r,deps:t});for(let p of t)Y.registerEdge(p,l);return l}function Kt(t){return t!=null&&typeof t.then=="function"}function Ut(t){return t!=null&&typeof t.subscribe=="function"}function Yt(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}function Wt(t){return t!=null&&typeof t[Symbol.iterator]=="function"}function Tt(t){return Kt(t)?ae(({emit:e,complete:r,error:n})=>{let s=!1;return t.then(i=>{s||(e(i),r())},i=>{s||n(i)}),()=>{s=!0}}):Ut(t)?ae(({emit:e,complete:r,error:n})=>{let s=!1,i=t.subscribe({next:o=>{s||e(o)},error:o=>{s||n(o)},complete:()=>{s||r()}});return()=>{s=!0,i.unsubscribe()}}):Yt(t)?ae(({emit:e,complete:r,error:n})=>{let s=new AbortController,i=s.signal,o=!1,c=t[Symbol.asyncIterator]();async function u(){try{for(;!o&&!i.aborted;){let f=await c.next();if(o||i.aborted)break;if(f.done){r();return}e(f.value)}}catch(f){!o&&!i.aborted&&n(f)}}return u(),()=>{o=!0,s.abort(),Promise.resolve(c.return?.()).catch(()=>{})}},{resubscribable:!0}):typeof t!="string"&&Wt(t)?ae(({emit:e,complete:r})=>{for(let n of t)e(n);r()}):ae(({emit:e,complete:r})=>{e(t),r()})}var Gt=Symbol.for("callbag-recharge:topic-internal"),zt=Symbol.for("callbag-recharge:topic-log"),Ht=0;function St(t){return{seq:t.seq,value:t.value.value,timestamp:t.value.timestamp,key:t.value.key,priority:t.value.priority,headers:t.value.headers}}function Ze(t,e){let r=`sub-${++Ht}`,n=e?.name??r,s=e?.mode??"exclusive",i=e?.batchSize??1,o=e?.ackTimeout??3e4,c=t[Gt],u=t[zt],f,a=s==="shared"||s==="failover"||s==="key_shared",l;a?(l=c.getOrCreateGroup(n),l.consumers.add(r),l.consumers.size===1&&(l.cursor=p()),f=l.cursor):f=p();function p(){return e?.initialPosition==="earliest"?u.headSeq>0?u.headSeq:1:typeof e?.initialPosition=="number"?e.initialPosition:u.tailSeq+1}let h=new Map,k=new Map,w=[],D=e?.retry?.maxRetries??3,g=e?.retry?.backoff??He(),v=e?.deadLetterTopic,L=!1,C=!1,K=q(f,{name:`${n}:pos`}),F=q(0,{name:`${n}:pending`}),z=X([u.lengthStore,u.events,K],()=>{let _=u.tailSeq,S=K.get(),R=u.headSeq,te=R>0?Math.max(S,R):S;return Math.max(0,_-te+1)},{name:`${n}:backlog`}),P=e?.persistence;function H(){P&&Promise.resolve(P.save(`${n}:cursor`,f)).catch(()=>{})}function b(){return s!=="failover"||!l?!0:l.consumers.values().next().value===r}function E(_){let S=0;for(let R=0;R<_.length;R++)S=(S<<5)-S+_.charCodeAt(R)|0;return Math.abs(S)}function U(_){if(s!=="key_shared"||!l||!_)return!0;let S=Array.from(l.consumers),R=E(_)%S.length;return S[R]===r}function se(_){if(L||C)return[];if(!b())return[];let S=_??i,R=[],te=Date.now(),le=[],Le=[];for(let Q of w)Q.readyAt<=te&&le.length<S?le.push(Q):Le.push(Q);w.length=0,w.push(...Le);for(let Q of le){let Ie=u.get(Q.seq);if(Ie){let Ae=St(Ie);R.push(Ae),ce(Q.seq)}}let lt=S-R.length,Me=-1;if(lt>0){let Q=a&&l?l.cursor:f,Ie=u.tailSeq,Ae=0;for(let ne=Q;ne<=Ie&&Ae<lt;ne++){let rt=u.get(ne);if(!rt||s==="key_shared"&&!U(rt.value.key))continue;if(s==="shared"&&l&&l.consumers.size>1){let ft=Array.from(l.consumers),Lt=l.roundRobinIndex%ft.length;if(ft[Lt]!==r)continue;l.roundRobinIndex++}let xt=St(rt);R.push(xt),ce(ne),ne>Me&&(Me=ne),Ae++}if(Me>=0){let ne=Me+1;a&&l&&(l.cursor=Math.max(l.cursor,ne)),f=a&&l?l.cursor:ne}}return R.length>0&&N(()=>{K.set(f),F.update(Q=>Q+R.length)}),R}function ce(_){let S;o>0&&(S=setTimeout(()=>{h.has(_)&&I(_)},o)),h.set(_,{timer:S})}function d(_){let S=h.get(_);S&&(S.timer&&clearTimeout(S.timer),h.delete(_),k.delete(_),F.update(R=>Math.max(0,R-1)),H())}function m(_,S){if(v){let R=u.get(_);R&&v.publish(R.value.value,{key:R.value.key,headers:{...R.value.headers,"x-original-topic":t.name,"x-retry-count":String(S),"x-original-seq":String(_)}})}k.delete(_)}function I(_){let S=h.get(_);if(!S)return;S.timer&&clearTimeout(S.timer),h.delete(_),F.update(Le=>Math.max(0,Le-1));let R=k.get(_)??{attempts:0},te=R.attempts+1;if(te>D){m(_,te);return}let le=g(te-1,void 0,R.prevDelay);if(le===null){m(_,te);return}k.set(_,{attempts:te,prevDelay:le}),w.push({seq:_,readyAt:Date.now()+le})}function ee(_){if(C)return;let S;_==="earliest"?S=u.headSeq>0?u.headSeq:1:_==="latest"?S=u.tailSeq+1:S=_,f=S,a&&l&&(l.cursor=S),K.set(S);for(let R of h.values())R.timer&&clearTimeout(R.timer);h.clear(),F.set(0),w.length=0,k.clear(),H()}let ct,nt;if(P){let _=Tt(P.load(`${n}:cursor`));nt=_,ct=bt([_],()=>{let S=_.get();typeof S=="number"&&ee(S)})}function Rt(){if(!C){C=!0,ct?.(),nt&&M(nt);for(let _ of h.values())_.timer&&clearTimeout(_.timer);h.clear(),w.length=0,k.clear(),l&&(l.consumers.delete(r),l.consumers.size===0&&c.removeGroup(n)),N(()=>{M(K),M(F),M(z)})}}return{get name(){return n},get mode(){return s},pull:se,ack:d,nack:I,seek:ee,position:K,backlog:z,pending:F,pause(){L||(L=!0,K.signal(de),F.signal(de))},resume(){L&&(L=!1,K.signal(pe),F.signal(pe))},get isPaused(){return L},destroy:Rt}}function vt(t,e,r){let n=r?.threshold??0,s=null,i=!1;function o(){if(i)return 0;let c=t.toArray();if(c.length===0)return 0;let u=new Map,f=[];for(let p of c){let h=e(p.value);u.has(h)||f.push(h),u.set(h,p.value)}let a=f.map(p=>u.get(p)),l=c.length-a.length;if(l===0)return 0;i=!0;try{t.clear(),t.appendMany(a)}finally{i=!1}return l}return n>0&&(s=ze(t.events,c=>{c?.type==="append"&&t.length>=n&&o()})),{compact:o,destroy(){s?.unsubscribe(),s=null}}}var Bt=0;Xe.from=function(e,r){let n=Xe({...r,id:e.id});for(let s of e.entries)n.append(s.value);return n};function Xe(t){let e=++Bt,r=t?.id??`rlog-${e}`,n=t?.maxSize??0,s=n>0,i=[],o=0,c=0,u=0,f=1,a=q(0,{name:`${r}:ver`}),l=q(void 0,{name:`${r}:events`,equals:()=>!1}),p=new Map,h=!1;function k(){if(!s)return i.slice();if(c===0)return[];let g=new Array(c);for(let v=0;v<c;v++)g[v]=i[(o+v)%n];return g}function w(g){if(!s)return i[g];if(!(g<0||g>=c))return i[(o+g)%n]}let D={get id(){return r},get version(){return a.get()},append(g){if(h)return-1;let v=++u,L={seq:v,value:g};return s?(c<n?(i[(o+c)%n]=L,c++):(i[o]=L,o=(o+1)%n),f=u-c+1):(i.push(L),f=i.length>0?i[0].seq:1),a.update(C=>C+1),l.set({type:"append",seq:v,value:g}),v},appendMany(g){if(h||g.length===0)return[];let v=[];return N(()=>{for(let L of g)v.push(D.append(L))}),v},get(g){if(s)return g<f||g>u||c===0?void 0:w(g-f);let v=g-f;if(!(v<0||v>=i.length))return i[v]},slice(g,v){let L=g??f,C=v??u;if((s?c:i.length)===0)return[];let F=Math.max(L,f),z=Math.min(C,u);if(F>z)return[];let P=F-f,H=z-f;if(!s)return i.slice(P,H+1);let b=[];for(let E=P;E<=H;E++)b.push(i[(o+E)%n]);return b},toArray(){return k()},get length(){return s?c:i.length},get headSeq(){return(s?c:i.length)>0?f:0},get tailSeq(){return u},clear(){(s?c:i.length)!==0&&N(()=>{s?(c=0,o=0):i.length=0,f=u+1,a.update(v=>v+1),l.set({type:"clear"})})},lengthStore:X([a],()=>s?c:i.length,{name:`${r}:length`}),latest:X([a],()=>{if((s?c:i.length)!==0)return s?i[(o+c-1)%n]:i[i.length-1]},{name:`${r}:latest`}),tail(g){let v=p.get(g);return v||(v=X([a],()=>{let L=k();return g===void 0||g>=L.length?L:L.slice(-g)},{name:`${r}:tail${g??""}`}),p.set(g,v),v)},events:l,snapshot(){return{type:"reactiveLog",id:r,version:a.get(),entries:k().map(g=>({seq:g.seq,value:g.value})),headSeq:(s?c:i.length)>0?f:0,tailSeq:u}},destroy(){h||(h=!0,N(()=>{for(let g of p.values())M(g);p.clear(),M(D.lengthStore),M(D.latest),M(l),M(a),i.length=0,c=0}))}};return D}var Qt=0;function et(t){return{seq:t.seq,value:t.value.value,timestamp:t.value.timestamp,key:t.value.key,priority:t.value.priority,headers:t.value.headers}}function tt(t,e){let r=++Qt,n=e?.namespace,s=n?n.prefix(t):t,i=`topic-${s}-${r}`,o=Xe({id:`${i}:log`,maxSize:e?.maxSize}),c;if(e?.compaction){let b=e.compaction.keyFn;c=vt(o,E=>b(E.value),{threshold:e.compaction.threshold})}let u=e?.dedup?.windowMs??6e4,f=new Map,a;u>0&&(a=setInterval(()=>{let b=Date.now();for(let[E,U]of f)b-U>=u&&f.delete(E)},Math.min(u,3e4)),a&&typeof a=="object"&&"unref"in a&&a.unref());let l=!1,p=!1,h=new Set,k=new Map,w=q(0,{name:`${i}:pubCount`}),D=q(0,{name:`${i}:ver`}),g=o.lengthStore,v=X([o.latest],()=>{let b=o.latest.get();return b?et(b):void 0},{name:`${i}:latest`}),L=e?.schema,C=e?.persistence?n?n.checkpoint(e.persistence):e.persistence:void 0,K={getOrCreateGroup(b){let E=k.get(b);return E||(E={cursor:o.tailSeq+1,roundRobinIndex:0,consumers:new Set},k.set(b,E)),E},removeGroup(b){k.delete(b)}};function F(b,E){if(p||l)return-1;L&&(b=L.parse(b));let U=E?.dedupKey;if(U){let d=Date.now(),m=f.get(U);if(m!==void 0&&d-m<u)return-1;f.set(U,d)}let se={value:b,timestamp:Date.now(),key:E?.key,priority:E?.priority,headers:E?.headers};if(E?.delay&&E.delay>0){let d=setTimeout(()=>{h.delete(d),!p&&!l&&N(()=>{o.append(se),w.update(m=>m+1),D.update(m=>m+1)})},E.delay);return h.add(d),-1}return N(()=>{let d=o.append(se);return w.update(m=>m+1),D.update(m=>m+1),d})}function z(b){let E=o.get(b);return E?et(E):void 0}function P(b,E){return o.slice(b,E).map(et)}let H={get id(){return i},get version(){return D.get()},get name(){return s},publish:F,get(b){return z(b)},slice(b,E){return P(b,E)},get headSeq(){return o.headSeq},get tailSeq(){return o.tailSeq},depth:g,latest:v,publishCount:w,peek(){if(o.length===0)return;let b=o.get(o.headSeq);return b?et(b):void 0},pause(){if(!l){l=!0;for(let b of h)clearTimeout(b);h.clear(),w.signal(de),D.signal(de)}},resume(){l&&(l=!1,w.signal(pe),D.signal(pe))},get paused(){return l},destroy(){if(!p){p=!0;for(let b of h)clearTimeout(b);h.clear(),a&&clearInterval(a),f.clear(),c?.destroy(),N(()=>{M(w),M(D),M(v),o.destroy()}),k.clear()}}};return H[Symbol.for("callbag-recharge:topic-internal")]=K,H[Symbol.for("callbag-recharge:topic-log")]=o,H}function Et(t,e,r){let n=r?.concurrency??1,s=r?.ackTimeout??3e4,i=r?.stallInterval??5e3,o=r?.stalledJobAction??"none",c=r?.retry?.maxRetries??3,u=r?.retry?.backoff??He(),f=q(!1,{name:`${t}:paused`}),a=!1,l=0,p=new AbortController,h=new Map,k={completed:new Set,failed:new Set,stalled:new Set},w=q(0,{name:`${t}:active`}),D=q(0,{name:`${t}:completed`}),g=q(0,{name:`${t}:failed`}),v=q(0,{name:`${t}:waiting`}),L=tt(`${t}:jobs`,r?.topicOptions),C=Ze(L,{name:`${t}:worker`,mode:"shared",initialPosition:"earliest",ackTimeout:0});function K(){let d=new AbortController;return p.signal.addEventListener("abort",()=>d.abort(),{once:!0}),d}function F(d){return{seq:d.seq,data:d.data,status:d.status,result:d.result,error:d.error,duration:d.duration,attempts:d.attempts}}function z(d,m){let I=F(m);for(let ee of k[d])try{ee(I)}catch{}}function P(){a||v.set(Math.max(0,C.backlog.get()))}async function H(d){for(;;){d.status="active",d.startTime=Date.now(),d.attempts++,l++,N(()=>{w.update(m=>m+1),P()});try{let m=await e(d.abort.signal,d.data);if(a)return;d.status="completed",d.result=m,d.duration=Date.now()-d.startTime,l--,C.ack(d.seq),N(()=>{w.update(I=>Math.max(0,I-1)),D.update(I=>I+1),P()}),z("completed",d);return}catch(m){if(a)return;if(d.duration=Date.now()-d.startTime,l--,N(()=>{w.update(I=>Math.max(0,I-1))}),d.attempts<c){let I=u(d.attempts-1,m,void 0);if(I===null){E(d,m);return}if(I>0&&await at(mt(I,d.abort.signal)),f.get())try{await at(f,ee=>!ee)}catch{return}if(a)return;d.abort=K();continue}E(d,m);return}}}async function b(d){try{await H(d)}finally{h.delete(d.seq),a||U()}}function E(d,m){if(d.status="failed",d.error=m,C.ack(d.seq),N(()=>{g.update(I=>I+1),P()}),r?.deadLetterTopic)try{r.deadLetterTopic.publish(d.data,{headers:{"x-original-queue":t,"x-retry-count":String(d.attempts),"x-original-seq":String(d.seq)}})}catch{}z("failed",d)}function U(){if(f.get()||a)return;let d=n-l;if(d<=0)return;let m=C.pull(d);if(m.length!==0){P();for(let I of m){let ee={seq:I.seq,data:I.value,status:"waiting",attempts:0,abort:K()};h.set(I.seq,ee),b(ee).catch(()=>{})}}}let se=setInterval(()=>{!f.get()&&!a&&(P(),U())},100),ce=setInterval(()=>{if(a)return;let d=Date.now();for(let m of h.values())m.status==="active"&&m.startTime&&d-m.startTime>s&&(m.status="stalled",z("stalled",m),(o==="cancel"||o==="retry")&&(m.abort.abort(),o==="cancel"&&(m.attempts=c)))},i);return P(),U(),{get name(){return t},add(d,m){let I=L.publish(d,m);return P(),queueMicrotask(()=>U()),I},active:w,completed:D,failed:g,waiting:v,on(d,m){return k[d].add(m),()=>{k[d].delete(m)}},pause(){f.get()||(f.set(!0),C.pause())},resume(){f.get()&&(f.set(!1),C.resume(),U())},get isPaused(){return f.get()},destroy(){a||(a=!0,p.abort(),se&&(clearInterval(se),se=null),ce&&(clearInterval(ce),ce=null),C.destroy(),L.destroy(),h.clear(),N(()=>{M(f),M(w),M(D),M(g),M(v)}))}}}function xe(t,e,r){let n=new Set;for(let s of t.split(",")){let[i,o]=s.split("/"),c=o?Number.parseInt(o,10):1;if(Number.isNaN(c)||c<1)throw new Error(`Invalid cron step: ${s}`);let u,f;if(i==="*")u=e,f=r;else if(i.includes("-")){let[a,l]=i.split("-");u=Number.parseInt(a,10),f=Number.parseInt(l,10)}else u=Number.parseInt(i,10),f=u;if(Number.isNaN(u)||Number.isNaN(f))throw new Error(`Invalid cron field: ${t}`);if(u<e||f>r)throw new Error(`Cron field out of range: ${t} (${e}-${r})`);if(u>f)throw new Error(`Invalid cron range: ${u}-${f} in ${t}`);for(let a=u;a<=f;a+=c)n.add(a)}return n}function Dt(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:xe(e[0],0,59),hours:xe(e[1],0,23),daysOfMonth:xe(e[2],1,31),months:xe(e[3],1,12),daysOfWeek:xe(e[4],0,6)}}function kt(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var Zt=0;function wt(t,e,r){let n=`repeat-${++Zt}`,s=r.limit??0,i=!0,o,c=q(0,{name:`${n}:count`}),u={key:r.key,headers:r.headers,dedupKey:r.dedupKey};function f(){return typeof e=="function"?e():e}function a(){if(!i)return;if(s>0&&c.get()>=s){l();return}let h={...u};r.dedupKey&&(h.dedupKey=`${r.dedupKey}:${c.get()}`),t.publish(f(),h),c.update(k=>k+1),s>0&&c.get()>=s&&l()}function l(){i&&(i=!1,o!==void 0&&(clearInterval(o),o=void 0),M(c))}if(r.every&&r.every>0)o=setInterval(a,r.every),o&&typeof o=="object"&&"unref"in o&&o.unref();else if(r.cron){let w=function(){if(!i)return;let D=new Date,g=D.getFullYear()*1e8+(D.getMonth()+1)*1e6+D.getDate()*1e4+D.getHours()*100+D.getMinutes();g!==k&&kt(h,D)&&(k=g,a())};var p=w;let h=Dt(r.cron),k=0;o=setInterval(w,6e4),o&&typeof o=="object"&&"unref"in o&&o.unref(),w()}return{cancel:l,get count(){return c},get active(){return i}}}0&&(module.exports={jobFlow,jobQueue,repeatPublish,subscription,topic});
@@ -194,6 +194,140 @@ interface RepeatHandle {
194
194
  /** Whether the repeat is still active. */
195
195
  readonly active: boolean;
196
196
  }
197
+ /** Status of an individual job. */
198
+ type JobStatus = "waiting" | "active" | "completed" | "failed" | "stalled";
199
+ /** Information about a job, exposed to event handlers and externally. */
200
+ interface JobInfo<T, R = unknown> {
201
+ /** Sequence number from the underlying topic. */
202
+ seq: number;
203
+ /** Original job data. */
204
+ data: T;
205
+ /** Job status. */
206
+ status: JobStatus;
207
+ /** Result value (if completed). */
208
+ result?: R;
209
+ /** Error (if failed). */
210
+ error?: unknown;
211
+ /** Duration in ms (if completed or failed). */
212
+ duration?: number;
213
+ /** Number of processing attempts. */
214
+ attempts: number;
215
+ }
216
+ /** Events emitted by the job queue. */
217
+ type JobEvent = "completed" | "failed" | "stalled";
218
+ /** What to do when a job stalls (exceeds ackTimeout). */
219
+ type StallAction = "none" | "cancel" | "retry";
220
+ /** Options for creating a job queue. */
221
+ interface JobQueueOptions<T> {
222
+ /** Maximum concurrent jobs. Default: 1. */
223
+ concurrency?: number;
224
+ /** Ack timeout in ms. Jobs exceeding this are marked stalled. Default: 30_000. */
225
+ ackTimeout?: number;
226
+ /** Stall check interval in ms. Default: 5_000. */
227
+ stallInterval?: number;
228
+ /**
229
+ * Action to take when a job stalls. Default: `"none"` (event only).
230
+ * - `"none"` — emit "stalled" event, no automatic recovery.
231
+ * - `"cancel"` — abort the job's signal and mark as failed.
232
+ * - `"retry"` — abort and re-enqueue for processing (respects retry limits).
233
+ */
234
+ stalledJobAction?: StallAction;
235
+ /** Retry configuration for failed jobs. */
236
+ retry?: {
237
+ /** Max retry attempts. Default: 3. */
238
+ maxRetries?: number;
239
+ /** Backoff strategy. Default: exponential(). */
240
+ backoff?: BackoffStrategy;
241
+ };
242
+ /** Dead letter topic for terminally failed jobs. */
243
+ deadLetterTopic?: Topic<T>;
244
+ /** Topic options passed to the underlying topic. */
245
+ topicOptions?: Omit<TopicOptions<T>, "namespace">;
246
+ }
247
+ /** A job queue built on topic + subscription + task processing. */
248
+ interface JobQueue<T, R = void> {
249
+ /** Queue name. */
250
+ readonly name: string;
251
+ /** Add a job to the queue. Returns the sequence number. */
252
+ add(data: T, opts?: PublishOptions): number;
253
+ /** Reactive count of currently processing jobs. */
254
+ readonly active: Store<number>;
255
+ /** Reactive count of completed jobs. */
256
+ readonly completed: Store<number>;
257
+ /** Reactive count of failed jobs. */
258
+ readonly failed: Store<number>;
259
+ /** Reactive count of delayed/waiting jobs (backlog). */
260
+ readonly waiting: Store<number>;
261
+ /** Subscribe to job events. Returns an unsubscribe function. */
262
+ on(event: JobEvent, fn: (job: JobInfo<T, R>) => void): () => void;
263
+ /** Pause job processing. New jobs can still be added. */
264
+ pause(): void;
265
+ /** Resume job processing. */
266
+ resume(): void;
267
+ /** Whether the queue is paused. */
268
+ readonly isPaused: boolean;
269
+ /** Destroy the queue and all internal resources. */
270
+ destroy(): void;
271
+ }
272
+ /** A single edge in a job flow wiring. */
273
+ interface JobFlowEdge<T = any, R = any, T2 = any> {
274
+ /** Source queue name. */
275
+ from: string;
276
+ /** Destination queue name. */
277
+ to: string;
278
+ /** Optional transform from source result to destination job data. */
279
+ transform?: (result: R) => T2;
280
+ }
281
+ /** Options for creating a job flow. */
282
+ interface JobFlowOptions {
283
+ /** Debug name. */
284
+ name?: string;
285
+ }
286
+ /** A multi-queue workflow that chains job queues via completion events. */
287
+ interface JobFlow {
288
+ /** Flow name. */
289
+ readonly name: string;
290
+ /** Named queues in the flow. */
291
+ readonly queues: Record<string, JobQueue<any, any>>;
292
+ /** Export the flow as a Mermaid diagram. */
293
+ toMermaid(): string;
294
+ /** Export the flow as a D2 diagram. */
295
+ toD2(): string;
296
+ /** Destroy all queues and wiring. */
297
+ destroy(): void;
298
+ }
299
+
300
+ /**
301
+ * Chain multiple job queues into a workflow. When a job completes in a source
302
+ * queue, its result is published to the destination queue (optionally transformed).
303
+ *
304
+ * @param queues - Named record of job queues.
305
+ * @param edges - Wiring edges describing which queue outputs feed into which queue inputs.
306
+ * @param opts - Optional configuration (name).
307
+ *
308
+ * @returns `JobFlow` — a multi-queue workflow with diagram export and lifecycle.
309
+ *
310
+ * @category messaging
311
+ */
312
+ declare function jobFlow(queues: Record<string, JobQueue<any, any>>, edges: JobFlowEdge[], opts?: JobFlowOptions): JobFlow;
313
+
314
+ /**
315
+ * Create a job queue backed by a topic and shared subscription.
316
+ *
317
+ * Each call to `add(data)` publishes a message to the underlying topic.
318
+ * The queue pulls messages, runs them through the processor function with
319
+ * concurrency control, and tracks per-job status. Event listeners fire
320
+ * on completion, failure, and stall detection.
321
+ *
322
+ * @param name - Queue name (used for topic and subscription naming).
323
+ * @param processor - Function called per job. Receives `(signal, data)`. Signal is aborted on stall (if configured) or destroy.
324
+ * @param opts - Queue configuration.
325
+ *
326
+ * @returns `JobQueue<T, R>` — queue with add, event subscription, companion stores, and lifecycle.
327
+ *
328
+ * @category messaging
329
+ */
330
+ declare function jobQueue<T, R = void>(name: string, processor: (signal: AbortSignal, data: T) => R | Promise<R>, opts?: JobQueueOptions<T>): JobQueue<T, R>;
197
331
 
198
332
  /**
199
333
  * Publish messages to a topic on a recurring schedule.
@@ -278,4 +412,4 @@ declare function subscription<T>(topicRef: Topic<T>, opts?: SubscriptionOptions<
278
412
  */
279
413
  declare function topic<T>(name: string, opts?: TopicOptions<T>): Topic<T>;
280
414
 
281
- export { type ConsumerGroup, type MessageMeta, type MessageSchema, type PublishOptions, type RepeatHandle, type RepeatPublishOptions, type SubscriptionMode, type SubscriptionOptions, type Topic, type TopicInternalAccess, type TopicMessage, type TopicOptions, type TopicSubscription, repeatPublish, subscription, topic };
415
+ export { type ConsumerGroup, type JobEvent, type JobFlow, type JobFlowEdge, type JobFlowOptions, type JobInfo, type JobQueue, type JobQueueOptions, type JobStatus, type MessageMeta, type MessageSchema, type PublishOptions, type RepeatHandle, type RepeatPublishOptions, type StallAction, type SubscriptionMode, type SubscriptionOptions, type Topic, type TopicInternalAccess, type TopicMessage, type TopicOptions, type TopicSubscription, jobFlow, jobQueue, repeatPublish, subscription, topic };
@@ -194,6 +194,140 @@ interface RepeatHandle {
194
194
  /** Whether the repeat is still active. */
195
195
  readonly active: boolean;
196
196
  }
197
+ /** Status of an individual job. */
198
+ type JobStatus = "waiting" | "active" | "completed" | "failed" | "stalled";
199
+ /** Information about a job, exposed to event handlers and externally. */
200
+ interface JobInfo<T, R = unknown> {
201
+ /** Sequence number from the underlying topic. */
202
+ seq: number;
203
+ /** Original job data. */
204
+ data: T;
205
+ /** Job status. */
206
+ status: JobStatus;
207
+ /** Result value (if completed). */
208
+ result?: R;
209
+ /** Error (if failed). */
210
+ error?: unknown;
211
+ /** Duration in ms (if completed or failed). */
212
+ duration?: number;
213
+ /** Number of processing attempts. */
214
+ attempts: number;
215
+ }
216
+ /** Events emitted by the job queue. */
217
+ type JobEvent = "completed" | "failed" | "stalled";
218
+ /** What to do when a job stalls (exceeds ackTimeout). */
219
+ type StallAction = "none" | "cancel" | "retry";
220
+ /** Options for creating a job queue. */
221
+ interface JobQueueOptions<T> {
222
+ /** Maximum concurrent jobs. Default: 1. */
223
+ concurrency?: number;
224
+ /** Ack timeout in ms. Jobs exceeding this are marked stalled. Default: 30_000. */
225
+ ackTimeout?: number;
226
+ /** Stall check interval in ms. Default: 5_000. */
227
+ stallInterval?: number;
228
+ /**
229
+ * Action to take when a job stalls. Default: `"none"` (event only).
230
+ * - `"none"` — emit "stalled" event, no automatic recovery.
231
+ * - `"cancel"` — abort the job's signal and mark as failed.
232
+ * - `"retry"` — abort and re-enqueue for processing (respects retry limits).
233
+ */
234
+ stalledJobAction?: StallAction;
235
+ /** Retry configuration for failed jobs. */
236
+ retry?: {
237
+ /** Max retry attempts. Default: 3. */
238
+ maxRetries?: number;
239
+ /** Backoff strategy. Default: exponential(). */
240
+ backoff?: BackoffStrategy;
241
+ };
242
+ /** Dead letter topic for terminally failed jobs. */
243
+ deadLetterTopic?: Topic<T>;
244
+ /** Topic options passed to the underlying topic. */
245
+ topicOptions?: Omit<TopicOptions<T>, "namespace">;
246
+ }
247
+ /** A job queue built on topic + subscription + task processing. */
248
+ interface JobQueue<T, R = void> {
249
+ /** Queue name. */
250
+ readonly name: string;
251
+ /** Add a job to the queue. Returns the sequence number. */
252
+ add(data: T, opts?: PublishOptions): number;
253
+ /** Reactive count of currently processing jobs. */
254
+ readonly active: Store<number>;
255
+ /** Reactive count of completed jobs. */
256
+ readonly completed: Store<number>;
257
+ /** Reactive count of failed jobs. */
258
+ readonly failed: Store<number>;
259
+ /** Reactive count of delayed/waiting jobs (backlog). */
260
+ readonly waiting: Store<number>;
261
+ /** Subscribe to job events. Returns an unsubscribe function. */
262
+ on(event: JobEvent, fn: (job: JobInfo<T, R>) => void): () => void;
263
+ /** Pause job processing. New jobs can still be added. */
264
+ pause(): void;
265
+ /** Resume job processing. */
266
+ resume(): void;
267
+ /** Whether the queue is paused. */
268
+ readonly isPaused: boolean;
269
+ /** Destroy the queue and all internal resources. */
270
+ destroy(): void;
271
+ }
272
+ /** A single edge in a job flow wiring. */
273
+ interface JobFlowEdge<T = any, R = any, T2 = any> {
274
+ /** Source queue name. */
275
+ from: string;
276
+ /** Destination queue name. */
277
+ to: string;
278
+ /** Optional transform from source result to destination job data. */
279
+ transform?: (result: R) => T2;
280
+ }
281
+ /** Options for creating a job flow. */
282
+ interface JobFlowOptions {
283
+ /** Debug name. */
284
+ name?: string;
285
+ }
286
+ /** A multi-queue workflow that chains job queues via completion events. */
287
+ interface JobFlow {
288
+ /** Flow name. */
289
+ readonly name: string;
290
+ /** Named queues in the flow. */
291
+ readonly queues: Record<string, JobQueue<any, any>>;
292
+ /** Export the flow as a Mermaid diagram. */
293
+ toMermaid(): string;
294
+ /** Export the flow as a D2 diagram. */
295
+ toD2(): string;
296
+ /** Destroy all queues and wiring. */
297
+ destroy(): void;
298
+ }
299
+
300
+ /**
301
+ * Chain multiple job queues into a workflow. When a job completes in a source
302
+ * queue, its result is published to the destination queue (optionally transformed).
303
+ *
304
+ * @param queues - Named record of job queues.
305
+ * @param edges - Wiring edges describing which queue outputs feed into which queue inputs.
306
+ * @param opts - Optional configuration (name).
307
+ *
308
+ * @returns `JobFlow` — a multi-queue workflow with diagram export and lifecycle.
309
+ *
310
+ * @category messaging
311
+ */
312
+ declare function jobFlow(queues: Record<string, JobQueue<any, any>>, edges: JobFlowEdge[], opts?: JobFlowOptions): JobFlow;
313
+
314
+ /**
315
+ * Create a job queue backed by a topic and shared subscription.
316
+ *
317
+ * Each call to `add(data)` publishes a message to the underlying topic.
318
+ * The queue pulls messages, runs them through the processor function with
319
+ * concurrency control, and tracks per-job status. Event listeners fire
320
+ * on completion, failure, and stall detection.
321
+ *
322
+ * @param name - Queue name (used for topic and subscription naming).
323
+ * @param processor - Function called per job. Receives `(signal, data)`. Signal is aborted on stall (if configured) or destroy.
324
+ * @param opts - Queue configuration.
325
+ *
326
+ * @returns `JobQueue<T, R>` — queue with add, event subscription, companion stores, and lifecycle.
327
+ *
328
+ * @category messaging
329
+ */
330
+ declare function jobQueue<T, R = void>(name: string, processor: (signal: AbortSignal, data: T) => R | Promise<R>, opts?: JobQueueOptions<T>): JobQueue<T, R>;
197
331
 
198
332
  /**
199
333
  * Publish messages to a topic on a recurring schedule.
@@ -278,4 +412,4 @@ declare function subscription<T>(topicRef: Topic<T>, opts?: SubscriptionOptions<
278
412
  */
279
413
  declare function topic<T>(name: string, opts?: TopicOptions<T>): Topic<T>;
280
414
 
281
- export { type ConsumerGroup, type MessageMeta, type MessageSchema, type PublishOptions, type RepeatHandle, type RepeatPublishOptions, type SubscriptionMode, type SubscriptionOptions, type Topic, type TopicInternalAccess, type TopicMessage, type TopicOptions, type TopicSubscription, repeatPublish, subscription, topic };
415
+ export { type ConsumerGroup, type JobEvent, type JobFlow, type JobFlowEdge, type JobFlowOptions, type JobInfo, type JobQueue, type JobQueueOptions, type JobStatus, type MessageMeta, type MessageSchema, type PublishOptions, type RepeatHandle, type RepeatPublishOptions, type StallAction, type SubscriptionMode, type SubscriptionOptions, type Topic, type TopicInternalAccess, type TopicMessage, type TopicOptions, type TopicSubscription, jobFlow, jobQueue, repeatPublish, subscription, topic };
@@ -1 +1,3 @@
1
- import{c as pe}from"../chunk-GO4JTIJI.js";import{a as ae,b as ue,c as ce}from"../chunk-JJ6PHYH4.js";import{a as se}from"../chunk-VD74HJ6V.js";import{a as oe}from"../chunk-DQVIVUSC.js";import{a as Q}from"../chunk-VO4IUQZE.js";import"../chunk-HK7DRUNM.js";import{a as ie}from"../chunk-GMLWTZFM.js";import{a as A}from"../chunk-7FX2AO6N.js";import"../chunk-VFN2CV32.js";import"../chunk-SOIVZBGE.js";import{B as _,e as G,f as K,v as O}from"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";var ye=0;function he(i,s,l){let g=`repeat-${++ye}`,m=l.limit??0,h=!0,r,y=A(0,{name:`${g}:count`}),c={key:l.key,headers:l.headers,dedupKey:l.dedupKey};function f(){return typeof s=="function"?s():s}function d(){if(!h)return;if(m>0&&y.get()>=m){e();return}let u={...c};l.dedupKey&&(u.dedupKey=`${l.dedupKey}:${y.get()}`),i.publish(f(),u),y.update(T=>T+1),m>0&&y.get()>=m&&e()}function e(){h&&(h=!1,r!==void 0&&(clearInterval(r),r=void 0),_(y))}if(l.every&&l.every>0)r=setInterval(d,l.every),r&&typeof r=="object"&&"unref"in r&&r.unref();else if(l.cron){let b=function(){if(!h)return;let v=new Date,$=v.getFullYear()*1e8+(v.getMonth()+1)*1e6+v.getDate()*1e4+v.getHours()*100+v.getMinutes();$!==T&&ue(u,v)&&(T=$,d())};var S=b;let u=ae(l.cron),T=0;r=setInterval(b,6e4),r&&typeof r=="object"&&"unref"in r&&r.unref(),b()}return{cancel:e,get count(){return y},get active(){return h}}}var be=Symbol.for("callbag-recharge:topic-internal"),Te=Symbol.for("callbag-recharge:topic-log"),ve=0;function le(i){return{seq:i.seq,value:i.value.value,timestamp:i.value.timestamp,key:i.value.key,priority:i.value.priority,headers:i.value.headers}}function Se(i,s){let l=`sub-${++ve}`,g=s?.name??l,m=s?.mode??"exclusive",h=s?.batchSize??1,r=s?.ackTimeout??3e4,y=i[be],c=i[Te],f,d=m==="shared"||m==="failover"||m==="key_shared",e;d?(e=y.getOrCreateGroup(g),e.consumers.add(l),e.consumers.size===1&&(e.cursor=S()),f=e.cursor):f=S();function S(){return s?.initialPosition==="earliest"?c.headSeq>0?c.headSeq:1:typeof s?.initialPosition=="number"?s.initialPosition:c.tailSeq+1}let u=new Map,T=new Map,b=[],v=s?.retry?.maxRetries??3,$=s?.retry?.backoff??pe(),z=s?.deadLetterTopic,k=!1,V=!1,x=A(f,{name:`${g}:pos`}),C=A(0,{name:`${g}:pending`}),j=Q([c.lengthStore,c.events,x],()=>{let t=c.tailSeq,n=x.get(),a=c.headSeq,I=a>0?Math.max(n,a):n;return Math.max(0,t-I+1)},{name:`${g}:backlog`}),L=s?.persistence;function D(){L&&Promise.resolve(L.save(`${g}:cursor`,f)).catch(()=>{})}function o(){return m!=="failover"||!e?!0:e.consumers.values().next().value===l}function p(t){let n=0;for(let a=0;a<t.length;a++)n=(n<<5)-n+t.charCodeAt(a)|0;return Math.abs(n)}function q(t){if(m!=="key_shared"||!e||!t)return!0;let n=Array.from(e.consumers),a=p(t)%n.length;return n[a]===l}function H(t){if(k||V)return[];if(!o())return[];let n=t??h,a=[],I=Date.now(),E=[],U=[];for(let R of b)R.readyAt<=I&&E.length<n?E.push(R):U.push(R);b.length=0,b.push(...U);for(let R of E){let N=c.get(R.seq);if(N){let Y=le(N);a.push(Y),B(R.seq)}}let re=n-a.length,F=-1;if(re>0){let R=d&&e?e.cursor:f,N=c.tailSeq,Y=0;for(let P=R;P<=N&&Y<re;P++){let X=c.get(P);if(!X||m==="key_shared"&&!q(X.value.key))continue;if(m==="shared"&&e&&e.consumers.size>1){let ne=Array.from(e.consumers),ge=e.roundRobinIndex%ne.length;if(ne[ge]!==l)continue;e.roundRobinIndex++}let de=le(X);a.push(de),B(P),P>F&&(F=P),Y++}if(F>=0){let P=F+1;d&&e&&(e.cursor=Math.max(e.cursor,P)),f=d&&e?e.cursor:P}}return a.length>0&&O(()=>{x.set(f),C.update(R=>R+a.length)}),a}function B(t){let n;r>0&&(n=setTimeout(()=>{u.has(t)&&Z(t)},r)),u.set(t,{timer:n})}function w(t){let n=u.get(t);n&&(n.timer&&clearTimeout(n.timer),u.delete(t),T.delete(t),C.update(a=>Math.max(0,a-1)),D())}function M(t,n){if(z){let a=c.get(t);a&&z.publish(a.value.value,{key:a.value.key,headers:{...a.value.headers,"x-original-topic":i.name,"x-retry-count":String(n),"x-original-seq":String(t)}})}T.delete(t)}function Z(t){let n=u.get(t);if(!n)return;n.timer&&clearTimeout(n.timer),u.delete(t),C.update(U=>Math.max(0,U-1));let a=T.get(t)??{attempts:0},I=a.attempts+1;if(I>v){M(t,I);return}let E=$(I-1,void 0,a.prevDelay);if(E===null){M(t,I);return}T.set(t,{attempts:I,prevDelay:E}),b.push({seq:t,readyAt:Date.now()+E})}function ee(t){if(V)return;let n;t==="earliest"?n=c.headSeq>0?c.headSeq:1:t==="latest"?n=c.tailSeq+1:n=t,f=n,d&&e&&(e.cursor=n),x.set(n);for(let a of u.values())a.timer&&clearTimeout(a.timer);u.clear(),C.set(0),b.length=0,T.clear(),D()}let te,J;if(L){let t=ce(L.load(`${g}:cursor`));J=t,te=oe([t],()=>{let n=t.get();typeof n=="number"&&ee(n)})}function fe(){if(!V){V=!0,te?.(),J&&_(J);for(let t of u.values())t.timer&&clearTimeout(t.timer);u.clear(),b.length=0,T.clear(),e&&(e.consumers.delete(l),e.consumers.size===0&&y.removeGroup(g)),O(()=>{_(x),_(C),_(j)})}}return{get name(){return g},get mode(){return m},pull:H,ack:w,nack:Z,seek:ee,position:x,backlog:j,pending:C,pause(){k||(k=!0,x.signal(G),C.signal(G))},resume(){k&&(k=!1,x.signal(K),C.signal(K))},get isPaused(){return k},destroy:fe}}function me(i,s,l){let g=l?.threshold??0,m=null,h=!1;function r(){if(h)return 0;let y=i.toArray();if(y.length===0)return 0;let c=new Map,f=[];for(let S of y){let u=s(S.value);c.has(u)||f.push(u),c.set(u,S.value)}let d=f.map(S=>c.get(S)),e=y.length-d.length;if(e===0)return 0;h=!0;try{i.clear(),i.appendMany(d)}finally{h=!1}return e}return g>0&&(m=ie(i.events,y=>{y?.type==="append"&&i.length>=g&&r()})),{compact:r,destroy(){m?.unsubscribe(),m=null}}}var Me=0;function W(i){return{seq:i.seq,value:i.value.value,timestamp:i.value.timestamp,key:i.value.key,priority:i.value.priority,headers:i.value.headers}}function _e(i,s){let l=++Me,g=s?.namespace,m=g?g.prefix(i):i,h=`topic-${m}-${l}`,r=se({id:`${h}:log`,maxSize:s?.maxSize}),y;if(s?.compaction){let o=s.compaction.keyFn;y=me(r,p=>o(p.value),{threshold:s.compaction.threshold})}let c=s?.dedup?.windowMs??6e4,f=new Map,d;c>0&&(d=setInterval(()=>{let o=Date.now();for(let[p,q]of f)o-q>=c&&f.delete(p)},Math.min(c,3e4)),d&&typeof d=="object"&&"unref"in d&&d.unref());let e=!1,S=!1,u=new Set,T=new Map,b=A(0,{name:`${h}:pubCount`}),v=A(0,{name:`${h}:ver`}),$=r.lengthStore,z=Q([r.latest],()=>{let o=r.latest.get();return o?W(o):void 0},{name:`${h}:latest`}),k=s?.schema,V=s?.persistence?g?g.checkpoint(s.persistence):s.persistence:void 0,x={getOrCreateGroup(o){let p=T.get(o);return p||(p={cursor:r.tailSeq+1,roundRobinIndex:0,consumers:new Set},T.set(o,p)),p},removeGroup(o){T.delete(o)}};function C(o,p){if(S||e)return-1;k&&(o=k.parse(o));let q=p?.dedupKey;if(q){let w=Date.now(),M=f.get(q);if(M!==void 0&&w-M<c)return-1;f.set(q,w)}let H={value:o,timestamp:Date.now(),key:p?.key,priority:p?.priority,headers:p?.headers};if(p?.delay&&p.delay>0){let w=setTimeout(()=>{u.delete(w),!S&&!e&&O(()=>{r.append(H),b.update(M=>M+1),v.update(M=>M+1)})},p.delay);return u.add(w),-1}return O(()=>{let w=r.append(H);return b.update(M=>M+1),v.update(M=>M+1),w})}function j(o){let p=r.get(o);return p?W(p):void 0}function L(o,p){return r.slice(o,p).map(W)}let D={get id(){return h},get version(){return v.get()},get name(){return m},publish:C,get(o){return j(o)},slice(o,p){return L(o,p)},get headSeq(){return r.headSeq},get tailSeq(){return r.tailSeq},depth:$,latest:z,publishCount:b,peek(){if(r.length===0)return;let o=r.get(r.headSeq);return o?W(o):void 0},pause(){if(!e){e=!0;for(let o of u)clearTimeout(o);u.clear(),b.signal(G),v.signal(G)}},resume(){e&&(e=!1,b.signal(K),v.signal(K))},get paused(){return e},destroy(){if(!S){S=!0;for(let o of u)clearTimeout(o);u.clear(),d&&clearInterval(d),f.clear(),y?.destroy(),O(()=>{_(b),_(v),_(z),r.destroy()}),T.clear()}}};return D[Symbol.for("callbag-recharge:topic-internal")]=x,D[Symbol.for("callbag-recharge:topic-log")]=r,D}export{he as repeatPublish,Se as subscription,_e as topic};
1
+ import{c as X}from"../chunk-GO4JTIJI.js";import{a as de,b as me,c as pe}from"../chunk-JJ6PHYH4.js";import{a as fe}from"../chunk-VD74HJ6V.js";import{a as ce}from"../chunk-DQVIVUSC.js";import{a as Z}from"../chunk-VO4IUQZE.js";import"../chunk-HK7DRUNM.js";import{a as B}from"../chunk-GMLWTZFM.js";import{a as J}from"../chunk-7FX2AO6N.js";import{i as le}from"../chunk-VFN2CV32.js";import"../chunk-SOIVZBGE.js";import{B as R,e as V,f as N,v as P}from"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";function Se(o,i,a){let g=a?.name??"jobFlow",f=[];for(let r of i){if(!o[r.from])throw new Error(`jobFlow: source queue "${r.from}" not found`);if(!o[r.to])throw new Error(`jobFlow: destination queue "${r.to}" not found`)}for(let r of i){let d=o[r.from],s=o[r.to],t=d.on("completed",v=>{let l=r.transform?r.transform(v.result):v.result;s.add(l)});f.push(t)}function h(){let r=[];r.push("graph LR");let d=Object.keys(o);for(let s of d)r.push(` ${b(s)}["${s}"]`);for(let s of i){let t=s.transform?"transform":"",v=b(s.from),l=b(s.to);t?r.push(` ${v} -->|${t}| ${l}`):r.push(` ${v} --> ${l}`)}return r.join(`
2
+ `)}function n(){let r=[],d=Object.keys(o);for(let s of d)r.push(`${b(s)}: ${s}`);for(let s of i){let t=b(s.from),v=b(s.to),l=s.transform?": transform":"";r.push(`${t} -> ${v}${l}`)}return r.join(`
3
+ `)}function b(r){return r.replace(/[^a-zA-Z0-9_]/g,"_")}return{get name(){return g},queues:o,toMermaid:h,toD2:n,destroy(){for(let r of f)r();f.length=0}}}function re(o,i){return new Promise((a,g)=>{let f=o.get();if(!i||i(f)){a(f);return}let h=B(o,n=>{(!i||i(n))&&(h.unsubscribe(),a(n))},{onEnd:n=>{g(n??new Error("source completed without matching value"))}})})}function be(o,i){return le(({emit:a,complete:g})=>{if(i?.aborted){a(void 0),g();return}let f=!1,h=setTimeout(()=>{f||(f=!0,b(),a(void 0),g())},o);function n(){f||(f=!0,clearTimeout(h),a(void 0),g())}i?.addEventListener("abort",n,{once:!0});function b(){i?.removeEventListener("abort",n)}return()=>{f||(f=!0,clearTimeout(h),b())}})}var _e=Symbol.for("callbag-recharge:topic-internal"),we=Symbol.for("callbag-recharge:topic-log"),Me=0;function ge(o){return{seq:o.seq,value:o.value.value,timestamp:o.value.timestamp,key:o.value.key,priority:o.value.priority,headers:o.value.headers}}function ne(o,i){let a=`sub-${++Me}`,g=i?.name??a,f=i?.mode??"exclusive",h=i?.batchSize??1,n=i?.ackTimeout??3e4,b=o[_e],r=o[we],d,s=f==="shared"||f==="failover"||f==="key_shared",t;s?(t=b.getOrCreateGroup(g),t.consumers.add(a),t.consumers.size===1&&(t.cursor=v()),d=t.cursor):d=v();function v(){return i?.initialPosition==="earliest"?r.headSeq>0?r.headSeq:1:typeof i?.initialPosition=="number"?i.initialPosition:r.tailSeq+1}let l=new Map,w=new Map,S=[],M=i?.retry?.maxRetries??3,q=i?.retry?.backoff??X(),O=i?.deadLetterTopic,k=!1,I=!1,C=J(d,{name:`${g}:pos`}),A=J(0,{name:`${g}:pending`}),D=Z([r.lengthStore,r.events,C],()=>{let c=r.tailSeq,m=C.get(),T=r.headSeq,F=T>0?Math.max(m,T):m;return Math.max(0,c-F+1)},{name:`${g}:backlog`}),x=i?.persistence;function Q(){x&&Promise.resolve(x.save(`${g}:cursor`,d)).catch(()=>{})}function p(){return f!=="failover"||!t?!0:t.consumers.values().next().value===a}function y(c){let m=0;for(let T=0;T<c.length;T++)m=(m<<5)-m+c.charCodeAt(T)|0;return Math.abs(m)}function $(c){if(f!=="key_shared"||!t||!c)return!0;let m=Array.from(t.consumers),T=y(c)%m.length;return m[T]===a}function G(c){if(k||I)return[];if(!p())return[];let m=c??h,T=[],F=Date.now(),z=[],H=[];for(let E of S)E.readyAt<=F&&z.length<m?z.push(E):H.push(E);S.length=0,S.push(...H);for(let E of z){let Y=r.get(E.seq);if(Y){let W=ge(Y);T.push(W),K(E.seq)}}let ae=m-T.length,U=-1;if(ae>0){let E=s&&t?t.cursor:d,Y=r.tailSeq,W=0;for(let j=E;j<=Y&&W<ae;j++){let oe=r.get(j);if(!oe||f==="key_shared"&&!$(oe.value.key))continue;if(f==="shared"&&t&&t.consumers.size>1){let ue=Array.from(t.consumers),ve=t.roundRobinIndex%ue.length;if(ue[ve]!==a)continue;t.roundRobinIndex++}let he=ge(oe);T.push(he),K(j),j>U&&(U=j),W++}if(U>=0){let j=U+1;s&&t&&(t.cursor=Math.max(t.cursor,j)),d=s&&t?t.cursor:j}}return T.length>0&&P(()=>{C.set(d),A.update(E=>E+T.length)}),T}function K(c){let m;n>0&&(m=setTimeout(()=>{l.has(c)&&_(c)},n)),l.set(c,{timer:m})}function e(c){let m=l.get(c);m&&(m.timer&&clearTimeout(m.timer),l.delete(c),w.delete(c),A.update(T=>Math.max(0,T-1)),Q())}function u(c,m){if(O){let T=r.get(c);T&&O.publish(T.value.value,{key:T.value.key,headers:{...T.value.headers,"x-original-topic":o.name,"x-retry-count":String(m),"x-original-seq":String(c)}})}w.delete(c)}function _(c){let m=l.get(c);if(!m)return;m.timer&&clearTimeout(m.timer),l.delete(c),A.update(H=>Math.max(0,H-1));let T=w.get(c)??{attempts:0},F=T.attempts+1;if(F>M){u(c,F);return}let z=q(F-1,void 0,T.prevDelay);if(z===null){u(c,F);return}w.set(c,{attempts:F,prevDelay:z}),S.push({seq:c,readyAt:Date.now()+z})}function L(c){if(I)return;let m;c==="earliest"?m=r.headSeq>0?r.headSeq:1:c==="latest"?m=r.tailSeq+1:m=c,d=m,s&&t&&(t.cursor=m),C.set(m);for(let T of l.values())T.timer&&clearTimeout(T.timer);l.clear(),A.set(0),S.length=0,w.clear(),Q()}let ie,te;if(x){let c=pe(x.load(`${g}:cursor`));te=c,ie=ce([c],()=>{let m=c.get();typeof m=="number"&&L(m)})}function Te(){if(!I){I=!0,ie?.(),te&&R(te);for(let c of l.values())c.timer&&clearTimeout(c.timer);l.clear(),S.length=0,w.clear(),t&&(t.consumers.delete(a),t.consumers.size===0&&b.removeGroup(g)),P(()=>{R(C),R(A),R(D)})}}return{get name(){return g},get mode(){return f},pull:G,ack:e,nack:_,seek:L,position:C,backlog:D,pending:A,pause(){k||(k=!0,C.signal(V),A.signal(V))},resume(){k&&(k=!1,C.signal(N),A.signal(N))},get isPaused(){return k},destroy:Te}}function ye(o,i,a){let g=a?.threshold??0,f=null,h=!1;function n(){if(h)return 0;let b=o.toArray();if(b.length===0)return 0;let r=new Map,d=[];for(let v of b){let l=i(v.value);r.has(l)||d.push(l),r.set(l,v.value)}let s=d.map(v=>r.get(v)),t=b.length-s.length;if(t===0)return 0;h=!0;try{o.clear(),o.appendMany(s)}finally{h=!1}return t}return g>0&&(f=B(o.events,b=>{b?.type==="append"&&o.length>=g&&n()})),{compact:n,destroy(){f?.unsubscribe(),f=null}}}var Re=0;function ee(o){return{seq:o.seq,value:o.value.value,timestamp:o.value.timestamp,key:o.value.key,priority:o.value.priority,headers:o.value.headers}}function se(o,i){let a=++Re,g=i?.namespace,f=g?g.prefix(o):o,h=`topic-${f}-${a}`,n=fe({id:`${h}:log`,maxSize:i?.maxSize}),b;if(i?.compaction){let p=i.compaction.keyFn;b=ye(n,y=>p(y.value),{threshold:i.compaction.threshold})}let r=i?.dedup?.windowMs??6e4,d=new Map,s;r>0&&(s=setInterval(()=>{let p=Date.now();for(let[y,$]of d)p-$>=r&&d.delete(y)},Math.min(r,3e4)),s&&typeof s=="object"&&"unref"in s&&s.unref());let t=!1,v=!1,l=new Set,w=new Map,S=J(0,{name:`${h}:pubCount`}),M=J(0,{name:`${h}:ver`}),q=n.lengthStore,O=Z([n.latest],()=>{let p=n.latest.get();return p?ee(p):void 0},{name:`${h}:latest`}),k=i?.schema,I=i?.persistence?g?g.checkpoint(i.persistence):i.persistence:void 0,C={getOrCreateGroup(p){let y=w.get(p);return y||(y={cursor:n.tailSeq+1,roundRobinIndex:0,consumers:new Set},w.set(p,y)),y},removeGroup(p){w.delete(p)}};function A(p,y){if(v||t)return-1;k&&(p=k.parse(p));let $=y?.dedupKey;if($){let e=Date.now(),u=d.get($);if(u!==void 0&&e-u<r)return-1;d.set($,e)}let G={value:p,timestamp:Date.now(),key:y?.key,priority:y?.priority,headers:y?.headers};if(y?.delay&&y.delay>0){let e=setTimeout(()=>{l.delete(e),!v&&!t&&P(()=>{n.append(G),S.update(u=>u+1),M.update(u=>u+1)})},y.delay);return l.add(e),-1}return P(()=>{let e=n.append(G);return S.update(u=>u+1),M.update(u=>u+1),e})}function D(p){let y=n.get(p);return y?ee(y):void 0}function x(p,y){return n.slice(p,y).map(ee)}let Q={get id(){return h},get version(){return M.get()},get name(){return f},publish:A,get(p){return D(p)},slice(p,y){return x(p,y)},get headSeq(){return n.headSeq},get tailSeq(){return n.tailSeq},depth:q,latest:O,publishCount:S,peek(){if(n.length===0)return;let p=n.get(n.headSeq);return p?ee(p):void 0},pause(){if(!t){t=!0;for(let p of l)clearTimeout(p);l.clear(),S.signal(V),M.signal(V)}},resume(){t&&(t=!1,S.signal(N),M.signal(N))},get paused(){return t},destroy(){if(!v){v=!0;for(let p of l)clearTimeout(p);l.clear(),s&&clearInterval(s),d.clear(),b?.destroy(),P(()=>{R(S),R(M),R(O),n.destroy()}),w.clear()}}};return Q[Symbol.for("callbag-recharge:topic-internal")]=C,Q[Symbol.for("callbag-recharge:topic-log")]=n,Q}function xe(o,i,a){let g=a?.concurrency??1,f=a?.ackTimeout??3e4,h=a?.stallInterval??5e3,n=a?.stalledJobAction??"none",b=a?.retry?.maxRetries??3,r=a?.retry?.backoff??X(),d=J(!1,{name:`${o}:paused`}),s=!1,t=0,v=new AbortController,l=new Map,w={completed:new Set,failed:new Set,stalled:new Set},S=J(0,{name:`${o}:active`}),M=J(0,{name:`${o}:completed`}),q=J(0,{name:`${o}:failed`}),O=J(0,{name:`${o}:waiting`}),k=se(`${o}:jobs`,a?.topicOptions),I=ne(k,{name:`${o}:worker`,mode:"shared",initialPosition:"earliest",ackTimeout:0});function C(){let e=new AbortController;return v.signal.addEventListener("abort",()=>e.abort(),{once:!0}),e}function A(e){return{seq:e.seq,data:e.data,status:e.status,result:e.result,error:e.error,duration:e.duration,attempts:e.attempts}}function D(e,u){let _=A(u);for(let L of w[e])try{L(_)}catch{}}function x(){s||O.set(Math.max(0,I.backlog.get()))}async function Q(e){for(;;){e.status="active",e.startTime=Date.now(),e.attempts++,t++,P(()=>{S.update(u=>u+1),x()});try{let u=await i(e.abort.signal,e.data);if(s)return;e.status="completed",e.result=u,e.duration=Date.now()-e.startTime,t--,I.ack(e.seq),P(()=>{S.update(_=>Math.max(0,_-1)),M.update(_=>_+1),x()}),D("completed",e);return}catch(u){if(s)return;if(e.duration=Date.now()-e.startTime,t--,P(()=>{S.update(_=>Math.max(0,_-1))}),e.attempts<b){let _=r(e.attempts-1,u,void 0);if(_===null){y(e,u);return}if(_>0&&await re(be(_,e.abort.signal)),d.get())try{await re(d,L=>!L)}catch{return}if(s)return;e.abort=C();continue}y(e,u);return}}}async function p(e){try{await Q(e)}finally{l.delete(e.seq),s||$()}}function y(e,u){if(e.status="failed",e.error=u,I.ack(e.seq),P(()=>{q.update(_=>_+1),x()}),a?.deadLetterTopic)try{a.deadLetterTopic.publish(e.data,{headers:{"x-original-queue":o,"x-retry-count":String(e.attempts),"x-original-seq":String(e.seq)}})}catch{}D("failed",e)}function $(){if(d.get()||s)return;let e=g-t;if(e<=0)return;let u=I.pull(e);if(u.length!==0){x();for(let _ of u){let L={seq:_.seq,data:_.value,status:"waiting",attempts:0,abort:C()};l.set(_.seq,L),p(L).catch(()=>{})}}}let G=setInterval(()=>{!d.get()&&!s&&(x(),$())},100),K=setInterval(()=>{if(s)return;let e=Date.now();for(let u of l.values())u.status==="active"&&u.startTime&&e-u.startTime>f&&(u.status="stalled",D("stalled",u),(n==="cancel"||n==="retry")&&(u.abort.abort(),n==="cancel"&&(u.attempts=b)))},h);return x(),$(),{get name(){return o},add(e,u){let _=k.publish(e,u);return x(),queueMicrotask(()=>$()),_},active:S,completed:M,failed:q,waiting:O,on(e,u){return w[e].add(u),()=>{w[e].delete(u)}},pause(){d.get()||(d.set(!0),I.pause())},resume(){d.get()&&(d.set(!1),I.resume(),$())},get isPaused(){return d.get()},destroy(){s||(s=!0,v.abort(),G&&(clearInterval(G),G=null),K&&(clearInterval(K),K=null),I.destroy(),k.destroy(),l.clear(),P(()=>{R(d),R(S),R(M),R(q),R(O)}))}}}var Je=0;function ke(o,i,a){let g=`repeat-${++Je}`,f=a.limit??0,h=!0,n,b=J(0,{name:`${g}:count`}),r={key:a.key,headers:a.headers,dedupKey:a.dedupKey};function d(){return typeof i=="function"?i():i}function s(){if(!h)return;if(f>0&&b.get()>=f){t();return}let l={...r};a.dedupKey&&(l.dedupKey=`${a.dedupKey}:${b.get()}`),o.publish(d(),l),b.update(w=>w+1),f>0&&b.get()>=f&&t()}function t(){h&&(h=!1,n!==void 0&&(clearInterval(n),n=void 0),R(b))}if(a.every&&a.every>0)n=setInterval(s,a.every),n&&typeof n=="object"&&"unref"in n&&n.unref();else if(a.cron){let S=function(){if(!h)return;let M=new Date,q=M.getFullYear()*1e8+(M.getMonth()+1)*1e6+M.getDate()*1e4+M.getHours()*100+M.getMinutes();q!==w&&me(l,M)&&(w=q,s())};var v=S;let l=de(a.cron),w=0;n=setInterval(S,6e4),n&&typeof n=="object"&&"unref"in n&&n.unref(),S()}return{cancel:t,get count(){return b},get active(){return h}}}export{Se as jobFlow,xe as jobQueue,ke as repeatPublish,ne as subscription,se as topic};
@@ -1,7 +1,7 @@
1
1
  import { S as Store } from '../types-BohB8jJr.cjs';
2
2
  import { N as NodeV0, c as ReactiveLog } from '../types-CrTRz6Oy.cjs';
3
3
  import { B as BackoffStrategy } from '../backoff-BXsH2Ago.cjs';
4
- import { a as RetryOptions } from '../retry-CVlLqopQ.cjs';
4
+ import { R as RetryOptions } from '../retry-CFYCmi5U.cjs';
5
5
  import '../protocol-fwiQ1TAS.cjs';
6
6
  import '../eviction-DGPP1vHP.cjs';
7
7
 
@@ -1,7 +1,7 @@
1
1
  import { S as Store } from '../types-CB1htCM8.js';
2
2
  import { N as NodeV0, c as ReactiveLog } from '../types-Ds0-O16t.js';
3
3
  import { B as BackoffStrategy } from '../backoff-BXsH2Ago.js';
4
- import { a as RetryOptions } from '../retry-CcB64N7t.js';
4
+ import { R as RetryOptions } from '../retry-uvt4L9x2.js';
5
5
  import '../protocol-fwiQ1TAS.js';
6
6
  import '../eviction-DGPP1vHP.js';
7
7
 
@@ -37,4 +37,4 @@ interface RetryMeta {
37
37
  */
38
38
  declare function retry<A>(config: number | RetryOptions): StoreOperator<A, A>;
39
39
 
40
- export { type DelayStrategy as D, type RetryMeta as R, type RetryOptions as a, retry as r };
40
+ export { type DelayStrategy as D, type RetryOptions as R, type RetryMeta as a, retry as r };
@@ -37,4 +37,4 @@ interface RetryMeta {
37
37
  */
38
38
  declare function retry<A>(config: number | RetryOptions): StoreOperator<A, A>;
39
39
 
40
- export { type DelayStrategy as D, type RetryMeta as R, type RetryOptions as a, retry as r };
40
+ export { type DelayStrategy as D, type RetryOptions as R, type RetryMeta as a, retry as r };