@directive-run/core 0.8.1 → 0.8.3

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.
Files changed (62) hide show
  1. package/LICENSE +5 -0
  2. package/dist/adapter-utils.cjs +1 -1
  3. package/dist/adapter-utils.cjs.map +1 -1
  4. package/dist/adapter-utils.d.cts +1 -1
  5. package/dist/adapter-utils.d.ts +1 -1
  6. package/dist/adapter-utils.js +1 -1
  7. package/dist/adapter-utils.js.map +1 -1
  8. package/dist/chunk-6WG7FPH7.cjs +3 -0
  9. package/dist/chunk-6WG7FPH7.cjs.map +1 -0
  10. package/dist/chunk-DIK3SZBM.js +3 -0
  11. package/dist/chunk-DIK3SZBM.js.map +1 -0
  12. package/dist/chunk-GO63IIN5.js +2 -0
  13. package/dist/chunk-GO63IIN5.js.map +1 -0
  14. package/dist/chunk-KQKNE23L.cjs +2 -0
  15. package/dist/chunk-KQKNE23L.cjs.map +1 -0
  16. package/dist/chunk-LAH2FMON.cjs +16 -0
  17. package/dist/chunk-LAH2FMON.cjs.map +1 -0
  18. package/dist/chunk-MAARYRI4.js +16 -0
  19. package/dist/chunk-MAARYRI4.js.map +1 -0
  20. package/dist/chunk-O75OISQ2.js +2 -0
  21. package/dist/chunk-O75OISQ2.js.map +1 -0
  22. package/dist/chunk-PK2EH26L.cjs +2 -0
  23. package/dist/chunk-PK2EH26L.cjs.map +1 -0
  24. package/dist/helpers-50q7yhA9.d.ts +179 -0
  25. package/dist/helpers-B6SkcKCD.d.cts +179 -0
  26. package/dist/index.cjs +1 -16
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +42 -1421
  29. package/dist/index.d.ts +42 -1421
  30. package/dist/index.js +1 -16
  31. package/dist/index.js.map +1 -1
  32. package/dist/internals.cjs +2 -0
  33. package/dist/internals.cjs.map +1 -0
  34. package/dist/internals.d.cts +1176 -0
  35. package/dist/internals.d.ts +1176 -0
  36. package/dist/internals.js +2 -0
  37. package/dist/internals.js.map +1 -0
  38. package/dist/plugins/index.cjs +2 -2
  39. package/dist/plugins/index.cjs.map +1 -1
  40. package/dist/plugins/index.d.cts +1 -1
  41. package/dist/plugins/index.d.ts +1 -1
  42. package/dist/plugins/index.js +2 -2
  43. package/dist/plugins/index.js.map +1 -1
  44. package/dist/{plugins-DaglUQVX.d.cts → plugins-Bg_oq2sO.d.cts} +22 -2
  45. package/dist/{plugins-DaglUQVX.d.ts → plugins-Bg_oq2sO.d.ts} +22 -2
  46. package/dist/system-L2FVVUSN.js +2 -0
  47. package/dist/system-L2FVVUSN.js.map +1 -0
  48. package/dist/system-L45Z2N4U.cjs +2 -0
  49. package/dist/system-L45Z2N4U.cjs.map +1 -0
  50. package/dist/testing.cjs +1 -16
  51. package/dist/testing.cjs.map +1 -1
  52. package/dist/testing.d.cts +54 -16
  53. package/dist/testing.d.ts +54 -16
  54. package/dist/testing.js +1 -16
  55. package/dist/testing.js.map +1 -1
  56. package/dist/worker.cjs +1 -16
  57. package/dist/worker.cjs.map +1 -1
  58. package/dist/worker.d.cts +1 -1
  59. package/dist/worker.d.ts +1 -1
  60. package/dist/worker.js +1 -16
  61. package/dist/worker.js.map +1 -1
  62. package/package.json +13 -4
@@ -1,4 +1,4 @@
1
- import { M as ModuleSchema, P as Plugin, z as System } from '../plugins-DaglUQVX.cjs';
1
+ import { M as ModuleSchema, P as Plugin, V as System } from '../plugins-Bg_oq2sO.cjs';
2
2
 
