@quantajs/core
Version:
A compact, scalable, and developer-friendly state management library designed for any JavaScript environment. It includes a reactivity system that enables efficient and flexible data handling, making complex state management easy.
24 lines (19 loc) • 22 kB
JavaScript
/*! MIT License
Copyright (c) 2025 QuantaJS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
(function(h,R){typeof exports=="object"&&typeof module<"u"?R(exports):typeof define=="function"&&define.amd?define(["exports"],R):(h=typeof globalThis<"u"?globalThis:h||self,R(h.QuantaJS={}))})(this,(function(h){"use strict";var R=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(R||{});class C{config;isNode;hasConsole;constructor(e={}){this.config={level:1,prefix:"",timestamp:!0,colors:!0,...e},this.isNode=this.detectNodeEnvironment(),this.hasConsole=this.detectConsole()}detectNodeEnvironment(){return typeof process<"u"&&!!process.versions&&!!process.versions.node}detectConsole(){return typeof console<"u"&&typeof console.log=="function"}getTimestamp(){if(!this.config.timestamp)return"";try{return`[${new Date().toISOString()}] `}catch{return""}}getColorCode(e){return!this.config.colors||!this.isNode?"":{0:"\x1B[36m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"}[e]||""}getResetCode(){return this.config.colors&&this.isNode?"\x1B[0m":""}getLevelName(e){const r={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"};return e in r?r[e]:"LOG"}formatMessage(e,r){const t=this.getTimestamp(),n=this.config.prefix?`[${this.config.prefix}] `:"",o=`[${this.getLevelName(e)}]`,a=this.getColorCode(e),f=this.getResetCode();return`${a}${t}${n}${o} ${r}${f}`}safeConsoleCall(e,r,...t){if(this.hasConsole)try{const n=console[e]||console.log;typeof n=="function"&&n(r,...t)}catch{try{console.log&&typeof console.log=="function"&&console.log(r,...t)}catch{}}}shouldLog(e){return e>=this.config.level}debug(e,...r){if(!this.shouldLog(0))return;const t=this.formatMessage(0,e);this.safeConsoleCall("debug",t,...r)}info(e,...r){this.log(e,...r)}log(e,...r){if(!this.shouldLog(1))return;const t=this.formatMessage(1,e);this.safeConsoleCall("log",t,...r)}warn(e,...r){if(!this.shouldLog(2))return;const t=this.formatMessage(2,e);this.safeConsoleCall("warn",t,...r)}error(e,...r){if(!this.shouldLog(3))return;const t=this.formatMessage(3,e);this.safeConsoleCall("error",t,...r)}configure(e){this.config={...this.config,...e}}setLevel(e){this.config.level=e}getLevel(){return this.config.level}child(e){const r=this.config.prefix?`${this.config.prefix}:${e}`:e;return new C({...this.config,prefix:r})}}const s=new C,Q=i=>new C(i);class T{subscribers;constructor(){this.subscribers=new Set}depend(e){try{e&&this.subscribers.add(e)}catch(r){s.error(`Dependency: Failed to add dependency: ${r instanceof Error?r.message:String(r)}`)}}notify(e){try{new Set(this.subscribers).forEach(t=>{try{e!==void 0?t(e):t()}catch(n){s.warn(`Dependency: Subscriber callback failed: ${n instanceof Error?n.message:String(n)}`)}})}catch(r){s.error(`Dependency: Failed to notify subscribers: ${r instanceof Error?r.message:String(r)}`)}}remove(e){try{this.subscribers.delete(e)}catch(r){s.error(`Dependency: Failed to remove dependency: ${r instanceof Error?r.message:String(r)}`)}}clear(){try{this.subscribers.clear()}catch(e){s.error(`Dependency: Failed to clear dependencies: ${e instanceof Error?e.message:String(e)}`)}}get getSubscribers(){return new Set(this.subscribers)}}const O=new WeakMap;let k=null,K=!1;const ce=new Set,w=[];function S(i,e){try{const r=O.get(i);if(r&&r[e]){const t=r[e].getSubscribers;t.size>0&&t.forEach(o=>{if(!K){if(w.includes(o)){const a=`Circular dependency detected: Effect "${o.name||"anonymous"}" triggered itself. Stack trace: ${w.map(g=>g.name||"anonymous").join(" -> ")}`;s.error(`Effect: ${a}`);const f=[...w,o].map(g=>g.name||"anonymous");throw s.error(`Effect: Circular dependency path: ${f.join(" -> ")}`),new Error(a)}try{o()}catch(a){throw s.error(`Effect: Failed to execute effect "${o.name||"anonymous"}": ${a instanceof Error?a.message:String(a)}`),a}}})}}catch(r){throw s.error(`Effect: Trigger failed for property "${String(e)}": ${r instanceof Error?r.message:String(r)}`),r}}function $(i,e){try{let r=O.get(i);r||O.set(i,r={}),r[e]||(r[e]=new T),k&&r[e].depend(k)}catch(r){throw s.error(`Effect: Failed to track dependency for property "${String(e)}": ${r instanceof Error?r.message:String(r)}`),r}}function B(i){const e=()=>{if(w.includes(i)){const r=`Circular dependency detected: Effect "${i.name||"anonymous"}" triggered itself. Stack trace: ${w.map(n=>n.name||"anonymous").join(" -> ")}`;s.error(`Effect: ${r}`);const t=[...w,i].map(n=>n.name||"anonymous");throw s.error(`Effect: Circular dependency path: ${t.join(" -> ")}`),s.error(`Effect: Current effect stack depth: ${w.length}`),new Error(r)}try{w.push(i),k=i,i()}catch(r){throw s.error(`Effect: Effect "${i.name||"anonymous"}" failed: ${r instanceof Error?r.message:String(r)}`),s.error(`Effect: Effect stack at failure: ${w.map(t=>t.name||"anonymous").join(" -> ")}`),r}finally{w.pop(),k=w[w.length-1]||null}};return e(),e}const j=i=>{try{let e,r=!0;const t=B(()=>{try{e=i(),r=!1}catch(o){throw s.error(`Computed: Failed to compute value: ${o instanceof Error?o.message:String(o)}`),o}}),n={get value(){try{return r&&t(),$(n,"value"),e}catch(o){throw s.error(`Computed: Failed to get computed value: ${o instanceof Error?o.message:String(o)}`),o}}};return n}catch(e){throw s.error(`Computed: Failed to create computed value: ${e instanceof Error?e.message:String(e)}`),e}};function H(i){return new Proxy(i,{get(e,r){try{if(r==="size")return $(e,"size"),e.size;if(r==="get"){const t=Reflect.get(e,r);return n=>{try{const o=t.call(e,n);return $(e,n),o}catch(o){throw s.error(`Reactive: Failed to get collection value for key "${String(n)}": ${o instanceof Error?o.message:String(o)}`),o}}}if(r==="set"||r==="add"||r==="delete"){const t=Reflect.get(e,r);return(...n)=>{try{const o=t.apply(e,n);if(S(e,"size"),r==="set"){const[a]=n;S(e,a)}return o}catch(o){throw s.error(`Reactive: Failed to execute collection operation "${String(r)}": ${o instanceof Error?o.message:String(o)}`),o}}}if(r==="clear"){const t=Reflect.get(e,r);return()=>{try{const n=t.apply(e);return S(e,"size"),n}catch(n){throw s.error(`Reactive: Failed to clear collection: ${n instanceof Error?n.message:String(n)}`),n}}}return $(e,r),Reflect.get(e,r)}catch(t){throw s.error(`Reactive: Failed to access collection property "${String(r)}": ${t instanceof Error?t.message:String(t)}`),t}}})}function J(i){try{return i instanceof Map||i instanceof Set?H(i):new Proxy(i,{get(e,r,t){try{const n=Reflect.get(e,r,t);return r==="size"&&(e instanceof Map||e instanceof Set)?($(e,"size"),n):($(e,r),typeof n=="object"&&n!==null?J(n):n)}catch(n){throw s.error(`Reactive: Failed to get property "${String(r)}": ${n instanceof Error?n.message:String(n)}`),n}},set(e,r,t,n){try{const o=e[r],a=Reflect.set(e,r,t,n);return(o!==t||isNaN(o)&&isNaN(t))&&S(e,r),a}catch(o){throw s.error(`Reactive: Failed to set property "${String(r)}": ${o instanceof Error?o.message:String(o)}`),o}},deleteProperty(e,r){try{const t=r in e,n=Reflect.deleteProperty(e,r);return t&&S(e,r),n}catch(t){throw s.error(`Reactive: Failed to delete property "${String(r)}": ${t instanceof Error?t.message:String(t)}`),t}},has(e,r){try{return $(e,r),Reflect.has(e,r)}catch(t){throw s.error(`Reactive: Failed to check property "${String(r)}" existence: ${t instanceof Error?t.message:String(t)}`),t}},ownKeys(e){try{return $(e,"keys"),Reflect.ownKeys(e)}catch(r){throw s.error(`Reactive: Failed to get own keys: ${r instanceof Error?r.message:String(r)}`),r}},getOwnPropertyDescriptor(e,r){try{return $(e,r),Reflect.getOwnPropertyDescriptor(e,r)}catch(t){throw s.error(`Reactive: Failed to get property descriptor for "${String(r)}": ${t instanceof Error?t.message:String(t)}`),t}}})}catch(e){throw s.error(`Reactive: Failed to create reactive object: ${e instanceof Error?e.message:String(e)}`),e}}const z=i=>{try{return J(i)}catch(e){throw s.error(`Reactive: Failed to create reactive object: ${e instanceof Error?e.message:String(e)}`),e}},L=(i,e,r={})=>{const{deep:t=!1,immediate:n=!0}=r;let o;if(t){const a=c=>JSON.stringify(c);let f=null;const g=100,y=()=>{try{const c=i(),l=a(c);if(o===void 0)n&&e(c,c);else{const v=a(o);l!==v&&e(c,o)}o=c}catch(c){s.warn(`Watch (deep): Poll failed: ${c instanceof Error?c.message:String(c)}`)}};return y(),f=setInterval(y,g),()=>{f&&(clearInterval(f),f=null)}}else try{return B(()=>{try{const f=i();n&&o===void 0?e(f,f):o!==void 0&&f!==o&&e(f,o),o=f}catch(f){throw s.error(`Watch: Failed to execute watch source function: ${f instanceof Error?f.message:String(f)}`),f}})}catch(a){throw s.error(`Watch: Failed to create watcher: ${a instanceof Error?a.message:String(a)}`),a}},X=i=>{try{return new Proxy(i,{get(r,t,n){try{if(t in r.state)return Reflect.get(r.state,t);if(t in r.getters){const o=Reflect.get(r.getters,t);return o&&typeof o=="object"&&"value"in o?o.value:o}return t in r.actions?Reflect.get(r.actions,t):Reflect.get(r,t,n)}catch(o){throw s.error(`FlattenStore: Failed to get property "${t}": ${o instanceof Error?o.message:String(o)}`),o}},set(r,t,n,o){try{const a=t in r.state,f=a?Reflect.set(r.state,t,n):Reflect.set(r,t,n,o);return f&&a&&(S(r.state,t),r.notifyAll?.()),f}catch(a){throw s.error(`FlattenStore: Failed to set property "${t}": ${a instanceof Error?a.message:String(a)}`),a}}})}catch(e){throw s.error(`FlattenStore: Failed to create flattened store: ${e instanceof Error?e.message:String(e)}`),e}};function Y(i,e){let r,t;const n=((...o)=>{try{t=o,r&&clearTimeout(r),r=setTimeout(()=>{try{t&&(i(...t),t=void 0)}catch(a){throw s.error(`Debounce: Failed to execute debounced function: ${a instanceof Error?a.message:String(a)}`),a}},e)}catch(a){throw s.error(`Debounce: Failed to schedule debounced function: ${a instanceof Error?a.message:String(a)}`),a}});return n.flush=()=>{try{r&&(clearTimeout(r),r=void 0),t&&(i(...t),t=void 0)}catch(o){throw s.error(`Debounce: Failed to flush debounced function: ${o instanceof Error?o.message:String(o)}`),o}},n.cancel=()=>{try{r&&(clearTimeout(r),r=void 0),t=void 0}catch(o){throw s.error(`Debounce: Failed to cancel debounced function: ${o instanceof Error?o.message:String(o)}`),o}},n}function W(i,e,r,t,n){const{adapter:o,serialize:a=JSON.stringify,deserialize:f=JSON.parse,debounceMs:g=300,include:y,exclude:c,transform:l,version:v=1,migrations:U={},onError:P,validator:N}=t;let F=!1,D=!1,b=null,p=null;const se=()=>{const u=i();let d={...u};return y&&(d=y.reduce((m,M)=>(M in u&&(m[M]=u[M]),m),{})),c&&c.forEach(m=>delete d[m]),l?.out&&(d=l.out(d)),N&&!N(d)?(s.warn(`Persistence: Slice validation failed for ${n||"store"}—skipping watch trigger`),null):d},x=Y(async()=>{if(!F)try{const u=i();let d={...u};if(y&&(d=y.reduce((E,A)=>(A in u&&(E[A]=u[A]),E),{})),c&&c.forEach(E=>delete d[E]),l?.out&&(d=l.out(d)),N&&!N(d))throw new Error("Data validation failed before saving");const m={data:d,version:v,timestamp:Date.now(),storeName:n||"anonymous"},M=a(m);await o.write(M),s.debug(`Persistence: Saved slice for ${n||"store"}`)}catch(u){const d=u instanceof Error?u:new Error(String(u));P?.(d,"write"),console.warn(`Failed to persist state: ${d.message}`)}},g),G=async()=>{try{F=!0;const u=await o.read();if(u){const d=f(u);let{data:m,version:M}=d;if(M<v)for(let E=M+1;E<=v;E++)U[E]&&(m=U[E](m));if(l?.in&&(m=l.in(m)),N&&!N(m))throw new Error("Loaded data failed validation");e(m),r()}D=!0}catch(u){const d=u instanceof Error?u:new Error(String(u));P?.(d,"read"),console.warn(`Failed to load persisted state: ${d.message}`),D=!0}finally{F=!1}},ie=()=>{o.subscribe&&!b&&(b=o.subscribe(u=>{if(!F&&D){F=!0;try{const d=f(u);let m=d.data||d;l?.in&&(m=l.in(m)),e(m),r()}catch(d){console.warn("Cross-tab sync failed:",d)}finally{F=!1}}}))},ae=()=>{if(!p)try{p=L(()=>{if(F)return null;const u=se();return u?a({data:u}):null},()=>{D&&x()},{deep:!0}),s.debug(`Persistence: Auto-save watcher active for ${n||"store"}`)}catch(u){const d=u instanceof Error?u:new Error(String(u));P?.(d,"watch-setup"),s.warn(`Persistence: Auto-save setup failed for ${n||"store"}: ${d.message}`)}};return G().then(()=>{ae(),ie()}),{async save(){await x.flush()},load:G,async clear(){try{p&&(p(),p=null),await o.remove(),b&&(b(),b=null)}catch(u){const d=u instanceof Error?u:new Error(String(u));throw P?.(d,"remove"),d}},getAdapter(){return o},isRehydrated(){return D},destroy(){p&&(p(),p=null),b&&(b(),b=null),x.cancel()}}}class q{migrations=new Map;constructor(e=[]){e.forEach(r=>{this.addMigration(r.version,r.migrate)})}addMigration(e,r){this.migrations.set(e,r),s.log(`Migration: Added migration for version ${e}`)}removeMigration(e){const r=this.migrations.has(e);this.migrations.delete(e),r?s.log(`Migration: Removed migration for version ${e}`):s.warn(`Migration: No migration found for version ${e} to remove`)}getVersions(){return Array.from(this.migrations.keys()).sort((e,r)=>e-r)}hasMigration(e){return this.migrations.has(e)}getHighestVersion(){const e=this.getVersions();return e.length>0?Math.max(...e):0}migrate(e,r,t){if(r===t)return e;if(r>t)throw new Error(`Cannot migrate from version ${r} to ${t} (downgrade not supported)`);s.log(`Migration: Starting migration from version ${r} to ${t}`);let n=e;for(let o=r+1;o<=t;o++){const a=this.migrations.get(o);if(a)try{s.log(`Migration: Applying migration for version ${o}`),n=a(n),s.log(`Migration: Successfully applied migration for version ${o}`)}catch(f){const g=`Migration ${o} failed: ${f instanceof Error?f.message:String(f)}`;throw s.warn(g),new Error(g)}else s.log(`Migration: No migration found for version ${o}, skipping`)}return s.log(`Migration: Successfully completed migration from version ${r} to ${t}`),n}validateMigrations(){s.log("Migration: Starting migration validation...");const e=[],r=this.getVersions();if(r.length===0)return s.log("Migration: No migrations to validate"),{valid:!0,errors:[]};s.log(`Migration: Validating ${r.length} migrations`);const t={test:!0};for(let o=0;o<r.length-1;o++){const a=r[o],f=r[o+1];try{s.log(`Migration: Testing migration from version ${a} to ${f}`),this.migrate(t,a,f),s.log(`Migration: Successfully validated migration from version ${a} to ${f}`)}catch(g){const y=`Migration from ${a} to ${f} failed: ${g instanceof Error?g.message:String(g)}`;s.warn(y),e.push(y)}}const n=e.length===0;return n?s.log("Migration: All migrations validated successfully"):s.warn(`Migration: Validation failed with ${e.length} errors`),{valid:n,errors:e}}}function Z(i){const e=new q;return i.migrations?(s.log(`Migration: Creating migration manager with ${Object.keys(i.migrations).length} migrations`),Object.entries(i.migrations).forEach(([r,t])=>{const n=parseInt(r,10);isNaN(n)?s.warn(`Migration: Invalid version number "${r}", skipping`):e.addMigration(n,t)})):s.log("Migration: Creating migration manager with no migrations"),e}const _={addProperty(i,e){return r=>(s.log(`Migration: Added property "${String(i)}" with default value:`,e),{...r,[i]:e})},removeProperty(i){return e=>{const{[i]:r,...t}=e;return s.log(`Migration: Removed property "${String(i)}" with value:`,r),t}},renameProperty(i,e){return r=>{const{[i]:t,...n}=r;return s.log(`Migration: Renamed property "${String(i)}" to "${String(e)}" with value:`,t),{...n,[e]:t}}},transformProperty(i,e){return r=>{const t=r[i],n=e(t);return s.log(`Migration: Transformed property "${String(i)}" from:`,t,"to:",n),{...r,[i]:n}}}};class ee{constructor(e){if(this.key=e,typeof window>"u"||!window.localStorage)throw new Error("LocalStorage is not available in this environment")}read(){try{const e=localStorage.getItem(this.key);return e?JSON.parse(e):null}catch(e){return s.warn(`Failed to read from localStorage: ${e instanceof Error?e.message:String(e)}`),null}}write(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch(r){throw r instanceof Error&&r.name==="QuotaExceededError"&&s.warn("LocalStorage quota exceeded"),r}}remove(){localStorage.removeItem(this.key)}subscribe(e){const r=t=>{if(t.key===this.key&&t.newValue)try{e(JSON.parse(t.newValue))}catch(n){s.warn("Failed to parse storage event data:",n)}};return window.addEventListener("storage",r),()=>window.removeEventListener("storage",r)}}class re{constructor(e){if(this.key=e,typeof window>"u"||!window.sessionStorage)throw new Error("SessionStorage is not available in this environment")}read(){try{const e=sessionStorage.getItem(this.key);return e?JSON.parse(e):null}catch(e){return s.warn(`Failed to read from sessionStorage: ${e instanceof Error?e.message:String(e)}`),null}}write(e){try{sessionStorage.setItem(this.key,JSON.stringify(e))}catch(r){throw r instanceof Error&&r.name==="QuotaExceededError"&&s.warn("SessionStorage quota exceeded"),r}}remove(){sessionStorage.removeItem(this.key)}subscribe(e){const r=t=>{if(t.key===this.key&&t.newValue)try{e(JSON.parse(t.newValue))}catch(n){s.warn("Failed to parse storage event data:",n)}};return window.addEventListener("storage",r),()=>window.removeEventListener("storage",r)}}class te{constructor(e,r="quantajs",t="stores",n=1){this.key=e,this.dbName=r,this.storeName=t,this.version=n}async read(){try{const t=(await this.openDB()).transaction([this.storeName],"readonly").objectStore(this.storeName);return new Promise((n,o)=>{const a=t.get(this.key);a.onsuccess=()=>n(a.result?.data||null),a.onerror=()=>o(a.error)})}catch(e){return s.warn(`IndexedDB read failed: ${e instanceof Error?e.message:String(e)}`),null}}async write(e){const n=(await this.openDB()).transaction([this.storeName],"readwrite").objectStore(this.storeName);return new Promise((o,a)=>{const f={key:this.key,data:e,timestamp:Date.now()},g=n.put(f);g.onsuccess=()=>o(),g.onerror=()=>a(g.error)})}async remove(){const t=(await this.openDB()).transaction([this.storeName],"readwrite").objectStore(this.storeName);return new Promise((n,o)=>{const a=t.delete(this.key);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}async openDB(){return new Promise((e,r)=>{const t=indexedDB.open(this.dbName,this.version);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"key"})},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error)})}}const I=new Map,V=new WeakMap,oe=(i,e)=>{try{if(I.has(i)){const c=`Store with name "${i}" already exists.`;throw s.error(`Store: ${c}`),new Error(c)}const r=e.state(),t=z(r),n=new T,o={};if(e.getters)for(const c in e.getters)try{const l=e.getters[c];o[c]=j(()=>l(t))}catch(l){throw s.error(`Store: Failed to create getter "${String(c)}" for store "${i}": ${l instanceof Error?l.message:String(l)}`),l}let a=null;if(e.persist)try{a=W(()=>t,c=>{try{for(const l in c)t[l]!==c[l]&&(t[l]=c[l],S(t,l))}catch(l){throw s.error(`Store: Persistence state update failed for store "${i}": ${l instanceof Error?l.message:String(l)}`),l}},()=>n.notify(),e.persist,i)}catch(c){throw s.error(`Store: Failed to set up persistence for store "${i}": ${c instanceof Error?c.message:String(c)}`),c}const f=new Set,g={state:t,getters:o,actions:{},subscribe:c=>{try{return f.add(c),n.depend(c),()=>{try{f.delete(c),n.remove(c)}catch(l){s.error(`Store: Failed to remove subscriber from store "${i}": ${l instanceof Error?l.message:String(l)}`)}}}catch(l){throw s.error(`Store: Failed to add subscriber to store "${i}": ${l instanceof Error?l.message:String(l)}`),l}},notifyAll:()=>{try{const c=g.state;f.forEach(l=>{try{l(c)}catch(v){s.warn(`Store: Subscriber callback failed for "${i}": ${v instanceof Error?v.message:String(v)}`)}})}catch(c){s.error(`Store: notifyAll failed for "${i}": ${c instanceof Error?c.message:String(c)}`)}},$reset:()=>{try{const c=V.get(g);if(!c){const l=`Initial state not found for store "${i}"`;throw s.error(`Store: ${l}`),new Error(l)}for(const l in c)g.state[l]!==c[l]&&(g.state[l]=c[l],S(g.state,l));for(const l in g.state)l in c||(delete g.state[l],S(g.state,l))}catch(c){throw s.error(`Store: Failed to reset store "${i}": ${c instanceof Error?c.message:String(c)}`),c}},$persist:a,$destroy:()=>{try{g.$persist?.destroy?.(),n.clear(),f.clear(),s.debug(`Store: Destroyed "${i}"`)}catch(c){s.error(`Store: Destroy failed for "${i}": ${c instanceof Error?c.message:String(c)}`)}}};V.set(g,r);const y=X(g);if(e.actions)for(const c in e.actions)try{const l=e.actions[c];g.actions[c]=l.bind(y)}catch(l){throw s.error(`Store: Failed to create action "${String(c)}" for store "${i}": ${l instanceof Error?l.message:String(l)}`),l}return I.set(i,y),y}catch(r){throw s.error(`Store: Failed to create store "${i}": ${r instanceof Error?r.message:String(r)}`),r}};function ne(i){try{const e=I.get(i);if(!e){const r=`Store with name "${i}" does not exist.`;throw s.error(`Store: ${r}`),new Error(r)}return e}catch(e){throw s.error(`Store: Failed to retrieve store "${i}": ${e instanceof Error?e.message:String(e)}`),e}}h.CommonMigrations=_,h.IndexedDBAdapter=te,h.LocalStorageAdapter=ee,h.LogLevel=R,h.Logger=C,h.MigrationManager=q,h.SessionStorageAdapter=re,h.computed=j,h.createLogger=Q,h.createMigrationManager=Z,h.createPersistenceManager=W,h.createStore=oe,h.logger=s,h.reactive=z,h.useStore=ne,h.watch=L,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));