synapse-storage 3.0.7 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,2 +1 @@
1
- export * from "./selector";
2
- export * from "./storage";
1
+ var m=!1,I=new Map;function U(c){let e=0;if(c.length===0)return e.toString(36);for(let t=0;t<c.length;t++){let r=c.charCodeAt(t);e=(e<<5)-e+r,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function P(c,e){if(c===e)return!0;if(c==null||e==null)return!1;if(typeof c!="object"&&typeof c!="function"&&typeof e!="object"&&typeof e!="function")return c===e;if(typeof c!=typeof e)return!1;if(c instanceof Date&&e instanceof Date)return c.getTime()===e.getTime();if(Array.isArray(c)&&Array.isArray(e)){if(c.length!==e.length)return!1;for(let t=0;t<c.length;t++)if(!P(c[t],e[t]))return!1;return!0}if(typeof c=="object"&&typeof e=="object"){let t=Object.keys(c),r=Object.keys(e);return t.length!==r.length?!1:t.every(s=>Object.prototype.hasOwnProperty.call(e,s)?P(c[s],e[s]):!1)}return!1}function _(c,e=P){let t,r,s=!1;return function(o){if(!s||t!==o){let a=c(o);(!s||!e(a,r))&&(r=a),t=o,s=!0}return r}}var M=class{constructor(e,t,r=P,s){this.name=e;this.equals=r;this.logger=s;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t),m&&console.log(`[${this.id}] \u0421\u043E\u0437\u0434\u0430\u043D new SelectorSubscription`)}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,r=!1;return async()=>{if(r&&t)return t;r=!0;try{return t=e(),await t}finally{r=!1}}}async notify(){try{let e=await this.memoizedGetState();if(this.lastValue===void 0||!this.equals(e,this.lastValue)){m&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C, notify()`,{old:this.lastValue,new:e}),this.lastValue=e;let t=Array.from(this.subscribers).map(async r=>{try{await r.notify(e)}catch(s){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`,{error:s})}});await Promise.all(t)}else m&&console.log(`[${this.id}] \u0417\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043D\u0435 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C in notify(), \u043F\u0440\u043E\u043F\u0443\u0441\u043A \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F`)}catch(e){throw this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 notify()`,{error:e}),e}}subscribe(e){return m&&console.log(`[${this.id}] \u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E \u043D\u043E\u0432\u044B\u0439 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A, \u0432\u0441\u0435\u0433\u043E: ${this.subscribers.size+1}`),this.subscribers.add(e),this.lastValue!==void 0?Promise.resolve().then(()=>{try{e.notify(this.lastValue)}catch(t){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}}):this.notify().catch(t=>{this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438`,{error:t})}),()=>{m&&console.log(`[${this.id}] \u041F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A \u0443\u0434\u0430\u043B\u0435\u043D, \u043E\u0441\u0442\u0430\u043B\u043E\u0441\u044C: ${this.subscribers.size-1}`),this.subscribers.delete(e)}}cleanup(){m&&console.log(`[${this.id}] \u041E\u0447\u0438\u0441\u0442\u043A\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0438, \u0431\u044B\u043B\u043E ${this.subscribers.size} \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u043E\u0432`),this.subscribers.clear(),this.lastValue=void 0}getId(){return this.id}},G=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,m&&console.log(`\u0421\u043E\u0437\u0434\u0430\u043D SelectorModule \u0434\u043B\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${this.storageName}`),this.source.getState().then(r=>{this.cachedState=r,m&&console.log(`\u041A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0434\u043B\u044F ${this.storageName}`)})}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=!1;pendingUpdates=new Set;generateName(e,t,r){let s=e?"simple":"combined",i="";if(e){let o=t.toString();i=U(o)}else{let o=t.map(n=>n.getId()).join("_"),a=r.toString();i=U(o+a)}return`${this.storageName}_${s}_${i}`}processPendingUpdates(){this.pendingUpdates.size===0||this.batchUpdateInProgress||(this.batchUpdateInProgress=!0,setTimeout(async()=>{try{let e=Array.from(this.pendingUpdates);this.pendingUpdates.clear(),this.cachedState=await this.source.getState();let t=e.map(async r=>{let s=this.subscriptions.get(r);if(s)try{return await s.notify()}catch(i){this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${r}`,{error:i})}return Promise.resolve()});await Promise.all(t)}catch(e){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439",{error:e})}finally{this.batchUpdateInProgress=!1,this.pendingUpdates.size>0&&this.processPendingUpdates()}},0))}createSelector(e,t,r){let s=!Array.isArray(e),i=s?t||{}:r||{},o=i.name||this.generateName(s,e,s?void 0:t);if(this.localSelectorCache.has(o))return m&&console.log(`[${this.storageName}] Reusing cached selector: ${o}`),this.localSelectorCache.get(o).api;if(I.has(o)){let u=I.get(o);return u.refCount++,m&&console.log(`[${this.storageName}] \u041F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440\u0430: ${o}, refCount: ${u.refCount}`),u.api}let a,n,l=[];if(s){let u=_(e,i.equals||P),g=this.createSimpleSelector(u,{...i,name:o,equals:i.equals||P});a=g.api,l=g.unsubscribeFunctions}else{n=e;let u=this.createCombinedSelector(n,t,{...i,name:o,equals:i.equals||P});a=u.api,l=u.unsubscribeFunctions}return this.localSelectorCache.set(o,{api:a,dependencies:n,unsubscribeFunctions:l}),I.set(o,{api:a,refCount:1,unsubscribeFunctions:l}),m&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043D\u043E\u0432\u044B\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${o}`),a}createSimpleSelector(e,t){m&&console.log(`[${this.storageName}] \u0421\u043E\u0437\u0434\u0430\u043D \u043F\u0440\u043E\u0441\u0442\u043E\u0439 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440: ${t.name}`);let r=async()=>{if(this.cachedState)return e(this.cachedState);let n=await this.source.getState();return this.cachedState=n,e(n)},s=new M(t.name,r,t.equals||P,this.logger),i=s.getId();this.subscriptions.set(i,s);let a=[this.source.subscribeToAll(async n=>{n?.type==="storage:update"&&(m&&console.log(`[${i}] \u041F\u043E\u043B\u0443\u0447\u0435\u043D\u043E \u0441\u043E\u0431\u044B\u0442\u0438\u0435 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430`),this.pendingUpdates.add(i),this.processPendingUpdates())})];return{api:{select:()=>r(),subscribe:n=>s.subscribe(n),getId:()=>i},unsubscribeFunctions:a}}createCombinedSelector(e,t,r){let s=_(g=>t(...g),r.equals||P),i=async()=>{let g=await Promise.all(e.map(d=>d.select()));return s(g)},o=new M(r.name,i,r.equals||P,this.logger),a=o.getId();this.subscriptions.set(a,o);let n=null,l=()=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,o.notify().catch(g=>this.logger?.error(`[${a}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u043D\u043E\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438:`,{error:g}))},10)},u=e.map(g=>g.subscribe({notify:()=>{l()}}));return{api:{select:()=>i(),subscribe:g=>o.subscribe(g),getId:()=>a},unsubscribeFunctions:u}}destroy(){m&&console.log(`[${this.storageName}] \u041D\u0430\u0447\u0430\u043B\u043E\u0441\u044C \u0443\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D\u0438\u0435 SelectorModule`),this.subscriptions.forEach(t=>t.cleanup()),this.subscriptions.clear(),this.cachedState=void 0,this.pendingUpdates.clear(),this.localSelectorCache.forEach(t=>{t.unsubscribeFunctions.forEach(r=>r())});let e=new Set;this.localSelectorCache.forEach((t,r)=>{e.add(r)}),this.localSelectorCache.clear(),e.forEach(t=>{let r=I.get(t);r&&(r.refCount--,r.refCount<=0&&(r.unsubscribeFunctions.forEach(s=>s()),I.delete(t),m&&console.log(`[${this.storageName}] \u0423\u0434\u0430\u043B\u0435\u043D \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440 \u0438\u0437 \u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u043A\u044D\u0448\u0430: ${t}`)))}),m&&console.log(`[${this.storageName}] \u0423\u043D\u0438\u0447\u0442\u043E\u0436\u0435\u043D`)}};var j=class{constructor(e,t,r="default"){this.parentExecutor=e;this.logger=t;this.storageName=r}plugins=new Map;createContext(e){return{storageName:this.storageName,timestamp:Date.now(),metadata:e}}async add(e){if(this.plugins.has(e.name)){this.logger?.warn(`\u041F\u043B\u0430\u0433\u0438\u043D ${e.name} \u0443\u0436\u0435 \u0431\u044B\u043B \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D`);return}try{await e.initialize?.(),this.plugins.set(e.name,e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D",{name:e.name})}catch(t){throw t}}async remove(e){let t=this.plugins.get(e);t&&(await t.destroy?.(),this.plugins.delete(e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0443\u0434\u0430\u043B\u0435\u043D",{name:e}))}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}async initialize(){for(let e of this.plugins.values())await e.initialize?.()}async destroy(){await Promise.all(Array.from(this.plugins.values()).map(e=>e.destroy?.()??Promise.resolve())),this.plugins.clear()}async executeBeforeSet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeSet(r,s));for(let i of this.plugins.values())if(i.onBeforeSet)try{r=await i.onBeforeSet(r,s)}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeSet`,{error:o}),o}return r}async executeAfterSet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterSet(e,s,i));for(let o of this.plugins.values())if(o.onAfterSet)try{s=await o.onAfterSet(e,s,i)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onAfterSet`,{key:e,error:a}),a}return s}async executeBeforeGet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeGet(r,s));for(let i of this.plugins.values())if(i.onBeforeGet)try{r=await i.onBeforeGet(r,s)}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeGet`,{key:e,error:o}),o}return r}async executeAfterGet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterGet(e,s,i)),console.log("executeAfterGet",e,t,r);for(let o of this.plugins.values())if(o.onAfterGet)try{s=await o.onAfterGet(e,s,i)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onAfterGet`,{key:e,error:a}),a}return s}async executeBeforeDelete(e,t){let r=!0,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeDelete(e,s));for(let i of this.plugins.values())if(i.onBeforeDelete)try{r=await i.onBeforeDelete(e,s)&&r}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeDelete`,{key:e,error:o}),o}return r}async executeAfterDelete(e,t){let r=this.createContext(t);this.parentExecutor&&await this.parentExecutor.executeAfterDelete(e,r);for(let s of this.plugins.values())if(s.onAfterDelete)try{await s.onAfterDelete(e,r)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${s.name} onAfterDelete`,{key:e,error:i}),i}}async executeOnClear(e){let t=this.createContext(e);this.parentExecutor&&await this.parentExecutor.executeOnClear(t);for(let r of this.plugins.values())if(r.onClear)try{await r.onClear(t)}catch(s){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onClear`,{error:s}),s}}};var C=(o=>(o.STORAGE_UPDATE="storage:update",o.STORAGE_DELETE="storage:delete",o.STORAGE_PATCH="storage:patch",o.STORAGE_SELECT="storage:select",o.STORAGE_CLEAR="storage:clear",o.STORAGE_DESTROY="storage:destroy",o))(C||{});var D=class{channel;tabId;messageHandlers;syncHandler;debug;syncTimeoutMs=1e3;pendingSyncRequests;constructor(e,t={}){this.channel=new BroadcastChannel(e),this.tabId=crypto.randomUUID(),this.messageHandlers=new Set,this.debug=t.debug??!1,this.pendingSyncRequests=new Map,this.channel.onmessage=this.handleMessage.bind(this),this.channel.onmessageerror=this.handleError.bind(this)}log(...e){this.debug&&console.log(`[SyncBroadcastChannel][${this.tabId}]`,...e)}error(...e){console.error(`[SyncBroadcastChannel][${this.tabId}]`,...e)}async handleMessage(e){let t=e.data;if(t.senderId!==this.tabId){if(t.type==="SYNC_REQUEST"){if(this.syncHandler)try{let r=await this.syncHandler();this.postMessage("SYNC_RESPONSE",r,t.senderId)}catch(r){this.error("Error handling sync request:",r)}return}if(t.type==="SYNC_RESPONSE"){let r=this.pendingSyncRequests.get(this.tabId);r&&(clearTimeout(r.timeout),this.pendingSyncRequests.delete(this.tabId),r.resolve(t.payload));return}for(let r of this.messageHandlers)try{await r(t)}catch(s){this.error("Error in message handler:",s)}}}handleError(e){this.error("Channel error:",e)}postMessage(e,t,r){let s={type:e,payload:t,senderId:this.tabId,timestamp:Date.now()};this.channel.postMessage(s)}subscribe(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}setSyncHandler(e){this.syncHandler=e}broadcast(e,t){this.postMessage(e,t)}async requestSync(){return new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingSyncRequests.delete(this.tabId),e(null)},this.syncTimeoutMs);this.pendingSyncRequests.set(this.tabId,{resolve:e,reject:t,timeout:r}),this.postMessage("SYNC_REQUEST",{type:"sync"})})}close(){for(let[,e]of this.pendingSyncRequests)clearTimeout(e.timeout),e.reject(new Error("Channel closed"));this.pendingSyncRequests.clear(),this.messageHandlers.clear(),this.syncHandler=void 0,this.channel.close()}};async function k(c,e,t){switch(e){case"set":t?.key!==void 0&&t?.value!==void 0&&(await c.storage.doSet(t.key,t.value),c.storage.notifySubscribers(t.key,t.value));break;case"update":Array.isArray(t?.value)&&(await c.storage.doUpdate(t.value),t.value.forEach(({key:r,value:s})=>{c.storage.notifySubscribers(r,s)}));break;case"delete":t?.key!==void 0&&(await c.storage.doDelete(t.key),c.storage.notifySubscribers(t.key,void 0));break;case"clear":await c.storage.doClear(),c.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}c.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:t?.value,source:"broadcast"})}async function H(c,e,t){switch(e){case"set":if(t?.key!==void 0){let r=await c.storage.doGet(t.key);c.storage.notifySubscribers(t.key,r)}break;case"update":if(Array.isArray(t?.value)){for(let{key:r}of t.value){let s=await c.storage.doGet(r);c.storage.notifySubscribers(r,s)}c.storage.notifySubscribers("*",{type:"storage:update",key:t.value.map(({key:r})=>r),value:t.value,source:"broadcast"})}break;case"delete":t?.key!==void 0&&c.storage.notifySubscribers(t.key,void 0);break;case"clear":c.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}e!=="update"&&c.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:e==="delete"?void 0:t?.value,source:"broadcast"})}var z=c=>{let{storageName:e,storageType:t}=c,r=`${t}-${e}`,s=new D(r,{debug:!0});return{name:"broadcast",setup:i=>(t==="memory"&&(s.setSyncHandler(async()=>{let o=await i.getState();return{type:"update",key:"*",value:Object.entries(o).map(([l,u])=>({key:l,value:u})),metadata:{batchUpdate:!0,timestamp:Date.now()}}}),s.requestSync().then(async o=>{if(o?.type==="update"&&Array.isArray(o.value))try{if(!o.value.every(n=>n&&typeof n=="object"&&"key"in n&&"value"in n)){console.error("[Sync Response] Invalid updates structure:",o.value);return}await i.storage.doUpdate(o.value),o.value.forEach(({key:n,value:l})=>{i.storage.notifySubscribers(n,l)}),i.storage.notifySubscribers("*",{type:"storage:update",value:o.value,source:"broadcast"})}catch(a){console.error("[Sync Response] Error applying updates:",a)}})),s.subscribe(async o=>{let{type:a,payload:n}=o;t==="memory"?await k(i,a,n):await H(i,a,n)})),reducer:i=>o=>async a=>{let n=await o(a);return["set","delete","clear","update"].includes(a.type)&&s.broadcast(a.type,a),n},cleanup:()=>{s.close()}}};var f=class{constructor(e,t=!1){this.value=e;this.isRawKey=t}toString(){return this.value}toJSON(){return this.value}valueOf(){return this.value}isUnparseable(){return this.isRawKey}};var q=(c={})=>{let e=c.batchSize??10,t=c.batchDelay??10,r=new Map,s=new Map,i=d=>d.type==="set"||d.type==="update",o=d=>`${d.type}_${d.key?.toString()||"default"}`,a=d=>{let h=new Map;for(let p of d){let S=`${p.type}_${p.key?.toString()||"default"}`;h.set(S,p)}return Array.from(h.values())},n=d=>{let h=s.get(d);h&&(globalThis.clearTimeout(h),s.delete(d))},l=(d,h)=>{let p=globalThis.setTimeout(h,t);s.set(d,p)},u=async(d,h,p)=>{let S=r.get(d);if(!(!S||S.length===0)){r.delete(d),n(d);try{let x=S.map(y=>y.action),b=a(x);console.log(`\u{1F504} Batching ${d}: ${S.length} actions -> ${b.length} merged`,{original:x.map(y=>({type:y.type,key:y.key?.toString(),value:y.value})),merged:b.map(y=>({type:y.type,key:y.key?.toString(),value:y.value}))});for(let y of b)try{let O=await p(y);S.filter(T=>T.action.type===y.type&&T.action.key?.toString()===y.key?.toString()).forEach(T=>T.resolve(O))}catch(O){S.filter(T=>T.action.type===y.type&&T.action.key?.toString()===y.key?.toString()).forEach(T=>T.reject(O))}}catch(x){S.forEach(b=>b.reject(x))}}},g=async(d,h,p)=>new Promise((S,x)=>{let b=o(d),y=r.get(b);y||(y=[],r.set(b,y)),y.push({action:d,resolve:S,reject:x,timestamp:Date.now()}),n(b),y.length>=e?setImmediate(()=>u(b,h,p)):l(b,()=>u(b,h,p))});return{name:"batching",setup:()=>{},cleanup:async()=>{s.forEach(d=>globalThis.clearTimeout(d)),s.clear(),r.clear()},reducer:d=>h=>async p=>i(p)?g(p,d,h):h(p)}};var L=(c={})=>{let{comparator:e=(s,i)=>{if(s===i)return!0;if(typeof s!="object"||typeof i!="object"||s===null||i===null)return s===i;let o=Object.keys(s),a=Object.keys(i);return o.length!==a.length?!1:o.every(n=>Object.prototype.hasOwnProperty.call(i,n)&&s[n]===i[n])},segments:t=[]}=c,r=new Map;return{name:"shallow-compare",setup:s=>{},reducer:s=>i=>async o=>{if(o.type!=="set"||t.length&&!t.includes(o.metadata?.segment??"default"))return i(o);let a=o.key,n=r.get(a),l=o.value;if(n!==void 0&&e(n,l))return console.log("ShallowCompare: \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0438\u0434\u0435\u043D\u0442\u0438\u0447\u043D\u044B, \u043F\u0440\u043E\u043F\u0443\u0441\u043A\u0430\u0435\u043C \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u044E",{key:a,value:l}),{...n,__metadata:{valueNotChanged:!0,originalValue:n}};let u=await i(o);return r.set(a,l),u}}};var R=class{middlewares=[];api;initialized=!1;dispatchFn;constructor(e){this.api={dispatch:async t=>this.dispatch(t),getState:()=>e.getState(),storage:{doGet:e.doGet.bind(e),doSet:e.doSet.bind(e),doUpdate:e.doUpdate.bind(e),doDelete:e.doDelete.bind(e),doClear:e.doClear.bind(e),doKeys:e.doKeys.bind(e),notifySubscribers:e.notifySubscribers.bind(e)}}}async baseOperation(e){let{processed:t,...r}=e.metadata||{},s={...e,metadata:r};switch(s.type){case"get":return this.api.storage.doGet(s.key);case"set":return await this.api.storage.doSet(s.key,s.value),this.api.storage.doGet(s.key);case"update":return Array.isArray(s.value)?(await this.api.storage.doUpdate(s.value),this.api.storage.doGet("")):s.value;case"delete":return this.api.storage.doDelete(s.key);case"clear":return this.api.storage.doClear();case"init":{let i=await this.api.storage.doGet("");return Object.keys(i||{}).length>0?i:s.value?(await this.api.storage.doSet("",s.value),this.api.storage.doGet("")):i}case"keys":return this.api.storage.doKeys();default:throw new Error(`Unknown action type: ${s.type}`)}}initializeMiddlewares(){if(this.initialized)return;let e=this.baseOperation.bind(this);for(let t of[...this.middlewares].reverse()){let r=e;e=async s=>{if(s.metadata?.processed)return r(s);let i={...s,metadata:{...s.metadata,processed:!0,timestamp:s.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(r)(i)}}this.dispatchFn=e,this.initialized=!0}use(e){e.setup&&e.setup(this.api),this.middlewares.push(e),this.initialized=!1}async dispatch(e){this.initialized||this.initializeMiddlewares();try{return this.dispatchFn(e)}catch(t){throw console.error("Error in middleware chain:",t),t}}};function w(c){return c instanceof f&&c.isUnparseable()?[c.toString()]:c.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function v(c,e){return w(e).reduce((r,s)=>r===void 0?void 0:r[s],c)}function E(c,e,t){if(e==="")return t;let r=w(e);if(e instanceof f&&e.isUnparseable())return c[e.toString()]=t,c;let s=r.pop(),i=r.reduce((o,a)=>{let n=r[r.indexOf(a)+1],l=!Number.isNaN(Number(n));return a in o||(o[a]=l?[]:{}),o[a]},c);return i[s]=t,c}var A=class c{constructor(e,t,r,s){this.config=e;this.pluginExecutor=t;this.eventEmitter=r;this.logger=s;this.name=e.name,this.middlewareModule=new R({getState:this.getState.bind(this),doGet:this.doGet.bind(this),doSet:this.doSet.bind(this),doUpdate:this.doUpdate.bind(this),doDelete:this.doDelete.bind(this),doClear:this.doClear.bind(this),doKeys:this.doKeys.bind(this),notifySubscribers:this.notifySubscribers.bind(this),pluginExecutor:this.pluginExecutor,eventEmitter:this.eventEmitter,logger:this.logger}),this.initializeMiddlewares()}static GLOBAL_SUBSCRIPTION_KEY="*";name;selectorPathCache=new WeakMap;middlewareModule;initializedMiddlewares=null;subscribers=new Map;initializeMiddlewares(){this.config.middlewares&&!this.initializedMiddlewares&&(this.initializedMiddlewares=this.config.middlewares(()=>this.getDefaultMiddleware()),this.initializedMiddlewares.forEach(e=>this.middlewareModule.use(e)))}getDefaultMiddleware(){return{batching:(e={})=>q(e),shallowCompare:(e={})=>L(e)}}async initializeWithMiddlewares(){try{let e=await this.getState();!(Object.keys(e).length>0)&&this.config.initialState&&await this.middlewareModule.dispatch({type:"init",value:this.config.initialState})}catch(e){throw this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",{error:e}),e}}async get(e){try{let t={operation:"get",timestamp:Date.now(),key:e},r=await this.middlewareModule.dispatch({type:"get",key:e,metadata:t}),s=await this.pluginExecutor?.executeAfterGet(e,r,t)??r;return await this.emitEvent({type:"storage:select",payload:{key:e,value:s}}),s}catch(t){throw this.logger?.error("Error getting value",{key:e,error:t}),t}}async set(e,t){try{let r={operation:"set",timestamp:Date.now(),key:e},s=await this.pluginExecutor?.executeBeforeSet(t,r)??t,i=await this.middlewareModule.dispatch({type:"set",key:e,value:s,metadata:r}),o=i?.__metadata?.valueNotChanged===!0,a;if(o&&i?.__metadata?.originalValue!==void 0?a=i.__metadata.originalValue:a=await this.pluginExecutor?.executeAfterSet(e,i,r)??i,!o){let l=[e.toString()];this.notifySubscribers(e,a),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:a,changedPaths:l}),await this.emitEvent({type:"storage:update",payload:{key:e,value:a,changedPaths:l}})}}catch(r){throw this.logger?.error("Error setting value",{key:e,error:r}),r}}async update(e){try{let t={operation:"update",timestamp:Date.now()},r=await this.getState(),s=structuredClone(r);e(s);let i=this.findChangedPaths(r,s);if(i.size===0){this.logger?.debug&&this.logger.debug("No changes detected in update");return}this.logger?.debug&&this.logger.debug("Changed paths:",{paths:Array.from(i)});let o=new Set;for(let d of i){let h=d.split(".")[0];o.add(h)}let a=await Promise.all(Array.from(o).map(async d=>{let h={...t,key:d},p=await this.pluginExecutor?.executeBeforeSet(s[d],h)??s[d];return{key:d,value:p}})),n=await this.middlewareModule.dispatch({type:"update",value:a,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(i)}}),l={};Array.isArray(n)?n.forEach(d=>{d&&typeof d=="object"&&"key"in d&&"value"in d&&(l[d.key]=d.value)}):n&&typeof n=="object"&&(l={...n});let u=Object.keys(l).filter(d=>!this.isEqual(r[d],l[d]));if(u.length===0){this.logger?.debug&&this.logger.debug("No actual changes after middleware processing");return}let g={};u.forEach(d=>{g[d]=l[d]}),this.logger?.debug&&this.logger.debug("Notifying subscribers about changes:",{keys:u}),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:u,value:g,changedPaths:Array.from(i)});for(let d of i)try{let h=d.split(".")[0];if(h in g){let p;if(d===h)p=g[h];else{let S=d.substring(h.length+1);p=v(g[h],S)}p!==void 0&&this.notifySubscribers(d,p)}}catch(h){this.logger?.error("Error notifying path subscribers",{path:d,error:h})}await this.emitEvent({type:"storage:update",payload:{state:g,key:u,changedPaths:Array.from(i)}})}catch(t){throw this.logger?.error("Error updating state",{error:t}),t}}async delete(e){try{let t={operation:"delete",timestamp:Date.now(),key:e};if(await this.pluginExecutor?.executeBeforeDelete(e,t)){let r=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});await this.pluginExecutor?.executeAfterDelete(e,t);let i=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:r,changedPaths:i}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:r,changedPaths:i}})}}catch(t){throw this.logger?.error("Error deleting value",{key:e,error:t}),t}}async clear(){try{this.pluginExecutor?.executeOnClear(),await this.middlewareModule.dispatch({type:"clear"})}catch(e){throw this.logger?.error("Error clearing storage",{error:e}),e}}async keys(){try{return await this.middlewareModule.dispatch({type:"keys"})}catch(e){throw this.logger?.error("Error getting keys",{error:e}),e}}async has(e){try{return await this.doHas(e)}catch(t){throw this.logger?.error("Error checking value existence",{key:e,error:t}),t}}async getState(){try{return await this.doGet("")||{}}catch(e){throw this.logger?.error("Error getting state",{error:e}),e}}subscribeToAll(e){return this.subscribers.has(c.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(c.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(c.GLOBAL_SUBSCRIPTION_KEY))}}subscribe(e,t){return typeof e=="string"?this.subscribeByKey(e,t):this.subscribeBySelector(e,t)}async destroy(){try{await this.clear(),await this.doDestroy(),this.initializedMiddlewares&&(await Promise.all(this.initializedMiddlewares.map(async e=>{"cleanup"in e&&await e.cleanup?.()})),this.initializedMiddlewares=null),await this.emitEvent({type:"storage:destroy"})}catch(e){throw this.logger?.error("Error destroying storage",{error:e}),e}}subscribeByKey(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=!1;return this.subscribers.get(e).add(t),this.get(e).then(s=>{try{r||(r=!0,t(s))}catch(i){this.logger?.error("Error in initial callback",{key:e,error:i})}}),()=>{let s=this.subscribers.get(e);s&&(s.delete(t),s.size===0&&this.subscribers.delete(e))}}createDummyState(){let e={get:(t,r)=>(t[r]=t[r]||new Proxy({},e),t[r])};return new Proxy({},e)}isEqual(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;let r=typeof e;if(r!==typeof t)return!1;if(r!=="object")return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(!this.isEqual(e[a],t[a]))return!1;return!0}let i=Object.keys(e),o=Object.keys(t);return i.length!==o.length?!1:i.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&this.isEqual(e[a],t[a]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let r=[],s=(i="")=>({get:(o,a)=>{if(typeof a=="symbol")return Reflect.get(o,a);let n=i?`${i}.${a}`:a;return r.push(n),new Proxy({},s(n))},has:(o,a)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(o,a,n)=>new Proxy(()=>{},s(i))});try{e(new Proxy(t,s()))}catch{}return r.length===0?"":(r.sort((i,o)=>o.length-i.length),this.selectorPathCache.set(e,r[0]),r[0])}notifySubscribers(e,t){let r=e.toString(),s=this.subscribers.get(r);s?.size&&new Set(s).forEach(o=>{try{o(t)}catch(a){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0435 \u043D\u0430 \u043A\u043E\u043B\u0431\u044D\u043A",{key:r,error:a})}})}findChangedPaths(e,t,r="",s=new Set,i=new WeakMap){if(e===t)return s;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e!==t&&s.add(r||""),s;if(i.has(e))return s;i.set(e,!0);let o=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let a of o){let n=e[a],l=t[a];if(n===l)continue;let u=r?`${r}.${a}`:a;n&&l&&typeof n=="object"&&typeof l=="object"&&!Array.isArray(n)&&!Array.isArray(l)?this.findChangedPaths(n,l,u,s,i):Array.isArray(n)&&Array.isArray(l)?this.isEqual(n,l)||s.add(u):this.isEqual(n,l)||s.add(u)}return s}subscribeBySelector(e,t){let r=this.createDummyState(),s=this.extractPath(e,r);this.logger?.debug&&this.logger.debug("Subscribing to path:",{path:s});let i=async o=>{try{if(o==null){let l=await this.getState(),u=e(l);t(u);return}if(typeof o!="object"||o===null){t(o);return}let a=await this.getState(),n=e(a);t(n)}catch(a){this.logger?.error("Error in selector callback",{path:s,error:a}),t(o)}};return s?this.subscribeByKey(s,i):this.subscribeToAll(()=>{this.getState().then(o=>{t(e(o))})})}async emitEvent(e){try{await this.eventEmitter?.emit({...e,metadata:{...e.metadata||{},timestamp:Date.now(),storageName:this.name}})}catch(t){this.logger?.error("Error emitting event",{event:e,error:t})}}};var N=class c{constructor(e,t,r){this.dbName=e;this.logger=r;this.dbVersion=t}static instances=new Map;db=null;initPromise=null;storeNames=new Set;dbVersion;static getInstance(e,t=1,r){c.instances.has(e)||c.instances.set(e,new c(e,t,r));let s=c.instances.get(e);return t>s.dbVersion&&(s.dbVersion=t),s}async initialize(){return this.db?this.db:(this.initPromise||(this.initPromise=this.openDatabase()),this.initPromise)}async ensureStoreExists(e){if(await this.initialize(),this.db.objectStoreNames.contains(e))return this.storeNames.add(e),this.db;this.logger?.debug(`Store "${e}" not found, upgrading database`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase([e]);let t=await this.initPromise;return this.storeNames.add(e),t}async openDatabase(e=[]){return new Promise((t,r)=>{this.logger?.debug(`Opening database "${this.dbName}" with version ${this.dbVersion}`);let s=indexedDB.open(this.dbName,this.dbVersion);s.onerror=()=>{this.logger?.error(`Failed to open database "${this.dbName}"`,{error:s.error}),r(s.error)},s.onsuccess=()=>{this.db=s.result;for(let i=0;i<this.db.objectStoreNames.length;i++)this.storeNames.add(this.db.objectStoreNames[i]);this.logger?.debug(`Database "${this.dbName}" opened successfully`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),t(this.db)},s.onupgradeneeded=i=>{let o=i.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let a of e)o.objectStoreNames.contains(a)||(this.logger?.debug(`Creating store "${a}"`),o.createObjectStore(a))}})}closeDatabase(){this.db&&(this.db.close(),this.db=null,this.initPromise=null)}async deleteDatabase(){return this.closeDatabase(),new Promise((e,t)=>{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{this.logger?.debug(`Database "${this.dbName}" deleted successfully`),c.instances.delete(this.dbName),this.storeNames.clear(),e()},r.onerror=()=>{this.logger?.error(`Failed to delete database "${this.dbName}"`,{error:r.error}),t(r.error)}})}async ensureStoresExist(e){await this.initialize();let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u043D\u0435\u0434\u043E\u0441\u0442\u0430\u044E\u0449\u0438\u0445 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449: ${t.join(", ")}`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase(t),this.initPromise)}getCurrentVersion(){return this.dbVersion}},B=class{constructor(e,t=1,r){this.dbName=e;this.logger=r;this.version=t}db=null;version;getCurrentVersion(){return this.version}openDatabase(e,t=[]){return new Promise((r,s)=>{this.logger?.debug(`\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0441 \u0432\u0435\u0440\u0441\u0438\u0435\u0439 ${e}`);let i=indexedDB.open(this.dbName,e);i.onerror=()=>{this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u0438\u0438 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}"`,{error:i.error}),s(i.error)},i.onsuccess=()=>{this.db=i.result,this.version=this.db.version,this.logger?.debug(`\u0411\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0442\u043A\u0440\u044B\u0442\u0430`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),r(this.db)},i.onupgradeneeded=o=>{let a=o.target.result;this.logger?.debug(`\u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0434\u043E \u0432\u0435\u0440\u0441\u0438\u0438 ${e}`);for(let n of t)a.objectStoreNames.contains(n)||(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "${n}"`),a.createObjectStore(n))}})}async ensureStoresExist(e){this.db||(this.db=await this.openDatabase(this.version));let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${t.join(", ")}`,{dbName:this.dbName,currentVersion:this.version}),this.db.close(),this.db=null,this.version++,this.db=await this.openDatabase(this.version,t),this.db)}close(){this.db&&(this.db.close(),this.db=null)}},K=class c extends A{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,r,s){super(e,t,r,s);let i=e.options;this.DB_NAME=i.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=i.dbVersion||1,this.dbManager=N.getInstance(this.DB_NAME,this.DB_VERSION,s)}async initialize(){try{this.logger?.debug(`Initializing IndexedDB storage "${this.STORE_NAME}"`),await this.dbManager.ensureStoreExists(this.STORE_NAME);try{if(!(await this.dbManager.initialize()).objectStoreNames.contains(this.STORE_NAME))throw new Error(`Store "${this.STORE_NAME}" not found after initialization`)}catch(e){throw this.logger?.error(`Error verifying store "${this.STORE_NAME}" exists:`,{error:e}),e}this.initializeMiddlewares();try{await this.initializeWithMiddlewares(),this.logger?.debug(`IndexedDB storage "${this.STORE_NAME}" initialized successfully`)}catch(e){this.logger?.error(`Failed to initialize middleware for store "${this.STORE_NAME}"`,{error:e})}return this}catch(e){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 IndexedDB "${this.name}"`,{error:e}),e}}static async getCurrentDBVersion(e){return new Promise(t=>{try{let r=indexedDB.open(e);r.onsuccess=()=>{let s=r.result.version;r.result.close(),t(s)},r.onerror=()=>{console.warn(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0438 \u0432\u0435\u0440\u0441\u0438\u0438 \u0411\u0414 ${e}`,r.error),t(0)}}catch(r){console.warn(`\u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043F\u0440\u0438 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0438 \u0432\u0435\u0440\u0441\u0438\u0438 \u0411\u0414 ${e}`,r),t(0)}})}static async createStorages(e,t,r){let i=await this.getCurrentDBVersion(e)||1,o=new B(e,i,r),a=Object.values(t).map(l=>l.name);await o.ensureStoresExist(a);let n={};for(let[l,u]of Object.entries(t)){let g=new c({...u,options:{dbName:e,dbVersion:o.getCurrentVersion()}},u.pluginExecutor,u.eventEmitter,r);n[l]=await g.initialize()}return n}async getTransaction(e="readonly"){try{let t=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!t.objectStoreNames.contains(this.STORE_NAME)){this.logger?.warn(`Object store "${this.STORE_NAME}" not found, attempting to repair`),t.close(),this.dbManager.closeDatabase();let r=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!r.objectStoreNames.contains(this.STORE_NAME))throw new Error(`Object store "${this.STORE_NAME}" still doesn't exist after repair attempt`);return r.transaction(this.STORE_NAME,e)}return t.transaction(this.STORE_NAME,e)}catch(t){throw this.logger?.error(`Failed to create transaction for store "${this.STORE_NAME}"`,{error:t}),t}}async getObjectStore(e="readonly"){return(await this.getTransaction(e)).objectStore(this.STORE_NAME)}async doGet(e){let t=await this.getObjectStore();if(e==="")return new Promise((s,i)=>{let o=t.getAll();o.onerror=()=>i(o.error),o.onsuccess=()=>{let a=o.result,n=t.getAllKeys();n.onsuccess=()=>{let l=n.result.reduce((u,g,d)=>(g!=="root"&&(u[g]=a[d]),u),{});s(l)},n.onerror=()=>i(n.error)}});if(e instanceof f&&e.isUnparseable())return new Promise((s,i)=>{let o=t.get(e.valueOf());o.onerror=()=>i(o.error),o.onsuccess=()=>s(o.result)});let r=w(e);if(r.length>1){let s=r[0];return new Promise((i,o)=>{let a=t.get(s);a.onerror=()=>o(a.error),a.onsuccess=()=>{let n=a.result;if(!n){i(void 0);return}let l=v(n,r.slice(1).join("."));i(l)}})}return new Promise((s,i)=>{let o=t.get(r[0]);o.onerror=()=>i(o.error),o.onsuccess=()=>s(o.result)})}async doSet(e,t){if(e===""){let i=await this.getObjectStore("readwrite");return new Promise((o,a)=>{let n=i.transaction;n.oncomplete=()=>{o()},n.onerror=()=>{a(n.error)};let l=i.clear();l.onsuccess=()=>{let u=Object.entries(t);for(let[g,d]of u)i.put(d,g)},l.onerror=()=>{a(l.error)}})}let r=await this.getObjectStore("readwrite");if(e instanceof f&&e.isUnparseable()){await this.putValueInStore(r,e.valueOf(),t);return}let s=w(e);if(s.length>1){let i=s[0];return new Promise((o,a)=>{let n=r.get(i);n.onerror=()=>a(n.error),n.onsuccess=()=>{let l=n.result||{},u=E(l,s.slice(1).join("."),t),g=r.put(u,i);g.onerror=()=>a(g.error),g.onsuccess=()=>o()}})}await this.putValueInStore(r,s[0],t)}async putValueInStore(e,t,r){return new Promise((s,i)=>{let o=e.put(r,t.valueOf());o.onerror=()=>i(o.error),o.onsuccess=()=>s()})}async doUpdate(e){let t=new Map,r=[];for(let{key:s,value:i}of e){if(s instanceof f&&s.isUnparseable()){r.push({key:s.valueOf(),value:i});continue}let o=w(s),a=o[0],n=o.slice(1);t.has(a)||t.set(a,[]),t.get(a).push({path:n,value:i})}try{for(let{key:s,value:i}of r){let o=await this.getObjectStore("readwrite");await this.putValueInStore(o,s,i)}for(let[s,i]of t){let a={...await this.doGet(s)||{}};for(let{path:l,value:u}of i)l.length===0?a=u:a=E(a,l.join("."),u);let n=await this.getObjectStore("readwrite");await this.putValueInStore(n,s,a)}}catch(s){throw this.logger?.error("Error during update:",{error:s}),s}}async doDelete(e){let t=await this.getObjectStore("readwrite");if(e instanceof f&&e.isUnparseable())return new Promise((i,o)=>{let a=t.delete(e.valueOf());a.onerror=()=>o(a.error),a.onsuccess=()=>i(!0)});let r=w(e);if(r.length===1)return new Promise((i,o)=>{let a=t.delete(r[0]);a.onerror=()=>o(a.error),a.onsuccess=()=>i(!0)});let s=r[0];return new Promise((i,o)=>{let a=t.get(s);a.onerror=()=>o(a.error),a.onsuccess=()=>{let n=a.result;if(!n){i(!1);return}let l=v(n,r.slice(0,-1).join(".")),u=r[r.length-1];if(!l||!(u in l)){i(!1);return}if(Array.isArray(l)){let d=parseInt(u,10);isNaN(d)?delete l[u]:l.splice(d,1)}else delete l[u];let g=t.put(n,s);g.onerror=()=>o(g.error),g.onsuccess=()=>i(!0)}})}async doClear(){let e=await this.getObjectStore("readwrite");return new Promise((t,r)=>{let s=e.clear();s.onsuccess=()=>t(),s.onerror=()=>r(s.error)})}async doKeys(){let t=(await this.getObjectStore()).getAllKeys();return new Promise((r,s)=>{t.onsuccess=()=>{r(t.result)},t.onerror=()=>s(t.error)})}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){try{await this.doClear()}catch(e){throw this.logger?.error(`Error destroying store "${this.STORE_NAME}"`,{error:e}),e}}};var $=class extends A{constructor(e,t,r,s){super(e,t,r,s)}async initialize(){try{return await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing LocalStorage",{error:e}),e}}async doGet(e){let t=localStorage.getItem(this.name);if(!t)return;let r=JSON.parse(t);return e instanceof f&&e.isUnparseable()?r[e.valueOf()]:v(r,e)}async doSet(e,t){let r=localStorage.getItem(this.name),s=r?JSON.parse(r):{};if(e instanceof f&&e.isUnparseable()){s[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(s));return}let i=E({...s},e,t);localStorage.setItem(this.name,JSON.stringify(i))}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return!1;let r=JSON.parse(t);if(e instanceof f&&e.isUnparseable()){let n=e.valueOf();return n in r?(delete r[n],localStorage.setItem(this.name,JSON.stringify(r)),!0):!1}let s=w(e),i=s.slice(0,-1).join("."),o=s[s.length-1],a=i?v(r,i):r;return!a||!(o in a)?!1:(delete a[o],localStorage.setItem(this.name,JSON.stringify(r)),!0)}async doUpdate(e){let t=localStorage.getItem(this.name),r=t?JSON.parse(t):{};for(let{key:s,value:i}of e)s instanceof f&&s.isUnparseable()?r[s.valueOf()]=i:E(r,s,i);localStorage.setItem(this.name,JSON.stringify(r))}async doClear(){localStorage.removeItem(this.name)}async doKeys(){let e=localStorage.getItem(this.name);if(!e)return[];let t=JSON.parse(e);return this.getAllKeys(t)}async doHas(e){return await this.doGet(e)!==void 0}getAllKeys(e){return Object.keys(e)}async doDestroy(){await this.doClear()}};var V=class extends A{storage=new Map;constructor(e,t,r,s){super(e,t,r,s)}async initialize(){try{return this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing MemoryStorage",{error:e}),e}}async doGet(e){let t=this.storage.get(this.name);if(t)return e instanceof f&&e.isUnparseable()?t[e.valueOf()]:v(t,e)}async doSet(e,t){let r=this.storage.get(this.name)||{};if(e instanceof f&&e.isUnparseable()){r[e.valueOf()]=t,this.storage.set(this.name,r);return}let s=E({...r},e,t);this.storage.set(this.name,s)}async doDelete(e){let t=this.storage.get(this.name);if(!t)return!1;if(e instanceof f&&e.isUnparseable()){let a=e.valueOf();return a in t?(delete t[a],this.storage.set(this.name,t),!0):!1}let r=w(e),s=r.slice(0,-1).join("."),i=r[r.length-1],o=s?v(t,s):t;return!o||!(i in o)?!1:(delete o[i],this.storage.set(this.name,t),!0)}async doUpdate(e){let r={...this.storage.get(this.name)||{}};for(let{key:s,value:i}of e)s instanceof f&&s.isUnparseable()?r[s.valueOf()]=i:E(r,s,i);this.storage.set(this.name,r)}async doClear(){this.storage.delete(this.name)}async doKeys(){let e=this.storage.get(this.name);return e?this.getAllKeys(e):[]}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){this.storage.delete(this.name)}getAllKeys(e){return Object.keys(e)}};export{K as IndexedDBStorage,$ as LocalStorage,V as MemoryStorage,G as SelectorModule,C as StorageEvents,j as StoragePluginModule,z as broadcastMiddleware};