signalforge
Version:
Fine-grained reactive state management with automatic dependency tracking - Ultra-optimized, zero dependencies
4 lines (3 loc) • 27.2 kB
JavaScript
var K=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var h=[],S=new Map,Se=0,L=!0;function ve(){return`signal_${++Se}_${Date.now()}`}function j(n){if(h.some(e=>e.name===n.name))throw new Error(`Plugin "${n.name}" is already registered`);if(h.push(n),n.onRegister)try{n.onRegister()}catch(e){console.error(`Error in plugin "${n.name}" onRegister:`,e)}`${n.name}`}function X(n,e,t){let r={id:ve(),type:n,createdAt:Date.now(),label:t};if(S.set(r.id,r),L){for(let s of h)if(s.onSignalCreate)try{s.onSignalCreate(r,e)}catch(o){console.error(`Error in plugin "${s.name}" onSignalCreate:`,o)}}return r}function J(n,e,t,r="set"){if(!L)return;let s=S.get(n);if(!s)return;let o={signal:s,oldValue:e,newValue:t,timestamp:Date.now(),source:r};for(let i of h)if(i.onSignalUpdate)try{i.onSignalUpdate(o)}catch(g){console.error(`Error in plugin "${i.name}" onSignalUpdate:`,g)}}function q(n){if(!L)return;let e=S.get(n);if(e){for(let t of h)if(t.onSignalDestroy)try{t.onSignalDestroy(e)}catch(r){console.error(`Error in plugin "${t.name}" onSignalDestroy:`,r)}S.delete(n)}}var u=1,P=2,A=4,x=8,W=16,Y=1e4,Q=new Array(Y),T=0;function Te(n){T<Y&&(n.value=void 0,n.subscribers=null,n.listeners=null,n.dependencies=null,n.computeFn=null,n.flags=0,Q[T++]=n)}var v=new WeakMap,I=new Map;function Z(n){return I.get(n)}var C=1e4,ee=new Array(C),p=0,y=0,w=!1;function _e(n){if(n.flags&P)return;let e=(y+1)%C;e===p&&(console.error("[SignalForge] Batch queue overflow \u2192 forcing flush"),R()),n.flags|=P,ee[y]=n,y=e,w||(w=!0,queueMicrotask(R))}function R(){for(w=!1;p!==y;){let n=ee[p];p=(p+1)%C,n.flags&=~P,n.flags&u&&m(n)}}var te=new Array(100),ne=0,l=null;function Ee(n){te[ne++]=l,l=n}function Le(){l=te[--ne]}var Ae=function(){return this._node.value},Pe=function(n){this._node.subscribers||(this._node.subscribers=new Set),this._node.subscribers.add(n)},xe=function(n){this._node.subscribers&&this._node.subscribers.delete(n)};function $(n,e=null){let t=T>0?Q[--T]:{value:void 0,subscribers:null,listeners:null,dependencies:null,computeFn:null,flags:0};return t.value=n,t.computeFn=e,t.flags=e?W|u:0,e&&m(t),t}function re(n,e){return l?(l!==n&&(se(n,l),Re(l,e)),n.flags&u&&n.computeFn&&m(n),n.value):(n.flags&u&&n.computeFn&&m(n),n.value)}function Ie(n,e,t){if(n.flags&W)throw new Error("Cannot set computed signal");if(typeof t=="function"&&(t=t(n.value)),Object.is(t,n.value))return;let r=n.value;n.value=t;let s=v.get(e);s&&J(s,r,t,"set"),ie(n)}function se(n,e){n.subscribers||(n.subscribers=new Set),n.subscribers.add(e)}function we(n,e){n.subscribers&&n.subscribers.delete(e)}function Re(n,e){n.dependencies||(n.dependencies=new Set),n.dependencies.has(e)||(n.dependencies.add(e),se(e._node,n))}function oe(n){if(n.dependencies){for(let e of n.dependencies)we(e._node,n);n.dependencies.clear()}}function M(n){if(!(n.flags&u)&&(n.flags|=u,_e(n),n.subscribers))for(let e of n.subscribers)M(e)}function m(n){if(n.computeFn&&!(n.flags&A)){n.flags|=A,oe(n),Ee(n);try{let e=n.computeFn();n.flags&=~u,n.flags&=~A,Object.is(e,n.value)||(n.value=e,ie(n))}finally{Le()}}}function ie(n){if(n.subscribers)for(let e of n.subscribers)M(e);if(n.flags&x&&n.listeners)for(let e of n.listeners)e(n.value)}function ae(n,e){return n.listeners||(n.listeners=new Set),n.listeners.add(e),n.flags|=x,()=>{n.listeners.delete(e),n.listeners.size===0&&(n.flags&=~x)}}function O(n){oe(n),n.subscribers&&n.subscribers.clear(),n.listeners&&n.listeners.clear(),Te(n)}function U(n){let e=$(n,null),t={get:()=>re(e,t),set:s=>Ie(e,t,s),subscribe:s=>ae(e,s),destroy:()=>{let s=v.get(t);s&&(q(s),I.delete(s),v.delete(t)),O(e)},_node:e,_peek:Ae,_addSubscriber:Pe,_removeSubscriber:xe},r=X("signal",n);return v.set(t,r.id),I.set(r.id,t),t}function Ce(n){let e,t=l;l=null;try{e=n()}finally{l=t}let r=$(e,n),s={get:()=>re(r,s),set:()=>{throw new Error("Cannot set a computed signal")},subscribe:o=>ae(r,o),destroy:()=>O(r),_node:r,_peek:()=>r.value,_addSubscriber:o=>{r.subscribers||(r.subscribers=new Set),r.subscribers.add(o)},_removeSubscriber:o=>{r.subscribers&&r.subscribers.delete(o)},_markDirty:()=>M(r),_recompute:()=>m(r)};return s}function N(n){let e=$(void 0,n);return()=>O(e)}function $e(n){let e=n();return le(),e}function le(){p!==y&&R()}function Me(n){let e=l;l=null;try{return n()}finally{l=e}}var Oe=le;var c=new Map,D=!1,ge=[];async function Ue(){return new Promise(n=>{D?ge.push(()=>n()):(D=!0,n())})}function Ne(){let n=ge.shift();n?n():D=!1}async function k(n){await Ue();try{return await n()}finally{Ne()}}function De(n,e){let t=()=>c.get(n);return{name:e.name,version:e.version,onRegister(){if(e.onRegister)try{e.onRegister()}catch(r){console.error(`[PluginManager] Error in "${n}" onRegister:`,r);let s=t();s&&s.metadata.errorCount++}},onUnregister(){if(e.onUnregister)try{e.onUnregister()}catch(r){console.error(`[PluginManager] Error in "${n}" onUnregister:`,r);let s=t();s&&s.metadata.errorCount++}},onSignalCreate(r,s){let o=t();if(o?.enabled&&e.onSignalCreate)try{e.onSignalCreate(r,s)}catch(i){console.error(`[PluginManager] Error in "${n}" onSignalCreate:`,i),o.metadata.errorCount++}},onBeforeUpdate(r){let s=t();if(!s?.enabled)return r.newValue;if(e.onBeforeUpdate)try{return e.onBeforeUpdate(r)}catch(o){return console.error(`[PluginManager] Error in "${n}" onBeforeUpdate:`,o),s.metadata.errorCount++,r.newValue}return r.newValue},onSignalUpdate(r){let s=t();if(s?.enabled&&e.onSignalUpdate)try{e.onSignalUpdate(r)}catch(o){console.error(`[PluginManager] Error in "${n}" onSignalUpdate:`,o),s.metadata.errorCount++}},onSignalDestroy(r){let s=t();if(s?.enabled&&e.onSignalDestroy)try{e.onSignalDestroy(r)}catch(o){console.error(`[PluginManager] Error in "${n}" onSignalDestroy:`,o),s.metadata.errorCount++}}}}async function Ve(n,e,t={}){await k(()=>{if(c.has(n))throw new Error(`[PluginManager] Plugin "${n}" is already registered`);let r=t.enabled!==!1,s=Date.now(),o={plugin:e,enabled:r,registeredAt:s,enabledAt:r?s:null,disabledAt:r?null:s,metadata:{enableCount:r?1:0,disableCount:r?0:1,errorCount:0}};c.set(n,o);let i=De(n,e);j(i),`${n}`})}async function He(n){return k(()=>{let e=c.get(n);return e?e.enabled?(`${n}`,!1):(e.enabled=!0,e.enabledAt=Date.now(),e.metadata.enableCount++,`${n}`,!0):(`${n}`,!1)})}async function ke(n){return k(()=>{let e=c.get(n);return e?e.enabled?(e.enabled=!1,e.disabledAt=Date.now(),e.metadata.disableCount++,`${n}`,!0):(`${n}`,!1):(`${n}`,!1)})}function Fe(n){return c.get(n)?.plugin}function Ge(n){return c.get(n)?.enabled??!1}var V=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,t)=>{if(!this.logCreates)return;let r=e.label||e.id;`${this.getElapsedTime()}${e.type}${r}`,this.verbose?this.formatTimestamp(e.createdAt):`${JSON.stringify(t)}`},onSignalUpdate:e=>{if(!this.logUpdates)return;let t=e.signal.label||e.signal.id,r=e.source?`[${e.source}]`:"";`${this.getElapsedTime()}${e.signal.type}${t}${r}`,this.verbose?this.formatTimestamp(e.timestamp):`${JSON.stringify(e.oldValue)}${JSON.stringify(e.newValue)}`},onSignalDestroy:e=>{if(!this.logDestroys)return;let t=e.label||e.id;`${this.getElapsedTime()}${e.type}${t}`},onUnregister:()=>{`${this.getElapsedTime()}`}}}},H=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(t=>t.signal.id===e).map(t=>({...t}))}createSnapshot(e){this.snapshots.set(e,[...this.history]),`${e}${this.history.length}`}restoreSnapshot(e){let t=this.snapshots.get(e);return t?(this.history=[...t],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 t=this.getStats();`${t.historySize}${t.maxHistory}`,`${t.futureSize}`,`${t.snapshotCount}`,this.history.length>0&&(`${Math.min(e,this.history.length)}`,this.history.slice(-e).forEach((s,o)=>{let i=s.signal.label||s.signal.id,g=new Date(s.timestamp).toISOString();o+1,`${g}${i}${JSON.stringify(s.oldValue)}${JSON.stringify(s.newValue)}`})),"=".repeat(60)+""}};var ue="3.0.0";function ce(n,e,t){return Math.min(Math.max(n,e),t)}function de(n){return n===void 0?100:ce(n,10,1e4)}function pe(n){return n===void 0?1e3:ce(n,100,1e4)}function fe(n,e=100){return n.length<=e?n:n.substring(0,e-3)+"..."}var _=class{constructor(e={}){this.snapshots=[];this.currentIndex=-1;this.snapshotIdCounter=0;this.signalValues=new Map;this.signalRefs=new Map;this.enabled=!0;this.isRestoring=!1;this.config={maxHistory:de(e.maxHistory),fullSnapshotInterval:e.fullSnapshotInterval??10,enableCompression:e.enableCompression??!0,verbose:e.verbose??!1}}getPlugin(){return{name:"time-travel",version:ue,onRegister:()=>{this.log("\u23F1\uFE0F Time Travel plugin activated"),this.log(` Max history: ${this.config.maxHistory}`),this.log(` Full snapshot interval: ${this.config.fullSnapshotInterval}`)},onSignalCreate:(e,t)=>{this.signalValues.set(e.id,t),this.log(`\u{1F4CC} Tracking signal: ${e.label||e.id}`)},onSignalUpdate:e=>{!this.enabled||this.isRestoring||(this.signalValues.set(e.signal.id,e.newValue),this.recordSnapshot(e))},onUnregister:()=>{this.log("\u23F1\uFE0F Time Travel plugin deactivated"),this.log(` Recorded ${this.snapshots.length} snapshots`),this.clear()}}}undo(){if(!this.canUndo())return this.log("\u23EA Cannot undo: at beginning of history"),!1;let e=this.snapshots[this.currentIndex],t=this.restoreState(this.currentIndex,"undo");return t&&(this.currentIndex--,this.log(`\u23EA Undo: ${e.signalLabel||e.signalId} \u2192 ${this.formatValue(e.oldValue)}`)),t}redo(){if(!this.canRedo())return this.log("\u23E9 Cannot redo: at end of history"),!1;this.currentIndex++;let e=this.snapshots[this.currentIndex],t=this.restoreState(this.currentIndex,"redo");return t&&this.log(`\u23E9 Redo: ${e.signalLabel||e.signalId} \u2192 ${this.formatValue(e.newValue)}`),t}jumpTo(e){if(e<0||e>=this.snapshots.length)return this.log(`\u274C Invalid index: ${e} (max: ${this.snapshots.length-1})`),!1;this.currentIndex=e;let t=this.restoreState(e);if(t){let r=this.snapshots[e];this.log(`\u{1F3AF} Jump to snapshot #${r.id}: ${r.signalLabel||r.signalId}`)}return t}canUndo(){return this.currentIndex>=0}canRedo(){return this.currentIndex<this.snapshots.length-1}getCurrentIndex(){return this.currentIndex}getSnapshotCount(){return this.snapshots.length}getTimelineState(){return{total:this.snapshots.length,current:this.currentIndex,canUndo:this.canUndo(),canRedo:this.canRedo(),snapshots:this.snapshots.map(e=>({id:e.id,timestamp:e.timestamp,signalId:e.signalId,signalLabel:e.signalLabel,preview:this.formatValue(e.newValue)}))}}getSnapshots(){return[...this.snapshots]}getSnapshotsForSignal(e){return this.snapshots.filter(t=>t.signalId===e)}getSnapshotAt(e){return this.snapshots[e]}getCurrentSnapshot(){return this.snapshots[this.currentIndex]}exportSession(){return{timestamp:Date.now(),version:"1.0.0",snapshots:[...this.snapshots],currentIndex:this.currentIndex}}importSession(e){this.snapshots=[...e.snapshots],this.currentIndex=e.currentIndex,this.snapshotIdCounter=Math.max(...this.snapshots.map(t=>t.id),0)+1,this.log(`\u{1F4E5} Imported session with ${this.snapshots.length} snapshots`)}clear(){this.snapshots=[],this.currentIndex=-1,this.snapshotIdCounter=0,this.signalValues.clear(),this.log("\u{1F5D1}\uFE0F History cleared")}setEnabled(e){this.enabled=e,this.log(`${e?"\u25B6\uFE0F":"\u23F8\uFE0F"} Recording ${e?"enabled":"paused"}`)}isEnabled(){return this.enabled}recordSnapshot(e){let t=this.snapshots.length,r=t%this.config.fullSnapshotInterval===0,s={id:this.snapshotIdCounter++,timestamp:Date.now(),signalId:e.signal.id,signalLabel:e.signal.label,signalType:e.signal.type,oldValue:e.oldValue,newValue:e.newValue,isFull:r,index:t};if(!r&&this.config.enableCompression&&(s.diff=this.computeDiff(e.oldValue,e.newValue)),this.currentIndex<this.snapshots.length-1&&(this.snapshots=this.snapshots.slice(0,this.currentIndex+1),this.log(`\u2702\uFE0F Discarded ${this.snapshots.length-this.currentIndex-1} future snapshots`)),this.snapshots.push(s),this.currentIndex=this.snapshots.length-1,this.snapshots.length>this.config.maxHistory){let o=this.snapshots.shift();this.currentIndex--,this.log(`\u{1F4E6} Pruned old snapshot #${o?.id}`)}this.log(`\u{1F4F8} Snapshot #${s.id}: ${s.signalLabel||s.signalId} = ${this.formatValue(s.newValue)}`)}restoreState(e,t="jump"){if(e<0||e>=this.snapshots.length)return!1;let r=this.snapshots[e],s=Z(r.signalId);if(!s)return this.log(`\u26A0\uFE0F Signal ${r.signalId} not found in registry`),this.signalValues.set(r.signalId,r.newValue),!1;let o;t==="undo"?o=r.oldValue:o=r.newValue,this.isRestoring=!0;try{return s.set(o),this.signalValues.set(r.signalId,o),!0}catch(i){return console.error(`[TimeTravel] Error restoring signal ${r.signalId}:`,i),!1}finally{this.isRestoring=!1}}computeDiff(e,t){if(this.isPrimitive(e)||this.isPrimitive(t))return{type:"primitive",oldValue:e,newValue:t};if(Array.isArray(e)&&Array.isArray(t))return{type:"array",added:t.filter((r,s)=>s>=e.length),removed:e.length>t.length?Array.from({length:e.length-t.length},(r,s)=>e.length-1-s):[],changed:this.computeArrayDiff(e,t)};if(typeof e=="object"&&typeof t=="object"){let r=Object.keys(e),s=Object.keys(t),o={},i=[],g={};for(let a of s)r.includes(a)||(o[a]=t[a]);for(let a of r)s.includes(a)||i.push(a);for(let a of s)r.includes(a)&&!this.isEqual(e[a],t[a])&&(g[a]={old:e[a],new:t[a]});return{type:"object",added:o,removed:i,changed:g}}return{type:"primitive",oldValue:e,newValue:t}}computeArrayDiff(e,t){let r={},s=Math.min(e.length,t.length);for(let o=0;o<s;o++)this.isEqual(e[o],t[o])||(r[o.toString()]={old:e[o],new:t[o]});return r}isPrimitive(e){return e==null||typeof e!="object"}isEqual(e,t){if(e===t)return!0;if(e==null||t==null||typeof e!=typeof t||typeof e!="object")return!1;let r=Object.keys(e),s=Object.keys(t);return r.length!==s.length?!1:r.every(o=>this.isEqual(e[o],t[o]))}formatValue(e){if(e==null)return String(e);if(typeof e=="string")return`"${e}"`;if(typeof e=="object"){let t=JSON.stringify(e);return fe(t,50)}return String(e)}log(...e){this.config.verbose&&[...e]}};function Ke(n){return new _(n)}var b=class{constructor(e={}){this.logs=[];this.logCounter=0;this.signalRegistry=new Map;this.options={level:e.level||"info",maxLogs:pe(e.maxLogs),enableConsole:e.enableConsole!==!1,filter:e.filter||(()=>!0),signalPattern:e.signalPattern||/.*/,signalIds:e.signalIds||[],includeStackTrace:e.includeStackTrace||!1,verbose:e.verbose||!1,formatter:e.formatter||this.defaultFormatter.bind(this)}}getPlugin(){return{name:"logger",version:"2.0.0",onRegister:()=>{this.logInternal("info","Logger plugin registered","create")},onSignalCreate:(e,t)=>{this.signalRegistry.set(e.id,e);let r=this.createLogEntry({type:"create",level:"info",signalId:e.id,signalLabel:e.label,metadata:e,newValue:t,message:`Signal created: ${e.label||e.id}`});this.addLog(r)},onSignalUpdate:e=>{let t=this.signalRegistry.get(e.signal.id)||e.signal,r=this.createLogEntry({type:"update",level:"debug",signalId:e.signal.id,signalLabel:t.label,metadata:t,oldValue:e.oldValue,newValue:e.newValue,message:`Signal updated: ${t.label||e.signal.id}`});this.addLog(r)},onSignalDestroy:e=>{let t=this.createLogEntry({type:"destroy",level:"info",signalId:e.id,signalLabel:e.label,metadata:e,message:`Signal destroyed: ${e.label||e.id}`});this.addLog(t),this.signalRegistry.delete(e.id)},onUnregister:()=>{this.logInternal("info","Logger plugin unregistered","destroy")}}}createLogEntry(e){let t={id:`log_${++this.logCounter}`,timestamp:Date.now(),type:e.type||"update",level:e.level||"info",signalId:e.signalId||"unknown",signalLabel:e.signalLabel,metadata:e.metadata,oldValue:e.oldValue,newValue:e.newValue,message:e.message};return this.options.includeStackTrace&&(t.stack=new Error().stack?.split(`
`).slice(3).join(`
`)),t}addLog(e){this.shouldLog(e)&&(this.logs.push(e),this.logs.length>this.options.maxLogs&&this.logs.shift(),this.options.enableConsole&&this.logToConsole(e))}shouldLog(e){if(!this.isLevelEnabled(e.level)||this.options.signalIds.length>0&&!this.options.signalIds.includes(e.signalId))return!1;let t=e.signalLabel||e.signalId;return!(!this.options.signalPattern.test(t)||!this.options.filter(e))}isLevelEnabled(e){let t=["debug","info","warn","error","off"],r=t.indexOf(this.options.level);return t.indexOf(e)>=r}logInternal(e,t,r){let s=this.createLogEntry({type:r,level:e,signalId:"__logger__",signalLabel:"Logger",message:t});this.logs.push(s),this.options.enableConsole&&this.logToConsole(s)}logToConsole(e){let t=this.options.formatter(e);switch(e.level){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":break;case"error":console.error(t);break}this.options.verbose&&e.type==="update"&&(e.oldValue,e.newValue)}defaultFormatter(e){let t=new Date(e.timestamp).toISOString(),r=e.signalLabel||e.signalId,s=this.getLogIcon(e.type),o=`[${t}] ${s} ${r}`;if(e.type==="update"){let i=this.formatValue(e.oldValue),g=this.formatValue(e.newValue);o+=` | ${i} \u2192 ${g}`}else if(e.type==="create"){let i=this.formatValue(e.newValue);o+=` = ${i}`}return e.message&&e.type==="destroy"&&(o+=` | ${e.message}`),o}getLogIcon(e){switch(e){case"create":return"\u{1F7E2}";case"update":return"\u{1F535}";case"destroy":return"\u{1F534}";default:return"\u26AA"}}formatValue(e){if(e===void 0)return"undefined";if(e===null)return"null";if(typeof e=="object")try{let t=JSON.stringify(e);return t.length>50?t.substring(0,47)+"...":t}catch{return"[Object]"}return String(e)}getLogs(){return[...this.logs]}getLogsFiltered(e){return this.logs.filter(t=>{if(e.type&&t.type!==e.type||e.level&&t.level!==e.level||e.signalId&&t.signalId!==e.signalId)return!1;if(e.signalPattern){let r=t.signalLabel||t.signalId;if(!e.signalPattern.test(r))return!1}return!(e.startTime&&t.timestamp<e.startTime||e.endTime&&t.timestamp>e.endTime)})}getLogById(e){return this.logs.find(t=>t.id===e)}getLogsForSignal(e){return this.logs.filter(t=>t.signalId===e)}getStats(){let e={total:this.logs.length,byType:{create:0,update:0,destroy:0},byLevel:{debug:0,info:0,warn:0,error:0,off:0},bySignal:{}};return this.logs.forEach(t=>{e.byType[t.type]++,e.byLevel[t.level]++;let r=t.signalLabel||t.signalId;e.bySignal[r]=(e.bySignal[r]||0)+1,(!e.oldestTimestamp||t.timestamp<e.oldestTimestamp)&&(e.oldestTimestamp=t.timestamp),(!e.newestTimestamp||t.timestamp>e.newestTimestamp)&&(e.newestTimestamp=t.timestamp)}),e}getSignalIds(){let e=new Set;return this.logs.forEach(t=>e.add(t.signalId)),Array.from(e)}getSignalLabels(){let e=new Set;return this.logs.forEach(t=>{t.signalLabel&&e.add(t.signalLabel)}),Array.from(e)}setOptions(e){Object.assign(this.options,e)}setLevel(e){this.options.level=e}setSignalPattern(e){this.options.signalPattern=e}setSignalIds(e){this.options.signalIds=e}setConsoleEnabled(e){this.options.enableConsole=e}setVerbose(e){this.options.verbose=e}clear(){this.logs=[],this.logCounter=0}exportLogs(){return JSON.stringify({timestamp:Date.now(),options:this.options,logs:this.logs,stats:this.getStats()},null,2)}importLogs(e){try{let t=JSON.parse(e);t.logs&&Array.isArray(t.logs)&&(this.logs=t.logs,this.logCounter=this.logs.length)}catch(t){console.error("Failed to import logs:",t)}}search(e){let t=e.toLowerCase();return this.logs.filter(r=>{let s=(r.signalLabel||r.signalId).toLowerCase(),o=(r.message||"").toLowerCase(),i=this.formatValue(r.oldValue).toLowerCase(),g=this.formatValue(r.newValue).toLowerCase();return s.includes(t)||o.includes(t)||i.includes(t)||g.includes(t)})}};function je(n){return new b(n)}function Xe(){return new b({level:"warn",enableConsole:!0,maxLogs:100})}function Je(){let n=typeof global<"u"?global:void 0,e=typeof window<"u"?window:void 0;return typeof navigator<"u"&&navigator.product==="ReactNative"||e?.navigator?.product==="ReactNative"||n?.HermesInternal||n?.__fbBatchedBridgeConfig||n?.nativeModuleProxy||n?.__turboModuleProxy?"react-native":e?.localStorage||n?.localStorage?"web":"node"}function he(n,e=!1){let t=new WeakSet;try{return JSON.stringify(n,(r,s)=>{if(s===void 0)return"__undefined__";if(s===null)return null;if(typeof s=="function")return e&&`${r}`,"__function__";if(s instanceof Date)return{__type__:"Date",value:s.toISOString()};if(s instanceof RegExp)return{__type__:"RegExp",value:s.toString()};if(typeof s=="object"&&s!==null){if(t.has(s))return e&&`${r}`,"__circular__";t.add(s)}return s})}catch(r){e&&console.error("[StorageAdapter] Serialization error:",r);try{return JSON.stringify(n)}catch{return"{}"}}}function ye(n,e=!1){try{return JSON.parse(n,(t,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 s=r.value.match(/^\/(.+)\/([gimuy]*)$/);if(s)return new RegExp(s[1],s[2])}}return r}})}catch(t){return e&&console.error("[StorageAdapter] Deserialization error:",t),null}}var F=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??z,this.serialize=e.serialize||(t=>he(t,this.devMode)),this.deserialize=e.deserialize||(t=>ye(t,this.devMode))}getKey(e){return`${this.prefix}${e}`}async load(e){try{let t=localStorage.getItem(this.getKey(e));return t===null?null:this.deserialize(t)}catch(t){return this.devMode&&console.error(`[StorageAdapter] Failed to load "${e}":`,t),null}}async save(e,t){try{let r=this.serialize(t);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(t){throw this.devMode&&console.error(`[StorageAdapter] Failed to clear "${e}":`,t),t}}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 t=0;t<localStorage.length;t++){let r=localStorage.key(t);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 t of e)await this.clear(t)}catch(e){throw this.devMode&&console.error("[StorageAdapter] Failed to clear all:",e),e}}},G=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??z,this.serialize=e.serialize||(t=>he(t,this.devMode)),this.deserialize=e.deserialize||(t=>ye(t,this.devMode));try{this.AsyncStorage=K("@react-native-async-storage/async-storage").default}catch{try{this.AsyncStorage=K("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 t=await this.AsyncStorage.getItem(this.getKey(e));return t===null?null:this.deserialize(t)}catch(t){return this.devMode&&console.error(`[StorageAdapter] Failed to load "${e}":`,t),null}}async save(e,t){if(!this.AsyncStorage){this.devMode;return}try{let r=this.serialize(t);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(t){throw this.devMode&&console.error(`[StorageAdapter] Failed to clear "${e}":`,t),t}}isAvailable(){return this.AsyncStorage!==null}async getAllKeys(){if(!this.AsyncStorage)return[];try{return(await this.AsyncStorage.getAllKeys()).filter(t=>t.startsWith(this.prefix)).map(t=>t.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 t=(await this.getAllKeys()).map(r=>this.getKey(r));await this.AsyncStorage.multiRemove(t)}catch(e){throw this.devMode&&console.error("[StorageAdapter] Failed to clear all:",e),e}}},B=class{constructor(e={}){this.storage=new Map;this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??z,this.devMode}getKey(e){return`${this.prefix}${e}`}async load(e){let t=this.storage.get(this.getKey(e));return t!==void 0?t:null}async save(e,t){let r=JSON.parse(JSON.stringify(t));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 t of this.storage.keys())t.startsWith(this.prefix)&&e.push(t.slice(this.prefix.length));return e}async clearAll(){let e=await this.getAllKeys();for(let t of e)this.storage.delete(this.getKey(t))}},f=null;function qe(n={}){if(f)return f;switch(Je()){case"web":f=new F(n);break;case"react-native":f=new G(n);break;case"node":case"unknown":default:f=new B(n);break}return f}function me(n,e={}){let t=e.adapter||qe(),r=e.key||`signal_${Math.random().toString(36).slice(2)}`,s=e.serialize||(a=>a),o=e.deserialize||(a=>a);t.load(r).then(a=>{if(a!==null)try{let d=o(a);n.set(d)}catch(d){e.onError&&e.onError(d)}}).catch(a=>{e.onError&&e.onError(a)});let i,g=N(()=>{let a=n.get(),d=()=>{try{let E=s(a);t.save(r,E).catch(be=>{e.onError&&e.onError(be)})}catch(E){e.onError&&e.onError(E)}};e.debounce?(i!==void 0&&clearTimeout(i),i=setTimeout(d,e.debounce)):d()});return()=>{g(),i!==void 0&&clearTimeout(i)}}function We(n,e,t={}){let r=U(e);return me(r,{...t,key:n}),r}var z=typeof globalThis.__DEV__<"u"?globalThis.__DEV__:process.env.NODE_ENV!=="production";export{V as LoggerPlugin,b as LoggerPluginEnhanced,H as TimeTravelPlugin,_ as TimeTravelPluginEnhanced,$e as batch,Ce as createComputed,N as createEffect,je as createLogger,Xe as createMinimalLogger,We as createPersistentSignal,U as createSignal,Ke as createTimeTravelPlugin,ke as disablePlugin,He as enablePlugin,Oe as flushSync,Fe as getPlugin,Ge as isPluginEnabled,me as persist,Ve as registerPlugin,Me as untrack};