@graphrefly/graphrefly 0.42.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-5ST42ESJ.js → chunk-3XDYJRYU.js} +1 -1
- package/dist/{chunk-FDZAZNRO.js → chunk-4YAN45KM.js} +1 -1
- package/dist/{chunk-ACMJ2ZPS.js → chunk-626TESAC.js} +1 -1
- package/dist/{chunk-7B7ELAT2.js → chunk-6HOSXQKF.js} +1 -1
- package/dist/{chunk-G5VBJ5K6.js → chunk-CUNIRONA.js} +1 -1
- package/dist/chunk-EBW4V6JN.js +1 -0
- package/dist/chunk-FDQGFWLF.js +1 -0
- package/dist/{chunk-KY2LMAXU.js → chunk-FG4TKHMC.js} +1 -1
- package/dist/{chunk-YGL7FPVQ.js → chunk-I7IGYPSL.js} +1 -1
- package/dist/{chunk-3K7HA4Y6.js → chunk-INQD2KRQ.js} +1 -1
- package/dist/{chunk-AGNM6RS6.js → chunk-JNWRYDJN.js} +1 -1
- package/dist/{chunk-LDQ3IUIP.js → chunk-JQFH2DV6.js} +1 -1
- package/dist/{chunk-5QRRKBUT.js → chunk-K2Q24F5T.js} +1 -1
- package/dist/chunk-KVV66NN2.js +1 -0
- package/dist/{chunk-3ERTUW2J.js → chunk-NON4NLIC.js} +4 -4
- package/dist/{chunk-IZM3UEH3.js → chunk-O2BLLH7M.js} +1 -1
- package/dist/{chunk-FUZ6S2DY.js → chunk-OCKEEPRJ.js} +1 -1
- package/dist/{chunk-NWXQIOIB.js → chunk-OFZG3TB3.js} +1 -1
- package/dist/{chunk-4QH6VJF4.js → chunk-OYJKFY7V.js} +1 -1
- package/dist/{chunk-7ARY3Y3T.js → chunk-P6C4WHZO.js} +1 -1
- package/dist/{chunk-Q7QQQA3I.js → chunk-PT7W5FCD.js} +1 -1
- package/dist/{chunk-KCACBSJH.js → chunk-Q4U3A3L5.js} +1 -1
- package/dist/{chunk-LPRWATHB.js → chunk-QE4IGY7I.js} +1 -1
- package/dist/{chunk-WHMUB5QB.js → chunk-QYVXF7GW.js} +1 -1
- package/dist/{chunk-DEJTNNQC.js → chunk-S3EEIPO7.js} +1 -1
- package/dist/{chunk-KT5DTRBP.js → chunk-SUWT3ZON.js} +1 -1
- package/dist/{chunk-CISGGAIF.js → chunk-TPKQW72B.js} +1 -1
- package/dist/{chunk-2K5RXLAH.js → chunk-V5A7M7RJ.js} +1 -1
- package/dist/{chunk-AS3TV2TV.js → chunk-VNC3TMVY.js} +1 -1
- package/dist/{chunk-6YFZMUMR.js → chunk-VOPGGIL7.js} +1 -1
- package/dist/{chunk-VRALOYRD.js → chunk-VQ4A6T2A.js} +1 -1
- package/dist/{chunk-HZKW2AAB.js → chunk-XG62INFA.js} +1 -1
- package/dist/{chunk-7VKFXLZQ.js → chunk-Y4NI3X7O.js} +1 -1
- package/dist/compat/index.cjs +5 -5
- package/dist/compat/index.d.cts +4 -4
- package/dist/compat/index.d.ts +4 -4
- package/dist/compat/index.js +1 -1
- package/dist/compat/nestjs/index.cjs +5 -5
- package/dist/compat/nestjs/index.d.cts +3 -3
- package/dist/compat/nestjs/index.d.ts +3 -3
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/zustand/index.js +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/extra/index.cjs +11 -11
- package/dist/extra/index.d.cts +2 -2
- package/dist/extra/index.d.ts +2 -2
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/sources.js +1 -1
- package/dist/graph/index.cjs +1 -1
- package/dist/graph/index.d.cts +1 -1
- package/dist/graph/index.d.ts +1 -1
- package/dist/graph/index.js +1 -1
- package/dist/{index-C0-Jv1kP.d.cts → index-0rKFCVFp.d.cts} +9 -0
- package/dist/{index-B11anra4.d.cts → index-B5iz82A3.d.cts} +2 -2
- package/dist/{index-BtAsBp8K.d.cts → index-BAOD98JD.d.cts} +1 -1
- package/dist/{index-D-Xs74HZ.d.cts → index-BiX1Nkgx.d.cts} +13 -3
- package/dist/{index-HoU88d5U.d.cts → index-BojK2fwH.d.cts} +2 -2
- package/dist/{index-3NmAfcH0.d.cts → index-BwLvVVsy.d.cts} +1 -1
- package/dist/{index-DQo8xBgd.d.ts → index-C59mYFKp.d.ts} +1 -1
- package/dist/{index-DBIqYS43.d.cts → index-C9pjcz3l.d.cts} +0 -15
- package/dist/{index-CJQm0g38.d.ts → index-CAC_rNzm.d.ts} +1 -1
- package/dist/{index-sl4NyzQx.d.cts → index-CDXc9zKM.d.cts} +1 -1
- package/dist/{index-2B7u2pVn.d.cts → index-CLon-IWF.d.cts} +1 -1
- package/dist/{index-CEMx8n40.d.cts → index-COD1kVoS.d.cts} +1 -1
- package/dist/{index-Bn4zHYLj.d.ts → index-CPT7C_f1.d.ts} +1 -1
- package/dist/{index-D8l8hNXn.d.ts → index-CQG3D1cp.d.ts} +1 -1
- package/dist/{index-DO9XxMzS.d.ts → index-CZQXo5tH.d.ts} +0 -15
- package/dist/{index-Bbkgpt5t.d.ts → index-D-AEQVLo.d.ts} +2 -2
- package/dist/{index-CZmcDtFn.d.ts → index-D4Y1cMG0.d.ts} +1 -1
- package/dist/{index-B3OTH1dV.d.ts → index-DSZ3ZCHF.d.ts} +1 -1
- package/dist/{index-BUYXac2c.d.ts → index-Dh_HJ82K.d.ts} +2 -2
- package/dist/{index-4Uz-e_fL.d.ts → index-DwigL4lY.d.ts} +13 -3
- package/dist/{index-CPNSy-U0.d.cts → index-DyR7eU5S.d.cts} +19 -0
- package/dist/{index-BeT2r7sk.d.ts → index-JZUPJIJy.d.ts} +19 -0
- package/dist/{index-pT8sCpOJ.d.ts → index-K0_0eR8g.d.ts} +9 -0
- package/dist/{index-CJIuLu2f.d.cts → index-O16yXPK4.d.cts} +1 -1
- package/dist/{index-LIpQQE9f.d.cts → index-O7fucFrU.d.cts} +1 -1
- package/dist/{index-DmAgG5CI.d.cts → index-RV_yDjOX.d.cts} +1 -1
- package/dist/{index-D6egPFAL.d.ts → index-cm1GNcWE.d.ts} +1 -1
- package/dist/{index-CpyNFqkB.d.ts → index-wAzD9yVj.d.ts} +1 -1
- package/dist/index.cjs +39 -39
- package/dist/index.d.cts +16 -16
- package/dist/index.d.ts +16 -16
- package/dist/index.js +1 -1
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +15 -15
- package/dist/patterns/ai/index.d.cts +5 -5
- package/dist/patterns/ai/index.d.ts +5 -5
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/cqrs/index.cjs +3 -3
- package/dist/patterns/cqrs/index.d.cts +2 -2
- package/dist/patterns/cqrs/index.d.ts +2 -2
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +2 -2
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +4 -4
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/harness/index.cjs +7 -7
- package/dist/patterns/harness/index.d.cts +5 -5
- package/dist/patterns/harness/index.d.ts +5 -5
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/inspect/index.cjs +3 -3
- package/dist/patterns/inspect/index.d.cts +1 -1
- package/dist/patterns/inspect/index.d.ts +1 -1
- package/dist/patterns/inspect/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +3 -3
- package/dist/patterns/job-queue/index.d.cts +2 -2
- package/dist/patterns/job-queue/index.d.ts +2 -2
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/memory/index.cjs +3 -3
- package/dist/patterns/memory/index.d.cts +2 -2
- package/dist/patterns/memory/index.d.ts +2 -2
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +3 -3
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +3 -3
- package/dist/patterns/orchestration/index.d.cts +3 -3
- package/dist/patterns/orchestration/index.d.ts +3 -3
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.cjs +1 -1
- package/dist/patterns/process/index.d.cts +3 -3
- package/dist/patterns/process/index.d.ts +3 -3
- package/dist/patterns/process/index.js +1 -1
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/surface/index.cjs +3 -3
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{pipeline-graph-WBlobVhU.d.cts → pipeline-graph-DPqKDk59.d.cts} +2 -2
- package/dist/{pipeline-graph-v8fMvqNk.d.ts → pipeline-graph-loP57TBA.d.ts} +2 -2
- package/dist/resilience-YIWPK4YC.js +1 -0
- package/dist/{sugar-CH-2ZY90.d.ts → sugar-DLwvMr3F.d.ts} +23 -3
- package/dist/{sugar-DStZfUEK.d.cts → sugar-DyVGtczU.d.cts} +23 -3
- package/package.json +1 -1
- package/dist/chunk-3ZZX7M25.js +0 -1
- package/dist/chunk-VE5SIZEM.js +0 -1
- package/dist/chunk-XLQPNNIC.js +0 -1
- package/dist/resilience-445VFFXQ.js +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var gt=Object.defineProperty;var $n=Object.getOwnPropertyDescriptor;var Fn=Object.getOwnPropertyNames;var Vn=Object.prototype.hasOwnProperty;var P=(r,e)=>()=>(r&&(e=r(r=0)),e);var zn=(r,e)=>{for(var t in e)gt(r,t,{get:e[t],enumerable:!0})},jn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fn(e))!Vn.call(r,s)&&s!==t&>(r,s,{get:()=>e[s],enumerable:!(n=$n(e,s))||n.enumerable});return r};var Bn=r=>jn(gt({},"__esModule",{value:!0}),r);function re(){return Math.trunc(performance.now()*1e6)}function ne(){return Date.now()*1e6}var we=P(()=>{"use strict"});function zt(r){return Array.isArray(r)?[...r]:[r]}function Hn(r,e){return r.has(e)||r.has("*")}function Te(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(zt(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(zt(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)Hn(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function mt(r){let e=qn.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var X,qn,ce=P(()=>{"use strict";X=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};qn=["human","llm","wallet","system"]});function Be(r){if(r==null)return Ee;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var Ee,He=P(()=>{"use strict";Ee={type:"system",id:""}});function qe(){return xe>0||De}function jt(){return xe>0}function Ne(r){xe>0?Me.push(r):r()}function ke(r){xe+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(xe-=1,xe===0)if(e){if(!De){let t=Me.splice(0);for(let n of t)try{n()}catch{}le.length=0,fe.length=0,Oe.length=0}}else Wn()}}function Wn(){let r=!De;r&&(De=!0);let e=[],t=0;try{for(;le.length>0||fe.length>0||Oe.length>0||r&&Me.length>0;){if(r&&Me.length>0){let o=Me.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw le.length=0,fe.length=0,Oe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(le.length>0?le:fe.length>0?fe:Oe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(De=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function We(r,e,t){if(e.length===0)return;if(e.length===1){let u=t(e[0][0]);if(u<3||!qe()){r(e);return}(u>=5?Oe:u===4?fe:le).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let d=qe();if(s>0){let u=e.slice(0,s);r(u)}if(o>s){let u=e.slice(s,o);d?le.push(()=>r(u)):r(u)}if(i>o){let u=e.slice(o,i);d?fe.push(()=>r(u)):r(u)}if(n>i){let u=e.slice(i,n);d?Oe.push(()=>r(u)):r(u)}}var xe,De,le,fe,Oe,Me,Ge=P(()=>{"use strict";xe=0,De=!1,le=[],fe=[],Oe=[],Me=[]});var Re,M,B,U,Q,te,se,j,H,L,pe,Ue,Bt,Ke,Ht,qt,Ye,yt,bt,vt,Je,he=P(()=>{"use strict";Re=Symbol.for("graphrefly/START"),M=Symbol.for("graphrefly/DATA"),B=Symbol.for("graphrefly/DIRTY"),U=Symbol.for("graphrefly/RESOLVED"),Q=Symbol.for("graphrefly/INVALIDATE"),te=Symbol.for("graphrefly/PAUSE"),se=Symbol.for("graphrefly/RESUME"),j=Symbol.for("graphrefly/TEARDOWN"),H=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),pe=Object.freeze([B]),Ue=Object.freeze([U]),Bt=Object.freeze([Q]),Ke=Object.freeze([Re]),Ht=Object.freeze([H]),qt=Object.freeze([j]),Ye=Object.freeze([pe]),yt=Object.freeze([Ue]),bt=Object.freeze([Bt]),vt=Object.freeze([Ht]),Je=Object.freeze([qt])});function Wt(r){r.registerMessageType(Re,{tier:0,wireCrossing:!1}),r.registerMessageType(B,{tier:1,wireCrossing:!1}),r.registerMessageType(Q,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(te,{tier:2,wireCrossing:!1}),r.registerMessageType(se,{tier:2,wireCrossing:!1}),r.registerMessageType(M,{tier:3,wireCrossing:!0}),r.registerMessageType(U,{tier:3,wireCrossing:!0}),r.registerMessageType(H,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(j,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ze,Ut=P(()=>{"use strict";he();Ze=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let n=this._messageTypes.get(t);return n!=null?n.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Yt(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=_t,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function Jt(r,e){if(r.length<Kt)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${Kt})`);let t=0,n=r[t++];if(n!==_t)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${_t})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Zt(r){r.registerCodec(Un)}var Un,_t,Kt,wt=P(()=>{"use strict";Un={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},_t=1,Kt=4});function Tt(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(Tt);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=Tt(r[t]);return e}return null}function Jn(r){let e=Yn.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,f=1359893119,p=2600822924,h=528734635,l=1541459225,y=new Uint32Array(64),g=(v,_)=>v>>>_|v<<32-_;for(let v=0;v<s;v+=64){for(let w=0;w<16;w++)y[w]=i.getUint32(v+w*4,!1);for(let w=16;w<64;w++){let R=y[w-15],C=y[w-2],S=g(R,7)^g(R,18)^R>>>3,$=g(C,17)^g(C,19)^C>>>10;y[w]=y[w-16]+S+y[w-7]+$>>>0}let _=a,b=d,T=u,N=c,m=f,x=p,k=h,O=l;for(let w=0;w<64;w++){let R=g(m,6)^g(m,11)^g(m,25),C=m&x^~m&k,S=O+R+C+Kn[w]+y[w]>>>0,$=g(_,2)^g(_,13)^g(_,22),z=_&b^_&T^b&T,W=$+z>>>0;O=k,k=x,x=m,m=N+S>>>0,N=T,T=b,b=_,_=S+W>>>0}a=a+_>>>0,d=d+b>>>0,u=u+T>>>0,c=c+N>>>0,f=f+m>>>0,p=p+x>>>0,h=h+k>>>0,l=l+O>>>0}let E=v=>v.toString(16).padStart(8,"0");return E(a)+E(d)+E(u)+E(c)+E(f)+E(p)+E(h)+E(l)}function Et(r){let e=Tt(r??null),t=JSON.stringify(e);return Jn(t).slice(0,16)}function Zn(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function xt(r,e,t){let n=t?.id??Zn();if(r===0)return{id:n,version:0};let o=(t?.hash??Et)(e);return{id:n,version:0,cid:o,prev:null}}function Xt(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var Kn,Yn,Qt=P(()=>{"use strict";Kn=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Yn=new TextEncoder});function nn(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Ot(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function Xe(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function oe(r,e,t){let n=rn(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return rn(r)?o=(Nt(e)?e:t)??{}:Nt(r)?o=r:o=(Nt(e)?e:t)??{},new F(n,s,o)}var en,tn,Xn,Qn,ge,F,rn,Nt,me=P(()=>{"use strict";wt();He();Ge();we();Ut();ce();he();Qt();en=()=>{},tn=100;Xn=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},Qn=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[Ke]:[Ke,[M,o]];s._status==="dirty"&&i.push(pe),We(e,i,s._config.tierOf)},ge=new Ze({onMessage:Xn,onSubscribe:Qn});Wt(ge);Zt(ge);F=class r{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,n){this._config=n.config??ge,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??Et;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?xt(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(nn);let o={};for(let[a,d]of Object.entries(n.meta??{})){let u={initial:d,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(u.guard=n.guard),o[a]=new r([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[M,a]])},down(a){i._emit(Xe(a))},up(a){i._emitUp(Xe(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??t?.id,d=i?.version??0,u=xt(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=Be(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=Be(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new X({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new X({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:ne()}}down(e,t){let n=Xe(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[M,e]])}up(e,t){if(this._deps.length===0)return;let n=Xe(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=Be(t);if(!this._guard(d,"observe"))throw new X({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)Ot(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=en,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:s},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}Ot(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=nn(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ye),n.unsub=en;try{n.unsub=e.subscribe(s=>{if(n.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[L,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[L,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}Ot(n)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==Re){if(s===B){this._depDirtied(n);return}if(s===Q){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(bt);return}if(s===te||s===se){this._emit([t]);return}if(s===j){this._emit(Je);return}if(s===M)this._depSettledAsData(n,t[1]);else if(s===U)this._depSettledAsResolved(n);else if(s===H)this._depSettledAsTerminal(n,!0);else if(s===L)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===M||s===U)&&this._emit([t]),(s===H||s===L)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ye))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(yt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[L,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(vt)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[L,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[L,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[L,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>tn?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${tn} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[pe,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let d of e){let u=t(d[0]);u<i&&(n=!1),u===3&&(s=!0),d[0]===B&&(o=!0),i=u}let a=e;if(!n){let d=e.map((u,c)=>({m:u,i:c,tier:t(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&t(a[d][0])===0;)d++;return d===0?[pe,...a]:[...a.slice(0,d),pe,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===L&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===j||d[0]===Q);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let d=t[a],u=d[0];if(u!==te&&u!==se){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===te?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let f=d[1];if(u===te)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(f),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(f))c=!1;else if(this._pauseLocks.delete(f),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===j))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Je)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[L,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===M){d=c;break}}for(let c=0;c<e.length;c++){let f=e[c],p=f[0];if(p===M){if(f.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,f[1])}catch(l){s=this._wrapFnError("equals threw",l),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Ue),this._status="resolved";continue}this._cached=f[1],this._versioning!=null&&(d<0||c===d)&&Xt(this._versioning,f[1],this._hashFn)}this._status="settled",n?.push(f)}else if(n?.push(f),p===B)this._status="dirty";else if(p===U)this._status="resolved";else if(p===H){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===L){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Q){if(this._cached!==void 0){let l=this._config.rigorRecorder;if(l!=null)try{l.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let l=h.invalidate;if(typeof l=="function")try{l()}catch{}}}else p===j&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?n??e.slice(0,o):n??e;return s!=null?{finalMessages:u,equalsError:s}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(jt()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Ne(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}We(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);We(this._deliverToSinks,t,this._config.tierOf)}},rn=r=>Array.isArray(r),Nt=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function Qe(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function er(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function Rt(r){let e=new WeakSet,t={};for(let[n,s]of sn(r))t[n]=kt(s,e);return t}function kt(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>kt(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of sn(n))s[o]=kt(i,e);return s}return"<unserializable>"}function sn(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function tr(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function St(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof F&&(i=er(r),a=r._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(n||e.has("status"))&&(d.status=r.status);let u=r instanceof F?r._guard:void 0;if(o){let c={...tr(r)};if(u!=null&&c.access===void 0&&(c.access=mt(u)),s!=null&&s.length>0&&!e.has("meta")){let f={};for(let p of s)p in c&&(f[p]=c[p]);d.meta=f}else d.meta=c}if(r.name!=null&&(d.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(d.sentinel=!0);try{d.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),d.v=c}return(n||e.has("guard"))&&u!=null&&(d.guard=mt(u)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(d.lastMutation=r.lastMutation),d}var At=P(()=>{"use strict";ce();me()});function K(r,e){return oe([],{...e,initial:r})}function et(r,e){return oe((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function Y(r,e,t){return oe(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...t})}var Ie=P(()=>{"use strict";me()});function Ct(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!Ct(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!Ct(r[o],e[o]))return!1;return!0}function on(r,e){return`${r}\0${e}`}function Dt(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let g of s)n.has(g)||o.push(g);o.sort();for(let g of o)t.push({type:"subgraph-mounted",path:g});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let g of a)i.has(g)||d.push(g);d.sort();for(let g of d)t.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of a){if(!i.has(g))continue;let E=r.nodes[g]?.meta,v=e.nodes[g]?.meta;E==null&&v==null||Ct(E??{},v??{})||u.push(g)}u.sort();for(let g of u)t.push({type:"node-meta-changed",path:g,prevMeta:r.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of r.edges)c.set(on(g.from,g.to),g);let f=new Map;for(let g of e.edges)f.set(on(g.from,g.to),g);let p=[];for(let[g,E]of f)c.has(g)||p.push(E);p.sort((g,E)=>g.from<E.from?-1:g.from>E.from?1:g.to<E.to?-1:g.to>E.to?1:0);for(let g of p)t.push({type:"edge-added",from:g.from,to:g.to});let h=[];for(let[g,E]of c)f.has(g)||h.push(E);h.sort((g,E)=>g.from<E.from?-1:g.from>E.from?1:g.to<E.to?-1:g.to>E.to?1:0);for(let g of h)t.push({type:"edge-removed",from:g.from,to:g.to});let l=[];for(let g of i)a.has(g)||l.push(g);l.sort();for(let g of l)t.push({type:"node-removed",path:g});let y=[];for(let g of n)s.has(g)||y.push(g);y.sort();for(let g of y)t.push({type:"subgraph-unmounted",path:g});return{events:t,flushedAt_ns:re()}}var an=P(()=>{"use strict";we()});function ie(r){return r.subscribe(()=>{})}var dn=P(()=>{"use strict"});var Mt=P(()=>{"use strict";dn()});var tt,un=P(()=>{"use strict";tt=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Le,cn=P(()=>{"use strict";Le=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let t=(this.head+this._size)%this.capacity;this.buf[t]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function ln(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return nt(e,t,"no-such-from");if(!o)return nt(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let u=nr(r,e,n);if(u!=null)return u}let d=rt(e,r.nodes[e],0,n);return st(e,t,[d])}if(i===0)return nt(e,t,"no-path");let a=fn(r,e,t,i);return a.found?st(e,t,pn(r,a.pathOrder,n)):nt(e,t,a.truncated?"max-depth-exceeded":"no-path")}function fn(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,d=!1;for(;a<o.length;){let f=o[a++];if(f.path===e)break;if(n!=null&&f.depth>=n){let y=r.nodes[f.path];y?.deps&&y.deps.length>0&&(d=!0);continue}let p=r.nodes[f.path];if(p==null)continue;let h=p.deps??[],l=new Map;for(let y=0;y<h.length;y++){let g=h[y];if(!g)continue;let E=l.get(g);E==null&&(E=[],l.set(g,E)),E.push(y)}for(let[y,g]of l)i.has(y)||(i.add(y),s.set(y,{from:f.path,depIndices:g}),o.push({path:y,depth:f.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==t;){let f=s.get(c);if(f==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=f.depIndices,u.push({path:f.from}),c=f.from}return{found:!0,pathOrder:u,truncated:!1}}function nr(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=rt(e,n,0,t);a.dep_index=o[0];let d=rt(e,n,1,t);return st(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=fn(r,d,e,t.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:st(e,e,pn(r,i.pathOrder,t))}function pn(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=rt(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function rt(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function st(r,e,t){return hn(r,e,!0,"ok",t)}function nt(r,e,t){return hn(r,e,!1,t,[])}function hn(r,e,t,n,s){let o=rr(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function rr(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${sr(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function En(r){if(r.version!==ye)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${ye})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function cr(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let p=o;if(s.length!==p.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],p[h]))return!1;return!0}if(s instanceof Map){let p=o;if(s.size!==p.size)return!1;for(let[h,l]of s)if(!p.has(h)||!n(l,p.get(h)))return!1;return!0}if(s instanceof Set){let p=o;if(s.size!==p.size)return!1;for(let h of s){let l=!1;for(let y of p)if(n(h,y)){l=!0;break}if(!l)return!1}return!0}if(ArrayBuffer.isView(s)){let p=s,h=o;if(p.length!==h.length)return!1;for(let l=0;l<p.length;l++)if(p[l]!==h[l])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let f=new Set(c);for(let p of u)if(!f.has(p)||!n(s[p],o[p]))return!1;return!0};return n(r,e)}function lr(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ot(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=lr(n)}return e+="$",new RegExp(e)}function Gt(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function hr(r){return r==="none"?pr:r==="ansi"||r==null?fr:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function xn(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function gr(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function It(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(I))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${I}' (path separator)`);if(r===ee)throw new Error(`Graph "${e}": ${t} name "${ee}" is reserved for meta companion paths`);gr(r,e,t)}function mr(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(I);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function yr(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function Nn(r){for(let e of r._mounts.values())Nn(e);for(let e of r._nodes.values())try{e.down([[j]],{internal:!0})}catch{}}function kn(r,e){let t=de.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function Lt(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[_,b]of Object.entries(r.nodes)){if(!_)continue;c.add(_);let T=b.deps??[];i.set(_,T);for(let N of T)N&&(c.add(N),a.has(N)||a.set(N,new Set),a.get(N).add(_))}for(let _ of r.edges){if(_==null||typeof _!="object")continue;let b=typeof _.from=="string"?_.from:"",T=typeof _.to=="string"?_.to:"";!b||!T||(c.add(b),c.add(T),u.has(b)||u.set(b,new Set),u.get(b).add(T),d.has(T)||d.set(T,new Set),d.get(T).add(b))}if(!c.has(e))return n.withDetail?s:[];let f=n.both===!0,p=_=>{if(f){let m=i.get(_)??[],x=d.get(_),k=a.get(_),O=u.get(_),w=[...m];return x&&w.push(...x),k&&w.push(...k),O&&w.push(...O),w}if(t==="upstream"){let m=i.get(_)??[],x=d.get(_);return x?[...m,...x]:m}let b=a.get(_),T=u.get(_),N=b?[...b]:[];return T&&N.push(...T),N},h=new Set([e]),l=new Map,y=[{path:e,depth:0}],g=0,E=!1;for(;g<y.length;){let _=y[g++];if(o!=null&&_.depth>=o){p(_.path).length>0&&(E=!0);continue}for(let b of p(_.path))!b||h.has(b)||(h.add(b),l.set(b,_.depth+1),y.push({path:b,depth:_.depth+1}))}let v=[...l.keys()].sort((_,b)=>_<b?-1:_>b?1:0);return n.withDetail?{paths:v,depths:l,truncated:E}:v}function br(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}var I,ee,ye,fr,pr,de,Pt=P(()=>{"use strict";He();Ge();we();ce();he();At();me();Ie();an();Mt();un();cn();wt();gn();vn();I="::",ee="__meta__",ye=1;fr={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},pr={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};de=class r{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(I))throw new Error(`Graph name must not contain '${I}' (got "${e}")`);if(e===ee)throw new Error(`Graph name "${ee}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??ge,this._traceRing=new Le(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=et(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=t?.annotation;if(It(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:re()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof F&&t._applyVersioning(e)}remove(e){It(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${I}${ee}${I}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${I}`)),this._mounts.delete(e),t._parent=void 0,Nn(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[j]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=ot(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(I))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[M,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);ke(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[Q]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[L,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[H]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,u]of this._nodes)n.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof F)for(let c of u._deps){let f=n.get(c.node);f!=null&&a.push([f,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof F)for(let u of d._deps){let c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(It(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=mr(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===ee)return this._resolveMetaChainFromNode(o,s,t.join(I));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(I)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(I))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==ee)throw new Error(`Graph "${this.name}": expected ${ee} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ee} in "${n}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=d,o+=2}return s}signal(e,t){if(t?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let d of this._mounts.values())d._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=yr(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!n.has(u)){n.add(u);try{u.down(e,i)}catch(c){if(c instanceof X)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(d){if(d instanceof X)throw d;o.push(d)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=dr(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=Qe(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[b,T]of a)d.set(T,b);let u=[];{let b=a.map(([,m])=>m),T=new Set(d.values()),N=0;for(;b.length>0;){let m=b.shift();if(m instanceof F)for(let x of m._deps){let k=x.node;if(d.has(k))continue;let O=k.name??"",w=O;if(!w||T.has(w))if(O){let R=2;for(;T.has(`${O}#${R}`);)R++;w=`${O}#${R}`}else for(w=`__internal__/${N++}`;T.has(w);)w=`__internal__/${N++}`;d.set(k,w),T.add(w),u.push([w,k]),b.push(k)}}}let c=[...a,...u],f={};for(let[b,T]of c){if(t!=null&&!T.allowsObserve(t))continue;let N=St(T,i,o),m=T instanceof F?T._deps.map(w=>d.get(w.node)??w.node.name??""):[],{name:x,...k}=N,O={...k,deps:m};if(!o){let w=this._annotations.get(b);w!=null&&(O.annotation=w)}if(n!=null)if(typeof n=="function"){let w=n;if(!(w.length>=2?w(b,O):w(O)))continue}else{let w=!0;for(let[R,C]of Object.entries(n)){let S=R==="deps_includes"?"depsIncludes":R==="meta_has"?"metaHas":R;if(S==="depsIncludes"){if(!O.deps.includes(String(C))){w=!1;break}continue}if(S==="metaHas"){if(!Object.hasOwn(O.meta??{},String(C))){w=!1;break}continue}if(O[S]!==C){w=!1;break}}if(!w)continue}f[b]=O}let p=new Set(Object.keys(f)),h=[];for(let[b,T]of c)if(T instanceof F)for(let N of T._deps){let m=d.get(N.node);m!=null&&h.push([m,b])}h.sort((b,T)=>b[0]<T[0]?-1:b[0]>T[0]?1:b[1]<T[1]?-1:b[1]>T[1]?1:0);let l=h.map(([b,T])=>({from:b,to:T}));(t!=null||n!=null)&&(l=l.filter(b=>p.has(b.from)&&p.has(b.to)));let y=this._collectSubgraphs(""),g=t!=null||n!=null?y.filter(b=>{let T=`${b}${I}`;return[...p].some(N=>N===b||N.startsWith(T))}):y,E=this,v=e;return{name:this.name,nodes:f,edges:l,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(b){let T={...v};return Array.isArray(b)?(T.fields=b,T.detail=void 0):(T.detail=b,T.fields=void 0),E.describe(T)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${I}`))}return t}resourceProfile(e){return bn(this,e)}reachable(e,t,n={}){return n.withDetail===!0?Lt(this.describe(),e,t,{...n,withDetail:!0}):Lt(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(ae(e),ae(t),{...n?.maxDepth!==void 0?{maxDepth:wn(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Tn(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return ln(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=K(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Ne(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),f=[],p=new WeakSet,h=v=>{if(p.has(v)||d)return;p.add(v);let _=v.topology.subscribe(b=>{for(let T of b){if(T[0]!==M)continue;let N=T[1];if(u(),N.kind==="added"&&N.nodeKind==="mount"){let m=v._mounts.get(N.name);m!=null&&h(m)}}});f.push(_);for(let b of v._mounts.keys()){let T=v._mounts.get(b);T!=null&&h(T)}};h(this);let l,y=e.actor;On(y)&&(l=y.subscribe(v=>{let _=!1,b=!1;for(let T of v){let N=T[0];N===M?_=!0:(N===H||N===L||N===j)&&(b=!0)}_&&u(),b&&(l?.(),l=void 0,u())}));let g;try{g=Y([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,_)=>v===_})}catch(v){c(),l?.();for(let _ of f)_();throw i.dispose(),v}let E=ie(g);return{node:g,dispose(){d=!0,c(),l?.();for(let v of f)v();f.length=0,i.dispose(),E()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=Dt(s,o),a=K(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(p,h)=>p===h}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let h of p){if(h[0]!==M)continue;let l=h[1],y=Dt(o,l);o=l,y.events.length!==0&&a.emit(y)}}),f=ie(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[j,"describe-diff disposed"]]),f()}}}_explainReactive(e,t,n){let s=0,o=K(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Ne(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),f=[];e!=null&&be(e)&&f.push(e),t!=null&&be(t)&&f.push(t),n?.maxDepth!=null&&be(n.maxDepth)&&f.push(n.maxDepth),n?.findCycle!=null&&be(n.findCycle)&&f.push(n.findCycle);let p=()=>{for(let v of f)if(v.cache===void 0)return!1;return!0},h=()=>{let v=ae(e),_=ae(t);return{from:v,to:_,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:_,found:!1,reason:"pending",steps:[]})}},l;try{l=Y([o],()=>{if(!p())return h();let v=ae(e),_=ae(t),b={...n?.maxDepth!==void 0?{maxDepth:wn(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Tn(n.findCycle)}:{}};return this._explainStatic(v,_,b)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:ae(e),to:ae(t)},equals:(v,_)=>v.found===_.found&&v.reason===_.reason&&v.steps.length===_.steps.length&&br(v.steps,_.steps)})}catch(v){throw c(),i.dispose(),v}let y=ie(l),g=[],E=v=>{let _;return _=v.subscribe(b=>{let T=!1,N=!1;for(let m of b){let x=m[0];x===M?T=!0:(x===H||x===L||x===j)&&(N=!0)}(T||N)&&u(),N&&_&&(_(),_=void 0)}),()=>{_&&(_(),_=void 0)}};for(let v of f)g.push(E(v));return{node:l,dispose(){d=!0,c();for(let v of g)v?.();g.length=0,i.dispose(),y()}}}_pathsMatching(e){let t=ot(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${I}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${I}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${I}${ee}${I}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=xn(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(n){let c=e,f=this.resolve(c);if(a!=null&&!f.allowsObserve(a))throw new X({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,f]],o,"one"):{subscribe(p){return f.subscribe(p)},up(p){try{f.up?.(p)}catch(h){if(h instanceof X)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let f=u.map(([p,h])=>h.subscribe(l=>{c(p,l)}));return()=>{for(let p of f)p()}},up:(c,f)=>{try{this.resolve(c).up?.(f)}catch(p){if(p instanceof X)return;throw p}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return et(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let y={events:a.slice(),flushedAt_ns:re()};a.length=0,i.emit(y)},f={...t,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,f):this.observe(f),h=y=>{u||(a.push(y),!d&&(d=!0,Ne(()=>{d=!1,c()})))};for(let y of p.events)h(y);let l=p.onEvent(h);return()=>{u=!0,l(),p.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=t.maxEvents,f=c!=null&&c>0?new Le(c):null,p=[],h=new Set,l=t.tiers!=null?new Set(t.tiers):null,y={},g=new Set,E=0,v=0,_=0,b=0,T=0,N=0,m=!1,x=!1,k=0,O=new Map,w=new Map,R=new Map,C=A=>{if(!(l!=null&&!l.has(A.type))){f?f.push(A):p.push(A);for(let G of h)G(A)}},S=A=>l==null||l.has(A),$=()=>s?{timestamp_ns:re(),in_batch:qe(),batch_id:k}:{},z=(A,G)=>{if(!(!u||!(A instanceof F)))return A._setInspectorHook(J=>{if(J.kind==="dep_message")O.set(A,J.depIndex);else if(J.kind==="run"){let Ce=J.batchData.map((D,q)=>D!=null&&D.length>0?D.at(-1):J.prevData[q]);w.set(A,Ce);let Z=J.batchData.map(D=>D!=null?[...D]:void 0);R.set(A,Z),i&&C({type:"derived",path:G,dep_values:Ce,dep_batches:Z,...$()})}})},W=A=>{let G=O.get(A),J=w.get(A);if(!o||J==null)return{};let Z=(G!=null&&G>=0&&A instanceof F?A._deps[G]:void 0)?.node,D=Z?.v,q=R.get(A);return{trigger_dep_index:G,trigger_dep_name:Z?.name,...D!=null?{trigger_version:{id:D.id,version:D.version}}:{},dep_values:[...J],...q!=null?{dep_batches:q}:{}}},ve=[],_e=[];for(let[A,G]of e){let J=z(G,A);J&&ve.push(J),_e.push(G.subscribe(Ce=>{k++;for(let Z of Ce){let D=Z[0],q=$();if(D===M){y[A]=Z[1];let ht=G instanceof F?G.lastMutation?.actor??Ee:Ee;C({type:"data",path:A,data:Z[1],actor:ht,...q,...W(G)})}else if(a)D===B?S("dirty")&&E++:D===U?S("resolved")&&v++:D===Q?S("invalidate")&&_++:D===te?S("pause")&&b++:D===se?S("resume")&&T++:D===j?S("teardown")&&N++:D===H&&!g.has(A)?S("complete")&&(m=!0):D===L&&S("error")&&(x=!0,g.add(A));else if(D===B)S("dirty")&&E++,C({type:"dirty",path:A,...q});else if(D===U)S("resolved")&&v++,C({type:"resolved",path:A,...q,...W(G)});else if(D===Q)S("invalidate")&&_++,C({type:"invalidate",path:A,...q});else if(D===te)S("pause")&&b++,C({type:"pause",path:A,lockId:Z[1],...q});else if(D===se)S("resume")&&T++,C({type:"resume",path:A,lockId:Z[1],...q});else if(D===H)S("complete")&&!g.has(A)&&(m=!0),C({type:"complete",path:A,...q});else if(D===L){S("error")&&(x=!0,g.add(A));let ht=G instanceof F?G.lastMutation?.actor??Ee:Ee;C({type:"error",path:A,data:Z[1],actor:ht,...q})}else D===j&&(S("teardown")&&N++,C({type:"teardown",path:A,...q}))}}))}let Se=!1,Ae=()=>{if(!Se){Se=!0;for(let A of _e)A();for(let A of ve)A();for(let A of je)A({value:void 0,done:!0});je.length=0}},pt=[],je=[];h.add(A=>{let G=je.shift();G?G({value:A,done:!1}):pt.push(A)});let Vt={get values(){return y},get dirtyCount(){return E},get resolvedCount(){return v},get invalidateCount(){return _},get pauseCount(){return b},get resumeCount(){return T},get teardownCount(){return N},get events(){return f?f.toArray():[...p]},get anyCompletedCleanly(){return m},get anyErrored(){return x},get completedWithoutErrors(){return m&&!x},onEvent(A){return h.add(A),()=>h.delete(A)},dispose:Ae,expand(A){Ae();let G={...t};return typeof A=="string"?G.detail=A:Object.assign(G,A),n(xn(G))},[Symbol.asyncIterator](){return{next(){return pt.length>0?Promise.resolve({value:pt.shift(),done:!1}):Se?Promise.resolve({value:void 0,done:!0}):new Promise(A=>je.push(A))},return(){return Ae(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(Vt,t),Vt}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(l=>console.log(l)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:l=>(o==null||o.has(l))&&(i==null||!i.has(l)),d=hr(t.theme),u=n==="stage-log"?re():0,c=l=>l==null?"":t.stageLabels?.[l]??l,f=(l,y)=>l.length>y?`${l.slice(0,y-1)}\u2026`:l,p=l=>l.type==="data"||l.type==="error"?f(Gt(l.data),120):"",h=l=>{if(n==="stage-log"){let m=(re()-u)/1e9,x=c(l.path).padEnd(9);if(l.type==="data"){let k=p(l);return`[${m.toFixed(3)}s] ${x} \u2190${k?` ${k}`:""}`}if(l.type==="error"){let k=p(l);return`[${m.toFixed(3)}s] ${x} \u2717${k?` ${k}`:""}`}return l.type==="complete"?`[${m.toFixed(3)}s] ${x} \u25A0 complete`:`[${m.toFixed(3)}s] ${x} ${l.type}`}if(n==="json")try{return JSON.stringify(l)}catch{return JSON.stringify({type:l.type,path:l.path,data:"[unserializable]"})}let y=d[l.type]??"",g=l.path?`${d.path}${l.path}${d.reset} `:"",E=l.type==="data"||l.type==="error",v=l.type==="pause"||l.type==="resume",_=E?` ${Gt(l.data)}`:v?` ${Gt(l.lockId)}`:"",b=l.type==="data"||l.type==="resolved"||l.type==="derived"?l:void 0,T=b?.trigger_dep_name!=null?` <- ${b.trigger_dep_name}`:b?.trigger_dep_index!=null?` <- #${b.trigger_dep_index}`:"",N=l.in_batch?" [batch]":"";return`${g}${y}${l.type.toUpperCase()}${d.reset}${_}${T}${N}`};e.onEvent(l=>{a(l.type)&&s(h(l),l)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){_n(this._disposers,this.name),this.signal([[j]],{internal:!0}),_n(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:u,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Yt(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??ge,{codec:s,codecVersion:o,payload:i}=Jt(e,n);return s.decode(i,o)}restore(e,t){if(En(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>ot(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&t?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){En(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((l,y)=>{let g=l.split(I).length,E=y.split(I).length;return g!==E?g-E:l<y?-1:l>y?1:0})){let l=h.split(I),y=o;for(let g of l)y._mounts.has(g)||y.mount(g,new r(g)),y=y._mounts.get(g)}let i=s?Object.entries(s).map(([h,l])=>({re:ot(h),factory:l})):[],a=h=>{for(let l of i)if(l.re.test(h))return l.factory},d=h=>{let l=h.split(I),y=l.pop();if(y==null||y.length===0)throw new Error(`invalid snapshot path "${h}"`);let g=o;for(let E of l){let v=g._mounts.get(E);if(!v)throw new Error(`unknown mount "${E}" in path "${h}"`);g=v}return[g,y]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${I}${ee}${I}`)).sort((h,l)=>h[0]<l[0]?-1:h[0]>l[0]?1:0),c=new Map(u),f=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[h,l]of[...c.entries()]){let y=l?.deps??[];if(!y.every(T=>f.has(T)))continue;let[g,E]=d(h),v={...l?.meta??{}},_=a(h),b;if(l?.type==="state")b=K(l.value,{meta:v});else{if(_==null)continue;b=_(E,{path:h,type:l.type,value:l.value,meta:v,deps:y,resolvedDeps:y.map(T=>f.get(T))})}g.add(b,{name:E}),f.set(h,b),c.delete(h),p=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(u,c)=>{if(u.disposed)return;let f=ur(c.nodes);if(u.lastSnapshot!=null&&f!==""&&f===u.lastFingerprint)return;let p=u.seq+1,h=ne(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:h,format_version:ye}:{name:this.name,mode:"diff",diff:kn(u.lastSnapshot,c),seq:p,timestamp_ns:h,format_version:ye};if(u.tier.filter&&!u.tier.filter(g))return;let E;try{E=u.tier.save(g)}catch(v){t.onError?.(v,u.tier);return}if(E&&typeof E.then=="function"){let b=(u.savePending??Promise.resolve()).then(()=>E,()=>E).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=f)},T=>{t.onError?.(T,u.tier)});u.savePending=b.finally(()=>{u.savePending===b&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=f},o=(u,c)=>{try{s(u,c)}catch(f){t.onError?.(f,u.tier)}},i=(u,c)=>{if(!c.some(l=>{let y=this.config.messageTier(l[0]);return y>=3&&y<5}))return;if(t.filter){let l=this.tryResolve(u);if(l==null)return;let y=St(l,Qe("standard"));if(!t.filter(u,y))return}let p,h=()=>(p==null&&(p=this.snapshot()),p);for(let l of n)l.disposed||(l.debounceMs===0?o(l,h()):(l.timer==null&&(l.timer=new tt),l.timer.start(l.debounceMs,()=>{l.disposed||o(l,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(f=>{let p=this.tryResolve(f);return p==null?()=>{}:p.subscribe(h=>i(f,h))});a=()=>{for(let f of c)f()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===ye&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(d){n?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===ye&&i.nodes!=null?i:void 0;if(a!=null)try{return r.fromSnapshot(a,n)}catch(d){n?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:re(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(v=>!n.has(v)).sort(),i=[...n].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of n){if(!s.has(v))continue;let _=e.nodes[v],b=t.nodes[v],T=_.v,N=b.v;T!=null&&N!=null&&T.id===N.id&&T.version!==N.version&&d.push({path:v,id:T.id,from:T.version,to:N.version});let m=T!=null&&N!=null&&T.id===N.id&&T.version===N.version;for(let x of["type","status","sentinel"]){let k=_[x],O=b[x];k!==O&&a.push({path:v,field:x,from:k,to:O})}if(!m)for(let x of["value","meta"]){let k=_[x],O=b[x];cr(k,O)||a.push({path:v,field:x,from:k,to:O})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),f=new Set(t.edges.map(u)),p=t.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!f.has(u(v))),l=new Set(e.subgraphs),y=new Set(t.subgraphs),g=[...y].filter(v=>!l.has(v)).sort(),E=[...l].filter(v=>!y.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:p,edgesRemoved:h,subgraphsAdded:g,subgraphsRemoved:E}}}});var Mn=P(()=>{"use strict";Pt()});function Gn(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var In=P(()=>{"use strict"});var kr={};zn(kr,{CqrsGraph:()=>ft,cqrs:()=>Nr,cqrsEventKeyOf:()=>Er,dispatchKeyOf:()=>xr,sagaInvocationKeyOf:()=>Or});module.exports=Bn(kr);we();ce();He();ce();he();At();me();Ie();Ge();we();ce();he();Ie();Pt();Ge();he();me();Ie();var $t=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let t=0;t<e;t++)this._buf[(this._head+t)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Pe(r){return r.subscribe(()=>{})}var vr=64;function $e(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new $t(r,n),d=K(a.toArray(),{name:t,describeKind:"state",equals:(m,x)=>m===x,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let m=a.toArray();ke(()=>{d.down([[B]],{internal:!0}),d.down([[M,m]],{internal:!0})})}let c=new Map,f=new Map,p=new Map;function h(m,x){return`${m}:${x===void 0?"END":x}`}function l(m){if(m.size<vr)return;let x=m.keys().next();if(x.done)return;let k=m.get(x.value);k!==void 0&&k.dispose(),m.delete(x.value)}function y(m){let x=a.version;try{return m()}finally{a.version!==x&&u()}}function g(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let x=c.get(m);if(x!==void 0)return c.delete(m),c.set(m,x),x.node;l(c);let k=Y([d],([w])=>{let R=w;return m===0||R.length===0?[]:R.slice(Math.max(0,R.length-m))},{initial:a.tail(m),describeKind:"derived"}),O=Pe(k);return c.set(m,{node:k,dispose:O}),k}function E(m,x){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(x!==void 0&&(!Number.isInteger(x)||x<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${x})`);let k=h(m,x),O=f.get(k);if(O!==void 0)return f.delete(k),f.set(k,O),O.node;l(f);let w=Y([d],([C])=>{let S=C;return x===void 0?S.slice(m):S.slice(m,x)},{initial:a.slice(m,x),describeKind:"derived"}),R=Pe(w);return f.set(k,{node:w,dispose:R}),w}function v(m){let x=p.get(m);if(x!==void 0)return x.node;let k=Y([d,m],([w,R])=>{let C=w,S=Math.max(0,Math.trunc(R??0));return C.slice(S)},{initial:[],describeKind:"derived"}),O=Pe(k);return p.set(m,{node:k,dispose:O}),k}let _,b;function T(){_===void 0&&(_=oe([d],(m,x,k)=>{let O=m[0],R=O!=null&&O.length>0?O.at(-1):k.prevData[0];if(R==null||R.length===0){x.down([[U]]);return}x.emit(R[R.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),b=Y([d],([m])=>m.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Pe(_),Pe(b))}let N={entries:d,get size(){return a.size},at(m){return a.at(m)},append(m){y(()=>a.append(m))},appendMany(m){m.length!==0&&y(()=>a.appendMany(m))},clear(){y(()=>a.clear())},trimHead(m){y(()=>a.trimHead(m))},withLatest(){return T(),d},get lastValue(){return T(),_},get hasLatest(){return T(),b},view(m){switch(m.kind){case"tail":return g(m.n);case"slice":return E(m.start,m.stop);case"fromCursor":return v(m.cursor)}},attach(m){let x=m.subscribe(k=>{for(let O of k)O[0]===M&&N.append(O[1])});return()=>x()},attachStorage(m){if(m.length===0)return()=>{};let x=new Map;for(let O of m)x.set(O,a.size);(async()=>{for(let O of m)if(typeof O.loadEntries=="function")try{let w=await Promise.resolve(O.loadEntries());w.entries.length>0&&a.size===0&&(a.restore(w.entries),x.set(O,w.entries.length),u());break}catch{}})();let k=d.subscribe(O=>{for(let w of O){if(w[0]!==M)continue;let R=w[1];for(let C of m){let S=x.get(C)??0;if(R.length<S){try{let z=C.appendEntries(R);z instanceof Promise&&z.catch(()=>{})}catch{}x.set(C,R.length);continue}if(R.length===S)continue;let $=R.slice(S);x.set(C,R.length);try{let z=C.appendEntries($);z instanceof Promise&&z.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of f.values())m.dispose();f.clear();for(let m of p.values())m.dispose();p.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of f.values())m.dispose();f.clear();for(let m of p.values())m.dispose();p.clear()}};return N}var _r=Te((r,e)=>{r("observe"),r("signal"),e("write")});function at(r){let e=$e([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??_r,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Ft(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Ft(r[e]);return Object.freeze(r)}function Rn(r){let e=r.cache,n=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return r.down([[B],[M,n]]),n}function it(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function Sn(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Ft):s,i=ne(),a=e.seq?Rn(e.seq):void 0;try{let d=r(...o);return e.audit&&e.onSuccess&&it(e.audit,e.onSuccess,o,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;it(e.audit,e.onFailure,o,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function An(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Ft):s,i=ne(),a,d,u=!1,c;try{ke(()=>{e.seq&&(c=Rn(e.seq));try{a=r(...o),e.audit&&e.onSuccess&&it(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(f){throw d=f,u=!0,f}})}catch(f){if(u&&e.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;it(e.audit,e.onFailure,o,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:f}return a}}function Cn(r,e,t=0){let n=K(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function Dn(r,e,t,n=0){let s={},o=new de(e);for(let i of t){let a=K(n,{name:i,describeKind:"state"});o.add(a,{name:i}),s[i]=a}return r.mount(e,o),s}Mn();var ue=class extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}},dt=class extends ue{constructor(t,n){super(`Duplicate ${t} registration: "${n}"`);this.kind=t;this.registrationName=n}},ut=class extends ue{constructor(t,n,s){super(`Command "${t}" emitted undeclared event "${n}". Declared emits: [${s.join(", ")}]`);this.commandName=t;this.eventName=n;this.declaredEmits=s}},ct=class extends ue{constructor(t,n,s){super(`Optimistic concurrency conflict on aggregate "${t}": expected version ${n}, got ${s}`);this.aggregateId=t;this.expected=n;this.actual=s}},lt=class extends ue{constructor(t){super(`Unknown command: "${t}". Register with command() first.`);this.commandName=t}},Fe=class extends ue{constructor(t,n){super(`Command handler "${t}" threw: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.commandName=t}};var Ve=class extends ue{constructor(t,n){super(`Projection "${t}" rebuild failed: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.projectionName=t}};In();Mt();var wr=Te((r,e)=>{r("write"),r("signal"),e("observe")}),Tr=Te((r,e)=>{r("observe"),r("signal"),e("write")}),Ln=Te((r,e)=>{r("observe"),r("signal"),e("write")});function ze(r,e){return Gn("cqrs",r,e)}function Pn(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Pn(r[e]);return Object.freeze(r)}var Er=r=>`${r.type}::${r.aggregateId??"__default__"}`,xr=r=>r.commandName,Or=r=>r.eventType,ft=class extends de{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,t={}){super(e,t.graph),this._retainedLimit=t.retainedLimit??1024,this._freezeCommandPayload=t.freezeCommandPayload??!0,this._freezeEventPayload=t.freezeEventPayload??!0,this._maxAggregates=t.maxAggregates??1e4,this.dispatches=at({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=at({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=Cn(this,"dispatch_seq",0)}aggregateVersion(e,t){return this._aggregateVersions.get(`${e}::${t}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let t=e.value;this._aggregateLru.delete(t);let n=t.indexOf("::");if(n<0)continue;let s=t.slice(0,n),o=t.slice(n+2),i=this._aggregateVersions.get(t)??0;this._aggregateVersions.delete(t);let a=this._eventLogsByAggregate.get(s);a&&(a.delete(o),a.size===0&&this._eventLogsByAggregate.delete(s)),this.aggregateEvictions.append({aggregateId:o,type:s,lastVersion:i,t_ns:ne()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[t,n]of this._eventLogs){let s=n.log.attachStorage(e),o=this._attachedTierDisposers.get(t);o||(o=[],this._attachedTierDisposers.set(t,o)),o.push(s)}for(let[t,n]of this._eventLogsByAggregate)for(let[s,o]of n){let i=`${t}::${s}`,a=o.log.attachStorage(e),d=this._attachedTierDisposers.get(i);d||(d=[],this._attachedTierDisposers.set(i,d)),d.push(a)}return()=>{let t=this._attachedEventTiers.indexOf(e);t>=0&&this._attachedEventTiers.splice(t,1)}}_autoWireStreamStorage(e,t){if(this._attachedEventTiers.length===0)return;let n=this._attachedTierDisposers.get(e);n||(n=[],this._attachedTierDisposers.set(e,n));for(let s of this._attachedEventTiers)n.push(t.attachStorage(s))}event(e,t){if(t!==void 0)return this._ensureAggregateStream(e,t).node;let n=this._eventLogs.get(e);if(n)return n.node;let s=$e([],{name:e,versioning:0,maxSize:this._retainedLimit});s.withLatest();let o=s.entries,i=Y([o],([a])=>a,{name:e,describeKind:"state",meta:ze("event",{event_name:e}),guard:Ln,initial:o.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(ie(i)),this._eventLogs.set(e,{log:s,node:i}),this._autoWireStreamStorage(e,s),i}_ensureAggregateStream(e,t){this._eventLogs.has(e)||this.event(e);let n=this._eventLogsByAggregate.get(e);n||(n=new Map,this._eventLogsByAggregate.set(e,n));let s=`${e}::${t}`;this._touchAggregate(s);let o=n.get(t);if(o)return o;let i=`${e}_${t.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=$e([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=Y([d],([h])=>h,{name:i,describeKind:"state",meta:ze("event_aggregate",{event_name:e,aggregate_id:t}),guard:Ln,initial:d.cache}),c=i,f=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(f+=1,c=`${i}_${f}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(ie(u));let p={log:a,node:u};return n.set(t,p),this._autoWireStreamStorage(`${e}::${t}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,t,n){let s=this._eventLogs.get(e);if(s||(this.event(e),s=this._eventLogs.get(e)),s.node.status==="completed"||s.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${s.node.status}).`);let o,i;if(n?.aggregateId!==void 0){let c=`${e}::${n.aggregateId}`;o=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,o),i=this._ensureAggregateStream(e,n.aggregateId)}let a=s.log.entries.v,d=this._freezeEventPayload?Pn(t):t,u={type:e,payload:d,timestampNs:ne(),seq:++this._seq,...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...o!==void 0?{aggregateVersion:o}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...n?.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return s.log.append(u),i&&i.log.append(u),u}command(e,t){if(this._commandRegs.has(e))throw new dt("command",e);let n=typeof t=="function"?{handler:t}:t,s=K(void 0,{name:e,describeKind:"state",meta:{...ze("command",{command_name:e}),error:null},guard:wr});if(this.add(s,{name:e}),this._commandRegs.set(e,{handler:n.handler,...n.emits!==void 0?{emits:n.emits}:{},...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{}}),n.emits)for(let o of n.emits)this._eventLogs.has(o)||this.event(o);return s}dispatch(e,t,n){let s=this._commandRegs.get(e);if(!s)throw new lt(e);if(n?.aggregateId!==void 0&&n.expectedAggregateVersion!==void 0&&s.emits!==void 0){let u=0;for(let c of s.emits){let f=this._aggregateVersions.get(`${c}::${n.aggregateId}`);f!==void 0&&f>u&&(u=f)}if(u!==n.expectedAggregateVersion)throw new ct(n.aggregateId,n.expectedAggregateVersion,u)}let o=this.resolve(e),i=[],a=!1,d=u=>{o.emit(u,{internal:!0});try{s.handler(u,{emit:(c,f)=>{if(s.emits!==void 0&&!s.emits.includes(c))throw new ut(e,c,s.emits);i.push(c),this._appendEvent(c,f,{...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}})}}),o.meta.error.emit(null,{internal:!0})}catch(c){throw a=!0,c}};try{An(d,{audit:this.dispatches,seq:this._dispatchSeqCursor,freeze:this._freezeCommandPayload,onSuccess:([u],c,{t_ns:f,seq:p})=>({commandName:e,payload:u,outcome:"success",emittedEvents:[...i],t_ns:f,seq:p??0,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}}),onFailure:([u],c,{t_ns:f,seq:p,errorType:h})=>{let l=c instanceof Fe?c:new Fe(e,c);return{commandName:e,payload:u,outcome:"failure",error:l,errorType:h,emittedEvents:[...i],t_ns:f,seq:p??0,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}}}})(t)}catch(u){throw a&&o.meta.error.emit(u,{internal:!0}),u}}projection(e){let{name:t,events:n,reducer:s,initial:o}=e,i=e.mode??"scan",a=e.freezeInputs??!0,d=e.snapshot,u=n.map(O=>(this._eventLogs.has(O)||this.event(O),this._eventLogs.get(O).node));function c(O){O.sort((w,R)=>w.timestampNs-R.timestampNs||w.seq-R.seq||(w.aggregateId??"").localeCompare(R.aggregateId??""))}function f(O){let w=[];for(let R of O)w.push(...R);return c(w),w}let p=u.map(O=>O.cache??[]),h=f(p),l=a?Object.freeze(h):h,y=0,g=o;i==="scan"&&h.length>0&&(g=s(o,l),y=h.length);let E=i==="replay"?s(o,l):g,v=d?.saveDebounceMs??1e3,_=d?.saveEvery??1e3,b,T=0;function N(O){if(d?.save){if(T+=1,T>=_){T=0,b!==void 0&&(clearTimeout(b),b=void 0);let w=d.save(O);w instanceof Promise&&w.catch(()=>{});return}b!==void 0&&clearTimeout(b),b=setTimeout(()=>{b=void 0,T=0;let w=d.save(O);w instanceof Promise&&w.catch(()=>{})},v)}}let m=Y(u,O=>{let w=f(O),R;if(i==="replay"){let C=a?Object.freeze(w):w;R=s(o,C)}else{let C=w.slice(y);y=w.length;let S=a?Object.freeze(C):C;R=s(g,S),g=R}return N(R),R},{name:t,describeKind:"derived",meta:ze("projection",{projection_name:t,source_events:n}),guard:Tr,initial:E});return this.add(m,{name:t}),this._keepaliveDisposers.push(ie(m)),this._keepaliveDisposers.push(()=>{b!==void 0&&(clearTimeout(b),b=void 0)}),this._projections.add(t),{node:m,rebuild:async O=>{try{let w=O?.pageSize??1e3,R=O?.fromTier??this._attachedEventTiers[0]?.[0],C=f(u.map($=>$.cache??[])).length,S=o;if(d?.load){let $=await d.load();$!==void 0&&(S=$)}if(!R||!R.loadEntries){let $=f(u.map(W=>W.cache??[])),z=a?Object.freeze($):$;S=s(S,z)}else{let $=new Set(n),z,W=!1;for(;!W;){let ve=await R.loadEntries({cursor:z,pageSize:w}),_e=[...ve.entries].filter(Ae=>$.has(Ae.type));c(_e);let Se=a?Object.freeze(_e):_e;S=s(S,Se),z=ve.cursor,W=!z||ve.entries.length===0}}if(i==="scan"){let $=f(u.map(W=>W.cache??[])),z=$.slice(C);if(z.length>0){let W=a?Object.freeze(z):z;S=s(S,W)}g=S,y=$.length}return m.emit(S,{internal:!0}),S}catch(w){throw new Ve(t,w)}},reset:async()=>{try{let O=o;if(d?.load){let S=await d.load();S!==void 0&&(O=S)}let w=f(u.map(S=>S.cache??[])),R=a?Object.freeze(w):w,C=s(O,R);return i==="scan"&&(g=C,y=w.length),m.emit(C,{internal:!0}),C}catch(O){throw new Ve(t,O)}}}}saga(e,t,n,s={}){let o=t.map(l=>(this._eventLogs.has(l)||this.event(l),this._eventLogs.get(l).node)),i=Dn(this,`${e}_cursor`,t,0),a=at({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=s.aggregateId,u=s.errorPolicy??"advance",c=new Map;for(let l of t){let y=i[l];c.set(l,y.cache??0);let g=y.subscribe(E=>{for(let v of E)v[0]===M&&c.set(l,v[1])});this._keepaliveDisposers.push(g)}let f=Sn((l,y)=>{n(l)},{audit:a,freeze:!1,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{},onSuccess:([l,y],g,{t_ns:E})=>({eventType:y,outcome:"success",aggregateId:l.aggregateId,event:l,t_ns:E}),onFailure:([l,y],g,{t_ns:E,errorType:v})=>({eventType:y,outcome:"failure",error:g,errorType:v,aggregateId:l.aggregateId,event:l,t_ns:E})}),p={},h=oe(o,(l,y)=>{let g=p.n.meta.error;for(let E=0;E<l.length;E++){let v=l[E];if(v==null||v.length===0)continue;let _=v.at(-1);if(!_)continue;let b=t[E],T=i[b],N=c.get(b)??0;if(_.length>N){let m=_.slice(N),x=N;for(let k of m){let O=k;if(d!==void 0&&O.aggregateId!==d){x+=1;continue}try{f(O,b),g.emit(null,{internal:!0}),x+=1}catch(w){if(g.emit(w,{internal:!0}),u==="hold")break;x+=1}}T.emit(x)}}},{name:e,describeKind:"effect",meta:{...ze("saga",{saga_name:e,source_events:t}),error:null}});return p.n=h,this.add(h,{name:e}),this._keepaliveDisposers.push(ie(h)),this._sagas.add(e),{node:h,invocations:a,audit:a,cursors:i}}};function Nr(r,e){let t=new ft(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("cqrs",Rt(o)),t}0&&(module.exports={CqrsGraph,cqrs,cqrsEventKeyOf,dispatchKeyOf,sagaInvocationKeyOf});
|
|
1
|
+
"use strict";var gt=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Vn=Object.getOwnPropertyNames;var zn=Object.prototype.hasOwnProperty;var P=(r,e)=>()=>(r&&(e=r(r=0)),e);var jn=(r,e)=>{for(var t in e)gt(r,t,{get:e[t],enumerable:!0})},Bn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vn(e))!zn.call(r,s)&&s!==t&>(r,s,{get:()=>e[s],enumerable:!(n=Fn(e,s))||n.enumerable});return r};var Hn=r=>Bn(gt({},"__esModule",{value:!0}),r);function re(){return Math.trunc(performance.now()*1e6)}function ne(){return Date.now()*1e6}var we=P(()=>{"use strict"});function zt(r){return Array.isArray(r)?[...r]:[r]}function qn(r,e){return r.has(e)||r.has("*")}function Te(r){let e=[];return r((s,o)=>{e.push({kind:"allow",actions:new Set(zt(s)),where:o?.where??(()=>!0)})},(s,o)=>{e.push({kind:"deny",actions:new Set(zt(s)),where:o?.where??(()=>!0)})}),(s,o)=>{let i=!1,a=!1;for(let d of e)qn(d.actions,o)&&d.where(s)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function mt(r){let e=Wn.filter(t=>r({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}var X,Wn,ce=P(()=>{"use strict";X=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};Wn=["human","llm","wallet","system"]});function Be(r){if(r==null)return Ee;let{type:e,id:t,...n}=r;return{type:e??"system",id:t??"",...n}}var Ee,He=P(()=>{"use strict";Ee={type:"system",id:""}});function qe(){return Oe>0||De}function jt(){return Oe>0}function Ne(r){Oe>0?Me.push(r):r()}function ke(r){Oe+=1;let e=!1;try{r()}catch(t){throw e=!0,t}finally{if(Oe-=1,Oe===0)if(e){if(!De){let t=Me.splice(0);for(let n of t)try{n()}catch{}le.length=0,fe.length=0,xe.length=0}}else Un()}}function Un(){let r=!De;r&&(De=!0);let e=[],t=0;try{for(;le.length>0||fe.length>0||xe.length>0||r&&Me.length>0;){if(r&&Me.length>0){let o=Me.splice(0);for(let i of o)try{i()}catch(a){e.push(a)}continue}if(t+=1,t>1e3)throw le.length=0,fe.length=0,xe.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let s=(le.length>0?le:fe.length>0?fe:xe).splice(0);for(let o of s)try{o()}catch(i){e.push(i)}}}finally{r&&(De=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function We(r,e,t){if(e.length===0)return;if(e.length===1){let u=t(e[0][0]);if(u<3||!qe()){r(e);return}(u>=5?xe:u===4?fe:le).push(()=>r(e));return}let n=e.length,s=n,o=n,i=n,a=0;for(;a<n&&t(e[a][0])<3;)a++;for(s=a;a<n&&t(e[a][0])===3;)a++;for(o=a;a<n&&t(e[a][0])===4;)a++;i=a;let d=qe();if(s>0){let u=e.slice(0,s);r(u)}if(o>s){let u=e.slice(s,o);d?le.push(()=>r(u)):r(u)}if(i>o){let u=e.slice(o,i);d?fe.push(()=>r(u)):r(u)}if(n>i){let u=e.slice(i,n);d?xe.push(()=>r(u)):r(u)}}var Oe,De,le,fe,xe,Me,Ge=P(()=>{"use strict";Oe=0,De=!1,le=[],fe=[],xe=[],Me=[]});var Re,M,B,U,Q,te,se,j,H,L,pe,Ue,Bt,Ke,Ht,qt,Ye,yt,bt,vt,Je,he=P(()=>{"use strict";Re=Symbol.for("graphrefly/START"),M=Symbol.for("graphrefly/DATA"),B=Symbol.for("graphrefly/DIRTY"),U=Symbol.for("graphrefly/RESOLVED"),Q=Symbol.for("graphrefly/INVALIDATE"),te=Symbol.for("graphrefly/PAUSE"),se=Symbol.for("graphrefly/RESUME"),j=Symbol.for("graphrefly/TEARDOWN"),H=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),pe=Object.freeze([B]),Ue=Object.freeze([U]),Bt=Object.freeze([Q]),Ke=Object.freeze([Re]),Ht=Object.freeze([H]),qt=Object.freeze([j]),Ye=Object.freeze([pe]),yt=Object.freeze([Ue]),bt=Object.freeze([Bt]),vt=Object.freeze([Ht]),Je=Object.freeze([qt])});function Wt(r){r.registerMessageType(Re,{tier:0,wireCrossing:!1}),r.registerMessageType(B,{tier:1,wireCrossing:!1}),r.registerMessageType(Q,{tier:1,wireCrossing:!1,metaPassthrough:!1}),r.registerMessageType(te,{tier:2,wireCrossing:!1}),r.registerMessageType(se,{tier:2,wireCrossing:!1}),r.registerMessageType(M,{tier:3,wireCrossing:!0}),r.registerMessageType(U,{tier:3,wireCrossing:!0}),r.registerMessageType(H,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),r.registerMessageType(j,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Ze,Ut=P(()=>{"use strict";he();Ze=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let n=this._messageTypes.get(t);return n!=null?n.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Yt(r,e){let t=new TextEncoder().encode(r.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${r.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let n=r.version;if(!Number.isInteger(n)||n<0||n>65535)throw new Error(`encodeEnvelope: codec.version ${n} out of u16 range (expected integer 0\u201365535)`);let s=2+t.length+2+e.length;if(s>4294967295)throw new Error(`encodeEnvelope: total envelope size ${s} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let o=new Uint8Array(s),i=0;return o[i++]=_t,o[i++]=t.length,o.set(t,i),i+=t.length,o[i++]=n>>>8&255,o[i++]=n&255,o.set(e,i),o}function Jt(r,e){if(r.length<Kt)throw new Error(`decodeEnvelope: bytes too short (${r.length} < ${Kt})`);let t=0,n=r[t++];if(n!==_t)throw new Error(`decodeEnvelope: unsupported envelope version ${n} (expected ${_t})`);let s=r[t++];if(s===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+s+2>r.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+s+2} bytes, have ${r.length})`);let o=new TextDecoder().decode(r.subarray(t,t+s));t+=s;let i=(r[t]<<8|r[t+1])>>>0;t+=2;let a=r.subarray(t),d=e.lookupCodec(o);if(d==null)throw new Error(`decodeEnvelope: codec "${o}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Zt(r){r.registerCodec(Kn)}var Kn,_t,Kt,wt=P(()=>{"use strict";Kn={name:"json",version:1,contentType:"application/json",encode(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)},decode(r,e){let t=new TextDecoder().decode(r);return JSON.parse(t)}},_t=1,Kt=4});function Tt(r){if(r===void 0)return null;if(typeof r=="number"){if(!Number.isFinite(r))throw new TypeError(`Cannot hash non-finite number: ${r}`);if(Number.isInteger(r)&&!Number.isSafeInteger(r))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${r}. Cross-language cid parity is not guaranteed for unsafe integers.`);return r}if(typeof r=="string"||typeof r=="boolean"||r===null)return r;if(Array.isArray(r))return r.map(Tt);if(typeof r=="object"&&r!==null){let e={};for(let t of Object.keys(r).sort())e[t]=Tt(r[t]);return e}return null}function Zn(r){let e=Jn.encode(r),t=e.length,n=t*8,s=t+9+63&-64,o=new Uint8Array(s);o.set(e),o[t]=128;let i=new DataView(o.buffer);i.setUint32(s-4,n>>>0,!1),i.setUint32(s-8,Math.floor(n/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,f=1359893119,p=2600822924,h=528734635,l=1541459225,y=new Uint32Array(64),g=(v,_)=>v>>>_|v<<32-_;for(let v=0;v<s;v+=64){for(let w=0;w<16;w++)y[w]=i.getUint32(v+w*4,!1);for(let w=16;w<64;w++){let R=y[w-15],C=y[w-2],S=g(R,7)^g(R,18)^R>>>3,$=g(C,17)^g(C,19)^C>>>10;y[w]=y[w-16]+S+y[w-7]+$>>>0}let _=a,b=d,T=u,N=c,m=f,O=p,k=h,x=l;for(let w=0;w<64;w++){let R=g(m,6)^g(m,11)^g(m,25),C=m&O^~m&k,S=x+R+C+Yn[w]+y[w]>>>0,$=g(_,2)^g(_,13)^g(_,22),z=_&b^_&T^b&T,W=$+z>>>0;x=k,k=O,O=m,m=N+S>>>0,N=T,T=b,b=_,_=S+W>>>0}a=a+_>>>0,d=d+b>>>0,u=u+T>>>0,c=c+N>>>0,f=f+m>>>0,p=p+O>>>0,h=h+k>>>0,l=l+x>>>0}let E=v=>v.toString(16).padStart(8,"0");return E(a)+E(d)+E(u)+E(c)+E(f)+E(p)+E(h)+E(l)}function Et(r){let e=Tt(r??null),t=JSON.stringify(e);return Zn(t).slice(0,16)}function Xn(){let r=globalThis.crypto;if(r?.randomUUID)return r.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function Ot(r,e,t){let n=t?.id??Xn();if(r===0)return{id:n,version:0};let o=(t?.hash??Et)(e);return{id:n,version:0,cid:o,prev:null}}function Xt(r,e,t){r.version+=1,"cid"in r&&(r.prev=r.cid,r.cid=t(e))}var Yn,Jn,Qt=P(()=>{"use strict";Yn=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jn=new TextEncoder});function nn(r){return{node:r,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function xt(r){r.prevData=void 0,r.dirty=!1,r.involvedThisWave=!1,r.dataBatch.length=0,r.terminal=void 0}function Xe(r){return r.length===0?r:typeof r[0]=="symbol"?[r]:r}function oe(r,e,t){let n=rn(r)?r:[],s=typeof r=="function"?r:typeof e=="function"?e:void 0,o={};return rn(r)?o=(Nt(e)?e:t)??{}:Nt(r)?o=r:o=(Nt(e)?e:t)??{},new F(n,s,o)}var en,tn,Qn,er,ge,F,rn,Nt,me=P(()=>{"use strict";wt();He();Ge();we();Ut();ce();he();Qt();en=()=>{},tn=100;Qn=(r,e,t,n)=>{t.direction==="down-in"&&r._onDepMessage(t.depIndex,e)},er=(r,e,t,n)=>{let s=r;if(s._status==="completed"||s._status==="errored")return;let o=s._cached,i=o===void 0?[Ke]:[Ke,[M,o]];s._status==="dirty"&&i.push(pe),We(e,i,s._config.tierOf)},ge=new Ze({onMessage:Qn,onSubscribe:er});Wt(ge);Zt(ge);F=class r{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,n){this._config=n.config??ge,this._config.onMessage,this._optsName=n.name,this._describeKind=n.describeKind,this._equals=n.equals??Object.is,this._resubscribable=n.resubscribable??!1,this._resetOnTeardown=n.resetOnTeardown??!1,this._autoComplete=n.completeWhenDepsComplete??!0,this._autoError=n.errorWhenDepsError??!0,this._pausable=n.pausable??!0,this._guard=n.guard,this._fn=t,this._partial=n.partial??!1,this._cached=n.initial!==void 0?n.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=n.versioningHash??this._config.defaultHashFn??Et;let s=n.versioning??this._config.defaultVersioning;this._versioningLevel=s,this._versioning=s!=null?Ot(s,this._cached===void 0?void 0:this._cached,{id:n.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(nn);let o={};for(let[a,d]of Object.entries(n.meta??{})){let u={initial:d,name:`${n.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};n.guard!=null&&(u.guard=n.guard),o[a]=new r([],void 0,u)}Object.freeze(o),this.meta=o,this._hasMeta=Object.keys(o).length>0;let i=this;this._actions={emit(a){i._emit([[M,a]])},down(a){i._emit(Xe(a))},up(a){i._emitUp(Xe(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let n=this._versioningLevel;if(n!=null&&e<=n)return;let s=t?.hash??this._hashFn;s!==this._hashFn&&(this._hashFn=s);let o=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??t?.id,d=i?.version??0,u=Ot(e,o,{id:a,hash:s});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=Be(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let n of this._extraGuards)if(!n(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,n=e?.actor!=null;if(!t&&!n)return;let s=Be(e?.actor),o=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(s,o))throw new X({actor:s,action:o,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(s,o))throw new X({actor:s,action:o,nodeName:this.name})}this._lastMutation={actor:s,timestamp_ns:ne()}}down(e,t){let n=Xe(e);n.length!==0&&(this._checkGuard(t),this._emit(n))}emit(e,t){this._checkGuard(t),this._emit([[M,e]])}up(e,t){if(this._deps.length===0)return;let n=Xe(e);if(n.length===0)return;this._checkGuard(t);let s=t??{internal:!0};this._validateUpTiers(n);for(let o of this._deps)o.node.up?.(n,s)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let n of e){let s=t(n[0]);if(s===3||s===4)throw new Error(`Node "${this.name}": tier-${s} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=Be(t);if(!this._guard(d,"observe"))throw new X({actor:d,action:"observe",nodeName:this.name})}let s=this._isTerminal&&this._resubscribable;if(s){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)xt(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let o;try{o=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:s},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof o=="function")try{o()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof o=="function"&&o(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let n=0;n<e;n++){let s=n,o=this._deps[n];o.unsub=en,o.unsub=o.node.subscribe(i=>{if(o.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:s},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(n){this._deps[t].unsub=null;for(let s=0;s<t;s++){let o=this._deps[s];if(o.unsub!=null){let i=o.unsub;o.unsub=null;try{i()}catch{}xt(o)}}throw this._dirtyDepCount=0,n}}_addDep(e){for(let s=0;s<this._deps.length;s++)if(this._deps[s].node===e)return s;let t=this._deps.length,n=nn(e);if(this._deps.push(n),this._sinks==null)return t;n.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ye),n.unsub=en;try{n.unsub=e.subscribe(s=>{if(n.unsub===null)return;let o=this._config.tierOf,i=!1;for(let a of s)o(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:t},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(s){throw n.unsub=null,this._deps.pop(),this._dirtyDepCount--,s}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(n){this._emit([[L,this._wrapFnError("cleanup threw",n)]])}else if(t!=null&&typeof t=="object"){let n=t.deactivate;if(typeof n=="function")try{n()}catch(s){this._emit([[L,this._wrapFnError("cleanup.deactivate threw",s)]])}}for(let n of this._deps){if(n.unsub!=null){let s=n.unsub;n.unsub=null;try{s()}catch{}}xt(n)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let n=this._deps[e],s=t[0];if(this._inspectorHooks!=null){let o={kind:"dep_message",depIndex:e,message:t};for(let i of this._inspectorHooks)i(o)}if(s!==Re){if(s===B){this._depDirtied(n);return}if(s===Q){if(this._depInvalidated(n),this._cached===void 0)return;this._emit(bt);return}if(s===te||s===se){this._emit([t]);return}if(s===j){this._emit(Je);return}if(s===M)this._depSettledAsData(n,t[1]);else if(s===U)this._depSettledAsResolved(n);else if(s===H)this._depSettledAsTerminal(n,!0);else if(s===L)this._depSettledAsTerminal(n,t[1]);else{this._emit([t]);return}if(!this._fn){(s===M||s===U)&&this._emit([t]),(s===H||s===L)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ye))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(yt),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[L,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(vt)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[L,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[L,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let t=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),n=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=t[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let s=this._deps.map(i=>i.terminal),o={prevData:n,terminalDeps:s,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:t,prevData:n};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(t,this._actions,o);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[L,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>tn?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${tn} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let n=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${n}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[pe,e[0]]:e;let n=!0,s=!1,o=!1,i=-1;for(let d of e){let u=t(d[0]);u<i&&(n=!1),u===3&&(s=!0),d[0]===B&&(o=!0),i=u}let a=e;if(!n){let d=e.map((u,c)=>({m:u,i:c,tier:t(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(s&&!o&&this._status!=="dirty"){let d=0;for(;d<a.length&&t(a[d][0])===0;)d++;return d===0?[pe,...a]:[...a.slice(0,d),pe,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===L&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===j||d[0]===Q);if(a.length===0)return;t=a}t=this._frameBatch(t);let s=null;for(let a=0;a<t.length;a++){let d=t[a],u=d[0];if(u!==te&&u!==se){s?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===te?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let f=d[1];if(u===te)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(f),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(f))c=!1;else if(this._pauseLocks.delete(f),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?s?.push(d):s==null&&(s=t.slice(0,a))}if(s!=null){if(s.length===0)return;t=s}if(this._hasMeta&&t.some(a=>a[0]===j))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Je)}catch{}let{finalMessages:o,equalsError:i}=this._updateState(t);if(o.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:o})}catch{}}if(o.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of o)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(o);i!=null&&this._emit([[L,i]])}_updateState(e){let t=this._config.tierOf,n,s,o=-1,i=0;for(let c of e)t(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===M){d=c;break}}for(let c=0;c<e.length;c++){let f=e[c],p=f[0];if(p===M){if(f.length>=2){let h=!1;if(a&&this._cached!==void 0)try{h=this._equals(this._cached,f[1])}catch(l){s=this._wrapFnError("equals threw",l),o=c;break}if(h){n==null&&(n=e.slice(0,c)),n.push(Ue),this._status="resolved";continue}this._cached=f[1],this._versioning!=null&&(d<0||c===d)&&Xt(this._versioning,f[1],this._hashFn)}this._status="settled",n?.push(f)}else if(n?.push(f),p===B)this._status="dirty";else if(p===U)this._status="resolved";else if(p===H){this._status="completed";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===L){this._status="errored";{let h=this._config.rigorRecorder;if(h!=null)try{h.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Q){if(this._cached!==void 0){let l=this._config.rigorRecorder;if(l!=null)try{l.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let l=h.invalidate;if(typeof l=="function")try{l()}catch{}}}else p===j&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=o>=0?n??e.slice(0,o):n??e;return s!=null?{finalMessages:u,equalsError:s}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let n of t)n(e)};_dispatchOrAccumulate(e){if(jt()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Ne(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}We(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);We(this._deliverToSinks,t,this._config.tierOf)}},rn=r=>Array.isArray(r),Nt=r=>typeof r=="object"&&r!=null&&!Array.isArray(r)});function Qe(r,e){if(e!=null&&e.length>0)return new Set(e);switch(r){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function tr(r){return r._describeKind!=null?r._describeKind:r._deps.length>0?"derived":r._fn!=null?"producer":"state"}function Rt(r){let e=new WeakSet,t={};for(let[n,s]of sn(r))t[n]=kt(s,e);return t}function kt(r,e){if(r==null)return r;let t=typeof r;if(t==="boolean"||t==="number"||t==="string")return r;if(t==="function")return"<function>";if(Array.isArray(r))return e.has(r)?"<cycle>":(e.add(r),r.map(n=>kt(n,e)));if(t==="object"){let n=r;if(e.has(n))return"<cycle>";e.add(n);try{if(typeof n.subscribe=="function"&&"cache"in n)return"<Node>"}catch{return"<unserializable>"}let s={};for(let[o,i]of sn(n))s[o]=kt(i,e);return s}return"<unserializable>"}function sn(r){let e=[],t;try{t=Object.keys(r)}catch{return e}for(let n of t)try{e.push([n,r[n]])}catch{e.push([n,"<unserializable>"])}return e}function nr(r){let e={};for(let[t,n]of Object.entries(r.meta))try{e[t]=n.cache}catch{}return e}function St(r,e,t){let n=e==null,s=!n&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,o=n||e.has("meta")||s!=null&&s.length>0,i="state",a=[];r instanceof F&&(i=tr(r),a=r._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(n||e.has("status"))&&(d.status=r.status);let u=r instanceof F?r._guard:void 0;if(o){let c={...nr(r)};if(u!=null&&c.access===void 0&&(c.access=mt(u)),s!=null&&s.length>0&&!e.has("meta")){let f={};for(let p of s)p in c&&(f[p]=c[p]);d.meta=f}else d.meta=c}if(r.name!=null&&(d.name=r.name),(n||e.has("value"))&&(!t||i==="state")){r.status==="sentinel"&&(d.sentinel=!0);try{d.value=r.cache}catch{}}if((n||e.has("v"))&&r.v!=null){let c={id:r.v.id,version:r.v.version};"cid"in r.v&&(c.cid=r.v.cid,c.prev=r.v.prev),d.v=c}return(n||e.has("guard"))&&u!=null&&(d.guard=mt(u)),(n||e.has("lastMutation"))&&r.lastMutation!=null&&(d.lastMutation=r.lastMutation),d}var At=P(()=>{"use strict";ce();me()});function K(r,e){return oe([],{...e,initial:r})}function et(r,e){return oe((n,s,o)=>r(s,o)??void 0,{describeKind:"producer",...e})}function Y(r,e,t){return oe(r,(s,o,i)=>{let a=s.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);o.emit(e(a,i))},{describeKind:"derived",...t})}var Ie=P(()=>{"use strict";me()});function Ct(r,e){if(Object.is(r,e))return!0;if(r==null||e==null||typeof r!="object"||typeof e!="object")return!1;if(Array.isArray(r)){if(!Array.isArray(e)||r.length!==e.length)return!1;for(let o=0;o<r.length;o++)if(!Ct(r[o],e[o]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let o of t)if(!s.has(o)||!Ct(r[o],e[o]))return!1;return!0}function on(r,e){return`${r}\0${e}`}function Dt(r,e){let t=[],n=new Set(r.subgraphs),s=new Set(e.subgraphs),o=[];for(let g of s)n.has(g)||o.push(g);o.sort();for(let g of o)t.push({type:"subgraph-mounted",path:g});let i=new Set(Object.keys(r.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let g of a)i.has(g)||d.push(g);d.sort();for(let g of d)t.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of a){if(!i.has(g))continue;let E=r.nodes[g]?.meta,v=e.nodes[g]?.meta;E==null&&v==null||Ct(E??{},v??{})||u.push(g)}u.sort();for(let g of u)t.push({type:"node-meta-changed",path:g,prevMeta:r.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of r.edges)c.set(on(g.from,g.to),g);let f=new Map;for(let g of e.edges)f.set(on(g.from,g.to),g);let p=[];for(let[g,E]of f)c.has(g)||p.push(E);p.sort((g,E)=>g.from<E.from?-1:g.from>E.from?1:g.to<E.to?-1:g.to>E.to?1:0);for(let g of p)t.push({type:"edge-added",from:g.from,to:g.to});let h=[];for(let[g,E]of c)f.has(g)||h.push(E);h.sort((g,E)=>g.from<E.from?-1:g.from>E.from?1:g.to<E.to?-1:g.to>E.to?1:0);for(let g of h)t.push({type:"edge-removed",from:g.from,to:g.to});let l=[];for(let g of i)a.has(g)||l.push(g);l.sort();for(let g of l)t.push({type:"node-removed",path:g});let y=[];for(let g of n)s.has(g)||y.push(g);y.sort();for(let g of y)t.push({type:"subgraph-unmounted",path:g});return{events:t,flushedAt_ns:re()}}var an=P(()=>{"use strict";we()});function ie(r){return r.subscribe(()=>{})}var dn=P(()=>{"use strict"});var Mt=P(()=>{"use strict";dn()});var tt,un=P(()=>{"use strict";tt=class{_timer;_gen=0;start(e,t){this.cancel(),this._gen+=1;let n=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,n===this._gen&&t()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Le,cn=P(()=>{"use strict";Le=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let t=(this.head+this._size)%this.capacity;this.buf[t]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function ln(r,e,t,n={}){let s=e in r.nodes,o=t in r.nodes;if(!s)return nt(e,t,"no-such-from");if(!o)return nt(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let u=rr(r,e,n);if(u!=null)return u}let d=rt(e,r.nodes[e],0,n);return st(e,t,[d])}if(i===0)return nt(e,t,"no-path");let a=fn(r,e,t,i);return a.found?st(e,t,pn(r,a.pathOrder,n)):nt(e,t,a.truncated?"max-depth-exceeded":"no-path")}function fn(r,e,t,n){let s=new Map,o=[{path:t,depth:0}],i=new Set([t]),a=0,d=!1;for(;a<o.length;){let f=o[a++];if(f.path===e)break;if(n!=null&&f.depth>=n){let y=r.nodes[f.path];y?.deps&&y.deps.length>0&&(d=!0);continue}let p=r.nodes[f.path];if(p==null)continue;let h=p.deps??[],l=new Map;for(let y=0;y<h.length;y++){let g=h[y];if(!g)continue;let E=l.get(g);E==null&&(E=[],l.set(g,E)),E.push(y)}for(let[y,g]of l)i.has(y)||(i.add(y),s.set(y,{from:f.path,depIndices:g}),o.push({path:y,depth:f.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==t;){let f=s.get(c);if(f==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=f.depIndices,u.push({path:f.from}),c=f.from}return{found:!0,pathOrder:u,truncated:!1}}function rr(r,e,t){let n=r.nodes[e];if(n==null)return null;let s=n.deps??[],o=[];for(let a=0;a<s.length;a++)s[a]===e&&o.push(a);if(o.length>0){let a=rt(e,n,0,t);a.dep_index=o[0];let d=rt(e,n,1,t);return st(e,e,[a,d])}let i=null;for(let a=0;a<s.length;a++){let d=s[a];if(!d||d===e)continue;let u=fn(r,d,e,t.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:st(e,e,pn(r,i.pathOrder,t))}function pn(r,e,t){return e.map((n,s)=>{let o=r.nodes[n.path],i=rt(n.path,o,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function rt(r,e,t,n){let s={path:r,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let o=n.annotations?.get(r)??e.annotation;o!=null&&(s.annotation=o);let i=n.lastMutations?.get(r)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function st(r,e,t){return hn(r,e,!0,"ok",t)}function nt(r,e,t){return hn(r,e,!1,t,[])}function hn(r,e,t,n,s){let o=sr(r,e,t,n,s);return{from:r,to:e,found:t,reason:n,steps:s,text:o,toJSON(){return{from:r,to:e,found:t,reason:n,steps:s}}}}function sr(r,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${r}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${r}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${r}" to "${e}"`}let o=[`Causal path: ${r} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(o.push(d),"value"in i&&o.push(` value: ${or(i.value)}`),i.annotation!=null&&o.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;o.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return o.join(`
|
|
2
|
+
`)}function or(r){if(r===void 0)return"<sentinel>";if(r===null)return"null";if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||typeof r=="bigint")return String(r);try{let e=JSON.stringify(r);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(r)}}var gn=P(()=>{"use strict"});function mn(r){let e=new WeakSet,t=new WeakSet,n=[r],s=0;for(;n.length>0;){let o=n.pop();s+=ar(o,e,t,n)}return s}function ar(r,e,t,n){if(r==null)return 0;switch(typeof r){case"number":return V.number;case"boolean":return V.boolean;case"string":return V.string+r.length*2;case"bigint":return V.bigint+dr(r);case"symbol":return V.symbol;case"function":return e.has(r)?0:(e.add(r),V.function);case"undefined":return 0}let o=r;if(e.has(o))return 0;e.add(o);let i=o[ir];if(typeof i=="function")try{let u=i.call(o);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(o instanceof Date)return V.date;if(o instanceof RegExp)return V.regexp+o.source.length*2;if(o instanceof Error){let u=o.message?o.message.length*2:0,c=o.stack?o.stack.length*2:0;return V.error+u+c}if(typeof URL<"u"&&o instanceof URL)return V.url+o.href.length*2;if(typeof Promise<"u"&&o instanceof Promise)return V.promise;if(o instanceof WeakMap)return V.weakmap;if(o instanceof WeakSet)return V.weakset;if(o instanceof Map){let u=V.map;for(let[c,f]of o)u+=V.mapEntry,n.push(c),n.push(f);return u}if(o instanceof Set){let u=V.set;for(let c of o)u+=V.setEntry,n.push(c);return u}if(Array.isArray(o)){let u=V.array+o.length*8;for(let c of o)n.push(c);return u}if(o instanceof ArrayBuffer)return t.has(o)?0:(t.add(o),o.byteLength);if(ArrayBuffer.isView(o)){let u=o;return t.has(u.buffer)?48:(t.add(u.buffer),u.buffer.byteLength+48)}let a=V.object,d=Object.keys(o);for(let u of d){a+=V.string+u.length*2;try{n.push(o[u])}catch{}}return a}function dr(r){let e=r<0n?-r:r;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}var V,ir,yn=P(()=>{"use strict";V={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},ir=Symbol.for("sizeof")});function bn(r,e){let t=e?.topN??10,n=r.describe({detail:"standard"}),s=[],o=r._collectObserveTargets;typeof o=="function"&&o.call(r,"",s);let i=new Map;for(let[p,h]of s)i.set(p,h);let a=[];for(let[p,h]of Object.entries(n.nodes)){let l=i.get(p),y=l instanceof F?l:null,g=y?mn(y.cache):0,E=y?y._sinkCount:0,v=h.deps?.length??0,_=h.type==="effect"&&E===0,b=E===0?h.type==="effect"?"orphan-effect":h.type==="derived"?"idle-derived":h.type==="producer"?"idle-producer":null:null;a.push({path:p,type:h.type,status:h.status??"unknown",valueSizeBytes:g,subscriberCount:E,depCount:v,isOrphanEffect:_,orphanKind:b})}let d=a.reduce((p,h)=>p+h.valueSizeBytes,0),u=(p,h)=>[...a].sort(h??((l,y)=>y[p]-l[p])).slice(0,t),c=a.filter(p=>p.orphanKind!=null),f=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:f}}var vn=P(()=>{"use strict";me();yn()});function _n(r,e){let t=Math.max(16,r.size*4),n=0;for(;r.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${r.size} disposer(s) discarded`),r.clear();return}let s=r.values().next();if(s.done)return;let o=s.value;r.delete(o);try{o()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function xn(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function ur(r){if(r!=null)return xn(r)?r.cache:r}function be(r){return r!=null&&typeof r=="object"&&"cache"in r&&typeof r.subscribe=="function"&&typeof r.down=="function"}function ae(r){return be(r)?r.cache??"":r}function wn(r){return be(r)?r.cache??0:r}function Tn(r){return be(r)?r.cache??!1:r}function cr(r){let e=[];for(let t of Object.keys(r).sort()){let n=r[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
|
|
3
|
+
`)}function En(r){if(r.version!==ye)throw new Error(`unsupported snapshot version ${String(r.version)} (expected ${ye})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in r))throw new Error(`snapshot missing required key "${e}"`);if(typeof r.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof r.nodes!="object"||r.nodes===null||Array.isArray(r.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(r.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(r.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function lr(r,e){let t=new WeakMap,n=(s,o)=>{if(Object.is(s,o))return!0;if(s==null||o==null||typeof s!="object"||typeof o!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(o))return!0;i.add(o);let a=s.constructor,d=o.constructor;if(a!==d)return!1;if(s instanceof Date)return s.getTime()===o.getTime();if(s instanceof RegExp)return s.source===o.source&&s.flags===o.flags;if(Array.isArray(s)){let p=o;if(s.length!==p.length)return!1;for(let h=0;h<s.length;h++)if(!n(s[h],p[h]))return!1;return!0}if(s instanceof Map){let p=o;if(s.size!==p.size)return!1;for(let[h,l]of s)if(!p.has(h)||!n(l,p.get(h)))return!1;return!0}if(s instanceof Set){let p=o;if(s.size!==p.size)return!1;for(let h of s){let l=!1;for(let y of p)if(n(h,y)){l=!0;break}if(!l)return!1}return!0}if(ArrayBuffer.isView(s)){let p=s,h=o;if(p.length!==h.length)return!1;for(let l=0;l<p.length;l++)if(p[l]!==h[l])return!1;return!0}let u=Object.keys(s),c=Object.keys(o);if(u.length!==c.length)return!1;let f=new Set(c);for(let p of u)if(!f.has(p)||!n(s[p],o[p]))return!1;return!0};return n(r,e)}function fr(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ot(r){let e="^";for(let t=0;t<r.length;t+=1){let n=r[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=r.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let o=r.slice(t+1,s);o.startsWith("!")&&(o=`^${o.slice(1)}`),o=o.replace(/\\/g,"\\\\"),e+=`[${o}]`,t=s;continue}e+=fr(n)}return e+="$",new RegExp(e)}function Gt(r){if(typeof r=="string")return JSON.stringify(r);if(typeof r=="number"||typeof r=="boolean"||r==null)return String(r);try{return JSON.stringify(r)}catch{return"[unserializable]"}}function gr(r){return r==="none"?hr:r==="ansi"||r==null?pr:{data:r.data??"",dirty:r.dirty??"",resolved:r.resolved??"",invalidate:r.invalidate??"",pause:r.pause??"",resume:r.resume??"",complete:r.complete??"",error:r.error??"",teardown:r.teardown??"",derived:r.derived??"",path:r.path??"",reset:r.reset??""}}function On(r){if(r==null)return{};let e=r.detail;return e==="full"?{...r,structured:r.structured??!0,timeline:r.timeline??!0,causal:r.causal??!0,derived:r.derived??!0}:e==="minimal"?{...r,structured:r.structured??!0}:r.format==="stage-log"?{...r,structured:r.structured??!0,timeline:r.timeline??!0}:r}function mr(r,e,t){for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${r}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function It(r,e,t){if(r==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(r.includes(I))throw new Error(`Graph "${e}": ${t} "${r}" must not contain '${I}' (path separator)`);if(r===ee)throw new Error(`Graph "${e}": ${t} name "${ee}" is reserved for meta companion paths`);mr(r,e,t)}function yr(r,e){if(r==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=r.split(I);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function br(r,e){let t=!1;for(let s of r)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?r.filter(s=>e.isMetaPassthrough(s[0])):r}function Nn(r){for(let e of r._mounts.values())Nn(e);for(let e of r._nodes.values())try{e.down([[j]],{internal:!0})}catch{}}function kn(r,e){let t=de.diff(r,e),n={};for(let s of t.nodesAdded){let o=e.nodes[s];o!=null&&(n[s]=o)}return{...t,nodesAddedFull:n}}function Lt(r,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let o=n.maxDepth;if(o!=null&&(!Number.isInteger(o)||o<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(o===0)return n.withDetail?s:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[_,b]of Object.entries(r.nodes)){if(!_)continue;c.add(_);let T=b.deps??[];i.set(_,T);for(let N of T)N&&(c.add(N),a.has(N)||a.set(N,new Set),a.get(N).add(_))}for(let _ of r.edges){if(_==null||typeof _!="object")continue;let b=typeof _.from=="string"?_.from:"",T=typeof _.to=="string"?_.to:"";!b||!T||(c.add(b),c.add(T),u.has(b)||u.set(b,new Set),u.get(b).add(T),d.has(T)||d.set(T,new Set),d.get(T).add(b))}if(!c.has(e))return n.withDetail?s:[];let f=n.both===!0,p=_=>{if(f){let m=i.get(_)??[],O=d.get(_),k=a.get(_),x=u.get(_),w=[...m];return O&&w.push(...O),k&&w.push(...k),x&&w.push(...x),w}if(t==="upstream"){let m=i.get(_)??[],O=d.get(_);return O?[...m,...O]:m}let b=a.get(_),T=u.get(_),N=b?[...b]:[];return T&&N.push(...T),N},h=new Set([e]),l=new Map,y=[{path:e,depth:0}],g=0,E=!1;for(;g<y.length;){let _=y[g++];if(o!=null&&_.depth>=o){p(_.path).length>0&&(E=!0);continue}for(let b of p(_.path))!b||h.has(b)||(h.add(b),l.set(b,_.depth+1),y.push({path:b,depth:_.depth+1}))}let v=[...l.keys()].sort((_,b)=>_<b?-1:_>b?1:0);return n.withDetail?{paths:v,depths:l,truncated:E}:v}function vr(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let o=n.v,i=s.v;if(o!==i&&(o==null||i==null||o.id!==i.id||o.version!==i.version))return!1}return!0}var I,ee,ye,pr,hr,de,Pt=P(()=>{"use strict";He();Ge();we();ce();he();At();me();Ie();an();Mt();un();cn();wt();gn();vn();I="::",ee="__meta__",ye=1;pr={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},hr={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};de=class r{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(I))throw new Error(`Graph name must not contain '${I}' (got "${e}")`);if(e===ee)throw new Error(`Graph name "${ee}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??ge,this._traceRing=new Le(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=et(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;if(s==null||s==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let o=s,i=t?.annotation;if(It(o,this.name,"add"),this._mounts.has(o))throw new Error(`Graph "${this.name}": name "${o}" is already a mount point`);if(this._nodes.has(o))throw new Error(`Graph "${this.name}": node "${o}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(o,e),this._nodeToName.set(e,o),this._emitTopology({kind:"added",name:o,nodeKind:"node"}),i!=null&&(this._annotations.set(o,i),this.config.inspectorEnabled&&this._traceRing.push({path:o,annotation:i,timestamp_ns:re()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof F&&t._applyVersioning(e)}remove(e){It(e,this.name,"remove");let t=this._mounts.get(e);if(t){let o={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${I}${ee}${I}`)||o.nodes.push(a);return o.nodes.sort(),o.mounts.push(e),o.mounts.push(...t._collectSubgraphs(`${e}${I}`)),this._mounts.delete(e),t._parent=void 0,Nn(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:o}),o}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[j]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let o=ot(e);return i=>o.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(o=>t(o));for(let o of s){let i=this.remove(o);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(I))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[M,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);ke(()=>{for(let[s,o]of n)this.set(s,o,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[Q]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[L,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[H]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,u]of this._nodes)n.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof F)for(let c of u._deps){let f=n.get(c.node);f!=null&&a.push([f,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let s=[];this._collectObserveTargets("",s);let o=new Map;for(let[a,d]of s)o.set(d,a);let i=[];for(let[a,d]of s)if(d instanceof F)for(let u of d._deps){let c=o.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,t){if(t===void 0){let s=new r(e);return this.mount(e,s)}if(typeof t=="function"){let s=new r(e);return t(s),this.mount(e,s)}let n=t;if(It(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=yr(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let o=this._nodes.get(n);if(o&&s.length>0&&s[0]===ee)return this._resolveMetaChainFromNode(o,s,t.join(I));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(I)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(I))}_resolveMetaChainFromNode(e,t,n){let s=e,o=0,i=[...t];for(;o<i.length;){if(i[o]!==ee)throw new Error(`Graph "${this.name}": expected ${ee} segment in meta path "${n}"`);if(o+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ee} in "${n}"`);let a=i[o+1],d=s.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);s=d,o+=2}return s}signal(e,t){if(t?.internal!==!0){for(let s of e)if(this.config.messageTier(s[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let d of this._mounts.values())d._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},a=br(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!n.has(u)){n.add(u);try{u.down(e,i)}catch(c){if(c instanceof X)throw c;s.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,s)}}}_signalMetaSubtree(e,t,n,s,o){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!n.has(a)){n.add(a);try{a.down(t,s)}catch(d){if(d instanceof X)throw d;o.push(d)}this._signalMetaSubtree(a,t,n,s,o)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=ur(e?.actor),n=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let s=Qe(e?.detail,e?.fields),o=e?.detail==="spec",i=s,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[b,T]of a)d.set(T,b);let u=[];{let b=a.map(([,m])=>m),T=new Set(d.values()),N=0;for(;b.length>0;){let m=b.shift();if(m instanceof F)for(let O of m._deps){let k=O.node;if(d.has(k))continue;let x=k.name??"",w=x;if(!w||T.has(w))if(x){let R=2;for(;T.has(`${x}#${R}`);)R++;w=`${x}#${R}`}else for(w=`__internal__/${N++}`;T.has(w);)w=`__internal__/${N++}`;d.set(k,w),T.add(w),u.push([w,k]),b.push(k)}}}let c=[...a,...u],f={};for(let[b,T]of c){if(t!=null&&!T.allowsObserve(t))continue;let N=St(T,i,o),m=T instanceof F?T._deps.map(w=>d.get(w.node)??w.node.name??""):[],{name:O,...k}=N,x={...k,deps:m};if(!o){let w=this._annotations.get(b);w!=null&&(x.annotation=w)}if(n!=null)if(typeof n=="function"){let w=n;if(!(w.length>=2?w(b,x):w(x)))continue}else{let w=!0;for(let[R,C]of Object.entries(n)){let S=R==="deps_includes"?"depsIncludes":R==="meta_has"?"metaHas":R;if(S==="depsIncludes"){if(!x.deps.includes(String(C))){w=!1;break}continue}if(S==="metaHas"){if(!Object.hasOwn(x.meta??{},String(C))){w=!1;break}continue}if(x[S]!==C){w=!1;break}}if(!w)continue}f[b]=x}let p=new Set(Object.keys(f)),h=[];for(let[b,T]of c)if(T instanceof F)for(let N of T._deps){let m=d.get(N.node);m!=null&&h.push([m,b])}h.sort((b,T)=>b[0]<T[0]?-1:b[0]>T[0]?1:b[1]<T[1]?-1:b[1]>T[1]?1:0);let l=h.map(([b,T])=>({from:b,to:T}));(t!=null||n!=null)&&(l=l.filter(b=>p.has(b.from)&&p.has(b.to)));let y=this._collectSubgraphs(""),g=t!=null||n!=null?y.filter(b=>{let T=`${b}${I}`;return[...p].some(N=>N===b||N.startsWith(T))}):y,E=this,v=e;return{name:this.name,nodes:f,edges:l,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(b){let T={...v};return Array.isArray(b)?(T.fields=b,T.detail=void 0):(T.detail=b,T.fields=void 0),E.describe(T)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${I}`))}return t}resourceProfile(e){return bn(this,e)}reachable(e,t,n={}){return n.withDetail===!0?Lt(this.describe(),e,t,{...n,withDetail:!0}):Lt(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(ae(e),ae(t),{...n?.maxDepth!==void 0?{maxDepth:wn(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Tn(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),o=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return ln(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:o,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,o=K(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Ne(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),f=[],p=new WeakSet,h=v=>{if(p.has(v)||d)return;p.add(v);let _=v.topology.subscribe(b=>{for(let T of b){if(T[0]!==M)continue;let N=T[1];if(u(),N.kind==="added"&&N.nodeKind==="mount"){let m=v._mounts.get(N.name);m!=null&&h(m)}}});f.push(_);for(let b of v._mounts.keys()){let T=v._mounts.get(b);T!=null&&h(T)}};h(this);let l,y=e.actor;xn(y)&&(l=y.subscribe(v=>{let _=!1,b=!1;for(let T of v){let N=T[0];N===M?_=!0:(N===H||N===L||N===j)&&(b=!0)}_&&u(),b&&(l?.(),l=void 0,u())}));let g;try{g=Y([o],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(v,_)=>v===_})}catch(v){c(),l?.();for(let _ of f)_();throw i.dispose(),v}let E=ie(g);return{node:g,dispose(){d=!0,c(),l?.();for(let v of f)v();f.length=0,i.dispose(),E()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},o=this.describe(t),i=Dt(s,o),a=K(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(p,h)=>p===h}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let h of p){if(h[0]!==M)continue;let l=h[1],y=Dt(o,l);o=l,y.events.length!==0&&a.emit(y)}}),f=ie(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[j,"describe-diff disposed"]]),f()}}}_explainReactive(e,t,n){let s=0,o=K(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Ne(()=>{a=!1,!d&&(s+=1,o.emit(s))}))},c=i.onEvent(v=>{let _=v.type;_!=="data"&&_!=="error"&&_!=="complete"&&_!=="teardown"||u()}),f=[];e!=null&&be(e)&&f.push(e),t!=null&&be(t)&&f.push(t),n?.maxDepth!=null&&be(n.maxDepth)&&f.push(n.maxDepth),n?.findCycle!=null&&be(n.findCycle)&&f.push(n.findCycle);let p=()=>{for(let v of f)if(v.cache===void 0)return!1;return!0},h=()=>{let v=ae(e),_=ae(t);return{from:v,to:_,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:v,to:_,found:!1,reason:"pending",steps:[]})}},l;try{l=Y([o],()=>{if(!p())return h();let v=ae(e),_=ae(t),b={...n?.maxDepth!==void 0?{maxDepth:wn(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:Tn(n.findCycle)}:{}};return this._explainStatic(v,_,b)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:ae(e),to:ae(t)},equals:(v,_)=>v.found===_.found&&v.reason===_.reason&&v.steps.length===_.steps.length&&vr(v.steps,_.steps)})}catch(v){throw c(),i.dispose(),v}let y=ie(l),g=[],E=v=>{let _;return _=v.subscribe(b=>{let T=!1,N=!1;for(let m of b){let O=m[0];O===M?T=!0:(O===H||O===L||O===j)&&(N=!0)}(T||N)&&u(),N&&_&&(_(),_=void 0)}),()=>{_&&(_(),_=void 0)}};for(let v of f)g.push(E(v));return{node:l,dispose(){d=!0,c();for(let v of g)v?.();g.length=0,i.dispose(),y()}}}_pathsMatching(e){let t=ot(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${I}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),o=e===""?n:`${e}${I}${n}`;t.push([o,s]),this._appendMetaObserveTargets(o,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let o=t.meta[s],i=`${e}${I}${ee}${I}${s}`;n.push([i,o]),this._appendMetaObserveTargets(i,o,n)}}observe(e,t){let n=typeof e=="string",o=On(n?t:e);if(o.reactive===!0)return this._observeReactive(n?e:void 0,o);let i=o.structured===!0||o.timeline===!0||o.causal===!0||o.derived===!0||o.detail==="minimal"||o.detail==="full"||o.format!=null,a=o.actor;if(n){let c=e,f=this.resolve(c);if(a!=null&&!f.allowsObserve(a))throw new X({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,f]],o,"one"):{subscribe(p){return f.subscribe(p)},up(p){try{f.up?.(p)}catch(h){if(h instanceof X)return;throw h}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,o,"all"):{subscribe:c=>{let f=u.map(([p,h])=>h.subscribe(l=>{c(p,l)}));return()=>{for(let p of f)p()}},up:(c,f)=>{try{this.resolve(c).up?.(f)}catch(p){if(p instanceof X)return;throw p}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,o=t.reactiveName??"observe";return et(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let y={events:a.slice(),flushedAt_ns:re()};a.length=0,i.emit(y)},f={...t,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,f):this.observe(f),h=y=>{u||(a.push(y),!d&&(d=!0,Ne(()=>{d=!1,c()})))};for(let y of p.events)h(y);let l=p.onEvent(h);return()=>{u=!0,l(),p.dispose()}},{name:o,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,o=i=>{if(n==="one"&&s!=null){let c=this.resolve(s);return this._buildStructuredObserver([[s,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,t,o)}_createObserveResult(e,t,n){let s=t.timeline===!0,o=t.causal===!0,i=t.derived===!0,a=t.detail==="minimal",d=this.config.inspectorEnabled,u=(o||i)&&d,c=t.maxEvents,f=c!=null&&c>0?new Le(c):null,p=[],h=new Set,l=t.tiers!=null?new Set(t.tiers):null,y={},g=new Set,E=0,v=0,_=0,b=0,T=0,N=0,m=!1,O=!1,k=0,x=new Map,w=new Map,R=new Map,C=A=>{if(!(l!=null&&!l.has(A.type))){f?f.push(A):p.push(A);for(let G of h)G(A)}},S=A=>l==null||l.has(A),$=()=>s?{timestamp_ns:re(),in_batch:qe(),batch_id:k}:{},z=(A,G)=>{if(!(!u||!(A instanceof F)))return A._setInspectorHook(J=>{if(J.kind==="dep_message")x.set(A,J.depIndex);else if(J.kind==="run"){let Ce=J.batchData.map((D,q)=>D!=null&&D.length>0?D.at(-1):J.prevData[q]);w.set(A,Ce);let Z=J.batchData.map(D=>D!=null?[...D]:void 0);R.set(A,Z),i&&C({type:"derived",path:G,dep_values:Ce,dep_batches:Z,...$()})}})},W=A=>{let G=x.get(A),J=w.get(A);if(!o||J==null)return{};let Z=(G!=null&&G>=0&&A instanceof F?A._deps[G]:void 0)?.node,D=Z?.v,q=R.get(A);return{trigger_dep_index:G,trigger_dep_name:Z?.name,...D!=null?{trigger_version:{id:D.id,version:D.version}}:{},dep_values:[...J],...q!=null?{dep_batches:q}:{}}},ve=[],_e=[];for(let[A,G]of e){let J=z(G,A);J&&ve.push(J),_e.push(G.subscribe(Ce=>{k++;for(let Z of Ce){let D=Z[0],q=$();if(D===M){y[A]=Z[1];let ht=G instanceof F?G.lastMutation?.actor??Ee:Ee;C({type:"data",path:A,data:Z[1],actor:ht,...q,...W(G)})}else if(a)D===B?S("dirty")&&E++:D===U?S("resolved")&&v++:D===Q?S("invalidate")&&_++:D===te?S("pause")&&b++:D===se?S("resume")&&T++:D===j?S("teardown")&&N++:D===H&&!g.has(A)?S("complete")&&(m=!0):D===L&&S("error")&&(O=!0,g.add(A));else if(D===B)S("dirty")&&E++,C({type:"dirty",path:A,...q});else if(D===U)S("resolved")&&v++,C({type:"resolved",path:A,...q,...W(G)});else if(D===Q)S("invalidate")&&_++,C({type:"invalidate",path:A,...q});else if(D===te)S("pause")&&b++,C({type:"pause",path:A,lockId:Z[1],...q});else if(D===se)S("resume")&&T++,C({type:"resume",path:A,lockId:Z[1],...q});else if(D===H)S("complete")&&!g.has(A)&&(m=!0),C({type:"complete",path:A,...q});else if(D===L){S("error")&&(O=!0,g.add(A));let ht=G instanceof F?G.lastMutation?.actor??Ee:Ee;C({type:"error",path:A,data:Z[1],actor:ht,...q})}else D===j&&(S("teardown")&&N++,C({type:"teardown",path:A,...q}))}}))}let Se=!1,Ae=()=>{if(!Se){Se=!0;for(let A of _e)A();for(let A of ve)A();for(let A of je)A({value:void 0,done:!0});je.length=0}},pt=[],je=[];h.add(A=>{let G=je.shift();G?G({value:A,done:!1}):pt.push(A)});let Vt={get values(){return y},get dirtyCount(){return E},get resolvedCount(){return v},get invalidateCount(){return _},get pauseCount(){return b},get resumeCount(){return T},get teardownCount(){return N},get events(){return f?f.toArray():[...p]},get anyCompletedCleanly(){return m},get anyErrored(){return O},get completedWithoutErrors(){return m&&!O},onEvent(A){return h.add(A),()=>h.delete(A)},dispose:Ae,expand(A){Ae();let G={...t};return typeof A=="string"?G.detail=A:Object.assign(G,A),n(On(G))},[Symbol.asyncIterator](){return{next(){return pt.length>0?Promise.resolve({value:pt.shift(),done:!1}):Se?Promise.resolve({value:void 0,done:!0}):new Promise(A=>je.push(A))},return(){return Ae(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(Vt,t),Vt}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(l=>console.log(l)),o=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,a=o==null&&i==null?()=>!0:l=>(o==null||o.has(l))&&(i==null||!i.has(l)),d=gr(t.theme),u=n==="stage-log"?re():0,c=l=>l==null?"":t.stageLabels?.[l]??l,f=(l,y)=>l.length>y?`${l.slice(0,y-1)}\u2026`:l,p=l=>l.type==="data"||l.type==="error"?f(Gt(l.data),120):"",h=l=>{if(n==="stage-log"){let m=(re()-u)/1e9,O=c(l.path).padEnd(9);if(l.type==="data"){let k=p(l);return`[${m.toFixed(3)}s] ${O} \u2190${k?` ${k}`:""}`}if(l.type==="error"){let k=p(l);return`[${m.toFixed(3)}s] ${O} \u2717${k?` ${k}`:""}`}return l.type==="complete"?`[${m.toFixed(3)}s] ${O} \u25A0 complete`:`[${m.toFixed(3)}s] ${O} ${l.type}`}if(n==="json")try{return JSON.stringify(l)}catch{return JSON.stringify({type:l.type,path:l.path,data:"[unserializable]"})}let y=d[l.type]??"",g=l.path?`${d.path}${l.path}${d.reset} `:"",E=l.type==="data"||l.type==="error",v=l.type==="pause"||l.type==="resume",_=E?` ${Gt(l.data)}`:v?` ${Gt(l.lockId)}`:"",b=l.type==="data"||l.type==="resolved"||l.type==="derived"?l:void 0,T=b?.trigger_dep_name!=null?` <- ${b.trigger_dep_name}`:b?.trigger_dep_index!=null?` <- #${b.trigger_dep_index}`:"",N=l.in_batch?" [batch]":"";return`${g}${y}${l.type.toUpperCase()}${d.reset}${_}${T}${N}`};e.onEvent(l=>{a(l.type)&&s(h(l),l)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){_n(this._disposers,this.name),this.signal([[j]],{internal:!0}),_n(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:t,...n}=this.describe({detail:"full"}),s={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:u,...c}=n.nodes[a];s[a]=c}let o=[...n.subgraphs].sort(),i={...n,version:1,nodes:s,subgraphs:o};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Yt(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??ge,{codec:s,codecVersion:o,payload:i}=Jt(e,n);return s.decode(i,o)}restore(e,t){if(En(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(o=>ot(o)),s=t?.includeProducers===!0;for(let o of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(a=>a.test(o)))continue;let i=e.nodes[o];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&t?.onError?.(o,new Error(`restore: slice.value is undefined for "${o}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(o)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(o,i.value)}catch(a){t?.onError?.(o,a)}}}}}static fromSnapshot(e,t){En(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,o=new r(e.name);if(n)return n(o),o.restore(e),o;for(let h of[...e.subgraphs].sort((l,y)=>{let g=l.split(I).length,E=y.split(I).length;return g!==E?g-E:l<y?-1:l>y?1:0})){let l=h.split(I),y=o;for(let g of l)y._mounts.has(g)||y.mount(g,new r(g)),y=y._mounts.get(g)}let i=s?Object.entries(s).map(([h,l])=>({re:ot(h),factory:l})):[],a=h=>{for(let l of i)if(l.re.test(h))return l.factory},d=h=>{let l=h.split(I),y=l.pop();if(y==null||y.length===0)throw new Error(`invalid snapshot path "${h}"`);let g=o;for(let E of l){let v=g._mounts.get(E);if(!v)throw new Error(`unknown mount "${E}" in path "${h}"`);g=v}return[g,y]},u=Object.entries(e.nodes).filter(([h])=>!h.includes(`${I}${ee}${I}`)).sort((h,l)=>h[0]<l[0]?-1:h[0]>l[0]?1:0),c=new Map(u),f=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[h,l]of[...c.entries()]){let y=l?.deps??[];if(!y.every(T=>f.has(T)))continue;let[g,E]=d(h),v={...l?.meta??{}},_=a(h),b;if(l?.type==="state")b=K(l.value,{meta:v});else{if(_==null)continue;b=_(E,{path:h,type:l.type,value:l.value,meta:v,deps:y,resolvedDeps:y.map(T=>f.get(T))})}g.add(b,{name:E}),f.set(h,b),c.delete(h),p=!0}}if(c.size>0){let h=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${h}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return o.restore(e),o}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(u,c)=>{if(u.disposed)return;let f=cr(c.nodes);if(u.lastSnapshot!=null&&f!==""&&f===u.lastFingerprint)return;let p=u.seq+1,h=ne(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:h,format_version:ye}:{name:this.name,mode:"diff",diff:kn(u.lastSnapshot,c),seq:p,timestamp_ns:h,format_version:ye};if(u.tier.filter&&!u.tier.filter(g))return;let E;try{E=u.tier.save(g)}catch(v){t.onError?.(v,u.tier);return}if(E&&typeof E.then=="function"){let b=(u.savePending??Promise.resolve()).then(()=>E,()=>E).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=f)},T=>{t.onError?.(T,u.tier)});u.savePending=b.finally(()=>{u.savePending===b&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=f},o=(u,c)=>{try{s(u,c)}catch(f){t.onError?.(f,u.tier)}},i=(u,c)=>{if(!c.some(l=>{let y=this.config.messageTier(l[0]);return y>=3&&y<5}))return;if(t.filter){let l=this.tryResolve(u);if(l==null)return;let y=St(l,Qe("standard"));if(!t.filter(u,y))return}let p,h=()=>(p==null&&(p=this.snapshot()),p);for(let l of n)l.disposed||(l.debounceMs===0?o(l,h()):(l.timer==null&&(l.timer=new tt),l.timer.start(l.debounceMs,()=>{l.disposed||o(l,this.snapshot())})))},a;if(t.paths!=null){let c=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(f=>{let p=this.tryResolve(f);return p==null?()=>{}:p.subscribe(h=>i(f,h))});a=()=>{for(let f of c)f()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let o=s;try{if(o.mode==="full"&&o.snapshot!=null)return this.restore(o.snapshot),!0;if(o.version===ye&&o.nodes!=null)return this.restore(o),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let o;try{o=await s.load?.()}catch(d){n?.onError?.(d,s);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===ye&&i.nodes!=null?i:void 0;if(a!=null)try{return r.fromSnapshot(a,n)}catch(d){n?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:re(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(s)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),o=[...s].filter(v=>!n.has(v)).sort(),i=[...n].filter(v=>!s.has(v)).sort(),a=[],d=[];for(let v of n){if(!s.has(v))continue;let _=e.nodes[v],b=t.nodes[v],T=_.v,N=b.v;T!=null&&N!=null&&T.id===N.id&&T.version!==N.version&&d.push({path:v,id:T.id,from:T.version,to:N.version});let m=T!=null&&N!=null&&T.id===N.id&&T.version===N.version;for(let O of["type","status","sentinel"]){let k=_[O],x=b[O];k!==x&&a.push({path:v,field:O,from:k,to:x})}if(!m)for(let O of["value","meta"]){let k=_[O],x=b[O];lr(k,x)||a.push({path:v,field:O,from:k,to:x})}}let u=v=>`${v.from} ${v.to}`,c=new Set(e.edges.map(u)),f=new Set(t.edges.map(u)),p=t.edges.filter(v=>!c.has(u(v))),h=e.edges.filter(v=>!f.has(u(v))),l=new Set(e.subgraphs),y=new Set(t.subgraphs),g=[...y].filter(v=>!l.has(v)).sort(),E=[...l].filter(v=>!y.has(v)).sort();return{nodesAdded:o,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:p,edgesRemoved:h,subgraphsAdded:g,subgraphsRemoved:E}}}});var Gn=P(()=>{"use strict";Pt()});function In(r,e,t){return{[r]:!0,[`${r}_type`]:e,...t??{}}}var Ln=P(()=>{"use strict"});var Rr={};jn(Rr,{CqrsGraph:()=>ft,cqrs:()=>kr,cqrsEventKeyOf:()=>Or,dispatchKeyOf:()=>xr,sagaInvocationKeyOf:()=>Nr});module.exports=Hn(Rr);we();ce();He();ce();he();At();me();Ie();Ge();we();ce();he();Ie();Pt();Ge();he();me();Ie();var $t=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,t){if(t!==void 0&&t<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=t,t!==void 0){if(this._buf=new Array(t),e&&e.length>0){let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let t=e>=0?e:this._size+e;if(!(t<0||t>=this._size))return this._maxSize!==void 0?this._buf[(this._head+t)%this._maxSize]:this._buf[t]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let t=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let n=t;n<e.length;n++)this._rawAppend(e[n]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let t=0;t<e;t++)this._buf[(this._head+t)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let t=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,t);else{for(let n=0;n<t;n++)this._buf[(this._head+n)%this._maxSize]=void 0;this._head=(this._head+t)%this._maxSize}return this._size-=t,this._version+=1,t}slice(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${t})`);let n=t===void 0?this._size:Math.min(Math.max(t,0),this._size),s=Math.min(e,this._size);if(s>=n)return[];let o=n-s;if(this._maxSize===void 0)return this._buf.slice(s,n);let i=new Array(o);for(let a=0;a<o;a++)i[a]=this._buf[(this._head+s+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let t=Math.min(e,this._size);return this.slice(this._size-t,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this._buf[(this._head+t)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let t=0;t<e.length;t++)this._buf.push(e[t]);this._size=this._buf.length}else{let t=this._maxSize;for(let o=0;o<t;o++)this._buf[o]=void 0;this._head=0;let n=Math.min(e.length,t),s=e.length-n;for(let o=0;o<n;o++)this._buf[o]=e[s+o];this._size=n}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Pe(r){return r.subscribe(()=>{})}var _r=64;function $e(r,e={}){let{name:t,maxSize:n,versioning:s,guard:o,backend:i}=e,a=i??new $t(r,n),d=K(a.toArray(),{name:t,describeKind:"state",equals:(m,O)=>m===O,...s!=null?{versioning:s}:{},...o!=null?{guard:o}:{}});function u(){let m=a.toArray();ke(()=>{d.down([[B]],{internal:!0}),d.down([[M,m]],{internal:!0})})}let c=new Map,f=new Map,p=new Map;function h(m,O){return`${m}:${O===void 0?"END":O}`}function l(m){if(m.size<_r)return;let O=m.keys().next();if(O.done)return;let k=m.get(O.value);k!==void 0&&k.dispose(),m.delete(O.value)}function y(m){let O=a.version;try{return m()}finally{a.version!==O&&u()}}function g(m){if(!Number.isInteger(m)||m<0)throw new RangeError(`tail: n must be a non-negative integer (got ${m})`);let O=c.get(m);if(O!==void 0)return c.delete(m),c.set(m,O),O.node;l(c);let k=Y([d],([w])=>{let R=w;return m===0||R.length===0?[]:R.slice(Math.max(0,R.length-m))},{initial:a.tail(m),describeKind:"derived"}),x=Pe(k);return c.set(m,{node:k,dispose:x}),k}function E(m,O){if(!Number.isInteger(m)||m<0)throw new RangeError(`slice: start must be a non-negative integer (got ${m})`);if(O!==void 0&&(!Number.isInteger(O)||O<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${O})`);let k=h(m,O),x=f.get(k);if(x!==void 0)return f.delete(k),f.set(k,x),x.node;l(f);let w=Y([d],([C])=>{let S=C;return O===void 0?S.slice(m):S.slice(m,O)},{initial:a.slice(m,O),describeKind:"derived"}),R=Pe(w);return f.set(k,{node:w,dispose:R}),w}function v(m){let O=p.get(m);if(O!==void 0)return O.node;let k=Y([d,m],([w,R])=>{let C=w,S=Math.max(0,Math.trunc(R??0));return C.slice(S)},{initial:[],describeKind:"derived"}),x=Pe(k);return p.set(m,{node:k,dispose:x}),k}let _,b;function T(){_===void 0&&(_=oe([d],(m,O,k)=>{let x=m[0],R=x!=null&&x.length>0?x.at(-1):k.prevData[0];if(R==null||R.length===0){O.down([[U]]);return}O.emit(R[R.length-1])},{name:t!=null?`${t}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),b=Y([d],([m])=>m.length>0,{name:t!=null?`${t}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Pe(_),Pe(b))}let N={entries:d,get size(){return a.size},at(m){return a.at(m)},append(m){y(()=>a.append(m))},appendMany(m){m.length!==0&&y(()=>a.appendMany(m))},clear(){y(()=>a.clear())},trimHead(m){y(()=>a.trimHead(m))},withLatest(){return T(),d},get lastValue(){return T(),_},get hasLatest(){return T(),b},view(m){switch(m.kind){case"tail":return g(m.n);case"slice":return E(m.start,m.stop);case"fromCursor":return v(m.cursor)}},attach(m){let O=m.subscribe(k=>{for(let x of k)x[0]===M&&N.append(x[1])});return()=>O()},attachStorage(m){if(m.length===0)return()=>{};let O=new Map;for(let x of m)O.set(x,a.size);(async()=>{for(let x of m)if(typeof x.loadEntries=="function")try{let w=await Promise.resolve(x.loadEntries());w.entries.length>0&&a.size===0&&(a.restore(w.entries),O.set(x,w.entries.length),u());break}catch{}})();let k=d.subscribe(x=>{for(let w of x){if(w[0]!==M)continue;let R=w[1];for(let C of m){let S=O.get(C)??0;if(R.length<S){try{let z=C.appendEntries(R);z instanceof Promise&&z.catch(()=>{})}catch{}O.set(C,R.length);continue}if(R.length===S)continue;let $=R.slice(S);O.set(C,R.length);try{let z=C.appendEntries($);z instanceof Promise&&z.catch(()=>{})}catch{}}}});return()=>k()},disposeAllViews(){for(let m of c.values())m.dispose();c.clear();for(let m of f.values())m.dispose();f.clear();for(let m of p.values())m.dispose();p.clear()},dispose(){for(let m of c.values())m.dispose();c.clear();for(let m of f.values())m.dispose();f.clear();for(let m of p.values())m.dispose();p.clear()}};return N}var wr=Te((r,e)=>{r("observe"),r("signal"),e("write")});function at(r){let e=$e([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??wr,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function Ft(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))Ft(r[e]);return Object.freeze(r)}var Rn=new WeakSet;function Sn(r){let e=r.cache,t=typeof e=="number"&&Number.isFinite(e);!t&&e!==void 0&&!Rn.has(r)&&(Rn.add(r),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let s=(t?e:0)+1;return r.down([[B],[M,s]]),s}function it(r,e,t,n,s,o){let i=e(t,n,s);if(i===void 0)return;let a=o!=null?{...i,handlerVersion:o}:i;r.append(a)}function An(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Ft):s,i=ne(),a=e.seq?Sn(e.seq):void 0;try{let d=r(...o);return e.audit&&e.onSuccess&&it(e.audit,e.onSuccess,o,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;it(e.audit,e.onFailure,o,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function Cn(r,e){let t=e.freeze??!0;return function(...s){let o=t?s.map(Ft):s,i=ne(),a,d,u=!1,c;try{ke(()=>{e.seq&&(c=Sn(e.seq));try{a=r(...o),e.audit&&e.onSuccess&&it(e.audit,e.onSuccess,o,a,{t_ns:i,seq:c},e.handlerVersion)}catch(f){throw d=f,u=!0,f}})}catch(f){if(u&&e.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;it(e.audit,e.onFailure,o,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:f}return a}}function Dn(r,e,t=0){let n=K(t,{name:e,describeKind:"state"});return r.add(n,{name:e}),n}function Mn(r,e,t,n=0){let s={},o=new de(e);for(let i of t){let a=K(n,{name:i,describeKind:"state"});o.add(a,{name:i}),s[i]=a}return r.mount(e,o),s}Gn();var ue=class extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}},dt=class extends ue{constructor(t,n){super(`Duplicate ${t} registration: "${n}"`);this.kind=t;this.registrationName=n}},ut=class extends ue{constructor(t,n,s){super(`Command "${t}" emitted undeclared event "${n}". Declared emits: [${s.join(", ")}]`);this.commandName=t;this.eventName=n;this.declaredEmits=s}},ct=class extends ue{constructor(t,n,s){super(`Optimistic concurrency conflict on aggregate "${t}": expected version ${n}, got ${s}`);this.aggregateId=t;this.expected=n;this.actual=s}},lt=class extends ue{constructor(t){super(`Unknown command: "${t}". Register with command() first.`);this.commandName=t}},Fe=class extends ue{constructor(t,n){super(`Command handler "${t}" threw: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.commandName=t}};var Ve=class extends ue{constructor(t,n){super(`Projection "${t}" rebuild failed: ${n instanceof Error?n.message:String(n)}`,{cause:n});this.projectionName=t}};Ln();Mt();var Tr=Te((r,e)=>{r("write"),r("signal"),e("observe")}),Er=Te((r,e)=>{r("observe"),r("signal"),e("write")}),Pn=Te((r,e)=>{r("observe"),r("signal"),e("write")});function ze(r,e){return In("cqrs",r,e)}function $n(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))$n(r[e]);return Object.freeze(r)}var Or=r=>`${r.type}::${r.aggregateId??"__default__"}`,xr=r=>r.commandName,Nr=r=>r.eventType,ft=class extends de{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,t={}){super(e,t.graph),this._retainedLimit=t.retainedLimit??1024,this._freezeCommandPayload=t.freezeCommandPayload??!0,this._freezeEventPayload=t.freezeEventPayload??!0,this._maxAggregates=t.maxAggregates??1e4,this.dispatches=at({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=at({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=Dn(this,"dispatch_seq",0)}aggregateVersion(e,t){return this._aggregateVersions.get(`${e}::${t}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let t=e.value;this._aggregateLru.delete(t);let n=t.indexOf("::");if(n<0)continue;let s=t.slice(0,n),o=t.slice(n+2),i=this._aggregateVersions.get(t)??0;this._aggregateVersions.delete(t);let a=this._eventLogsByAggregate.get(s);a&&(a.delete(o),a.size===0&&this._eventLogsByAggregate.delete(s)),this.aggregateEvictions.append({aggregateId:o,type:s,lastVersion:i,t_ns:ne()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[t,n]of this._eventLogs){let s=n.log.attachStorage(e),o=this._attachedTierDisposers.get(t);o||(o=[],this._attachedTierDisposers.set(t,o)),o.push(s)}for(let[t,n]of this._eventLogsByAggregate)for(let[s,o]of n){let i=`${t}::${s}`,a=o.log.attachStorage(e),d=this._attachedTierDisposers.get(i);d||(d=[],this._attachedTierDisposers.set(i,d)),d.push(a)}return()=>{let t=this._attachedEventTiers.indexOf(e);t>=0&&this._attachedEventTiers.splice(t,1)}}_autoWireStreamStorage(e,t){if(this._attachedEventTiers.length===0)return;let n=this._attachedTierDisposers.get(e);n||(n=[],this._attachedTierDisposers.set(e,n));for(let s of this._attachedEventTiers)n.push(t.attachStorage(s))}event(e,t){if(t!==void 0)return this._ensureAggregateStream(e,t).node;let n=this._eventLogs.get(e);if(n)return n.node;let s=$e([],{name:e,versioning:0,maxSize:this._retainedLimit});s.withLatest();let o=s.entries,i=Y([o],([a])=>a,{name:e,describeKind:"state",meta:ze("event",{event_name:e}),guard:Pn,initial:o.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(ie(i)),this._eventLogs.set(e,{log:s,node:i}),this._autoWireStreamStorage(e,s),i}_ensureAggregateStream(e,t){this._eventLogs.has(e)||this.event(e);let n=this._eventLogsByAggregate.get(e);n||(n=new Map,this._eventLogsByAggregate.set(e,n));let s=`${e}::${t}`;this._touchAggregate(s);let o=n.get(t);if(o)return o;let i=`${e}_${t.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=$e([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=Y([d],([h])=>h,{name:i,describeKind:"state",meta:ze("event_aggregate",{event_name:e,aggregate_id:t}),guard:Pn,initial:d.cache}),c=i,f=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(f+=1,c=`${i}_${f}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(ie(u));let p={log:a,node:u};return n.set(t,p),this._autoWireStreamStorage(`${e}::${t}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,t,n){let s=this._eventLogs.get(e);if(s||(this.event(e),s=this._eventLogs.get(e)),s.node.status==="completed"||s.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${s.node.status}).`);let o,i;if(n?.aggregateId!==void 0){let c=`${e}::${n.aggregateId}`;o=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,o),i=this._ensureAggregateStream(e,n.aggregateId)}let a=s.log.entries.v,d=this._freezeEventPayload?$n(t):t,u={type:e,payload:d,timestampNs:ne(),seq:++this._seq,...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...o!==void 0?{aggregateVersion:o}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...n?.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return s.log.append(u),i&&i.log.append(u),u}command(e,t){if(this._commandRegs.has(e))throw new dt("command",e);let n=typeof t=="function"?{handler:t}:t,s=K(void 0,{name:e,describeKind:"state",meta:{...ze("command",{command_name:e}),error:null},guard:Tr});if(this.add(s,{name:e}),this._commandRegs.set(e,{handler:n.handler,...n.emits!==void 0?{emits:n.emits}:{},...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{}}),n.emits)for(let o of n.emits)this._eventLogs.has(o)||this.event(o);return s}dispatch(e,t,n){let s=this._commandRegs.get(e);if(!s)throw new lt(e);if(n?.aggregateId!==void 0&&n.expectedAggregateVersion!==void 0&&s.emits!==void 0){let u=0;for(let c of s.emits){let f=this._aggregateVersions.get(`${c}::${n.aggregateId}`);f!==void 0&&f>u&&(u=f)}if(u!==n.expectedAggregateVersion)throw new ct(n.aggregateId,n.expectedAggregateVersion,u)}let o=this.resolve(e),i=[],a=!1,d=u=>{o.emit(u,{internal:!0});try{s.handler(u,{emit:(c,f)=>{if(s.emits!==void 0&&!s.emits.includes(c))throw new ut(e,c,s.emits);i.push(c),this._appendEvent(c,f,{...n?.aggregateId!==void 0?{aggregateId:n.aggregateId}:{},...n?.correlationId!==void 0?{correlationId:n.correlationId}:{},...n?.causationId!==void 0?{causationId:n.causationId}:{},...n?.metadata!==void 0?{metadata:Object.freeze({...n.metadata})}:{},...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}})}}),o.meta.error.emit(null,{internal:!0})}catch(c){throw a=!0,c}};try{Cn(d,{audit:this.dispatches,seq:this._dispatchSeqCursor,freeze:this._freezeCommandPayload,onSuccess:([u],c,{t_ns:f,seq:p})=>({commandName:e,payload:u,outcome:"success",emittedEvents:[...i],t_ns:f,seq:p??0,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}}),onFailure:([u],c,{t_ns:f,seq:p,errorType:h})=>{let l=c instanceof Fe?c:new Fe(e,c);return{commandName:e,payload:u,outcome:"failure",error:l,errorType:h,emittedEvents:[...i],t_ns:f,seq:p??0,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{}}}})(t)}catch(u){throw a&&o.meta.error.emit(u,{internal:!0}),u}}projection(e){let{name:t,events:n,reducer:s,initial:o}=e,i=e.mode??"scan",a=e.freezeInputs??!0,d=e.snapshot,u=n.map(x=>(this._eventLogs.has(x)||this.event(x),this._eventLogs.get(x).node));function c(x){x.sort((w,R)=>w.timestampNs-R.timestampNs||w.seq-R.seq||(w.aggregateId??"").localeCompare(R.aggregateId??""))}function f(x){let w=[];for(let R of x)w.push(...R);return c(w),w}let p=u.map(x=>x.cache??[]),h=f(p),l=a?Object.freeze(h):h,y=0,g=o;i==="scan"&&h.length>0&&(g=s(o,l),y=h.length);let E=i==="replay"?s(o,l):g,v=d?.saveDebounceMs??1e3,_=d?.saveEvery??1e3,b,T=0;function N(x){if(d?.save){if(T+=1,T>=_){T=0,b!==void 0&&(clearTimeout(b),b=void 0);let w=d.save(x);w instanceof Promise&&w.catch(()=>{});return}b!==void 0&&clearTimeout(b),b=setTimeout(()=>{b=void 0,T=0;let w=d.save(x);w instanceof Promise&&w.catch(()=>{})},v)}}let m=Y(u,x=>{let w=f(x),R;if(i==="replay"){let C=a?Object.freeze(w):w;R=s(o,C)}else{let C=w.slice(y);y=w.length;let S=a?Object.freeze(C):C;R=s(g,S),g=R}return N(R),R},{name:t,describeKind:"derived",meta:ze("projection",{projection_name:t,source_events:n}),guard:Er,initial:E});return this.add(m,{name:t}),this._keepaliveDisposers.push(ie(m)),this._keepaliveDisposers.push(()=>{b!==void 0&&(clearTimeout(b),b=void 0)}),this._projections.add(t),{node:m,rebuild:async x=>{try{let w=x?.pageSize??1e3,R=x?.fromTier??this._attachedEventTiers[0]?.[0],C=f(u.map($=>$.cache??[])).length,S=o;if(d?.load){let $=await d.load();$!==void 0&&(S=$)}if(!R||!R.loadEntries){let $=f(u.map(W=>W.cache??[])),z=a?Object.freeze($):$;S=s(S,z)}else{let $=new Set(n),z,W=!1;for(;!W;){let ve=await R.loadEntries({cursor:z,pageSize:w}),_e=[...ve.entries].filter(Ae=>$.has(Ae.type));c(_e);let Se=a?Object.freeze(_e):_e;S=s(S,Se),z=ve.cursor,W=!z||ve.entries.length===0}}if(i==="scan"){let $=f(u.map(W=>W.cache??[])),z=$.slice(C);if(z.length>0){let W=a?Object.freeze(z):z;S=s(S,W)}g=S,y=$.length}return m.emit(S,{internal:!0}),S}catch(w){throw new Ve(t,w)}},reset:async()=>{try{let x=o;if(d?.load){let S=await d.load();S!==void 0&&(x=S)}let w=f(u.map(S=>S.cache??[])),R=a?Object.freeze(w):w,C=s(x,R);return i==="scan"&&(g=C,y=w.length),m.emit(C,{internal:!0}),C}catch(x){throw new Ve(t,x)}}}}saga(e,t,n,s={}){let o=t.map(l=>(this._eventLogs.has(l)||this.event(l),this._eventLogs.get(l).node)),i=Mn(this,`${e}_cursor`,t,0),a=at({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=s.aggregateId,u=s.errorPolicy??"advance",c=new Map;for(let l of t){let y=i[l];c.set(l,y.cache??0);let g=y.subscribe(E=>{for(let v of E)v[0]===M&&c.set(l,v[1])});this._keepaliveDisposers.push(g)}let f=An((l,y)=>{n(l)},{audit:a,freeze:!1,...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{},onSuccess:([l,y],g,{t_ns:E})=>({eventType:y,outcome:"success",aggregateId:l.aggregateId,event:l,t_ns:E}),onFailure:([l,y],g,{t_ns:E,errorType:v})=>({eventType:y,outcome:"failure",error:g,errorType:v,aggregateId:l.aggregateId,event:l,t_ns:E})}),p={},h=oe(o,(l,y)=>{let g=p.n.meta.error;for(let E=0;E<l.length;E++){let v=l[E];if(v==null||v.length===0)continue;let _=v.at(-1);if(!_)continue;let b=t[E],T=i[b],N=c.get(b)??0;if(_.length>N){let m=_.slice(N),O=N;for(let k of m){let x=k;if(d!==void 0&&x.aggregateId!==d){O+=1;continue}try{f(x,b),g.emit(null,{internal:!0}),O+=1}catch(w){if(g.emit(w,{internal:!0}),u==="hold")break;O+=1}}T.emit(O)}}},{name:e,describeKind:"effect",meta:{...ze("saga",{saga_name:e,source_events:t}),error:null}});return p.n=h,this.add(h,{name:e}),this._keepaliveDisposers.push(ie(h)),this._sagas.add(e),{node:h,invocations:a,audit:a,cursors:i}}};function kr(r,e){let t=new ft(r,e),{factory:n,factoryArgs:s,...o}=e??{};return t.tagFactory("cqrs",Rt(o)),t}0&&(module.exports={CqrsGraph,cqrs,cqrsEventKeyOf,dispatchKeyOf,sagaInvocationKeyOf});
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import '../../node-ClS5yC-B.cjs';
|
|
2
|
-
import '../../index-
|
|
2
|
+
import '../../index-C9pjcz3l.cjs';
|
|
3
3
|
import '../../reactive-log-B00laMSQ.cjs';
|
|
4
4
|
import '../../extra/storage-tiers.cjs';
|
|
5
5
|
import '../../graph-C4SHb3Ly.cjs';
|
|
6
|
-
export { A as AggregateEvictionRecord, d as CommandActions, e as CommandHandler, f as CommandRegistration, a as CqrsEvent, C as CqrsEventMap, b as CqrsGraph, c as CqrsOptions, D as DispatchOptions, g as DispatchRecord, P as ProjectionController, h as ProjectionOptions, j as ProjectionReducer, k as ProjectionSnapshotOpts, S as SagaController, l as SagaHandler, m as SagaInvocation, n as SagaOptions, o as cqrs, p as cqrsEventKeyOf, q as dispatchKeyOf, s as sagaInvocationKeyOf } from '../../index-
|
|
6
|
+
export { A as AggregateEvictionRecord, d as CommandActions, e as CommandHandler, f as CommandRegistration, a as CqrsEvent, C as CqrsEventMap, b as CqrsGraph, c as CqrsOptions, D as DispatchOptions, g as DispatchRecord, P as ProjectionController, h as ProjectionOptions, j as ProjectionReducer, k as ProjectionSnapshotOpts, S as SagaController, l as SagaHandler, m as SagaInvocation, n as SagaOptions, o as cqrs, p as cqrsEventKeyOf, q as dispatchKeyOf, s as sagaInvocationKeyOf } from '../../index-COD1kVoS.cjs';
|
|
7
7
|
import '../../meta-vE8bxW1E.cjs';
|
|
8
8
|
import '../../extra/storage-core.cjs';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import '../../node-ClS5yC-B.js';
|
|
2
|
-
import '../../index-
|
|
2
|
+
import '../../index-CZQXo5tH.js';
|
|
3
3
|
import '../../reactive-log-BezYsbA_.js';
|
|
4
4
|
import '../../extra/storage-tiers.js';
|
|
5
5
|
import '../../graph-7VguS7a4.js';
|
|
6
|
-
export { A as AggregateEvictionRecord, d as CommandActions, e as CommandHandler, f as CommandRegistration, a as CqrsEvent, C as CqrsEventMap, b as CqrsGraph, c as CqrsOptions, D as DispatchOptions, g as DispatchRecord, P as ProjectionController, h as ProjectionOptions, j as ProjectionReducer, k as ProjectionSnapshotOpts, S as SagaController, l as SagaHandler, m as SagaInvocation, n as SagaOptions, o as cqrs, p as cqrsEventKeyOf, q as dispatchKeyOf, s as sagaInvocationKeyOf } from '../../index-
|
|
6
|
+
export { A as AggregateEvictionRecord, d as CommandActions, e as CommandHandler, f as CommandRegistration, a as CqrsEvent, C as CqrsEventMap, b as CqrsGraph, c as CqrsOptions, D as DispatchOptions, g as DispatchRecord, P as ProjectionController, h as ProjectionOptions, j as ProjectionReducer, k as ProjectionSnapshotOpts, S as SagaController, l as SagaHandler, m as SagaInvocation, n as SagaOptions, o as cqrs, p as cqrsEventKeyOf, q as dispatchKeyOf, s as sagaInvocationKeyOf } from '../../index-CQG3D1cp.js';
|
|
7
7
|
import '../../meta-BgVAsg9j.js';
|
|
8
8
|
import '../../extra/storage-core.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"../../chunk-
|
|
1
|
+
import{a,b,c,d,e}from"../../chunk-VQ4A6T2A.js";import"../../chunk-4I45FVQS.js";import"../../chunk-FDQGFWLF.js";import"../../chunk-L6NSJVJZ.js";import"../../chunk-KVV66NN2.js";import"../../chunk-3G5U5QNE.js";import"../../chunk-C72GO4IZ.js";import"../../chunk-626TESAC.js";import"../../chunk-ESMPEKEV.js";import"../../chunk-35JTVPOX.js";import"../../chunk-JQFH2DV6.js";import"../../chunk-V5A7M7RJ.js";import"../../chunk-LYCLF26R.js";import"../../chunk-CK2E7BTU.js";import"../../chunk-QYADASLV.js";export{d as CqrsGraph,e as cqrs,a as cqrsEventKeyOf,b as dispatchKeyOf,c as sagaInvocationKeyOf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../../chunk-
|
|
1
|
+
import{a}from"../../chunk-FG4TKHMC.js";import"../../chunk-OCKEEPRJ.js";import"../../chunk-D27JNOLZ.js";import"../../chunk-3G5U5QNE.js";import"../../chunk-C72GO4IZ.js";import"../../chunk-626TESAC.js";import"../../chunk-ESMPEKEV.js";import"../../chunk-35JTVPOX.js";import"../../chunk-V5A7M7RJ.js";import"../../chunk-LYCLF26R.js";import"../../chunk-CK2E7BTU.js";import"../../chunk-QYADASLV.js";export{a as demoShell};
|