UNPKG

signalforge

Version:

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

4 lines (3 loc) 27.5 kB
"use strict";var I=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var Ue=(n,e)=>{for(var t in e)I(n,t,{get:e[t],enumerable:!0})},Ne=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Me(e))!Oe.call(n,s)&&s!==t&&I(n,s,{get:()=>e[s],enumerable:!(r=$e(e,s))||r.enumerable});return n};var De=n=>Ne(I({},"__esModule",{value:!0}),n);var rt={};Ue(rt,{LoggerPlugin:()=>A,LoggerPluginEnhanced:()=>f,TimeTravelPlugin:()=>P,TimeTravelPluginEnhanced:()=>S,batch:()=>ue,createComputed:()=>ge,createEffect:()=>L,createLogger:()=>Pe,createMinimalLogger:()=>xe,createPersistentSignal:()=>Re,createSignal:()=>E,createTimeTravelPlugin:()=>Ae,disablePlugin:()=>me,enablePlugin:()=>ye,flushSync:()=>pe,getPlugin:()=>be,isPluginEnabled:()=>Se,persist:()=>K,registerPlugin:()=>he,untrack:()=>de});module.exports=De(rt);var y=[],v=new Map,Ve=0,w=!0;function He(){return`signal_${++Ve}_${Date.now()}`}function X(n){if(y.some(e=>e.name===n.name))throw new Error(`Plugin "${n.name}" is already registered`);if(y.push(n),n.onRegister)try{n.onRegister()}catch(e){console.error(`Error in plugin "${n.name}" onRegister:`,e)}`${n.name}`}function J(n,e,t){let r={id:He(),type:n,createdAt:Date.now(),label:t};if(v.set(r.id,r),w){for(let s of y)if(s.onSignalCreate)try{s.onSignalCreate(r,e)}catch(o){console.error(`Error in plugin "${s.name}" onSignalCreate:`,o)}}return r}function q(n,e,t,r="set"){if(!w)return;let s=v.get(n);if(!s)return;let o={signal:s,oldValue:e,newValue:t,timestamp:Date.now(),source:r};for(let i of y)if(i.onSignalUpdate)try{i.onSignalUpdate(o)}catch(g){console.error(`Error in plugin "${i.name}" onSignalUpdate:`,g)}}function W(n){if(!w)return;let e=v.get(n);if(e){for(let t of y)if(t.onSignalDestroy)try{t.onSignalDestroy(e)}catch(r){console.error(`Error in plugin "${t.name}" onSignalDestroy:`,r)}v.delete(n)}}var u=1,C=2,R=4,$=8,Y=16,Q=1e4,Z=new Array(Q),_=0;function ke(n){_<Q&&(n.value=void 0,n.subscribers=null,n.listeners=null,n.dependencies=null,n.computeFn=null,n.flags=0,Z[_++]=n)}var T=new WeakMap,M=new Map;function ee(n){return M.get(n)}var N=1e4,te=new Array(N),p=0,m=0,O=!1;function Fe(n){if(n.flags&C)return;let e=(m+1)%N;e===p&&(console.error("[SignalForge] Batch queue overflow \u2192 forcing flush"),U()),n.flags|=C,te[m]=n,m=e,O||(O=!0,queueMicrotask(U))}function U(){for(O=!1;p!==m;){let n=te[p];p=(p+1)%N,n.flags&=~C,n.flags&u&&b(n)}}var ne=new Array(100),re=0,l=null;function Ge(n){ne[re++]=l,l=n}function Be(){l=ne[--re]}var ze=function(){return this._node.value},Ke=function(n){this._node.subscribers||(this._node.subscribers=new Set),this._node.subscribers.add(n)},je=function(n){this._node.subscribers&&this._node.subscribers.delete(n)};function D(n,e=null){let t=_>0?Z[--_]:{value:void 0,subscribers:null,listeners:null,dependencies:null,computeFn:null,flags:0};return t.value=n,t.computeFn=e,t.flags=e?Y|u:0,e&&b(t),t}function se(n,e){return l?(l!==n&&(oe(n,l),qe(l,e)),n.flags&u&&n.computeFn&&b(n),n.value):(n.flags&u&&n.computeFn&&b(n),n.value)}function Xe(n,e,t){if(n.flags&Y)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=T.get(e);s&&q(s,r,t,"set"),ae(n)}function oe(n,e){n.subscribers||(n.subscribers=new Set),n.subscribers.add(e)}function Je(n,e){n.subscribers&&n.subscribers.delete(e)}function qe(n,e){n.dependencies||(n.dependencies=new Set),n.dependencies.has(e)||(n.dependencies.add(e),oe(e._node,n))}function ie(n){if(n.dependencies){for(let e of n.dependencies)Je(e._node,n);n.dependencies.clear()}}function V(n){if(!(n.flags&u)&&(n.flags|=u,Fe(n),n.subscribers))for(let e of n.subscribers)V(e)}function b(n){if(n.computeFn&&!(n.flags&R)){n.flags|=R,ie(n),Ge(n);try{let e=n.computeFn();n.flags&=~u,n.flags&=~R,Object.is(e,n.value)||(n.value=e,ae(n))}finally{Be()}}}function ae(n){if(n.subscribers)for(let e of n.subscribers)V(e);if(n.flags&$&&n.listeners)for(let e of n.listeners)e(n.value)}function le(n,e){return n.listeners||(n.listeners=new Set),n.listeners.add(e),n.flags|=$,()=>{n.listeners.delete(e),n.listeners.size===0&&(n.flags&=~$)}}function H(n){ie(n),n.subscribers&&n.subscribers.clear(),n.listeners&&n.listeners.clear(),ke(n)}function E(n){let e=D(n,null),t={get:()=>se(e,t),set:s=>Xe(e,t,s),subscribe:s=>le(e,s),destroy:()=>{let s=T.get(t);s&&(W(s),M.delete(s),T.delete(t)),H(e)},_node:e,_peek:ze,_addSubscriber:Ke,_removeSubscriber:je},r=J("signal",n);return T.set(t,r.id),M.set(r.id,t),t}function ge(n){let e,t=l;l=null;try{e=n()}finally{l=t}let r=D(e,n),s={get:()=>se(r,s),set:()=>{throw new Error("Cannot set a computed signal")},subscribe:o=>le(r,o),destroy:()=>H(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:()=>V(r),_recompute:()=>b(r)};return s}function L(n){let e=D(void 0,n);return()=>H(e)}function ue(n){let e=n();return ce(),e}function ce(){p!==m&&U()}function de(n){let e=l;l=null;try{return n()}finally{l=e}}var pe=ce;var c=new Map,k=!1,fe=[];async function We(){return new Promise(n=>{k?fe.push(()=>n()):(k=!0,n())})}function Ye(){let n=fe.shift();n?n():k=!1}async function F(n){await We();try{return await n()}finally{Ye()}}function Qe(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 he(n,e,t={}){await F(()=>{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=Qe(n,e);X(i),`${n}`})}async function ye(n){return F(()=>{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 me(n){return F(()=>{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 be(n){return c.get(n)?.plugin}function Se(n){return c.get(n)?.enabled??!1}var A=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()}`}}}},P=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 ve="3.0.0";function Te(n,e,t){return Math.min(Math.max(n,e),t)}function _e(n){return n===void 0?100:Te(n,10,1e4)}function Ee(n){return n===void 0?1e3:Te(n,100,1e4)}function Le(n,e=100){return n.length<=e?n:n.substring(0,e-3)+"..."}var S=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:_e(e.maxHistory),fullSnapshotInterval:e.fullSnapshotInterval??10,enableCompression:e.enableCompression??!0,verbose:e.verbose??!1}}getPlugin(){return{name:"time-travel",version:ve,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=ee(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 Le(t,50)}return String(e)}log(...e){this.config.verbose&&[...e]}};function Ae(n){return new S(n)}var f=class{constructor(e={}){this.logs=[];this.logCounter=0;this.signalRegistry=new Map;this.options={level:e.level||"info",maxLogs:Ee(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 Pe(n){return new f(n)}function xe(){return new f({level:"warn",enableConsole:!0,maxLogs:100})}function tt(){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 Ie(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 we(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 G=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??j,this.serialize=e.serialize||(t=>Ie(t,this.devMode)),this.deserialize=e.deserialize||(t=>we(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}}},B=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??j,this.serialize=e.serialize||(t=>Ie(t,this.devMode)),this.deserialize=e.deserialize||(t=>we(t,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 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}}},z=class{constructor(e={}){this.storage=new Map;this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??j,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))}},h=null;function nt(n={}){if(h)return h;switch(tt()){case"web":h=new G(n);break;case"react-native":h=new B(n);break;case"node":case"unknown":default:h=new z(n);break}return h}function K(n,e={}){let t=e.adapter||nt(),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=L(()=>{let a=n.get(),d=()=>{try{let x=s(a);t.save(r,x).catch(Ce=>{e.onError&&e.onError(Ce)})}catch(x){e.onError&&e.onError(x)}};e.debounce?(i!==void 0&&clearTimeout(i),i=setTimeout(d,e.debounce)):d()});return()=>{g(),i!==void 0&&clearTimeout(i)}}function Re(n,e,t={}){let r=E(e);return K(r,{...t,key:n}),r}var j=typeof globalThis.__DEV__<"u"?globalThis.__DEV__:process.env.NODE_ENV!=="production";