UNPKG

synapse-storage

Version:

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

1 lines 74 kB
var le={debug:(n,...e)=>{process.env.NODE_ENV},log:(n,...e)=>{process.env.NODE_ENV},info:(n,...e)=>{},warn:(n,...e)=>{},error:(n,...e)=>{}};function de(n){return`${n?`${n}|`:""}${Math.random().toString(36).substring(2,9)+Date.now().toString(36)}`}function ue(n){let e={};return n.forEach((t,s)=>{e[s.toLowerCase()]=t}),e}function N(n={},e={}){return{...n,...e,getFromStorage:n.getFromStorage||(t=>{try{let s=localStorage.getItem(t);return s?JSON.parse(s):void 0}catch{return}}),getCookie:n.getCookie||(t=>{try{let s=document.cookie.match(new RegExp(`(?:^|; )${t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")}=([^;]*)`));return s?decodeURIComponent(s[1]):void 0}catch{return}})}}async function pe(n,e){let t=new Headers,s=e||N({},{});if(n)try{t=await Promise.resolve(n(t,s))}catch{}return t}function ge(n,e){return async(t,s)=>{let r=new Headers(t);if(n)try{r=await Promise.resolve(n(r,s))}catch{}if(e)try{r=await Promise.resolve(e(r,s))}catch{}return r}}var k=(a=>(a.Json="json",a.Blob="blob",a.ArrayBuffer="arrayBuffer",a.Text="text",a.FormData="formData",a.Raw="raw",a))(k||{});function he(n){let e=n.toLowerCase().split(";")[0].trim();if(e.includes("application/json"))return"json";if(e.includes("text/"))return"text";if(e.includes("multipart/form-data"))return"formData";if(e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"))return"blob"}function Z(n){let e=n.get("content-type")||"",t=n.get("content-disposition")||"",s=e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"),r=t.includes("attachment")||t.includes("filename=");return s||r}function Ke(n){let e=n.get("content-disposition");if(!e)return;let t=e.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);if(t&&t[1])return t[1].replace(/['"]/g,"").trim()}function ye(n){let e=n.get("content-type")||"",t=n.get("content-disposition")||"",s=n.get("content-length");return Z(n)?{filename:Ke(n),contentType:e,contentDisposition:t,size:s?parseInt(s,10):void 0}:void 0}async function qe(n,e){let t=e,s=n.headers.get("content-type")||"";!t&&s&&(Z(n.headers)?t="blob":t=he(s)),t||(t="json");try{let r;switch((t==="blob"||t==="arrayBuffer")&&(r=ye(n.headers)),t){case"json":try{let a=await n.json();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}catch{let i=await n.text();return n.ok?{data:i,fileMetadata:r}:{error:i,fileMetadata:r}}case"text":{let a=await n.text();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"blob":{let a=await n.blob();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"arrayBuffer":{let a=await n.arrayBuffer();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"formData":{let a=await n.formData();return n.ok?{data:a,fileMetadata:r}:{error:a,fileMetadata:r}}case"raw":return n.ok?{data:n,fileMetadata:r}:{error:n,fileMetadata:r};default:let o=await n.blob();return n.ok?{data:o,fileMetadata:r}:{error:o,fileMetadata:r}}}catch(r){return n.ok?{data:void 0}:{error:r}}}function fe(n){let{baseUrl:e,timeout:t=3e4,fetchFn:s=fetch,credentials:r="same-origin"}=n;return async(o,a={},i)=>{let{path:c,method:d,body:l,query:p,responseFormat:u}=o,{signal:h,timeout:g=t,responseFormat:y}=a,v=y||u,f=new URL(c.startsWith("http")?c:`${e}${c}`);p&&Object.entries(p).forEach(([S,T])=>{T!=null&&(Array.isArray(T)?T.forEach(D=>f.searchParams.append(S,String(D))):f.searchParams.append(S,String(T)))});let m;if(l!==void 0)if(l instanceof FormData||l instanceof Blob)m=l;else if(typeof l=="object"&&l!==null)try{m=JSON.stringify(l),i.has("Content-Type")||i.set("Content-Type","application/json")}catch{m=String(l)}else m=String(l);let x,w=new Promise((S,T)=>{g&&(x=window.setTimeout(()=>{T(new Error(`\u041F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u043E \u0432\u0440\u0435\u043C\u044F \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u0437\u0430\u043F\u0440\u043E\u0441\u0430 (${g}\u043C\u0441)`))},g))});try{let S=s(f.toString(),{method:d,headers:i,body:m,signal:h,credentials:r}),T=await Promise.race([S,w]),{data:D,error:M,fileMetadata:ce}=await qe(T,v);return{data:D,error:M,ok:T.ok,status:T.status,statusText:T.statusText,headers:T.headers,fileDownloadResult:ce}}catch(S){let T=S;return{error:T,ok:!1,status:0,statusText:T.message,headers:new Headers}}finally{x&&window.clearTimeout(x)}}}function me(n,e=[]){let t={};return!n||e.length===0||e.forEach(s=>{n.has(s)&&(t[s]=n.get(s)||"")}),t}var j=class{constructor(e,t,s,r,o,a){this.name=e;this.queryStorage=t;this.configCurrentEndpoint=s;this.cacheableHeaderKeys=r;this.globalCacheConfig=o;this.baseQueryConfig=a;this.prepareHeaders=ge(a.prepareHeaders,s.prepareHeaders),this.queryFunction=fe({baseUrl:a.baseUrl,fetchFn:a.fetchFn,timeout:a.timeout,credentials:a.credentials}),this.cacheableHeaders=[...r||[],...s.includeCacheableHeaderKeys||[]].filter(i=>!s.excludeCacheableHeaderKeys?.includes(i)),this.meta.name=e,this.meta.tags=s.tags??this.meta.tags,this.meta.invalidatesTags=s.invalidatesTags??this.meta.invalidatesTags,this.meta.cache=this.queryStorage.createCacheConfig(this.configCurrentEndpoint)??this.meta.cache}endpointSubscribers=new Set;fetchCounts=0;meta={cache:!1,invalidatesTags:[],name:"",tags:[]};queryFunction;cacheableHeaders;prepareHeaders;request(e,t){this.fetchCounts++;let s=de(this.name),r=new AbortController,o=new Set,a={status:"idle",requestParams:e,headers:{},error:void 0,data:void 0,fromCache:!1},i=N({requestParams:e},t?.context||{}),c=l=>{Object.assign(a,l),o.forEach(p=>{p({...a})})},d=new Promise(async(l,p)=>{try{let u=await pe(this.prepareHeaders,i),h=me(u,t?.cacheableHeaderKeys?t.cacheableHeaderKeys:this.cacheableHeaders),g=this.queryStorage.shouldCache(this.configCurrentEndpoint,t),[y,v]=this.queryStorage.createCacheKey(this.name,{...e,...h}),f;if(g&&(f=await this.queryStorage.getCachedResult(y)),f)c({fromCache:!0,status:"success",data:f.data,error:void 0,headers:f.headers,requestParams:e}),l({...f,fromCache:!0});else{c({fromCache:!1,status:"loading"});let m=this.configCurrentEndpoint.request(e,t?.context),x={...t,signal:r.signal},w=await this.queryFunction(m,x,u);if(w.ok){let{headers:S,...T}=w;if(g){let D=this.queryStorage.createCacheConfig(this.configCurrentEndpoint);await this.queryStorage.setCachedResult(y,{...T,headers:ue(S)},D,v??{},this.configCurrentEndpoint.tags??[],this.configCurrentEndpoint.invalidatesTags??[])}c({fromCache:!1,status:"success",data:w.data,error:void 0,headers:w.headers,requestParams:e}),this.endpointSubscribers.forEach(D=>{let M={status:"success",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};D(M)}),l({...w,fromCache:!1})}else c({fromCache:!1,status:"error",data:void 0,error:w.error,headers:w.headers,requestParams:e}),this.endpointSubscribers.forEach(S=>{let T={status:"error",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:w.error};S(T)}),p(w.error)}}catch(u){c({fromCache:!1,status:"error",data:void 0,error:u,headers:void 0,requestParams:e}),p(u)}});return{id:s,subscribe(l,p={}){let{autoUnsubscribe:u=!0}=p;o.add(l),l(a);let h=()=>o.delete(l);return u&&d.finally(()=>{h()}),h},wait:()=>d,waitWithCallbacks(l={}){let{idle:p,loading:u,success:h,error:g}=l;return this.subscribe(y=>{switch(y.status){case"idle":p?.(y);break;case"loading":u?.(y);break;case"success":h?.(y.data,y);break;case"error":g?.(y.error,y);break}},{autoUnsubscribe:!0}),d},abort:()=>{r&&!r.signal.aborted&&r.abort()},then:(l,p)=>d.then(l,p),catch:l=>d.catch(l),finally:l=>d.finally(l)}}subscribe(e){this.endpointSubscribers.add(e);let t={status:"idle",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};return e(t),()=>this.endpointSubscribers.delete(e)}reset(){return this.fetchCounts=0,Promise.resolve()}destroy(){this.endpointSubscribers.clear()}};var b=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 C=class{static createMetadata(e=0,t=[]){let s=Date.now(),r=e>0?s+e:1/0;return{createdAt:s,updatedAt:s,expiresAt:r,tags:t,createdAtDateTime:this.formatDateTime(s),updatedAtDateTime:this.formatDateTime(s),expiresAtDateTime:r===1/0?"never":this.formatDateTime(r)}}static formatDateTime(e){return new Date(e).toISOString()}static isExpired(e){return Date.now()>e.expiresAt}static updateMetadata(e){return{...e,updatedAt:Date.now()}}static createKey(...e){return new b(e.join("_"))}static createApiKey(e,t){if(!t)return[new b(e,!0),t];let s=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>`${r}=${o}`).join("&");return[new b(`${e}_${s}`,!0),t]}static hasAnyTag(e,t=[]){return!e.tags||!t.length?!1:t.some(s=>e.tags?.includes(s))}};var U=class{constructor(e,t){this.storageExternal=e;this.globalCacheConfig=t}storage=null;cleanupInterval=null;defaultCacheOptions={ttl:5*60*1e3,cleanup:{enabled:!0,interval:10*60*1e3},invalidateOnError:!0};async initialize(){return await this.createStorage(),this.startCleanupInterval(),this}async createStorage(){try{let e=this.storageExternal;await e.initialize(),this.storage=e}catch(e){throw e}}startCleanupInterval(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);let e=typeof this.globalCacheConfig=="object"?this.globalCacheConfig.cleanup:this.defaultCacheOptions.cleanup;e?.enabled&&e.interval&&(this.cleanupInterval=setInterval(()=>{this.cleanup().catch(t=>{})},e.interval))}getStorage(){return this.storage}createCacheKey(e,t){return C.createApiKey(e,t)}async getCachedResult(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let t=await this.storage.get(e);if(!t)return;if(C.isExpired(t.metadata)){await this.storage.delete(e);return}let s={...t,metadata:C.updateMetadata(t.metadata)};return await this.storage.set(e,s),t.data}async setCachedResult(e,t,s,r,o,a){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");a?.length&&await this.invalidateCacheByTags(a);let i=C.createMetadata(s.ttl,o),c={data:t,metadata:i,params:r};await this.storage.set(e,c)}shouldCache(e,t){return!(this.globalCacheConfig===!1||e?.cache===!1||typeof e?.cache=="object"&&e?.cache.ttl===0||t?.disableCache===!0||this.globalCacheConfig===void 0&&e?.cache===void 0)}createCacheConfig(e){let t=this.defaultCacheOptions;if(typeof this.globalCacheConfig=="object"&&(t=this.globalCacheConfig),typeof e?.cache=="object"){let s=e.cache;t={...t,...s}}return t}async invalidateCacheByTags(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let t=await this.storage.keys();for(let s of t){let r=await this.storage.get(s);r&&C.hasAnyTag(r.metadata,e)&&await this.storage.delete(s)}}async invalidateCache(e){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");await this.storage.delete(e)}async cleanup(){if(!this.storage)throw new Error("\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E");let e=await this.storage.keys();for(let t of e){let s=await this.storage.get(t);s&&C.isExpired(s.metadata)&&await this.storage.delete(t)}}async destroy(){this.cleanupInterval&&(window.clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.storage&&(await this.storage.destroy(),this.storage=null)}};var Se=class{queryStorage;cacheableHeaderKeys;globalCacheConfig;baseQueryConfig;storageExternal;createEndpoints;endpoints={};constructor(e){this.cacheableHeaderKeys=e.cacheableHeaderKeys,this.globalCacheConfig=e.cache,this.baseQueryConfig=e.baseQuery,this.storageExternal=e.storage,this.createEndpoints=e.endpoints}async init(){return this.queryStorage=await new U(this.storageExternal,this.globalCacheConfig).initialize(),await this.initializeEndpoints(),this}async initializeEndpoints(){let e=s=>s,t=await this.createEndpoints(e)||{};for(let[s,r]of Object.entries(t)){let o=s;this.endpoints[o]=new j(s,this.queryStorage,r,this.cacheableHeaderKeys,this.globalCacheConfig,this.baseQueryConfig)}}getEndpoints(){return this.endpoints}async request(e,t,s){let o=this.getEndpoints()[e];if(!o)throw new Error(`\u042D\u043D\u0434\u043F\u043E\u0438\u043D\u0442 ${String(e)} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`);try{return await o.request(t,s).wait()}catch(a){throw le.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043A ${String(e)}`,{error:a,params:t}),a}}async destroy(){await Promise.all(Object.values(this.endpoints).map(async e=>(e.destroy(),Promise.resolve()))),this.endpoints={},await this.queryStorage.destroy()}};var E=!1,F=new Map;function be(n){let e=0;if(n.length===0)return e.toString(36);for(let t=0;t<n.length;t++){let s=n.charCodeAt(t);e=(e<<5)-e+s,e=e&e}return Math.abs(e).toString(36).substring(0,6)}function A(n,e){if(n===e)return!0;if(n==null||e==null)return!1;if(typeof n!="object"&&typeof n!="function"&&typeof e!="object"&&typeof e!="function")return n===e;if(typeof n!=typeof e)return!1;if(n instanceof Date&&e instanceof Date)return n.getTime()===e.getTime();if(Array.isArray(n)&&Array.isArray(e)){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!A(n[t],e[t]))return!1;return!0}if(typeof n=="object"&&typeof e=="object"){let t=Object.keys(n),s=Object.keys(e);return t.length!==s.length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)?A(n[r],e[r]):!1)}return!1}function Te(n,e=A){let t,s,r=!1;return function(a){if(!r||t!==a){let i=n(a);(!r||!e(i,s))&&(s=i),t=a,r=!0}return s}}var V=class{constructor(e,t,s=A,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}},z=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",o="";if(e){let a=t.toString();o=be(a)}else{let a=t.map(c=>c.getId()).join("_"),i=s.toString();o=be(a+i)}return`${this.storageName}_${r}_${o}`}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(o){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:o})}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),o=r?t||{}:s||{},a=o.name||this.generateName(r,e,r?void 0:t);if(this.localSelectorCache.has(a))return this.localSelectorCache.get(a).api;if(F.has(a)){let l=F.get(a);return l.refCount++,l.api}let i,c,d=[];if(r){let l=Te(e,o.equals||A),p=this.createSimpleSelector(l,{...o,name:a,equals:o.equals||A});i=p.api,d=p.unsubscribeFunctions}else{c=e;let l=this.createCombinedSelector(c,t,{...o,name:a,equals:o.equals||A});i=l.api,d=l.unsubscribeFunctions}return this.localSelectorCache.set(a,{api:i,dependencies:c,unsubscribeFunctions:d}),F.set(a,{api:i,refCount:1,unsubscribeFunctions:d}),i}createSimpleSelector(e,t){let s=async()=>{if(this.cachedState)return e(this.cachedState);let c=await this.source.getState();return this.cachedState=c,e(c)},r=new V(t.name,s,t.equals||A,this.logger),o=r.getId();this.subscriptions.set(o,r);let i=[this.source.subscribeToAll(async c=>{c?.type==="storage:update"&&(this.pendingUpdates.add(o),this.processPendingUpdates())})];return{api:{select:()=>s(),subscribe:c=>r.subscribe(c),getId:()=>o},unsubscribeFunctions:i}}createCombinedSelector(e,t,s){let r=Te(p=>t(...p),s.equals||A),o=async()=>{let p=await Promise.all(e.map(u=>u.select()));return r(p)},a=new V(s.name,o,s.equals||A,this.logger),i=a.getId();this.subscriptions.set(i,a);let c=null,d=()=>{c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,a.notify().catch(p=>this.logger?.error(`[${i}] \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:p}))},10)},l=e.map(p=>p.subscribe({notify:()=>{d()}}));return{api:{select:()=>o(),subscribe:p=>a.subscribe(p),getId:()=>i},unsubscribeFunctions:l}}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=F.get(t);s&&(s.refCount--,s.refCount<=0&&(s.unsubscribeFunctions.forEach(r=>r()),F.delete(t)))})}};var we=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 o of this.plugins.values())if(o.onBeforeSet)try{s=await o.onBeforeSet(s,r)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onBeforeSet`,{error:a}),a}return s}async executeAfterSet(e,t,s){let r=t,o=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterSet(e,r,o));for(let a of this.plugins.values())if(a.onAfterSet)try{r=await a.onAfterSet(e,r,o)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onAfterSet`,{key:e,error:i}),i}return r}async executeBeforeGet(e,t){let s=e,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeGet(s,r));for(let o of this.plugins.values())if(o.onBeforeGet)try{s=await o.onBeforeGet(s,r)}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onBeforeGet`,{key:e,error:a}),a}return s}async executeAfterGet(e,t,s){let r=t,o=this.createContext(s);this.parentExecutor&&(r=await this.parentExecutor.executeAfterGet(e,r,o));for(let a of this.plugins.values())if(a.onAfterGet)try{r=await a.onAfterGet(e,r,o)}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onAfterGet`,{key:e,error:i}),i}return r}async executeBeforeDelete(e,t){let s=!0,r=this.createContext(t);this.parentExecutor&&(s=await this.parentExecutor.executeBeforeDelete(e,r));for(let o of this.plugins.values())if(o.onBeforeDelete)try{s=await o.onBeforeDelete(e,r)&&s}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${o.name} onBeforeDelete`,{key:e,error:a}),a}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(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onAfterDelete`,{key:e,error:o}),o}}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 Ee=(r=>(r.IDLE="idle",r.LOADING="loading",r.READY="ready",r.ERROR="error",r))(Ee||{}),ee=(a=>(a.STORAGE_UPDATE="storage:update",a.STORAGE_DELETE="storage:delete",a.STORAGE_PATCH="storage:patch",a.STORAGE_SELECT="storage:select",a.STORAGE_CLEAR="storage:clear",a.STORAGE_DESTROY="storage:destroy",a))(ee||{});var L=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 Ne(n,e,t){switch(e){case"set":t?.key!==void 0&&t?.value!==void 0&&(await n.storage.doSet(t.key,t.value),n.storage.notifySubscribers(t.key,t.value));break;case"update":Array.isArray(t?.value)&&(await n.storage.doUpdate(t.value),t.value.forEach(({key:s,value:r})=>{n.storage.notifySubscribers(s,r)}));break;case"delete":t?.key!==void 0&&(await n.storage.doDelete(t.key),n.storage.notifySubscribers(t.key,void 0));break;case"clear":await n.storage.doClear(),n.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}n.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:t?.value,source:"broadcast"})}async function ke(n,e,t){switch(e){case"set":if(t?.key!==void 0){let s=await n.storage.doGet(t.key);n.storage.notifySubscribers(t.key,s)}break;case"update":if(Array.isArray(t?.value)){for(let{key:s}of t.value){let r=await n.storage.doGet(s);n.storage.notifySubscribers(s,r)}n.storage.notifySubscribers("*",{type:"storage:update",key:t.value.map(({key:s})=>s),value:t.value,source:"broadcast"})}break;case"delete":t?.key!==void 0&&n.storage.notifySubscribers(t.key,void 0);break;case"clear":n.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}e!=="update"&&n.storage.notifySubscribers("*",{type:"storage:update",key:t?.key,value:e==="delete"?void 0:t?.value,source:"broadcast"})}var ve=n=>{let{storageName:e,storageType:t}=n,s=`${t}-${e}`,r=new L(s,{debug:!0});return{name:"broadcast",setup:o=>(t==="memory"&&(r.setSyncHandler(async()=>{let a=await o.getState();return{type:"update",key:"*",value:Object.entries(a).map(([d,l])=>({key:d,value:l})),metadata:{batchUpdate:!0,timestamp:Date.now()}}}),r.requestSync().then(async a=>{if(a?.type==="update"&&Array.isArray(a.value))try{if(!a.value.every(c=>c&&typeof c=="object"&&"key"in c&&"value"in c))return;await o.storage.doUpdate(a.value),a.value.forEach(({key:c,value:d})=>{o.storage.notifySubscribers(c,d)}),o.storage.notifySubscribers("*",{type:"storage:update",value:a.value,source:"broadcast"})}catch{}})),r.subscribe(async a=>{let{type:i,payload:c}=a;t==="memory"?await Ne(o,i,c):await ke(o,i,c)})),reducer:o=>a=>async i=>{let c=await a(i);return["set","delete","clear","update"].includes(i.type)&&r.broadcast(i.type,i),c},cleanup:()=>{r.close()}}};var xe=(n={})=>{let e=n.batchSize??10,t=n.batchDelay??10,s=new Map,r=new Map,o=u=>u.type==="set"||u.type==="update",a=u=>`${u.type}_${u.key?.toString()||"default"}`,i=u=>{let h=new Map;for(let g of u){let y=`${g.type}_${g.key?.toString()||"default"}`;h.set(y,g)}return Array.from(h.values())},c=u=>{let h=r.get(u);h&&(globalThis.clearTimeout(h),r.delete(u))},d=(u,h)=>{let g=globalThis.setTimeout(h,t);r.set(u,g)},l=async(u,h,g)=>{let y=s.get(u);if(!(!y||y.length===0)){s.delete(u),c(u);try{let v=y.map(m=>m.action),f=i(v);for(let m of f)try{let x=await g(m);y.filter(S=>S.action.type===m.type&&S.action.key?.toString()===m.key?.toString()).forEach(S=>S.resolve(x))}catch(x){y.filter(S=>S.action.type===m.type&&S.action.key?.toString()===m.key?.toString()).forEach(S=>S.reject(x))}}catch(v){y.forEach(f=>f.reject(v))}}},p=async(u,h,g)=>new Promise((y,v)=>{let f=a(u),m=s.get(f);m||(m=[],s.set(f,m)),m.push({action:u,resolve:y,reject:v,timestamp:Date.now()}),c(f),m.length>=e?setImmediate(()=>l(f,h,g)):d(f,()=>l(f,h,g))});return{name:"batching",setup:()=>{},cleanup:async()=>{r.forEach(u=>globalThis.clearTimeout(u)),r.clear(),s.clear()},reducer:u=>h=>async g=>o(g)?p(g,u,h):h(g)}};var Re=(n={})=>{let{comparator:e=(r,o)=>{if(r===o)return!0;if(typeof r!="object"||typeof o!="object"||r===null||o===null)return r===o;let a=Object.keys(r),i=Object.keys(o);return a.length!==i.length?!1:a.every(c=>Object.prototype.hasOwnProperty.call(o,c)&&r[c]===o[c])},segments:t=[]}=n,s=new Map;return{name:"shallow-compare",setup:r=>{},reducer:r=>o=>async a=>{if(a.type!=="set"||t.length&&!t.includes(a.metadata?.segment??"default"))return o(a);let i=a.key,c=s.get(i),d=a.value;if(c!==void 0&&e(c,d))return{...c,t:{valueNotChanged:!0,originalValue:c}};let l=await o(a);return s.set(i,d),l}}};var H=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 o=await this.api.storage.doGet("");return Object.keys(o||{}).length>0?o:r.value?(await this.api.storage.doSet("",r.value),this.api.storage.doGet("")):o}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 o={...r,metadata:{...r.metadata,processed:!0,timestamp:r.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(s)(o)}}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 R(n){return n instanceof b&&n.isUnparseable()?[n.toString()]:n.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function P(n,e){return R(e).reduce((s,r)=>s===void 0?void 0:s[r],n)}function I(n,e,t){if(e==="")return t;let s=R(e);if(e instanceof b&&e.isUnparseable())return n[e.toString()]=t,n;let r=s.pop(),o=s.reduce((a,i)=>{let c=s[s.indexOf(i)+1],d=!Number.isNaN(Number(c));return i in a||(a[i]=d?[]:{}),a[i]},n);return o[r]=t,n}var O=class n{constructor(e,t,s,r){this.config=e;this.pluginExecutor=t;this.eventEmitter=s;this.logger=r;this.name=e.name,this.middlewareModule=new H({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;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(o){this.logger?.error("Error in status change callback",{error:o})}})}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={})=>xe(e),shallowCompare:(e={})=>Re(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,o=await this.middlewareModule.dispatch({type:"set",key:e,value:r,metadata:s}),a=o?.t?.valueNotChanged===!0,i;if(a&&o?.t?.originalValue!==void 0?i=o.t.originalValue:i=await this.pluginExecutor?.executeAfterSet(e,o,s)??o,!a){let d=[e.toString()];this.notifySubscribers(e,i),this.notifySubscribers(n.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:i,changedPaths:d}),await this.emitEvent({type:"storage:update",payload:{key:e,value:i,changedPaths:d}})}}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 o=this.findChangedPaths(s,r);if(o.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(o)});let a=new Set;for(let u of o){let h=u.split(".")[0];a.add(h)}let i=await Promise.all(Array.from(a).map(async u=>{let h={...t,key:u},g=await this.pluginExecutor?.executeBeforeSet(r[u],h)??r[u];return{key:u,value:g}})),c=await this.middlewareModule.dispatch({type:"update",value:i,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(o)}}),d={};Array.isArray(c)?c.forEach(u=>{u&&typeof u=="object"&&"key"in u&&"value"in u&&(d[u.key]=u.value)}):c&&typeof c=="object"&&(d={...c});let l=Object.keys(d).filter(u=>!this.isEqual(s[u],d[u]));if(l.length===0){this.logger?.debug&&this.logger.debug("No actual changes after middleware processing");return}let p={};l.forEach(u=>{p[u]=d[u]}),this.logger?.debug&&this.logger.debug("Notifying subscribers about changes:",{keys:l}),this.notifySubscribers(n.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:l,value:p,changedPaths:Array.from(o)});for(let u of o)try{let h=u.split(".")[0];if(h in p){let g;if(u===h)g=p[h];else{let y=u.substring(h.length+1);g=P(p[h],y)}g!==void 0&&this.notifySubscribers(u,g)}}catch(h){this.logger?.error("Error notifying path subscribers",{path:u,error:h})}await this.emitEvent({type:"storage:update",payload:{state:p,key:l,changedPaths:Array.from(o)}})}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)){let s=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});await this.pluginExecutor?.executeAfterDelete(e,t);let o=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(n.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:s,changedPaths:o}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:s,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(n.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(n.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(n.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(n.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(n.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),this.statusSubscribers.clear(),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(o){this.logger?.error("Error in initial callback",{key:e,error:o})}}),()=>{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 i=0;i<e.length;i++)if(!this.isEqual(e[i],t[i]))return!1;return!0}let o=Object.keys(e),a=Object.keys(t);return o.length!==a.length?!1:o.every(i=>Object.prototype.hasOwnProperty.call(t,i)&&this.isEqual(e[i],t[i]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let s=[],r=(o="")=>({get:(a,i)=>{if(typeof i=="symbol")return Reflect.get(a,i);let c=o?`${o}.${i}`:i;return s.push(c),new Proxy({},r(c))},has:(a,i)=>!0,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:!0,enumerable:!0}),apply:(a,i,c)=>new Proxy(()=>{},r(o))});try{e(new Proxy(t,r()))}catch{}return s.length===0?"":(s.sort((o,a)=>a.length-o.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(a=>{try{a(t)}catch(i){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:i})}})}findChangedPaths(e,t,s="",r=new Set,o=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(o.has(e))return r;o.set(e,!0);let a=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let i of a){let c=e[i],d=t[i];if(c===d)continue;let l=s?`${s}.${i}`:i;c&&d&&typeof c=="object"&&typeof d=="object"&&!Array.isArray(c)&&!Array.isArray(d)?this.findChangedPaths(c,d,l,r,o):Array.isArray(c)&&Array.isArray(d)?this.isEqual(c,d)||r.add(l):this.isEqual(c,d)||r.add(l)}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 o=async a=>{try{if(a==null){let d=await this.getState(),l=e(d);t(l);return}if(typeof a!="object"||a===null){t(a);return}let i=await this.getState(),c=e(i);t(c)}catch(i){this.logger?.error("Error in selector callback",{path:r,error:i}),t(a)}};return r?this.subscribeByKey(r,o):this.subscribeToAll(()=>{this.getState().then(a=>{t(e(a))})})}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 te=class n{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){n.instances.has(e)||n.instances.set(e,new n(e,t,s));let r=n.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 o=0;o<this.db.objectStoreNames.length;o++)this.storeNames.add(this.db.objectStoreNames[o]);this.logger?.debug(`Database "${this.dbName}" opened successfully`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),t(this.db)},r.onupgradeneeded=o=>{let a=o.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let i of e)a.objectStoreNames.contains(i)||(this.logger?.debug(`Creating store "${i}"`),a.createObjectStore(i))}})}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`),n.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}},re=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 o=indexedDB.open(this.dbName,e);o.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:o.error}),r(o.error)},o.onsuccess=()=>{this.db=o.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)},o.onupgradeneeded=a=>{let i=a.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 c of t)i.objectStoreNames.contains(c)||(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "${c}"`),i.createObjectStore(c))}})}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)}},se=class n extends O{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,s,r){super(e,t,s,r);let o=e.options;this.DB_NAME=o.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=o.dbVersion||1,this.dbManager=te.getInstance(this.DB_NAME,this.DB_VERSION,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 o=await this.getCurrentDBVersion(e)||1,a=new re(e,o,s),i=Object.values(t).map(d=>d.name);await a.ensureStoresExist(i);let c={};for(let[d,l]of Object.entries(t)){let p=new n({...l,options:{dbName:e,dbVersion:a.getCurrentVersion()}},l.pluginExecutor,l.eventEmitter,s);c[d]=await p.initialize()}return c}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,o)=>{let a=t.getAll();a.onerror=()=>o(a.error),a.onsuccess=()=>{let i=a.result,c=t.getAllKeys();c.onsuccess=()=>{let d=c.result.reduce((l,p,u)=>(p!=="root"&&(l[p]=i[u]),l),{});r(d)},c.onerror=()=>o(c.error)}});if(e instanceof b&&e.isUnparseable())return new Promise((r,o)=>{let a=t.get(e.valueOf());a.onerror=()=>o(a.error),a.onsuccess=()=>r(a.result)});let s=R(e);if(s.length>1){let r=s[0];return new Promise((o,a)=>{let i=t.get(r);i.onerror=()=>a(i.error),i.onsuccess=()=>{let c=i.result;if(!c){o(void 0);return}let d=P(c,s.slice(1).join("."));o(d)}})}return new Promise((r,o)=>{let a=t.get(s[0]);a.onerror=()=>o(a.error),a.onsuccess=()=>r(a.result)})}async doSet(e,t){if(e===""){let o=await this.getObjectStore("readwrite");return new Promise((a,i)=>{let c=o.transaction;c.oncomplete=()=>{a()},c.onerror=()=>{i(c.error)};let d=o.clear();d.onsuccess=()=>{let l=Object.entries(t);for(let[p,u]of l)o.put(u,p)},d.onerror=()=>{i(d.error)}})}let s=await this.getObjectStore("readwrite");if(e instanceof b&&e.isUnparseable