@asaidimu/utils-persistence 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/index.d.mts +82 -0
- package/index.d.ts +82 -0
- package/index.js +1 -0
- package/index.mjs +1 -0
- package/package.json +4 -4
package/LICENSE.md
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 Saidimu
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
|
+
SOFTWARE.
|
package/index.d.mts
ADDED
@@ -0,0 +1,82 @@
|
|
1
|
+
import { S as SimplePersistence } from '../types-dsQOAvmQ.js';
|
2
|
+
export { a as StorageEvents, b as author } from '../types-dsQOAvmQ.js';
|
3
|
+
|
4
|
+
/**
|
5
|
+
* Implements SimplePersistence using web storage (localStorage or sessionStorage).
|
6
|
+
* Supports cross-tab synchronization via an event bus and native storage events when using localStorage.
|
7
|
+
*/
|
8
|
+
declare class WebStoragePersistence<T extends object> implements SimplePersistence<T> {
|
9
|
+
private readonly storageKey;
|
10
|
+
private readonly eventBus;
|
11
|
+
private readonly storage;
|
12
|
+
/**
|
13
|
+
* Initializes a new instance of WebStoragePersistence.
|
14
|
+
* @param storageKey The key under which data is stored in web storage (e.g., 'user-profile').
|
15
|
+
* @param session Optional flag; if true, uses sessionStorage instead of localStorage (default: false).
|
16
|
+
*/
|
17
|
+
constructor(storageKey: string, session?: boolean);
|
18
|
+
/**
|
19
|
+
* Initializes the event bus with configured settings.
|
20
|
+
* @returns Configured event bus instance.
|
21
|
+
*/
|
22
|
+
private initializeEventBus;
|
23
|
+
/**
|
24
|
+
* Sets up a listener for native storage events to synchronize across tabs (localStorage only).
|
25
|
+
*/
|
26
|
+
private setupStorageEventListener;
|
27
|
+
/**
|
28
|
+
* Persists the provided state to web storage and notifies subscribers.
|
29
|
+
* @param instanceId Unique identifier of the instance making the update.
|
30
|
+
* @param state The state to persist.
|
31
|
+
* @returns True if successful, false if an error occurs.
|
32
|
+
*/
|
33
|
+
set(instanceId: string, state: T): boolean;
|
34
|
+
/**
|
35
|
+
* Retrieves the current state from web storage.
|
36
|
+
* @returns The persisted state, or null if not found or invalid.
|
37
|
+
*/
|
38
|
+
get(): T | null;
|
39
|
+
/**
|
40
|
+
* Subscribes to updates in the persisted state, excluding the instance’s own changes.
|
41
|
+
* @param instanceId Unique identifier of the subscribing instance.
|
42
|
+
* @param onStateChange Callback to invoke with the updated state.
|
43
|
+
* @returns Function to unsubscribe from updates.
|
44
|
+
*/
|
45
|
+
subscribe(instanceId: string, onStateChange: (state: T) => void): () => void;
|
46
|
+
/**
|
47
|
+
* Removes the persisted state from web storage.
|
48
|
+
* @returns True if successful, false if an error occurs.
|
49
|
+
*/
|
50
|
+
clear(): boolean;
|
51
|
+
}
|
52
|
+
|
53
|
+
/**
|
54
|
+
* Configuration for database connections
|
55
|
+
*/
|
56
|
+
interface DatabaseConfig {
|
57
|
+
store: string;
|
58
|
+
database: string;
|
59
|
+
collection: string;
|
60
|
+
enableTelemetry?: boolean;
|
61
|
+
}
|
62
|
+
/**
|
63
|
+
* IndexedDB persistence adapter with configurable database support
|
64
|
+
*/
|
65
|
+
declare class IndexedDBPersistence<T> implements SimplePersistence<T> {
|
66
|
+
private collection;
|
67
|
+
private collectionPromise;
|
68
|
+
private config;
|
69
|
+
private eventBus;
|
70
|
+
constructor(config: DatabaseConfig);
|
71
|
+
private getCollection;
|
72
|
+
set(id: string, state: T): Promise<boolean>;
|
73
|
+
get(): Promise<T | null>;
|
74
|
+
subscribe(id: string, callback: (state: T) => void): () => void;
|
75
|
+
clear(): Promise<boolean>;
|
76
|
+
/**
|
77
|
+
* Close a specific database
|
78
|
+
*/
|
79
|
+
close(): Promise<void>;
|
80
|
+
}
|
81
|
+
|
82
|
+
export { IndexedDBPersistence, SimplePersistence, WebStoragePersistence };
|
package/index.d.ts
ADDED
@@ -0,0 +1,82 @@
|
|
1
|
+
import { S as SimplePersistence } from '../types-dsQOAvmQ.js';
|
2
|
+
export { a as StorageEvents, b as author } from '../types-dsQOAvmQ.js';
|
3
|
+
|
4
|
+
/**
|
5
|
+
* Implements SimplePersistence using web storage (localStorage or sessionStorage).
|
6
|
+
* Supports cross-tab synchronization via an event bus and native storage events when using localStorage.
|
7
|
+
*/
|
8
|
+
declare class WebStoragePersistence<T extends object> implements SimplePersistence<T> {
|
9
|
+
private readonly storageKey;
|
10
|
+
private readonly eventBus;
|
11
|
+
private readonly storage;
|
12
|
+
/**
|
13
|
+
* Initializes a new instance of WebStoragePersistence.
|
14
|
+
* @param storageKey The key under which data is stored in web storage (e.g., 'user-profile').
|
15
|
+
* @param session Optional flag; if true, uses sessionStorage instead of localStorage (default: false).
|
16
|
+
*/
|
17
|
+
constructor(storageKey: string, session?: boolean);
|
18
|
+
/**
|
19
|
+
* Initializes the event bus with configured settings.
|
20
|
+
* @returns Configured event bus instance.
|
21
|
+
*/
|
22
|
+
private initializeEventBus;
|
23
|
+
/**
|
24
|
+
* Sets up a listener for native storage events to synchronize across tabs (localStorage only).
|
25
|
+
*/
|
26
|
+
private setupStorageEventListener;
|
27
|
+
/**
|
28
|
+
* Persists the provided state to web storage and notifies subscribers.
|
29
|
+
* @param instanceId Unique identifier of the instance making the update.
|
30
|
+
* @param state The state to persist.
|
31
|
+
* @returns True if successful, false if an error occurs.
|
32
|
+
*/
|
33
|
+
set(instanceId: string, state: T): boolean;
|
34
|
+
/**
|
35
|
+
* Retrieves the current state from web storage.
|
36
|
+
* @returns The persisted state, or null if not found or invalid.
|
37
|
+
*/
|
38
|
+
get(): T | null;
|
39
|
+
/**
|
40
|
+
* Subscribes to updates in the persisted state, excluding the instance’s own changes.
|
41
|
+
* @param instanceId Unique identifier of the subscribing instance.
|
42
|
+
* @param onStateChange Callback to invoke with the updated state.
|
43
|
+
* @returns Function to unsubscribe from updates.
|
44
|
+
*/
|
45
|
+
subscribe(instanceId: string, onStateChange: (state: T) => void): () => void;
|
46
|
+
/**
|
47
|
+
* Removes the persisted state from web storage.
|
48
|
+
* @returns True if successful, false if an error occurs.
|
49
|
+
*/
|
50
|
+
clear(): boolean;
|
51
|
+
}
|
52
|
+
|
53
|
+
/**
|
54
|
+
* Configuration for database connections
|
55
|
+
*/
|
56
|
+
interface DatabaseConfig {
|
57
|
+
store: string;
|
58
|
+
database: string;
|
59
|
+
collection: string;
|
60
|
+
enableTelemetry?: boolean;
|
61
|
+
}
|
62
|
+
/**
|
63
|
+
* IndexedDB persistence adapter with configurable database support
|
64
|
+
*/
|
65
|
+
declare class IndexedDBPersistence<T> implements SimplePersistence<T> {
|
66
|
+
private collection;
|
67
|
+
private collectionPromise;
|
68
|
+
private config;
|
69
|
+
private eventBus;
|
70
|
+
constructor(config: DatabaseConfig);
|
71
|
+
private getCollection;
|
72
|
+
set(id: string, state: T): Promise<boolean>;
|
73
|
+
get(): Promise<T | null>;
|
74
|
+
subscribe(id: string, callback: (state: T) => void): () => void;
|
75
|
+
clear(): Promise<boolean>;
|
76
|
+
/**
|
77
|
+
* Close a specific database
|
78
|
+
*/
|
79
|
+
close(): Promise<void>;
|
80
|
+
}
|
81
|
+
|
82
|
+
export { IndexedDBPersistence, SimplePersistence, WebStoragePersistence };
|
package/index.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
"use strict";var e=Object.create,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,s=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)((function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})),i=(e,t)=>function(){return t||(0,e[n(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(s,i,c)=>(c=null!=s?e(o(s)):{},((e,o,s,i)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of n(o))a.call(e,c)||c===s||t(e,c,{get:()=>o[c],enumerable:!(i=r(o,c))||i.enumerable});return e})(s&&s.__esModule?c:t(c,"default",{value:s,enumerable:!0}),s)),l=i({"node_modules/@asaidimu/events/index.js"(e,t){var r,n=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(i,{createEventBus:()=>c}),t.exports=(r=i,((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))s.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(i=o(t,c))||i.enumerable});return e})(n({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],n=0,o=0;const a=new Map,s=new Map;let i=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?i=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{n++,o+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const n=performance.now();try{(s.get(t)||[]).forEach((e=>e(r)))}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-n)}))},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?s.set(e,Array.from(r)):s.delete(e)};return i&&(i.onmessage=e=>{const{name:t,payload:r}=e.data;(s.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const n=t.get(e);return n.add(r),d(e),()=>{n.delete(r),0===n.size?(t.delete(e),s.delete(e)):d(e)}},emit:({name:t,payload:n})=>{if(e.async)return r.push({name:t,payload:n}),r.length>=e.batchSize?l():u(),void(i&&i.postMessage({name:t,payload:n}));const o=performance.now();try{(s.get(t)||[]).forEach((e=>e(n))),i&&i.postMessage({name:t,payload:n})}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-o)},getMetrics:()=>({totalEvents:n,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:n>0?o/n:0}),clear:()=>{t.clear(),s.clear(),r=[],n=0,o=0,a.clear(),i&&(i.close(),i=null)}}}}}),u=i({"node_modules/@asaidimu/query/index.js"(e,t){var r,n=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(i,{QueryBuilder:()=>c,createJoiner:()=>h,createMatcher:()=>u,createPaginator:()=>j,createProjector:()=>D,createSorter:()=>E}),t.exports=(r=i,((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))!s.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(i=o(t,c))||i.enumerable});return e})(n({},"__esModule",{value:!0}),r));var c=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:"offset",offset:e,limit:t},this}cursor(e,t,r){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:r},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"computed",expression:e,alias:t}),this}case(e,t,r){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"case",conditions:e,else:t,alias:r}),this}join(e,t,r){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:r,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function l(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?n(t,e):function(e){return"computed"===e?.type}(t)?n(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let r of t.conditions)if(o(e,r.when))return r.then;return t.else}(e,t):t}let r=new Map([["and",(e,t)=>t.every((t=>o(e,t)))],["or",(e,t)=>t.some((t=>o(e,t)))],["not",(e,t)=>!t.every((t=>o(e,t)))],["nor",(e,t)=>!t.some((t=>o(e,t)))],["xor",(e,t)=>1===t.filter((t=>o(e,t))).length]]);function n(r,n){let o=r.arguments.map((e=>t(n,e)));if(e[r.function])return e[r.function](...o);throw new Error(`Function ${r.function} not found!`)}function o(n,o){if(function(e){return!!e&&void 0!==e.conditions}(o))return function(e,t){let{operator:n,conditions:o}=t,a=r.get(n);if(a)return a(e,o);throw new Error(`Unsupported logical operator: ${n}`)}(n,o);if(!o||!o.field)return!1;let{field:a,operator:s,value:i}=o,c=n[a],l=t(n,i),u=new Map([["eq",(e,t)=>e===t],["neq",(e,t)=>e!==t],["lt",(e,t)=>e<t],["lte",(e,t)=>e<=t],["gt",(e,t)=>e>t],["gte",(e,t)=>e>=t],["in",(e,t)=>Array.isArray(t)&&t.includes(e)],["nin",(e,t)=>Array.isArray(t)&&!t.includes(e)],["contains",(e,t)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(i)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[s]||u.get(s);if(d)return d(c,l);throw new Error(`Unsupported comparison operator: ${s}`)}return{resolve:t,evaluate:o}}function u(e){let{evaluate:t}=l(e),r=new WeakMap;function n(e,n){let o=r.get(e);o||(o=new Map,r.set(e,o));let a=JSON.stringify(n);if(o.has(a))return o.get(a);let s=t(e,n);return o.set(a,s),s}return{matcher:n,match:n}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},y=e=>e&&"field"in e&&"operator"in e&&"value"in e,f=(e,t)=>{if(e){if(y(e)&&e){let r=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:r}}if((e=>"operator"in e&&"conditions"in e)(e)){let r={...e};return e.conditions&&(r.conditions=e.conditions.map((e=>f(e,t)))),r}return e}},p=async(e,t,r,n)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let o,a=e[r.relation];return r.query?.filters&&y(r.query.filters)&&(o=((e,t)=>{let r=new Map;return e.forEach((e=>{let n=e[t];r.has(n)||r.set(n,[]),r.get(n).push(e)})),r})(a,r.query.filters.field)),(await Promise.all(t.map((async e=>{let t,s=((e,t)=>{if(!e)return{};let r=f(e.filters,t);return{...e,filters:r}})(r.query,e);return t=s.filters&&y(s.filters)&&o?.has(s.filters.value)?o.get(s.filters.value)||[]:a.filter((e=>n.matcher(e,s.filters))),((e,t,r)=>{let n=r.alias||r.relation;return[{...e,[n]:t}]})(e,await[e=>s.sort?n.sorter(e,s.sort):e,e=>s.projection?n.projector(e,s.projection):e,async e=>s.pagination?await n.paginator(e,s.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),r)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},m=async(e,t,r,n)=>r.reduce((async(t,r)=>p(e,await t,r,n)),Promise.resolve(t));function h(){return{join:m}}var w=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},g=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,r){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===r?-1:1:"asc"===r?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===r?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===r?e-t:t-e;throw new w(e,t)}function v(e,t){let r=Array.from(e);return 0===t.length?r:r.sort(((e,r)=>{for(let n of t){let{field:t,direction:o}=n,a=e[t],s=r[t];try{if("asc"!==o&&"desc"!==o)throw new g(o);let e=b(a,s,o);if(0!==e)return e}catch(e){throw e instanceof w||e instanceof g?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function E(){return{sort:v}}function D(e){let{resolve:t}=l(e);function r(e,n){let o={};return n.include?.length&&function(e,t,n){for(let o of t)if("string"!=typeof o){for(let[t,a]of Object.entries(o))if(Object.prototype.hasOwnProperty.call(e,t)){let o=r(e[t],a);n[t]=o}}else{let t=o;n[t]=e[t]}}(e,n.include,o),n.exclude?.length&&function(e,t,n){0===Object.keys(n).length&&Object.assign(n,e);for(let e of t)if("string"!=typeof e)for(let[t,o]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(n,t))continue;let e=n[t];e&&"object"==typeof e?n[t]=r(e,o):delete n[t]}else delete n[e]}(e,n.exclude,o),n.computed?.length&&function(e,r,n){for(let o of r)n[o.alias]=t(e,o)}(e,n.computed,o),o}return{project:r}}async function*O(e,t,r=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:r,limit:n}=t,o=0,a=n,s=[];for await(let t of e)a<=0&&(yield s,s=[],a=n),o<r?o++:(s.push(t),a--);s.length>0&&(yield s)}(e,t):yield*async function*(e,t,r){let{cursor:n,limit:o,direction:a}=t,s=o,i=void 0===n,c=[];if("forward"===a)for await(let t of e)s<=0&&(yield c,c=[],s=o),i?(c.push(t),s--):i=r(t)===n;else{let t=[];for await(let r of e)t.push(r);for(let e=t.length-1;e>=0;e--){let a=t[e];i?(c.push(a),s--,s<=0&&(yield c,c=[],s=o)):i=r(a)===n}}c.length>0&&(yield c)}(e,t,r)}function j(){return{paginate:O}}}}),d=i({"node_modules/@asaidimu/indexed/index.js"(e,t){var r,n=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,c={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(c,{DatabaseConnection:()=>D,DatabaseError:()=>E,DatabaseErrorType:()=>v}),t.exports=(r=c,((e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))i.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(s=o(t,c))||s.enumerable});return e})(n({},"__esModule",{value:!0}),r));var d=l(),y=u();var f=class extends Error{constructor(e,t){super(e),this.cause=t,this.name="StoreError",t&&t.stack&&(this.stack=`${this.stack}\nCaused by: ${t.stack}`)}},p=async(e,{name:t,keyPath:r="$id"},n)=>{if(!t||"string"!=typeof t)throw new f("Invalid store name");if(!r||"string"!=typeof r)throw new f("Invalid store key path");const o=new Set(Array.from((await e()).transaction([t]).objectStore(t).indexNames)),a=async(r,n,a)=>{const{store:s}=await(r=>new Promise((async(n,o)=>{const a=(await e()).transaction([t],r),s=a.objectStore(t);a.onerror=()=>{o(new f(`Transaction failed: ${a.error?.message||"Unknown error"}`,a.error))},n({transaction:a,store:s})})))(r),i=((e,r)=>{if(!r)return e;if(!o.has(r))throw new f(`Index '${r}' does not exist in store '${t}'`);return e.index(r)})(s,a?.indexName),c=n(s,i);if(a?.cursorCallback){return((e,t)=>new Promise(((r,n)=>{let o=null;e.onsuccess=async e=>{const a=e.target.result;if(a)try{const{value:e,done:n,offset:s}=await t(a.value,a.key,a);if(o=e,s&&s<=0)throw new f("Offset must be positive");if(n)return void r(e);s&&s>0?a.advance(s):a.continue()}catch(e){n(e instanceof Error?e:new f("Cursor callback failed",e))}else r(o)},e.onerror=()=>{n(new f(`Cursor request failed: ${e.error?.message||"Unknown error"}`,e.error))}})))(c,a.cursorCallback)}const l=c;return"single"===l.type?(u=l.request,new Promise(((e,t)=>{u.onsuccess=()=>e(u.result),u.onerror=()=>{t(new f(`Operation failed: ${u.error?.message||"Unknown error"}`,u.error))}}))):(e=>{const t=e.map((e=>new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>{r(new f(`Request failed: ${e.error?.message||"Unknown error"}`,e.error))}}))));return Promise.all(t)})(l.requests);var u};return{add:async e=>{const t=Array.isArray(e)?e:[e];t.forEach((e=>{if(!e[r])throw new f(`Record must have a ${r} property`)}));const n=await a("readwrite",(e=>({type:"multiple",requests:t.map((t=>e.add(t)))})));return Array.isArray(e)?n:n[0]},clear:()=>a("readwrite",(e=>({type:"single",request:e.clear()}))),count:()=>a("readonly",(e=>({type:"single",request:e.count()}))),delete:async e=>{const t=Array.isArray(e)?e:[e];if(t.some((e=>void 0===e)))throw new f("ID cannot be undefined");return a("readwrite",(e=>({type:"multiple",requests:t.map((t=>e.delete(t)))})))},getById:e=>{if(void 0===e)throw new f("ID cannot be undefined");return a("readonly",(t=>({type:"single",request:t.get(e)})))},getByIndex:(e,t)=>{if(void 0===t)throw new f("Key cannot be undefined for index query");return a("readonly",((e,r)=>({type:"single",request:r.get(t)})),{indexName:e})},getByKeyRange:(e,t)=>a("readonly",((e,r)=>({type:"single",request:r.getAll(t)})),{indexName:e}),getAll:()=>a("readonly",(e=>({type:"single",request:e.getAll()}))),put:e=>{if(!e[r])throw new f(`Record must have a ${r} property`);return a("readwrite",(t=>({type:"single",request:t.put(e)})))},cursor:(e,t="forward")=>{const r="forward"===t?"next":"prev";return a("readwrite",(e=>e.openCursor(void 0,r)),{cursorCallback:e,cursorDirection:r})},batch:async e=>{if(!e.length)throw new f("Batch operations array cannot be empty");return a("readwrite",(t=>{const n=[];for(const o of e)if("add"===o.type||"put"===o.type){(Array.isArray(o.data)?o.data:[o.data]).forEach((e=>{if(!e[r])throw new f(`Record must have a ${r} property`);n.push(t[o.type](e))}))}else if("delete"===o.type){const e=Array.isArray(o.data)?o.data:[o.data];if(e.some((e=>void 0===e)))throw new f("ID cannot be undefined");e.forEach((e=>n.push(t.delete(e))))}return{type:"multiple",requests:n}}))}}};function m(e,t,r){return new Proxy(e,{get(e,n){const o=e[n];return"function"==typeof o?async function(...a){const s=Date.now();let i,c=null;try{return i=await o.apply(e,a),i}catch(e){throw c=e,e}finally{r.emit({name:"telemetry",payload:{type:"telemetry",method:n.toString(),timestamp:Date.now(),metadata:{args:a,performance:{durationMs:Date.now()-s},source:t,context:{userAgent:globalThis.navigator?.userAgent},result:c?void 0:{type:Array.isArray(i)?"array":typeof i,size:Array.isArray(i)?i.length:void 0},error:c?{message:c.message,name:c.name,stack:c.stack}:null}}})}}:o}})}var h=s("uuid"),{matcher:w}=(0,y.createMatcher)({});async function g({connection:e,collection:t,initial:r,enableTelemetry:n=!1,bus:o}){const a=await p(e,{name:t}),s={current:structuredClone(r)};if(void 0===s.current.$id){const e=Object.assign(s.current,{$id:(0,h.v4)(),$created:(new Date).toJSON(),$version:1});await a.put(e),s.current=e,o.emit({name:"document:create",payload:{type:"document:create",data:s.current,timestamp:Date.now()}})}const i={save:async e=>{const{$id:t}=s.current;if(!t)throw new Error("Document ID is missing.");return s.current.$version=(s.current.$version||0)+1,s.current.$updated=(new Date).toJSON(),await a.put(s.current),e||o.emit({name:"document:write",payload:{type:"document:write",data:s.current,timestamp:Date.now()}}),!0},update:async e=>{s.current=Object.assign(s.current,e);const t=await i.save(!0);return t&&o.emit({name:"document:update",payload:{type:"document:update",data:s.current,timestamp:Date.now()}}),t},delete:async()=>{const{$id:e}=s.current;if(!e)throw new Error("Document ID is missing.");return await a.delete(e),o.emit({name:"document:delete",payload:{type:"document:delete",data:s.current,timestamp:Date.now()}}),!0},read:async()=>{const e=s.current.$id;if(!e)throw new Error("Document ID is missing.");const t=await a.getById(e);if(!t)throw new Error("Document not found.");return s.current=structuredClone(t),o.emit({name:"document:read",payload:{type:"document:read",data:s.current,timestamp:Date.now()}}),!0},subscribe:o.subscribe},c=n?m(i,{level:"document",collection:t,document:s.current.$id},o):i;return o.emit({name:"document:read",payload:{type:"document:read",data:s.current,timestamp:Date.now()}}),new Proxy({},{get:(e,t)=>["update","delete","subscribe","read"].includes(t)?c[t]:Reflect.get(s.current,t)})}async function b({connection:e,collection:t,enableTelemetry:r=!1,bus:n}){const o=await p(e,{name:t}),a={create:async o=>{const a=await g({connection:e,collection:t,initial:o,enableTelemetry:r,bus:n});return n.emit({name:"collection:read",payload:{type:"collection:read",model:t,timestamp:Date.now()}}),a},find:async a=>{const s=await o.cursor((async e=>e&&w(e,a)?{value:e,done:!0}:{value:null,done:!1}));if(s){const o=await g({connection:e,collection:t,initial:s,enableTelemetry:r,bus:n});return n.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:t,timestamp:Date.now()}}),o}return null},list:async a=>{const s={total:await o.count(),offset:"offset"===a.type?a.offset:0,limit:a.limit,cursor:"cursor"===a.type?a.cursor:void 0,direction:"cursor"===a.type?a.direction:"forward",count:0};return{async next(){const i="offset"===a.type?await async function(e,t){const{offset:r,limit:n}=t,o=[];let a=0,s=!1;for(;!(s||(await e((async e=>a<r?(a++,{value:e,done:!1,offset:1}):(o.push(e),a++,a>=r+n?(s=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),o.length>=n)););return o}(o.cursor,{...a,offset:s.offset}):await async function(e,t){const{limit:r,direction:n}=t,o=[];let a=!1;for(;!a;)await e((async e=>(o.push(e),o.length>=r?(a=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),n);return o}(o.cursor,{...a});s.offset+=s.limit,s.count+=i.length;const c=await Promise.all(i.map((o=>g({collection:t,connection:e,initial:o,enableTelemetry:r,bus:n}))));return n.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:t,timestamp:Date.now()}}),{value:c,done:s.count===s.total}}}},filter:async a=>{const s=[];return await o.cursor((async o=>(o&&w(o,a)&&s.push(await g({connection:e,collection:t,initial:o,enableTelemetry:r,bus:n})),{value:null,done:!1}))),n.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:t,timestamp:Date.now()}}),s},subscribe:n.subscribe};return r?m(a,{level:"collection",collection:t},n):a}var v=(e=>(e.SCHEMA_NOT_FOUND="SCHEMA_NOT_FOUND",e.SCHEMA_ALREADY_EXISTS="SCHEMA_ALREADY_EXISTS",e.INVALID_SCHEMA_NAME="INVALID_SCHEMA_NAME",e.INVALID_SCHEMA_DEFINITION="INVALID_SCHEMA_DEFINITION",e.SUBSCRIPTION_FAILED="SUBSCRIPTION_FAILED",e.INTERNAL_ERROR="INTERNAL_ERROR",e))(v||{}),E=class extends Error{type;schema;constructor(e,t,r){super(t),this.type=e,this.schema=r}};async function D(e){const t=(0,d.createEventBus)(),r=e.indexSchema||"$schema",n=e.keyPath||"$id",o=new Map;if(o.has(e.name))return o.get(e.name);let a=null;async function s(){return a||(a=await new Promise(((t,o)=>{const a=indexedDB.open(e.name);a.onerror=()=>o(new Error(`Failed to open database: ${a.error}`)),a.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(r)||t.createObjectStore(r,{keyPath:n})},a.onsuccess=()=>t(a.result)}))),a}const i={collection:async function(r){if(!(await s()).objectStoreNames.contains(r))throw new E("SCHEMA_NOT_FOUND",`Collection with name ${r} does not exist`);return t.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:r},timestamp:Date.now()}}),b({connection:s,collection:r,bus:t,enableTelemetry:e.enableTelemetry})},createCollection:async function(n){const o=await s();if(o.objectStoreNames.contains(n.name))throw new E("SCHEMA_ALREADY_EXISTS",`Collection with name ${n.name} exists`);const i=structuredClone(o.version);o.close(),a=await new Promise(((t,r)=>{const o=indexedDB.open(e.name,i+1);o.onerror=()=>r(new Error(`Failed to open database: ${o.error}`)),o.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(n.name)||t.createObjectStore(n.name,{keyPath:"$id"})},o.onsuccess=()=>t(o.result)}));const c=await b({connection:s,collection:r,bus:t,enableTelemetry:e.enableTelemetry});return await c.create(n),t.emit({name:"collection:create",payload:{type:"collection:create",schema:n,timestamp:Date.now()}}),c},deleteCollection:async function(n){const o=await s();if(!o.objectStoreNames.contains(n))throw new E("SCHEMA_NOT_FOUND",`Collection with name ${n} does not exist`);const i=structuredClone(o.version);o.close(),a=await new Promise(((t,r)=>{const o=indexedDB.open(e.name,i+1);o.onerror=()=>r(new Error(`Failed to open database: ${o.error}`)),o.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(n)&&t.deleteObjectStore(n)},o.onsuccess=()=>t(o.result)}));const c=await b({connection:s,collection:r,bus:t,enableTelemetry:e.enableTelemetry}),l=await c.find({field:"name",operator:"eq",value:n});try{await(l?.delete())}catch(e){throw new E("INTERNAL_ERROR",e.message)}return t.emit({name:"collection:delete",payload:{type:"collection:delete",schema:l,timestamp:Date.now()}}),!0},updateCollection:async function(n){if(!(await s()).objectStoreNames.contains(n.name))throw new E("SCHEMA_NOT_FOUND",`Collection with name ${n.name} does not exist`);const o=await b({connection:s,collection:r,enableTelemetry:e.enableTelemetry,bus:t}),a=await o.find({field:"name",operator:"eq",value:n.name});return!!a&&(await a.update(n),t.emit({name:"collection:update",payload:{type:"collection:update",schema:n,timestamp:Date.now()}}),!0)},subscribe:t.subscribe,close:()=>{a&&a.close()}},c=e.enableTelemetry?m(i,{level:"database"},t):i;return o.set(e.name,c),c}}}),y=c(l()),f=c(l()),p=c(d()),m=c(u()),h=class e{static dbInstances=new Map;static collectionInstances=new Map;static eventBusMap=new Map;static defaultModelName="stores";static getDatabase(t){const{database:r,enableTelemetry:n=!1,collection:o=e.defaultModelName}=t;if(!e.dbInstances.has(r)){const t=(0,p.DatabaseConnection)({name:r,enableTelemetry:n}).then((async e=>{try{await e.createCollection({name:o,version:"1.0.0",nestedSchemas:{},fields:{store:{name:"store",type:"string",required:!0},data:{name:"data",type:"object",required:!0}}})}catch(e){if(e instanceof p.DatabaseError&&"SCHEMA_ALREADY_EXISTS"!==e.type)throw e}return e}));e.dbInstances.set(r,t)}return e.dbInstances.get(r)}static getEventBus(t,r){const n=`${t}_store_${r}`;return e.eventBusMap.has(n)||e.eventBusMap.set(n,(0,f.createEventBus)({batchSize:5,async:!0,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${t}:${r}:`,e),crossTab:!0,channelName:n})),e.eventBusMap.get(n)}static getCollection(t){const{database:r,collection:n=e.defaultModelName}=t,o=`${r}:${n}`;if(!e.collectionInstances.has(o)){const r=e.getDatabase(t).then((e=>e.collection(n)));e.collectionInstances.set(o,r)}return e.collectionInstances.get(o)}static async closeDatabase(t){const r=e.dbInstances.get(t);if(r){(await r).close(),e.dbInstances.delete(t);const n=[];e.collectionInstances.forEach(((e,r)=>{r.startsWith(`${t}:`)&&n.push(r)})),n.forEach((t=>e.collectionInstances.delete(t)));const o=[];e.eventBusMap.forEach(((e,r)=>{r.startsWith(`${t}_store_`)&&(e.clear(),o.push(r))})),o.forEach((t=>e.eventBusMap.delete(t)))}}static async closeAll(){const t=Array.from(e.dbInstances.keys()).map((t=>e.closeDatabase(t)));await Promise.all(t)}static getActiveDatabases(){return Array.from(e.dbInstances.keys())}};exports.IndexedDBPersistence=class{collection=null;collectionPromise;config;eventBus;constructor(e){this.config=e,this.collectionPromise=h.getCollection(this.config),this.collectionPromise.then((e=>{this.collection=e})).catch((e=>{console.error(`Failed to initialize collection for store ${this.config.store}:`,e)})),this.eventBus=h.getEventBus(this.config.database,this.config.store)}async getCollection(){return this.collection?this.collection:this.collectionPromise}async set(e,t){try{const r=await this.getCollection(),n=(new m.QueryBuilder).where({field:"store",operator:"eq",value:this.config.store}).build(),o=await r.find(n.filters),a={store:this.config.store,data:t};let s;return o?s=await o.update(a):(await r.create(a),s=!0),s&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.store,instanceId:e,state:t}}),s}catch(t){return console.error(`Failed to set state for store ${this.config.store} in database ${this.config.database} by instance ${e}:`,t),!1}}async get(){try{const e=await this.getCollection(),t=(new m.QueryBuilder).where({field:"store",operator:"eq",value:this.config.store}).build(),r=await e.find(t.filters);return r?r.read().then((()=>r.data)):null}catch(e){return console.error(`Failed to get state for store ${this.config.store} in database ${this.config.database}:`,e),null}}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:n,state:o})=>{r===this.config.store&&n!==e&&t(o)}))}async clear(){try{const e=await this.collectionPromise,t=(new m.QueryBuilder).where({field:"store",operator:"eq",value:this.config.store}).build(),r=await e.find(t.filters);return!r||await r.delete()}catch(e){return console.error(`Failed to clear state for store ${this.config.store} in database ${this.config.database}:`,e),!1}}async close(){await h.closeDatabase(this.config.database)}},exports.WebStoragePersistence=class{storageKey;eventBus;storage;constructor(e,t=!1){this.storageKey=e,this.storage=t?sessionStorage:localStorage,this.eventBus=this.initializeEventBus(),t||this.setupStorageEventListener()}initializeEventBus(){const e={async:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${this.storageKey}:`,e),crossTab:!0,channelName:`storage_${this.storageKey}`};return(0,y.createEventBus)(e)}setupStorageEventListener(){window.addEventListener("storage",(e=>{if(e.key===this.storageKey&&e.newValue)try{const t=JSON.parse(e.newValue);this.eventBus.emit({name:"store:updated",payload:{storageKey:this.storageKey,instanceId:"external",state:t}})}catch(e){console.error("Failed to parse storage event data:",e)}}))}set(e,t){try{const r=JSON.stringify(t);return this.storage.setItem(this.storageKey,r),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.storageKey,instanceId:e,state:t}}),!0}catch(e){return console.error(`Failed to persist state to web storage for ${this.storageKey}:`,e),!1}}get(){try{const e=this.storage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return console.error(`Failed to retrieve state from web storage for ${this.storageKey}:`,e),null}}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:n,state:o})=>{r===this.storageKey&&n!==e&&t(o)}))}clear(){try{return this.storage.removeItem(this.storageKey),!0}catch(e){return console.error(`Failed to clear persisted state for ${this.storageKey}:`,e),!1}}},exports.author="https://github.com/asaidimu";
|
package/index.mjs
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,s=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)((function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})),i=(e,t)=>function(){return t||(0,e[n(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(s,i,c)=>(c=null!=s?e(o(s)):{},((e,o,s,i)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of n(o))a.call(e,c)||c===s||t(e,c,{get:()=>o[c],enumerable:!(i=r(o,c))||i.enumerable});return e})(s&&s.__esModule?c:t(c,"default",{value:s,enumerable:!0}),s)),l=i({"node_modules/@asaidimu/events/index.js"(e,t){var r,n=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(i,{createEventBus:()=>c}),t.exports=(r=i,((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))s.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(i=o(t,c))||i.enumerable});return e})(n({},"__esModule",{value:!0}),r));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let r=[],n=0,o=0;const a=new Map,s=new Map;let i=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?i=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{n++,o+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=r;r=[],t.forEach((({name:t,payload:r})=>{const n=performance.now();try{(s.get(t)||[]).forEach((e=>e(r)))}catch(n){e.errorHandler({...n,eventName:t,payload:r})}c(t,performance.now()-n)}))},u=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),d=e=>{const r=t.get(e);r?s.set(e,Array.from(r)):s.delete(e)};return i&&(i.onmessage=e=>{const{name:t,payload:r}=e.data;(s.get(t)||[]).forEach((e=>e(r)))}),{subscribe:(e,r)=>{t.has(e)||t.set(e,new Set);const n=t.get(e);return n.add(r),d(e),()=>{n.delete(r),0===n.size?(t.delete(e),s.delete(e)):d(e)}},emit:({name:t,payload:n})=>{if(e.async)return r.push({name:t,payload:n}),r.length>=e.batchSize?l():u(),void(i&&i.postMessage({name:t,payload:n}));const o=performance.now();try{(s.get(t)||[]).forEach((e=>e(n))),i&&i.postMessage({name:t,payload:n})}catch(r){e.errorHandler({...r,eventName:t,payload:n})}c(t,performance.now()-o)},getMetrics:()=>({totalEvents:n,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:n>0?o/n:0}),clear:()=>{t.clear(),s.clear(),r=[],n=0,o=0,a.clear(),i&&(i.close(),i=null)}}}}}),u=i({"node_modules/@asaidimu/query/index.js"(e,t){var r,n=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(i,{QueryBuilder:()=>c,createJoiner:()=>h,createMatcher:()=>u,createPaginator:()=>j,createProjector:()=>O,createSorter:()=>E}),t.exports=(r=i,((e,t,r,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))!s.call(e,c)&&c!==r&&n(e,c,{get:()=>t[c],enumerable:!(i=o(t,c))||i.enumerable});return e})(n({},"__esModule",{value:!0}),r));var c=class{query;constructor(){this.query={}}where(e){return this.query.filters=e,this}orderBy(e,t){return this.query.sort||(this.query.sort=[]),this.query.sort.push({field:e,direction:t}),this}offset(e,t){return this.query.pagination={type:"offset",offset:e,limit:t},this}cursor(e,t,r){return this.query.pagination={type:"cursor",cursor:e,limit:t,direction:r},this}include(e){return this.query.projection||(this.query.projection={}),this.query.projection.include=e,this}exclude(e){return this.query.projection||(this.query.projection={}),this.query.projection.exclude=e,this}computed(e,t){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"computed",expression:e,alias:t}),this}case(e,t,r){return this.query.projection||(this.query.projection={}),this.query.projection.computed||(this.query.projection.computed=[]),this.query.projection.computed.push({type:"case",conditions:e,else:t,alias:r}),this}join(e,t,r){return this.query.joins||(this.query.joins=[]),this.query.joins.push({relation:e,alias:r,query:t}),this}aggregate(e,t){return this.query.aggregations={groupBy:e,metrics:t},this}window(e){return this.query.window||(this.query.window=[]),this.query.window.push(e),this}hint(e){return this.query.hints||(this.query.hints=[]),this.query.hints.push(e),this}build(){return this.query}};function l(e){function t(e,t){return function(e){return"field"===e?.type}(t)?e[t.field]:function(e){return"value"===e?.type}(t)?t.value:function(e){return"function"===e?.type}(t)?n(t,e):function(e){return"computed"===e?.type}(t)?n(t.expression,e):function(e){return"case"===e?.type}(t)?function(e,t){for(let r of t.conditions)if(o(e,r.when))return r.then;return t.else}(e,t):t}let r=new Map([["and",(e,t)=>t.every((t=>o(e,t)))],["or",(e,t)=>t.some((t=>o(e,t)))],["not",(e,t)=>!t.every((t=>o(e,t)))],["nor",(e,t)=>!t.some((t=>o(e,t)))],["xor",(e,t)=>1===t.filter((t=>o(e,t))).length]]);function n(r,n){let o=r.arguments.map((e=>t(n,e)));if(e[r.function])return e[r.function](...o);throw new Error(`Function ${r.function} not found!`)}function o(n,o){if(function(e){return!!e&&void 0!==e.conditions}(o))return function(e,t){let{operator:n,conditions:o}=t,a=r.get(n);if(a)return a(e,o);throw new Error(`Unsupported logical operator: ${n}`)}(n,o);if(!o||!o.field)return!1;let{field:a,operator:s,value:i}=o,c=n[a],l=t(n,i),u=new Map([["eq",(e,t)=>e===t],["neq",(e,t)=>e!==t],["lt",(e,t)=>e<t],["lte",(e,t)=>e<=t],["gt",(e,t)=>e>t],["gte",(e,t)=>e>=t],["in",(e,t)=>Array.isArray(t)&&t.includes(e)],["nin",(e,t)=>Array.isArray(t)&&!t.includes(e)],["contains",(e,t)=>"string"==typeof e?e.includes(t):!!Array.isArray(e)&&e.includes(i)],["ncontains",(e,t)=>"string"==typeof e&&!e.includes(t)],["startswith",(e,t)=>"string"==typeof e&&e.startsWith(t)],["endswith",(e,t)=>"string"==typeof e&&e.endsWith(t)],["exists",e=>null!=e],["nexists",e=>null==e]]),d=e[s]||u.get(s);if(d)return d(c,l);throw new Error(`Unsupported comparison operator: ${s}`)}return{resolve:t,evaluate:o}}function u(e){let{evaluate:t}=l(e),r=new WeakMap;function n(e,n){let o=r.get(e);o||(o=new Map,r.set(e,o));let a=JSON.stringify(n);if(o.has(a))return o.get(a);let s=t(e,n);return o.set(a,s),s}return{matcher:n,match:n}}var d=class extends Error{constructor(e,t){super(e),this.code=t,this.name="JoinError"}},y=e=>e&&"field"in e&&"operator"in e&&"value"in e,f=(e,t)=>{if(e){if(y(e)&&e){let r=(e=>"object"==typeof e&&null!==e&&"type"in e&&"field"===e.type)(e.value)?((e,t)=>t.split(".").reduce(((e,t)=>e?.[t]),e))(t,e.value.field):e.value;return{...e,value:r}}if((e=>"operator"in e&&"conditions"in e)(e)){let r={...e};return e.conditions&&(r.conditions=e.conditions.map((e=>f(e,t)))),r}return e}},p=async(e,t,r,n)=>{try{if(((e,t)=>{if(!e.relation)throw new d("Join configuration must specify a relation","INVALID_CONFIG");if(!t[e.relation])throw new d(`Collection "${e.relation}" not found in database`,"COLLECTION_NOT_FOUND");if(e.alias&&"string"!=typeof e.alias)throw new d("Join alias must be a string","INVALID_ALIAS")})(r,e),!Array.isArray(t))throw new d("Source data must be an array","INVALID_SOURCE_DATA");let o,a=e[r.relation];return r.query?.filters&&y(r.query.filters)&&(o=((e,t)=>{let r=new Map;return e.forEach((e=>{let n=e[t];r.has(n)||r.set(n,[]),r.get(n).push(e)})),r})(a,r.query.filters.field)),(await Promise.all(t.map((async e=>{let t,s=((e,t)=>{if(!e)return{};let r=f(e.filters,t);return{...e,filters:r}})(r.query,e);return t=s.filters&&y(s.filters)&&o?.has(s.filters.value)?o.get(s.filters.value)||[]:a.filter((e=>n.matcher(e,s.filters))),((e,t,r)=>{let n=r.alias||r.relation;return[{...e,[n]:t}]})(e,await[e=>s.sort?n.sorter(e,s.sort):e,e=>s.projection?n.projector(e,s.projection):e,async e=>s.pagination?await n.paginator(e,s.pagination):e].reduce((async(e,t)=>t(await e)),Promise.resolve(t)),r)})))).flat()}catch(e){throw e instanceof d?e:new d(`Join operation failed: ${e.message}`,"JOIN_EXECUTION_ERROR")}},m=async(e,t,r,n)=>r.reduce((async(t,r)=>p(e,await t,r,n)),Promise.resolve(t));function h(){return{join:m}}var w=class extends Error{constructor(e,t){super(`Unsupported comparison between ${typeof e} and ${typeof t}`),this.name="UnsupportedComparisonError"}},g=class extends Error{constructor(e){super(`Unsupported sort direction: ${e}`),this.name="InvalidSortDirectionError"}};function b(e,t,r){if(e===t)return 0;if(null==e||null==t)return null==e?"asc"===r?-1:1:"asc"===r?1:-1;if("string"==typeof e&&"string"==typeof t)return"asc"===r?e.localeCompare(t):t.localeCompare(e);if("number"==typeof e&&"number"==typeof t)return"asc"===r?e-t:t-e;throw new w(e,t)}function v(e,t){let r=Array.from(e);return 0===t.length?r:r.sort(((e,r)=>{for(let n of t){let{field:t,direction:o}=n,a=e[t],s=r[t];try{if("asc"!==o&&"desc"!==o)throw new g(o);let e=b(a,s,o);if(0!==e)return e}catch(e){throw e instanceof w||e instanceof g?e:new Error(`Error comparing field '${t}': ${e.message}`)}}return 0}))}function E(){return{sort:v}}function O(e){let{resolve:t}=l(e);function r(e,n){let o={};return n.include?.length&&function(e,t,n){for(let o of t)if("string"!=typeof o){for(let[t,a]of Object.entries(o))if(Object.prototype.hasOwnProperty.call(e,t)){let o=r(e[t],a);n[t]=o}}else{let t=o;n[t]=e[t]}}(e,n.include,o),n.exclude?.length&&function(e,t,n){0===Object.keys(n).length&&Object.assign(n,e);for(let e of t)if("string"!=typeof e)for(let[t,o]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(n,t))continue;let e=n[t];e&&"object"==typeof e?n[t]=r(e,o):delete n[t]}else delete n[e]}(e,n.exclude,o),n.computed?.length&&function(e,r,n){for(let o of r)n[o.alias]=t(e,o)}(e,n.computed,o),o}return{project:r}}async function*D(e,t,r=e=>String(e)){"offset"===t.type?yield*async function*(e,t){let{offset:r,limit:n}=t,o=0,a=n,s=[];for await(let t of e)a<=0&&(yield s,s=[],a=n),o<r?o++:(s.push(t),a--);s.length>0&&(yield s)}(e,t):yield*async function*(e,t,r){let{cursor:n,limit:o,direction:a}=t,s=o,i=void 0===n,c=[];if("forward"===a)for await(let t of e)s<=0&&(yield c,c=[],s=o),i?(c.push(t),s--):i=r(t)===n;else{let t=[];for await(let r of e)t.push(r);for(let e=t.length-1;e>=0;e--){let a=t[e];i?(c.push(a),s--,s<=0&&(yield c,c=[],s=o)):i=r(a)===n}}c.length>0&&(yield c)}(e,t,r)}function j(){return{paginate:D}}}}),d=i({"node_modules/@asaidimu/indexed/index.js"(e,t){var r,n=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,c={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(c,{DatabaseConnection:()=>O,DatabaseError:()=>E,DatabaseErrorType:()=>v}),t.exports=(r=c,((e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))i.call(e,c)||c===r||n(e,c,{get:()=>t[c],enumerable:!(s=o(t,c))||s.enumerable});return e})(n({},"__esModule",{value:!0}),r));var d=l(),y=u();var f=class extends Error{constructor(e,t){super(e),this.cause=t,this.name="StoreError",t&&t.stack&&(this.stack=`${this.stack}\nCaused by: ${t.stack}`)}},p=async(e,{name:t,keyPath:r="$id"},n)=>{if(!t||"string"!=typeof t)throw new f("Invalid store name");if(!r||"string"!=typeof r)throw new f("Invalid store key path");const o=new Set(Array.from((await e()).transaction([t]).objectStore(t).indexNames)),a=async(r,n,a)=>{const{store:s}=await(r=>new Promise((async(n,o)=>{const a=(await e()).transaction([t],r),s=a.objectStore(t);a.onerror=()=>{o(new f(`Transaction failed: ${a.error?.message||"Unknown error"}`,a.error))},n({transaction:a,store:s})})))(r),i=((e,r)=>{if(!r)return e;if(!o.has(r))throw new f(`Index '${r}' does not exist in store '${t}'`);return e.index(r)})(s,a?.indexName),c=n(s,i);if(a?.cursorCallback){return((e,t)=>new Promise(((r,n)=>{let o=null;e.onsuccess=async e=>{const a=e.target.result;if(a)try{const{value:e,done:n,offset:s}=await t(a.value,a.key,a);if(o=e,s&&s<=0)throw new f("Offset must be positive");if(n)return void r(e);s&&s>0?a.advance(s):a.continue()}catch(e){n(e instanceof Error?e:new f("Cursor callback failed",e))}else r(o)},e.onerror=()=>{n(new f(`Cursor request failed: ${e.error?.message||"Unknown error"}`,e.error))}})))(c,a.cursorCallback)}const l=c;return"single"===l.type?(u=l.request,new Promise(((e,t)=>{u.onsuccess=()=>e(u.result),u.onerror=()=>{t(new f(`Operation failed: ${u.error?.message||"Unknown error"}`,u.error))}}))):(e=>{const t=e.map((e=>new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>{r(new f(`Request failed: ${e.error?.message||"Unknown error"}`,e.error))}}))));return Promise.all(t)})(l.requests);var u};return{add:async e=>{const t=Array.isArray(e)?e:[e];t.forEach((e=>{if(!e[r])throw new f(`Record must have a ${r} property`)}));const n=await a("readwrite",(e=>({type:"multiple",requests:t.map((t=>e.add(t)))})));return Array.isArray(e)?n:n[0]},clear:()=>a("readwrite",(e=>({type:"single",request:e.clear()}))),count:()=>a("readonly",(e=>({type:"single",request:e.count()}))),delete:async e=>{const t=Array.isArray(e)?e:[e];if(t.some((e=>void 0===e)))throw new f("ID cannot be undefined");return a("readwrite",(e=>({type:"multiple",requests:t.map((t=>e.delete(t)))})))},getById:e=>{if(void 0===e)throw new f("ID cannot be undefined");return a("readonly",(t=>({type:"single",request:t.get(e)})))},getByIndex:(e,t)=>{if(void 0===t)throw new f("Key cannot be undefined for index query");return a("readonly",((e,r)=>({type:"single",request:r.get(t)})),{indexName:e})},getByKeyRange:(e,t)=>a("readonly",((e,r)=>({type:"single",request:r.getAll(t)})),{indexName:e}),getAll:()=>a("readonly",(e=>({type:"single",request:e.getAll()}))),put:e=>{if(!e[r])throw new f(`Record must have a ${r} property`);return a("readwrite",(t=>({type:"single",request:t.put(e)})))},cursor:(e,t="forward")=>{const r="forward"===t?"next":"prev";return a("readwrite",(e=>e.openCursor(void 0,r)),{cursorCallback:e,cursorDirection:r})},batch:async e=>{if(!e.length)throw new f("Batch operations array cannot be empty");return a("readwrite",(t=>{const n=[];for(const o of e)if("add"===o.type||"put"===o.type){(Array.isArray(o.data)?o.data:[o.data]).forEach((e=>{if(!e[r])throw new f(`Record must have a ${r} property`);n.push(t[o.type](e))}))}else if("delete"===o.type){const e=Array.isArray(o.data)?o.data:[o.data];if(e.some((e=>void 0===e)))throw new f("ID cannot be undefined");e.forEach((e=>n.push(t.delete(e))))}return{type:"multiple",requests:n}}))}}};function m(e,t,r){return new Proxy(e,{get(e,n){const o=e[n];return"function"==typeof o?async function(...a){const s=Date.now();let i,c=null;try{return i=await o.apply(e,a),i}catch(e){throw c=e,e}finally{r.emit({name:"telemetry",payload:{type:"telemetry",method:n.toString(),timestamp:Date.now(),metadata:{args:a,performance:{durationMs:Date.now()-s},source:t,context:{userAgent:globalThis.navigator?.userAgent},result:c?void 0:{type:Array.isArray(i)?"array":typeof i,size:Array.isArray(i)?i.length:void 0},error:c?{message:c.message,name:c.name,stack:c.stack}:null}}})}}:o}})}var h=s("uuid"),{matcher:w}=(0,y.createMatcher)({});async function g({connection:e,collection:t,initial:r,enableTelemetry:n=!1,bus:o}){const a=await p(e,{name:t}),s={current:structuredClone(r)};if(void 0===s.current.$id){const e=Object.assign(s.current,{$id:(0,h.v4)(),$created:(new Date).toJSON(),$version:1});await a.put(e),s.current=e,o.emit({name:"document:create",payload:{type:"document:create",data:s.current,timestamp:Date.now()}})}const i={save:async e=>{const{$id:t}=s.current;if(!t)throw new Error("Document ID is missing.");return s.current.$version=(s.current.$version||0)+1,s.current.$updated=(new Date).toJSON(),await a.put(s.current),e||o.emit({name:"document:write",payload:{type:"document:write",data:s.current,timestamp:Date.now()}}),!0},update:async e=>{s.current=Object.assign(s.current,e);const t=await i.save(!0);return t&&o.emit({name:"document:update",payload:{type:"document:update",data:s.current,timestamp:Date.now()}}),t},delete:async()=>{const{$id:e}=s.current;if(!e)throw new Error("Document ID is missing.");return await a.delete(e),o.emit({name:"document:delete",payload:{type:"document:delete",data:s.current,timestamp:Date.now()}}),!0},read:async()=>{const e=s.current.$id;if(!e)throw new Error("Document ID is missing.");const t=await a.getById(e);if(!t)throw new Error("Document not found.");return s.current=structuredClone(t),o.emit({name:"document:read",payload:{type:"document:read",data:s.current,timestamp:Date.now()}}),!0},subscribe:o.subscribe},c=n?m(i,{level:"document",collection:t,document:s.current.$id},o):i;return o.emit({name:"document:read",payload:{type:"document:read",data:s.current,timestamp:Date.now()}}),new Proxy({},{get:(e,t)=>["update","delete","subscribe","read"].includes(t)?c[t]:Reflect.get(s.current,t)})}async function b({connection:e,collection:t,enableTelemetry:r=!1,bus:n}){const o=await p(e,{name:t}),a={create:async o=>{const a=await g({connection:e,collection:t,initial:o,enableTelemetry:r,bus:n});return n.emit({name:"collection:read",payload:{type:"collection:read",model:t,timestamp:Date.now()}}),a},find:async a=>{const s=await o.cursor((async e=>e&&w(e,a)?{value:e,done:!0}:{value:null,done:!1}));if(s){const o=await g({connection:e,collection:t,initial:s,enableTelemetry:r,bus:n});return n.emit({name:"collection:read",payload:{type:"collection:read",method:"find",model:t,timestamp:Date.now()}}),o}return null},list:async a=>{const s={total:await o.count(),offset:"offset"===a.type?a.offset:0,limit:a.limit,cursor:"cursor"===a.type?a.cursor:void 0,direction:"cursor"===a.type?a.direction:"forward",count:0};return{async next(){const i="offset"===a.type?await async function(e,t){const{offset:r,limit:n}=t,o=[];let a=0,s=!1;for(;!(s||(await e((async e=>a<r?(a++,{value:e,done:!1,offset:1}):(o.push(e),a++,a>=r+n?(s=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1}))),o.length>=n)););return o}(o.cursor,{...a,offset:s.offset}):await async function(e,t){const{limit:r,direction:n}=t,o=[];let a=!1;for(;!a;)await e((async e=>(o.push(e),o.length>=r?(a=!0,{value:e,done:!0,offset:1}):{value:e,done:!1,offset:1})),n);return o}(o.cursor,{...a});s.offset+=s.limit,s.count+=i.length;const c=await Promise.all(i.map((o=>g({collection:t,connection:e,initial:o,enableTelemetry:r,bus:n}))));return n.emit({name:"collection:read",payload:{type:"collection:read",method:"list",model:t,timestamp:Date.now()}}),{value:c,done:s.count===s.total}}}},filter:async a=>{const s=[];return await o.cursor((async o=>(o&&w(o,a)&&s.push(await g({connection:e,collection:t,initial:o,enableTelemetry:r,bus:n})),{value:null,done:!1}))),n.emit({name:"collection:read",payload:{type:"collection:read",method:"filter",model:t,timestamp:Date.now()}}),s},subscribe:n.subscribe};return r?m(a,{level:"collection",collection:t},n):a}var v=(e=>(e.SCHEMA_NOT_FOUND="SCHEMA_NOT_FOUND",e.SCHEMA_ALREADY_EXISTS="SCHEMA_ALREADY_EXISTS",e.INVALID_SCHEMA_NAME="INVALID_SCHEMA_NAME",e.INVALID_SCHEMA_DEFINITION="INVALID_SCHEMA_DEFINITION",e.SUBSCRIPTION_FAILED="SUBSCRIPTION_FAILED",e.INTERNAL_ERROR="INTERNAL_ERROR",e))(v||{}),E=class extends Error{type;schema;constructor(e,t,r){super(t),this.type=e,this.schema=r}};async function O(e){const t=(0,d.createEventBus)(),r=e.indexSchema||"$schema",n=e.keyPath||"$id",o=new Map;if(o.has(e.name))return o.get(e.name);let a=null;async function s(){return a||(a=await new Promise(((t,o)=>{const a=indexedDB.open(e.name);a.onerror=()=>o(new Error(`Failed to open database: ${a.error}`)),a.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(r)||t.createObjectStore(r,{keyPath:n})},a.onsuccess=()=>t(a.result)}))),a}const i={collection:async function(r){if(!(await s()).objectStoreNames.contains(r))throw new E("SCHEMA_NOT_FOUND",`Collection with name ${r} does not exist`);return t.emit({name:"collection:read",payload:{type:"collection:read",schema:{name:r},timestamp:Date.now()}}),b({connection:s,collection:r,bus:t,enableTelemetry:e.enableTelemetry})},createCollection:async function(n){const o=await s();if(o.objectStoreNames.contains(n.name))throw new E("SCHEMA_ALREADY_EXISTS",`Collection with name ${n.name} exists`);const i=structuredClone(o.version);o.close(),a=await new Promise(((t,r)=>{const o=indexedDB.open(e.name,i+1);o.onerror=()=>r(new Error(`Failed to open database: ${o.error}`)),o.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(n.name)||t.createObjectStore(n.name,{keyPath:"$id"})},o.onsuccess=()=>t(o.result)}));const c=await b({connection:s,collection:r,bus:t,enableTelemetry:e.enableTelemetry});return await c.create(n),t.emit({name:"collection:create",payload:{type:"collection:create",schema:n,timestamp:Date.now()}}),c},deleteCollection:async function(n){const o=await s();if(!o.objectStoreNames.contains(n))throw new E("SCHEMA_NOT_FOUND",`Collection with name ${n} does not exist`);const i=structuredClone(o.version);o.close(),a=await new Promise(((t,r)=>{const o=indexedDB.open(e.name,i+1);o.onerror=()=>r(new Error(`Failed to open database: ${o.error}`)),o.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(n)&&t.deleteObjectStore(n)},o.onsuccess=()=>t(o.result)}));const c=await b({connection:s,collection:r,bus:t,enableTelemetry:e.enableTelemetry}),l=await c.find({field:"name",operator:"eq",value:n});try{await(l?.delete())}catch(e){throw new E("INTERNAL_ERROR",e.message)}return t.emit({name:"collection:delete",payload:{type:"collection:delete",schema:l,timestamp:Date.now()}}),!0},updateCollection:async function(n){if(!(await s()).objectStoreNames.contains(n.name))throw new E("SCHEMA_NOT_FOUND",`Collection with name ${n.name} does not exist`);const o=await b({connection:s,collection:r,enableTelemetry:e.enableTelemetry,bus:t}),a=await o.find({field:"name",operator:"eq",value:n.name});return!!a&&(await a.update(n),t.emit({name:"collection:update",payload:{type:"collection:update",schema:n,timestamp:Date.now()}}),!0)},subscribe:t.subscribe,close:()=>{a&&a.close()}},c=e.enableTelemetry?m(i,{level:"database"},t):i;return o.set(e.name,c),c}}}),y="https://github.com/asaidimu",f=c(l()),p=class{storageKey;eventBus;storage;constructor(e,t=!1){this.storageKey=e,this.storage=t?sessionStorage:localStorage,this.eventBus=this.initializeEventBus(),t||this.setupStorageEventListener()}initializeEventBus(){const e={async:!0,batchSize:5,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${this.storageKey}:`,e),crossTab:!0,channelName:`storage_${this.storageKey}`};return(0,f.createEventBus)(e)}setupStorageEventListener(){window.addEventListener("storage",(e=>{if(e.key===this.storageKey&&e.newValue)try{const t=JSON.parse(e.newValue);this.eventBus.emit({name:"store:updated",payload:{storageKey:this.storageKey,instanceId:"external",state:t}})}catch(e){console.error("Failed to parse storage event data:",e)}}))}set(e,t){try{const r=JSON.stringify(t);return this.storage.setItem(this.storageKey,r),this.eventBus.emit({name:"store:updated",payload:{storageKey:this.storageKey,instanceId:e,state:t}}),!0}catch(e){return console.error(`Failed to persist state to web storage for ${this.storageKey}:`,e),!1}}get(){try{const e=this.storage.getItem(this.storageKey);return e?JSON.parse(e):null}catch(e){return console.error(`Failed to retrieve state from web storage for ${this.storageKey}:`,e),null}}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:n,state:o})=>{r===this.storageKey&&n!==e&&t(o)}))}clear(){try{return this.storage.removeItem(this.storageKey),!0}catch(e){return console.error(`Failed to clear persisted state for ${this.storageKey}:`,e),!1}}},m=c(l()),h=c(d()),w=c(u()),g=class e{static dbInstances=new Map;static collectionInstances=new Map;static eventBusMap=new Map;static defaultModelName="stores";static getDatabase(t){const{database:r,enableTelemetry:n=!1,collection:o=e.defaultModelName}=t;if(!e.dbInstances.has(r)){const t=(0,h.DatabaseConnection)({name:r,enableTelemetry:n}).then((async e=>{try{await e.createCollection({name:o,version:"1.0.0",nestedSchemas:{},fields:{store:{name:"store",type:"string",required:!0},data:{name:"data",type:"object",required:!0}}})}catch(e){if(e instanceof h.DatabaseError&&"SCHEMA_ALREADY_EXISTS"!==e.type)throw e}return e}));e.dbInstances.set(r,t)}return e.dbInstances.get(r)}static getEventBus(t,r){const n=`${t}_store_${r}`;return e.eventBusMap.has(n)||e.eventBusMap.set(n,(0,m.createEventBus)({batchSize:5,async:!0,batchDelay:16,errorHandler:e=>console.error(`Event bus error for ${t}:${r}:`,e),crossTab:!0,channelName:n})),e.eventBusMap.get(n)}static getCollection(t){const{database:r,collection:n=e.defaultModelName}=t,o=`${r}:${n}`;if(!e.collectionInstances.has(o)){const r=e.getDatabase(t).then((e=>e.collection(n)));e.collectionInstances.set(o,r)}return e.collectionInstances.get(o)}static async closeDatabase(t){const r=e.dbInstances.get(t);if(r){(await r).close(),e.dbInstances.delete(t);const n=[];e.collectionInstances.forEach(((e,r)=>{r.startsWith(`${t}:`)&&n.push(r)})),n.forEach((t=>e.collectionInstances.delete(t)));const o=[];e.eventBusMap.forEach(((e,r)=>{r.startsWith(`${t}_store_`)&&(e.clear(),o.push(r))})),o.forEach((t=>e.eventBusMap.delete(t)))}}static async closeAll(){const t=Array.from(e.dbInstances.keys()).map((t=>e.closeDatabase(t)));await Promise.all(t)}static getActiveDatabases(){return Array.from(e.dbInstances.keys())}},b=class{collection=null;collectionPromise;config;eventBus;constructor(e){this.config=e,this.collectionPromise=g.getCollection(this.config),this.collectionPromise.then((e=>{this.collection=e})).catch((e=>{console.error(`Failed to initialize collection for store ${this.config.store}:`,e)})),this.eventBus=g.getEventBus(this.config.database,this.config.store)}async getCollection(){return this.collection?this.collection:this.collectionPromise}async set(e,t){try{const r=await this.getCollection(),n=(new w.QueryBuilder).where({field:"store",operator:"eq",value:this.config.store}).build(),o=await r.find(n.filters),a={store:this.config.store,data:t};let s;return o?s=await o.update(a):(await r.create(a),s=!0),s&&this.eventBus.emit({name:"store:updated",payload:{storageKey:this.config.store,instanceId:e,state:t}}),s}catch(t){return console.error(`Failed to set state for store ${this.config.store} in database ${this.config.database} by instance ${e}:`,t),!1}}async get(){try{const e=await this.getCollection(),t=(new w.QueryBuilder).where({field:"store",operator:"eq",value:this.config.store}).build(),r=await e.find(t.filters);return r?r.read().then((()=>r.data)):null}catch(e){return console.error(`Failed to get state for store ${this.config.store} in database ${this.config.database}:`,e),null}}subscribe(e,t){return this.eventBus.subscribe("store:updated",(({storageKey:r,instanceId:n,state:o})=>{r===this.config.store&&n!==e&&t(o)}))}async clear(){try{const e=await this.collectionPromise,t=(new w.QueryBuilder).where({field:"store",operator:"eq",value:this.config.store}).build(),r=await e.find(t.filters);return!r||await r.delete()}catch(e){return console.error(`Failed to clear state for store ${this.config.store} in database ${this.config.database}:`,e),!1}}async close(){await g.closeDatabase(this.config.database)}};export{b as IndexedDBPersistence,p as WebStoragePersistence,y as author};
|
package/package.json
CHANGED
@@ -1,12 +1,12 @@
|
|
1
1
|
{
|
2
2
|
"name": "@asaidimu/utils-persistence",
|
3
|
-
"version": "2.0.
|
3
|
+
"version": "2.0.2",
|
4
4
|
"description": "Persistence utilities.",
|
5
5
|
"main": "index.js",
|
6
6
|
"module": "index.mjs",
|
7
7
|
"types": "index.d.ts",
|
8
8
|
"files": [
|
9
|
-
"
|
9
|
+
"./*"
|
10
10
|
],
|
11
11
|
"keywords": [
|
12
12
|
"typescript",
|
@@ -30,7 +30,7 @@
|
|
30
30
|
},
|
31
31
|
"dependencies": {
|
32
32
|
"@asaidimu/events": "^1.1.1",
|
33
|
-
"@asaidimu/indexed": "^3.0.
|
33
|
+
"@asaidimu/indexed": "^3.0.1",
|
34
34
|
"@asaidimu/query": "^1.1.2",
|
35
35
|
"uuid": "^11.1.0"
|
36
36
|
},
|
@@ -51,7 +51,7 @@
|
|
51
51
|
[
|
52
52
|
"@semantic-release/npm",
|
53
53
|
{
|
54
|
-
"pkgRoot": "
|
54
|
+
"pkgRoot": "./dist"
|
55
55
|
}
|
56
56
|
],
|
57
57
|
[
|