UNPKG

signalforge

Version:

Fine-grained reactive state management with automatic dependency tracking - Ultra-optimized, zero dependencies

52 lines (49 loc) 91.1 kB
"use strict";var Po=Object.create;var Ye=Object.defineProperty;var Co=Object.getOwnPropertyDescriptor;var wo=Object.getOwnPropertyNames;var Eo=Object.getPrototypeOf,Ro=Object.prototype.hasOwnProperty;var gn=(t,e)=>()=>(t&&(e=t(t=0)),e);var Lo=(t,e)=>{for(var n in e)Ye(t,n,{get:e[n],enumerable:!0})},pn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wo(e))!Ro.call(t,o)&&o!==n&&Ye(t,o,{get:()=>e[o],enumerable:!(r=Co(e,o))||r.enumerable});return t};var Mo=(t,e,n)=>(n=t!=null?Po(Eo(t)):{},pn(e||!t||!t.__esModule?Ye(n,"default",{value:t,enumerable:!0}):n,t)),ko=t=>pn(Ye({},"__esModule",{value:!0}),t);function _o(){return`signal_${++Do}_${Date.now()}`}function Ze(t){if(W.some(e=>e.name===t.name))throw new Error(`Plugin "${t.name}" is already registered`);if(W.push(t),t.onRegister)try{t.onRegister()}catch(e){console.error(`Error in plugin "${t.name}" onRegister:`,e)}`${t.name}`}function _e(t){let e=typeof t=="string"?t:t.name,n=W.findIndex(o=>o.name===e);if(n===-1)return!1;let r=W[n];if(r.onUnregister)try{r.onUnregister()}catch(o){console.error(`Error in plugin "${r.name}" onUnregister:`,o)}return W.splice(n,1),`${r.name}`,!0}function fn(){return[...W]}function mn(){let t=W.map(e=>e.name);W.forEach(e=>{if(e.onUnregister)try{e.onUnregister()}catch(n){console.error(`Error in plugin "${e.name}" onUnregister:`,n)}}),W.length=0,`${t.length}`}function yn(){xe=!0}function hn(){xe=!1}function bn(){return xe}function vn(t,e,n){let r={id:_o(),type:t,createdAt:Date.now(),label:n};if(Qe.set(r.id,r),xe){for(let o of W)if(o.onSignalCreate)try{o.onSignalCreate(r,e)}catch(s){console.error(`Error in plugin "${o.name}" onSignalCreate:`,s)}}return r}function Sn(t,e,n,r="set"){if(!xe)return;let o=Qe.get(t);if(!o)return;let s={signal:o,oldValue:e,newValue:n,timestamp:Date.now(),source:r};for(let i of W)if(i.onSignalUpdate)try{i.onSignalUpdate(s)}catch(l){console.error(`Error in plugin "${i.name}" onSignalUpdate:`,l)}}function Tn(t){if(!xe)return;let e=Qe.get(t);if(e){for(let n of W)if(n.onSignalDestroy)try{n.onSignalDestroy(e)}catch(r){console.error(`Error in plugin "${n.name}" onSignalDestroy:`,r)}Qe.delete(t)}}function xn(t={}){let{verbose:e=!1,logCreates:n=!0,logUpdates:r=!0,logDestroys:o=!0}=t;return{name:"logger",version:"1.0.0",onRegister(){},onSignalCreate(s,i){n&&`${s.type}${s.label||s.id}`},onSignalUpdate(s){r&&(`${s.signal.type}${s.signal.label||s.signal.id}`,e||`${s.oldValue}${s.newValue}`)},onSignalDestroy(s){o&&`${s.type}${s.label||s.id}`},onUnregister(){}}}function Pn(t={}){let{maxHistory:e=50}=t,n=[],r=[];return{plugin:{name:"time-travel",version:"1.0.0",onRegister(){},onSignalUpdate(s){n.push({signalId:s.signal.id,oldValue:s.oldValue,newValue:s.newValue,timestamp:s.timestamp}),r.length=0,n.length>e&&n.shift()},onUnregister(){n.length=0,r.length=0}},undo(){if(n.length===0)return!1;let s=n.pop();return r.push(s),`${s.newValue}${s.oldValue}`,!0},redo(){if(r.length===0)return!1;let s=r.pop();return n.push(s),`${s.oldValue}${s.newValue}`,!0},getHistory(){return[...n]},clear(){n.length=0,r.length=0},get historySize(){return n.length},get futureSize(){return r.length}}}function Cn(){let t={totalUpdates:0,updatesBySignal:new Map,averageUpdateTime:0,slowestUpdate:null},e=0,n=new Map;return{plugin:{name:"performance",version:"1.0.0",onRegister(){},onBeforeUpdate(o){return n.set(o.signal.id,performance.now()),o.newValue},onSignalUpdate(o){let s=n.get(o.signal.id);if(s!==void 0){let i=performance.now()-s;e+=i,n.delete(o.signal.id),t.totalUpdates++,t.updatesBySignal.set(o.signal.id,(t.updatesBySignal.get(o.signal.id)||0)+1),t.averageUpdateTime=e/t.totalUpdates,(!t.slowestUpdate||i>t.slowestUpdate.duration)&&(t.slowestUpdate={signalId:o.signal.label||o.signal.id,duration:i})}},onUnregister(){}},getMetrics(){return{...t,updatesBySignal:new Map(t.updatesBySignal)}},reset(){t.totalUpdates=0,t.updatesBySignal.clear(),t.averageUpdateTime=0,t.slowestUpdate=null,e=0},printMetrics(){"=".repeat(50),`${t.totalUpdates}`,`${t.averageUpdateTime.toFixed(3)}`,t.slowestUpdate&&`${t.slowestUpdate.signalId}${t.slowestUpdate.duration.toFixed(3)}`,t.updatesBySignal.forEach((o,s)=>{`${s}${o}`}),"=".repeat(50)+""}}}function wn(t){return{name:"validation",version:"1.0.0",onRegister(){},onBeforeUpdate(e){let n=e.signal.label;if(n&&t[n]&&!t[n](e.newValue)){console.error(`[Validation] \u274C Invalid value for signal "${n}":`,e.newValue);return}return e.newValue},onUnregister(){}}}var W,Qe,Do,xe,et=gn(()=>{"use strict";W=[],Qe=new Map,Do=0,xe=!0});async function jo(){return new Promise(t=>{Vt?gr.push(()=>t()):(Vt=!0,t())})}function qo(){let t=gr.shift();t?t():Vt=!1}async function $e(t){await jo();try{return await t()}finally{qo()}}function Wo(t,e){let n=()=>k.get(t);return{name:e.name,version:e.version,onRegister(){if(e.onRegister)try{e.onRegister()}catch(r){console.error(`[PluginManager] Error in "${t}" onRegister:`,r);let o=n();o&&o.metadata.errorCount++}},onUnregister(){if(e.onUnregister)try{e.onUnregister()}catch(r){console.error(`[PluginManager] Error in "${t}" onUnregister:`,r);let o=n();o&&o.metadata.errorCount++}},onSignalCreate(r,o){let s=n();if(s?.enabled&&e.onSignalCreate)try{e.onSignalCreate(r,o)}catch(i){console.error(`[PluginManager] Error in "${t}" onSignalCreate:`,i),s.metadata.errorCount++}},onBeforeUpdate(r){let o=n();if(!o?.enabled)return r.newValue;if(e.onBeforeUpdate)try{return e.onBeforeUpdate(r)}catch(s){return console.error(`[PluginManager] Error in "${t}" onBeforeUpdate:`,s),o.metadata.errorCount++,r.newValue}return r.newValue},onSignalUpdate(r){let o=n();if(o?.enabled&&e.onSignalUpdate)try{e.onSignalUpdate(r)}catch(s){console.error(`[PluginManager] Error in "${t}" onSignalUpdate:`,s),o.metadata.errorCount++}},onSignalDestroy(r){let o=n();if(o?.enabled&&e.onSignalDestroy)try{e.onSignalDestroy(r)}catch(s){console.error(`[PluginManager] Error in "${t}" onSignalDestroy:`,s),o.metadata.errorCount++}}}}async function pr(t,e,n={}){await $e(()=>{if(k.has(t))throw new Error(`[PluginManager] Plugin "${t}" is already registered`);let r=n.enabled!==!1,o=Date.now(),s={plugin:e,enabled:r,registeredAt:o,enabledAt:r?o:null,disabledAt:r?null:o,metadata:{enableCount:r?1:0,disableCount:r?0:1,errorCount:0}};k.set(t,s);let i=Wo(t,e);Ze(i),`${t}`})}async function fr(t){return $e(()=>{let e=k.get(t);return e?e.enabled?(`${t}`,!1):(e.enabled=!0,e.enabledAt=Date.now(),e.metadata.enableCount++,`${t}`,!0):(`${t}`,!1)})}async function mr(t){return $e(()=>{let e=k.get(t);return e?e.enabled?(e.enabled=!1,e.disabledAt=Date.now(),e.metadata.disableCount++,`${t}`,!0):(`${t}`,!1):(`${t}`,!1)})}async function yr(t){return $e(()=>{let e=k.get(t);return e?(_e(e.plugin.name),k.delete(t),`${t}`,!0):(`${t}`,!1)})}function hr(t){return k.get(t)?.plugin}function br(t){return k.get(t)?.enabled??!1}function vr(){return Array.from(k.entries()).map(([t,e])=>({name:t,plugin:e.plugin,enabled:e.enabled,registeredAt:e.registeredAt,enabledAt:e.enabledAt,disabledAt:e.disabledAt,metadata:{...e.metadata}}))}function zt(){let t=0,e=0,n=0;for(let r of k.values())r.enabled?t++:e++,n+=r.metadata.errorCount;return{total:k.size,enabled:t,disabled:e,totalErrors:n}}async function Sr(){await $e(()=>{let t=Array.from(k.keys());for(let e of t){let n=k.get(e);n&&_e(n.plugin.name)}k.clear(),`${t.length}`})}function Tr(){"=".repeat(60);let t=zt();if(`${t.total}`,`${t.enabled}`,`${t.disabled}`,`${t.totalErrors}`,k.size>0)for(let[e,n]of k.entries()){let r=n.enabled?"\u2705 Enabled":"\u23F8\uFE0F Disabled",o=n.plugin.version?` v${n.plugin.version}`:"",s=n.metadata.errorCount>0?` (${n.metadata.errorCount} errors)`:"";`${r}${e}${o}${s}`}"=".repeat(60)+""}var k,Vt,gr,gt,pt,xr=gn(()=>{"use strict";et();k=new Map,Vt=!1,gr=[];gt=class{constructor(e={}){this.verbose=e.verbose??!1,this.logCreates=e.logCreates??!0,this.logUpdates=e.logUpdates??!0,this.logDestroys=e.logDestroys??!0,this.startTime=Date.now()}getElapsedTime(){return`+${Date.now()-this.startTime}ms`}formatTimestamp(e){return new Date(e).toISOString()}getPlugin(){return{name:"logger",version:"2.0.0",onRegister:()=>{`${this.formatTimestamp(Date.now())}`,this.startTime=Date.now()},onSignalCreate:(e,n)=>{if(!this.logCreates)return;let r=e.label||e.id;`${this.getElapsedTime()}${e.type}${r}`,this.verbose?this.formatTimestamp(e.createdAt):`${JSON.stringify(n)}`},onSignalUpdate:e=>{if(!this.logUpdates)return;let n=e.signal.label||e.signal.id,r=e.source?`[${e.source}]`:"";`${this.getElapsedTime()}${e.signal.type}${n}${r}`,this.verbose?this.formatTimestamp(e.timestamp):`${JSON.stringify(e.oldValue)}${JSON.stringify(e.newValue)}`},onSignalDestroy:e=>{if(!this.logDestroys)return;let n=e.label||e.id;`${this.getElapsedTime()}${e.type}${n}`},onUnregister:()=>{`${this.getElapsedTime()}`}}}},pt=class{constructor(e={}){this.history=[];this.future=[];this.snapshots=new Map;this.maxHistory=e.maxHistory??50}getPlugin(){return{name:"time-travel",version:"2.0.0",onRegister:()=>{`${this.maxHistory}`},onSignalUpdate:e=>{this.history.push({...e}),this.future=[],this.history.length>this.maxHistory&&this.history.shift()},onUnregister:()=>{`${this.history.length}`,this.clear()}}}undo(){if(this.history.length===0)return!1;let e=this.history.pop();return this.future.push(e),`${e.signal.label||e.signal.id}${JSON.stringify(e.newValue)}${JSON.stringify(e.oldValue)}`,!0}redo(){if(this.future.length===0)return!1;let e=this.future.pop();return this.history.push(e),`${e.signal.label||e.signal.id}${JSON.stringify(e.oldValue)}${JSON.stringify(e.newValue)}`,!0}getHistory(){return this.history.map(e=>({...e}))}getHistoryForSignal(e){return this.history.filter(n=>n.signal.id===e).map(n=>({...n}))}createSnapshot(e){this.snapshots.set(e,[...this.history]),`${e}${this.history.length}`}restoreSnapshot(e){let n=this.snapshots.get(e);return n?(this.history=[...n],this.future=[],`${e}`,!0):(`${e}`,!1)}listSnapshots(){return Array.from(this.snapshots.keys())}clear(){this.history=[],this.future=[]}getStats(){return{historySize:this.history.length,futureSize:this.future.length,snapshotCount:this.snapshots.size,maxHistory:this.maxHistory}}printHistory(e=10){"=".repeat(60);let n=this.getStats();`${n.historySize}${n.maxHistory}`,`${n.futureSize}`,`${n.snapshotCount}`,this.history.length>0&&(`${Math.min(e,this.history.length)}`,this.history.slice(-e).forEach((o,s)=>{let i=o.signal.label||o.signal.id,l=new Date(o.timestamp).toISOString();s+1,`${l}${i}${JSON.stringify(o.oldValue)}${JSON.stringify(o.newValue)}`})),"=".repeat(60)+""}}});var ws={};Lo(ws,{LogViewer:()=>To,LoggerPlugin:()=>gt,LoggerPluginEnhanced:()=>de,PerformanceTab:()=>to,SignalGraphVisualizer:()=>Zr,TimeTravelPlugin:()=>pt,TimeTravelPluginEnhanced:()=>Je,TimeTravelTimeline:()=>mo,__DEVTOOLS__:()=>Ve,arePluginsEnabled:()=>bn,batch:()=>rt,benchmarkBatchedUpdates:()=>Tt,benchmarkMemoryUsage:()=>Ct,benchmarkSignalUpdates:()=>St,calculateMemoryUsage:()=>Rt,clearAllPlugins:()=>Sr,clearPerformanceMetrics:()=>qr,clearPlugins:()=>mn,clearResults:()=>Zt,combine:()=>Er,compareWithRedux:()=>xt,compareWithZustand:()=>Pt,configureProfiler:()=>Hn,createArraySignal:()=>Ar,createComputed:()=>X,createConsoleOverlay:()=>Wr,createDebugLogger:()=>bo,createEffect:()=>ne,createEnhancedTimeTravelPlugin:()=>fo,createFilteredLogger:()=>vo,createLogger:()=>yo,createLoggerPlugin:()=>xn,createMinimalLogger:()=>ho,createPerformancePlugin:()=>Cn,createPersistentSignal:()=>qt,createRecordSignal:()=>Ir,createResource:()=>kr,createSignal:()=>_,createStorageAdapter:()=>jt,createTimeTravelPlugin:()=>Pn,createValidationPlugin:()=>wn,customBenchmark:()=>tn,debounce:()=>Dr,derive:()=>wr,detectEnvironment:()=>Fe,disableDevTools:()=>$r,disablePlugin:()=>mr,disablePlugins:()=>hn,disableProfiler:()=>it,enableDevTools:()=>Ur,enablePlugin:()=>fr,enablePlugins:()=>yn,enableProfiler:()=>st,endBatch:()=>ir,endBatchMeasurement:()=>dt,endLatencyMeasurement:()=>jn,exportResults:()=>en,exportSnapshot:()=>Kr,filter:()=>Lr,flushBatches:()=>lr,flushSync:()=>Nn,formatMemorySize:()=>Lt,getAllPlugins:()=>vr,getBatchDepth:()=>cr,getBatchRecords:()=>Jn,getBatchStats:()=>Wn,getBridgeConfig:()=>ao,getDependencies:()=>Hr,getDependencyGraph:()=>oe,getLatencySamples:()=>Kn,getPendingCount:()=>dr,getPerformanceMetrics:()=>be,getPerformanceSummary:()=>ze,getPlugin:()=>hr,getPluginStats:()=>zt,getProfilerData:()=>pe,getRegisteredPlugins:()=>fn,getResults:()=>Qt,getSignal:()=>wt,getSignalLatencyStats:()=>qn,getSignalsByType:()=>jr,getStorageAdapter:()=>bt,getSubscribers:()=>Gr,initializeDevToolsBridge:()=>oo,isBatching:()=>ur,isBridgeConnected:()=>io,isDevToolsEnabled:()=>A,isPluginEnabled:()=>br,isProfilerEnabled:()=>ae,listSignals:()=>re,logResults:()=>Yt,map:()=>Rr,memo:()=>Mr,monitor:()=>Br,notifyPerformanceMetric:()=>po,notifySignalCreated:()=>uo,notifySignalUpdated:()=>go,persist:()=>vt,printDependencyGraph:()=>Jr,printPluginStatus:()=>Tr,queueBatchCallback:()=>ar,recordBatchOperation:()=>ct,registerManagedPlugin:()=>pr,registerPlugin:()=>Ze,registerSignal:()=>Fr,resetProfiler:()=>at,resetStorageAdapter:()=>Gt,runBenchmarkSuite:()=>Xt,safeParse:()=>Ne,safeStringify:()=>Oe,shutdownDevToolsBridge:()=>so,startBatch:()=>sr,startBatchMeasurement:()=>lt,startLatencyMeasurement:()=>Gn,throttle:()=>_r,trackDependency:()=>Vr,trackUpdate:()=>Nr,unregisterManagedPlugin:()=>yr,unregisterPlugin:()=>_e,unregisterSignal:()=>Or,untrack:()=>On,untrackDependency:()=>zr,useSignal:()=>Pr,useSignalEffect:()=>Cr,useSignalValue:()=>Ht});module.exports=ko(ws);et();var ue=1,kt=2,Mt=4,Dt=8,En=16,Rn=1e4,Ln=new Array(Rn),nt=0;function Ao(t){nt<Rn&&(t.value=void 0,t.subscribers=null,t.listeners=null,t.dependencies=null,t.computeFn=null,t.flags=0,Ln[nt++]=t)}var tt=new WeakMap,_t=new Map;function Mn(t){return _t.get(t)}var Bt=1e4,kn=new Array(Bt),Pe=0,Ae=0,At=!1;function Io(t){if(t.flags&kt)return;let e=(Ae+1)%Bt;e===Pe&&(console.error("[SignalForge] Batch queue overflow \u2192 forcing flush"),It()),t.flags|=kt,kn[Ae]=t,Ae=e,At||(At=!0,queueMicrotask(It))}function It(){for(At=!1;Pe!==Ae;){let t=kn[Pe];Pe=(Pe+1)%Bt,t.flags&=~kt,t.flags&ue&&Ie(t)}}var Dn=new Array(100),_n=0,j=null;function Bo(t){Dn[_n++]=j,j=t}function Uo(){j=Dn[--_n]}var $o=function(){return this._node.value},Fo=function(t){this._node.subscribers||(this._node.subscribers=new Set),this._node.subscribers.add(t)},Oo=function(t){this._node.subscribers&&this._node.subscribers.delete(t)};function Ut(t,e=null){let n=nt>0?Ln[--nt]:{value:void 0,subscribers:null,listeners:null,dependencies:null,computeFn:null,flags:0};return n.value=t,n.computeFn=e,n.flags=e?En|ue:0,e&&Ie(n),n}function An(t,e){return j?(j!==t&&(In(t,j),zo(j,e)),t.flags&ue&&t.computeFn&&Ie(t),t.value):(t.flags&ue&&t.computeFn&&Ie(t),t.value)}function No(t,e,n){if(t.flags&En)throw new Error("Cannot set computed signal");if(typeof n=="function"&&(n=n(t.value)),Object.is(n,t.value))return;let r=t.value;t.value=n;let o=tt.get(e);o&&Sn(o,r,n,"set"),Un(t)}function In(t,e){t.subscribers||(t.subscribers=new Set),t.subscribers.add(e)}function Vo(t,e){t.subscribers&&t.subscribers.delete(e)}function zo(t,e){t.dependencies||(t.dependencies=new Set),t.dependencies.has(e)||(t.dependencies.add(e),In(e._node,t))}function Bn(t){if(t.dependencies){for(let e of t.dependencies)Vo(e._node,t);t.dependencies.clear()}}function $t(t){if(!(t.flags&ue)&&(t.flags|=ue,Io(t),t.subscribers))for(let e of t.subscribers)$t(e)}function Ie(t){if(t.computeFn&&!(t.flags&Mt)){t.flags|=Mt,Bn(t),Bo(t);try{let e=t.computeFn();t.flags&=~ue,t.flags&=~Mt,Object.is(e,t.value)||(t.value=e,Un(t))}finally{Uo()}}}function Un(t){if(t.subscribers)for(let e of t.subscribers)$t(e);if(t.flags&Dt&&t.listeners)for(let e of t.listeners)e(t.value)}function $n(t,e){return t.listeners||(t.listeners=new Set),t.listeners.add(e),t.flags|=Dt,()=>{t.listeners.delete(e),t.listeners.size===0&&(t.flags&=~Dt)}}function Ft(t){Bn(t),t.subscribers&&t.subscribers.clear(),t.listeners&&t.listeners.clear(),Ao(t)}function _(t){let e=Ut(t,null),n={get:()=>An(e,n),set:o=>No(e,n,o),subscribe:o=>$n(e,o),destroy:()=>{let o=tt.get(n);o&&(Tn(o),_t.delete(o),tt.delete(n)),Ft(e)},_node:e,_peek:$o,_addSubscriber:Fo,_removeSubscriber:Oo},r=vn("signal",t);return tt.set(n,r.id),_t.set(r.id,n),n}function X(t){let e,n=j;j=null;try{e=t()}finally{j=n}let r=Ut(e,t),o={get:()=>An(r,o),set:()=>{throw new Error("Cannot set a computed signal")},subscribe:s=>$n(r,s),destroy:()=>Ft(r),_node:r,_peek:()=>r.value,_addSubscriber:s=>{r.subscribers||(r.subscribers=new Set),r.subscribers.add(s)},_removeSubscriber:s=>{r.subscribers&&r.subscribers.delete(s)},_markDirty:()=>$t(r),_recompute:()=>Ie(r)};return o}function ne(t){let e=Ut(void 0,t);return()=>Ft(e)}function rt(t){let e=t();return Fn(),e}function Fn(){Pe!==Ae&&It()}function On(t){let e=j;j=null;try{return t()}finally{j=e}}var Nn=Fn;var K=!1,Be=null,zn=0,ge=new Map,ie=[],ot=new Map,Ue=new Map,te={maxSamplesPerSignal:100,maxBatchRecords:50,autoComputeStats:!1,emitEvents:!0};function st(t){K||(te={...te,...t},K=!0,Be=performance.now())}function it(){K&&(K=!1)}function ae(){return K}function at(){ge.clear(),ie.length=0,ot.clear(),Ue.clear(),Be=K?performance.now():null,zn=0}function Hn(t){te={...te,...t}}function Gn(t,e){K&&ot.set(t,{startTime:performance.now(),subscriberCount:e})}function jn(t,e,n){if(!K)return;let r=ot.get(t);if(!r)return;let o=performance.now(),s=o-r.startTime,i={signalId:t,type:e,startTime:r.startTime,endTime:o,latency:s,subscriberCount:r.subscriberCount,skipped:n},l=ge.get(t);l||(l=[],ge.set(t,l)),l.push(i),l.length>te.maxSamplesPerSignal&&l.shift(),ot.delete(t),te.emitEvents}function lt(t){if(!K)return-1;let e=++zn;return Ue.set(e,{startTime:performance.now(),operationCount:0,affectedSignals:new Set,depth:t}),e}function ct(t,e){if(!K||t===-1)return;let n=Ue.get(t);n&&(n.operationCount++,n.affectedSignals.add(e))}function dt(t){if(!K||t===-1)return;let e=Ue.get(t);if(!e)return;let n=performance.now(),r=n-e.startTime,o={batchId:t,startTime:e.startTime,endTime:n,duration:r,operationCount:e.operationCount,affectedSignals:Array.from(e.affectedSignals),depth:e.depth};ie.push(o),ie.length>te.maxBatchRecords&&ie.shift(),Ue.delete(t),te.emitEvents}function pe(){let t=performance.now(),e=Be?t-Be:0,n=new Map,r=0;for(let[s,i]of ge.entries()){if(i.length===0)continue;let l=Xn(s,i);n.set(s,l),r+=i.length}let o=Yn(ie);return{enabled:K,startedAt:Be,duration:e,signalStats:n,batchRecords:[...ie],batchStats:o,totalSamples:r,totalSignals:ge.size}}function qn(t){let e=ge.get(t);return!e||e.length===0?null:Xn(t,e)}function Wn(){return Yn(ie)}function Kn(t){return ge.get(t)||[]}function Jn(){return[...ie]}function Xn(t,e){if(e.length===0)return{signalId:t,type:"signal",sampleCount:0,min:0,max:0,mean:0,median:0,p95:0,p99:0,stdDev:0,avgSubscribers:0,skippedCount:0};let n=e[0].type,r=e.map(C=>C.latency),o=[...r].sort((C,E)=>C-E),s=o[0],i=o[o.length-1],c=r.reduce((C,E)=>C+E,0)/r.length,d=Math.floor(o.length/2),h=o.length%2===0?(o[d-1]+o[d])/2:o[d],S=Vn(o,.95),x=Vn(o,.99),M=r.map(C=>Math.pow(C-c,2)).reduce((C,E)=>C+E,0)/r.length,w=Math.sqrt(M),$=e.reduce((C,E)=>C+E.subscriberCount,0)/e.length,ee=e.filter(C=>C.skipped).length;return{signalId:t,type:n,sampleCount:e.length,min:s,max:i,mean:c,median:h,p95:S,p99:x,stdDev:w,avgSubscribers:$,skippedCount:ee}}function Yn(t){if(t.length===0)return{totalBatches:0,avgDuration:0,minDuration:0,maxDuration:0,avgOperationsPerBatch:0,totalOperations:0};let e=t.map(d=>d.duration),n=t.map(d=>d.operationCount),r=t.length,o=e.reduce((d,h)=>d+h,0)/r,s=Math.min(...e),i=Math.max(...e),l=n.reduce((d,h)=>d+h,0),c=l/r;return{totalBatches:r,avgDuration:o,minDuration:s,maxDuration:i,avgOperationsPerBatch:c,totalOperations:l}}function Vn(t,e){if(t.length===0)return 0;let n=e*(t.length-1),r=Math.floor(n),o=Math.ceil(n),s=n-r;return r===o?t[r]:t[r]*(1-s)+t[o]*s}var Ho="[SignalForge]",Ot={BATCH_MISMATCH:"endBatch called without matching startBatch",MAX_BATCH_DEPTH:"Maximum batch depth (1000) exceeded",MAX_DEPENDENCY_DEPTH:"Maximum dependency depth (100) exceeded - possible circular dependency",INVALID_SIGNAL:"Invalid signal provided",PLUGIN_NOT_FOUND:"Plugin not found",PLUGIN_ALREADY_REGISTERED:"Plugin with this name is already registered",STORAGE_NOT_AVAILABLE:"Storage backend not available",DEVTOOLS_CONNECTION_FAILED:"Failed to connect to DevTools"};var Qn="3.0.0";function Zn(t,e,n){return Math.min(Math.max(t,e),n)}function er(t){return t===void 0?100:Zn(t,10,1e4)}function tr(t){return t===void 0?1e3:Zn(t,100,1e4)}function nr(t,e=100){return t.length<=e?t:t.substring(0,e-3)+"..."}function Nt(t){return`${Ho} ${t}`}var q=0,Ce=-1,fe=new Set,ut=!1;function or(){ut||(ut=!0,typeof queueMicrotask<"u"?queueMicrotask(rr):Promise.resolve().then(rr))}function rr(){if(ut=!1,q>0)return;let t=Array.from(fe);fe.clear();for(let e of t)try{e()}catch(n){console.error("Error in batch callback:",n)}}function sr(){if(q>=1e3)throw new Error(Nt(Ot.MAX_BATCH_DEPTH));q++,q===1&&ae()&&(Ce=lt(q))}function ir(){if(q<=0)throw new Error(Nt(Ot.BATCH_MISMATCH));q--,q===0&&ae()&&Ce!==-1&&(dt(Ce),Ce=-1),q===0&&fe.size>0&&or()}function ar(t,e){fe.add(t),q>0&&ae()&&Ce!==-1&&e&&ct(Ce,e),q===0&&or()}function lr(){ut=!1;let t=Array.from(fe);fe.clear();for(let e of t)try{e()}catch(n){console.error("Error in batch callback:",n)}}function cr(){return q}function dr(){return fe.size}function ur(){return q>0}et();xr();var me=require("react");function Ko(){if(typeof me.useState!="function"||typeof me.useEffect!="function")throw new Error(`[SignalForge] React hooks unavailable. Possible duplicate React instance or invalid bundler resolution. Troubleshooting: 1. Ensure only one react copy: node_modules/react (no nested copy under library). 2. Clear Metro cache: npx react-native start --reset-cache. 3. Verify metro.config.js extraNodeModules maps react to example app node_modules.`)}Ko();function Ht(t){let[e,n]=(0,me.useState)(()=>t.get());return(0,me.useEffect)(()=>(n(t.get()),t.subscribe(()=>n(t.get()))),[t]),e}function Pr(t){let[e]=(0,me.useState)(()=>{let r=typeof t=="function"?t():t;return _(r)});return[Ht(e),e.set.bind(e)]}var we=require("react");var ft=new WeakMap;function Cr(t,e=[]){let n=(0,we.useRef)({}),r=(0,we.useRef)(null),o=(0,we.useRef)(null);(0,we.useEffect)(()=>{let s=()=>{if(!ft.get(n.current)){ft.set(n.current,!0);try{r.current&&(r.current(),r.current=null);let i=t();typeof i=="function"&&(r.current=i)}finally{ft.set(n.current,!1)}}};return o.current=ne(s),()=>{r.current&&r.current(),o.current&&o.current(),ft.delete(n.current)}},e)}function Fe(){let t=typeof global<"u"?global:void 0,e=typeof window<"u"?window:void 0;return typeof navigator<"u"&&navigator.product==="ReactNative"||e?.navigator?.product==="ReactNative"||t?.HermesInternal||t?.__fbBatchedBridgeConfig||t?.nativeModuleProxy||t?.__turboModuleProxy?"react-native":e?.localStorage||t?.localStorage?"web":"node"}function Oe(t,e=!1){let n=new WeakSet;try{return JSON.stringify(t,(r,o)=>{if(o===void 0)return"__undefined__";if(o===null)return null;if(typeof o=="function")return e&&`${r}`,"__function__";if(o instanceof Date)return{__type__:"Date",value:o.toISOString()};if(o instanceof RegExp)return{__type__:"RegExp",value:o.toString()};if(typeof o=="object"&&o!==null){if(n.has(o))return e&&`${r}`,"__circular__";n.add(o)}return o})}catch(r){e&&console.error("[StorageAdapter] Serialization error:",r);try{return JSON.stringify(t)}catch{return"{}"}}}function Ne(t,e=!1){try{return JSON.parse(t,(n,r)=>{if(r!=="__undefined__"&&r!=="__function__"){if(r==="__circular__")return null;if(r&&typeof r=="object"){if(r.__type__==="Date")return new Date(r.value);if(r.__type__==="RegExp"){let o=r.value.match(/^\/(.+)\/([gimuy]*)$/);if(o)return new RegExp(o[1],o[2])}}return r}})}catch(n){return e&&console.error("[StorageAdapter] Deserialization error:",n),null}}var mt=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??Wt,this.serialize=e.serialize||(n=>Oe(n,this.devMode)),this.deserialize=e.deserialize||(n=>Ne(n,this.devMode))}getKey(e){return`${this.prefix}${e}`}async load(e){try{let n=localStorage.getItem(this.getKey(e));return n===null?null:this.deserialize(n)}catch(n){return this.devMode&&console.error(`[StorageAdapter] Failed to load "${e}":`,n),null}}async save(e,n){try{let r=this.serialize(n);localStorage.setItem(this.getKey(e),r)}catch(r){throw this.devMode&&console.error(`[StorageAdapter] Failed to save "${e}":`,r),r}}async clear(e){try{localStorage.removeItem(this.getKey(e))}catch(n){throw this.devMode&&console.error(`[StorageAdapter] Failed to clear "${e}":`,n),n}}isAvailable(){try{let e="__storage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return!1}}async getAllKeys(){try{let e=[];for(let n=0;n<localStorage.length;n++){let r=localStorage.key(n);r&&r.startsWith(this.prefix)&&e.push(r.slice(this.prefix.length))}return e}catch(e){return this.devMode&&console.error("[StorageAdapter] Failed to get all keys:",e),[]}}async clearAll(){try{let e=await this.getAllKeys();for(let n of e)await this.clear(n)}catch(e){throw this.devMode&&console.error("[StorageAdapter] Failed to clear all:",e),e}}},yt=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??Wt,this.serialize=e.serialize||(n=>Oe(n,this.devMode)),this.deserialize=e.deserialize||(n=>Ne(n,this.devMode));try{this.AsyncStorage=require("@react-native-async-storage/async-storage").default}catch{try{this.AsyncStorage=require("react-native").AsyncStorage}catch{this.devMode&&console.error("[StorageAdapter] AsyncStorage not found. Install @react-native-async-storage/async-storage"),this.AsyncStorage=null}}}getKey(e){return`${this.prefix}${e}`}async load(e){if(!this.AsyncStorage)return this.devMode,null;try{let n=await this.AsyncStorage.getItem(this.getKey(e));return n===null?null:this.deserialize(n)}catch(n){return this.devMode&&console.error(`[StorageAdapter] Failed to load "${e}":`,n),null}}async save(e,n){if(!this.AsyncStorage){this.devMode;return}try{let r=this.serialize(n);await this.AsyncStorage.setItem(this.getKey(e),r)}catch(r){throw this.devMode&&console.error(`[StorageAdapter] Failed to save "${e}":`,r),r}}async clear(e){if(!this.AsyncStorage){this.devMode;return}try{await this.AsyncStorage.removeItem(this.getKey(e))}catch(n){throw this.devMode&&console.error(`[StorageAdapter] Failed to clear "${e}":`,n),n}}isAvailable(){return this.AsyncStorage!==null}async getAllKeys(){if(!this.AsyncStorage)return[];try{return(await this.AsyncStorage.getAllKeys()).filter(n=>n.startsWith(this.prefix)).map(n=>n.slice(this.prefix.length))}catch(e){return this.devMode&&console.error("[StorageAdapter] Failed to get all keys:",e),[]}}async clearAll(){if(this.AsyncStorage)try{let n=(await this.getAllKeys()).map(r=>this.getKey(r));await this.AsyncStorage.multiRemove(n)}catch(e){throw this.devMode&&console.error("[StorageAdapter] Failed to clear all:",e),e}}},ht=class{constructor(e={}){this.storage=new Map;this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??Wt,this.devMode}getKey(e){return`${this.prefix}${e}`}async load(e){let n=this.storage.get(this.getKey(e));return n!==void 0?n:null}async save(e,n){let r=JSON.parse(JSON.stringify(n));this.storage.set(this.getKey(e),r)}async clear(e){this.storage.delete(this.getKey(e))}isAvailable(){return!0}async getAllKeys(){let e=[];for(let n of this.storage.keys())n.startsWith(this.prefix)&&e.push(n.slice(this.prefix.length));return e}async clearAll(){let e=await this.getAllKeys();for(let n of e)this.storage.delete(this.getKey(n))}},ye=null;function bt(t={}){if(ye)return ye;switch(Fe()){case"web":ye=new mt(t);break;case"react-native":ye=new yt(t);break;case"node":case"unknown":default:ye=new ht(t);break}return ye}function Gt(){ye=null}function jt(t=Fe(),e={}){switch(t){case"web":return new mt(e);case"react-native":return new yt(e);case"node":case"unknown":default:return new ht(e)}}function vt(t,e={}){let n=e.adapter||bt(),r=e.key||`signal_${Math.random().toString(36).slice(2)}`,o=e.serialize||(c=>c),s=e.deserialize||(c=>c);n.load(r).then(c=>{if(c!==null)try{let d=s(c);t.set(d)}catch(d){e.onError&&e.onError(d)}}).catch(c=>{e.onError&&e.onError(c)});let i,l=ne(()=>{let c=t.get(),d=()=>{try{let h=o(c);n.save(r,h).catch(S=>{e.onError&&e.onError(S)})}catch(h){e.onError&&e.onError(h)}};e.debounce?(i!==void 0&&clearTimeout(i),i=setTimeout(d,e.debounce)):d()});return()=>{l(),i!==void 0&&clearTimeout(i)}}function qt(t,e,n={}){let r=_(e);return vt(r,{...n,key:t}),r}var Wt=typeof globalThis.__DEV__<"u"?globalThis.__DEV__:process.env.NODE_ENV!=="production";var L=[];function J(){return typeof performance<"u"&&performance.now?performance.now():Date.now()}function St(t){console.time("SignalForge: Sequential Updates");let e=J(),n=_(0),r=X(()=>n.get()*2),o=0;for(let h=0;h<t;h++)n.set(h),o=r.get();let s=J();console.timeEnd("SignalForge: Sequential Updates");let i=s-e,l=i/t,c=t/i*1e3,d={name:"SignalForge Sequential Updates",iterations:t,totalTime:i,averageTime:l,opsPerSecond:c,metadata:{lastValue:o}};return L.push(d),d}function Tt(t){console.time("SignalForge: Batched Updates");let e=J(),n=Array.from({length:t},()=>_(0)),r=X(()=>n.reduce((h,S)=>h+S.get(),0));rt(()=>{for(let h=0;h<t;h++)n[h].set(h)});let o=r.get(),s=J();console.timeEnd("SignalForge: Batched Updates");let i=s-e,l=i/t,c=t/i*1e3,d={name:"SignalForge Batched Updates",iterations:t,totalTime:i,averageTime:l,opsPerSecond:c,metadata:{computedValue:o}};return L.push(d),d}var Kt=class{constructor(e){this.listeners=new Set;this.state=e}getState(){return this.state}dispatch(e){e.type==="INCREMENT"?this.state={count:this.state.count+1}:e.type==="SET"&&(this.state={count:e.payload}),this.listeners.forEach(n=>n())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};function xt(t=1e4){console.time("Redux-like: Sequential Updates");let e=J(),n=new Kt({count:0}),r=0;n.subscribe(()=>{r=n.getState().count*2});for(let d=0;d<t;d++)n.dispatch({type:"SET",payload:d});let o=J();console.timeEnd("Redux-like: Sequential Updates");let s=o-e,i=s/t,l=t/s*1e3,c={name:"Redux-like Sequential Updates",iterations:t,totalTime:s,averageTime:i,opsPerSecond:l,metadata:{lastValue:r}};return L.push(c),c}var Jt=class{constructor(e){this.listeners=new Set;this.state=e}getState(){return this.state}setState(e){this.state={...this.state,...e},this.listeners.forEach(n=>n())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};function Pt(t=1e4){console.time("Zustand-like: Sequential Updates");let e=J(),n=new Jt({count:0}),r=0;n.subscribe(()=>{r=n.getState().count*2});for(let d=0;d<t;d++)n.setState({count:d});let o=J();console.timeEnd("Zustand-like: Sequential Updates");let s=o-e,i=s/t,l=t/s*1e3,c={name:"Zustand-like Sequential Updates",iterations:t,totalTime:s,averageTime:i,opsPerSecond:l,metadata:{lastValue:r}};return L.push(c),c}function Ct(t){let e=typeof performance<"u"&&performance.memory,n=e?performance.memory.usedJSHeapSize:0,r=J(),o=Array.from({length:t},(S,x)=>_(x));typeof global<"u"&&global.gc&&global.gc();let s=J(),i=e?performance.memory.usedJSHeapSize:0,l=s-r,c=i-n,d=c/t,h={name:"Memory Usage",iterations:t,totalTime:l,averageTime:l/t,opsPerSecond:t/l*1e3,metadata:{memoryUsedBytes:c,memoryUsedKB:c/1024,memoryUsedMB:c/(1024*1024),bytesPerSignal:d,hasMemoryAPI:e,signalCount:o.length}};return L.push(h),h}function Xt(t=1e4){return L.length=0,St(t),Tt(Math.floor(t/10)),xt(t),Pt(t),Ct(1e3),L}function Yt(){if(L.length===0)return;"=".repeat(100),""+"Benchmark Name".padEnd(35)+"Iterations".padEnd(12)+"Total (ms)".padEnd(12)+"Avg (ms)".padEnd(12)+"Ops/sec".padEnd(15),"=".repeat(100);for(let s of L)""+s.name.padEnd(35)+s.iterations.toLocaleString().padEnd(12)+s.totalTime.toFixed(2).padEnd(12)+s.averageTime.toFixed(4).padEnd(12)+s.opsPerSecond.toLocaleString(void 0,{maximumFractionDigits:0}).padEnd(15);"=".repeat(100);let t=L.find(s=>s.name==="SignalForge Sequential Updates"),e=L.find(s=>s.name==="Redux-like Sequential Updates"),n=L.find(s=>s.name==="Zustand-like Sequential Updates");if(t&&e){let s=e.totalTime/t.totalTime;`${s.toFixed(2)}`,s>1}if(t&&n){let s=n.totalTime/t.totalTime;`${s.toFixed(2)}`,s>1}let r=L.find(s=>s.name==="SignalForge Batched Updates");t&&r&&`${(t.averageTime/r.averageTime).toFixed(2)}`;let o=L.find(s=>s.name==="Memory Usage");o&&o.metadata?.hasMemoryAPI&&(`${o.metadata.memoryUsedKB.toFixed(2)}${o.iterations}`,`${o.metadata.bytesPerSignal.toFixed(0)}`)}function Qt(){return[...L]}function Zt(){L.length=0}function en(){return JSON.stringify(L,null,2)}function tn(t,e,n=1e3){console.time(t);let r=J();for(let d=0;d<n;d++)e();let o=J();console.timeEnd(t);let s=o-r,i=s/n,l=n/s*1e3,c={name:t,iterations:n,totalTime:s,averageTime:i,opsPerSecond:l};return L.push(c),c}function wr(t,e){return X(()=>{let n=t.map(r=>r.get());return e(...n)})}function Er(t){return X(()=>t.map(e=>e.get()))}function Rr(t,e){return X(()=>e(t.get()))}function Lr(t,e,n){return X(()=>{let r=t.get();return e(r)?r:n})}function Mr(t,e=Object.is){let n=t._peek?t._peek():t.get();return X(()=>{let r=t.get();return e(r,n)||(n=r),n})}function kr(t){let e=_({status:"pending",data:void 0,error:void 0});return t().then(n=>{e.set({status:"success",data:n,error:void 0})}).catch(n=>{e.set({status:"error",data:void 0,error:n})}),e}function Dr(t,e){let n=_(t._peek?t._peek():t.get()),r;return ne(()=>{let o=t.get();r!==void 0&&clearTimeout(r),r=setTimeout(()=>{n.set(o)},e)}),n}function _r(t,e){let n=_(t._peek?t._peek():t.get()),r=0,o,s;return ne(()=>{let i=t.get(),l=Date.now(),c=l-r;c>=e?(n.set(i),r=l,o=void 0):(o=i,s===void 0&&(s=setTimeout(()=>{o!==void 0&&(n.set(o),r=Date.now(),o=void 0),s=void 0},e-c)))}),n}function Ar(t=[]){let e=_(t);return{...e,push(...n){e.set(r=>[...r,...n])},pop(){let n;return e.set(r=>{let o=[...r];return n=o.pop(),o}),n},filter(n){e.set(r=>r.filter(n))},map(n){return e.get().map(n)},find(n){return e.get().find(n)},remove(n){e.set(r=>r.filter(o=>o!==n))},clear(){e.set([])},get length(){return e.get().length}}}function Ir(t={}){let e=_(t);return{...e,setKey(n,r){e.set(o=>({...o,[n]:r}))},deleteKey(n){e.set(r=>{let o={...r};return delete o[n],o})},hasKey(n){return n in e.get()},getKey(n){return e.get()[n]},keys(){return Object.keys(e.get())},values(){return Object.values(e.get())},entries(){return Object.entries(e.get())},clear(){e.set({})}}}function Br(t,e){let n=0,r=0,o=0,s=0;return{get(){let i=performance.now(),l=t.get(),c=performance.now()-i;return n++,o+=c,n%100===0&&`${e}${n}${(o/n).toFixed(3)}`,l},set(i){let l=performance.now();t.set(i);let c=performance.now()-l;r++,s+=c,`${e}${r}${c.toFixed(3)}`},subscribe:t.subscribe.bind(t),destroy:t.destroy.bind(t),_node:t._node,_addSubscriber:t._addSubscriber?t._addSubscriber.bind(t):void 0,_removeSubscriber:t._removeSubscriber?t._removeSubscriber.bind(t):void 0,_peek:t._peek?t._peek.bind(t):void 0}}var Ve=!1,F={enabled:!1,trackPerformance:!0,logToConsole:!1,maxPerformanceSamples:1e3,flipperEnabled:!1},O=new Map,ce=new WeakMap,he=[],Jo=0,le=null;function Ur(t={}){Ve=!0,Object.assign(F,t),F.enabled=!0,F.logToConsole,F.flipperEnabled&&Xo()}function $r(){Ve=!1,F.enabled=!1,le&&Yo()}function A(){return Ve&&F.enabled}function Fr(t,e,n){if(!A())return"";let r=`${e}_${++Jo}`,o;if(typeof Error<"u")try{throw new Error}catch(i){o=i.stack?.split(` `).slice(2,6).join(` `)}let s={id:r,type:e,value:Ee(n),subscriberCount:0,dependencies:[],subscribers:[],createdAt:Date.now(),updatedAt:Date.now(),updateCount:0,creationStack:o};return O.set(r,s),ce.set(t,r),F.logToConsole&&`${e}${r}`,nn("signalRegistered",s),r}function Or(t){if(!A())return;let e=ce.get(t);e&&(O.delete(e),ce.delete(t),F.logToConsole&&`${e}`,nn("signalUnregistered",{id:e}))}function Nr(t,e,n){if(!A()){e();return}let r=ce.get(t);if(!r){e();return}let o=O.get(r);if(!o){e();return}let s=performance.now(),i=!1,l;try{e(),l=t._peek?t._peek():t.get(),i=Object.is(n,l)}catch(c){throw console.error(`[SignalForge] Error updating signal "${r}"`,c),c}finally{let d=performance.now()-s;if(o.value=Ee(l),o.updatedAt=Date.now(),i||o.updateCount++,F.trackPerformance){let h={signalId:r,type:o.type,timestamp:s,duration:d,skipped:i,previousValue:Ee(n),newValue:Ee(l)};Qo(h),F.logToConsole&&d>16&&`${r}${d.toFixed(2)}`}nn("signalUpdated",{id:r,value:o.value,duration:d,skipped:i})}}function Vr(t,e){if(!A())return;let n=ce.get(t),r=ce.get(e);if(!n||!r)return;let o=O.get(n),s=O.get(r);!o||!s||(o.dependencies.includes(r)||o.dependencies.push(r),s.subscribers.includes(n)||s.subscribers.push(n),s.subscriberCount=s.subscribers.length)}function zr(t,e){if(!A())return;let n=ce.get(t),r=ce.get(e);if(!n||!r)return;let o=O.get(n),s=O.get(r);!o||!s||(o.dependencies=o.dependencies.filter(i=>i!==r),s.subscribers=s.subscribers.filter(i=>i!==n),s.subscriberCount=s.subscribers.length)}function re(){return A()?Array.from(O.values()).sort((t,e)=>t.createdAt-e.createdAt):[]}function wt(t){if(A())return O.get(t)}function Hr(t){return A()?O.get(t)?.dependencies||[]:[]}function Gr(t){return A()?O.get(t)?.subscribers||[]:[]}function oe(){if(!A())return[];let t=[],e=new Map,n=(r,o=0)=>{let s=e.get(r);if(s!==void 0)return Math.max(s,o);e.set(r,o);let i=O.get(r);if(i)for(let l of i.subscribers)n(l,o+1);return o};for(let[r,o]of O)o.dependencies.length===0&&n(r,0);for(let[r,o]of O)t.push({id:r,type:o.type,dependencies:o.dependencies,subscribers:o.subscribers,depth:e.get(r)||0});return t.sort((r,o)=>r.depth-o.depth)}function jr(t){return A()?Array.from(O.values()).filter(e=>e.type===t):[]}function be(t){if(!A())return[];let e=[...he];return t?e.slice(-t):e}function ze(){if(!A())return{totalUpdates:0,totalDuration:0,averageDuration:0,slowestUpdate:null,updatesByType:{}};let t=0,e=null,n={signal:0,computed:0,effect:0};for(let s of he)s.skipped||(t+=s.duration,n[s.type]++,(!e||s.duration>e.duration)&&(e=s));let r=he.filter(s=>!s.skipped).length,o=r>0?t/r:0;return{totalUpdates:r,totalDuration:t,averageDuration:o,slowestUpdate:e,updatesByType:n}}function qr(){he.length=0}function Xo(){try{typeof global<"u"&&global.__FLIPPER__&&(le=global.__FLIPPER__.addPlugin({getId:()=>"signalforge-inspector",onConnect:e=>{e.send("initialState",{signals:re(),graph:oe(),config:F}),e.receive("getSignals",()=>{e.send("signals",re())}),e.receive("getGraph",()=>{e.send("graph",oe())}),e.receive("getPerformance",()=>{e.send("performance",{metrics:be(100),summary:ze()})})},onDisconnect:()=>{le=null}}))}catch(t){}}function Yo(){if(le){try{le.disconnect()}catch(t){}le=null}}function nn(t,e){if(le&&F.flipperEnabled)try{le.send(t,e)}catch{}}function Wr(){if(typeof window>"u"||typeof document>"u")return{show:()=>{},hide:()=>{},destroy:()=>{}};let t=document.createElement("div");t.id="signalforge-devtools-overlay",t.style.cssText=` position: fixed; top: 0; right: 0; width: 400px; height: 100vh; background: rgba(0, 0, 0, 0.95); color: #fff; font-family: monospace; font-size: 12px; padding: 16px; overflow-y: auto; z-index: 999999; display: none; box-shadow: -2px 0 10px rgba(0, 0, 0, 0.5); `,document.body.appendChild(t);let e=()=>{let r=re(),o=ze();t.innerHTML=` <h2 style="margin: 0 0 16px 0; color: #61dafb;">SignalForge DevTools</h2> <div style="margin-bottom: 16px;"> <h3 style="margin: 0 0 8px 0;">Performance</h3> <div>Total Updates: ${o.totalUpdates}</div> <div>Avg Duration: ${o.averageDuration.toFixed(2)}ms</div> <div>Total Time: ${o.totalDuration.toFixed(2)}ms</div> </div> <div style="margin-bottom: 16px;"> <h3 style="margin: 0 0 8px 0;">Signals (${r.length})</h3> ${r.map(s=>` <div style="margin-bottom: 8px; padding: 8px; background: rgba(255,255,255,0.1); border-radius: 4px;"> <div style="color: #61dafb;">${s.id}</div> <div style="color: #999; font-size: 10px;">${s.type}</div> <div>Value: ${JSON.stringify(s.value)}</div> <div style="font-size: 10px; color: #999;"> Deps: ${s.dependencies.length} | Subs: ${s.subscriberCount} | Updates: ${s.updateCount} </div> </div> `).join("")} </div> <button onclick="document.getElementById('signalforge-devtools-overlay').style.display='none'" style="padding: 8px 16px; background: #61dafb; color: #000; border: none; border-radius: 4px; cursor: pointer;" > Close </button> `},n;return{show:()=>{t.style.display="block",e(),n=setInterval(e,1e3)},hide:()=>{t.style.display="none",n&&clearInterval(n)},destroy:()=>{n&&clearInterval(n),t.remove()}}}function Ee(t){try{if(t===null||typeof t>"u"||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(typeof t=="function")return`[Function: ${t.name||"anonymous"}]`;if(t instanceof Date)return t.toISOString();if(Array.isArray(t))return t.slice(0,10).map(Ee);if(typeof t=="object"){let e=Object.keys(t).slice(0,10),n={};for(let r of e)n[r]=Ee(t[r]);return n}return String(t)}catch{return"[Unserializable]"}}function Qo(t){he.push(t),he.length>F.maxPerformanceSamples&&he.shift()}function Kr(){return{timestamp:Date.now(),config:{...F},signals:re(),graph:oe(),performance:{metrics:be(),summary:ze()}}}function Jr(){if(!A())return;let t=oe();console.group("SignalForge Dependency Graph");for(let e of t){let n=" ".repeat(e.depth),r=e.dependencies.length>0?` \u2190 [${e.dependencies.join(", ")}]`:"",o=e.subscribers.length>0?` \u2192 [${e.subscribers.join(", ")}]`:"";`${n}${e.id}${e.type}${r}${o}`}console.groupEnd()}var I=require("react");var rn=class{constructor(){this.listeners=new Map;this.sequence=0}on(e,n){let r=e;return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(n),()=>this.off(e,n)}off(e,n){let r=e,o=this.listeners.get(r);o&&(o.delete(n),o.size===0&&this.listeners.delete(r))}emit(e,n){let r={type:e,payload:n,timestamp:Date.now(),sequence:++this.sequence},o=this.listeners.get(e);if(o)for(let i of o)try{i(r)}catch(l){console.error(`[DevTools] Error in listener for ${e}:`,l)}let s=this.listeners.get("*");if(s)for(let i of s)try{i(r)}catch(l){console.error("[DevTools] Error in wildcard listener:",l)}}removeAllListeners(){this.listeners.clear(),this.sequence=0}getListenerCount(e){if(e)return this.listeners.get(e)?.size||0;let n=0;for(let r of this.listeners.values())n+=r.size;return n}},Xr=typeof process<"u"?process.env.NODE_ENV!=="production":!0,He={enabled:!1,trackPerformance:!0,logToConsole:!1,maxPerformanceSamples:1e3,slowUpdateThreshold:16,emitPerformanceWarnings:!0},Zo=new Map;var es=new rn;function Yr(t={}){Xr=!0,Object.assign(He,t),He.enabled=!0,He.logToConsole}function ve(){return Xr&&He.enabled}function Qr(){return ve()?Array.from(Zo.values()).sort((t,e)=>t.createdAt-e.createdAt):[]}function Re(t,e){return es.on(t,e)}var y=require("react/jsx-runtime"),on=class{constructor(e,n){this.repulsionForce=3e3;this.attractionForce=.01;this.centerForce=.01;this.damping=.9;this.minDistance=50;this.nodes=new Map,this.edges=[],this.width=e,this.height=n}setGraph(e,n){this.nodes=e,this.edges=n}tick(){for(let e of this.nodes.values())e.fx=0,e.fy=0;this.applyRepulsion(),this.applyAttraction(),this.applyCenterForce(),this.updatePositions()}applyRepulsion(){let e=Array.from(this.nodes.values());for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let o=e[n],s=e[r],i=s.x-o.x,l=s.y-o.y,c=i*i+l*l,d=Math.sqrt(c)||1;if(d<this.minDistance){let h=this.repulsionForce/(this.minDistance*this.minDistance),S=i/d*h,x=l/d*h;o.fx-=S,o.fy-=x,s.fx+=S,s.fy+=x}else{let h=this.repulsionForce/c,S=i/d*h,x=l/d*h;o.fx-=S,o.fy-=x,s.fx+=S,s.fy+=x}}}applyAttraction(){for(let e of this.edges){let n=this.nodes.get(e.source),r=this.nodes.get(e.target);if(!n||!r)continue;let o=r.x-n.x,s=r.y-n.y,i=Math.sqrt(o*o+s*s)||1,l=i*this.attractionForce,c=o/i*l,d=s/i*l;n.fx+=c,n.fy+=d,r.fx-=c,r.fy-=d}}applyCenterForce(){let e=this.width/2,n=this.height/2;for(let r of this.nodes.values()){let o=e-r.x,s=n-r.y;r.fx+=o*this.centerForce,r.fy+=s*this.centerForce}}updatePositions(){for(let e of this.nodes.values()){e.vx=(e.vx+e.fx)*this.damping,e.vy=(e.vy+e.fy)*this.damping,e.x+=e.vx,e.y+=e.vy;let n=50;e.x<n?(e.x=n,e.vx*=-.5):e.x>this.width-n&&(e.x=this.width-n,e.vx*=-.5),e.y<n?(e.y=n,e.vy*=-.5):e.y>this.height-n&&(e.y=this.height-n,e.vy*=-.5)}}initializePositions(){let e=this.width/2,n=this.height/2,r=Math.min(this.width,this.height)/4;for(let o of this.nodes.values())if(o.x===0&&o.y===0){let s=Math.random()*Math.PI*2,i=Math.random()*r;o.x=e+Math.cos(s)*i,o.y=n+Math.sin(s)*i,o.vx=0,o.vy=0}}},Zr=({width:t=800,height:e=600,showLabels:n=!0,animate:r=!0,updateInterval:o=50,enablePhysics:s=!0,nodeRadius:i=20,highlightDuration:l=1e3})=>{let[c,d]=(0,I.useState)({nodes:new Map,edges:[]}),[h,S]=(0,I.useState)(null),x=(0,I.useRef)(new on(t,e)),U=(0,I.useRef)(null),M=(0,I.useRef)(Date.now()),w=(0,I.useCallback)(()=>{if(!ve())return{nodes:new Map,edges:[]};let u=Qr(),v=new Map,b=[];for(let f of u){let T=c.nodes.get(f.id);v.set(f.id,{id:f.id,type:f.type,value:f.value,label:f.name||f.id.split("_")[0],x:T?.x||0,y:T?.y||0,vx:T?.vx||0,vy:T?.vy||0,fx:0,fy:0,isUpdating:T?.isUpdating||!1,lastUpdate:f.updatedAt,subscriberCount:f.subscriberCount,dependencies:f.dependencies,subscribers:f.subscribers})}for(let f of v.values())for(let T of f.dependencies)v.has(T)&&b.push({source:f.id,target:T});return{nodes:v,edges:b}},[c.nodes]),$=(0,I.useCallback)(u=>{d(v=>{let b=w();return x.current.setGraph(b.nodes,b.edges),x.current.initializePositions(),b})},[w]),ee=(0,I.useCallback)(u=>{let{id:v}=u.payload;d(b=>{let f=b.nodes.get(v);return f&&(f.isUpdating=!0,f.lastUpdate=u.timestamp,setTimeout(()=>{d(T=>{let G=T.nodes.get(v);return G&&(G.isUpdating=!1),{...T}})},l)),{...b}})},[l]),C=(0,I.useCallback)(u=>{d(v=>{let b=w();return x.current.setGraph(b.nodes,b.edges),b})},[w]),E=(0,I.useCallback)(u=>{d(v=>{let b=w();return x.current.setGraph(b.nodes,b.edges),b})},[w]);(0,I.useEffect)(()=>{if(!ve())return;let u=w();d(u),x.current.setGraph(u.nodes,u.edges),x.current.initializePositions();let v=[Re("signal-created",$),Re("signal-updated",ee),Re("signal-destroyed",C),Re("dependency-added",E),Re("dependency-removed",E)];return()=>{v.forEach(b=>b())}},[w,$,ee,C,E]),(0,I.useEffect)(()=>{if(!r||!s)return;let u=()=>{let v=Date.now();v-M.current>=o&&(x.current.tick(),d(b=>({...b})),M.current=v),U.current=requestAnimationFrame(u)};return U.current=requestAnimationFrame(u),()=>{U.current&&cancelAnimationFrame(U.current)}},[r,s,o]);let H=u=>{if(u.isUpdating)return"#ff4444";switch(u.type){case"signal":return"#4CAF50";case"computed":return"#2196F3";case"effect":return"#FF9800";default:return"#9E9E9E"}},p=u=>h===u.id?"#FFD700":"#ffffff",P=u=>new Date(u).toLocaleTimeString(),R=u=>{if(u===null)return"null";if(u===void 0)return"undefined";if(typeof u=="object")try{return JSON.stringify(u).slice(0,50)}catch{return"[Object]"}return String(u).slice(0,50)};return ve()?(0,y.jsxs)("div",{style:{position:"relative",width:t,height:e,background:"#1e1e1e",borderRadius:8},children:[(0,y.jsxs)("svg",{width:t,height:e,children:[(0,y.jsx)("defs",{children:(0,y.jsx)("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"10",refX:"9",refY:"3",orient:"auto",markerUnits:"strokeWidth",children:(0,y.jsx)("path",{d:"M0,0 L0,6 L9,3 z",fill:"#666"})})}),(0,y.jsx)("g",{className:"edges",children:c.edges.map((u,v)=>{let b=c.nodes.get(u.source),f=c.nodes.get(u.target);if(!b||!f)return null;let T=f.x-b.x,G=f.y-b.y,Te=Math.sqrt(T*T+G*G)||1,dn=T/Te*i,un=G/Te*i;return(0,y.jsx)("line",{x1:b.x+dn,y1:b.y+un,x2:f.x-dn,y2:f.y-un,stroke:"#666",strokeWidth:2,markerEnd:"url(#arrowhead)",opacity:h===b.id||h===f.id?1:.3},`${u.source}-${u.target}-${v}`)})}),(0,y.jsx)("g",{className:"nodes",children:Array.from(c.nodes.values()).map(u=>(0,y.jsxs)("g",{onMouseEnter:()=>S(u.id),onMouseLeave:()=>S(null),style:{cursor:"pointer"},children:[(0,y.jsx)("circle",{cx:u.x,cy:u.y,r:i,fill:H(u),stroke:p(u),strokeWidth:h===u.id?3:1,opacity:h&&h!==u.id?.5:1}),n&&(0,y.jsx)("text",{x:u.x,y:u.y+i+15,textAnchor:"middle",fill:"#ffffff",fontSize:"12",fontFamily:"monospace",children:u.label}),u.isUpdating&&(0,y.jsxs)("circle",{cx:u.x,cy:u.y,r:i,fill:"none",stroke:"#ff4444",strokeWidth:2,opacity:.6,children:[(0,y.jsx)("animate",{attributeName:"r",from:i,to:i*2,dur:"0.5s",repeatCount:"indefinite"}),(0,y.jsx)("animate",{attributeName:"opacity",from:"0.6",to:"0",dur:"0.5s",repeatCount:"indefinite"})]})]},u.id))})]}),h&&c.nodes.has(h)&&(0,y.jsx)("div",{style:{position:"absolute",top:10,right:10,background:"rgba(0, 0, 0, 0.9)",color:"#fff",padding:15,borderRadius:8,fontSize:12,fontFamily:"monospace",maxWidth:300,border:"2px solid #FFD700"},children:(()=>{let u=c.nodes.get(h);return(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)("div",{style:{fontWeight:"bold",marginBottom:8,fontSize:14},children:u.label}),(0,y.jsxs)("div",{style:{marginBottom:4},children:[(0,y.jsx)("strong",{children:"Type:"})," ",u.type]}),(0,y.jsxs)("div",{style:{marginBottom:4},children:[(0,y.jsx)("strong",{children:"ID:"})," ",u.id]}),(0,y.jsxs)("div",{style:{marginBottom:4},children:[(0,y.jsx)("strong",{children:"Value:"})," ",R(u.value)]}),(0,y.jsxs)("div",{style:{marginBottom:4},children:[(0,y.jsx)("strong",{children:"Last Update:"})," ",P(u.lastUpdate)]}),(0,y.jsxs)("div",{style:{marginBottom:4},children:[(0,y.jsx)("strong",{children:"Subscribers:"})," ",u.subscriberCount]}),u.dependencies.length>0&&(0,y.jsxs)("div",{style:{marginBottom:4},children:[(0,y.jsx)("strong",{children:"Dependencies:"}),(0,y.jsx)("ul",{style:{margin:"4px 0",paddingLeft:20},children:u.dependencies.map(v=>{let b=c.nodes.get(v);return(0,y.jsx)("li",{children:b?.label||v},v)})})]}),u.subscribers.length>0&&(0,y.jsxs)("div",{children:[(0,y.jsx)("strong",{children:"Subscribers:"}),(0,y.jsxs)("ul",{style:{margin:"4px 0",paddingLeft:20},children:[u.subscribers.slice(0,5).map(v=>{let b=c.nodes.get(v);return(0,y.jsx)("li",{children:b?.label||v},v)}),u.subscribers.length>5&&(0,y.jsxs)("li",{children:["... and ",u.subscribers.length-5," more"]})]})]})]})})()}),(0,y.jsxs)("div",{style:{position:"absolute",bottom:10,left:10,background:"rgba(0, 0, 0, 0.8)"