synapse-storage 3.0.3 → 3.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ 'use strict';var chunk635Q6YJZ_cjs=require('./chunk-635Q6YJZ.cjs');var k={debug:(a,...e)=>{process.env.NODE_ENV;},log:(a,...e)=>{process.env.NODE_ENV;},info:(a,...e)=>{},warn:(a,...e)=>{},error:(a,...e)=>{}};function O(a){return `${a?`${a}|`:""}${Math.random().toString(36).substring(2,9)+Date.now().toString(36)}`}function I(a){let e={};return a.forEach((t,r)=>{e[r.toLowerCase()]=t;}),e}function T(a={},e={}){return {...a,...e,getFromStorage:a.getFromStorage||(t=>{try{let r=localStorage.getItem(t);return r?JSON.parse(r):void 0}catch{return}}),getCookie:a.getCookie||(t=>{try{let r=document.cookie.match(new RegExp(`(?:^|; )${t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")}=([^;]*)`));return r?decodeURIComponent(r[1]):void 0}catch{return}})}}async function D(a,e){let t=new Headers,r=e||T({},{});if(a)try{t=await Promise.resolve(a(t,r));}catch{}return t}function K(a,e){return async(t,r)=>{let n=new Headers(t);if(a)try{n=await Promise.resolve(a(n,r));}catch{}if(e)try{n=await Promise.resolve(e(n,r));}catch{}return n}}var q=(s=>(s.Json="json",s.Blob="blob",s.ArrayBuffer="arrayBuffer",s.Text="text",s.FormData="formData",s.Raw="raw",s))(q||{});function Q(a){let e=a.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 H(a){let e=a.get("content-type")||"",t=a.get("content-disposition")||"",r=e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"),n=t.includes("attachment")||t.includes("filename=");return r||n}function L(a){let e=a.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 B(a){let e=a.get("content-type")||"",t=a.get("content-disposition")||"",r=a.get("content-length");return H(a)?{filename:L(a),contentType:e,contentDisposition:t,size:r?parseInt(r,10):void 0}:void 0}async function z(a,e){let t=e,r=a.headers.get("content-type")||"";!t&&r&&(H(a.headers)?t="blob":t=Q(r)),t||(t="json");try{let n;switch((t==="blob"||t==="arrayBuffer")&&(n=B(a.headers)),t){case "json":try{let s=await a.json();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}catch{let u=await a.text();return a.ok?{data:u,fileMetadata:n}:{error:u,fileMetadata:n}}case "text":{let s=await a.text();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "blob":{let s=await a.blob();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "arrayBuffer":{let s=await a.arrayBuffer();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "formData":{let s=await a.formData();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "raw":return a.ok?{data:a,fileMetadata:n}:{error:a,fileMetadata:n};default:let i=await a.blob();return a.ok?{data:i,fileMetadata:n}:{error:i,fileMetadata:n}}}catch(n){return a.ok?{data:void 0}:{error:n}}}function M(a){let{baseUrl:e,timeout:t=3e4,fetchFn:r=fetch,credentials:n="same-origin"}=a;return async(i,s={},u)=>{let{path:h,method:C,body:o,query:d,responseFormat:f}=i,{signal:b,timeout:R=t,responseFormat:l}=s,A=l||f,m=new URL(h.startsWith("http")?h:`${e}${h}`);d&&Object.entries(d).forEach(([p,c])=>{c!=null&&(Array.isArray(c)?c.forEach(w=>m.searchParams.append(p,String(w))):m.searchParams.append(p,String(c)));});let E;if(o!==void 0)if(o instanceof FormData||o instanceof Blob)E=o;else if(typeof o=="object"&&o!==null)try{E=JSON.stringify(o),u.has("Content-Type")||u.set("Content-Type","application/json");}catch{E=String(o);}else E=String(o);let x,g=new Promise((p,c)=>{R&&(x=window.setTimeout(()=>{c(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 (${R}\u043C\u0441)`));},R));});try{let p=r(m.toString(),{method:C,headers:u,body:E,signal:b,credentials:n}),c=await Promise.race([p,g]),{data:w,error:F,fileMetadata:U}=await z(c,A);return {data:w,error:F,ok:c.ok,status:c.status,statusText:c.statusText,headers:c.headers,fileDownloadResult:U}}catch(p){let c=p;return {error:c,ok:false,status:0,statusText:c.message,headers:new Headers}}finally{x&&window.clearTimeout(x);}}}function $(a,e=[]){let t={};return !a||e.length===0||e.forEach(r=>{a.has(r)&&(t[r]=a.get(r)||"");}),t}var S=class{constructor(e,t,r,n,i,s){this.name=e;this.queryStorage=t;this.configCurrentEndpoint=r;this.cacheableHeaderKeys=n;this.globalCacheConfig=i;this.baseQueryConfig=s;this.prepareHeaders=K(s.prepareHeaders,r.prepareHeaders),this.queryFunction=M({baseUrl:s.baseUrl,fetchFn:s.fetchFn,timeout:s.timeout,credentials:s.credentials}),this.cacheableHeaders=[...n||[],...r.includeCacheableHeaderKeys||[]].filter(u=>!r.excludeCacheableHeaderKeys?.includes(u)),this.meta.name=e,this.meta.tags=r.tags??this.meta.tags,this.meta.invalidatesTags=r.invalidatesTags??this.meta.invalidatesTags,this.meta.cache=this.queryStorage.createCacheConfig(this.configCurrentEndpoint)??this.meta.cache;}endpointSubscribers=new Set;fetchCounts=0;meta={cache:false,invalidatesTags:[],name:"",tags:[]};queryFunction;cacheableHeaders;prepareHeaders;request(e,t){this.fetchCounts++;let r=O(this.name),n=new AbortController,i=new Set,s={status:"idle",requestParams:e,headers:{},error:void 0,data:void 0,fromCache:false},u=T({requestParams:e},t?.context||{}),h=o=>{Object.assign(s,o),i.forEach(d=>{d({...s});});},C=new Promise(async(o,d)=>{try{let f=await D(this.prepareHeaders,u),b=$(f,t?.cacheableHeaderKeys?t.cacheableHeaderKeys:this.cacheableHeaders),R=this.queryStorage.shouldCache(this.configCurrentEndpoint,t),[l,A]=this.queryStorage.createCacheKey(this.name,{...e,...b}),m;if(R&&(m=await this.queryStorage.getCachedResult(l)),m)h({fromCache:!0,status:"success",data:m.data,error:void 0,headers:m.headers,requestParams:e}),o({...m,fromCache:!0});else {h({fromCache:!1,status:"loading"});let E=this.configCurrentEndpoint.request(e,t?.context),x={...t,signal:n.signal},g=await this.queryFunction(E,x,f);if(g.ok){let{headers:p,...c}=g;if(R){let w=this.queryStorage.createCacheConfig(this.configCurrentEndpoint);await this.queryStorage.setCachedResult(l,{...c,headers:I(p)},w,A??{},this.configCurrentEndpoint.tags??[],this.configCurrentEndpoint.invalidatesTags??[]);}h({fromCache:!1,status:"success",data:g.data,error:void 0,headers:g.headers,requestParams:e}),this.endpointSubscribers.forEach(w=>{let F={status:"success",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};w(F);}),o({...g,fromCache:!1});}else h({fromCache:!1,status:"error",data:void 0,error:g.error,headers:g.headers,requestParams:e}),this.endpointSubscribers.forEach(p=>{let c={status:"error",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:g.error};p(c);}),d(g.error);}}catch(f){h({fromCache:false,status:"error",data:void 0,error:f,headers:void 0,requestParams:e}),d(f);}});return {id:r,subscribe(o,d={}){let{autoUnsubscribe:f=true}=d;i.add(o),o(s);let b=()=>i.delete(o);return f&&C.finally(()=>{b();}),b},wait:()=>C,waitWithCallbacks(o={}){let{idle:d,loading:f,success:b,error:R}=o;return this.subscribe(l=>{switch(l.status){case "idle":d?.(l);break;case "loading":f?.(l);break;case "success":b?.(l.data,l);break;case "error":R?.(l.error,l);break}},{autoUnsubscribe:true}),C},abort:()=>{n&&!n.signal.aborted&&n.abort();},then:(o,d)=>C.then(o,d),catch:o=>C.catch(o),finally:o=>C.finally(o)}}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 y=class{static createMetadata(e=0,t=[]){let r=Date.now(),n=e>0?r+e:1/0;return {createdAt:r,updatedAt:r,expiresAt:n,tags:t,createdAtDateTime:this.formatDateTime(r),updatedAtDateTime:this.formatDateTime(r),expiresAtDateTime:n===1/0?"never":this.formatDateTime(n)}}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 chunk635Q6YJZ_cjs.a(e.join("_"))}static createApiKey(e,t){if(!t)return [new chunk635Q6YJZ_cjs.a(e,true),t];let r=Object.entries(t).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>`${n}=${i}`).join("&");return [new chunk635Q6YJZ_cjs.a(`${e}_${r}`,true),t]}static hasAnyTag(e,t=[]){return !e.tags||!t.length?false:t.some(r=>e.tags?.includes(r))}};var v=class{constructor(e,t){this.storageExternal=e;this.globalCacheConfig=t;}storage=null;cleanupInterval=null;defaultCacheOptions={ttl:5*60*1e3,cleanup:{enabled:true,interval:10*60*1e3},invalidateOnError:true};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 y.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(y.isExpired(t.metadata)){await this.storage.delete(e);return}let r={...t,metadata:y.updateMetadata(t.metadata)};return await this.storage.set(e,r),t.data}async setCachedResult(e,t,r,n,i,s){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");s?.length&&await this.invalidateCacheByTags(s);let u=y.createMetadata(r.ttl,i),h={data:t,metadata:u,params:n};await this.storage.set(e,h);}shouldCache(e,t){return !(this.globalCacheConfig===false||e?.cache===false||typeof e?.cache=="object"&&e?.cache.ttl===0||t?.disableCache===true||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 r=e.cache;t={...t,...r};}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 r of t){let n=await this.storage.get(r);n&&y.hasAnyTag(n.metadata,e)&&await this.storage.delete(r);}}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 r=await this.storage.get(t);r&&y.isExpired(r.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 j=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 v(this.storageExternal,this.globalCacheConfig).initialize(),await this.initializeEndpoints(),this}async initializeEndpoints(){let e=r=>r,t=await this.createEndpoints(e)||{};for(let[r,n]of Object.entries(t)){let i=r;this.endpoints[i]=new S(r,this.queryStorage,n,this.cacheableHeaderKeys,this.globalCacheConfig,this.baseQueryConfig);}}getEndpoints(){return this.endpoints}async request(e,t,r){let i=this.getEndpoints()[e];if(!i)throw new Error(`\u042D\u043D\u0434\u043F\u043E\u0438\u043D\u0442 ${String(e)} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`);try{return await i.request(t,r).wait()}catch(s){throw k.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043A ${String(e)}`,{error:s,params:t}),s}}async destroy(){await Promise.all(Object.values(this.endpoints).map(async e=>(e.destroy(),Promise.resolve()))),this.endpoints={},await this.queryStorage.destroy();}};exports.a=k;exports.b=O;exports.c=I;exports.d=q;exports.e=j;
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-ZE2EJX2Y.js';var k={debug:(a,...e)=>{process.env.NODE_ENV;},log:(a,...e)=>{process.env.NODE_ENV;},info:(a,...e)=>{},warn:(a,...e)=>{},error:(a,...e)=>{}};function O(a){return `${a?`${a}|`:""}${Math.random().toString(36).substring(2,9)+Date.now().toString(36)}`}function I(a){let e={};return a.forEach((t,r)=>{e[r.toLowerCase()]=t;}),e}function T(a={},e={}){return {...a,...e,getFromStorage:a.getFromStorage||(t=>{try{let r=localStorage.getItem(t);return r?JSON.parse(r):void 0}catch{return}}),getCookie:a.getCookie||(t=>{try{let r=document.cookie.match(new RegExp(`(?:^|; )${t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")}=([^;]*)`));return r?decodeURIComponent(r[1]):void 0}catch{return}})}}async function D(a,e){let t=new Headers,r=e||T({},{});if(a)try{t=await Promise.resolve(a(t,r));}catch{}return t}function K(a,e){return async(t,r)=>{let n=new Headers(t);if(a)try{n=await Promise.resolve(a(n,r));}catch{}if(e)try{n=await Promise.resolve(e(n,r));}catch{}return n}}var q=(s=>(s.Json="json",s.Blob="blob",s.ArrayBuffer="arrayBuffer",s.Text="text",s.FormData="formData",s.Raw="raw",s))(q||{});function Q(a){let e=a.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 H(a){let e=a.get("content-type")||"",t=a.get("content-disposition")||"",r=e.includes("application/octet-stream")||e.includes("application/pdf")||e.includes("image/")||e.includes("audio/")||e.includes("video/"),n=t.includes("attachment")||t.includes("filename=");return r||n}function L(a){let e=a.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 B(a){let e=a.get("content-type")||"",t=a.get("content-disposition")||"",r=a.get("content-length");return H(a)?{filename:L(a),contentType:e,contentDisposition:t,size:r?parseInt(r,10):void 0}:void 0}async function z(a,e){let t=e,r=a.headers.get("content-type")||"";!t&&r&&(H(a.headers)?t="blob":t=Q(r)),t||(t="json");try{let n;switch((t==="blob"||t==="arrayBuffer")&&(n=B(a.headers)),t){case "json":try{let s=await a.json();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}catch{let u=await a.text();return a.ok?{data:u,fileMetadata:n}:{error:u,fileMetadata:n}}case "text":{let s=await a.text();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "blob":{let s=await a.blob();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "arrayBuffer":{let s=await a.arrayBuffer();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "formData":{let s=await a.formData();return a.ok?{data:s,fileMetadata:n}:{error:s,fileMetadata:n}}case "raw":return a.ok?{data:a,fileMetadata:n}:{error:a,fileMetadata:n};default:let i=await a.blob();return a.ok?{data:i,fileMetadata:n}:{error:i,fileMetadata:n}}}catch(n){return a.ok?{data:void 0}:{error:n}}}function M(a){let{baseUrl:e,timeout:t=3e4,fetchFn:r=fetch,credentials:n="same-origin"}=a;return async(i,s={},u)=>{let{path:h,method:C,body:o,query:d,responseFormat:f}=i,{signal:b,timeout:R=t,responseFormat:l}=s,A=l||f,m=new URL(h.startsWith("http")?h:`${e}${h}`);d&&Object.entries(d).forEach(([p,c])=>{c!=null&&(Array.isArray(c)?c.forEach(w=>m.searchParams.append(p,String(w))):m.searchParams.append(p,String(c)));});let E;if(o!==void 0)if(o instanceof FormData||o instanceof Blob)E=o;else if(typeof o=="object"&&o!==null)try{E=JSON.stringify(o),u.has("Content-Type")||u.set("Content-Type","application/json");}catch{E=String(o);}else E=String(o);let x,g=new Promise((p,c)=>{R&&(x=window.setTimeout(()=>{c(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 (${R}\u043C\u0441)`));},R));});try{let p=r(m.toString(),{method:C,headers:u,body:E,signal:b,credentials:n}),c=await Promise.race([p,g]),{data:w,error:F,fileMetadata:U}=await z(c,A);return {data:w,error:F,ok:c.ok,status:c.status,statusText:c.statusText,headers:c.headers,fileDownloadResult:U}}catch(p){let c=p;return {error:c,ok:false,status:0,statusText:c.message,headers:new Headers}}finally{x&&window.clearTimeout(x);}}}function $(a,e=[]){let t={};return !a||e.length===0||e.forEach(r=>{a.has(r)&&(t[r]=a.get(r)||"");}),t}var S=class{constructor(e,t,r,n,i,s){this.name=e;this.queryStorage=t;this.configCurrentEndpoint=r;this.cacheableHeaderKeys=n;this.globalCacheConfig=i;this.baseQueryConfig=s;this.prepareHeaders=K(s.prepareHeaders,r.prepareHeaders),this.queryFunction=M({baseUrl:s.baseUrl,fetchFn:s.fetchFn,timeout:s.timeout,credentials:s.credentials}),this.cacheableHeaders=[...n||[],...r.includeCacheableHeaderKeys||[]].filter(u=>!r.excludeCacheableHeaderKeys?.includes(u)),this.meta.name=e,this.meta.tags=r.tags??this.meta.tags,this.meta.invalidatesTags=r.invalidatesTags??this.meta.invalidatesTags,this.meta.cache=this.queryStorage.createCacheConfig(this.configCurrentEndpoint)??this.meta.cache;}endpointSubscribers=new Set;fetchCounts=0;meta={cache:false,invalidatesTags:[],name:"",tags:[]};queryFunction;cacheableHeaders;prepareHeaders;request(e,t){this.fetchCounts++;let r=O(this.name),n=new AbortController,i=new Set,s={status:"idle",requestParams:e,headers:{},error:void 0,data:void 0,fromCache:false},u=T({requestParams:e},t?.context||{}),h=o=>{Object.assign(s,o),i.forEach(d=>{d({...s});});},C=new Promise(async(o,d)=>{try{let f=await D(this.prepareHeaders,u),b=$(f,t?.cacheableHeaderKeys?t.cacheableHeaderKeys:this.cacheableHeaders),R=this.queryStorage.shouldCache(this.configCurrentEndpoint,t),[l,A]=this.queryStorage.createCacheKey(this.name,{...e,...b}),m;if(R&&(m=await this.queryStorage.getCachedResult(l)),m)h({fromCache:!0,status:"success",data:m.data,error:void 0,headers:m.headers,requestParams:e}),o({...m,fromCache:!0});else {h({fromCache:!1,status:"loading"});let E=this.configCurrentEndpoint.request(e,t?.context),x={...t,signal:n.signal},g=await this.queryFunction(E,x,f);if(g.ok){let{headers:p,...c}=g;if(R){let w=this.queryStorage.createCacheConfig(this.configCurrentEndpoint);await this.queryStorage.setCachedResult(l,{...c,headers:I(p)},w,A??{},this.configCurrentEndpoint.tags??[],this.configCurrentEndpoint.invalidatesTags??[]);}h({fromCache:!1,status:"success",data:g.data,error:void 0,headers:g.headers,requestParams:e}),this.endpointSubscribers.forEach(w=>{let F={status:"success",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:void 0};w(F);}),o({...g,fromCache:!1});}else h({fromCache:!1,status:"error",data:void 0,error:g.error,headers:g.headers,requestParams:e}),this.endpointSubscribers.forEach(p=>{let c={status:"error",fetchCounts:this.fetchCounts,meta:this.meta,cacheableHeaders:this.cacheableHeaders,error:g.error};p(c);}),d(g.error);}}catch(f){h({fromCache:false,status:"error",data:void 0,error:f,headers:void 0,requestParams:e}),d(f);}});return {id:r,subscribe(o,d={}){let{autoUnsubscribe:f=true}=d;i.add(o),o(s);let b=()=>i.delete(o);return f&&C.finally(()=>{b();}),b},wait:()=>C,waitWithCallbacks(o={}){let{idle:d,loading:f,success:b,error:R}=o;return this.subscribe(l=>{switch(l.status){case "idle":d?.(l);break;case "loading":f?.(l);break;case "success":b?.(l.data,l);break;case "error":R?.(l.error,l);break}},{autoUnsubscribe:true}),C},abort:()=>{n&&!n.signal.aborted&&n.abort();},then:(o,d)=>C.then(o,d),catch:o=>C.catch(o),finally:o=>C.finally(o)}}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 y=class{static createMetadata(e=0,t=[]){let r=Date.now(),n=e>0?r+e:1/0;return {createdAt:r,updatedAt:r,expiresAt:n,tags:t,createdAtDateTime:this.formatDateTime(r),updatedAtDateTime:this.formatDateTime(r),expiresAtDateTime:n===1/0?"never":this.formatDateTime(n)}}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 a(e.join("_"))}static createApiKey(e,t){if(!t)return [new a(e,true),t];let r=Object.entries(t).sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>`${n}=${i}`).join("&");return [new a(`${e}_${r}`,true),t]}static hasAnyTag(e,t=[]){return !e.tags||!t.length?false:t.some(r=>e.tags?.includes(r))}};var v=class{constructor(e,t){this.storageExternal=e;this.globalCacheConfig=t;}storage=null;cleanupInterval=null;defaultCacheOptions={ttl:5*60*1e3,cleanup:{enabled:true,interval:10*60*1e3},invalidateOnError:true};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 y.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(y.isExpired(t.metadata)){await this.storage.delete(e);return}let r={...t,metadata:y.updateMetadata(t.metadata)};return await this.storage.set(e,r),t.data}async setCachedResult(e,t,r,n,i,s){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");s?.length&&await this.invalidateCacheByTags(s);let u=y.createMetadata(r.ttl,i),h={data:t,metadata:u,params:n};await this.storage.set(e,h);}shouldCache(e,t){return !(this.globalCacheConfig===false||e?.cache===false||typeof e?.cache=="object"&&e?.cache.ttl===0||t?.disableCache===true||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 r=e.cache;t={...t,...r};}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 r of t){let n=await this.storage.get(r);n&&y.hasAnyTag(n.metadata,e)&&await this.storage.delete(r);}}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 r=await this.storage.get(t);r&&y.isExpired(r.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 j=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 v(this.storageExternal,this.globalCacheConfig).initialize(),await this.initializeEndpoints(),this}async initializeEndpoints(){let e=r=>r,t=await this.createEndpoints(e)||{};for(let[r,n]of Object.entries(t)){let i=r;this.endpoints[i]=new S(r,this.queryStorage,n,this.cacheableHeaderKeys,this.globalCacheConfig,this.baseQueryConfig);}}getEndpoints(){return this.endpoints}async request(e,t,r){let i=this.getEndpoints()[e];if(!i)throw new Error(`\u042D\u043D\u0434\u043F\u043E\u0438\u043D\u0442 ${String(e)} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D`);try{return await i.request(t,r).wait()}catch(s){throw k.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043A ${String(e)}`,{error:s,params:t}),s}}async destroy(){await Promise.all(Object.values(this.endpoints).map(async e=>(e.destroy(),Promise.resolve()))),this.endpoints={},await this.queryStorage.destroy();}};export{k as a,O as b,I as c,q as d,j as e};
@@ -0,0 +1 @@
1
+ var p=(t,n)=>{for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(typeof n[e]=="object"&&n[e]!==null&&!Array.isArray(n[e])?((!t[e]||typeof t[e]!="object")&&(t[e]={}),p(t[e],n[e])):t[e]=n[e]);};function l(t,n=1){if(n<=0)throw new Error("Size must be greater than 0");if(!t||!t.length)return [];let e=[],o=t.length,r=0;for(;r<o;)e.push(t.slice(r,r+n)),r+=n;return e}export{l as a,p as b};
@@ -0,0 +1 @@
1
+ 'use strict';var e=class{constructor(t,a=false){this.value=t;this.isRawKey=a;}toString(){return this.value}toJSON(){return this.value}valueOf(){return this.value}isUnparseable(){return this.isRawKey}};exports.a=e;
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-ZE2EJX2Y.js';var T=new Map;function O(c){let e=0;if(c.length===0)return e.toString(36);for(let t=0;t<c.length;t++){let r=c.charCodeAt(t);e=(e<<5)-e+r,e=e&e;}return Math.abs(e).toString(36).substring(0,6)}function S(c,e){if(c===e)return true;if(c==null||e==null)return false;if(typeof c!="object"&&typeof c!="function"&&typeof e!="object"&&typeof e!="function")return c===e;if(typeof c!=typeof e)return false;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 false;for(let t=0;t<c.length;t++)if(!S(c[t],e[t]))return false;return true}if(typeof c=="object"&&typeof e=="object"){let t=Object.keys(c),r=Object.keys(e);return t.length!==r.length?false:t.every(s=>Object.prototype.hasOwnProperty.call(e,s)?S(c[s],e[s]):false)}return false}function C(c,e=S){let t,r,s=false;return function(a){if(!s||t!==a){let o=c(a);(!s||!e(o,r))&&(r=o),t=a,s=true;}return r}}var P=class{constructor(e,t,r=S,s){this.name=e;this.equals=r;this.logger=s;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t);}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,r=false;return async()=>{if(r&&t)return t;r=true;try{return t=e(),await t}finally{r=false;}}}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 r=>{try{await r.notify(e);}catch(s){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`,{error:s});}});await Promise.all(t);}}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}},N=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,this.source.getState().then(r=>{this.cachedState=r;});}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=false;pendingUpdates=new Set;generateName(e,t,r){let s=e?"simple":"combined",i="";if(e){let a=t.toString();i=O(a);}else {let a=t.map(n=>n.getId()).join("_"),o=r.toString();i=O(a+o);}return `${this.storageName}_${s}_${i}`}processPendingUpdates(){this.pendingUpdates.size===0||this.batchUpdateInProgress||(this.batchUpdateInProgress=true,setTimeout(async()=>{try{let e=Array.from(this.pendingUpdates);this.pendingUpdates.clear(),this.cachedState=await this.source.getState();let t=e.map(async r=>{let s=this.subscriptions.get(r);if(s)try{return await s.notify()}catch(i){this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${r}`,{error:i});}return Promise.resolve()});await Promise.all(t);}catch(e){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439",{error:e});}finally{this.batchUpdateInProgress=false,this.pendingUpdates.size>0&&this.processPendingUpdates();}},0));}createSelector(e,t,r){let s=!Array.isArray(e),i=s?t||{}:r||{},a=i.name||this.generateName(s,e,s?void 0:t);if(this.localSelectorCache.has(a))return this.localSelectorCache.get(a).api;if(T.has(a)){let d=T.get(a);return d.refCount++,d.api}let o,n,l=[];if(s){let d=C(e,i.equals||S),u=this.createSimpleSelector(d,{...i,name:a,equals:i.equals||S});o=u.api,l=u.unsubscribeFunctions;}else {n=e;let d=this.createCombinedSelector(n,t,{...i,name:a,equals:i.equals||S});o=d.api,l=d.unsubscribeFunctions;}return this.localSelectorCache.set(a,{api:o,dependencies:n,unsubscribeFunctions:l}),T.set(a,{api:o,refCount:1,unsubscribeFunctions:l}),o}createSimpleSelector(e,t){let r=async()=>{if(this.cachedState)return e(this.cachedState);let n=await this.source.getState();return this.cachedState=n,e(n)},s=new P(t.name,r,t.equals||S,this.logger),i=s.getId();this.subscriptions.set(i,s);let o=[this.source.subscribeToAll(async n=>{n?.type==="storage:update"&&(this.pendingUpdates.add(i),this.processPendingUpdates());})];return {api:{select:()=>r(),subscribe:n=>s.subscribe(n),getId:()=>i},unsubscribeFunctions:o}}createCombinedSelector(e,t,r){let s=C(u=>t(...u),r.equals||S),i=async()=>{let u=await Promise.all(e.map(g=>g.select()));return s(u)},a=new P(r.name,i,r.equals||S,this.logger),o=a.getId();this.subscriptions.set(o,a);let n=null,l=()=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,a.notify().catch(u=>this.logger?.error(`[${o}] \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=>a.subscribe(u),getId:()=>o},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(r=>r());});let e=new Set;this.localSelectorCache.forEach((t,r)=>{e.add(r);}),this.localSelectorCache.clear(),e.forEach(t=>{let r=T.get(t);r&&(r.refCount--,r.refCount<=0&&(r.unsubscribeFunctions.forEach(s=>s()),T.delete(t)));});}};var $=class{constructor(e,t,r="default"){this.parentExecutor=e;this.logger=t;this.storageName=r;}plugins=new Map;createContext(e){return {storageName:this.storageName,timestamp:Date.now(),metadata:e}}async add(e){if(this.plugins.has(e.name)){this.logger?.warn(`\u041F\u043B\u0430\u0433\u0438\u043D ${e.name} \u0443\u0436\u0435 \u0431\u044B\u043B \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D`);return}try{await e.initialize?.(),this.plugins.set(e.name,e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D",{name:e.name});}catch(t){throw t}}async remove(e){let t=this.plugins.get(e);t&&(await t.destroy?.(),this.plugins.delete(e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0443\u0434\u0430\u043B\u0435\u043D",{name:e}));}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}async initialize(){for(let e of this.plugins.values())await e.initialize?.();}async destroy(){await Promise.all(Array.from(this.plugins.values()).map(e=>e.destroy?.()??Promise.resolve())),this.plugins.clear();}async executeBeforeSet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeSet(r,s));for(let i of this.plugins.values())if(i.onBeforeSet)try{r=await i.onBeforeSet(r,s);}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeSet`,{error:a}),a}return r}async executeAfterSet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterSet(e,s,i));for(let a of this.plugins.values())if(a.onAfterSet)try{s=await a.onAfterSet(e,s,i);}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onAfterSet`,{key:e,error:o}),o}return s}async executeBeforeGet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeGet(r,s));for(let i of this.plugins.values())if(i.onBeforeGet)try{r=await i.onBeforeGet(r,s);}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeGet`,{key:e,error:a}),a}return r}async executeAfterGet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterGet(e,s,i));for(let a of this.plugins.values())if(a.onAfterGet)try{s=await a.onAfterGet(e,s,i);}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onAfterGet`,{key:e,error:o}),o}return s}async executeBeforeDelete(e,t){let r=true,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeDelete(e,s));for(let i of this.plugins.values())if(i.onBeforeDelete)try{r=await i.onBeforeDelete(e,s)&&r;}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeDelete`,{key:e,error:a}),a}return r}async executeAfterDelete(e,t){let r=this.createContext(t);this.parentExecutor&&await this.parentExecutor.executeAfterDelete(e,r);for(let s of this.plugins.values())if(s.onAfterDelete)try{await s.onAfterDelete(e,r);}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${s.name} onAfterDelete`,{key:e,error:i}),i}}async executeOnClear(e){let t=this.createContext(e);this.parentExecutor&&await this.parentExecutor.executeOnClear(t);for(let r of this.plugins.values())if(r.onClear)try{await r.onClear(t);}catch(s){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onClear`,{error:s}),s}}};var I=(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))(I||{});var E=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??false,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 r=await this.syncHandler();this.postMessage("SYNC_RESPONSE",r,t.senderId);}catch(r){this.error("Error handling sync request:",r);}return}if(t.type==="SYNC_RESPONSE"){let r=this.pendingSyncRequests.get(this.tabId);r&&(clearTimeout(r.timeout),this.pendingSyncRequests.delete(this.tabId),r.resolve(t.payload));return}for(let r of this.messageHandlers)try{await r(t);}catch(s){this.error("Error in message handler:",s);}}}handleError(e){this.error("Channel error:",e);}postMessage(e,t,r){let s={type:e,payload:t,senderId:this.tabId,timestamp:Date.now()};this.channel.postMessage(s);}subscribe(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}setSyncHandler(e){this.syncHandler=e;}broadcast(e,t){this.postMessage(e,t);}async requestSync(){return new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingSyncRequests.delete(this.tabId),e(null);},this.syncTimeoutMs);this.pendingSyncRequests.set(this.tabId,{resolve:e,reject:t,timeout:r}),this.postMessage("SYNC_REQUEST",{type:"sync"});})}close(){for(let[,e]of this.pendingSyncRequests)clearTimeout(e.timeout),e.reject(new Error("Channel closed"));this.pendingSyncRequests.clear(),this.messageHandlers.clear(),this.syncHandler=void 0,this.channel.close();}};var V=c=>{let{storageName:e,storageType:t}=c,r=`${t}-${e}`,s=new E(r,{debug:true});return {name:"sync",setup:i=>(t==="memory"&&(s.setSyncHandler(async()=>{let a=await i.getState();return {type:"update",key:"*",value:Object.entries(a).map(([l,d])=>({key:l,value:d})),metadata:{batchUpdate:true,timestamp:Date.now()}}}),s.requestSync().then(async a=>{if(a?.type==="update"&&Array.isArray(a.value))try{if(!a.value.every(n=>n&&typeof n=="object"&&"key"in n&&"value"in n))return;await i.storage.doUpdate(a.value),a.value.forEach(({key:n,value:l})=>{i.storage.notifySubscribers(n,l);}),i.storage.notifySubscribers("*",{type:"storage:update",value:a.value,source:"broadcast"});}catch{}})),s.subscribe(async a=>{let{type:o,payload:n}=a;if(t==="memory"){switch(o){case "set":await i.storage.doSet(n.key,n.value),i.storage.notifySubscribers(n.key,n.value);break;case "update":Array.isArray(n.value)&&(await i.storage.doUpdate(n.value),n.value.forEach(({key:l,value:d})=>{i.storage.notifySubscribers(l,d);}));break;case "delete":await i.storage.doDelete(n.key),i.storage.notifySubscribers(n.key,void 0);break;case "clear":await i.storage.doClear(),i.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}i.storage.notifySubscribers("*",{type:"storage:update",key:n?.key,value:n?.value,source:"broadcast"});}})),reducer:i=>a=>async o=>{let n=await a(o);return ["set","delete","clear","update"].includes(o.type)&&s.broadcast(o.type,o),n},cleanup:()=>{s.close();}}};var A=class{options;queues=new Map;timeouts=new Map;constructor(e){this.options={batchSize:e.batchSize??10,batchDelay:e.batchDelay??300,onBatch:e.onBatch??(async()=>{}),getSegmentKey:e.getSegmentKey??(()=>"default"),shouldBatch:e.shouldBatch??(()=>true),mergeItems:e.mergeItems??(t=>t)};}async add(e,t){return this.options.shouldBatch(e)?new Promise((r,s)=>{let i=this.options.getSegmentKey(e);this.addToQueue(i,{action:e,baseOperation:t,resolve:r,reject:s});}):t()}addToQueue(e,t){let r=this.queues.get(e);r||(r=[],this.queues.set(e,r)),r.push(t),this.clearSegmentTimeout(e),r.length>=this.options.batchSize?this.processBatch(e):this.setSegmentTimeout(e);}async processBatch(e){let t=this.queues.get(e);if(t?.length){this.queues.delete(e),this.clearSegmentTimeout(e);try{let r=this.options.mergeItems(t.map(s=>s.action));for(let s=0;s<r.length;s++){let i=await t[s].baseOperation();t[s].resolve(i);}}catch(r){t.forEach(({reject:s})=>s(r));}}}clearSegmentTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e));}setSegmentTimeout(e){let t=setTimeout(()=>{this.processBatch(e);},this.options.batchDelay);this.timeouts.set(e,t);}async flush(){let e=Array.from(this.queues.keys());await Promise.all(e.map(t=>this.processBatch(t)));}clear(){this.queues.clear(),Array.from(this.timeouts.values()).forEach(clearTimeout),this.timeouts.clear();}getState(){let e={};return this.queues.forEach((t,r)=>{e[r]=t.length;}),e}};var U=(c={})=>{let e=new A({batchSize:c.batchSize,batchDelay:c.batchDelay,shouldBatch:t=>!(t.type==="get"||t.type==="keys"),getSegmentKey:t=>t.key||"default",mergeItems:t=>t.reduce((r,s)=>{if(s.type==="set"){let i=r.findIndex(a=>a.type==="set"&&a.key===s.key);i!==-1?r[i]=s:r.push(s);}else r.push(s);return r},[])});return {name:"batching",setup:()=>{},reducer:t=>r=>s=>e.add(s,()=>r(s))}};var q=(c={})=>{let{comparator:e=(s,i)=>{if(s===i)return true;if(typeof s!="object"||typeof i!="object"||s===null||i===null)return s===i;let a=Object.keys(s),o=Object.keys(i);return a.length!==o.length?false:a.every(n=>Object.prototype.hasOwnProperty.call(i,n)&&s[n]===i[n])},segments:t=[]}=c,r=new Map;return {name:"shallow-compare",setup:s=>{},reducer:s=>i=>async a=>{if(a.type!=="set"||t.length&&!t.includes(a.metadata?.segment??"default"))return i(a);let o=a.key,n=r.get(o),l=a.value;if(n!==void 0&&e(n,l))return {...n,e:{valueNotChanged:true,originalValue:n}};let d=await i(a);return r.set(o,l),d}}};var x=class{middlewares=[];api;initialized=false;dispatchFn;constructor(e){this.api={dispatch:async t=>this.dispatch(t),getState:()=>e.getState(),storage:{doGet:e.doGet.bind(e),doSet:e.doSet.bind(e),doUpdate:e.doUpdate.bind(e),doDelete:e.doDelete.bind(e),doClear:e.doClear.bind(e),doKeys:e.doKeys.bind(e),notifySubscribers:e.notifySubscribers.bind(e)}};}async baseOperation(e){let{processed:t,...r}=e.metadata||{},s={...e};switch(s.type){case "get":return this.api.storage.doGet(s.key);case "set":return await this.api.storage.doSet(s.key,s.value),this.api.storage.doGet(s.key);case "update":return Array.isArray(s.value)?(await this.api.storage.doUpdate(s.value),this.api.storage.doGet("")):s.value;case "delete":return this.api.storage.doDelete(s.key);case "clear":return this.api.storage.doClear();case "init":{let i=await this.api.storage.doGet("");return Object.keys(i||{}).length>0?i:s.value?(await this.api.storage.doSet("",s.value),this.api.storage.doGet("")):i}case "keys":return this.api.storage.doKeys();default:throw new Error(`Unknown action type: ${s.type}`)}}initializeMiddlewares(){if(this.initialized)return;let e=this.baseOperation.bind(this);for(let t of [...this.middlewares].reverse()){let r=e;e=async s=>{if(s.metadata?.processed)return r(s);let i={...s,metadata:{...s.metadata,processed:true,timestamp:s.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(r)(i)};}this.dispatchFn=e,this.initialized=true;}use(e){e.setup&&e.setup(this.api),this.middlewares.push(e),this.initialized=false;}async dispatch(e){this.initialized||this.initializeMiddlewares();try{return this.dispatchFn(e)}catch(t){throw t}}};function m(c){return c instanceof a&&c.isUnparseable()?[c.toString()]:c.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function f(c,e){return m(e).reduce((r,s)=>r===void 0?void 0:r[s],c)}function b(c,e,t){if(e==="")return t;let r=m(e);if(e instanceof a&&e.isUnparseable())return c[e.toString()]=t,c;let s=r.pop(),i=r.reduce((a,o)=>{let n=r[r.indexOf(o)+1],l=!Number.isNaN(Number(n));return o in a||(a[o]=l?[]:{}),a[o]},c);return i[s]=t,c}var w=class c{constructor(e,t,r,s){this.config=e;this.pluginExecutor=t;this.eventEmitter=r;this.logger=s;this.name=e.name,this.middlewareModule=new x({getState:this.getState.bind(this),doGet:this.doGet.bind(this),doSet:this.doSet.bind(this),doUpdate:this.doUpdate.bind(this),doDelete:this.doDelete.bind(this),doClear:this.doClear.bind(this),doKeys:this.doKeys.bind(this),notifySubscribers:this.notifySubscribers.bind(this),pluginExecutor:this.pluginExecutor,eventEmitter:this.eventEmitter,logger:this.logger}),this.initializeMiddlewares();}static GLOBAL_SUBSCRIPTION_KEY="*";name;selectorPathCache=new WeakMap;middlewareModule;initializedMiddlewares=null;subscribers=new Map;initializeMiddlewares(){this.config.middlewares&&!this.initializedMiddlewares&&(this.initializedMiddlewares=this.config.middlewares(()=>this.getDefaultMiddleware()),this.initializedMiddlewares.forEach(e=>this.middlewareModule.use(e)));}getDefaultMiddleware(){return {batching:(e={})=>U(e),shallowCompare:(e={})=>q(e)}}async initializeWithMiddlewares(){try{let e=await this.getState();!(Object.keys(e).length>0)&&this.config.initialState&&await this.middlewareModule.dispatch({type:"init",value:this.config.initialState});}catch(e){throw this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",{error:e}),e}}async get(e){try{let t={operation:"get",timestamp:Date.now(),key:e},r=await this.middlewareModule.dispatch({type:"get",key:e,metadata:t}),s=await this.pluginExecutor?.executeAfterGet(e,r,t)??r;return await this.emitEvent({type:"storage:select",payload:{key:e,value:s}}),s}catch(t){throw this.logger?.error("Error getting value",{key:e,error:t}),t}}async set(e,t){try{let r={operation:"set",timestamp:Date.now(),key:e},s=await this.pluginExecutor?.executeBeforeSet(t,r)??t,i=await this.middlewareModule.dispatch({type:"set",key:e,value:s,metadata:r}),a=i?.e?.valueNotChanged===!0,o;if(a&&i?.e?.originalValue!==void 0?o=i.e.originalValue:o=await this.pluginExecutor?.executeAfterSet(e,i,r)??i,!a){let l=[e.toString()];this.notifySubscribers(e,o),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:o,changedPaths:l}),await this.emitEvent({type:"storage:update",payload:{key:e,value:o,changedPaths:l}});}}catch(r){throw this.logger?.error("Error setting value",{key:e,error:r}),r}}async update(e){try{let t={operation:"update",timestamp:Date.now()},r=await this.getState(),s=structuredClone(r);e(s);let i=this.findChangedPaths(r,s);if(i.size===0){this.logger?.debug&&this.logger.debug("No changes detected in update");return}this.logger?.debug&&this.logger.debug("Changed paths:",{paths:Array.from(i)});let a=new Set;for(let g of i){let y=g.split(".")[0];a.add(y);}let o=await Promise.all(Array.from(a).map(async g=>{let y={...t,key:g},v=await this.pluginExecutor?.executeBeforeSet(s[g],y)??s[g];return {key:g,value:v}})),n=await this.middlewareModule.dispatch({type:"update",value:o,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(i)}}),l={};Array.isArray(n)?n.forEach(g=>{g&&typeof g=="object"&&"key"in g&&"value"in g&&(l[g.key]=g.value);}):n&&typeof n=="object"&&(l={...n});let d=Object.keys(l).filter(g=>!this.isEqual(r[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 y=g.split(".")[0];if(y in u){let v;if(g===y)v=u[y];else {let z=g.substring(y.length+1);v=f(u[y],z);}v!==void 0&&this.notifySubscribers(g,v);}}catch(y){this.logger?.error("Error notifying path subscribers",{path:g,error:y});}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){try{let t={operation:"delete",timestamp:Date.now(),key:e};if(await this.pluginExecutor?.executeBeforeDelete(e,t)){let r=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});await this.pluginExecutor?.executeAfterDelete(e,t);let i=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:r,changedPaths:i}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:r,changedPaths:i}});}}catch(t){throw this.logger?.error("Error deleting value",{key:e,error:t}),t}}async clear(){try{this.pluginExecutor?.executeOnClear(),await this.middlewareModule.dispatch({type:"clear"});}catch(e){throw this.logger?.error("Error clearing storage",{error:e}),e}}async keys(){try{return await this.middlewareModule.dispatch({type:"keys"})}catch(e){throw this.logger?.error("Error getting keys",{error:e}),e}}async has(e){try{return await this.doHas(e)}catch(t){throw this.logger?.error("Error checking value existence",{key:e,error:t}),t}}async getState(){try{return await this.doGet("")||{}}catch(e){throw this.logger?.error("Error getting state",{error:e}),e}}subscribeToAll(e){return this.subscribers.has(c.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(c.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(c.GLOBAL_SUBSCRIPTION_KEY));}}subscribe(e,t){return typeof e=="string"?this.subscribeByKey(e,t):this.subscribeBySelector(e,t)}async destroy(){try{await this.clear(),await this.doDestroy(),this.initializedMiddlewares&&(await Promise.all(this.initializedMiddlewares.map(async e=>{"cleanup"in e&&await e.cleanup?.();})),this.initializedMiddlewares=null),await this.emitEvent({type:"storage:destroy"});}catch(e){throw this.logger?.error("Error destroying storage",{error:e}),e}}subscribeByKey(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=false;return this.subscribers.get(e).add(t),this.get(e).then(s=>{try{r||(r=!0,t(s));}catch(i){this.logger?.error("Error in initial callback",{key:e,error:i});}}),()=>{let s=this.subscribers.get(e);s&&(s.delete(t),s.size===0&&this.subscribers.delete(e));}}createDummyState(){let e={get:(t,r)=>(t[r]=t[r]||new Proxy({},e),t[r])};return new Proxy({},e)}isEqual(e,t){if(e===t)return true;if(e==null||t==null)return e===t;let r=typeof e;if(r!==typeof t)return false;if(r!=="object")return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return false;for(let o=0;o<e.length;o++)if(!this.isEqual(e[o],t[o]))return false;return true}let i=Object.keys(e),a=Object.keys(t);return i.length!==a.length?false:i.every(o=>Object.prototype.hasOwnProperty.call(t,o)&&this.isEqual(e[o],t[o]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let r=[],s=(i="")=>({get:(a,o)=>{if(typeof o=="symbol")return Reflect.get(a,o);let n=i?`${i}.${o}`:o;return r.push(n),new Proxy({},s(n))},has:(a,o)=>true,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:true,enumerable:true}),apply:(a,o,n)=>new Proxy(()=>{},s(i))});try{e(new Proxy(t,s()));}catch{}return r.length===0?"":(r.sort((i,a)=>a.length-i.length),this.selectorPathCache.set(e,r[0]),r[0])}notifySubscribers(e,t){let r=e.toString(),s=this.subscribers.get(r);s?.size&&new Set(s).forEach(a=>{try{a(t);}catch(o){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0435 \u043D\u0430 \u043A\u043E\u043B\u0431\u044D\u043A",{key:r,error:o});}});}findChangedPaths(e,t,r="",s=new Set,i=new WeakMap){if(e===t)return s;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e!==t&&s.add(r||""),s;if(i.has(e))return s;i.set(e,true);let a=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let o of a){let n=e[o],l=t[o];if(n===l)continue;let d=r?`${r}.${o}`:o;n&&l&&typeof n=="object"&&typeof l=="object"&&!Array.isArray(n)&&!Array.isArray(l)?this.findChangedPaths(n,l,d,s,i):Array.isArray(n)&&Array.isArray(l)?this.isEqual(n,l)||s.add(d):this.isEqual(n,l)||s.add(d);}return s}subscribeBySelector(e,t){let r=this.createDummyState(),s=this.extractPath(e,r);this.logger?.debug&&this.logger.debug("Subscribing to path:",{path:s});let i=async a=>{try{if(a==null){let l=await this.getState(),d=e(l);t(d);return}if(typeof a!="object"||a===null){t(a);return}let o=await this.getState(),n=e(o);t(n);}catch(o){this.logger?.error("Error in selector callback",{path:s,error:o}),t(a);}};return s?this.subscribeByKey(s,i):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 M=class c{constructor(e,t,r){this.dbName=e;this.logger=r;this.dbVersion=t;}static instances=new Map;db=null;initPromise=null;storeNames=new Set;dbVersion;static getInstance(e,t=1,r){c.instances.has(e)||c.instances.set(e,new c(e,t,r));let s=c.instances.get(e);return t>s.dbVersion&&(s.dbVersion=t),s}async initialize(){return this.db?this.db:(this.initPromise||(this.initPromise=this.openDatabase()),this.initPromise)}async ensureStoreExists(e){if(await this.initialize(),this.db.objectStoreNames.contains(e))return this.storeNames.add(e),this.db;this.logger?.debug(`Store "${e}" not found, upgrading database`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase([e]);let t=await this.initPromise;return this.storeNames.add(e),t}async openDatabase(e=[]){return new Promise((t,r)=>{this.logger?.debug(`Opening database "${this.dbName}" with version ${this.dbVersion}`);let s=indexedDB.open(this.dbName,this.dbVersion);s.onerror=()=>{this.logger?.error(`Failed to open database "${this.dbName}"`,{error:s.error}),r(s.error);},s.onsuccess=()=>{this.db=s.result;for(let i=0;i<this.db.objectStoreNames.length;i++)this.storeNames.add(this.db.objectStoreNames[i]);this.logger?.debug(`Database "${this.dbName}" opened successfully`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),t(this.db);},s.onupgradeneeded=i=>{let a=i.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let o of e)a.objectStoreNames.contains(o)||(this.logger?.debug(`Creating store "${o}"`),a.createObjectStore(o));};})}closeDatabase(){this.db&&(this.db.close(),this.db=null,this.initPromise=null);}async deleteDatabase(){return this.closeDatabase(),new Promise((e,t)=>{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{this.logger?.debug(`Database "${this.dbName}" deleted successfully`),c.instances.delete(this.dbName),this.storeNames.clear(),e();},r.onerror=()=>{this.logger?.error(`Failed to delete database "${this.dbName}"`,{error:r.error}),t(r.error);};})}async ensureStoresExist(e){await this.initialize();let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u043D\u0435\u0434\u043E\u0441\u0442\u0430\u044E\u0449\u0438\u0445 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449: ${t.join(", ")}`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase(t),this.initPromise)}getCurrentVersion(){return this.dbVersion}},D=class{constructor(e,t=1,r){this.dbName=e;this.logger=r;this.version=t;}db=null;version;getCurrentVersion(){return this.version}openDatabase(e,t=[]){return new Promise((r,s)=>{this.logger?.debug(`\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0441 \u0432\u0435\u0440\u0441\u0438\u0435\u0439 ${e}`);let i=indexedDB.open(this.dbName,e);i.onerror=()=>{this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u0438\u0438 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}"`,{error:i.error}),s(i.error);},i.onsuccess=()=>{this.db=i.result,this.version=this.db.version,this.logger?.debug(`\u0411\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0442\u043A\u0440\u044B\u0442\u0430`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),r(this.db);},i.onupgradeneeded=a=>{let o=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 n of t)o.objectStoreNames.contains(n)||(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "${n}"`),o.createObjectStore(n));};})}async ensureStoresExist(e){this.db||(this.db=await this.openDatabase(this.version));let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${t.join(", ")}`,{dbName:this.dbName,currentVersion:this.version}),this.db.close(),this.db=null,this.version++,this.db=await this.openDatabase(this.version,t),this.db)}close(){this.db&&(this.db.close(),this.db=null);}},R=class c extends w{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,r,s){super(e,t,r,s);let i=e.options;this.DB_NAME=i.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=i.dbVersion||1,this.dbManager=M.getInstance(this.DB_NAME,this.DB_VERSION,s);}async initialize(){try{this.logger?.debug(`Initializing IndexedDB storage "${this.STORE_NAME}"`),await this.dbManager.ensureStoreExists(this.STORE_NAME);try{if(!(await this.dbManager.initialize()).objectStoreNames.contains(this.STORE_NAME))throw new Error(`Store "${this.STORE_NAME}" not found after initialization`)}catch(e){throw this.logger?.error(`Error verifying store "${this.STORE_NAME}" exists:`,{error:e}),e}this.initializeMiddlewares();try{await this.initializeWithMiddlewares(),this.logger?.debug(`IndexedDB storage "${this.STORE_NAME}" initialized successfully`);}catch(e){this.logger?.error(`Failed to initialize middleware for store "${this.STORE_NAME}"`,{error:e});}return this}catch(e){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 IndexedDB "${this.name}"`,{error:e}),e}}static async getCurrentDBVersion(e){return new Promise(t=>{try{let r=indexedDB.open(e);r.onsuccess=()=>{let s=r.result.version;r.result.close(),t(s);},r.onerror=()=>{t(0);};}catch{t(0);}})}static async createStorages(e,t,r){let i=await this.getCurrentDBVersion(e)||1,a=new D(e,i,r),o=Object.values(t).map(l=>l.name);await a.ensureStoresExist(o);let n={};for(let[l,d]of Object.entries(t)){let u=new c({...d,options:{dbName:e,dbVersion:a.getCurrentVersion()}},d.pluginExecutor,d.eventEmitter,r);n[l]=await u.initialize();}return n}async getTransaction(e="readonly"){try{let t=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!t.objectStoreNames.contains(this.STORE_NAME)){this.logger?.warn(`Object store "${this.STORE_NAME}" not found, attempting to repair`),t.close(),this.dbManager.closeDatabase();let r=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!r.objectStoreNames.contains(this.STORE_NAME))throw new Error(`Object store "${this.STORE_NAME}" still doesn't exist after repair attempt`);return r.transaction(this.STORE_NAME,e)}return t.transaction(this.STORE_NAME,e)}catch(t){throw this.logger?.error(`Failed to create transaction for store "${this.STORE_NAME}"`,{error:t}),t}}async getObjectStore(e="readonly"){return (await this.getTransaction(e)).objectStore(this.STORE_NAME)}async doGet(e){let t=await this.getObjectStore();if(e==="")return new Promise((s,i)=>{let a=t.getAll();a.onerror=()=>i(a.error),a.onsuccess=()=>{let o=a.result,n=t.getAllKeys();n.onsuccess=()=>{let l=n.result.reduce((d,u,g)=>(u!=="root"&&(d[u]=o[g]),d),{});s(l);},n.onerror=()=>i(n.error);};});if(e instanceof a&&e.isUnparseable())return new Promise((s,i)=>{let a=t.get(e.valueOf());a.onerror=()=>i(a.error),a.onsuccess=()=>s(a.result);});let r=m(e);if(r.length>1){let s=r[0];return new Promise((i,a)=>{let o=t.get(s);o.onerror=()=>a(o.error),o.onsuccess=()=>{let n=o.result;if(!n){i(void 0);return}let l=f(n,r.slice(1).join("."));i(l);};})}return new Promise((s,i)=>{let a=t.get(r[0]);a.onerror=()=>i(a.error),a.onsuccess=()=>s(a.result);})}async doSet(e,t){if(e===""){let i=await this.getObjectStore("readwrite");return new Promise((a,o)=>{let n=i.transaction;n.oncomplete=()=>{a();},n.onerror=()=>{o(n.error);};let l=i.clear();l.onsuccess=()=>{let d=Object.entries(t);for(let[u,g]of d)i.put(g,u);},l.onerror=()=>{o(l.error);};})}let r=await this.getObjectStore("readwrite");if(e instanceof a&&e.isUnparseable()){await this.putValueInStore(r,e.valueOf(),t);return}let s=m(e);if(s.length>1){let i=s[0];return new Promise((a,o)=>{let n=r.get(i);n.onerror=()=>o(n.error),n.onsuccess=()=>{let l=n.result||{},d=b(l,s.slice(1).join("."),t),u=r.put(d,i);u.onerror=()=>o(u.error),u.onsuccess=()=>a();};})}await this.putValueInStore(r,s[0],t);}async putValueInStore(e,t,r){return new Promise((s,i)=>{let a=e.put(r,t.valueOf());a.onerror=()=>i(a.error),a.onsuccess=()=>s();})}async doUpdate(e){let t=new Map,r=[];for(let{key:s,value:i}of e){if(s instanceof a&&s.isUnparseable()){r.push({key:s.valueOf(),value:i});continue}let a$1=m(s),o=a$1[0],n=a$1.slice(1);t.has(o)||t.set(o,[]),t.get(o).push({path:n,value:i});}try{for(let{key:s,value:i}of r){let a=await this.getObjectStore("readwrite");await this.putValueInStore(a,s,i);}for(let[s,i]of t){let o={...await this.doGet(s)||{}};for(let{path:l,value:d}of i)l.length===0?o=d:o=b(o,l.join("."),d);let n=await this.getObjectStore("readwrite");await this.putValueInStore(n,s,o);}}catch(s){throw this.logger?.error("Error during update:",{error:s}),s}}async doDelete(e){let t=await this.getObjectStore("readwrite");if(e instanceof a&&e.isUnparseable())return new Promise((i,a)=>{let o=t.delete(e.valueOf());o.onerror=()=>a(o.error),o.onsuccess=()=>i(true);});let r=m(e);if(r.length===1)return new Promise((i,a)=>{let o=t.delete(r[0]);o.onerror=()=>a(o.error),o.onsuccess=()=>i(true);});let s=r[0];return new Promise((i,a)=>{let o=t.get(s);o.onerror=()=>a(o.error),o.onsuccess=()=>{let n=o.result;if(!n){i(false);return}let l=f(n,r.slice(0,-1).join(".")),d=r[r.length-1];if(!l||!(d in l)){i(false);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(n,s);u.onerror=()=>a(u.error),u.onsuccess=()=>i(true);};})}async doClear(){let e=await this.getObjectStore("readwrite");return new Promise((t,r)=>{let s=e.clear();s.onsuccess=()=>t(),s.onerror=()=>r(s.error);})}async doKeys(){let t=(await this.getObjectStore()).getAllKeys();return new Promise((r,s)=>{t.onsuccess=()=>{r(t.result);},t.onerror=()=>s(t.error);})}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){try{await this.doClear();}catch(e){throw this.logger?.error(`Error destroying store "${this.STORE_NAME}"`,{error:e}),e}}};var B=class extends w{constructor(e,t,r,s){super(e,t,r,s);}async initialize(){try{return await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing LocalStorage",{error:e}),e}}async doGet(e){let t=localStorage.getItem(this.name);if(!t)return;let r=JSON.parse(t);return e instanceof a&&e.isUnparseable()?r[e.valueOf()]:f(r,e)}async doSet(e,t){let r=localStorage.getItem(this.name),s=r?JSON.parse(r):{};if(e instanceof a&&e.isUnparseable()){s[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(s));return}let i=b({...s},e,t);localStorage.setItem(this.name,JSON.stringify(i));}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return false;let r=JSON.parse(t);if(e instanceof a&&e.isUnparseable()){let n=e.valueOf();return n in r?(delete r[n],localStorage.setItem(this.name,JSON.stringify(r)),true):false}let s=m(e),i=s.slice(0,-1).join("."),a$1=s[s.length-1],o=i?f(r,i):r;return !o||!(a$1 in o)?false:(delete o[a$1],localStorage.setItem(this.name,JSON.stringify(r)),true)}async doUpdate(e){let t=localStorage.getItem(this.name),r=t?JSON.parse(t):{};for(let{key:s,value:i}of e)s instanceof a&&s.isUnparseable()?r[s.valueOf()]=i:b(r,s,i);localStorage.setItem(this.name,JSON.stringify(r));}async doClear(){localStorage.removeItem(this.name);}async doKeys(){let e=localStorage.getItem(this.name);if(!e)return [];let t=JSON.parse(e);return this.getAllKeys(t)}async doHas(e){return await this.doGet(e)!==void 0}getAllKeys(e){return Object.keys(e)}async doDestroy(){await this.doClear();}};var K=class extends w{storage=new Map;constructor(e,t,r,s){super(e,t,r,s);}async initialize(){try{return this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing MemoryStorage",{error:e}),e}}async doGet(e){let t=this.storage.get(this.name);if(t)return e instanceof a&&e.isUnparseable()?t[e.valueOf()]:f(t,e)}async doSet(e,t){let r=this.storage.get(this.name)||{};if(e instanceof a&&e.isUnparseable()){r[e.valueOf()]=t,this.storage.set(this.name,r);return}let s=b({...r},e,t);this.storage.set(this.name,s);}async doDelete(e){let t=this.storage.get(this.name);if(!t)return false;if(e instanceof a&&e.isUnparseable()){let o=e.valueOf();return o in t?(delete t[o],this.storage.set(this.name,t),true):false}let r=m(e),s=r.slice(0,-1).join("."),i=r[r.length-1],a$1=s?f(t,s):t;return !a$1||!(i in a$1)?false:(delete a$1[i],this.storage.set(this.name,t),true)}async doUpdate(e){let r={...this.storage.get(this.name)||{}};for(let{key:s,value:i}of e)s instanceof a&&s.isUnparseable()?r[s.valueOf()]=i:b(r,s,i);this.storage.set(this.name,r);}async doClear(){this.storage.delete(this.name);}async doKeys(){let e=this.storage.get(this.name);return e?this.getAllKeys(e):[]}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){this.storage.delete(this.name);}getAllKeys(e){return Object.keys(e)}};export{N as a,$ as b,I as c,V as d,R as e,B as f,K as g};
@@ -0,0 +1 @@
1
+ 'use strict';var chunkNMDHQXMS_cjs=require('./chunk-NMDHQXMS.cjs'),react=require('react'),jsxRuntime=require('react/jsx-runtime');var f=new Map;function B(s,r){let[p,l]=react.useState(r?.initialValue),[a,S]=react.useState(!!r?.withLoading),i=react.useRef(r?.initialValue),n=react.useRef(r?.equals||((t,o)=>t===o)),c=s.getId(),u=t=>{(i.current===void 0||!n.current(t,i.current))&&(i.current=t,l(t));};return react.useEffect(()=>{f.has(c)||f.set(c,{lastValue:void 0,listeners:new Set,unsubscribe:null});let t=f.get(c);return t.listeners.add(u),t.lastValue!==void 0?(u(t.lastValue),r?.withLoading&&S(false)):(r?.withLoading&&S(true),s.select().then(o=>{t.lastValue=o,t.listeners.forEach(T=>T(o)),r?.withLoading&&S(false);}).catch(o=>{r?.withLoading&&S(false);})),t.unsubscribe||(t.unsubscribe=s.subscribe({notify:o=>{t.lastValue=o,t.listeners.forEach(T=>{try{T(o);}catch{}});}})),()=>{let o=f.get(c);o&&(o.listeners.delete(u),o.listeners.size===0&&(o.unsubscribe&&o.unsubscribe(),f.delete(c)));}},[s,c]),r?.withLoading?{data:p,isLoading:a}:p}var X=(s,r)=>{let[p,l]=react.useState(void 0);return react.useEffect(()=>{let a=true;(async()=>{try{let n=await s.getState(),c=r(n);a&&l(c);}catch{}})();let i;try{i=s.subscribe(r,n=>{a&&l(n);});}catch{i=()=>{};}return ()=>{a=false,i();}},[s,r]),p};var g="useSynapseActions \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438 \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0430 contextSynapse";function ee(s,r){let{loadingComponent:p=null,mergeFn:l=chunkNMDHQXMS_cjs.b}=r||{},a=null,S=false,i=(async()=>{try{a=await(s instanceof Promise?s:Promise.resolve(s)),S=!0;}catch{}})(),n=react.createContext(null),c=()=>{let e=react.useContext(n);if(!e)throw new Error(g);return e.storage},u=()=>{let e=react.useContext(n);if(!e)throw new Error(g);return e.selectors},t=()=>{let e=react.useContext(n);if(!e)throw new Error(g);if("actions"in e)return e.actions;throw new Error("useSynapseActions: actions \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u0430 \u0444\u0443\u043D\u043A\u0446\u0438\u044F createDispatcherFn \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")},o=()=>{let e=react.useContext(n);if(!e)throw new Error(g);if("state$"in e)return e.state$;throw new Error("useSynapseState$: state$ \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u044B \u0444\u0443\u043D\u043A\u0446\u0438\u0438 createDispatcherFn \u0438 createEffectConfig \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")};function T(e){function P({contextProps:d,...O}){let [W,L]=react.useState(false),[C,V]=react.useState(S);react.useRef(`synapse-${a?.storage.name||"initializing"}`);return react.useEffect(()=>{S||i.then(()=>{V(true);});},[]),react.useEffect(()=>{if(!C)return;let x=true;return (async()=>{try{a&&d&&Object.keys(d).length>0&&await a.storage.update(b=>{l(b,d);}),x&&L(!0);}catch{}})(),()=>{x=false;}},[d,C]),C?W?jsxRuntime.jsx(n.Provider,{value:a,children:jsxRuntime.jsx(e,{...O})}):p||jsxRuntime.jsx("div",{children:"\u0418\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430..."}):p||jsxRuntime.jsx("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let v=e.displayName||e.name||"Component";return P.displayName=`SynapseContext(${v})`,P}return {contextSynapse:T,useSynapseStorage:c,useSynapseSelectors:u,useSynapseActions:t,useSynapseState$:o,cleanupSynapse:async()=>(await i,a?.destroy()||Promise.resolve())}}exports.a=B;exports.b=X;exports.c=ee;
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-5X65PSGD.js';import {Subject,of,combineLatest,pipe,Observable,merge,forkJoin,timer}from'rxjs';import {filter,take,map,switchMap,share,catchError,delay,mergeMap,concatAll,toArray}from'rxjs/operators';var m=class{constructor(e){this.options=e;this.storage=e.storage,this.middlewareAPI={getState:()=>this.storage.getState(),dispatch:async t=>(this.actions$.next(t),t.payload),storage:this.storage,actions$:this.actions,actions:this.dispatch,watchers:this.watchers,findActionByType:t=>this.findActionByType(t),findWatcherByType:t=>this.findWatcherByType(t)},e.middlewares&&e.middlewares.length>0&&this.use(...e.middlewares);}actions$=new Subject;actions=this.actions$.asObservable();dispatch={};watchers={};storage;middlewareFunctions=[];middlewareAPI;use(...e){for(let t=0;t<e.length;t++)try{let r=e[t](this.middlewareAPI);this.middlewareFunctions.push(r);}catch{}return this}getActions(){return this.dispatch}getTypedDispatch(){return this.dispatch}getTypedWatchers(){return this.watchers}findActionByType(e){return Object.values(this.dispatch).find(t=>t.actionType.split(`[${this.storage.name}]`)[1]===e)}findWatcherByType(e){return Object.values(this.watchers).find(t=>t.actionType===e)}createAction(e,t){let r=`[${this.storage.name}]${e.type}`,n=null,a=null,i=async c=>{let o=[c];if(t?.memoize&&n&&a&&t.memoize(o,n,a))return a;let l={type:r,meta:e.meta},p;if(this.middlewareFunctions.length>0){let d=async u=>t?.worker?this.executeInWorker(t.worker,r,o,e.action):Promise.resolve(e.action(c));for(let u=this.middlewareFunctions.length-1;u>=0;u--){let T=this.middlewareFunctions[u],b=d;d=async x=>T(async R=>b(R))(x);}p=await d(l);}else t?.worker?p=await this.executeInWorker(t.worker,r,o,e.action):p=await e.action(c);return l.payload=p,n=[...o],a=p,this.actions$.next(l),p};return i.t="dispatch",Object.defineProperty(i,"actionType",{value:r,writable:false,enumerable:true}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:false,enumerable:true}),i}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,r=new Subject,n,a=this.storage.subscribe(e.selector,c=>{if(!e.shouldTrigger||e.shouldTrigger(n,c)){let o={type:t,payload:c,meta:e.meta};this.actions$.next(o),r.next(o),n=c;}}),i=()=>r.asObservable();return i.t="watchers",Object.defineProperty(i,"actionType",{value:t,writable:false,enumerable:true}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:false,enumerable:true}),Object.defineProperty(i,"unsubscribe",{value:a,writable:false,enumerable:true}),i}async executeInWorker(e,t,r,n){return new Promise((a,i)=>{let c=`${t}_${Date.now()}_${Math.random()}`,o=l=>{l.data.requestId===c&&(e.removeEventListener("message",o),l.data.error?i(new Error(l.data.error)):a(l.data.result));};e.addEventListener("message",o),e.postMessage({type:t,args:r,requestId:c}),setTimeout(()=>{e.removeEventListener("message",o),i(new Error(`Worker execution timeout for action: ${t}`));},3e4);})}};function H(s,e){let t=new m(s),r=e(s.storage,{createAction:(n,a)=>t.createAction(n,a),createWatcher:n=>t.createWatcher(n)});for(let[n,a]of Object.entries(r))if(typeof a=="function"){let i=a.t;t[i][n]=a;}return t}function v(s,e){let t={};return [...new Set([...Object.keys(s),...Object.keys(e)])].forEach(n=>{if(n in s&&n in e)if(typeof s[n]=="object"&&s[n]!==null&&typeof e[n]=="object"&&e[n]!==null&&!Array.isArray(s[n])&&!Array.isArray(e[n])){let a=v(s[n],e[n]);Object.keys(a).length>0&&(t[n]=a);}else JSON.stringify(s[n])!==JSON.stringify(e[n])&&(t[n]={PREV:s[n],NEXT:e[n]});else n in s?t[n]={PREV:s[n],NEXT:void 0}:t[n]={PREV:void 0,NEXT:e[n]};}),t}var Y=(s={})=>{let e={action:"\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435",prevState:"\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",nextState:"\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",duration:"\u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",error:"\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0438",diff:"\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F",changesCount:"\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439",showFullState:"\u041F\u043E\u043B\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435"},t={collapsed:false,duration:true,diff:false,showFullState:true,translations:e,colors:{title:"#3498db",prevState:"#9E9E9E",fullState:"#008a15",action:"#03A9F4",nextState:"#4CAF50",error:"#F20404",diff:"#9C27B0"}},r={...t,...s,translations:{...e,...s.translations||{}},colors:{...t.colors,...s.colors||{}}},{collapsed:n,colors:i}=r;return o=>l=>async p=>{let d=Date.now(),u=await o.getState();try{let T=await l(p),b=await o.getState(),F=Date.now()-d,R=`${p.type}`;if((n?console.groupCollapsed:console.group)(`%c ${R}`,`color: ${i.title}; font-weight: bold`),r.diff){let P=v(u,b),J=Object.keys(P).length;}return r.showFullState,T}catch(T){throw T}}};var w=(s,e,t,r=0)=>{let n=a(e,t).map(a=>of(a).pipe(delay(r),mergeMap(s)));return of(...n).pipe(concatAll(),toArray())};var E=(s,e,t,r=0)=>forkJoin(a(e,t).map((n,a)=>timer(a*r).pipe(mergeMap(()=>s(n)))));function we(s){let{actionType:e}=s;return e?t=>t.pipe(filter(r=>r!==void 0&&r.type===e)):filter(()=>false)}function Ee(s){let e=s.map(t=>t.actionType).filter(Boolean);return e.length===0?filter(()=>false):t=>t.pipe(filter(r=>r!==void 0&&e.includes(r.type)))}function De(s){return e=>{let t=s.map(n=>n.actionType).filter(Boolean);if(t.length===0)return of([]);let r=t.map((n,a)=>e.pipe(filter(i=>i.type===n),take(1),map(i=>({index:a,action:i}))));return combineLatest(r).pipe(map(n=>(n.sort((a,i)=>a.index-i.index),n.map(a=>a.action))))}}function Fe(s,...e){return s.pipe(map(t=>e.map(r=>r(t))))}function Pe(s,e){return s.pipe(map(t=>{let r={};for(let[n,a]of Object.entries(e))r[n]=a(t);return r}))}function Oe({validator:s,apiCall:e}){return pipe(switchMap(t=>{let r=()=>e(t,{chunkRequest:E,chunkRequestConsistent:w});if(!s)return r();let n=s(t),{conditions:a,skipAction:i}=n;return a.every(Boolean)?r():Array.isArray(i)?of(...i?.filter(Boolean).map(o=>typeof o=="function"?o():o)):of(typeof i=="function"?i():i)}))}var D=class{constructor(e,t={},r,n={},a={}){this.storage=e;this.externalStates=t;this.dispatchers=r;this.services=n;this.config=a;this.subscribeToDispatchers(),this.state$=new Observable(i=>{this.storage.getState().then(o=>i.next(o));let c=this.storage.subscribeToAll(()=>{this.storage.getState().then(o=>i.next(o));});return ()=>c()}).pipe(share());}effects=[];subscriptions=[];running=false;action$=new Subject;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let r=t.actions.subscribe(n=>{this.action$.next(n);});this.subscriptions.push(r);}}add(e){return this.effects.push(e),this.running&&this.subscribeToEffect(e),this}addEffects(e){return e.forEach(t=>this.add(t)),this}start(){return this.running?this:(this.effects.forEach(e=>this.subscribeToEffect(e)),this.running=true,this)}stop(){return this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.running=false,this}subscribeToEffect(e){try{let r=e(this.action$.asObservable(),this.state$,this.externalStates,this.dispatchers,this.services,this.config).pipe(catchError(n=>of(null))).subscribe(n=>{if(n!=null&&typeof n=="function")try{n();}catch{}});this.subscriptions.push(r);}catch{}}};function Ce(s){return s}function $e(s){return s}function We(...s){return (e,t,r,n,a,i)=>{let c=s.map(o=>{try{return o(e,t,r,n,a,i)}catch{return of(null)}});return merge(...c)}}export{m as a,H as b,Y as c,we as d,Ee as e,De as f,Fe as g,Pe as h,Oe as i,D as j,Ce as k,$e as l,We as m};
@@ -0,0 +1 @@
1
+ 'use strict';var p=(t,n)=>{for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(typeof n[e]=="object"&&n[e]!==null&&!Array.isArray(n[e])?((!t[e]||typeof t[e]!="object")&&(t[e]={}),p(t[e],n[e])):t[e]=n[e]);};function l(t,n=1){if(n<=0)throw new Error("Size must be greater than 0");if(!t||!t.length)return [];let e=[],o=t.length,r=0;for(;r<o;)e.push(t.slice(r,r+n)),r+=n;return e}exports.a=l;exports.b=p;
@@ -0,0 +1 @@
1
+ import {b}from'./chunk-5X65PSGD.js';import {useState,useRef,useEffect,createContext,useContext}from'react';import {jsx}from'react/jsx-runtime';var f=new Map;function B(s,r){let[p,l]=useState(r?.initialValue),[a,S]=useState(!!r?.withLoading),i=useRef(r?.initialValue),n=useRef(r?.equals||((t,o)=>t===o)),c=s.getId(),u=t=>{(i.current===void 0||!n.current(t,i.current))&&(i.current=t,l(t));};return useEffect(()=>{f.has(c)||f.set(c,{lastValue:void 0,listeners:new Set,unsubscribe:null});let t=f.get(c);return t.listeners.add(u),t.lastValue!==void 0?(u(t.lastValue),r?.withLoading&&S(false)):(r?.withLoading&&S(true),s.select().then(o=>{t.lastValue=o,t.listeners.forEach(T=>T(o)),r?.withLoading&&S(false);}).catch(o=>{r?.withLoading&&S(false);})),t.unsubscribe||(t.unsubscribe=s.subscribe({notify:o=>{t.lastValue=o,t.listeners.forEach(T=>{try{T(o);}catch{}});}})),()=>{let o=f.get(c);o&&(o.listeners.delete(u),o.listeners.size===0&&(o.unsubscribe&&o.unsubscribe(),f.delete(c)));}},[s,c]),r?.withLoading?{data:p,isLoading:a}:p}var X=(s,r)=>{let[p,l]=useState(void 0);return useEffect(()=>{let a=true;(async()=>{try{let n=await s.getState(),c=r(n);a&&l(c);}catch{}})();let i;try{i=s.subscribe(r,n=>{a&&l(n);});}catch{i=()=>{};}return ()=>{a=false,i();}},[s,r]),p};var g="useSynapseActions \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438 \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0430 contextSynapse";function ee(s,r){let{loadingComponent:p=null,mergeFn:l=b}=r||{},a=null,S=false,i=(async()=>{try{a=await(s instanceof Promise?s:Promise.resolve(s)),S=!0;}catch{}})(),n=createContext(null),c=()=>{let e=useContext(n);if(!e)throw new Error(g);return e.storage},u=()=>{let e=useContext(n);if(!e)throw new Error(g);return e.selectors},t=()=>{let e=useContext(n);if(!e)throw new Error(g);if("actions"in e)return e.actions;throw new Error("useSynapseActions: actions \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u0430 \u0444\u0443\u043D\u043A\u0446\u0438\u044F createDispatcherFn \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")},o=()=>{let e=useContext(n);if(!e)throw new Error(g);if("state$"in e)return e.state$;throw new Error("useSynapseState$: state$ \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0442\u0438\u043F\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430. \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u043D\u044B \u0444\u0443\u043D\u043A\u0446\u0438\u0438 createDispatcherFn \u0438 createEffectConfig \u043F\u0440\u0438 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430.")};function T(e){function P({contextProps:d,...O}){let [W,L]=useState(false),[C,V]=useState(S);useRef(`synapse-${a?.storage.name||"initializing"}`);return useEffect(()=>{S||i.then(()=>{V(true);});},[]),useEffect(()=>{if(!C)return;let x=true;return (async()=>{try{a&&d&&Object.keys(d).length>0&&await a.storage.update(b=>{l(b,d);}),x&&L(!0);}catch{}})(),()=>{x=false;}},[d,C]),C?W?jsx(n.Provider,{value:a,children:jsx(e,{...O})}):p||jsx("div",{children:"\u0418\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430..."}):p||jsx("div",{children:"\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430..."})}let v=e.displayName||e.name||"Component";return P.displayName=`SynapseContext(${v})`,P}return {contextSynapse:T,useSynapseStorage:c,useSynapseSelectors:u,useSynapseActions:t,useSynapseState$:o,cleanupSynapse:async()=>(await i,a?.destroy()||Promise.resolve())}}export{B as a,X as b,ee as c};
@@ -0,0 +1 @@
1
+ 'use strict';var chunkNMDHQXMS_cjs=require('./chunk-NMDHQXMS.cjs'),rxjs=require('rxjs'),operators=require('rxjs/operators');var m=class{constructor(e){this.options=e;this.storage=e.storage,this.middlewareAPI={getState:()=>this.storage.getState(),dispatch:async t=>(this.actions$.next(t),t.payload),storage:this.storage,actions$:this.actions,actions:this.dispatch,watchers:this.watchers,findActionByType:t=>this.findActionByType(t),findWatcherByType:t=>this.findWatcherByType(t)},e.middlewares&&e.middlewares.length>0&&this.use(...e.middlewares);}actions$=new rxjs.Subject;actions=this.actions$.asObservable();dispatch={};watchers={};storage;middlewareFunctions=[];middlewareAPI;use(...e){for(let t=0;t<e.length;t++)try{let r=e[t](this.middlewareAPI);this.middlewareFunctions.push(r);}catch{}return this}getActions(){return this.dispatch}getTypedDispatch(){return this.dispatch}getTypedWatchers(){return this.watchers}findActionByType(e){return Object.values(this.dispatch).find(t=>t.actionType.split(`[${this.storage.name}]`)[1]===e)}findWatcherByType(e){return Object.values(this.watchers).find(t=>t.actionType===e)}createAction(e,t){let r=`[${this.storage.name}]${e.type}`,n=null,a=null,i=async c=>{let o=[c];if(t?.memoize&&n&&a&&t.memoize(o,n,a))return a;let l={type:r,meta:e.meta},p;if(this.middlewareFunctions.length>0){let d=async u=>t?.worker?this.executeInWorker(t.worker,r,o,e.action):Promise.resolve(e.action(c));for(let u=this.middlewareFunctions.length-1;u>=0;u--){let T=this.middlewareFunctions[u],b=d;d=async x=>T(async R=>b(R))(x);}p=await d(l);}else t?.worker?p=await this.executeInWorker(t.worker,r,o,e.action):p=await e.action(c);return l.payload=p,n=[...o],a=p,this.actions$.next(l),p};return i.t="dispatch",Object.defineProperty(i,"actionType",{value:r,writable:false,enumerable:true}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:false,enumerable:true}),i}createWatcher(e){let t=`[${this.storage.name}]${e.type}`,r=new rxjs.Subject,n,a=this.storage.subscribe(e.selector,c=>{if(!e.shouldTrigger||e.shouldTrigger(n,c)){let o={type:t,payload:c,meta:e.meta};this.actions$.next(o),r.next(o),n=c;}}),i=()=>r.asObservable();return i.t="watchers",Object.defineProperty(i,"actionType",{value:t,writable:false,enumerable:true}),e.meta&&Object.defineProperty(i,"meta",{value:e.meta,writable:false,enumerable:true}),Object.defineProperty(i,"unsubscribe",{value:a,writable:false,enumerable:true}),i}async executeInWorker(e,t,r,n){return new Promise((a,i)=>{let c=`${t}_${Date.now()}_${Math.random()}`,o=l=>{l.data.requestId===c&&(e.removeEventListener("message",o),l.data.error?i(new Error(l.data.error)):a(l.data.result));};e.addEventListener("message",o),e.postMessage({type:t,args:r,requestId:c}),setTimeout(()=>{e.removeEventListener("message",o),i(new Error(`Worker execution timeout for action: ${t}`));},3e4);})}};function H(s,e){let t=new m(s),r=e(s.storage,{createAction:(n,a)=>t.createAction(n,a),createWatcher:n=>t.createWatcher(n)});for(let[n,a]of Object.entries(r))if(typeof a=="function"){let i=a.t;t[i][n]=a;}return t}function v(s,e){let t={};return [...new Set([...Object.keys(s),...Object.keys(e)])].forEach(n=>{if(n in s&&n in e)if(typeof s[n]=="object"&&s[n]!==null&&typeof e[n]=="object"&&e[n]!==null&&!Array.isArray(s[n])&&!Array.isArray(e[n])){let a=v(s[n],e[n]);Object.keys(a).length>0&&(t[n]=a);}else JSON.stringify(s[n])!==JSON.stringify(e[n])&&(t[n]={PREV:s[n],NEXT:e[n]});else n in s?t[n]={PREV:s[n],NEXT:void 0}:t[n]={PREV:void 0,NEXT:e[n]};}),t}var Y=(s={})=>{let e={action:"\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435",prevState:"\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",nextState:"\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435",duration:"\u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",error:"\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0438",diff:"\u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F",changesCount:"\u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439",showFullState:"\u041F\u043E\u043B\u043D\u043E\u0435 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435"},t={collapsed:false,duration:true,diff:false,showFullState:true,translations:e,colors:{title:"#3498db",prevState:"#9E9E9E",fullState:"#008a15",action:"#03A9F4",nextState:"#4CAF50",error:"#F20404",diff:"#9C27B0"}},r={...t,...s,translations:{...e,...s.translations||{}},colors:{...t.colors,...s.colors||{}}},{collapsed:n,colors:i}=r;return o=>l=>async p=>{let d=Date.now(),u=await o.getState();try{let T=await l(p),b=await o.getState(),F=Date.now()-d,R=`${p.type}`;if((n?console.groupCollapsed:console.group)(`%c ${R}`,`color: ${i.title}; font-weight: bold`),r.diff){let P=v(u,b),J=Object.keys(P).length;}return r.showFullState,T}catch(T){throw T}}};var w=(s,e,t,r=0)=>{let n=chunkNMDHQXMS_cjs.a(e,t).map(a=>rxjs.of(a).pipe(operators.delay(r),operators.mergeMap(s)));return rxjs.of(...n).pipe(operators.concatAll(),operators.toArray())};var E=(s,e,t,r=0)=>rxjs.forkJoin(chunkNMDHQXMS_cjs.a(e,t).map((n,a)=>rxjs.timer(a*r).pipe(operators.mergeMap(()=>s(n)))));function we(s){let{actionType:e}=s;return e?t=>t.pipe(operators.filter(r=>r!==void 0&&r.type===e)):operators.filter(()=>false)}function Ee(s){let e=s.map(t=>t.actionType).filter(Boolean);return e.length===0?operators.filter(()=>false):t=>t.pipe(operators.filter(r=>r!==void 0&&e.includes(r.type)))}function De(s){return e=>{let t=s.map(n=>n.actionType).filter(Boolean);if(t.length===0)return rxjs.of([]);let r=t.map((n,a)=>e.pipe(operators.filter(i=>i.type===n),operators.take(1),operators.map(i=>({index:a,action:i}))));return rxjs.combineLatest(r).pipe(operators.map(n=>(n.sort((a,i)=>a.index-i.index),n.map(a=>a.action))))}}function Fe(s,...e){return s.pipe(operators.map(t=>e.map(r=>r(t))))}function Pe(s,e){return s.pipe(operators.map(t=>{let r={};for(let[n,a]of Object.entries(e))r[n]=a(t);return r}))}function Oe({validator:s,apiCall:e}){return rxjs.pipe(operators.switchMap(t=>{let r=()=>e(t,{chunkRequest:E,chunkRequestConsistent:w});if(!s)return r();let n=s(t),{conditions:a,skipAction:i}=n;return a.every(Boolean)?r():Array.isArray(i)?rxjs.of(...i?.filter(Boolean).map(o=>typeof o=="function"?o():o)):rxjs.of(typeof i=="function"?i():i)}))}var D=class{constructor(e,t={},r,n={},a={}){this.storage=e;this.externalStates=t;this.dispatchers=r;this.services=n;this.config=a;this.subscribeToDispatchers(),this.state$=new rxjs.Observable(i=>{this.storage.getState().then(o=>i.next(o));let c=this.storage.subscribeToAll(()=>{this.storage.getState().then(o=>i.next(o));});return ()=>c()}).pipe(operators.share());}effects=[];subscriptions=[];running=false;action$=new rxjs.Subject;state$;subscribeToDispatchers(){for(let[e,t]of Object.entries(this.dispatchers)){let r=t.actions.subscribe(n=>{this.action$.next(n);});this.subscriptions.push(r);}}add(e){return this.effects.push(e),this.running&&this.subscribeToEffect(e),this}addEffects(e){return e.forEach(t=>this.add(t)),this}start(){return this.running?this:(this.effects.forEach(e=>this.subscribeToEffect(e)),this.running=true,this)}stop(){return this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.running=false,this}subscribeToEffect(e){try{let r=e(this.action$.asObservable(),this.state$,this.externalStates,this.dispatchers,this.services,this.config).pipe(operators.catchError(n=>rxjs.of(null))).subscribe(n=>{if(n!=null&&typeof n=="function")try{n();}catch{}});this.subscriptions.push(r);}catch{}}};function Ce(s){return s}function $e(s){return s}function We(...s){return (e,t,r,n,a,i)=>{let c=s.map(o=>{try{return o(e,t,r,n,a,i)}catch{return rxjs.of(null)}});return rxjs.merge(...c)}}exports.a=m;exports.b=H;exports.c=Y;exports.d=we;exports.e=Ee;exports.f=De;exports.g=Fe;exports.h=Pe;exports.i=Oe;exports.j=D;exports.k=Ce;exports.l=$e;exports.m=We;
@@ -0,0 +1 @@
1
+ 'use strict';var chunk635Q6YJZ_cjs=require('./chunk-635Q6YJZ.cjs');var T=new Map;function O(c){let e=0;if(c.length===0)return e.toString(36);for(let t=0;t<c.length;t++){let r=c.charCodeAt(t);e=(e<<5)-e+r,e=e&e;}return Math.abs(e).toString(36).substring(0,6)}function S(c,e){if(c===e)return true;if(c==null||e==null)return false;if(typeof c!="object"&&typeof c!="function"&&typeof e!="object"&&typeof e!="function")return c===e;if(typeof c!=typeof e)return false;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 false;for(let t=0;t<c.length;t++)if(!S(c[t],e[t]))return false;return true}if(typeof c=="object"&&typeof e=="object"){let t=Object.keys(c),r=Object.keys(e);return t.length!==r.length?false:t.every(s=>Object.prototype.hasOwnProperty.call(e,s)?S(c[s],e[s]):false)}return false}function C(c,e=S){let t,r,s=false;return function(a){if(!s||t!==a){let o=c(a);(!s||!e(o,r))&&(r=o),t=a,s=true;}return r}}var P=class{constructor(e,t,r=S,s){this.name=e;this.equals=r;this.logger=s;this.id=e,this.memoizedGetState=this.createMemoizedGetState(t);}id;subscribers=new Set;lastValue;memoizedGetState;createMemoizedGetState(e){let t=null,r=false;return async()=>{if(r&&t)return t;r=true;try{return t=e(),await t}finally{r=false;}}}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 r=>{try{await r.notify(e);}catch(s){this.logger?.error(`[${this.id}] \u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0438 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430`,{error:s});}});await Promise.all(t);}}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}},N=class{constructor(e,t){this.source=e;this.logger=t;this.storageName=e.name,this.source.getState().then(r=>{this.cachedState=r;});}storageName;subscriptions=new Map;cachedState;localSelectorCache=new Map;batchUpdateInProgress=false;pendingUpdates=new Set;generateName(e,t,r){let s=e?"simple":"combined",i="";if(e){let a=t.toString();i=O(a);}else {let a=t.map(n=>n.getId()).join("_"),o=r.toString();i=O(a+o);}return `${this.storageName}_${s}_${i}`}processPendingUpdates(){this.pendingUpdates.size===0||this.batchUpdateInProgress||(this.batchUpdateInProgress=true,setTimeout(async()=>{try{let e=Array.from(this.pendingUpdates);this.pendingUpdates.clear(),this.cachedState=await this.source.getState();let t=e.map(async r=>{let s=this.subscriptions.get(r);if(s)try{return await s.notify()}catch(i){this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430 ${r}`,{error:i});}return Promise.resolve()});await Promise.all(t);}catch(e){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0436\u0438\u0434\u0430\u044E\u0449\u0438\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0439",{error:e});}finally{this.batchUpdateInProgress=false,this.pendingUpdates.size>0&&this.processPendingUpdates();}},0));}createSelector(e,t,r){let s=!Array.isArray(e),i=s?t||{}:r||{},a=i.name||this.generateName(s,e,s?void 0:t);if(this.localSelectorCache.has(a))return this.localSelectorCache.get(a).api;if(T.has(a)){let d=T.get(a);return d.refCount++,d.api}let o,n,l=[];if(s){let d=C(e,i.equals||S),u=this.createSimpleSelector(d,{...i,name:a,equals:i.equals||S});o=u.api,l=u.unsubscribeFunctions;}else {n=e;let d=this.createCombinedSelector(n,t,{...i,name:a,equals:i.equals||S});o=d.api,l=d.unsubscribeFunctions;}return this.localSelectorCache.set(a,{api:o,dependencies:n,unsubscribeFunctions:l}),T.set(a,{api:o,refCount:1,unsubscribeFunctions:l}),o}createSimpleSelector(e,t){let r=async()=>{if(this.cachedState)return e(this.cachedState);let n=await this.source.getState();return this.cachedState=n,e(n)},s=new P(t.name,r,t.equals||S,this.logger),i=s.getId();this.subscriptions.set(i,s);let o=[this.source.subscribeToAll(async n=>{n?.type==="storage:update"&&(this.pendingUpdates.add(i),this.processPendingUpdates());})];return {api:{select:()=>r(),subscribe:n=>s.subscribe(n),getId:()=>i},unsubscribeFunctions:o}}createCombinedSelector(e,t,r){let s=C(u=>t(...u),r.equals||S),i=async()=>{let u=await Promise.all(e.map(g=>g.select()));return s(u)},a=new P(r.name,i,r.equals||S,this.logger),o=a.getId();this.subscriptions.set(o,a);let n=null,l=()=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,a.notify().catch(u=>this.logger?.error(`[${o}] \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=>a.subscribe(u),getId:()=>o},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(r=>r());});let e=new Set;this.localSelectorCache.forEach((t,r)=>{e.add(r);}),this.localSelectorCache.clear(),e.forEach(t=>{let r=T.get(t);r&&(r.refCount--,r.refCount<=0&&(r.unsubscribeFunctions.forEach(s=>s()),T.delete(t)));});}};var $=class{constructor(e,t,r="default"){this.parentExecutor=e;this.logger=t;this.storageName=r;}plugins=new Map;createContext(e){return {storageName:this.storageName,timestamp:Date.now(),metadata:e}}async add(e){if(this.plugins.has(e.name)){this.logger?.warn(`\u041F\u043B\u0430\u0433\u0438\u043D ${e.name} \u0443\u0436\u0435 \u0431\u044B\u043B \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D`);return}try{await e.initialize?.(),this.plugins.set(e.name,e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D",{name:e.name});}catch(t){throw t}}async remove(e){let t=this.plugins.get(e);t&&(await t.destroy?.(),this.plugins.delete(e),this.logger?.info("\u041F\u043B\u0430\u0433\u0438\u043D \u0443\u0434\u0430\u043B\u0435\u043D",{name:e}));}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}async initialize(){for(let e of this.plugins.values())await e.initialize?.();}async destroy(){await Promise.all(Array.from(this.plugins.values()).map(e=>e.destroy?.()??Promise.resolve())),this.plugins.clear();}async executeBeforeSet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeSet(r,s));for(let i of this.plugins.values())if(i.onBeforeSet)try{r=await i.onBeforeSet(r,s);}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeSet`,{error:a}),a}return r}async executeAfterSet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterSet(e,s,i));for(let a of this.plugins.values())if(a.onAfterSet)try{s=await a.onAfterSet(e,s,i);}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onAfterSet`,{key:e,error:o}),o}return s}async executeBeforeGet(e,t){let r=e,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeGet(r,s));for(let i of this.plugins.values())if(i.onBeforeGet)try{r=await i.onBeforeGet(r,s);}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeGet`,{key:e,error:a}),a}return r}async executeAfterGet(e,t,r){let s=t,i=this.createContext(r);this.parentExecutor&&(s=await this.parentExecutor.executeAfterGet(e,s,i));for(let a of this.plugins.values())if(a.onAfterGet)try{s=await a.onAfterGet(e,s,i);}catch(o){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${a.name} onAfterGet`,{key:e,error:o}),o}return s}async executeBeforeDelete(e,t){let r=true,s=this.createContext(t);this.parentExecutor&&(r=await this.parentExecutor.executeBeforeDelete(e,s));for(let i of this.plugins.values())if(i.onBeforeDelete)try{r=await i.onBeforeDelete(e,s)&&r;}catch(a){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${i.name} onBeforeDelete`,{key:e,error:a}),a}return r}async executeAfterDelete(e,t){let r=this.createContext(t);this.parentExecutor&&await this.parentExecutor.executeAfterDelete(e,r);for(let s of this.plugins.values())if(s.onAfterDelete)try{await s.onAfterDelete(e,r);}catch(i){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${s.name} onAfterDelete`,{key:e,error:i}),i}}async executeOnClear(e){let t=this.createContext(e);this.parentExecutor&&await this.parentExecutor.executeOnClear(t);for(let r of this.plugins.values())if(r.onClear)try{await r.onClear(t);}catch(s){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043B\u0430\u0433\u0438\u043D\u0435 ${r.name} onClear`,{error:s}),s}}};var I=(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))(I||{});var E=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??false,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 r=await this.syncHandler();this.postMessage("SYNC_RESPONSE",r,t.senderId);}catch(r){this.error("Error handling sync request:",r);}return}if(t.type==="SYNC_RESPONSE"){let r=this.pendingSyncRequests.get(this.tabId);r&&(clearTimeout(r.timeout),this.pendingSyncRequests.delete(this.tabId),r.resolve(t.payload));return}for(let r of this.messageHandlers)try{await r(t);}catch(s){this.error("Error in message handler:",s);}}}handleError(e){this.error("Channel error:",e);}postMessage(e,t,r){let s={type:e,payload:t,senderId:this.tabId,timestamp:Date.now()};this.channel.postMessage(s);}subscribe(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}setSyncHandler(e){this.syncHandler=e;}broadcast(e,t){this.postMessage(e,t);}async requestSync(){return new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingSyncRequests.delete(this.tabId),e(null);},this.syncTimeoutMs);this.pendingSyncRequests.set(this.tabId,{resolve:e,reject:t,timeout:r}),this.postMessage("SYNC_REQUEST",{type:"sync"});})}close(){for(let[,e]of this.pendingSyncRequests)clearTimeout(e.timeout),e.reject(new Error("Channel closed"));this.pendingSyncRequests.clear(),this.messageHandlers.clear(),this.syncHandler=void 0,this.channel.close();}};var V=c=>{let{storageName:e,storageType:t}=c,r=`${t}-${e}`,s=new E(r,{debug:true});return {name:"sync",setup:i=>(t==="memory"&&(s.setSyncHandler(async()=>{let a=await i.getState();return {type:"update",key:"*",value:Object.entries(a).map(([l,d])=>({key:l,value:d})),metadata:{batchUpdate:true,timestamp:Date.now()}}}),s.requestSync().then(async a=>{if(a?.type==="update"&&Array.isArray(a.value))try{if(!a.value.every(n=>n&&typeof n=="object"&&"key"in n&&"value"in n))return;await i.storage.doUpdate(a.value),a.value.forEach(({key:n,value:l})=>{i.storage.notifySubscribers(n,l);}),i.storage.notifySubscribers("*",{type:"storage:update",value:a.value,source:"broadcast"});}catch{}})),s.subscribe(async a=>{let{type:o,payload:n}=a;if(t==="memory"){switch(o){case "set":await i.storage.doSet(n.key,n.value),i.storage.notifySubscribers(n.key,n.value);break;case "update":Array.isArray(n.value)&&(await i.storage.doUpdate(n.value),n.value.forEach(({key:l,value:d})=>{i.storage.notifySubscribers(l,d);}));break;case "delete":await i.storage.doDelete(n.key),i.storage.notifySubscribers(n.key,void 0);break;case "clear":await i.storage.doClear(),i.storage.notifySubscribers("*",{type:"storage:update",value:{},source:"broadcast"});break}i.storage.notifySubscribers("*",{type:"storage:update",key:n?.key,value:n?.value,source:"broadcast"});}})),reducer:i=>a=>async o=>{let n=await a(o);return ["set","delete","clear","update"].includes(o.type)&&s.broadcast(o.type,o),n},cleanup:()=>{s.close();}}};var A=class{options;queues=new Map;timeouts=new Map;constructor(e){this.options={batchSize:e.batchSize??10,batchDelay:e.batchDelay??300,onBatch:e.onBatch??(async()=>{}),getSegmentKey:e.getSegmentKey??(()=>"default"),shouldBatch:e.shouldBatch??(()=>true),mergeItems:e.mergeItems??(t=>t)};}async add(e,t){return this.options.shouldBatch(e)?new Promise((r,s)=>{let i=this.options.getSegmentKey(e);this.addToQueue(i,{action:e,baseOperation:t,resolve:r,reject:s});}):t()}addToQueue(e,t){let r=this.queues.get(e);r||(r=[],this.queues.set(e,r)),r.push(t),this.clearSegmentTimeout(e),r.length>=this.options.batchSize?this.processBatch(e):this.setSegmentTimeout(e);}async processBatch(e){let t=this.queues.get(e);if(t?.length){this.queues.delete(e),this.clearSegmentTimeout(e);try{let r=this.options.mergeItems(t.map(s=>s.action));for(let s=0;s<r.length;s++){let i=await t[s].baseOperation();t[s].resolve(i);}}catch(r){t.forEach(({reject:s})=>s(r));}}}clearSegmentTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e));}setSegmentTimeout(e){let t=setTimeout(()=>{this.processBatch(e);},this.options.batchDelay);this.timeouts.set(e,t);}async flush(){let e=Array.from(this.queues.keys());await Promise.all(e.map(t=>this.processBatch(t)));}clear(){this.queues.clear(),Array.from(this.timeouts.values()).forEach(clearTimeout),this.timeouts.clear();}getState(){let e={};return this.queues.forEach((t,r)=>{e[r]=t.length;}),e}};var U=(c={})=>{let e=new A({batchSize:c.batchSize,batchDelay:c.batchDelay,shouldBatch:t=>!(t.type==="get"||t.type==="keys"),getSegmentKey:t=>t.key||"default",mergeItems:t=>t.reduce((r,s)=>{if(s.type==="set"){let i=r.findIndex(a=>a.type==="set"&&a.key===s.key);i!==-1?r[i]=s:r.push(s);}else r.push(s);return r},[])});return {name:"batching",setup:()=>{},reducer:t=>r=>s=>e.add(s,()=>r(s))}};var q=(c={})=>{let{comparator:e=(s,i)=>{if(s===i)return true;if(typeof s!="object"||typeof i!="object"||s===null||i===null)return s===i;let a=Object.keys(s),o=Object.keys(i);return a.length!==o.length?false:a.every(n=>Object.prototype.hasOwnProperty.call(i,n)&&s[n]===i[n])},segments:t=[]}=c,r=new Map;return {name:"shallow-compare",setup:s=>{},reducer:s=>i=>async a=>{if(a.type!=="set"||t.length&&!t.includes(a.metadata?.segment??"default"))return i(a);let o=a.key,n=r.get(o),l=a.value;if(n!==void 0&&e(n,l))return {...n,e:{valueNotChanged:true,originalValue:n}};let d=await i(a);return r.set(o,l),d}}};var x=class{middlewares=[];api;initialized=false;dispatchFn;constructor(e){this.api={dispatch:async t=>this.dispatch(t),getState:()=>e.getState(),storage:{doGet:e.doGet.bind(e),doSet:e.doSet.bind(e),doUpdate:e.doUpdate.bind(e),doDelete:e.doDelete.bind(e),doClear:e.doClear.bind(e),doKeys:e.doKeys.bind(e),notifySubscribers:e.notifySubscribers.bind(e)}};}async baseOperation(e){let{processed:t,...r}=e.metadata||{},s={...e};switch(s.type){case "get":return this.api.storage.doGet(s.key);case "set":return await this.api.storage.doSet(s.key,s.value),this.api.storage.doGet(s.key);case "update":return Array.isArray(s.value)?(await this.api.storage.doUpdate(s.value),this.api.storage.doGet("")):s.value;case "delete":return this.api.storage.doDelete(s.key);case "clear":return this.api.storage.doClear();case "init":{let i=await this.api.storage.doGet("");return Object.keys(i||{}).length>0?i:s.value?(await this.api.storage.doSet("",s.value),this.api.storage.doGet("")):i}case "keys":return this.api.storage.doKeys();default:throw new Error(`Unknown action type: ${s.type}`)}}initializeMiddlewares(){if(this.initialized)return;let e=this.baseOperation.bind(this);for(let t of [...this.middlewares].reverse()){let r=e;e=async s=>{if(s.metadata?.processed)return r(s);let i={...s,metadata:{...s.metadata,processed:true,timestamp:s.metadata?.timestamp||Date.now()}};return t.reducer(this.api)(r)(i)};}this.dispatchFn=e,this.initialized=true;}use(e){e.setup&&e.setup(this.api),this.middlewares.push(e),this.initialized=false;}async dispatch(e){this.initialized||this.initializeMiddlewares();try{return this.dispatchFn(e)}catch(t){throw t}}};function m(c){return c instanceof chunk635Q6YJZ_cjs.a&&c.isUnparseable()?[c.toString()]:c.toString().replace(/\[/g,".").replace(/\]/g,"").split(".").filter(Boolean)}function f(c,e){return m(e).reduce((r,s)=>r===void 0?void 0:r[s],c)}function b(c,e,t){if(e==="")return t;let r=m(e);if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable())return c[e.toString()]=t,c;let s=r.pop(),i=r.reduce((a,o)=>{let n=r[r.indexOf(o)+1],l=!Number.isNaN(Number(n));return o in a||(a[o]=l?[]:{}),a[o]},c);return i[s]=t,c}var w=class c{constructor(e,t,r,s){this.config=e;this.pluginExecutor=t;this.eventEmitter=r;this.logger=s;this.name=e.name,this.middlewareModule=new x({getState:this.getState.bind(this),doGet:this.doGet.bind(this),doSet:this.doSet.bind(this),doUpdate:this.doUpdate.bind(this),doDelete:this.doDelete.bind(this),doClear:this.doClear.bind(this),doKeys:this.doKeys.bind(this),notifySubscribers:this.notifySubscribers.bind(this),pluginExecutor:this.pluginExecutor,eventEmitter:this.eventEmitter,logger:this.logger}),this.initializeMiddlewares();}static GLOBAL_SUBSCRIPTION_KEY="*";name;selectorPathCache=new WeakMap;middlewareModule;initializedMiddlewares=null;subscribers=new Map;initializeMiddlewares(){this.config.middlewares&&!this.initializedMiddlewares&&(this.initializedMiddlewares=this.config.middlewares(()=>this.getDefaultMiddleware()),this.initializedMiddlewares.forEach(e=>this.middlewareModule.use(e)));}getDefaultMiddleware(){return {batching:(e={})=>U(e),shallowCompare:(e={})=>q(e)}}async initializeWithMiddlewares(){try{let e=await this.getState();!(Object.keys(e).length>0)&&this.config.initialState&&await this.middlewareModule.dispatch({type:"init",value:this.config.initialState});}catch(e){throw this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430",{error:e}),e}}async get(e){try{let t={operation:"get",timestamp:Date.now(),key:e},r=await this.middlewareModule.dispatch({type:"get",key:e,metadata:t}),s=await this.pluginExecutor?.executeAfterGet(e,r,t)??r;return await this.emitEvent({type:"storage:select",payload:{key:e,value:s}}),s}catch(t){throw this.logger?.error("Error getting value",{key:e,error:t}),t}}async set(e,t){try{let r={operation:"set",timestamp:Date.now(),key:e},s=await this.pluginExecutor?.executeBeforeSet(t,r)??t,i=await this.middlewareModule.dispatch({type:"set",key:e,value:s,metadata:r}),a=i?.e?.valueNotChanged===!0,o;if(a&&i?.e?.originalValue!==void 0?o=i.e.originalValue:o=await this.pluginExecutor?.executeAfterSet(e,i,r)??i,!a){let l=[e.toString()];this.notifySubscribers(e,o),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:o,changedPaths:l}),await this.emitEvent({type:"storage:update",payload:{key:e,value:o,changedPaths:l}});}}catch(r){throw this.logger?.error("Error setting value",{key:e,error:r}),r}}async update(e){try{let t={operation:"update",timestamp:Date.now()},r=await this.getState(),s=structuredClone(r);e(s);let i=this.findChangedPaths(r,s);if(i.size===0){this.logger?.debug&&this.logger.debug("No changes detected in update");return}this.logger?.debug&&this.logger.debug("Changed paths:",{paths:Array.from(i)});let a=new Set;for(let g of i){let y=g.split(".")[0];a.add(y);}let o=await Promise.all(Array.from(a).map(async g=>{let y={...t,key:g},v=await this.pluginExecutor?.executeBeforeSet(s[g],y)??s[g];return {key:g,value:v}})),n=await this.middlewareModule.dispatch({type:"update",value:o,metadata:{...t,batchUpdate:!0,changedPaths:Array.from(i)}}),l={};Array.isArray(n)?n.forEach(g=>{g&&typeof g=="object"&&"key"in g&&"value"in g&&(l[g.key]=g.value);}):n&&typeof n=="object"&&(l={...n});let d=Object.keys(l).filter(g=>!this.isEqual(r[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 y=g.split(".")[0];if(y in u){let v;if(g===y)v=u[y];else {let z=g.substring(y.length+1);v=f(u[y],z);}v!==void 0&&this.notifySubscribers(g,v);}}catch(y){this.logger?.error("Error notifying path subscribers",{path:g,error:y});}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){try{let t={operation:"delete",timestamp:Date.now(),key:e};if(await this.pluginExecutor?.executeBeforeDelete(e,t)){let r=await this.middlewareModule.dispatch({type:"delete",key:e,metadata:t});await this.pluginExecutor?.executeAfterDelete(e,t);let i=[e.toString()];this.notifySubscribers(e,void 0),this.notifySubscribers(c.GLOBAL_SUBSCRIPTION_KEY,{type:"storage:update",key:e,value:void 0,result:r,changedPaths:i}),await this.emitEvent({type:"storage:update",payload:{key:e,value:void 0,result:r,changedPaths:i}});}}catch(t){throw this.logger?.error("Error deleting value",{key:e,error:t}),t}}async clear(){try{this.pluginExecutor?.executeOnClear(),await this.middlewareModule.dispatch({type:"clear"});}catch(e){throw this.logger?.error("Error clearing storage",{error:e}),e}}async keys(){try{return await this.middlewareModule.dispatch({type:"keys"})}catch(e){throw this.logger?.error("Error getting keys",{error:e}),e}}async has(e){try{return await this.doHas(e)}catch(t){throw this.logger?.error("Error checking value existence",{key:e,error:t}),t}}async getState(){try{return await this.doGet("")||{}}catch(e){throw this.logger?.error("Error getting state",{error:e}),e}}subscribeToAll(e){return this.subscribers.has(c.GLOBAL_SUBSCRIPTION_KEY)||this.subscribers.set(c.GLOBAL_SUBSCRIPTION_KEY,new Set),this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY).add(e),()=>{let t=this.subscribers.get(c.GLOBAL_SUBSCRIPTION_KEY);t&&(t.delete(e),t.size===0&&this.subscribers.delete(c.GLOBAL_SUBSCRIPTION_KEY));}}subscribe(e,t){return typeof e=="string"?this.subscribeByKey(e,t):this.subscribeBySelector(e,t)}async destroy(){try{await this.clear(),await this.doDestroy(),this.initializedMiddlewares&&(await Promise.all(this.initializedMiddlewares.map(async e=>{"cleanup"in e&&await e.cleanup?.();})),this.initializedMiddlewares=null),await this.emitEvent({type:"storage:destroy"});}catch(e){throw this.logger?.error("Error destroying storage",{error:e}),e}}subscribeByKey(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let r=false;return this.subscribers.get(e).add(t),this.get(e).then(s=>{try{r||(r=!0,t(s));}catch(i){this.logger?.error("Error in initial callback",{key:e,error:i});}}),()=>{let s=this.subscribers.get(e);s&&(s.delete(t),s.size===0&&this.subscribers.delete(e));}}createDummyState(){let e={get:(t,r)=>(t[r]=t[r]||new Proxy({},e),t[r])};return new Proxy({},e)}isEqual(e,t){if(e===t)return true;if(e==null||t==null)return e===t;let r=typeof e;if(r!==typeof t)return false;if(r!=="object")return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return false;for(let o=0;o<e.length;o++)if(!this.isEqual(e[o],t[o]))return false;return true}let i=Object.keys(e),a=Object.keys(t);return i.length!==a.length?false:i.every(o=>Object.prototype.hasOwnProperty.call(t,o)&&this.isEqual(e[o],t[o]))}extractPath(e,t){if(this.selectorPathCache.has(e))return this.selectorPathCache.get(e);let r=[],s=(i="")=>({get:(a,o)=>{if(typeof o=="symbol")return Reflect.get(a,o);let n=i?`${i}.${o}`:o;return r.push(n),new Proxy({},s(n))},has:(a,o)=>true,ownKeys:()=>[],getOwnPropertyDescriptor:()=>({configurable:true,enumerable:true}),apply:(a,o,n)=>new Proxy(()=>{},s(i))});try{e(new Proxy(t,s()));}catch{}return r.length===0?"":(r.sort((i,a)=>a.length-i.length),this.selectorPathCache.set(e,r[0]),r[0])}notifySubscribers(e,t){let r=e.toString(),s=this.subscribers.get(r);s?.size&&new Set(s).forEach(a=>{try{a(t);}catch(o){this.logger?.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u0432 \u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0435 \u043D\u0430 \u043A\u043E\u043B\u0431\u044D\u043A",{key:r,error:o});}});}findChangedPaths(e,t,r="",s=new Set,i=new WeakMap){if(e===t)return s;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return e!==t&&s.add(r||""),s;if(i.has(e))return s;i.set(e,true);let a=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(let o of a){let n=e[o],l=t[o];if(n===l)continue;let d=r?`${r}.${o}`:o;n&&l&&typeof n=="object"&&typeof l=="object"&&!Array.isArray(n)&&!Array.isArray(l)?this.findChangedPaths(n,l,d,s,i):Array.isArray(n)&&Array.isArray(l)?this.isEqual(n,l)||s.add(d):this.isEqual(n,l)||s.add(d);}return s}subscribeBySelector(e,t){let r=this.createDummyState(),s=this.extractPath(e,r);this.logger?.debug&&this.logger.debug("Subscribing to path:",{path:s});let i=async a=>{try{if(a==null){let l=await this.getState(),d=e(l);t(d);return}if(typeof a!="object"||a===null){t(a);return}let o=await this.getState(),n=e(o);t(n);}catch(o){this.logger?.error("Error in selector callback",{path:s,error:o}),t(a);}};return s?this.subscribeByKey(s,i):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 M=class c{constructor(e,t,r){this.dbName=e;this.logger=r;this.dbVersion=t;}static instances=new Map;db=null;initPromise=null;storeNames=new Set;dbVersion;static getInstance(e,t=1,r){c.instances.has(e)||c.instances.set(e,new c(e,t,r));let s=c.instances.get(e);return t>s.dbVersion&&(s.dbVersion=t),s}async initialize(){return this.db?this.db:(this.initPromise||(this.initPromise=this.openDatabase()),this.initPromise)}async ensureStoreExists(e){if(await this.initialize(),this.db.objectStoreNames.contains(e))return this.storeNames.add(e),this.db;this.logger?.debug(`Store "${e}" not found, upgrading database`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase([e]);let t=await this.initPromise;return this.storeNames.add(e),t}async openDatabase(e=[]){return new Promise((t,r)=>{this.logger?.debug(`Opening database "${this.dbName}" with version ${this.dbVersion}`);let s=indexedDB.open(this.dbName,this.dbVersion);s.onerror=()=>{this.logger?.error(`Failed to open database "${this.dbName}"`,{error:s.error}),r(s.error);},s.onsuccess=()=>{this.db=s.result;for(let i=0;i<this.db.objectStoreNames.length;i++)this.storeNames.add(this.db.objectStoreNames[i]);this.logger?.debug(`Database "${this.dbName}" opened successfully`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),t(this.db);},s.onupgradeneeded=i=>{let a=i.target.result;this.logger?.debug(`Upgrading database "${this.dbName}" to version ${this.dbVersion}`);for(let o of e)a.objectStoreNames.contains(o)||(this.logger?.debug(`Creating store "${o}"`),a.createObjectStore(o));};})}closeDatabase(){this.db&&(this.db.close(),this.db=null,this.initPromise=null);}async deleteDatabase(){return this.closeDatabase(),new Promise((e,t)=>{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{this.logger?.debug(`Database "${this.dbName}" deleted successfully`),c.instances.delete(this.dbName),this.storeNames.clear(),e();},r.onerror=()=>{this.logger?.error(`Failed to delete database "${this.dbName}"`,{error:r.error}),t(r.error);};})}async ensureStoresExist(e){await this.initialize();let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u043D\u0435\u0434\u043E\u0441\u0442\u0430\u044E\u0449\u0438\u0445 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449: ${t.join(", ")}`,{dbName:this.dbName,currentStores:Array.from(this.db.objectStoreNames)}),this.db.close(),this.db=null,this.dbVersion++,this.initPromise=this.openDatabase(t),this.initPromise)}getCurrentVersion(){return this.dbVersion}},D=class{constructor(e,t=1,r){this.dbName=e;this.logger=r;this.version=t;}db=null;version;getCurrentVersion(){return this.version}openDatabase(e,t=[]){return new Promise((r,s)=>{this.logger?.debug(`\u041E\u0442\u043A\u0440\u044B\u0442\u0438\u0435 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0441 \u0432\u0435\u0440\u0441\u0438\u0435\u0439 ${e}`);let i=indexedDB.open(this.dbName,e);i.onerror=()=>{this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u0438\u0438 \u0431\u0430\u0437\u044B \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}"`,{error:i.error}),s(i.error);},i.onsuccess=()=>{this.db=i.result,this.version=this.db.version,this.logger?.debug(`\u0411\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445 "${this.dbName}" \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u043E\u0442\u043A\u0440\u044B\u0442\u0430`,{version:this.db.version,stores:Array.from(this.db.objectStoreNames)}),r(this.db);},i.onupgradeneeded=a=>{let o=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 n of t)o.objectStoreNames.contains(n)||(this.logger?.debug(`\u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "${n}"`),o.createObjectStore(n));};})}async ensureStoresExist(e){this.db||(this.db=await this.openDatabase(this.version));let t=e.filter(r=>!this.db.objectStoreNames.contains(r));return t.length===0?this.db:(this.logger?.debug(`\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430: ${t.join(", ")}`,{dbName:this.dbName,currentVersion:this.version}),this.db.close(),this.db=null,this.version++,this.db=await this.openDatabase(this.version,t),this.db)}close(){this.db&&(this.db.close(),this.db=null);}},R=class c extends w{DB_NAME;STORE_NAME;DB_VERSION;dbManager;constructor(e,t,r,s){super(e,t,r,s);let i=e.options;this.DB_NAME=i.dbName||"app_storage",this.STORE_NAME=e.name,this.DB_VERSION=i.dbVersion||1,this.dbManager=M.getInstance(this.DB_NAME,this.DB_VERSION,s);}async initialize(){try{this.logger?.debug(`Initializing IndexedDB storage "${this.STORE_NAME}"`),await this.dbManager.ensureStoreExists(this.STORE_NAME);try{if(!(await this.dbManager.initialize()).objectStoreNames.contains(this.STORE_NAME))throw new Error(`Store "${this.STORE_NAME}" not found after initialization`)}catch(e){throw this.logger?.error(`Error verifying store "${this.STORE_NAME}" exists:`,{error:e}),e}this.initializeMiddlewares();try{await this.initializeWithMiddlewares(),this.logger?.debug(`IndexedDB storage "${this.STORE_NAME}" initialized successfully`);}catch(e){this.logger?.error(`Failed to initialize middleware for store "${this.STORE_NAME}"`,{error:e});}return this}catch(e){throw this.logger?.error(`\u041E\u0448\u0438\u0431\u043A\u0430 \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 IndexedDB "${this.name}"`,{error:e}),e}}static async getCurrentDBVersion(e){return new Promise(t=>{try{let r=indexedDB.open(e);r.onsuccess=()=>{let s=r.result.version;r.result.close(),t(s);},r.onerror=()=>{t(0);};}catch{t(0);}})}static async createStorages(e,t,r){let i=await this.getCurrentDBVersion(e)||1,a=new D(e,i,r),o=Object.values(t).map(l=>l.name);await a.ensureStoresExist(o);let n={};for(let[l,d]of Object.entries(t)){let u=new c({...d,options:{dbName:e,dbVersion:a.getCurrentVersion()}},d.pluginExecutor,d.eventEmitter,r);n[l]=await u.initialize();}return n}async getTransaction(e="readonly"){try{let t=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!t.objectStoreNames.contains(this.STORE_NAME)){this.logger?.warn(`Object store "${this.STORE_NAME}" not found, attempting to repair`),t.close(),this.dbManager.closeDatabase();let r=await this.dbManager.ensureStoreExists(this.STORE_NAME);if(!r.objectStoreNames.contains(this.STORE_NAME))throw new Error(`Object store "${this.STORE_NAME}" still doesn't exist after repair attempt`);return r.transaction(this.STORE_NAME,e)}return t.transaction(this.STORE_NAME,e)}catch(t){throw this.logger?.error(`Failed to create transaction for store "${this.STORE_NAME}"`,{error:t}),t}}async getObjectStore(e="readonly"){return (await this.getTransaction(e)).objectStore(this.STORE_NAME)}async doGet(e){let t=await this.getObjectStore();if(e==="")return new Promise((s,i)=>{let a=t.getAll();a.onerror=()=>i(a.error),a.onsuccess=()=>{let o=a.result,n=t.getAllKeys();n.onsuccess=()=>{let l=n.result.reduce((d,u,g)=>(u!=="root"&&(d[u]=o[g]),d),{});s(l);},n.onerror=()=>i(n.error);};});if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable())return new Promise((s,i)=>{let a=t.get(e.valueOf());a.onerror=()=>i(a.error),a.onsuccess=()=>s(a.result);});let r=m(e);if(r.length>1){let s=r[0];return new Promise((i,a)=>{let o=t.get(s);o.onerror=()=>a(o.error),o.onsuccess=()=>{let n=o.result;if(!n){i(void 0);return}let l=f(n,r.slice(1).join("."));i(l);};})}return new Promise((s,i)=>{let a=t.get(r[0]);a.onerror=()=>i(a.error),a.onsuccess=()=>s(a.result);})}async doSet(e,t){if(e===""){let i=await this.getObjectStore("readwrite");return new Promise((a,o)=>{let n=i.transaction;n.oncomplete=()=>{a();},n.onerror=()=>{o(n.error);};let l=i.clear();l.onsuccess=()=>{let d=Object.entries(t);for(let[u,g]of d)i.put(g,u);},l.onerror=()=>{o(l.error);};})}let r=await this.getObjectStore("readwrite");if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable()){await this.putValueInStore(r,e.valueOf(),t);return}let s=m(e);if(s.length>1){let i=s[0];return new Promise((a,o)=>{let n=r.get(i);n.onerror=()=>o(n.error),n.onsuccess=()=>{let l=n.result||{},d=b(l,s.slice(1).join("."),t),u=r.put(d,i);u.onerror=()=>o(u.error),u.onsuccess=()=>a();};})}await this.putValueInStore(r,s[0],t);}async putValueInStore(e,t,r){return new Promise((s,i)=>{let a=e.put(r,t.valueOf());a.onerror=()=>i(a.error),a.onsuccess=()=>s();})}async doUpdate(e){let t=new Map,r=[];for(let{key:s,value:i}of e){if(s instanceof chunk635Q6YJZ_cjs.a&&s.isUnparseable()){r.push({key:s.valueOf(),value:i});continue}let a=m(s),o=a[0],n=a.slice(1);t.has(o)||t.set(o,[]),t.get(o).push({path:n,value:i});}try{for(let{key:s,value:i}of r){let a=await this.getObjectStore("readwrite");await this.putValueInStore(a,s,i);}for(let[s,i]of t){let o={...await this.doGet(s)||{}};for(let{path:l,value:d}of i)l.length===0?o=d:o=b(o,l.join("."),d);let n=await this.getObjectStore("readwrite");await this.putValueInStore(n,s,o);}}catch(s){throw this.logger?.error("Error during update:",{error:s}),s}}async doDelete(e){let t=await this.getObjectStore("readwrite");if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable())return new Promise((i,a)=>{let o=t.delete(e.valueOf());o.onerror=()=>a(o.error),o.onsuccess=()=>i(true);});let r=m(e);if(r.length===1)return new Promise((i,a)=>{let o=t.delete(r[0]);o.onerror=()=>a(o.error),o.onsuccess=()=>i(true);});let s=r[0];return new Promise((i,a)=>{let o=t.get(s);o.onerror=()=>a(o.error),o.onsuccess=()=>{let n=o.result;if(!n){i(false);return}let l=f(n,r.slice(0,-1).join(".")),d=r[r.length-1];if(!l||!(d in l)){i(false);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(n,s);u.onerror=()=>a(u.error),u.onsuccess=()=>i(true);};})}async doClear(){let e=await this.getObjectStore("readwrite");return new Promise((t,r)=>{let s=e.clear();s.onsuccess=()=>t(),s.onerror=()=>r(s.error);})}async doKeys(){let t=(await this.getObjectStore()).getAllKeys();return new Promise((r,s)=>{t.onsuccess=()=>{r(t.result);},t.onerror=()=>s(t.error);})}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){try{await this.doClear();}catch(e){throw this.logger?.error(`Error destroying store "${this.STORE_NAME}"`,{error:e}),e}}};var B=class extends w{constructor(e,t,r,s){super(e,t,r,s);}async initialize(){try{return await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing LocalStorage",{error:e}),e}}async doGet(e){let t=localStorage.getItem(this.name);if(!t)return;let r=JSON.parse(t);return e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable()?r[e.valueOf()]:f(r,e)}async doSet(e,t){let r=localStorage.getItem(this.name),s=r?JSON.parse(r):{};if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable()){s[e.valueOf()]=t,localStorage.setItem(this.name,JSON.stringify(s));return}let i=b({...s},e,t);localStorage.setItem(this.name,JSON.stringify(i));}async doDelete(e){let t=localStorage.getItem(this.name);if(!t)return false;let r=JSON.parse(t);if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable()){let n=e.valueOf();return n in r?(delete r[n],localStorage.setItem(this.name,JSON.stringify(r)),true):false}let s=m(e),i=s.slice(0,-1).join("."),a=s[s.length-1],o=i?f(r,i):r;return !o||!(a in o)?false:(delete o[a],localStorage.setItem(this.name,JSON.stringify(r)),true)}async doUpdate(e){let t=localStorage.getItem(this.name),r=t?JSON.parse(t):{};for(let{key:s,value:i}of e)s instanceof chunk635Q6YJZ_cjs.a&&s.isUnparseable()?r[s.valueOf()]=i:b(r,s,i);localStorage.setItem(this.name,JSON.stringify(r));}async doClear(){localStorage.removeItem(this.name);}async doKeys(){let e=localStorage.getItem(this.name);if(!e)return [];let t=JSON.parse(e);return this.getAllKeys(t)}async doHas(e){return await this.doGet(e)!==void 0}getAllKeys(e){return Object.keys(e)}async doDestroy(){await this.doClear();}};var K=class extends w{storage=new Map;constructor(e,t,r,s){super(e,t,r,s);}async initialize(){try{return this.initializeMiddlewares(),await this.initializeWithMiddlewares(),this}catch(e){throw this.logger?.error("Error initializing MemoryStorage",{error:e}),e}}async doGet(e){let t=this.storage.get(this.name);if(t)return e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable()?t[e.valueOf()]:f(t,e)}async doSet(e,t){let r=this.storage.get(this.name)||{};if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable()){r[e.valueOf()]=t,this.storage.set(this.name,r);return}let s=b({...r},e,t);this.storage.set(this.name,s);}async doDelete(e){let t=this.storage.get(this.name);if(!t)return false;if(e instanceof chunk635Q6YJZ_cjs.a&&e.isUnparseable()){let o=e.valueOf();return o in t?(delete t[o],this.storage.set(this.name,t),true):false}let r=m(e),s=r.slice(0,-1).join("."),i=r[r.length-1],a=s?f(t,s):t;return !a||!(i in a)?false:(delete a[i],this.storage.set(this.name,t),true)}async doUpdate(e){let r={...this.storage.get(this.name)||{}};for(let{key:s,value:i}of e)s instanceof chunk635Q6YJZ_cjs.a&&s.isUnparseable()?r[s.valueOf()]=i:b(r,s,i);this.storage.set(this.name,r);}async doClear(){this.storage.delete(this.name);}async doKeys(){let e=this.storage.get(this.name);return e?this.getAllKeys(e):[]}async doHas(e){return await this.doGet(e)!==void 0}async doDestroy(){this.storage.delete(this.name);}getAllKeys(e){return Object.keys(e)}};exports.a=N;exports.b=$;exports.c=I;exports.d=V;exports.e=R;exports.f=B;exports.g=K;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkVSIVOWZF_cjs=require('./chunk-VSIVOWZF.cjs'),chunkUFBCZ25Y_cjs=require('./chunk-UFBCZ25Y.cjs');async function l(e){let s=e.createStorageFn?await e.createStorageFn():e.storage,a=[],n={storage:s,selectors:{},destroy:async()=>{for(let o of a)await o();}};a.push(()=>s.destroy());let t,c,r;if(e.createSelectorsFn)try{c=new chunkVSIVOWZF_cjs.a(s);let o=e.externalSelectors||{};n.selectors=e.createSelectorsFn(c,o),typeof c.destroy=="function"&&a.push(()=>c.destroy());}catch{}if(e.createDispatcherFn&&(t=e.createDispatcherFn(s),n.dispatcher=t,t&&"dispatch"in t&&(n.actions=t.dispatch,typeof t.destroy=="function"&&a.push(()=>t.destroy()))),e.createEffectConfig&&t)try{let{dispatchers:o,api:T,config:y,externalStates:d}=e.createEffectConfig(t),p=d||{};r=new chunkUFBCZ25Y_cjs.j(s,p,o,T,y),Array.isArray(e.effects)&&e.effects.forEach(g=>{r&&r.add(g);}),r.start(),n.state$=r.state$,a.push(()=>{r&&r.stop();});}catch{}return n}exports.a=l;
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-6RNZVHSR.js';import {j}from'./chunk-IPUPRMZK.js';async function l(e){let s=e.createStorageFn?await e.createStorageFn():e.storage,a$1=[],n={storage:s,selectors:{},destroy:async()=>{for(let o of a$1)await o();}};a$1.push(()=>s.destroy());let t,c,r;if(e.createSelectorsFn)try{c=new a(s);let o=e.externalSelectors||{};n.selectors=e.createSelectorsFn(c,o),typeof c.destroy=="function"&&a$1.push(()=>c.destroy());}catch{}if(e.createDispatcherFn&&(t=e.createDispatcherFn(s),n.dispatcher=t,t&&"dispatch"in t&&(n.actions=t.dispatch,typeof t.destroy=="function"&&a$1.push(()=>t.destroy()))),e.createEffectConfig&&t)try{let{dispatchers:o,api:T,config:y,externalStates:d}=e.createEffectConfig(t),p=d||{};r=new j(s,p,o,T,y),Array.isArray(e.effects)&&e.effects.forEach(g=>{r&&r.add(g);}),r.start(),n.state$=r.state$,a$1.push(()=>{r&&r.stop();});}catch{}return n}export{l as a};
@@ -0,0 +1 @@
1
+ var e=class{constructor(t,a=false){this.value=t;this.isRawKey=a;}toString(){return this.value}toJSON(){return this.value}valueOf(){return this.value}isUnparseable(){return this.isRawKey}};export{e as a};