3
3
  /**
4
4
  * Logging Plugin - Console logging for Directive events
@@ -1,4 +1,4 @@
1
- import { M as ModuleSchema, P as Plugin, z as System } from '../plugins-DaglUQVX.js';
1
+ import { M as ModuleSchema, P as Plugin, V as System } from '../plugins-Bg_oq2sO.js';
2
2
 
3
3
  /**
4
4
  * Logging Plugin - Console logging for Directive events
@@ -1,3 +1,3 @@
1
- var Te={debug:0,info:1,warn:2,error:3};function Xe(n={}){let{level:c="info",filter:l=()=>true,logger:i=console,prefix:s="[Directive]"}=n,m=Te[c],o=(t,r,...a)=>{Te[t]<m||l(r)&&i[t](`${s} ${r}`,...a);};return {name:"logging",onInit:()=>o("debug","init"),onStart:()=>o("info","start"),onStop:()=>o("info","stop"),onDestroy:()=>o("debug","destroy"),onFactSet:(t,r,a)=>{o("debug","fact.set",{key:t,value:r,prev:a});},onFactDelete:(t,r)=>{o("debug","fact.delete",{key:t,prev:r});},onFactsBatch:t=>{o("debug","facts.batch",{count:t.length,changes:t});},onDerivationCompute:(t,r,a)=>{o("debug","derivation.compute",{id:t,value:r,deps:a});},onDerivationInvalidate:t=>{o("debug","derivation.invalidate",{id:t});},onReconcileStart:()=>{o("debug","reconcile.start");},onReconcileEnd:t=>{o("debug","reconcile.end",{unmet:t.unmet.length,inflight:t.inflight.length,completed:t.completed.length,canceled:t.canceled.length});},onConstraintEvaluate:(t,r)=>{o("debug","constraint.evaluate",{id:t,active:r});},onConstraintError:(t,r)=>{o("error","constraint.error",{id:t,error:r});},onRequirementCreated:t=>{o("debug","requirement.created",{id:t.id,type:t.requirement.type});},onRequirementMet:(t,r)=>{o("info","requirement.met",{id:t.id,byResolver:r});},onRequirementCanceled:t=>{o("debug","requirement.canceled",{id:t.id});},onResolverStart:(t,r)=>{o("debug","resolver.start",{resolver:t,requirementId:r.id});},onResolverComplete:(t,r,a)=>{o("info","resolver.complete",{resolver:t,requirementId:r.id,duration:a});},onResolverError:(t,r,a)=>{o("error","resolver.error",{resolver:t,requirementId:r.id,error:a});},onResolverRetry:(t,r,a)=>{o("warn","resolver.retry",{resolver:t,requirementId:r.id,attempt:a});},onResolverCancel:(t,r)=>{o("debug","resolver.cancel",{resolver:t,requirementId:r.id});},onEffectRun:t=>{o("debug","effect.run",{id:t});},onEffectError:(t,r)=>{o("error","effect.error",{id:t,error:r});},onSnapshot:t=>{o("debug","timetravel.snapshot",{id:t.id,trigger:t.trigger});},onHistoryNavigate:(t,r)=>{o("info","timetravel.jump",{from:t,to:r});},onError:t=>{o("error","error",{source:t.source,sourceId:t.sourceId,message:t.message});},onErrorRecovery:(t,r)=>{o("warn","error.recovery",{source:t.source,sourceId:t.sourceId,strategy:r});},onDefinitionRegister:(t,r)=>{o("info","definition.register",{type:t,id:r});},onDefinitionAssign:(t,r)=>{o("info","definition.assign",{type:t,id:r});},onDefinitionUnregister:(t,r)=>{o("info","definition.unregister",{type:t,id:r});},onDefinitionCall:(t,r,a)=>{o("debug","definition.call",{type:t,id:r,props:a});}}}var ie=class{constructor(c){this.capacity=c;this.buf=new Array(c);}buf;head=0;_size=0;get size(){return this._size}push(c){this.buf[this.head]=c,this.head=(this.head+1)%this.capacity,this._size<this.capacity&&this._size++;}toArray(){return this._size===0?[]:this._size<this.capacity?this.buf.slice(0,this._size):[...this.buf.slice(this.head),...this.buf.slice(0,this.head)]}clear(){this.buf=new Array(this.capacity),this.head=0,this._size=0;}};function le(){try{if(typeof process<"u"&&process.env?.NODE_ENV==="production")return !1}catch{}try{if(typeof import.meta<"u"&&import.meta.env?.MODE==="production")return !1}catch{}return true}function pe(n){try{if(n===void 0)return "undefined";if(n===null)return "null";if(typeof n=="bigint")return String(n)+"n";if(typeof n=="symbol")return String(n);if(typeof n=="object"){let c=JSON.stringify(n,(l,i)=>typeof i=="bigint"?String(i)+"n":typeof i=="symbol"?String(i):i);return c.length>120?c.slice(0,117)+"...":c}return String(n)}catch{return "<error>"}}function K(n,c){return n.length<=c?n:n.slice(0,c-3)+"..."}function te(n){try{return n.inspect()}catch{return null}}function Ae(n){try{return n==null||typeof n!="object"?n:JSON.parse(JSON.stringify(n))}catch{return null}}function De(n){return n===void 0?1e3:!Number.isFinite(n)||n<1?(le()&&console.warn(`[directive:devtools] Invalid maxEvents value (${n}), using default 1000`),1e3):Math.floor(n)}function Re(){return {reconcileCount:0,reconcileTotalMs:0,resolverStats:new Map,effectRunCount:0,effectErrorCount:0,lastReconcileStartMs:0}}var Ye=200,ne=340,re=16,oe=80,fe=2,ge=["#8b9aff","#4ade80","#fbbf24","#c084fc","#f472b6","#22d3ee"];function ke(){return {entries:new ie(Ye),inflight:new Map}}function Le(){return {derivationDeps:new Map,activeConstraints:new Set,recentlyChangedFacts:new Set,recentlyComputedDerivations:new Set,recentlyActiveConstraints:new Set,animationTimer:null}}var Oe=1e4,Pe=100;function _e(){return {isRecording:false,recordedEvents:[],snapshots:[]}}var Ie=50,ye=200,g={bg:"#1a1a2e",text:"#e0e0e0",accent:"#8b9aff",muted:"#b0b0d0",border:"#333",rowBorder:"#2a2a4a",green:"#4ade80",yellow:"#fbbf24",red:"#f87171",closeBtn:"#aaa",font:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},_={nodeW:90,nodeH:16,nodeGap:6,startY:16,colGap:20,fontSize:10,labelMaxChars:11};function Ne(n,c,l,i){let s=false,m={position:"fixed",zIndex:"99999",...c.includes("bottom")?{bottom:"12px"}:{top:"12px"},...c.includes("right")?{right:"12px"}:{left:"12px"}},o=document.createElement("style");o.textContent=`[data-directive-devtools] summary:focus-visible{outline:2px solid ${g.accent};outline-offset:2px;border-radius:2px}[data-directive-devtools] button:focus-visible{outline:2px solid ${g.accent};outline-offset:2px}`,document.head.appendChild(o);let t=document.createElement("button");t.setAttribute("aria-label","Open Directive DevTools"),t.setAttribute("aria-expanded",String(l)),t.title="Ctrl+Shift+D to toggle",Object.assign(t.style,{...m,background:g.bg,color:g.text,border:`1px solid ${g.border}`,borderRadius:"6px",padding:"10px 14px",minWidth:"44px",minHeight:"44px",cursor:"pointer",fontFamily:g.font,fontSize:"12px",display:l?"none":"block"}),t.textContent="Directive";let r=document.createElement("div");r.setAttribute("role","region"),r.setAttribute("aria-label","Directive DevTools"),r.setAttribute("data-directive-devtools",""),r.tabIndex=-1,Object.assign(r.style,{...m,background:g.bg,color:g.text,border:`1px solid ${g.border}`,borderRadius:"8px",padding:"12px",fontFamily:g.font,fontSize:"11px",maxWidth:"min(380px, calc(100vw - 24px))",maxHeight:"min(500px, calc(100vh - 24px))",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.5)",display:l?"block":"none"});let a=document.createElement("div");Object.assign(a.style,{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"});let f=document.createElement("strong");f.style.color=g.accent,f.textContent=n==="default"?"Directive DevTools":`DevTools (${n})`;let v=document.createElement("button");v.setAttribute("aria-label","Close DevTools"),Object.assign(v.style,{background:"none",border:"none",color:g.closeBtn,cursor:"pointer",fontSize:"16px",padding:"8px 12px",minWidth:"44px",minHeight:"44px",lineHeight:"1",display:"flex",alignItems:"center",justifyContent:"center"}),v.textContent="\xD7",a.appendChild(f),a.appendChild(v),r.appendChild(a);let T=document.createElement("div");T.style.marginBottom="6px",T.setAttribute("aria-live","polite");let D=document.createElement("span");D.style.color=g.green,D.textContent="Settled",T.appendChild(D),r.appendChild(T);let S=document.createElement("div");Object.assign(S.style,{display:"none",marginBottom:"8px",padding:"4px 8px",background:"#252545",borderRadius:"4px",alignItems:"center",gap:"6px"});let E=document.createElement("button");Object.assign(E.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:g.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),E.textContent="\u25C0 Undo",E.disabled=true;let d=document.createElement("button");Object.assign(d.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:g.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),d.textContent="Redo \u25B6",d.disabled=true;let y=document.createElement("span");y.style.color=g.muted,y.style.fontSize="10px",S.appendChild(E),S.appendChild(d),S.appendChild(y),r.appendChild(S);function M($,X){let z=document.createElement("details");X&&(z.open=true),z.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${$} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",z.appendChild(Y);let Q=document.createElement("table");Object.assign(Q.style,{width:"100%",borderCollapse:"collapse",fontSize:"11px"});let we=document.createElement("thead"),Ce=document.createElement("tr");for(let Ge of ["Key","Value"]){let ce=document.createElement("th");ce.scope="col",Object.assign(ce.style,{textAlign:"left",padding:"2px 4px",color:g.accent}),ce.textContent=Ge,Ce.appendChild(ce);}we.appendChild(Ce),Q.appendChild(we);let Me=document.createElement("tbody");return Q.appendChild(Me),z.appendChild(Q),{details:z,tbody:Me,countSpan:ee}}function w($,X){let z=document.createElement("details");z.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:X,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${$} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",z.appendChild(Y);let Q=document.createElement("ul");return Object.assign(Q.style,{margin:"0",paddingLeft:"16px"}),z.appendChild(Q),{details:z,list:Q,countSpan:ee}}let L=M("Facts",true);r.appendChild(L.details);let I=M("Derivations",false);r.appendChild(I.details);let k=w("Inflight",g.yellow);r.appendChild(k.details);let j=w("Unmet",g.red);r.appendChild(j.details);let R=document.createElement("details");R.style.marginBottom="4px";let P=document.createElement("summary");Object.assign(P.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),P.textContent="Performance",R.appendChild(P);let A=document.createElement("div");A.style.fontSize="10px",A.style.color=g.muted,A.textContent="No data yet",R.appendChild(A),r.appendChild(R);let O=document.createElement("details");O.style.marginBottom="4px";let V=document.createElement("summary");Object.assign(V.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),V.textContent="Dependency Graph",O.appendChild(V);let F=document.createElementNS("http://www.w3.org/2000/svg","svg");F.setAttribute("width","100%"),F.setAttribute("height","120"),F.setAttribute("role","img"),F.setAttribute("aria-label","System dependency graph"),F.style.display="block",F.setAttribute("viewBox","0 0 460 120"),F.setAttribute("preserveAspectRatio","xMinYMin meet"),O.appendChild(F),r.appendChild(O);let U=document.createElement("details");U.style.marginBottom="4px";let G=document.createElement("summary");Object.assign(G.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),G.textContent="Timeline",U.appendChild(G);let N=document.createElementNS("http://www.w3.org/2000/svg","svg");N.setAttribute("width","100%"),N.setAttribute("height","60"),N.setAttribute("role","img"),N.setAttribute("aria-label","Resolver execution timeline"),N.style.display="block",N.setAttribute("viewBox",`0 0 ${ne} 60`),N.setAttribute("preserveAspectRatio","xMinYMin meet");let p=document.createElementNS("http://www.w3.org/2000/svg","text");p.setAttribute("x",String(ne/2)),p.setAttribute("y","30"),p.setAttribute("text-anchor","middle"),p.setAttribute("fill",g.muted),p.setAttribute("font-size","10"),p.setAttribute("font-family",g.font),p.textContent="No resolver activity yet",N.appendChild(p),U.appendChild(N),r.appendChild(U);let h,b,e,u;if(i){let $=document.createElement("details");$.style.marginBottom="4px";let X=document.createElement("summary");Object.assign(X.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),e=document.createElement("span"),e.textContent="0",X.textContent="Events (",X.appendChild(e),X.appendChild(document.createTextNode(")")),$.appendChild(X),b=document.createElement("div"),Object.assign(b.style,{maxHeight:"150px",overflow:"auto",fontSize:"10px"}),b.setAttribute("role","log"),b.setAttribute("aria-live","polite"),b.tabIndex=0;let z=document.createElement("div");z.style.color=g.muted,z.style.padding="4px",z.textContent="Waiting for events...",z.className="dt-events-empty",b.appendChild(z),$.appendChild(b),r.appendChild($),h=$,u=document.createElement("div");}else h=document.createElement("details"),b=document.createElement("div"),e=document.createElement("span"),u=document.createElement("div"),u.style.fontSize="10px",u.style.color=g.muted,u.style.marginTop="4px",u.style.fontStyle="italic",u.textContent="Enable trace: true for event log",r.appendChild(u);let x=document.createElement("div");Object.assign(x.style,{display:"flex",gap:"6px",marginTop:"6px"});let C=document.createElement("button");Object.assign(C.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:g.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),C.textContent="\u23FA Record";let H=document.createElement("button");Object.assign(H.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:g.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),H.textContent="\u2913 Export",x.appendChild(C),x.appendChild(H),r.appendChild(x),r.addEventListener("wheel",$=>{let X=r,z=X.scrollTop===0&&$.deltaY<0,Y=X.scrollTop+X.clientHeight>=X.scrollHeight&&$.deltaY>0;(z||Y)&&$.preventDefault();},{passive:false});let B=l,q=new Set;function W(){B=true,r.style.display="block",t.style.display="none",t.setAttribute("aria-expanded","true"),v.focus();}function J(){B=false,r.style.display="none",t.style.display="block",t.setAttribute("aria-expanded","false"),t.focus();}t.addEventListener("click",W),v.addEventListener("click",J);function xe($){$.key==="Escape"&&B&&J();}r.addEventListener("keydown",xe);function Ee($){$.key==="d"&&$.shiftKey&&($.ctrlKey||$.metaKey)&&($.preventDefault(),B?J():W());}document.addEventListener("keydown",Ee);function me(){s||(document.body.appendChild(t),document.body.appendChild(r));}document.body?me():document.addEventListener("DOMContentLoaded",me,{once:true});function Ue(){s=true,t.removeEventListener("click",W),v.removeEventListener("click",J),r.removeEventListener("keydown",xe),document.removeEventListener("keydown",Ee),document.removeEventListener("DOMContentLoaded",me);for(let $ of q)clearTimeout($);q.clear(),t.remove(),r.remove(),o.remove();}return {refs:{container:r,toggleBtn:t,titleEl:f,statusEl:D,factsBody:L.tbody,factsCount:L.countSpan,derivBody:I.tbody,derivCount:I.countSpan,derivSection:I.details,inflightList:k.list,inflightSection:k.details,inflightCount:k.countSpan,unmetList:j.list,unmetSection:j.details,unmetCount:j.countSpan,perfSection:R,perfBody:A,historySection:S,historyLabel:y,undoBtn:E,redoBtn:d,flowSection:O,flowSvg:F,timelineSection:U,timelineSvg:N,eventsSection:h,eventsList:b,eventsCount:e,traceHint:u,recordBtn:C,exportBtn:H},destroy:Ue,isOpen:()=>B,flashTimers:q}}function se(n,c,l,i,s,m){let o=pe(i),t=n.get(l);if(t){let r=t.cells;if(r[1]&&(r[1].textContent=o,s&&m)){let a=r[1];a.style.background="rgba(139, 154, 255, 0.25)";let f=setTimeout(()=>{a.style.background="",m.delete(f);},300);m.add(f);}}else {t=document.createElement("tr"),t.style.borderBottom=`1px solid ${g.rowBorder}`;let r=document.createElement("td");Object.assign(r.style,{padding:"2px 4px",color:g.muted}),r.textContent=l;let a=document.createElement("td");a.style.padding="2px 4px",a.textContent=o,t.appendChild(r),t.appendChild(a),c.appendChild(t),n.set(l,t);}}function Be(n,c){let l=n.get(c);l&&(l.remove(),n.delete(c));}function ue(n,c,l){if(n.inflightList.replaceChildren(),n.inflightCount.textContent=String(c.length),c.length>0)for(let i of c){let s=document.createElement("li");s.style.fontSize="11px",s.textContent=`${i.resolverId} (${i.id})`,n.inflightList.appendChild(s);}else {let i=document.createElement("li");i.style.fontSize="10px",i.style.color=g.muted,i.textContent="None",n.inflightList.appendChild(i);}if(n.unmetList.replaceChildren(),n.unmetCount.textContent=String(l.length),l.length>0)for(let i of l){let s=document.createElement("li");s.style.fontSize="11px",s.textContent=`${i.requirement.type} from ${i.fromConstraint}`,n.unmetList.appendChild(s);}else {let i=document.createElement("li");i.style.fontSize="10px",i.style.color=g.muted,i.textContent="None",n.unmetList.appendChild(i);}}function de(n,c,l){let i=c===0&&l===0;n.statusEl.style.color=i?g.green:g.yellow,n.statusEl.textContent=i?"Settled":"Working...",n.toggleBtn.textContent=i?"Directive":"Directive...",n.toggleBtn.setAttribute("aria-label",`Open Directive DevTools${i?"":" (system working)"}`);}function he(n,c,l,i){let s=Object.keys(l.derive);if(n.derivCount.textContent=String(s.length),s.length===0){c.clear(),n.derivBody.replaceChildren();let o=document.createElement("tr"),t=document.createElement("td");t.colSpan=2,t.style.color=g.muted,t.style.fontSize="10px",t.textContent="No derivations defined",o.appendChild(t),n.derivBody.appendChild(o);return}let m=new Set(s);for(let[o,t]of c)m.has(o)||(t.remove(),c.delete(o));for(let o of s){let t;try{t=pe(l.read(o));}catch{t="<error>";}se(c,n.derivBody,o,t,true,i);}}function $e(n,c,l,i){let s=n.eventsList.querySelector(".dt-events-empty");s&&s.remove();let m=document.createElement("div");Object.assign(m.style,{padding:"2px 4px",borderBottom:`1px solid ${g.rowBorder}`,fontFamily:"inherit"});let o=new Date,t=`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}:${String(o.getSeconds()).padStart(2,"0")}.${String(o.getMilliseconds()).padStart(3,"0")}`,r;try{let T=JSON.stringify(l);r=K(T,60);}catch{r="{}";}let a=document.createElement("span");a.style.color=g.closeBtn,a.textContent=t;let f=document.createElement("span");f.style.color=g.accent,f.textContent=` ${c} `;let v=document.createElement("span");for(v.style.color=g.muted,v.textContent=r,m.appendChild(a),m.appendChild(f),m.appendChild(v),n.eventsList.prepend(m);n.eventsList.childElementCount>Ie;)n.eventsList.lastElementChild?.remove();n.eventsCount.textContent=String(i);}function He(n,c){n.perfBody.replaceChildren();let l=c.reconcileCount>0?(c.reconcileTotalMs/c.reconcileCount).toFixed(1):"\u2014",i=[`Reconciles: ${c.reconcileCount} (avg ${l}ms)`,`Effects: ${c.effectRunCount} run, ${c.effectErrorCount} errors`];for(let s of i){let m=document.createElement("div");m.style.marginBottom="2px",m.textContent=s,n.perfBody.appendChild(m);}if(c.resolverStats.size>0){let s=document.createElement("div");s.style.marginTop="4px",s.style.marginBottom="2px",s.style.color=g.accent,s.textContent="Resolvers:",n.perfBody.appendChild(s);let m=[...c.resolverStats.entries()].sort((o,t)=>t[1].totalMs-o[1].totalMs);for(let[o,t]of m){let r=t.count>0?(t.totalMs/t.count).toFixed(1):"0",a=document.createElement("div");a.style.paddingLeft="8px",a.textContent=`${o}: ${t.count}x, avg ${r}ms${t.errors>0?`, ${t.errors} err`:""}`,t.errors>0&&(a.style.color=g.red),n.perfBody.appendChild(a);}}}function be(n,c){let l=c.history;if(!l){n.historySection.style.display="none";return}n.historySection.style.display="flex";let i=l.currentIndex,s=l.snapshots.length;n.historyLabel.textContent=s>0?`${i+1} / ${s}`:"0 snapshots";let m=i>0,o=i<s-1;n.undoBtn.disabled=!m,n.undoBtn.style.opacity=m?"1":"0.4",n.redoBtn.disabled=!o,n.redoBtn.style.opacity=o?"1":"0.4";}function Fe(n,c){n.undoBtn.addEventListener("click",()=>{c.history&&c.history.currentIndex>0&&c.history.goBack(1);}),n.redoBtn.addEventListener("click",()=>{c.history&&c.history.currentIndex<c.history.snapshots.length-1&&c.history.goForward(1);});}var ve=new WeakMap;function Ke(n,c,l,i,s,m){return [n.join(","),c.join(","),l.map(o=>`${o.id}:${o.active}`).join(","),[...i.entries()].map(([o,t])=>`${o}:${t.status}:${t.type}`).join(","),s.join(","),m.join(",")].join("|")}function Je(n,c,l,i,s){for(let m of l){let o=n.nodes.get(`0:${m}`);if(!o)continue;let t=c.recentlyChangedFacts.has(m);o.rect.setAttribute("fill",t?g.text+"33":"none"),o.rect.setAttribute("stroke-width",t?"2":"1");}for(let m of i){let o=n.nodes.get(`1:${m}`);if(!o)continue;let t=c.recentlyComputedDerivations.has(m);o.rect.setAttribute("fill",t?g.accent+"33":"none"),o.rect.setAttribute("stroke-width",t?"2":"1");}for(let m of s){let o=n.nodes.get(`2:${m}`);if(!o)continue;let t=c.recentlyActiveConstraints.has(m),r=o.rect.getAttribute("stroke")??g.muted;o.rect.setAttribute("fill",t?r+"33":"none"),o.rect.setAttribute("stroke-width",t?"2":"1");}}function Se(n,c,l){let i=te(c);if(!i)return;let s;try{s=Object.keys(c.facts.$store.toObject());}catch{s=[];}let m=Object.keys(c.derive),o=i.constraints,t=i.unmet,r=i.inflight,a=Object.keys(i.resolvers),f=new Map;for(let p of t)f.set(p.id,{type:p.requirement.type,fromConstraint:p.fromConstraint,status:"unmet"});for(let p of r)f.set(p.id,{type:p.resolverId,fromConstraint:"",status:"inflight"});if(s.length===0&&m.length===0&&o.length===0&&a.length===0){ve.delete(n.flowSvg),n.flowSvg.replaceChildren(),n.flowSvg.setAttribute("viewBox","0 0 460 40");let p=document.createElementNS("http://www.w3.org/2000/svg","text");p.setAttribute("x","230"),p.setAttribute("y","24"),p.setAttribute("text-anchor","middle"),p.setAttribute("fill",g.muted),p.setAttribute("font-size","10"),p.setAttribute("font-family",g.font),p.textContent="No system topology",n.flowSvg.appendChild(p);return}let v=r.map(p=>p.resolverId).sort(),T=Ke(s,m,o,f,a,v),D=ve.get(n.flowSvg);if(D&&D.fingerprint===T){Je(D,l,s,m,o.map(p=>p.id));return}let S=_.nodeW+_.colGap,E=[5,5+S,5+S*2,5+S*3,5+S*4],d=E[4]+_.nodeW+5;function y(p){let h=_.startY+12;return p.map(b=>{let e={...b,y:h};return h+=_.nodeH+_.nodeGap,e})}let M=y(s.map(p=>({id:p,label:K(p,_.labelMaxChars)}))),w=y(m.map(p=>({id:p,label:K(p,_.labelMaxChars)}))),L=y(o.map(p=>({id:p.id,label:K(p.id,_.labelMaxChars),active:p.active,priority:p.priority}))),I=y([...f.entries()].map(([p,h])=>({id:p,type:h.type,fromConstraint:h.fromConstraint,status:h.status}))),k=y(a.map(p=>({id:p,label:K(p,_.labelMaxChars)}))),j=Math.max(M.length,w.length,L.length,I.length,k.length,1),R=_.startY+12+j*(_.nodeH+_.nodeGap)+8;n.flowSvg.replaceChildren(),n.flowSvg.setAttribute("viewBox",`0 0 ${d} ${R}`),n.flowSvg.setAttribute("aria-label",`Dependency graph: ${s.length} facts, ${m.length} derivations, ${o.length} constraints, ${f.size} requirements, ${a.length} resolvers`);let P=["Facts","Derivations","Constraints","Reqs","Resolvers"];for(let[p,h]of P.entries()){let b=document.createElementNS("http://www.w3.org/2000/svg","text");b.setAttribute("x",String(E[p]??0)),b.setAttribute("y","10"),b.setAttribute("fill",g.accent),b.setAttribute("font-size",String(_.fontSize)),b.setAttribute("font-family",g.font),b.textContent=h,n.flowSvg.appendChild(b);}let A={fingerprint:T,nodes:new Map};function O(p,h,b,e,u,x,C,H){let B=document.createElementNS("http://www.w3.org/2000/svg","g"),q=document.createElementNS("http://www.w3.org/2000/svg","rect");q.setAttribute("x",String(h)),q.setAttribute("y",String(b-6)),q.setAttribute("width",String(_.nodeW)),q.setAttribute("height",String(_.nodeH)),q.setAttribute("rx","3"),q.setAttribute("fill",H?x+"33":"none"),q.setAttribute("stroke",x),q.setAttribute("stroke-width",H?"2":"1"),q.setAttribute("opacity",C?"0.35":"1"),B.appendChild(q);let W=document.createElementNS("http://www.w3.org/2000/svg","text");return W.setAttribute("x",String(h+4)),W.setAttribute("y",String(b+4)),W.setAttribute("fill",x),W.setAttribute("font-size",String(_.fontSize)),W.setAttribute("font-family",g.font),W.setAttribute("opacity",C?"0.35":"1"),W.textContent=u,B.appendChild(W),n.flowSvg.appendChild(B),A.nodes.set(`${p}:${e}`,{g:B,rect:q,text:W}),{midX:h+_.nodeW/2,midY:b}}function V(p,h,b,e,u,x){let C=document.createElementNS("http://www.w3.org/2000/svg","line");C.setAttribute("x1",String(p)),C.setAttribute("y1",String(h)),C.setAttribute("x2",String(b)),C.setAttribute("y2",String(e)),C.setAttribute("stroke",u),C.setAttribute("stroke-width","1"),C.setAttribute("stroke-dasharray","3,2"),C.setAttribute("opacity","0.7"),n.flowSvg.appendChild(C);}let F=new Map,U=new Map,G=new Map,N=new Map;for(let p of M){let h=l.recentlyChangedFacts.has(p.id),b=O(0,E[0],p.y,p.id,p.label,g.text,false,h);F.set(p.id,b);}for(let p of w){let h=l.recentlyComputedDerivations.has(p.id),b=O(1,E[1],p.y,p.id,p.label,g.accent,false,h);U.set(p.id,b);}for(let p of L){let h=l.recentlyActiveConstraints.has(p.id),b=O(2,E[2],p.y,p.id,p.label,p.active?g.yellow:g.muted,!p.active,h);G.set(p.id,b);}for(let p of I){let h=p.status==="unmet"?g.red:g.yellow,b=O(3,E[3],p.y,p.id,K(p.type,_.labelMaxChars),h,false,false);N.set(p.id,b);}for(let p of k){let h=r.some(b=>b.resolverId===p.id);O(4,E[4],p.y,p.id,p.label,h?g.green:g.muted,!h,false);}for(let p of w){let h=l.derivationDeps.get(p.id),b=U.get(p.id);if(h&&b)for(let e of h){let u=F.get(e);u&&V(u.midX+_.nodeW/2,u.midY,b.midX-_.nodeW/2,b.midY,g.accent);}}for(let p of I){let h=G.get(p.fromConstraint),b=N.get(p.id);h&&b&&V(h.midX+_.nodeW/2,h.midY,b.midX-_.nodeW/2,b.midY,g.muted);}for(let p of r){let h=N.get(p.id);if(h){let b=k.find(e=>e.id===p.resolverId);b&&V(h.midX+_.nodeW/2,h.midY,E[4],b.y,g.green);}}ve.set(n.flowSvg,A);}function je(n){n.animationTimer&&clearTimeout(n.animationTimer),n.animationTimer=setTimeout(()=>{n.recentlyChangedFacts.clear(),n.recentlyComputedDerivations.clear(),n.recentlyActiveConstraints.clear(),n.animationTimer=null;},600);}function Ve(n,c){let l=c.entries.toArray();if(l.length===0)return;n.timelineSvg.replaceChildren();let i=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let S of l)S.startMs<i&&(i=S.startMs),S.endMs>s&&(s=S.endMs);let m=performance.now();for(let S of c.inflight.values())S<i&&(i=S),m>s&&(s=m);let o=s-i||1,t=ne-oe-10,r=[],a=new Set;for(let S of l)a.has(S.resolver)||(a.add(S.resolver),r.push(S.resolver));for(let S of c.inflight.keys())a.has(S)||(a.add(S),r.push(S));let v=r.slice(-12),T=re*v.length+20;n.timelineSvg.setAttribute("viewBox",`0 0 ${ne} ${T}`),n.timelineSvg.setAttribute("height",String(Math.min(T,200)));let D=5;for(let S=0;S<=D;S++){let E=oe+t*S/D,d=o*S/D,y=document.createElementNS("http://www.w3.org/2000/svg","text");y.setAttribute("x",String(E)),y.setAttribute("y","8"),y.setAttribute("fill",g.muted),y.setAttribute("font-size","6"),y.setAttribute("font-family",g.font),y.setAttribute("text-anchor","middle"),y.textContent=d<1e3?`${d.toFixed(0)}ms`:`${(d/1e3).toFixed(1)}s`,n.timelineSvg.appendChild(y);let M=document.createElementNS("http://www.w3.org/2000/svg","line");M.setAttribute("x1",String(E)),M.setAttribute("y1","10"),M.setAttribute("x2",String(E)),M.setAttribute("y2",String(T)),M.setAttribute("stroke",g.border),M.setAttribute("stroke-width","0.5"),n.timelineSvg.appendChild(M);}for(let S=0;S<v.length;S++){let E=v[S],d=12+S*re,y=S%ge.length,M=ge[y],w=document.createElementNS("http://www.w3.org/2000/svg","text");w.setAttribute("x",String(oe-4)),w.setAttribute("y",String(d+re/2+3)),w.setAttribute("fill",g.muted),w.setAttribute("font-size","7"),w.setAttribute("font-family",g.font),w.setAttribute("text-anchor","end"),w.textContent=K(E,12),n.timelineSvg.appendChild(w);let L=l.filter(k=>k.resolver===E);for(let k of L){let j=oe+(k.startMs-i)/o*t,R=Math.max((k.endMs-k.startMs)/o*t,fe),P=document.createElementNS("http://www.w3.org/2000/svg","rect");P.setAttribute("x",String(j)),P.setAttribute("y",String(d+2)),P.setAttribute("width",String(R)),P.setAttribute("height",String(re-4)),P.setAttribute("rx","2"),P.setAttribute("fill",k.error?g.red:M),P.setAttribute("opacity","0.8");let A=document.createElementNS("http://www.w3.org/2000/svg","title"),O=k.endMs-k.startMs;A.textContent=`${E}: ${O.toFixed(1)}ms${k.error?" (error)":""}`,P.appendChild(A),n.timelineSvg.appendChild(P);}let I=c.inflight.get(E);if(I!==void 0){let k=oe+(I-i)/o*t,j=Math.max((m-I)/o*t,fe),R=document.createElementNS("http://www.w3.org/2000/svg","rect");R.setAttribute("x",String(k)),R.setAttribute("y",String(d+2)),R.setAttribute("width",String(j)),R.setAttribute("height",String(re-4)),R.setAttribute("rx","2"),R.setAttribute("fill",M),R.setAttribute("opacity","0.4"),R.setAttribute("stroke",M),R.setAttribute("stroke-width","1"),R.setAttribute("stroke-dasharray","3,2");let P=document.createElementNS("http://www.w3.org/2000/svg","title");P.textContent=`${E}: inflight ${(m-I).toFixed(0)}ms`,R.appendChild(P),n.timelineSvg.appendChild(R);}}n.timelineSvg.setAttribute("aria-label",`Timeline: ${l.length} resolver executions across ${v.length} resolvers`);}function Qe(){if(typeof window>"u")return {systems:new Map,getSystem:()=>null,getSystems:()=>[],inspect:()=>null,getEvents:()=>[],explain:()=>null,exportSession:()=>null,importSession:()=>false,clearEvents:()=>{},subscribe:()=>()=>{}};if(!window.__DIRECTIVE__){let n=new Map,c={systems:n,getSystem(l){return l?n.get(l)?.system??null:n.values().next().value?.system??null},getSystems(){return [...n.keys()]},inspect(l){let i=this.getSystem(l),s=l?n.get(l):n.values().next().value,m=i?.inspect()??null;return m&&s&&(m.resolverStats=s.resolverStats?Object.fromEntries(s.resolverStats):{}),m},getEvents(l){return l?n.get(l)?.events.toArray()??[]:n.values().next().value?.events.toArray()??[]},explain(l,i){return this.getSystem(i)?.explain(l)??null},subscribe(l,i){let s=i?n.get(i):n.values().next().value;if(!s){let m=false,t=setInterval(()=>{let a=i?n.get(i):n.values().next().value;a&&!m&&(m=true,a.subscribers.add(l));},100),r=setTimeout(()=>clearInterval(t),1e4);return ()=>{clearInterval(t),clearTimeout(r);for(let a of n.values())a.subscribers.delete(l);}}return s.subscribers.add(l),()=>{s.subscribers.delete(l);}},exportSession(l){let i=l?n.get(l):n.values().next().value;return i?JSON.stringify({version:1,name:l??n.keys().next().value??"default",exportedAt:Date.now(),events:i.events.toArray()}):null},importSession(l,i){try{if(l.length>10*1024*1024)return !1;let s=JSON.parse(l);if(!s||typeof s!="object"||Array.isArray(s)||!Array.isArray(s.events))return !1;let m=i?n.get(i):n.values().next().value;if(!m)return !1;let o=m.maxEvents,t=s.events,r=t.length>o?t.length-o:0;m.events.clear();for(let a=r;a<t.length;a++){let f=t[a];f&&typeof f=="object"&&!Array.isArray(f)&&typeof f.timestamp=="number"&&typeof f.type=="string"&&f.type!=="__proto__"&&f.type!=="constructor"&&f.type!=="prototype"&&m.events.push({timestamp:f.timestamp,type:f.type,data:f.data??null});}return !0}catch{return false}},clearEvents(l){let i=l?n.get(l):n.values().next().value;i&&i.events.clear();}};return Object.defineProperty(window,"__DIRECTIVE__",{value:c,writable:false,configurable:le(),enumerable:true}),c}return window.__DIRECTIVE__}function Ze(n={}){let{name:c="default",trace:l=false,maxEvents:i,panel:s=false,position:m="bottom-right",defaultOpen:o=false}=n,t=De(i),r=Qe(),a={system:null,events:new ie(t),maxEvents:t,subscribers:new Set,resolverStats:new Map};r.systems.set(c,a);let f=(e,u)=>{let x={timestamp:Date.now(),type:e,data:u};l&&a.events.push(x);for(let C of a.subscribers)try{C(x);}catch{}},v=null,T=new Map,D=new Map,S=Re(),E=Le(),d=_e(),y=ke(),M=s&&typeof window<"u"&&typeof document<"u"&&le(),w=null,L=0,I=1,k=2,j=4,R=8,P=16,A=32,O=64,V=128,F=new Map,U=new Set,G=null;function N(e){L|=e,w===null&&typeof requestAnimationFrame<"u"&&(w=requestAnimationFrame(p));}function p(){if(w=null,!v||!a.system){L=0;return}let e=v.refs,u=a.system,x=L;if(L=0,x&I){for(let C of U)Be(T,C);U.clear();for(let[C,{value:H,flash:B}]of F)se(T,e.factsBody,C,H,B,v.flashTimers);F.clear(),e.factsCount.textContent=String(T.size);}if(x&k&&he(e,D,u,v.flashTimers),x&R)if(G)de(e,G.inflight.length,G.unmet.length);else {let C=te(u);C&&de(e,C.inflight.length,C.unmet.length);}if(x&j)if(G)ue(e,G.inflight,G.unmet);else {let C=te(u);C&&ue(e,C.inflight,C.unmet);}x&P&&He(e,S),x&A&&Se(e,u,E),x&O&&be(e,u),x&V&&Ve(e,y);}function h(e,u){v&&l&&$e(v.refs,e,u,a.events.size);}function b(e,u){d.isRecording&&d.recordedEvents.length<Oe&&d.recordedEvents.push({timestamp:Date.now(),type:e,data:Ae(u)});}return {name:"devtools",onInit:e=>{if(a.system=e,f("init",{}),typeof window<"u"&&console.log(`%c[Directive Devtools]%c System "${c}" initialized. Access via window.__DIRECTIVE__`,"color: #7c3aed; font-weight: bold","color: inherit"),M){let u=a.system;v=Ne(c,m,o,l);let x=v.refs;try{let H=u.facts.$store.toObject();for(let[B,q]of Object.entries(H))se(T,x.factsBody,B,q,!1);x.factsCount.textContent=String(Object.keys(H).length);}catch{}he(x,D,u);let C=te(u);C&&(de(x,C.inflight.length,C.unmet.length),ue(x,C.inflight,C.unmet)),be(x,u),Fe(x,u),Se(x,u,E),x.recordBtn.addEventListener("click",()=>{if(d.isRecording=!d.isRecording,x.recordBtn.textContent=d.isRecording?"\u23F9 Stop":"\u23FA Record",x.recordBtn.style.color=d.isRecording?g.red:g.text,d.isRecording){d.recordedEvents=[],d.snapshots=[];try{d.snapshots.push({timestamp:Date.now(),facts:u.facts.$store.toObject()});}catch{}}}),x.exportBtn.addEventListener("click",()=>{let H=d.recordedEvents.length>0?d.recordedEvents:a.events.toArray(),B=JSON.stringify({version:1,name:c,exportedAt:Date.now(),events:H,snapshots:d.snapshots},null,2),q=new Blob([B],{type:"application/json"}),W=URL.createObjectURL(q),J=document.createElement("a");J.href=W,J.download=`directive-session-${c}-${Date.now()}.json`,J.click(),URL.revokeObjectURL(W);});}},onStart:e=>{f("start",{}),h("start",{}),b("start",{});},onStop:e=>{f("stop",{}),h("stop",{}),b("stop",{});},onDestroy:e=>{f("destroy",{}),r.systems.delete(c),w!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(w),w=null),E.animationTimer&&clearTimeout(E.animationTimer),v&&(v.destroy(),v=null,T.clear(),D.clear());},onFactSet:(e,u,x)=>{f("fact.set",{key:e,value:u,prev:x}),b("fact.set",{key:e,value:u,prev:x}),E.recentlyChangedFacts.add(e),v&&a.system&&(F.set(e,{value:u,flash:true}),U.delete(e),N(I),h("fact.set",{key:e,value:u}));},onFactDelete:(e,u)=>{f("fact.delete",{key:e,prev:u}),b("fact.delete",{key:e,prev:u}),v&&(U.add(e),F.delete(e),N(I),h("fact.delete",{key:e}));},onFactsBatch:e=>{if(f("facts.batch",{changes:e}),b("facts.batch",{count:e.length}),v&&a.system){for(let u of e)u.type==="delete"?(U.add(u.key),F.delete(u.key)):(E.recentlyChangedFacts.add(u.key),F.set(u.key,{value:u.value,flash:true}),U.delete(u.key));N(I),h("facts.batch",{count:e.length});}},onDerivationCompute:(e,u,x)=>{f("derivation.compute",{id:e,value:u,deps:x}),b("derivation.compute",{id:e,deps:x}),E.derivationDeps.set(e,x),E.recentlyComputedDerivations.add(e),h("derivation.compute",{id:e,deps:x});},onDerivationInvalidate:e=>{f("derivation.invalidate",{id:e}),h("derivation.invalidate",{id:e});},onReconcileStart:e=>{f("reconcile.start",{}),S.lastReconcileStartMs=performance.now(),h("reconcile.start",{}),b("reconcile.start",{});},onReconcileEnd:e=>{if(f("reconcile.end",e),b("reconcile.end",{unmet:e.unmet.length,inflight:e.inflight.length,completed:e.completed.length}),S.lastReconcileStartMs>0){let u=performance.now()-S.lastReconcileStartMs;S.reconcileCount++,S.reconcileTotalMs+=u,S.lastReconcileStartMs=0;}if(d.isRecording&&a.system&&d.snapshots.length<Pe)try{d.snapshots.push({timestamp:Date.now(),facts:a.system.facts.$store.toObject()});}catch{}v&&a.system&&(G=e,je(E),N(k|R|j|P|A|O),h("reconcile.end",{unmet:e.unmet.length,inflight:e.inflight.length}));},onConstraintEvaluate:(e,u)=>{f("constraint.evaluate",{id:e,active:u}),b("constraint.evaluate",{id:e,active:u}),u?(E.activeConstraints.add(e),E.recentlyActiveConstraints.add(e)):E.activeConstraints.delete(e),h("constraint.evaluate",{id:e,active:u});},onConstraintError:(e,u)=>{f("constraint.error",{id:e,error:String(u)}),h("constraint.error",{id:e,error:String(u)});},onRequirementCreated:e=>{f("requirement.created",{id:e.id,type:e.requirement.type}),b("requirement.created",{id:e.id,type:e.requirement.type}),h("requirement.created",{id:e.id,type:e.requirement.type});},onRequirementMet:(e,u)=>{f("requirement.met",{id:e.id,byResolver:u}),b("requirement.met",{id:e.id,byResolver:u}),h("requirement.met",{id:e.id,byResolver:u});},onRequirementCanceled:e=>{f("requirement.canceled",{id:e.id}),b("requirement.canceled",{id:e.id}),h("requirement.canceled",{id:e.id});},onResolverStart:(e,u)=>{f("resolver.start",{resolver:e,requirementId:u.id}),b("resolver.start",{resolver:e,requirementId:u.id}),y.inflight.set(e,performance.now()),v&&a.system&&(N(j|R|V),h("resolver.start",{resolver:e,requirementId:u.id}));},onResolverComplete:(e,u,x)=>{f("resolver.complete",{resolver:e,requirementId:u.id,duration:x}),b("resolver.complete",{resolver:e,requirementId:u.id,duration:x});let C=a.resolverStats.get(e)??{count:0,totalMs:0,errors:0};if(C.count++,C.totalMs+=x,a.resolverStats.set(e,C),a.resolverStats.size>ye){let B=a.resolverStats.keys().next().value;B!==void 0&&a.resolverStats.delete(B);}S.resolverStats.set(e,{...C});let H=y.inflight.get(e);y.inflight.delete(e),H!==void 0&&y.entries.push({resolver:e,startMs:H,endMs:performance.now(),error:false}),v&&a.system&&(N(j|R|P|V),h("resolver.complete",{resolver:e,duration:x}));},onResolverError:(e,u,x)=>{f("resolver.error",{resolver:e,requirementId:u.id,error:String(x)}),b("resolver.error",{resolver:e,requirementId:u.id,error:String(x)});let C=a.resolverStats.get(e)??{count:0,totalMs:0,errors:0};if(C.errors++,a.resolverStats.set(e,C),a.resolverStats.size>ye){let B=a.resolverStats.keys().next().value;B!==void 0&&a.resolverStats.delete(B);}S.resolverStats.set(e,{...C});let H=y.inflight.get(e);y.inflight.delete(e),H!==void 0&&y.entries.push({resolver:e,startMs:H,endMs:performance.now(),error:true}),v&&a.system&&(N(j|R|P|V),h("resolver.error",{resolver:e,error:String(x)}));},onResolverRetry:(e,u,x)=>{f("resolver.retry",{resolver:e,requirementId:u.id,attempt:x}),b("resolver.retry",{resolver:e,requirementId:u.id,attempt:x}),h("resolver.retry",{resolver:e,attempt:x});},onResolverCancel:(e,u)=>{f("resolver.cancel",{resolver:e,requirementId:u.id}),b("resolver.cancel",{resolver:e,requirementId:u.id}),y.inflight.delete(e),h("resolver.cancel",{resolver:e});},onEffectRun:e=>{f("effect.run",{id:e}),b("effect.run",{id:e}),S.effectRunCount++,h("effect.run",{id:e});},onEffectError:(e,u)=>{f("effect.error",{id:e,error:String(u)}),S.effectErrorCount++,h("effect.error",{id:e,error:String(u)});},onSnapshot:e=>{f("timetravel.snapshot",{id:e.id,trigger:e.trigger}),v&&a.system&&N(O),h("timetravel.snapshot",{id:e.id,trigger:e.trigger});},onHistoryNavigate:(e,u)=>{if(f("timetravel.jump",{from:e,to:u}),b("timetravel.jump",{from:e,to:u}),v&&a.system){let x=a.system;try{let C=x.facts.$store.toObject();T.clear(),v.refs.factsBody.replaceChildren();for(let[H,B]of Object.entries(C))se(T,v.refs.factsBody,H,B,!1);v.refs.factsCount.textContent=String(Object.keys(C).length);}catch{}D.clear(),E.derivationDeps.clear(),v.refs.derivBody.replaceChildren(),G=null,N(k|R|j|A|O),h("timetravel.jump",{from:e,to:u});}},onError:e=>{f("error",{source:e.source,sourceId:e.sourceId,message:e.message}),b("error",{source:e.source,message:e.message}),h("error",{source:e.source,message:e.message});},onErrorRecovery:(e,u)=>{f("error.recovery",{source:e.source,sourceId:e.sourceId,strategy:u}),h("error.recovery",{source:e.source,strategy:u});},onTraceComplete:e=>{f("trace.complete",{id:e.id,status:e.status,facts:e.factChanges.length,constraints:e.constraintsHit.length,requirements:e.requirementsAdded.length,resolvers:e.resolversStarted.length,effects:e.effectsRun.length}),h("trace.complete",{id:e.id});},onDefinitionRegister:(e,u)=>{f("definition.register",{type:e,id:u}),b("definition.register",{type:e,id:u}),h("definition.register",{type:e,id:u});},onDefinitionAssign:(e,u)=>{f("definition.assign",{type:e,id:u}),b("definition.assign",{type:e,id:u}),h("definition.assign",{type:e,id:u});},onDefinitionUnregister:(e,u)=>{f("definition.unregister",{type:e,id:u}),b("definition.unregister",{type:e,id:u}),h("definition.unregister",{type:e,id:u});},onDefinitionCall:(e,u,x)=>{f("definition.call",{type:e,id:u,props:x}),b("definition.call",{type:e,id:u,props:x}),h("definition.call",{type:e,id:u,props:x});}}}var ze="directive-devtools-event",qe=new Set(["__proto__","constructor","prototype"]),et=Math.random().toString(36).slice(2,8);function tt(){if(typeof window<"u"){let n=`__DIRECTIVE_BRIDGE_ID_${et}__`,c=window,l=c[n]??0;return c[n]=l+1,l+1}return 1}function nt(n){let c=false;for(let i of qe)if(i in n){c=true;break}if(!c)return n;let l=Object.create(null);for(let[i,s]of Object.entries(n))qe.has(i)||(l[i]=s);return l}function rt(n){if(!(typeof window>"u"))try{let c=nt(n),l={id:tt(),timestamp:Date.now(),snapshotId:null,...c};window.dispatchEvent(new CustomEvent(ze,{detail:l}));}catch{}}function We(n,c=50){let l=new Set(["__proto__","constructor","prototype"]),i=new WeakSet;function s(m,o){if(o>c)return false;if(m==null||typeof m!="object")return true;let t=m;if(i.has(t))return true;if(i.add(t),Array.isArray(t)){for(let r of t)if(!s(r,o+1))return i.delete(t),false;return i.delete(t),true}for(let r of Object.keys(t))if(l.has(r)||!s(t[r],o+1))return i.delete(t),false;return i.delete(t),true}return s(n,0)}function ot(n){let{storage:c,key:l,include:i,exclude:s=[],debounce:m=100,onRestore:o,onSave:t,onError:r}=n,a=null,f=null,v=new Set,T=d=>s.includes(d)?false:i?i.includes(d):true,D=()=>{try{let d=c.getItem(l);if(!d)return null;let y=JSON.parse(d);return typeof y!="object"||y===null?null:We(y)?y:(r?.(new Error("Potential prototype pollution detected in stored data")),null)}catch(d){return r?.(d instanceof Error?d:new Error(String(d))),null}},S=()=>{if(f)try{let d={};for(let y of v)T(y)&&(d[y]=f.facts[y]);c.setItem(l,JSON.stringify(d)),t?.(d);}catch(d){r?.(d instanceof Error?d:new Error(String(d)));}},E=()=>{a&&clearTimeout(a),a=setTimeout(S,m);};return {name:"persistence",onInit:d=>{f=d;let y=D();y&&(f.facts.$store.batch(()=>{for(let[M,w]of Object.entries(y))T(M)&&(f.facts[M]=w,v.add(M));}),o?.(y));},onDestroy:()=>{a&&clearTimeout(a),S();},onFactSet:d=>{v.add(d),T(d)&&E();},onFactDelete:d=>{v.delete(d),T(d)&&E();},onFactsBatch:d=>{let y=false;for(let M of d)M.type==="set"?v.add(M.key):v.delete(M.key),T(M.key)&&(y=true);y&&E();}}}function it(n={}){let{onSlowConstraint:c,onSlowResolver:l,slowConstraintThresholdMs:i=16,slowResolverThresholdMs:s=1e3}=n,m=new Map,o=new Map,t=new Map,r={runs:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0},a=0,f=0,v=0;function T(d){let y=m.get(d);return y||(y={evaluations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastEvaluatedAt:0},m.set(d,y)),y}function D(d){let y=o.get(d);return y||(y={starts:0,completions:0,errors:0,retries:0,cancellations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastCompletedAt:0},o.set(d,y)),y}function S(d){let y=t.get(d);return y||(y={runs:0,errors:0,lastRunAt:0},t.set(d,y)),y}return {name:"performance",onStart(){a=Date.now();},onConstraintEvaluate(d,y){let M=performance.now(),w=T(d);if(w.evaluations++,w.lastEvaluatedAt=Date.now(),v>0){let L=M-v;w.totalDurationMs+=L;let I=w.evaluations;w.avgDurationMs=w.totalDurationMs/I,L>w.maxDurationMs&&(w.maxDurationMs=L),L>i&&c?.(d,L);}v=M;},onResolverStart(d,y){let M=D(d);M.starts++;},onResolverComplete(d,y,M){let w=D(d);w.completions++,w.totalDurationMs+=M,w.avgDurationMs=w.totalDurationMs/w.completions,M>w.maxDurationMs&&(w.maxDurationMs=M),w.lastCompletedAt=Date.now(),M>s&&l?.(d,M);},onResolverError(d,y,M){D(d).errors++;},onResolverRetry(d,y,M){D(d).retries++;},onResolverCancel(d,y){D(d).cancellations++;},onEffectRun(d){let y=S(d);y.runs++,y.lastRunAt=Date.now();},onEffectError(d,y){S(d).errors++;},onReconcileStart(){f=performance.now(),v=0;},onReconcileEnd(){let d=performance.now()-f;r.runs++,r.totalDurationMs+=d,r.avgDurationMs=r.totalDurationMs/r.runs,d>r.maxDurationMs&&(r.maxDurationMs=d);},getSnapshot(){let d={};for(let[w,L]of m)d[w]={...L};let y={};for(let[w,L]of o)y[w]={...L};let M={};for(let[w,L]of t)M[w]={...L};return {constraints:d,resolvers:y,effects:M,reconcile:{...r},uptime:a?Date.now()-a:0}},reset(){m.clear(),o.clear(),t.clear(),r.runs=0,r.totalDurationMs=0,r.avgDurationMs=0,r.maxDurationMs=0,v=0;}}}function st(n){let c=[{key:"service.name",value:{stringValue:n.serviceName??"directive-agents"}}];if(n.serviceVersion&&c.push({key:"service.version",value:{stringValue:n.serviceVersion}}),n.resourceAttributes)for(let[l,i]of Object.entries(n.resourceAttributes))c.push({key:l,value:{stringValue:i}});return {attributes:c}}function Z(n){return `${BigInt(n)*BigInt(1e6)}`}function at(n){switch(n){case "counter":return "sum";case "gauge":return "gauge";case "histogram":return "histogram";default:return "gauge"}}function ct(n,c,l){let i=n.map(s=>{let m=s.lastUpdated-6e4,o=[{asInt:s.type==="counter"?s.sum:void 0,asDouble:s.type!=="counter"?s.lastValue:void 0,timeUnixNano:Z(s.lastUpdated),startTimeUnixNano:Z(m),attributes:[]}],t=at(s.type),r={name:s.name,unit:""};return t==="sum"?r.sum={dataPoints:o,aggregationTemporality:2,isMonotonic:true}:t==="histogram"?r.histogram={dataPoints:[{count:s.count,sum:s.sum,min:s.min,max:s.max,timeUnixNano:Z(s.lastUpdated),startTimeUnixNano:Z(m),attributes:[]}],aggregationTemporality:2}:r.gauge={dataPoints:o},r});return {resourceMetrics:[{resource:c,scopeMetrics:[{scope:{name:"directive",version:l},metrics:i}]}]}}function lt(n,c,l){let i=n.map(s=>{let m=s.logs.map(r=>({timeUnixNano:Z(r.timestamp),name:r.level,attributes:[{key:"message",value:{stringValue:r.message}},{key:"level",value:{stringValue:r.level}}]})),o=Object.entries(s.tags).map(([r,a])=>({key:r,value:typeof a=="string"?{stringValue:a}:typeof a=="number"?{intValue:`${a}`}:{boolValue:a}})),t=s.status==="ok"?1:s.status==="error"?2:0;return {traceId:s.traceId.replace(/-/g,"").padEnd(32,"0").slice(0,32),spanId:s.spanId.replace(/-/g,"").padEnd(16,"0").slice(0,16),parentSpanId:s.parentSpanId?s.parentSpanId.replace(/-/g,"").padEnd(16,"0").slice(0,16):void 0,name:s.operationName,kind:1,startTimeUnixNano:Z(s.startTime),endTimeUnixNano:s.endTime?Z(s.endTime):Z(s.startTime),attributes:o,events:m,status:{code:t}}});return {resourceSpans:[{resource:c,scopeSpans:[{scope:{name:"directive",version:l},spans:i}]}]}}function ut(n){let{endpoint:c,headers:l={},scopeVersion:i="0.1.0",timeoutMs:s=1e4,fetch:m=globalThis.fetch,onError:o}=n;try{let a=new URL(c);if(a.protocol!=="http:"&&a.protocol!=="https:")throw new Error("Only http: and https: protocols are supported")}catch(a){throw new Error(`[Directive OTLP] Invalid endpoint URL "${c}": ${a instanceof Error?a.message:String(a)}`)}if(/\/v1\/(metrics|traces)/.test(c)&&console.warn(`[Directive OTLP] Endpoint "${c}" already contains a /v1/metrics or /v1/traces path. The exporter will append /v1/metrics or /v1/traces automatically. Use the base URL (e.g., "http://localhost:4318") instead.`),s<=0||!Number.isFinite(s))throw new Error(`[Directive OTLP] timeoutMs must be > 0, got ${s}`);let t=st(n);async function r(a,f,v){let T=`${c.replace(/\/$/,"")}${a}`,D=new AbortController,S=setTimeout(()=>D.abort(),s);try{let E=await m(T,{method:"POST",headers:{"Content-Type":"application/json",...l},body:JSON.stringify(f),signal:D.signal});if(!E.ok)throw new Error(`OTLP export failed: ${E.status} ${E.statusText}`)}catch(E){let d=E instanceof Error?E:new Error(String(E));o?o(d,v):console.error(`[Directive OTLP] Export ${v} error:`,d.message);}finally{clearTimeout(S);}}return {async exportMetrics(a){if(a.length===0)return;let f=ct(a,t,i);await r("/v1/metrics",f,"metrics");},async exportTraces(a){if(a.length===0)return;let f=lt(a,t,i);await r("/v1/traces",f,"traces");}}}var ae=class extends Error{code="CIRCUIT_OPEN";retryAfterMs;state;constructor(c,l,i="OPEN",s){let m=s?`[Directive CircuitBreaker] Circuit "${c}" is ${i}. ${s}`:`[Directive CircuitBreaker] Circuit "${c}" is ${i}. Request rejected. Try again in ${Math.ceil(l/1e3)}s.`;super(m),this.name="CircuitBreakerOpenError",this.retryAfterMs=l,this.state=i;}};function dt(n={}){let{failureThreshold:c=5,recoveryTimeMs:l=3e4,halfOpenMaxRequests:i=3,failureWindowMs:s=6e4,observability:m,metricPrefix:o="circuit_breaker",name:t="default",isFailure:r=()=>true,onStateChange:a}=n;if(c<1||!Number.isFinite(c))throw new Error(`[Directive CircuitBreaker] failureThreshold must be >= 1, got ${c}`);if(l<=0||!Number.isFinite(l))throw new Error(`[Directive CircuitBreaker] recoveryTimeMs must be > 0, got ${l}`);if(i<1||!Number.isFinite(i))throw new Error(`[Directive CircuitBreaker] halfOpenMaxRequests must be >= 1, got ${i}`);if(s<=0||!Number.isFinite(s))throw new Error(`[Directive CircuitBreaker] failureWindowMs must be > 0, got ${s}`);let f="CLOSED",v=[],T=0,D=0,S=Date.now(),E=0,d=0,y=0,M=0,w=0,L=null,I=null;function k(A){if(f===A)return;let O=f;f=A,S=Date.now(),A==="OPEN"&&(E=Date.now()),A==="HALF_OPEN"&&(T=0,D=0),a?.(O,A),m&&m.incrementCounter(`${o}.state_change`,{name:t,from:O,to:A});}function j(){let A=Date.now()-s;return v=v.filter(O=>O>A),v.length}function R(){M++,I=Date.now(),m&&m.incrementCounter(`${o}.success`,{name:t}),f==="HALF_OPEN"&&(D++,D>=i&&(k("CLOSED"),v=[]));}function P(A){if(!r(A)){R();return}y++,L=Date.now(),v.push(Date.now());let O=c*2;if(v.length>O&&(v=v.slice(-O)),m&&m.incrementCounter(`${o}.failure`,{name:t}),f==="HALF_OPEN"){k("OPEN");return}f==="CLOSED"&&j()>=c&&k("OPEN");}return {async execute(A){if(d++,m&&m.incrementCounter(`${o}.requests`,{name:t}),f==="OPEN")if(Date.now()-E>=l)k("HALF_OPEN");else throw w++,m&&m.incrementCounter(`${o}.rejected`,{name:t}),new ae(t,l-(Date.now()-E));if(f==="HALF_OPEN"){if(T>=i)throw w++,new ae(t,l,"HALF_OPEN",`Max trial requests (${i}) reached.`);T++;}let O=Date.now();try{let V=await A();return R(),m&&m.observeHistogram(`${o}.latency`,Date.now()-O,{name:t}),V}catch(V){let F=V instanceof Error?V:new Error(String(V));throw P(F),m&&m.observeHistogram(`${o}.latency`,Date.now()-O,{name:t}),V}},getState(){return f==="OPEN"&&Date.now()-E>=l&&k("HALF_OPEN"),f},getStats(){return {state:this.getState(),totalRequests:d,totalFailures:y,totalSuccesses:M,totalRejected:w,recentFailures:j(),lastFailureTime:L,lastSuccessTime:I,lastStateChange:S}},forceState(A){k(A);},reset(){let A=f;f="CLOSED",v=[],T=0,D=0,S=Date.now(),E=0,d=0,y=0,M=0,w=0,L=null,I=null,A!=="CLOSED"&&a?.(A,"CLOSED");},isAllowed(){return f==="CLOSED"?true:f==="OPEN"?Date.now()-E>=l:T<i}}}
2
- export{ae as CircuitBreakerOpenError,ze as DEVTOOLS_EVENT_NAME,dt as createCircuitBreaker,ut as createOTLPExporter,Ze as devtoolsPlugin,rt as emitDevToolsEvent,Xe as loggingPlugin,it as performancePlugin,ot as persistencePlugin};//# sourceMappingURL=index.js.map
1
+ import {c}from'../chunk-GO63IIN5.js';var Re={debug:0,info:1,warn:2,error:3};function Xe(n={}){let{level:a="info",filter:l=()=>true,logger:c=console,prefix:s="[Directive]"}=n,f=Re[a],o=(t,r,...i)=>{Re[t]<f||l(r)&&c[t](`${s} ${r}`,...i);};return {name:"logging",onInit:()=>o("debug","init"),onStart:()=>o("info","start"),onStop:()=>o("info","stop"),onDestroy:()=>o("debug","destroy"),onFactSet:(t,r,i)=>{o("debug","fact.set",{key:t,value:r,prev:i});},onFactDelete:(t,r)=>{o("debug","fact.delete",{key:t,prev:r});},onFactsBatch:t=>{o("debug","facts.batch",{count:t.length,changes:t});},onDerivationCompute:(t,r,i)=>{o("debug","derivation.compute",{id:t,value:r,deps:i});},onDerivationInvalidate:t=>{o("debug","derivation.invalidate",{id:t});},onReconcileStart:()=>{o("debug","reconcile.start");},onReconcileEnd:t=>{o("debug","reconcile.end",{unmet:t.unmet.length,inflight:t.inflight.length,completed:t.completed.length,canceled:t.canceled.length});},onConstraintEvaluate:(t,r)=>{o("debug","constraint.evaluate",{id:t,active:r});},onConstraintError:(t,r)=>{o("error","constraint.error",{id:t,error:r});},onRequirementCreated:t=>{o("debug","requirement.created",{id:t.id,type:t.requirement.type});},onRequirementMet:(t,r)=>{o("info","requirement.met",{id:t.id,byResolver:r});},onRequirementCanceled:t=>{o("debug","requirement.canceled",{id:t.id});},onResolverStart:(t,r)=>{o("debug","resolver.start",{resolver:t,requirementId:r.id});},onResolverComplete:(t,r,i)=>{o("info","resolver.complete",{resolver:t,requirementId:r.id,duration:i});},onResolverError:(t,r,i)=>{o("error","resolver.error",{resolver:t,requirementId:r.id,error:i});},onResolverRetry:(t,r,i)=>{o("warn","resolver.retry",{resolver:t,requirementId:r.id,attempt:i});},onResolverCancel:(t,r)=>{o("debug","resolver.cancel",{resolver:t,requirementId:r.id});},onEffectRun:t=>{o("debug","effect.run",{id:t});},onEffectError:(t,r)=>{o("error","effect.error",{id:t,error:r});},onSnapshot:t=>{o("debug","timetravel.snapshot",{id:t.id,trigger:t.trigger});},onHistoryNavigate:(t,r)=>{o("info","timetravel.jump",{from:t,to:r});},onError:t=>{o("error","error",{source:t.source,sourceId:t.sourceId,message:t.message});},onErrorRecovery:(t,r)=>{o("warn","error.recovery",{source:t.source,sourceId:t.sourceId,strategy:r});},onDefinitionRegister:(t,r)=>{o("info","definition.register",{type:t,id:r});},onDefinitionAssign:(t,r)=>{o("info","definition.assign",{type:t,id:r});},onDefinitionUnregister:(t,r)=>{o("info","definition.unregister",{type:t,id:r});},onDefinitionCall:(t,r,i)=>{o("debug","definition.call",{type:t,id:r,props:i});},onTraceComplete:t=>{o("debug","trace.complete",{id:t.id,status:t.status,duration:t.duration,factChanges:t.factChanges.length,derivationsRecomputed:t.derivationsRecomputed.length,constraintsHit:t.constraintsHit.length,resolversStarted:t.resolversStarted.length,effectsRun:t.effectsRun.length});}}}var ie=class{constructor(a){this.capacity=a;this.buf=new Array(a);}buf;head=0;_size=0;get size(){return this._size}push(a){this.buf[this.head]=a,this.head=(this.head+1)%this.capacity,this._size<this.capacity&&this._size++;}toArray(){return this._size===0?[]:this._size<this.capacity?this.buf.slice(0,this._size):[...this.buf.slice(this.head),...this.buf.slice(0,this.head)]}clear(){this.buf=new Array(this.capacity),this.head=0,this._size=0;}};function le(){try{if(typeof process<"u"&&process.env?.NODE_ENV==="production")return !1}catch{}try{if(typeof import.meta<"u"&&import.meta.env?.MODE==="production")return !1}catch{}return true}function pe(n){try{if(n===void 0)return "undefined";if(n===null)return "null";if(typeof n=="bigint")return String(n)+"n";if(typeof n=="symbol")return String(n);if(typeof n=="object"){let a=JSON.stringify(n,(l,c)=>typeof c=="bigint"?String(c)+"n":typeof c=="symbol"?String(c):c);return a.length>120?a.slice(0,117)+"...":a}return String(n)}catch{return "<error>"}}function K(n,a){return n.length<=a?n:n.slice(0,a-3)+"..."}function te(n){try{return n.inspect()}catch{return null}}function De(n){try{return n==null||typeof n!="object"?n:JSON.parse(JSON.stringify(n))}catch{return null}}function Ae(n){return n===void 0?1e3:!Number.isFinite(n)||n<1?(le()&&console.warn(`[directive:devtools] Invalid maxEvents value (${n}), using default 1000`),1e3):Math.floor(n)}function Oe(){return {reconcileCount:0,reconcileTotalMs:0,resolverStats:new Map,effectRunCount:0,effectErrorCount:0,lastReconcileStartMs:0}}var Ye=200,ne=340,re=16,oe=80,fe=2,ge=["#8b9aff","#4ade80","#fbbf24","#c084fc","#f472b6","#22d3ee"];function Le(){return {entries:new ie(Ye),inflight:new Map}}function ke(){return {derivationDeps:new Map,activeConstraints:new Set,recentlyChangedFacts:new Set,recentlyComputedDerivations:new Set,recentlyActiveConstraints:new Set,animationTimer:null}}var Pe=1e4,_e=100;function Ie(){return {isRecording:false,recordedEvents:[],snapshots:[]}}var Ne=50,ve=200,g={bg:"#1a1a2e",text:"#e0e0e0",accent:"#8b9aff",muted:"#b0b0d0",border:"#333",rowBorder:"#2a2a4a",green:"#4ade80",yellow:"#fbbf24",red:"#f87171",closeBtn:"#aaa",font:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},_={nodeW:90,nodeH:16,nodeGap:6,startY:16,colGap:20,fontSize:10,labelMaxChars:11};function Be(n,a,l,c){let s=false,f={position:"fixed",zIndex:"99999",...a.includes("bottom")?{bottom:"12px"}:{top:"12px"},...a.includes("right")?{right:"12px"}:{left:"12px"}},o=document.createElement("style");o.textContent=`[data-directive-devtools] summary:focus-visible{outline:2px solid ${g.accent};outline-offset:2px;border-radius:2px}[data-directive-devtools] button:focus-visible{outline:2px solid ${g.accent};outline-offset:2px}`,document.head.appendChild(o);let t=document.createElement("button");t.setAttribute("aria-label","Open Directive DevTools"),t.setAttribute("aria-expanded",String(l)),t.title="Ctrl+Shift+D to toggle",Object.assign(t.style,{...f,background:g.bg,color:g.text,border:`1px solid ${g.border}`,borderRadius:"6px",padding:"10px 14px",minWidth:"44px",minHeight:"44px",cursor:"pointer",fontFamily:g.font,fontSize:"12px",display:l?"none":"block"}),t.textContent="Directive";let r=document.createElement("div");r.setAttribute("role","region"),r.setAttribute("aria-label","Directive DevTools"),r.setAttribute("data-directive-devtools",""),r.tabIndex=-1,Object.assign(r.style,{...f,background:g.bg,color:g.text,border:`1px solid ${g.border}`,borderRadius:"8px",padding:"12px",fontFamily:g.font,fontSize:"11px",maxWidth:"min(380px, calc(100vw - 24px))",maxHeight:"min(500px, calc(100vh - 24px))",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.5)",display:l?"block":"none"});let i=document.createElement("div");Object.assign(i.style,{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"});let p=document.createElement("strong");p.style.color=g.accent,p.textContent=n==="default"?"Directive DevTools":`DevTools (${n})`;let h=document.createElement("button");h.setAttribute("aria-label","Close DevTools"),Object.assign(h.style,{background:"none",border:"none",color:g.closeBtn,cursor:"pointer",fontSize:"16px",padding:"8px 12px",minWidth:"44px",minHeight:"44px",lineHeight:"1",display:"flex",alignItems:"center",justifyContent:"center"}),h.textContent="\xD7",i.appendChild(p),i.appendChild(h),r.appendChild(i);let T=document.createElement("div");T.style.marginBottom="6px",T.setAttribute("aria-live","polite");let D=document.createElement("span");D.style.color=g.green,D.textContent="Settled",T.appendChild(D),r.appendChild(T);let S=document.createElement("div");Object.assign(S.style,{display:"none",marginBottom:"8px",padding:"4px 8px",background:"#252545",borderRadius:"4px",alignItems:"center",gap:"6px"});let E=document.createElement("button");Object.assign(E.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:g.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),E.textContent="\u25C0 Undo",E.disabled=true;let d=document.createElement("button");Object.assign(d.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"4px 10px",borderRadius:"3px",fontFamily:g.font,fontSize:"11px",minWidth:"44px",minHeight:"44px"}),d.textContent="Redo \u25B6",d.disabled=true;let v=document.createElement("span");v.style.color=g.muted,v.style.fontSize="10px",S.appendChild(E),S.appendChild(d),S.appendChild(v),r.appendChild(S);function M($,X){let z=document.createElement("details");X&&(z.open=true),z.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${$} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",z.appendChild(Y);let Q=document.createElement("table");Object.assign(Q.style,{width:"100%",borderCollapse:"collapse",fontSize:"11px"});let Ce=document.createElement("thead"),we=document.createElement("tr");for(let Ge of ["Key","Value"]){let ce=document.createElement("th");ce.scope="col",Object.assign(ce.style,{textAlign:"left",padding:"2px 4px",color:g.accent}),ce.textContent=Ge,we.appendChild(ce);}Ce.appendChild(we),Q.appendChild(Ce);let Me=document.createElement("tbody");return Q.appendChild(Me),z.appendChild(Q),{details:z,tbody:Me,countSpan:ee}}function C($,X){let z=document.createElement("details");z.style.marginBottom="4px";let Y=document.createElement("summary");Object.assign(Y.style,{cursor:"pointer",color:X,marginBottom:"4px"});let ee=document.createElement("span");Y.textContent=`${$} (`,Y.appendChild(ee),Y.appendChild(document.createTextNode(")")),ee.textContent="0",z.appendChild(Y);let Q=document.createElement("ul");return Object.assign(Q.style,{margin:"0",paddingLeft:"16px"}),z.appendChild(Q),{details:z,list:Q,countSpan:ee}}let L=M("Facts",true);r.appendChild(L.details);let I=M("Derivations",false);r.appendChild(I.details);let O=C("Inflight",g.yellow);r.appendChild(O.details);let F=C("Unmet",g.red);r.appendChild(F.details);let A=document.createElement("details");A.style.marginBottom="4px";let P=document.createElement("summary");Object.assign(P.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),P.textContent="Performance",A.appendChild(P);let R=document.createElement("div");R.style.fontSize="10px",R.style.color=g.muted,R.textContent="No data yet",A.appendChild(R),r.appendChild(A);let k=document.createElement("details");k.style.marginBottom="4px";let q=document.createElement("summary");Object.assign(q.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),q.textContent="Dependency Graph",k.appendChild(q);let j=document.createElementNS("http://www.w3.org/2000/svg","svg");j.setAttribute("width","100%"),j.setAttribute("height","120"),j.setAttribute("role","img"),j.setAttribute("aria-label","System dependency graph"),j.style.display="block",j.setAttribute("viewBox","0 0 460 120"),j.setAttribute("preserveAspectRatio","xMinYMin meet"),k.appendChild(j),r.appendChild(k);let U=document.createElement("details");U.style.marginBottom="4px";let G=document.createElement("summary");Object.assign(G.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),G.textContent="Timeline",U.appendChild(G);let N=document.createElementNS("http://www.w3.org/2000/svg","svg");N.setAttribute("width","100%"),N.setAttribute("height","60"),N.setAttribute("role","img"),N.setAttribute("aria-label","Resolver execution timeline"),N.style.display="block",N.setAttribute("viewBox",`0 0 ${ne} 60`),N.setAttribute("preserveAspectRatio","xMinYMin meet");let m=document.createElementNS("http://www.w3.org/2000/svg","text");m.setAttribute("x",String(ne/2)),m.setAttribute("y","30"),m.setAttribute("text-anchor","middle"),m.setAttribute("fill",g.muted),m.setAttribute("font-size","10"),m.setAttribute("font-family",g.font),m.textContent="No resolver activity yet",N.appendChild(m),U.appendChild(N),r.appendChild(U);let b,y,e,u;if(c){let $=document.createElement("details");$.style.marginBottom="4px";let X=document.createElement("summary");Object.assign(X.style,{cursor:"pointer",color:g.accent,marginBottom:"4px"}),e=document.createElement("span"),e.textContent="0",X.textContent="Events (",X.appendChild(e),X.appendChild(document.createTextNode(")")),$.appendChild(X),y=document.createElement("div"),Object.assign(y.style,{maxHeight:"150px",overflow:"auto",fontSize:"10px"}),y.setAttribute("role","log"),y.setAttribute("aria-live","polite"),y.tabIndex=0;let z=document.createElement("div");z.style.color=g.muted,z.style.padding="4px",z.textContent="Waiting for events...",z.className="dt-events-empty",y.appendChild(z),$.appendChild(y),r.appendChild($),b=$,u=document.createElement("div");}else b=document.createElement("details"),y=document.createElement("div"),e=document.createElement("span"),u=document.createElement("div"),u.style.fontSize="10px",u.style.color=g.muted,u.style.marginTop="4px",u.style.fontStyle="italic",u.textContent="Enable trace: true for event log",r.appendChild(u);let x=document.createElement("div");Object.assign(x.style,{display:"flex",gap:"6px",marginTop:"6px"});let w=document.createElement("button");Object.assign(w.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:g.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),w.textContent="\u23FA Record";let H=document.createElement("button");Object.assign(H.style,{background:"none",border:`1px solid ${g.border}`,color:g.text,cursor:"pointer",padding:"8px 12px",borderRadius:"3px",fontFamily:g.font,fontSize:"10px",minWidth:"44px",minHeight:"44px"}),H.textContent="\u2913 Export",x.appendChild(w),x.appendChild(H),r.appendChild(x),r.addEventListener("wheel",$=>{let X=r,z=X.scrollTop===0&&$.deltaY<0,Y=X.scrollTop+X.clientHeight>=X.scrollHeight&&$.deltaY>0;(z||Y)&&$.preventDefault();},{passive:false});let B=l,V=new Set;function W(){B=true,r.style.display="block",t.style.display="none",t.setAttribute("aria-expanded","true"),h.focus();}function J(){B=false,r.style.display="none",t.style.display="block",t.setAttribute("aria-expanded","false"),t.focus();}t.addEventListener("click",W),h.addEventListener("click",J);function xe($){$.key==="Escape"&&B&&J();}r.addEventListener("keydown",xe);function Ee($){$.key==="d"&&$.shiftKey&&($.ctrlKey||$.metaKey)&&($.preventDefault(),B?J():W());}document.addEventListener("keydown",Ee);function me(){s||(document.body.appendChild(t),document.body.appendChild(r));}document.body?me():document.addEventListener("DOMContentLoaded",me,{once:true});function Ue(){s=true,t.removeEventListener("click",W),h.removeEventListener("click",J),r.removeEventListener("keydown",xe),document.removeEventListener("keydown",Ee),document.removeEventListener("DOMContentLoaded",me);for(let $ of V)clearTimeout($);V.clear(),t.remove(),r.remove(),o.remove();}return {refs:{container:r,toggleBtn:t,titleEl:p,statusEl:D,factsBody:L.tbody,factsCount:L.countSpan,derivBody:I.tbody,derivCount:I.countSpan,derivSection:I.details,inflightList:O.list,inflightSection:O.details,inflightCount:O.countSpan,unmetList:F.list,unmetSection:F.details,unmetCount:F.countSpan,perfSection:A,perfBody:R,historySection:S,historyLabel:v,undoBtn:E,redoBtn:d,flowSection:k,flowSvg:j,timelineSection:U,timelineSvg:N,eventsSection:b,eventsList:y,eventsCount:e,traceHint:u,recordBtn:w,exportBtn:H},destroy:Ue,isOpen:()=>B,flashTimers:V}}function se(n,a,l,c,s,f){let o=pe(c),t=n.get(l);if(t){let r=t.cells;if(r[1]&&(r[1].textContent=o,s&&f)){let i=r[1];i.style.background="rgba(139, 154, 255, 0.25)";let p=setTimeout(()=>{i.style.background="",f.delete(p);},300);f.add(p);}}else {t=document.createElement("tr"),t.style.borderBottom=`1px solid ${g.rowBorder}`;let r=document.createElement("td");Object.assign(r.style,{padding:"2px 4px",color:g.muted}),r.textContent=l;let i=document.createElement("td");i.style.padding="2px 4px",i.textContent=o,t.appendChild(r),t.appendChild(i),a.appendChild(t),n.set(l,t);}}function $e(n,a){let l=n.get(a);l&&(l.remove(),n.delete(a));}function ue(n,a,l){if(n.inflightList.replaceChildren(),n.inflightCount.textContent=String(a.length),a.length>0)for(let c of a){let s=document.createElement("li");s.style.fontSize="11px",s.textContent=`${c.resolverId} (${c.id})`,n.inflightList.appendChild(s);}else {let c=document.createElement("li");c.style.fontSize="10px",c.style.color=g.muted,c.textContent="None",n.inflightList.appendChild(c);}if(n.unmetList.replaceChildren(),n.unmetCount.textContent=String(l.length),l.length>0)for(let c of l){let s=document.createElement("li");s.style.fontSize="11px",s.textContent=`${c.requirement.type} from ${c.fromConstraint}`,n.unmetList.appendChild(s);}else {let c=document.createElement("li");c.style.fontSize="10px",c.style.color=g.muted,c.textContent="None",n.unmetList.appendChild(c);}}function de(n,a,l){let c=a===0&&l===0;n.statusEl.style.color=c?g.green:g.yellow,n.statusEl.textContent=c?"Settled":"Working...",n.toggleBtn.textContent=c?"Directive":"Directive...",n.toggleBtn.setAttribute("aria-label",`Open Directive DevTools${c?"":" (system working)"}`);}function be(n,a,l,c){let s=Object.keys(l.derive);if(n.derivCount.textContent=String(s.length),s.length===0){a.clear(),n.derivBody.replaceChildren();let o=document.createElement("tr"),t=document.createElement("td");t.colSpan=2,t.style.color=g.muted,t.style.fontSize="10px",t.textContent="No derivations defined",o.appendChild(t),n.derivBody.appendChild(o);return}let f=new Set(s);for(let[o,t]of a)f.has(o)||(t.remove(),a.delete(o));for(let o of s){let t;try{t=pe(l.read(o));}catch{t="<error>";}se(a,n.derivBody,o,t,true,c);}}function He(n,a,l,c){let s=n.eventsList.querySelector(".dt-events-empty");s&&s.remove();let f=document.createElement("div");Object.assign(f.style,{padding:"2px 4px",borderBottom:`1px solid ${g.rowBorder}`,fontFamily:"inherit"});let o=new Date,t=`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}:${String(o.getSeconds()).padStart(2,"0")}.${String(o.getMilliseconds()).padStart(3,"0")}`,r;try{let T=JSON.stringify(l);r=K(T,60);}catch{r="{}";}let i=document.createElement("span");i.style.color=g.closeBtn,i.textContent=t;let p=document.createElement("span");p.style.color=g.accent,p.textContent=` ${a} `;let h=document.createElement("span");for(h.style.color=g.muted,h.textContent=r,f.appendChild(i),f.appendChild(p),f.appendChild(h),n.eventsList.prepend(f);n.eventsList.childElementCount>Ne;)n.eventsList.lastElementChild?.remove();n.eventsCount.textContent=String(c);}function je(n,a){n.perfBody.replaceChildren();let l=a.reconcileCount>0?(a.reconcileTotalMs/a.reconcileCount).toFixed(1):"\u2014",c=[`Reconciles: ${a.reconcileCount} (avg ${l}ms)`,`Effects: ${a.effectRunCount} run, ${a.effectErrorCount} errors`];for(let s of c){let f=document.createElement("div");f.style.marginBottom="2px",f.textContent=s,n.perfBody.appendChild(f);}if(a.resolverStats.size>0){let s=document.createElement("div");s.style.marginTop="4px",s.style.marginBottom="2px",s.style.color=g.accent,s.textContent="Resolvers:",n.perfBody.appendChild(s);let f=[...a.resolverStats.entries()].sort((o,t)=>t[1].totalMs-o[1].totalMs);for(let[o,t]of f){let r=t.count>0?(t.totalMs/t.count).toFixed(1):"0",i=document.createElement("div");i.style.paddingLeft="8px",i.textContent=`${o}: ${t.count}x, avg ${r}ms${t.errors>0?`, ${t.errors} err`:""}`,t.errors>0&&(i.style.color=g.red),n.perfBody.appendChild(i);}}}function ye(n,a){let l=a.history;if(!l){n.historySection.style.display="none";return}n.historySection.style.display="flex";let c=l.currentIndex,s=l.snapshots.length;n.historyLabel.textContent=s>0?`${c+1} / ${s}`:"0 snapshots";let f=c>0,o=c<s-1;n.undoBtn.disabled=!f,n.undoBtn.style.opacity=f?"1":"0.4",n.redoBtn.disabled=!o,n.redoBtn.style.opacity=o?"1":"0.4";}function Fe(n,a){n.undoBtn.addEventListener("click",()=>{a.history&&a.history.currentIndex>0&&a.history.goBack(1);}),n.redoBtn.addEventListener("click",()=>{a.history&&a.history.currentIndex<a.history.snapshots.length-1&&a.history.goForward(1);});}var he=new WeakMap;function Ke(n,a,l,c,s,f){return [n.join(","),a.join(","),l.map(o=>`${o.id}:${o.active}`).join(","),[...c.entries()].map(([o,t])=>`${o}:${t.status}:${t.type}`).join(","),s.join(","),f.join(",")].join("|")}function Je(n,a,l,c,s){for(let f of l){let o=n.nodes.get(`0:${f}`);if(!o)continue;let t=a.recentlyChangedFacts.has(f);o.rect.setAttribute("fill",t?g.text+"33":"none"),o.rect.setAttribute("stroke-width",t?"2":"1");}for(let f of c){let o=n.nodes.get(`1:${f}`);if(!o)continue;let t=a.recentlyComputedDerivations.has(f);o.rect.setAttribute("fill",t?g.accent+"33":"none"),o.rect.setAttribute("stroke-width",t?"2":"1");}for(let f of s){let o=n.nodes.get(`2:${f}`);if(!o)continue;let t=a.recentlyActiveConstraints.has(f),r=o.rect.getAttribute("stroke")??g.muted;o.rect.setAttribute("fill",t?r+"33":"none"),o.rect.setAttribute("stroke-width",t?"2":"1");}}function Se(n,a,l){let c=te(a);if(!c)return;let s;try{s=Object.keys(a.facts.$store.toObject());}catch{s=[];}let f=Object.keys(a.derive),o=c.constraints,t=c.unmet,r=c.inflight,i=Object.keys(c.resolvers),p=new Map;for(let m of t)p.set(m.id,{type:m.requirement.type,fromConstraint:m.fromConstraint,status:"unmet"});for(let m of r)p.set(m.id,{type:m.resolverId,fromConstraint:"",status:"inflight"});if(s.length===0&&f.length===0&&o.length===0&&i.length===0){he.delete(n.flowSvg),n.flowSvg.replaceChildren(),n.flowSvg.setAttribute("viewBox","0 0 460 40");let m=document.createElementNS("http://www.w3.org/2000/svg","text");m.setAttribute("x","230"),m.setAttribute("y","24"),m.setAttribute("text-anchor","middle"),m.setAttribute("fill",g.muted),m.setAttribute("font-size","10"),m.setAttribute("font-family",g.font),m.textContent="No system topology",n.flowSvg.appendChild(m);return}let h=r.map(m=>m.resolverId).sort(),T=Ke(s,f,o,p,i,h),D=he.get(n.flowSvg);if(D&&D.fingerprint===T){Je(D,l,s,f,o.map(m=>m.id));return}let S=_.nodeW+_.colGap,E=[5,5+S,5+S*2,5+S*3,5+S*4],d=E[4]+_.nodeW+5;function v(m){let b=_.startY+12;return m.map(y=>{let e={...y,y:b};return b+=_.nodeH+_.nodeGap,e})}let M=v(s.map(m=>({id:m,label:K(m,_.labelMaxChars)}))),C=v(f.map(m=>({id:m,label:K(m,_.labelMaxChars)}))),L=v(o.map(m=>({id:m.id,label:K(m.id,_.labelMaxChars),active:m.active,priority:m.priority}))),I=v([...p.entries()].map(([m,b])=>({id:m,type:b.type,fromConstraint:b.fromConstraint,status:b.status}))),O=v(i.map(m=>({id:m,label:K(m,_.labelMaxChars)}))),F=Math.max(M.length,C.length,L.length,I.length,O.length,1),A=_.startY+12+F*(_.nodeH+_.nodeGap)+8;n.flowSvg.replaceChildren(),n.flowSvg.setAttribute("viewBox",`0 0 ${d} ${A}`),n.flowSvg.setAttribute("aria-label",`Dependency graph: ${s.length} facts, ${f.length} derivations, ${o.length} constraints, ${p.size} requirements, ${i.length} resolvers`);let P=["Facts","Derivations","Constraints","Reqs","Resolvers"];for(let[m,b]of P.entries()){let y=document.createElementNS("http://www.w3.org/2000/svg","text");y.setAttribute("x",String(E[m]??0)),y.setAttribute("y","10"),y.setAttribute("fill",g.accent),y.setAttribute("font-size",String(_.fontSize)),y.setAttribute("font-family",g.font),y.textContent=b,n.flowSvg.appendChild(y);}let R={fingerprint:T,nodes:new Map};function k(m,b,y,e,u,x,w,H){let B=document.createElementNS("http://www.w3.org/2000/svg","g"),V=document.createElementNS("http://www.w3.org/2000/svg","rect");V.setAttribute("x",String(b)),V.setAttribute("y",String(y-6)),V.setAttribute("width",String(_.nodeW)),V.setAttribute("height",String(_.nodeH)),V.setAttribute("rx","3"),V.setAttribute("fill",H?x+"33":"none"),V.setAttribute("stroke",x),V.setAttribute("stroke-width",H?"2":"1"),V.setAttribute("opacity",w?"0.35":"1"),B.appendChild(V);let W=document.createElementNS("http://www.w3.org/2000/svg","text");return W.setAttribute("x",String(b+4)),W.setAttribute("y",String(y+4)),W.setAttribute("fill",x),W.setAttribute("font-size",String(_.fontSize)),W.setAttribute("font-family",g.font),W.setAttribute("opacity",w?"0.35":"1"),W.textContent=u,B.appendChild(W),n.flowSvg.appendChild(B),R.nodes.set(`${m}:${e}`,{g:B,rect:V,text:W}),{midX:b+_.nodeW/2,midY:y}}function q(m,b,y,e,u,x){let w=document.createElementNS("http://www.w3.org/2000/svg","line");w.setAttribute("x1",String(m)),w.setAttribute("y1",String(b)),w.setAttribute("x2",String(y)),w.setAttribute("y2",String(e)),w.setAttribute("stroke",u),w.setAttribute("stroke-width","1"),w.setAttribute("stroke-dasharray","3,2"),w.setAttribute("opacity","0.7"),n.flowSvg.appendChild(w);}let j=new Map,U=new Map,G=new Map,N=new Map;for(let m of M){let b=l.recentlyChangedFacts.has(m.id),y=k(0,E[0],m.y,m.id,m.label,g.text,false,b);j.set(m.id,y);}for(let m of C){let b=l.recentlyComputedDerivations.has(m.id),y=k(1,E[1],m.y,m.id,m.label,g.accent,false,b);U.set(m.id,y);}for(let m of L){let b=l.recentlyActiveConstraints.has(m.id),y=k(2,E[2],m.y,m.id,m.label,m.active?g.yellow:g.muted,!m.active,b);G.set(m.id,y);}for(let m of I){let b=m.status==="unmet"?g.red:g.yellow,y=k(3,E[3],m.y,m.id,K(m.type,_.labelMaxChars),b,false,false);N.set(m.id,y);}for(let m of O){let b=r.some(y=>y.resolverId===m.id);k(4,E[4],m.y,m.id,m.label,b?g.green:g.muted,!b,false);}for(let m of C){let b=l.derivationDeps.get(m.id),y=U.get(m.id);if(b&&y)for(let e of b){let u=j.get(e);u&&q(u.midX+_.nodeW/2,u.midY,y.midX-_.nodeW/2,y.midY,g.accent);}}for(let m of I){let b=G.get(m.fromConstraint),y=N.get(m.id);b&&y&&q(b.midX+_.nodeW/2,b.midY,y.midX-_.nodeW/2,y.midY,g.muted);}for(let m of r){let b=N.get(m.id);if(b){let y=O.find(e=>e.id===m.resolverId);y&&q(b.midX+_.nodeW/2,b.midY,E[4],y.y,g.green);}}he.set(n.flowSvg,R);}function qe(n){n.animationTimer&&clearTimeout(n.animationTimer),n.animationTimer=setTimeout(()=>{n.recentlyChangedFacts.clear(),n.recentlyComputedDerivations.clear(),n.recentlyActiveConstraints.clear(),n.animationTimer=null;},600);}function Ve(n,a){let l=a.entries.toArray();if(l.length===0)return;n.timelineSvg.replaceChildren();let c=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let S of l)S.startMs<c&&(c=S.startMs),S.endMs>s&&(s=S.endMs);let f=performance.now();for(let S of a.inflight.values())S<c&&(c=S),f>s&&(s=f);let o=s-c||1,t=ne-oe-10,r=[],i=new Set;for(let S of l)i.has(S.resolver)||(i.add(S.resolver),r.push(S.resolver));for(let S of a.inflight.keys())i.has(S)||(i.add(S),r.push(S));let h=r.slice(-12),T=re*h.length+20;n.timelineSvg.setAttribute("viewBox",`0 0 ${ne} ${T}`),n.timelineSvg.setAttribute("height",String(Math.min(T,200)));let D=5;for(let S=0;S<=D;S++){let E=oe+t*S/D,d=o*S/D,v=document.createElementNS("http://www.w3.org/2000/svg","text");v.setAttribute("x",String(E)),v.setAttribute("y","8"),v.setAttribute("fill",g.muted),v.setAttribute("font-size","6"),v.setAttribute("font-family",g.font),v.setAttribute("text-anchor","middle"),v.textContent=d<1e3?`${d.toFixed(0)}ms`:`${(d/1e3).toFixed(1)}s`,n.timelineSvg.appendChild(v);let M=document.createElementNS("http://www.w3.org/2000/svg","line");M.setAttribute("x1",String(E)),M.setAttribute("y1","10"),M.setAttribute("x2",String(E)),M.setAttribute("y2",String(T)),M.setAttribute("stroke",g.border),M.setAttribute("stroke-width","0.5"),n.timelineSvg.appendChild(M);}for(let S=0;S<h.length;S++){let E=h[S],d=12+S*re,v=S%ge.length,M=ge[v],C=document.createElementNS("http://www.w3.org/2000/svg","text");C.setAttribute("x",String(oe-4)),C.setAttribute("y",String(d+re/2+3)),C.setAttribute("fill",g.muted),C.setAttribute("font-size","7"),C.setAttribute("font-family",g.font),C.setAttribute("text-anchor","end"),C.textContent=K(E,12),n.timelineSvg.appendChild(C);let L=l.filter(O=>O.resolver===E);for(let O of L){let F=oe+(O.startMs-c)/o*t,A=Math.max((O.endMs-O.startMs)/o*t,fe),P=document.createElementNS("http://www.w3.org/2000/svg","rect");P.setAttribute("x",String(F)),P.setAttribute("y",String(d+2)),P.setAttribute("width",String(A)),P.setAttribute("height",String(re-4)),P.setAttribute("rx","2"),P.setAttribute("fill",O.error?g.red:M),P.setAttribute("opacity","0.8");let R=document.createElementNS("http://www.w3.org/2000/svg","title"),k=O.endMs-O.startMs;R.textContent=`${E}: ${k.toFixed(1)}ms${O.error?" (error)":""}`,P.appendChild(R),n.timelineSvg.appendChild(P);}let I=a.inflight.get(E);if(I!==void 0){let O=oe+(I-c)/o*t,F=Math.max((f-I)/o*t,fe),A=document.createElementNS("http://www.w3.org/2000/svg","rect");A.setAttribute("x",String(O)),A.setAttribute("y",String(d+2)),A.setAttribute("width",String(F)),A.setAttribute("height",String(re-4)),A.setAttribute("rx","2"),A.setAttribute("fill",M),A.setAttribute("opacity","0.4"),A.setAttribute("stroke",M),A.setAttribute("stroke-width","1"),A.setAttribute("stroke-dasharray","3,2");let P=document.createElementNS("http://www.w3.org/2000/svg","title");P.textContent=`${E}: inflight ${(f-I).toFixed(0)}ms`,A.appendChild(P),n.timelineSvg.appendChild(A);}}n.timelineSvg.setAttribute("aria-label",`Timeline: ${l.length} resolver executions across ${h.length} resolvers`);}function Qe(){if(typeof window>"u")return {systems:new Map,getSystem:()=>null,getSystems:()=>[],inspect:()=>null,getEvents:()=>[],explain:()=>null,exportSession:()=>null,importSession:()=>false,clearEvents:()=>{},subscribe:()=>()=>{}};if(!window.__DIRECTIVE__){let n=new Map,a={systems:n,getSystem(l){return l?n.get(l)?.system??null:n.values().next().value?.system??null},getSystems(){return [...n.keys()]},inspect(l){let c=this.getSystem(l),s=l?n.get(l):n.values().next().value,f=c?.inspect()??null;return f&&s&&(f.resolverStats=s.resolverStats?Object.fromEntries(s.resolverStats):{}),f},getEvents(l){return l?n.get(l)?.events.toArray()??[]:n.values().next().value?.events.toArray()??[]},explain(l,c){return this.getSystem(c)?.explain(l)??null},subscribe(l,c){let s=c?n.get(c):n.values().next().value;if(!s){let f=false,t=setInterval(()=>{let i=c?n.get(c):n.values().next().value;i&&!f&&(f=true,i.subscribers.add(l));},100),r=setTimeout(()=>clearInterval(t),1e4);return ()=>{clearInterval(t),clearTimeout(r);for(let i of n.values())i.subscribers.delete(l);}}return s.subscribers.add(l),()=>{s.subscribers.delete(l);}},exportSession(l){let c=l?n.get(l):n.values().next().value;return c?JSON.stringify({version:1,name:l??n.keys().next().value??"default",exportedAt:Date.now(),events:c.events.toArray()}):null},importSession(l,c){try{if(l.length>10*1024*1024)return !1;let s=JSON.parse(l);if(!s||typeof s!="object"||Array.isArray(s)||!Array.isArray(s.events))return !1;let f=c?n.get(c):n.values().next().value;if(!f)return !1;let o=f.maxEvents,t=s.events,r=t.length>o?t.length-o:0;f.events.clear();for(let i=r;i<t.length;i++){let p=t[i];p&&typeof p=="object"&&!Array.isArray(p)&&typeof p.timestamp=="number"&&typeof p.type=="string"&&p.type!=="__proto__"&&p.type!=="constructor"&&p.type!=="prototype"&&f.events.push({timestamp:p.timestamp,type:p.type,data:p.data??null});}return !0}catch{return false}},clearEvents(l){let c=l?n.get(l):n.values().next().value;c&&c.events.clear();}};return Object.defineProperty(window,"__DIRECTIVE__",{value:a,writable:false,configurable:le(),enumerable:true}),a}return window.__DIRECTIVE__}function Ze(n={}){let{name:a="default",trace:l=false,maxEvents:c,panel:s=false,position:f="bottom-right",defaultOpen:o=false}=n,t=Ae(c),r=Qe(),i={system:null,events:new ie(t),maxEvents:t,subscribers:new Set,resolverStats:new Map};r.systems.set(a,i);let p=(e,u)=>{let x={timestamp:Date.now(),type:e,data:u};l&&i.events.push(x);for(let w of i.subscribers)try{w(x);}catch{}},h=null,T=new Map,D=new Map,S=Oe(),E=ke(),d=Ie(),v=Le(),M=s&&typeof window<"u"&&typeof document<"u"&&le(),C=null,L=0,I=1,O=2,F=4,A=8,P=16,R=32,k=64,q=128,j=new Map,U=new Set,G=null;function N(e){L|=e,C===null&&typeof requestAnimationFrame<"u"&&(C=requestAnimationFrame(m));}function m(){if(C=null,!h||!i.system){L=0;return}let e=h.refs,u=i.system,x=L;if(L=0,x&I){for(let w of U)$e(T,w);U.clear();for(let[w,{value:H,flash:B}]of j)se(T,e.factsBody,w,H,B,h.flashTimers);j.clear(),e.factsCount.textContent=String(T.size);}if(x&O&&be(e,D,u,h.flashTimers),x&A)if(G)de(e,G.inflight.length,G.unmet.length);else {let w=te(u);w&&de(e,w.inflight.length,w.unmet.length);}if(x&F)if(G)ue(e,G.inflight,G.unmet);else {let w=te(u);w&&ue(e,w.inflight,w.unmet);}x&P&&je(e,S),x&R&&Se(e,u,E),x&k&&ye(e,u),x&q&&Ve(e,v);}function b(e,u){h&&l&&He(h.refs,e,u,i.events.size);}function y(e,u){d.isRecording&&d.recordedEvents.length<Pe&&d.recordedEvents.push({timestamp:Date.now(),type:e,data:De(u)});}return {name:"devtools",onInit:e=>{if(i.system=e,p("init",{}),typeof window<"u"&&console.log(`%c[Directive Devtools]%c System "${a}" initialized. Access via window.__DIRECTIVE__`,"color: #7c3aed; font-weight: bold","color: inherit"),M){let u=i.system;h=Be(a,f,o,l);let x=h.refs;try{let H=u.facts.$store.toObject();for(let[B,V]of Object.entries(H))se(T,x.factsBody,B,V,!1);x.factsCount.textContent=String(Object.keys(H).length);}catch{}be(x,D,u);let w=te(u);w&&(de(x,w.inflight.length,w.unmet.length),ue(x,w.inflight,w.unmet)),ye(x,u),Fe(x,u),Se(x,u,E),x.recordBtn.addEventListener("click",()=>{if(d.isRecording=!d.isRecording,x.recordBtn.textContent=d.isRecording?"\u23F9 Stop":"\u23FA Record",x.recordBtn.style.color=d.isRecording?g.red:g.text,d.isRecording){d.recordedEvents=[],d.snapshots=[];try{d.snapshots.push({timestamp:Date.now(),facts:u.facts.$store.toObject()});}catch{}}}),x.exportBtn.addEventListener("click",()=>{let H=d.recordedEvents.length>0?d.recordedEvents:i.events.toArray(),B=JSON.stringify({version:1,name:a,exportedAt:Date.now(),events:H,snapshots:d.snapshots},null,2),V=new Blob([B],{type:"application/json"}),W=URL.createObjectURL(V),J=document.createElement("a");J.href=W,J.download=`directive-session-${a}-${Date.now()}.json`,J.click(),URL.revokeObjectURL(W);});}},onStart:e=>{p("start",{}),b("start",{}),y("start",{});},onStop:e=>{p("stop",{}),b("stop",{}),y("stop",{});},onDestroy:e=>{p("destroy",{}),r.systems.delete(a),C!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(C),C=null),E.animationTimer&&clearTimeout(E.animationTimer),h&&(h.destroy(),h=null,T.clear(),D.clear());},onFactSet:(e,u,x)=>{p("fact.set",{key:e,value:u,prev:x}),y("fact.set",{key:e,value:u,prev:x}),E.recentlyChangedFacts.add(e),h&&i.system&&(j.set(e,{value:u,flash:true}),U.delete(e),N(I),b("fact.set",{key:e,value:u}));},onFactDelete:(e,u)=>{p("fact.delete",{key:e,prev:u}),y("fact.delete",{key:e,prev:u}),h&&(U.add(e),j.delete(e),N(I),b("fact.delete",{key:e}));},onFactsBatch:e=>{if(p("facts.batch",{changes:e}),y("facts.batch",{count:e.length}),h&&i.system){for(let u of e)u.type==="delete"?(U.add(u.key),j.delete(u.key)):(E.recentlyChangedFacts.add(u.key),j.set(u.key,{value:u.value,flash:true}),U.delete(u.key));N(I),b("facts.batch",{count:e.length});}},onDerivationCompute:(e,u,x)=>{p("derivation.compute",{id:e,value:u,deps:x}),y("derivation.compute",{id:e,deps:x}),E.derivationDeps.set(e,x),E.recentlyComputedDerivations.add(e),b("derivation.compute",{id:e,deps:x});},onDerivationInvalidate:e=>{p("derivation.invalidate",{id:e}),b("derivation.invalidate",{id:e});},onReconcileStart:e=>{p("reconcile.start",{}),S.lastReconcileStartMs=performance.now(),b("reconcile.start",{}),y("reconcile.start",{});},onReconcileEnd:e=>{if(p("reconcile.end",e),y("reconcile.end",{unmet:e.unmet.length,inflight:e.inflight.length,completed:e.completed.length}),S.lastReconcileStartMs>0){let u=performance.now()-S.lastReconcileStartMs;S.reconcileCount++,S.reconcileTotalMs+=u,S.lastReconcileStartMs=0;}if(d.isRecording&&i.system&&d.snapshots.length<_e)try{d.snapshots.push({timestamp:Date.now(),facts:i.system.facts.$store.toObject()});}catch{}h&&i.system&&(G=e,qe(E),N(O|A|F|P|R|k),b("reconcile.end",{unmet:e.unmet.length,inflight:e.inflight.length}));},onConstraintEvaluate:(e,u)=>{p("constraint.evaluate",{id:e,active:u}),y("constraint.evaluate",{id:e,active:u}),u?(E.activeConstraints.add(e),E.recentlyActiveConstraints.add(e)):E.activeConstraints.delete(e),b("constraint.evaluate",{id:e,active:u});},onConstraintError:(e,u)=>{p("constraint.error",{id:e,error:String(u)}),b("constraint.error",{id:e,error:String(u)});},onRequirementCreated:e=>{p("requirement.created",{id:e.id,type:e.requirement.type}),y("requirement.created",{id:e.id,type:e.requirement.type}),b("requirement.created",{id:e.id,type:e.requirement.type});},onRequirementMet:(e,u)=>{p("requirement.met",{id:e.id,byResolver:u}),y("requirement.met",{id:e.id,byResolver:u}),b("requirement.met",{id:e.id,byResolver:u});},onRequirementCanceled:e=>{p("requirement.canceled",{id:e.id}),y("requirement.canceled",{id:e.id}),b("requirement.canceled",{id:e.id});},onResolverStart:(e,u)=>{p("resolver.start",{resolver:e,requirementId:u.id}),y("resolver.start",{resolver:e,requirementId:u.id}),v.inflight.set(e,performance.now()),h&&i.system&&(N(F|A|q),b("resolver.start",{resolver:e,requirementId:u.id}));},onResolverComplete:(e,u,x)=>{p("resolver.complete",{resolver:e,requirementId:u.id,duration:x}),y("resolver.complete",{resolver:e,requirementId:u.id,duration:x});let w=i.resolverStats.get(e)??{count:0,totalMs:0,errors:0};if(w.count++,w.totalMs+=x,i.resolverStats.set(e,w),i.resolverStats.size>ve){let B=i.resolverStats.keys().next().value;B!==void 0&&i.resolverStats.delete(B);}S.resolverStats.set(e,{...w});let H=v.inflight.get(e);v.inflight.delete(e),H!==void 0&&v.entries.push({resolver:e,startMs:H,endMs:performance.now(),error:false}),h&&i.system&&(N(F|A|P|q),b("resolver.complete",{resolver:e,duration:x}));},onResolverError:(e,u,x)=>{p("resolver.error",{resolver:e,requirementId:u.id,error:String(x)}),y("resolver.error",{resolver:e,requirementId:u.id,error:String(x)});let w=i.resolverStats.get(e)??{count:0,totalMs:0,errors:0};if(w.errors++,i.resolverStats.set(e,w),i.resolverStats.size>ve){let B=i.resolverStats.keys().next().value;B!==void 0&&i.resolverStats.delete(B);}S.resolverStats.set(e,{...w});let H=v.inflight.get(e);v.inflight.delete(e),H!==void 0&&v.entries.push({resolver:e,startMs:H,endMs:performance.now(),error:true}),h&&i.system&&(N(F|A|P|q),b("resolver.error",{resolver:e,error:String(x)}));},onResolverRetry:(e,u,x)=>{p("resolver.retry",{resolver:e,requirementId:u.id,attempt:x}),y("resolver.retry",{resolver:e,requirementId:u.id,attempt:x}),b("resolver.retry",{resolver:e,attempt:x});},onResolverCancel:(e,u)=>{p("resolver.cancel",{resolver:e,requirementId:u.id}),y("resolver.cancel",{resolver:e,requirementId:u.id}),v.inflight.delete(e),b("resolver.cancel",{resolver:e});},onEffectRun:e=>{p("effect.run",{id:e}),y("effect.run",{id:e}),S.effectRunCount++,b("effect.run",{id:e});},onEffectError:(e,u)=>{p("effect.error",{id:e,error:String(u)}),S.effectErrorCount++,b("effect.error",{id:e,error:String(u)});},onSnapshot:e=>{p("timetravel.snapshot",{id:e.id,trigger:e.trigger}),h&&i.system&&N(k),b("timetravel.snapshot",{id:e.id,trigger:e.trigger});},onHistoryNavigate:(e,u)=>{if(p("timetravel.jump",{from:e,to:u}),y("timetravel.jump",{from:e,to:u}),h&&i.system){let x=i.system;try{let w=x.facts.$store.toObject();T.clear(),h.refs.factsBody.replaceChildren();for(let[H,B]of Object.entries(w))se(T,h.refs.factsBody,H,B,!1);h.refs.factsCount.textContent=String(Object.keys(w).length);}catch{}D.clear(),E.derivationDeps.clear(),h.refs.derivBody.replaceChildren(),G=null,N(O|A|F|R|k),b("timetravel.jump",{from:e,to:u});}},onError:e=>{p("error",{source:e.source,sourceId:e.sourceId,message:e.message}),y("error",{source:e.source,message:e.message}),b("error",{source:e.source,message:e.message});},onErrorRecovery:(e,u)=>{p("error.recovery",{source:e.source,sourceId:e.sourceId,strategy:u}),b("error.recovery",{source:e.source,strategy:u});},onTraceComplete:e=>{p("trace.complete",{id:e.id,status:e.status,facts:e.factChanges.length,constraints:e.constraintsHit.length,requirements:e.requirementsAdded.length,resolvers:e.resolversStarted.length,effects:e.effectsRun.length}),b("trace.complete",{id:e.id});},onDefinitionRegister:(e,u)=>{p("definition.register",{type:e,id:u}),y("definition.register",{type:e,id:u}),b("definition.register",{type:e,id:u});},onDefinitionAssign:(e,u)=>{p("definition.assign",{type:e,id:u}),y("definition.assign",{type:e,id:u}),b("definition.assign",{type:e,id:u});},onDefinitionUnregister:(e,u)=>{p("definition.unregister",{type:e,id:u}),y("definition.unregister",{type:e,id:u}),b("definition.unregister",{type:e,id:u});},onDefinitionCall:(e,u,x)=>{p("definition.call",{type:e,id:u,props:x}),y("definition.call",{type:e,id:u,props:x}),b("definition.call",{type:e,id:u,props:x});}}}var We="directive-devtools-event",ze=new Set(["__proto__","constructor","prototype"]),et=Math.random().toString(36).slice(2,8);function tt(){if(typeof window<"u"){let n=`__DIRECTIVE_BRIDGE_ID_${et}__`,a=window,l=a[n]??0;return a[n]=l+1,l+1}return 1}function nt(n){let a=false;for(let c of ze)if(c in n){a=true;break}if(!a)return n;let l=Object.create(null);for(let[c,s]of Object.entries(n))ze.has(c)||(l[c]=s);return l}function rt(n){if(!(typeof window>"u"))try{let a=nt(n),l={id:tt(),timestamp:Date.now(),snapshotId:null,...a};window.dispatchEvent(new CustomEvent(We,{detail:l}));}catch{}}function ot(n){let{storage:a,key:l,include:c$1,exclude:s=[],debounce:f=100,onRestore:o,onSave:t,onError:r}=n,i=null,p=null,h=new Set,T=d=>s.includes(d)?false:c$1?c$1.includes(d):true,D=()=>{try{let d=a.getItem(l);if(!d)return null;let v=JSON.parse(d);return typeof v!="object"||v===null?null:c(v)?v:(r?.(new Error("Potential prototype pollution detected in stored data")),null)}catch(d){return r?.(d instanceof Error?d:new Error(String(d))),null}},S=()=>{if(p)try{let d={};for(let v of h)T(v)&&(d[v]=p.facts[v]);a.setItem(l,JSON.stringify(d)),t?.(d);}catch(d){r?.(d instanceof Error?d:new Error(String(d)));}},E=()=>{i&&clearTimeout(i),i=setTimeout(S,f);};return {name:"persistence",onInit:d=>{p=d;let v=D();v&&(p.facts.$store.batch(()=>{for(let[M,C]of Object.entries(v))T(M)&&(p.facts[M]=C,h.add(M));}),o?.(v));},onDestroy:()=>{i&&clearTimeout(i),S();},onFactSet:d=>{h.add(d),T(d)&&E();},onFactDelete:d=>{h.delete(d),T(d)&&E();},onFactsBatch:d=>{let v=false;for(let M of d)M.type==="set"?h.add(M.key):h.delete(M.key),T(M.key)&&(v=true);v&&E();}}}function it(n={}){let{onSlowConstraint:a,onSlowResolver:l,slowConstraintThresholdMs:c=16,slowResolverThresholdMs:s=1e3}=n,f=new Map,o=new Map,t=new Map,r={runs:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0},i=0,p=0,h=0;function T(d){let v=f.get(d);return v||(v={evaluations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastEvaluatedAt:0},f.set(d,v)),v}function D(d){let v=o.get(d);return v||(v={starts:0,completions:0,errors:0,retries:0,cancellations:0,totalDurationMs:0,avgDurationMs:0,maxDurationMs:0,lastCompletedAt:0},o.set(d,v)),v}function S(d){let v=t.get(d);return v||(v={runs:0,errors:0,lastRunAt:0},t.set(d,v)),v}let E={name:"performance",onStart(){i=Date.now();},onConstraintEvaluate(d,v){let M=performance.now(),C=T(d);if(C.evaluations++,C.lastEvaluatedAt=Date.now(),h>0){let L=M-h;C.totalDurationMs+=L;let I=C.evaluations;C.avgDurationMs=C.totalDurationMs/I,L>C.maxDurationMs&&(C.maxDurationMs=L),L>c&&a?.(d,L);}h=M;},onResolverStart(d,v){let M=D(d);M.starts++;},onResolverComplete(d,v,M){let C=D(d);C.completions++,C.totalDurationMs+=M,C.avgDurationMs=C.totalDurationMs/C.completions,M>C.maxDurationMs&&(C.maxDurationMs=M),C.lastCompletedAt=Date.now(),M>s&&l?.(d,M);},onResolverError(d,v,M){D(d).errors++;},onResolverRetry(d,v,M){D(d).retries++;},onResolverCancel(d,v){D(d).cancellations++;},onEffectRun(d){let v=S(d);v.runs++,v.lastRunAt=Date.now();},onEffectError(d,v){S(d).errors++;},onReconcileStart(){p=performance.now(),h=0;},onReconcileEnd(){let d=performance.now()-p;r.runs++,r.totalDurationMs+=d,r.avgDurationMs=r.totalDurationMs/r.runs,d>r.maxDurationMs&&(r.maxDurationMs=d);},onDestroy(){E.reset();},getSnapshot(){let d={};for(let[C,L]of f)d[C]={...L};let v={};for(let[C,L]of o)v[C]={...L};let M={};for(let[C,L]of t)M[C]={...L};return {constraints:d,resolvers:v,effects:M,reconcile:{...r},uptime:i?Date.now()-i:0}},reset(){f.clear(),o.clear(),t.clear(),r.runs=0,r.totalDurationMs=0,r.avgDurationMs=0,r.maxDurationMs=0,h=0;}};return E}function st(n){let a=[{key:"service.name",value:{stringValue:n.serviceName??"directive-agents"}}];if(n.serviceVersion&&a.push({key:"service.version",value:{stringValue:n.serviceVersion}}),n.resourceAttributes)for(let[l,c]of Object.entries(n.resourceAttributes))a.push({key:l,value:{stringValue:c}});return {attributes:a}}function Z(n){return `${BigInt(n)*BigInt(1e6)}`}function at(n){switch(n){case "counter":return "sum";case "gauge":return "gauge";case "histogram":return "histogram";default:return "gauge"}}function ct(n,a,l){let c=n.map(s=>{let f=s.lastUpdated-6e4,o=[{asInt:s.type==="counter"?s.sum:void 0,asDouble:s.type!=="counter"?s.lastValue:void 0,timeUnixNano:Z(s.lastUpdated),startTimeUnixNano:Z(f),attributes:[]}],t=at(s.type),r={name:s.name,unit:""};return t==="sum"?r.sum={dataPoints:o,aggregationTemporality:2,isMonotonic:true}:t==="histogram"?r.histogram={dataPoints:[{count:s.count,sum:s.sum,min:s.min,max:s.max,timeUnixNano:Z(s.lastUpdated),startTimeUnixNano:Z(f),attributes:[]}],aggregationTemporality:2}:r.gauge={dataPoints:o},r});return {resourceMetrics:[{resource:a,scopeMetrics:[{scope:{name:"directive",version:l},metrics:c}]}]}}function lt(n,a,l){let c=n.map(s=>{let f=s.logs.map(r=>({timeUnixNano:Z(r.timestamp),name:r.level,attributes:[{key:"message",value:{stringValue:r.message}},{key:"level",value:{stringValue:r.level}}]})),o=Object.entries(s.tags).map(([r,i])=>({key:r,value:typeof i=="string"?{stringValue:i}:typeof i=="number"?{intValue:`${i}`}:{boolValue:i}})),t=s.status==="ok"?1:s.status==="error"?2:0;return {traceId:s.traceId.replace(/-/g,"").padEnd(32,"0").slice(0,32),spanId:s.spanId.replace(/-/g,"").padEnd(16,"0").slice(0,16),parentSpanId:s.parentSpanId?s.parentSpanId.replace(/-/g,"").padEnd(16,"0").slice(0,16):void 0,name:s.operationName,kind:1,startTimeUnixNano:Z(s.startTime),endTimeUnixNano:s.endTime?Z(s.endTime):Z(s.startTime),attributes:o,events:f,status:{code:t}}});return {resourceSpans:[{resource:a,scopeSpans:[{scope:{name:"directive",version:l},spans:c}]}]}}function ut(n){let{endpoint:a,headers:l={},scopeVersion:c="0.1.0",timeoutMs:s=1e4,fetch:f=globalThis.fetch,onError:o}=n;try{let i=new URL(a);if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error("[Directive] Only http: and https: protocols are supported")}catch(i){throw new Error(`[Directive OTLP] Invalid endpoint URL "${a}": ${i instanceof Error?i.message:String(i)}`)}if(/\/v1\/(metrics|traces)/.test(a)&&console.warn(`[Directive OTLP] Endpoint "${a}" already contains a /v1/metrics or /v1/traces path. The exporter will append /v1/metrics or /v1/traces automatically. Use the base URL (e.g., "http://localhost:4318") instead.`),s<=0||!Number.isFinite(s))throw new Error(`[Directive OTLP] timeoutMs must be > 0, got ${s}`);let t=st(n);async function r(i,p,h){let T=`${a.replace(/\/$/,"")}${i}`,D=new AbortController,S=setTimeout(()=>D.abort(),s);try{let E=await f(T,{method:"POST",headers:{"Content-Type":"application/json",...l},body:JSON.stringify(p),signal:D.signal});if(!E.ok)throw new Error(`[Directive] OTLP export failed: ${E.status} ${E.statusText}`)}catch(E){let d=E instanceof Error?E:new Error(String(E));o?o(d,h):console.error(`[Directive OTLP] Export ${h} error:`,d.message);}finally{clearTimeout(S);}}return {async exportMetrics(i){if(i.length===0)return;let p=ct(i,t,c);await r("/v1/metrics",p,"metrics");},async exportTraces(i){if(i.length===0)return;let p=lt(i,t,c);await r("/v1/traces",p,"traces");}}}var ae=class extends Error{code="CIRCUIT_OPEN";retryAfterMs;state;constructor(a,l,c="OPEN",s){let f=s?`[Directive CircuitBreaker] Circuit "${a}" is ${c}. ${s}`:`[Directive CircuitBreaker] Circuit "${a}" is ${c}. Request rejected. Try again in ${Math.ceil(l/1e3)}s.`;super(f),this.name="CircuitBreakerOpenError",this.retryAfterMs=l,this.state=c;}};function dt(n={}){let{failureThreshold:a=5,recoveryTimeMs:l=3e4,halfOpenMaxRequests:c=3,failureWindowMs:s=6e4,observability:f,metricPrefix:o="circuit_breaker",name:t="default",isFailure:r=()=>true,onStateChange:i}=n;if(a<1||!Number.isFinite(a))throw new Error(`[Directive CircuitBreaker] failureThreshold must be >= 1, got ${a}`);if(l<=0||!Number.isFinite(l))throw new Error(`[Directive CircuitBreaker] recoveryTimeMs must be > 0, got ${l}`);if(c<1||!Number.isFinite(c))throw new Error(`[Directive CircuitBreaker] halfOpenMaxRequests must be >= 1, got ${c}`);if(s<=0||!Number.isFinite(s))throw new Error(`[Directive CircuitBreaker] failureWindowMs must be > 0, got ${s}`);let p="CLOSED",h=[],T=0,D=0,S=Date.now(),E=0,d=0,v=0,M=0,C=0,L=null,I=null;function O(R){if(p===R)return;let k=p;p=R,S=Date.now(),R==="OPEN"&&(E=Date.now()),R==="HALF_OPEN"&&(T=0,D=0),i?.(k,R),f&&f.incrementCounter(`${o}.state_change`,{name:t,from:k,to:R});}function F(){let R=Date.now()-s;return h=h.filter(k=>k>R),h.length}function A(){M++,I=Date.now(),f&&f.incrementCounter(`${o}.success`,{name:t}),p==="HALF_OPEN"&&(D++,D>=c&&(O("CLOSED"),h=[]));}function P(R){if(!r(R)){A();return}v++,L=Date.now(),h.push(Date.now());let k=a*2;if(h.length>k&&(h=h.slice(-k)),f&&f.incrementCounter(`${o}.failure`,{name:t}),p==="HALF_OPEN"){O("OPEN");return}p==="CLOSED"&&F()>=a&&O("OPEN");}return {async execute(R){if(d++,f&&f.incrementCounter(`${o}.requests`,{name:t}),p==="OPEN")if(Date.now()-E>=l)O("HALF_OPEN");else throw C++,f&&f.incrementCounter(`${o}.rejected`,{name:t}),new ae(t,l-(Date.now()-E));if(p==="HALF_OPEN"){if(T>=c)throw C++,new ae(t,l,"HALF_OPEN",`Max trial requests (${c}) reached.`);T++;}let k=Date.now();try{let q=await R();return A(),f&&f.observeHistogram(`${o}.latency`,Date.now()-k,{name:t}),q}catch(q){let j=q instanceof Error?q:new Error(String(q));throw P(j),f&&f.observeHistogram(`${o}.latency`,Date.now()-k,{name:t}),q}},getState(){return p==="OPEN"&&Date.now()-E>=l&&O("HALF_OPEN"),p},getStats(){return {state:this.getState(),totalRequests:d,totalFailures:v,totalSuccesses:M,totalRejected:C,recentFailures:F(),lastFailureTime:L,lastSuccessTime:I,lastStateChange:S}},forceState(R){O(R);},reset(){let R=p;p="CLOSED",h=[],T=0,D=0,S=Date.now(),E=0,d=0,v=0,M=0,C=0,L=null,I=null,R!=="CLOSED"&&i?.(R,"CLOSED");},isAllowed(){return p==="CLOSED"?true:p==="OPEN"?Date.now()-E>=l:T<c}}}
2
+ export{ae as CircuitBreakerOpenError,We as DEVTOOLS_EVENT_NAME,dt as createCircuitBreaker,ut as createOTLPExporter,Ze as devtoolsPlugin,rt as emitDevToolsEvent,Xe as loggingPlugin,it as performancePlugin,ot as persistencePlugin};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map