UNPKG

synapse-storage

Version:

Набор инструментов для управления состоянием и апи-запросами

2 lines (1 loc) 47.8 kB
var y=!1,M=new Map;function z(c){let e=0;if(c.length===0)return e.toString(36);for(let t=0;t<c.length;t++){let s=c.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function T(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(!T(c[t],e[t]))return!1;return!0}if(typeof c=="object"&&typeof e=="object"){let t=Object.keys(c),s=Object.keys(e);return t.length!==s.length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)?T(c[r],e[r]):!1)}return!1}function q(c,e=T){let t,s,r=!1;return function(o){if(!r||t!==o){let n=c(o);(!r||!e(n,s))&&(s=n),t=o,r=!0}return s}}var B=class{constructor(e,t,s=T,r){this.name=e;this.equals=s;this.logger=r;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t)}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,s=!1;return async()=>{if(s&&t)return t;s=!0;try{return t=e(),await t}finally{s=!1}}}async notify(){try{let e=await this.memoizedGetState();if(this.lastValue===void 0||!this.equals(e,this.lastValue)){this.lastValue=e;let t=Array.from(this.subscribers).map(async s=>{try{await s.notify(e)}catch(r){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:r})}});await Promise.all(t)}}catch(e){throw this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 notify()`,{error:e}),e}}subscribe(e){return 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})}),()=>{this.subscribers.delete(e)}}cleanup(){this.subscribers.clear(),this.lastValue=void 0}getId(){return this.id}},F=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,this.source.getState().then(s=>{this.cachedState=s})}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=!1;pendingUpdates=new Set;generateName(e,t,s){let r=e?"simple":"combined",i="";if(e){let o=t.toString();i=z(o)}else{let o=t.map(a=>a.getId()).join("_"),n=s.toString();i=z(o+n)}return`${this.storageName}_${r}_${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 s=>{let r=this.subscriptions.get(s);if(r)try{return await r.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 ${s}`,{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,s){let r=!Array.isArray(e),i=r?t||{}:s||{},o=i.name||this.generateName(r,e,r?void 0:t);if(this.localSelectorCache.has(o))return this.localSelectorCache.get(o).api;if(M.has(o)){let d=M.get(o);return d.refCount++,d.api}let n,a,l=[];if(r){let d=q(e,i.equals||T),u=this.createSimpleSelector(d,{...i,name:o,equals:i.equals||T});n=u.api,l=u.unsubscribeFunctions}else{a=e;let d=this.createCombinedSelector(a,t,{...i,name:o,equals:i.equals||T});n=d.api,l=d.unsubscribeFunctions}return this.localSelectorCache.set(o,{api:n,dependencies:a,unsubscribeFunctions:l}),M.set(o,{api:n,refCount:1,unsubscribeFunctions:l}),n}createSimpleSelector(e,t){let s=async()=>{if(this.cachedState)return e(this.cachedState);let a=await this.source.getState();return this.cachedState=a,e(a)},r=new B(t.name,s,t.equals||T,this.logger),i=r.getId();this.subscriptions.set(i,r);let n=[this.source.subscribeToAll(async a=>{a?.type==="storage:update"&&(this.pendingUpdates.add(i),this.processPendingUpdates())})];return{api:{select:()=>s(),subscribe:a=>r.subscribe(a),getId:()=>i},unsubscribeFunctions:n}}createCombinedSelector(e,t,s){let r=q(u=>t(...u),s.equals||T),i=async()=>{let u=await Promise.all(e.map(g=>g.select()));return r(u)},o=new B(s.name,i,s.equals||T,this.logger),n=o.getId();this.subscriptions.set(n,o);let a=null,l=()=>{a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,o.notify().catch(u=>this.logger?.error(`[${n}] \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:u}))},10)},d=e.map(u=>u.subscribe({notify:()=>{l()}}));return{api:{select:()=>i(),subscribe:u=>o.subscribe(u),getId:()=>n},unsubscribeFunctions:d}}destroy(){this.subscriptions.forEach(t=>t.cleanup()),this.subscriptions.clear(),this.cachedState=void 0,this.pendingUpdates.clear(),this.localSelectorCache.forEach(t=>{t.unsubscribeFunctions.forEach(s=>s())});let e=new Set;this.localSelectorCache.forEach((t,s)=>{e.add(s)}),this.localSelectorCache.clear(),e.forEach(t=>{let s=M.get(t);s&&(s.refCount--,s.refCount<=0&&(s.unsubscribeFunctions.forEach(r=>r()),M.delete(t)))})}};var k=class{constructor(e,t,s="default"){this.parentExecutor=e;this.logger=t;this.storageName=s}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 s=e,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeSet(s,r));for(let i of this.plugins.values())if(i.onBeforeSet)try{s=await i.onBeforeSet(s,r)}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 s}async executeAfterSet(e,t,s){let r=t,i=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterSet(e,r,i));for(let o of this.plugins.values())if(o.onAfterSet)try{r=await o.onAfterSet(e,r,i)}catch(n){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onAfterSet`,{key:e,error:n}),n}return r}async executeBeforeGet(e,t){let s=e,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeGet(s,r));for(let i of this.plugins.values())if(i.onBeforeGet)try{s=await i.onBeforeGet(s,r)}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 s}async executeAfterGet(e,t,s){let r=t,i=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterGet(e,r,i));for(let o of this.plugins.values())if(o.onAfterGet)try{r=await o.onAfterGet(e,r,i)}catch(n){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onAfterGet`,{key:e,error:n}),n}return r}async executeBeforeDelete(e,t){let s=!0,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeDelete(e,r));for(let i of this.plugins.values())if(i.onBeforeDelete)try{s=await i.onBeforeDelete(e,r)&&s}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 s}async executeAfterDelete(e,t){let s=this.createContext(t);this.parentExecutor&&await this.parentExecutor.executeAfterDelete(e,s);for(let r of this.plugins.values())if(r.onAfterDelete)try{await r.onAfterDelete(e,s)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onAfterDelete`,{key:e,error:i}),i}}async executeOnClear(e){let t=this.createContext(e);this.parentExecutor&&await this.parentExecutor.executeOnClear(t);for(let s of this.plugins.values())if(s.onClear)try{await s.onClear(t)}catch(r){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${s.name} onClear`,{error:r}),r}}};var V=(i=>(i.STRICT="strict",i.FIRST_WINS="first_wins",i.DEEP_MERGE="deep_merge",i.OVERRIDE="override",i.WARN_AND_USE_FIRST="warn_and_use_first",i))(V||{});var H=(r=>(r.IDLE="idle",r.LOADING="loading",r.READY="ready",r.ERROR="error",r))(H||{}),G=(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))(G||{});var K=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}error(...e){}async handleMessage(e){let t=e.data;if(t.senderId!==this.tabId){if(t.type==="SYNC_REQUEST"){if(this.syncHandler)try{let s=await this.syncHandler();this.postMessage("SYNC_RESPONSE",s,t.senderId)}catch(s){this.error("Error handling sync request:",s)}return}if(t.type==="SYNC_RESPONSE"){let s=this.pendingSyncRequests.get(this.tabId);s&&(clearTimeout(s.timeout),this.pendingSyncRequests.delete(this.tabId),s.resolve(t.payload));return}for(let s of this.messageHandlers)try{await s(t)}catch(r){this.error("Error in message handler:",r)}}}handleError(e){this.error("Channel error:",e)}postMessage(e,t,s){let r={type:e,payload:t,senderId:this.tabId,timestamp:Date.now()};this.channel.postMessage(r)}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 s=setTimeout(()=>{this.pendingSyncRequests.delete(this.tabId),e(null)},this.syncTimeoutMs);this.pendingSyncRequests.set(this.tabId,{resolve:e,reject:t,timeout:s}),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 X(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:s,value:r})=>{c.storage.notifySubscribers(s,r)}));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 Z(c,e,t){switch(e){case"set":if(t?.key!==void 0){let s=await c.storage.doGet(t.key);c.storage.notifySubscribers(t.key,s)}break;case"update":if(Array.isArray(t?.value)){for(let{key:s}of t.value){let r=await c.storage.doGet(s);c.storage.notifySubscribers(s,r)}c.storage.notifySubscribers("*",{type:"storage:update",key:t.value.map(({key:s})=>s),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 Y=c=>{let{storageName:e,storageType:t}=c,s=`${t}-${e}`,r=new K(s,{debug:!0});return{name:"broadcast",setup:i=>(t==="memory"&&(r.setSyncHandler(async()=>{let o=await i.getState();return{type:"update",key:"*",value:Object.entries(o).map(([l,d])=>({key:l,value:d})),metadata:{batchUpdate:!0,timestamp:Date.now()}}}),r.requestSync().then(async o=>{if(o?.type==="update"&&Array.isArray(o.value))try{if(!o.value.every(a=>a&&typeof a=="object"&&"key"in a&&"value"in a))return;await i.storage.doUpdate(o.value),o.value.forEach(({key:a,value:l})=>{i.storage.notifySubscribers(a,l)}),i.storage.notifySubscribers("*",{type:"storage:update",value:o.value,source:"broadcast"})}catch{}})),r.subscribe(async o=>{let{type:n,payload:a}=o;t==="memory"?await X(i,n,a):await Z(i,n,a)})),reducer:i=>o=>async n=>{let a=await o(n);return["set","delete","clear","update"].includes(n.type)&&r.broadcast(n.type,n),a},cleanup:()=>{r.close()}}};var C=class{static instances=new Map;static configs=new Map;static logger;static setLogger(e){this.logger=e}static getOrCreate(e,t,s){let r=this.configs.get(e),i=this.instances.get(e);if(i&&r){let n=this.mergeConfigurations(r,t);return{instance:i,isNewInstance:!1,appliedConfig:n.finalConfig,conflicts:n.conflicts}}let o=s(t);return this.instances.set(e,o),this.configs.set(e,{...t}),this.logger?.debug(`Created new singleton instance: ${e}`),{instance:o,isNewInstance:!0,appliedConfig:t,conflicts:[]}}static exists(e){return this.instances.has(e)}static getConfig(e){return this.configs.get(e)}static remove(e){let t=this.instances.get(e);return t?(typeof t.destroy=="function"&&t.destroy(),this.instances.delete(e),this.configs.delete(e),this.logger?.debug(`Removed singleton instance: ${e}`),!0):!1}static clear(){for(let[e,t]of this.instances)typeof t.destroy=="function"&&t.destroy();this.instances.clear(),this.configs.clear(),this.logger?.debug("Cleared all singleton instances")}static getStats(){return{instanceCount:this.instances.size,instances:Array.from(this.instances.keys())}}static mergeConfigurations(e,t){let s=t.singleton?.mergeStrategy||"first_wins",r=t.singleton?.warnOnConflict??!0;switch(s){case"strict":return this.strictMerge(e,t);case"first_wins":return this.firstWinsMerge(e,t,r);case"deep_merge":return this.deepMerge(e,t);case"override":return this.overrideMerge(e,t);case"warn_and_use_first":return this.warnAndUseFirst(e,t);default:return this.firstWinsMerge(e,t,r)}}static strictMerge(e,t){let s=this.findConflicts(e,t);if(s.length>0)throw new Error(`Strict singleton validation failed for "${e.name}". Conflicts: ${s.join(", ")}`);return{finalConfig:e,conflicts:[]}}static firstWinsMerge(e,t,s){let r=this.findConflicts(e,t);return s&&r.length>0&&(this.logger?.warn(`Singleton config conflicts for "${e.name}":`,r),this.logger?.warn("Using existing configuration")),{finalConfig:e,conflicts:r}}static deepMerge(e,t){let s=this.findConflicts(e,t),r={...e,initialState:this.deepMergeObjects(e.initialState||{},t.initialState||{})};return this.logger?.debug(`Deep merged singleton config for "${e.name}"`),{finalConfig:r,conflicts:s}}static overrideMerge(e,t){let s=this.findConflicts(e,t),r={...t,name:e.name};return this.logger?.warn(`Overriding singleton config for "${e.name}"`),{finalConfig:r,conflicts:s}}static warnAndUseFirst(e,t){let s=this.findConflicts(e,t);return s.length>0&&(this.logger?.warn(`Configuration conflicts detected for singleton "${e.name}":`),this.logger?.warn("Existing config:",e),this.logger?.warn("Incoming config:",t),this.logger?.warn("Using existing configuration")),{finalConfig:e,conflicts:s}}static findConflicts(e,t){let s=[];if(e.initialState&&t.initialState){let r=this.findObjectConflicts(e.initialState,t.initialState,"initialState");s.push(...r)}else e.initialState!==t.initialState&&s.push("initialState: one is undefined");return!!e.middlewares!=!!t.middlewares&&s.push("middlewares: configuration differs"),s}static findObjectConflicts(e,t,s){let r=[],i=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let o of i){let n=`${s}.${o}`,a=e?.[o],l=t?.[o];a!==l&&(a===void 0||l===void 0?r.push(`${n}: missing in one config`):typeof a!=typeof l?r.push(`${n}: type mismatch (${typeof a} vs ${typeof l})`):typeof a=="object"&&a!==null&&l!==null?r.push(...this.findObjectConflicts(a,l,n)):r.push(`${n}: value mismatch (${a} vs ${l})`))}return r}static deepMergeObjects(e,t){let s={...e};for(let r in t)t[r]!==null&&typeof t[r]=="object"&&!Array.isArray(t[r])?s[r]=this.deepMergeObjects(e[r]||{},t[r]):s[r]=t[r];return s}},x=class{static generate(e,t){return e.singleton?.key?e.singleton.key:`${t}_${e.name}`}};var I=class{static handleSingletonCreation(e,t,s,r){if(!e.singleton?.enabled)return s(e);r&&C.setLogger(r);let i=x.generate(e,t),o=C.getOrCreate(i,e,s);return o.isNewInstance?r?.debug(`Created new singleton storage: ${i}`):(r?.debug(`Reusing existing singleton storage: ${i}`),o.conflicts&&o.conflicts.length>0&&r?.debug(`Configuration conflicts detected: ${o.conflicts.join(", ")}`)),o.instance}};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 W=(c={})=>{let e=c.batchSize??10,t=c.batchDelay??10,s=new Map,r=new Map,i=g=>g.type==="set"||g.type==="update",o=g=>`${g.type}_${g.key?.toString()||"default"}`,n=g=>{let h=new Map;for(let p of g){let m=`${p.type}_${p.key?.toString()||"default"}`;h.set(m,p)}return Array.from(h.values())},a=g=>{let h=r.get(g);h&&(globalThis.clearTimeout(h),r.delete(g))},l=(g,h)=>{let p=globalThis.setTimeout(h,t);r.set(g,p)},d=async(g,h,p)=>{let m=s.get(g);if(!(!m||m.length===0)){s.delete(g),a(g);try{let R=m.map(S=>S.action),v=n(R);for(let S of v)try{let U=await p(S);m.filter(E=>E.action.type===S.type&&E.action.key?.toString()===S.key?.toString()).forEach(E=>E.resolve(U))}catch(U){m.filter(E=>E.action.type===S.type&&E.action.key?.toString()===S.key?.toString()).forEach(E=>E.reject(U))}}catch(R){m.forEach(v=>v.reject(R))}}},u=async(g,h,p)=>new Promise((m,R)=>{let v=o(g),S=s.get(v);S||(S=[],s.set(v,S)),S.push({action:g,resolve:m,reject:R,timestamp:Date.now()}),a(v),S.length>=e?setImmediate(()=>d(v,h,p)):l(v,()=>d(v,h,p))});return{name:"batching",setup:()=>{},cleanup:async()=>{r.forEach(g=>globalThis.clearTimeout(g)),r.clear(),s.clear()},reducer:g=>h=>async p=>i(p)?u(p,g,h):h(p)}};var J=(c={})=>{let{comparator:e=(r,i)=>{if(r===i)return!0;if(typeof r!="object"||typeof i!="object"||r===null||i===null)return r===i;let o=Object.keys(r),n=Object.keys(i);return o.length!==n.length?!1:o.every(a=>Object.prototype.hasOwnProperty.call(i,a)&&r[a]===i[a])},segments:t=[]}=c,s=new Map;return{name:"shallow-compare",setup:r=>{},reducer:r=>i=>async o=>{if(o.type!=="set"||t.length&&!t.includes(o.metadata?.segment??"default"))return i(o);let n=o.key,a=s.get(n),l=o.value;if(a!==void 0&&e(a,l))return{...a,t:{valueNotChanged:!0,originalValue:a}};let d=await i(o);return s.set(n,l),d}}};var $=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,...s}=e.metadata||{},r={...e,metadata:s};switch(r.type){case"get":return this.api.storage.doGet(r.key);case"set":return await this.api.storage.doSet(r.key,r.value),this.api.storage.doGet(r.key);case"update":return Array.isArray(r.value)?(await this.api.storage.doUpdate(r.value),this.api.storage.doGet("")):r.value;case"delete":return this.api.storage.doDelete(r.key);case"clear":return this.api.storage.doClear();case"init":{let i=await this.api.storage.doGet("");return Object.keys(i||{}).length>0?i:r.value?(await this.api.storage.doSet("",r.value),this.api.storage.doGet("")):i}case"keys":return this.api.storage.doKeys();default:throw new Error(`Unknown action type: ${r.type}`)}}initializeMiddlewares(){if(this.initialized)return;let e=this.baseOperation.bind(this);for(let t of[...this.middlewares].reverse()){let s=e;e=async r=>{if(r.metadata?.processed)return s(r);let i={...r,metadata:{...r.metadata,processed:!0,timestamp:r.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(s)(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 t}}};function b(c){return c instanceof f&&c.isUnparseable()?[c.toString()]:c.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function w(c,e){return b(e).reduce((s,r)=>s===void 0?void 0:s[r],c)}function P(c,e,t){if(e==="")return t;let s=b(e);if(e instanceof f&&e.isUnparseable())return c[e.toString()]=t,c;let r=s.pop(),i=s.reduce((o,n)=>{let a=s[s.indexOf(n)+1],l=!Number.isNaN(Number(a));return n in o||(o[n]=l?[]:{}),o[n]},c);return i[r]=t,c}var A=class c{constructor(e,t,s,r){this.config=e;this.pluginExecutor=t;this.eventEmitter=s;this.logger=r;this.name=e.name,this.middlewareModule=new $({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="*";static STORAGE_TYPE;name;e={status:"idle"};statusSubscribers=new Set;selectorPathCache=new WeakMap;middlewareModule;initializedMiddlewares=null;subscribers=new Map;get initStatus(){return{...this.e}}async waitForReady(){if(this.e.status==="ready")return this;if(this.e.status==="error")throw this.e.error||new Error("Storage initialization failed");return new Promise((e,t)=>{let s=this.onStatusChange(r=>{r.status==="ready"?(s(),e(this)):r.status==="error"&&(s(),t(r.error||new Error("Storage initialization failed")))})})}onStatusChange(e){return this.statusSubscribers.add(e),e(this.initStatus),()=>{this.statusSubscribers.delete(e)}}updateInitStatus(e){let t=this.e.status;this.e={...this.e,...e},t!==this.e.status&&this.logger?.debug(`Storage "${this.name}" status changed: ${t} -> ${this.e.status}`);let s=this.initStatus;this.statusSubscribers.forEach(r=>{try{r(s)}catch(i){this.logger?.error("Error in status change callback",{error:i})}})}async initialize(){if(this.e.status==="ready")return this;if(this.e.status==="loading")return this.waitForReady();this.updateInitStatus({status:"loading",error:void 0});try{let e=await this.doInitialize();return this.updateInitStatus({status:"ready",error:void 0}),e}catch(e){throw this.updateInitStatus({status:"error",error:e instanceof Error?e:new Error(String(e))}),e}}ensureReady(){if(this.e.status!=="ready")throw new Error(`Storage "${this.name}" is not ready. Current status: ${this.e.status}`)}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={})=>W(e),shallowCompare:(e={})=>J(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){this.ensureReady();try{let t={operation:"get",timestamp:Date.now(),key:e},s=await this.middlewareModule.dispatch({type:"get",key:e,metadata:t}),r=await this.pluginExecutor?.executeAfterGet(e,s,t)??s;return await this.emitEvent({type:"storage:select",payload:{key:e,value:r}}),r}catch(t){throw this.logger?.error("Error getting value",{key:e,error:t}),t}}async set(e,t){this.ensureReady();try{let s={operation:"set",timestamp:Date.now(),key:e},r=await this.pluginExecutor?.executeBeforeSet(t,s)??t,i=await this.middlewareModule.dispatch({type:"set",key:e,value:r,metadata:s}),o=i?.t?.valueNotChanged===!0,n;if(o&&i?.t?.originalValue!==void 0?n=i.t.originalValue:n=await this.pluginExecutor?.executeAfterSet(e,i,s)??i,!o){let l=[e.toString()];this.notifySubscribers(e,n),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:n,changedPaths:l}),await this.emitEvent({type:"storage:update",payload:{key:e,value:n,changedPaths:l}})}}catch(s){throw this.logger?.error("Error setting value",{key:e,error:s}),s}}async update(e){this.ensureReady();try{let t={operation:"update",timestamp:Date.now()},s=await this.getState(),r=structuredClone(s);e(r);let i=this.findChangedPaths(s,r);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 g of i){let h=g.split(".")[0];o.add(h)}let n=await Promise.all(Array.from(o).map(async g=>{let h={...t,key:g},p=await this.pluginExecutor?.executeBeforeSet(r[g],h)??r[g];return{key:g,value:p}})),a=await this.middlewareModule.dispatch({type:"update",value:n,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(i)}}),l={};Array.isArray(a)?a.forEach(g=>{g&&typeof g=="object"&&"key"in g&&"value"in g&&(l[g.key]=g.value)}):a&&typeof a=="object"&&(l={...a});let d=Object.keys(l).filter(g=>!this.isEqual(s[g],l[g]));if(d.length===0){this.logger?.debug&&this.logger.debug("No actual changes after middleware processing");return}let u={};d.forEach(g=>{u[g]=l[g]}),this.logger?.debug&&this.logger.debug("Notifying subscribers about changes:",{keys:d}),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:d,value:u,changedPaths:Array.from(i)});for(let g of i)try{let h=g.split(".")[0];if(h in u){let p;if(g===h)p=u[h];else{let m=g.substring(h.length+1);p=w(u[h],m)}p!==void 0&&this.notifySubscribers(g,p)}}catch(h){this.logger?.error("Error notifying path subscribers",{path:g,error:h})}await this.emitEvent({type:"storage:update",payload:{state:u,key:d,changedPaths:Array.from(i)}})}catch(t){throw this.logger?.error("Error updating state",{error:t}),t}}async delete(e){this.ensureReady();try{let t={operation:"delete",timestamp:Date.now(),key:e};if(await this.pluginExecutor?.executeBeforeDelete(e,t)===!1)return;let r=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});if(r===!1)return;await this.pluginExecutor?.executeAfterDelete(e,t);let o=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:r,changedPaths:o}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:r,changedPaths:o}})}catch(t){throw this.logger?.error("Error deleting value",{key:e,error:t}),t}}async clear(){this.ensureReady();try{this.pluginExecutor?.executeOnClear(),await this.middlewareModule.dispatch({type:"clear"})}catch(e){throw this.logger?.error("Error clearing storage",{error:e}),e}}async keys(){this.ensureReady();try{return await this.middlewareModule.dispatch({type:"keys"})}catch(e){throw this.logger?.error("Error getting keys",{error:e}),e}}async has(e){this.ensureReady();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{if(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),this.statusSubscribers.clear(),this.config.singleton?.enabled){let e=this.constructor.STORAGE_TYPE,t=x.generate(this.config,e);C.remove(t)}this.updateInitStatus({status:"idle"}),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 s=!1;return this.subscribers.get(e).add(t),this.get(e).then(r=>{try{s||(s=!0,t(r))}catch(i){this.logger?.error("Error in initial callback",{key:e,error:i})}}),()=>{let r=this.subscribers.get(e);r&&(r.delete(t),r.size===0&&this.subscribers.delete(e))}}createDummyState(){let e={get:(t,s)=>(t[s]=t[s]||new Proxy({},e),t[s])};return new Proxy({},e)}isEqual(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;let s=typeof e;if(s!==typeof t)return!1;if(s!=="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 n=0;n<e.length;n++)if(!this.isEqual(e[n],t[n]))return!1;return!0}let i=Object.keys(e),o=Object.keys(t);return i.length!==o.length?!1:i.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&this.isEqual(e[n],t[n]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let s=[],r=(i="")=>({get:(o,n)=>{if(typeof n=="symbol")return Reflect.get(o,n);let a=i?`${i}.${n}`:n;return s.push(a),new Proxy({},r(a))},has:(o,n)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(o,n,a)=>new Proxy(()=>{},r(i))});try{e(new Proxy(t,r()))}catch{}return s.length===0?"":(s.sort((i,o)=>o.length-i.length),this.selectorPathCache.set(e,s[0]),s[0])}notifySubscribers(e,t){let s=e.toString(),r=this.subscribers.get(s);r?.size&&new Set(r).forEach(o=>{try{o(t)}catch(n){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:s,error:n})}})}findChangedPaths(e,t,s="",r=new Set,i=new WeakMap){if(e===t)return r;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e!==t&&r.add(s||""),r;if(i.has(e))return r;i.set(e,!0);let o=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let n of o){let a=e[n],l=t[n];if(a===l)continue;let d=s?`${s}.${n}`:n;a&&l&&typeof a=="object"&&typeof l=="object"&&!Array.isArray(a)&&!Array.isArray(l)?this.findChangedPaths(a,l,d,r,i):Array.isArray(a)&&Array.isArray(l)?this.isEqual(a,l)||r.add(d):this.isEqual(a,l)||r.add(d)}return r}subscribeBySelector(e,t){let s=this.createDummyState(),r=this.extractPath(e,s);this.logger?.debug&&this.logger.debug("Subscribing to path:",{path:r});let i=async o=>{try{if(o==null){let l=await this.getState(),d=e(l);t(d);return}if(typeof o!="object"||o===null){t(o);return}let n=await this.getState(),a=e(n);t(a)}catch(n){this.logger?.error("Error in selector callback",{path:r,error:n}),t(o)}};return r?this.subscribeByKey(r,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 _=class c{constructor(e,t,s){this.dbName=e;this.logger=s;this.dbVersion=t}static instances=new Map;db=null;initPromise=null;storeNames=new Set;dbVersion;static getInstance(e,t=1,s){c.instances.has(e)||c.instances.set(e,new c(e,t,s));let r=c.instances.get(e);return t>r.dbVersion&&(r.dbVersion=t),r}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,s)=>{this.logger?.debug(`Opening database "${this.dbName}" with version ${this.dbVersion}`);let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=()=>{this.logger?.error(`Failed to open database "${this.dbName}"`,{error:r.error}),s(r.error)},r.onsuccess=()=>{this.db=r.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)},r.onupgradeneeded=i=>{let o=i.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let n of e)o.objectStoreNames.contains(n)||(this.logger?.debug(`Creating store "${n}"`),o.createObjectStore(n))}})}closeDatabase(){this.db&&(this.db.close(),this.db=null,this.initPromise=null)}async deleteDatabase(){return this.closeDatabase(),new Promise((e,t)=>{let s=indexedDB.deleteDatabase(this.dbName);s.onsuccess=()=>{this.logger?.debug(`Database "${this.dbName}" deleted successfully`),c.instances.delete(this.dbName),this.storeNames.clear(),e()},s.onerror=()=>{this.logger?.error(`Failed to delete database "${this.dbName}"`,{error:s.error}),t(s.error)}})}async ensureStoresExist(e){await this.initialize();let t=e.filter(s=>!this.db.objectStoreNames.contains(s));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}},L=class{constructor(e,t=1,s){this.dbName=e;this.logger=s;this.version=t}db=null;version;getCurrentVersion(){return this.version}openDatabase(e,t=[]){return new Promise((s,r)=>{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}),r(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)}),s(this.db)},i.onupgradeneeded=o=>{let n=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 a of t)n.objectStoreNames.contains(a)||(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "${a}"`),n.createObjectStore(a))}})}async ensureStoresExist(e){this.db||(this.db=await this.openDatabase(this.version));let t=e.filter(s=>!this.db.objectStoreNames.contains(s));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)}},D=class c extends A{static STORAGE_TYPE="memory";DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,s,r){super(e,t,s,r);let i=e.options;this.DB_NAME=i.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=i.dbVersion||1,this.dbManager=_.getInstance(this.DB_NAME,this.DB_VERSION,r)}getStorageType(){return"memory"}static create(e,t,s,r){return I.handleSingletonCreation(e,this.STORAGE_TYPE,i=>new c(i,t,s,r),r)}async doInitialize(){try{if(this.logger?.debug(`Initializing IndexedDB storage "${this.STORE_NAME}"`),await this.dbManager.ensureStoreExists(this.STORE_NAME),!(await this.dbManager.initialize()).objectStoreNames.contains(this.STORE_NAME))throw new Error(`Store "${this.STORE_NAME}" not found after initialization`);return this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this.logger?.debug(`IndexedDB storage "${this.STORE_NAME}" initialized successfully`),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 s=indexedDB.open(e);s.onsuccess=()=>{let r=s.result.version;s.result.close(),t(r)},s.onerror=()=>{t(0)}}catch{t(0)}})}static async createStorages(e,t,s){let i=await this.getCurrentDBVersion(e)||1,o=new L(e,i,s),n=Object.values(t).map(l=>l.name);await o.ensureStoresExist(n);let a={};for(let[l,d]of Object.entries(t)){let u=new c({...d,options:{dbName:e,dbVersion:o.getCurrentVersion()}},d.pluginExecutor,d.eventEmitter,s);a[l]=await u.initialize()}return a}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 s=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!s.objectStoreNames.contains(this.STORE_NAME))throw new Error(`Object store "${this.STORE_NAME}" still doesn't exist after repair attempt`);return s.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((r,i)=>{let o=t.getAll();o.onerror=()=>i(o.error),o.onsuccess=()=>{let n=o.result,a=t.getAllKeys();a.onsuccess=()=>{let l=a.result.reduce((d,u,g)=>(u!=="root"&&(d[u]=n[g]),d),{});r(l)},a.onerror=()=>i(a.error)}});if(e instanceof f&&e.isUnparseable())return new Promise((r,i)=>{let o=t.get(e.valueOf());o.onerror=()=>i(o.error),o.onsuccess=()=>r(o.result)});let s=b(e);if(s.length>1){let r=s[0];return new Promise((i,o)=>{let n=t.get(r);n.onerror=()=>o(n.error),n.onsuccess=()=>{let a=n.result;if(!a){i(void 0);return}let l=w(a,s.slice(1).join("."));i(l)}})}return new Promise((r,i)=>{let o=t.get(s[0]);o.onerror=()=>i(o.error),o.onsuccess=()=>r(o.result)})}async doSet(e,t){if(e===""){let i=await this.getObjectStore("readwrite");return new Promise((o,n)=>{let a=i.transaction;a.oncomplete=()=>{o()},a.onerror=()=>{n(a.error)};let l=i.clear();l.onsuccess=()=>{let d=Object.entries(t);for(let[u,g]of d)i.put(g,u)},l.onerror=()=>{n(l.error)}})}let s=await this.getObjectStore("readwrite");if(e instanceof f&&e.isUnparseable()){await this.putValueInStore(s,e.valueOf(),t);return}let r=b(e);if(r.length>1){let i=r[0];return new Promise((o,n)=>{let a=s.get(i);a.onerror=()=>n(a.error),a.onsuccess=()=>{let l=a.result||{},d=P(l,r.slice(1).join("."),t),u=s.put(d,i);u.onerror=()=>n(u.error),u.onsuccess=()=>o()}})}await this.putValueInStore(s,r[0],t)}async putValueInStore(e,t,s){return new Promise((r,i)=>{let o=e.put(s,t.valueOf());o.onerror=()=>i(o.error),o.onsuccess=()=>r()})}async doUpdate(e){let t=new Map,s=[];for(let{key:r,value:i}of e){if(r instanceof f&&r.isUnparseable()){s.push({key:r.valueOf(),value:i});continue}let o=b(r),n=o[0],a=o.slice(1);t.has(n)||t.set(n,[]),t.get(n).push({path:a,value:i})}try{for(let{key:r,value:i}of s){let o=await this.getObjectStore("readwrite");await this.putValueInStore(o,r,i)}for(let[r,i]of t){let n={...await this.doGet(r)||{}};for(let{path:l,value:d}of i)l.length===0?n=d:n=P(n,l.join("."),d);let a=await this.getObjectStore("readwrite");await this.putValueInStore(a,r,n)}}catch(r){throw this.logger?.error("Error during update:",{error:r}),r}}async doDelete(e){let t=await this.getObjectStore("readwrite");if(e instanceof f&&e.isUnparseable())return new Promise((i,o)=>{let n=t.delete(e.valueOf());n.onerror=()=>o(n.error),n.onsuccess=()=>i(!0)});let s=b(e);if(s.length===1)return new Promise((i,o)=>{let n=t.delete(s[0]);n.onerror=()=>o(n.error),n.onsuccess=()=>i(!0)});let r=s[0];return new Promise((i,o)=>{let n=t.get(r);n.onerror=()=>o(n.error),n.onsuccess=()=>{let a=n.result;if(!a){i(!1);return}let l=w(a,s.slice(0,-1).join(".")),d=s[s.length-1];if(!l||!(d in l)){i(!1);return}if(Array.isArray(l)){let g=parseInt(d,10);isNaN(g)?delete l[d]:l.splice(g,1)}else delete l[d];let u=t.put(a,r);u.onerror=()=>o(u.error),u.onsuccess=()=>i(!0)}})}async doClear(){let e=await this.getObjectStore("readwrite");return new Promise((t,s)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>s(r.error)})}async doKeys(){let t=(await this.getObjectStore()).getAllKeys();return new Promise((s,r)=>{t.onsuccess=()=>{s(t.result)},t.onerror=()=>r(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 O=class c extends A{static STORAGE_TYPE="localStorage";constructor(e,t,s,r){super(e,t,s,r)}static create(e,t,s,r){return I.handleSingletonCreation(e,this.STORAGE_TYPE,i=>new c(i,t,s,r),r)}async doInitialize(){try{return this.logger?.debug(`Initializing LocalStorage "${this.name}"`),this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this.logger?.debug(`LocalStorage "${this.name}" initialized successfully`),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 s=JSON.parse(t);return e instanceof f&&e.isUnparseable()?s[e.valueOf()]:w(s,e)}async doSet(e,t){let s=localStorage.getItem(this.name),r=s?JSON.parse(s):{};if(e instanceof f&&e.isUnparseable()){r[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(r));return}let i=P({...r},e,t);localStorage.setItem(this.name,JSON.stringify(i))}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return!1;let s=JSON.parse(t);if(e instanceof f&&e.isUnparseable()){let a=e.valueOf();return a in s?(delete s[a],localStorage.setItem(this.name,JSON.stringify(s)),!0):!1}let r=b(e),i=r.slice(0,-1).join("."),o=r[r.length-1],n=i?w(s,i):s;return!n||!(o in n)?!1:(delete n[o],localStorage.setItem(this.name,JSON.stringify(s)),!0)}async doUpdate(e){let t=localStorage.getItem(this.name),s=t?JSON.parse(t):{};for(let{key:r,value:i}of e)r instanceof f&&r.isUnparseable()?s[r.valueOf()]=i:P(s,r,i);localStorage.setItem(this.name,JSON.stringify(s))}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 N=class c extends A{static STORAGE_TYPE="memory";storage=new Map;constructor(e,t,s,r){super(e,t,s,r)}static create(e,t,s,r){return I.handleSingletonCreation(e,this.STORAGE_TYPE,i=>new c(i,t,s,r),r)}async doInitialize(){try{return this.logger?.debug(`Initializing MemoryStorage "${this.name}"`),this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this.logger?.debug(`MemoryStorage "${this.name}" initialized successfully`),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()]:w(t,e)}async doSet(e,t){let s=this.storage.get(this.name)||{};if(e instanceof f&&e.isUnparseable()){s[e.valueOf()]=t,this.storage.set(this.name,s);return}let r=P({...s},e,t);this.storage.set(this.name,r)}async doDelete(e){let t=this.storage.get(this.name);if(!t)return!1;if(e instanceof f&&e.isUnparseable()){let n=e.valueOf();return n in t?(delete t[n],this.storage.set(this.name,t),!0):!1}let s=b(e),r=s.slice(0,-1).join("."),i=s[s.length-1],o=r?w(t,r):t;return!o||!(i in o)?!1:(delete o[i],this.storage.set(this.name,t),!0)}async doUpdate(e){let s={...this.storage.get(this.name)||{}};for(let{key:r,value:i}of e)r instanceof f&&r.isUnparseable()?s[r.valueOf()]=i:P(s,r,i);this.storage.set(this.name,s)}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)}};var j=class{static createMemory(e,t,s,r){return N.create(e,t,s,r)}static createLocal(e,t,s,r){return O.create(e,t,s,r)}static createIndexedDB(e,t,s,r){return D.create(e,t,s,r)}static create(e,t,s,r){switch(e.type){case"memory":return this.createMemory(e,t,s,r);case"localStorage":return this.createLocal(e,t,s,r);case"indexedDB":return this.createIndexedDB(e,t,s,r);default:throw new Error(`Unsupported storage type: ${e.type}`)}}};export{V as ConfigMergeStrategy,D as IndexedDBStorage,O as LocalStorage,N as MemoryStorage,F as SelectorModule,G as StorageEvents,j as StorageFactory,k as StoragePluginModule,H as StorageStatus,Y as broadcastMiddleware};