tsdf 17.0.0-alpha.7 → 17.0.0-alpha.8

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 ADDED
@@ -0,0 +1,140 @@
1
+ # PolyForm Noncommercial License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
4
+
5
+ Required Notice: Copyright Lucas Santos
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree
10
+ to them as both strict obligations and conditions to all
11
+ your licenses.
12
+
13
+ ## Copyright License
14
+
15
+ The licensor grants you a copyright license for the
16
+ software to do everything you might do with the software
17
+ that would otherwise infringe the licensor's copyright
18
+ in it for any permitted purpose. However, you may
19
+ only distribute the software according to [Distribution
20
+ License](#distribution-license) and make changes or new works
21
+ based on the software according to [Changes and New Works
22
+ License](#changes-and-new-works-license).
23
+
24
+ ## Distribution License
25
+
26
+ The licensor grants you an additional copyright license
27
+ to distribute copies of the software for any permitted
28
+ purpose. Your license to distribute covers distributing
29
+ unchanged copies of the software, copies of the software
30
+ with changes, and new works based on the software permitted
31
+ by [Changes and New Works License](#changes-and-new-works-license),
32
+ but only for permitted purposes.
33
+
34
+ For clarity, distributing unchanged copies of the software,
35
+ copies of the software with changes, or new works based on the
36
+ software for commercial purposes is not a permitted purpose and
37
+ requires the licensor's prior written permission.
38
+
39
+ ## Notices
40
+
41
+ You must ensure that anyone who gets a copy of any part of
42
+ the software from you also gets a copy of these terms or the
43
+ URL for them above, as well as copies of any plain-text lines
44
+ beginning with `Required Notice:` that the licensor provided
45
+ with the software. For example:
46
+
47
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
48
+
49
+ ## Changes and New Works License
50
+
51
+ The licensor grants you an additional copyright license to
52
+ make changes and new works based on the software for any
53
+ permitted purpose.
54
+
55
+ ## Patent License
56
+
57
+ The licensor grants you a patent license for the software that
58
+ covers patent claims the licensor can license, or becomes able
59
+ to license, that you would infringe by using the software.
60
+
61
+ ## Noncommercial Purposes
62
+
63
+ Any noncommercial purpose is a permitted purpose.
64
+
65
+ ## Personal Uses
66
+
67
+ Personal use for research, experiment, and testing for
68
+ the benefit of public knowledge, personal study, private
69
+ entertainment, hobby projects, amateur pursuits, or religious
70
+ observance, without any anticipated commercial application,
71
+ is use for a permitted purpose.
72
+
73
+ ## Noncommercial Organizations
74
+
75
+ Use by any charitable organization, educational institution,
76
+ public research organization, public safety or health
77
+ organization, environmental protection organization,
78
+ or government institution is use for a permitted purpose
79
+ regardless of the source of funding or obligations resulting
80
+ from the funding.
81
+
82
+ ## Fair Use
83
+
84
+ You may have "fair use" rights for the software under the
85
+ law. These terms do not limit them.
86
+
87
+ ## No Other Rights
88
+
89
+ These terms do not allow you to sublicense or transfer any of
90
+ your licenses to anyone else, or prevent the licensor from
91
+ granting licenses to anyone else. These terms do not imply
92
+ any other licenses.
93
+
94
+ ## Patent Defense
95
+
96
+ If you make any written claim that the software infringes or
97
+ contributes to infringement of any patent, your patent license
98
+ for the software granted under these terms ends immediately. If
99
+ your company makes such a claim, your patent license ends
100
+ immediately for work on behalf of your company.
101
+
102
+ ## Violations
103
+
104
+ The first time you are notified in writing that you have
105
+ violated any of these terms, or done anything with the software
106
+ not covered by your licenses, your licenses can nonetheless
107
+ continue if you come into full compliance with these terms,
108
+ and take practical steps to correct past violations, within
109
+ 32 days of receiving notice. Otherwise, all your licenses
110
+ end immediately.
111
+
112
+ ## No Liability
113
+
114
+ ***As far as the law allows, the software comes as is, without
115
+ any warranty or condition, and the licensor will not be liable
116
+ to you for any damages arising out of these terms or the use
117
+ or nature of the software, under any kind of legal claim.***
118
+
119
+ ## Definitions
120
+
121
+ The **licensor** is the individual or entity offering these
122
+ terms, and the **software** is the software the licensor makes
123
+ available under these terms.
124
+
125
+ **You** refers to the individual or entity agreeing to these
126
+ terms.
127
+
128
+ **Your company** is any legal entity, sole proprietorship,
129
+ or other kind of organization that you work for, plus all
130
+ organizations that have control over, are under the control of,
131
+ or are under common control with that organization. **Control**
132
+ means ownership of substantially all the assets of an entity,
133
+ or the power to direct its management and policies by vote,
134
+ contract, or otherwise. Control can be direct or indirect.
135
+
136
+ **Your licenses** are all the licenses granted to you for the
137
+ software under these terms.
138
+
139
+ **Use** means anything you do with the software requiring one
140
+ of your licenses.
package/README.md CHANGED
@@ -2,4 +2,7 @@
2
2
 
3
3
  A data fetching solution based on T-State.
4
4
 
5
+ TSDF is source-available under the PolyForm Noncommercial License 1.0.0.
6
+ Commercial use requires separate permission.
7
+
5
8
  Check full docs on [/docs/README.md](./docs/README.md)
@@ -0,0 +1,2 @@
1
+ import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-kvAIhrBD.js";
2
+ export { createAsyncStorageAdapter };
@@ -0,0 +1 @@
1
+ import{i as e}from"./asyncStorageAdapter-CgG3vm0t.js";export{e as createAsyncStorageAdapter};
@@ -0,0 +1 @@
1
+ import{__LEGIT_CAST__ as e}from"@ls-stack/utils/saferTyping";import{klona as t}from"klona/json";import{isObject as n}from"@ls-stack/utils/typeGuards";import{createCache as r}from"@ls-stack/utils/cache";import{deepEqual as i}from"@ls-stack/utils/deepEqual";import{sleep as a}from"@ls-stack/utils/sleep";import{rc_array as o,rc_discriminated_union as s,rc_literals as c,rc_number as l,rc_object as u,rc_parse as d,rc_parse_json as f,rc_record as p,rc_string as m,rc_tuple as h,rc_unknown as g}from"runcheck";import{asPossiblyUndefined as _}from"@ls-stack/utils/typingFnUtils";function v(e){if(typeof requestIdleCallback==`function`){let t=requestIdleCallback(()=>e(),{timeout:3e3});return()=>cancelIdleCallback(t)}else{let t=setTimeout(e,2e3);return()=>clearTimeout(t)}}function y(e){return JSON.stringify([e.sessionKey,e.storeName,e.kind])}function b(e){switch(e){case`document`:return`d`;case`collection.item`:return`ci`;case`listQuery.item`:return`li`;case`listQuery.query`:return`lq`;case`offline.queue`:return`oq`;case`offline.conflict`:return`oc`;case`offline.entity`:return`oe`;case`__internal.protected`:return`ip`}}function x(e){switch(e){case`d`:return`document`;case`ci`:return`collection.item`;case`li`:return`listQuery.item`;case`lq`:return`listQuery.query`;case`oq`:return`offline.queue`;case`oc`:return`offline.conflict`;case`oe`:return`offline.entity`;case`ip`:return`__internal.protected`;default:return null}}function S(e){return JSON.stringify([e.sessionKey,e.storeName,b(e.kind)])}function C(e){return`__tsdf_payload__:${e}`}function w(e){return JSON.stringify([e.sessionKey,e.storeName,b(e.kind),e.key])}function ee(e){let t=f(e,h([m,m,m,m])).unwrapOrNull();if(t===null)return null;let[n,r,i,a]=t,o=x(i);return o===null?null:{sessionKey:n,storeName:r,kind:o,key:a}}function T(e){return e.startsWith(`__tsdf_payload__:`)?{recordKind:`payload`,userKey:e.slice(17)}:{rawKey:e,recordKind:`raw`}}function E(e){if(e==null)return null;let t=typeof e.maxBytes==`number`&&Number.isInteger(e.maxBytes)&&e.maxBytes>=0?e.maxBytes:void 0,n=Array.isArray(e.pinnedKeys)?[...new Set(e.pinnedKeys)].sort((e,t)=>e.localeCompare(t)):[];return t===void 0&&n.length===0?null:{...t===void 0?{}:{maxBytes:t},...n.length>0?{pinnedKeys:n}:{}}}function D(e,t,n){return n===`key`||e.lastAccessAt===t.lastAccessAt?e.key.localeCompare(t.key):n===`lru-asc`?e.lastAccessAt-t.lastAccessAt:t.lastAccessAt-e.lastAccessAt}function O(e,t){if(`v`in e&&e.v!==void 0)throw Error(`[TSDF] Compact localStorage entries cannot use the reserved "v" key.`);return t===void 0?e:{...e,v:t}}function k(e){if(e===null)return null;let t=f(e,g).unwrapOrNull();return t===null||!n(t)||!(`d`in t)||`v`in t&&t.v!==void 0&&typeof t.v!=`number`?null:{value:t,...typeof t.v==`number`?{version:t.v}:{}}}function A(){return _(globalThis.navigator)?.locks??null}const te=new Set;function ne(e){A()===null&&(te.has(e)||(te.add(e),console.warn(e)))}async function re(e,t,n){let r=A();return r===null?(ne(t),await n()):r.request(e,n)}const j=new Map;function ie(e,t){j.set(e,new Set(t))}function M(e){return j.get(e)??null}function ae(e){j.delete(e)}const oe=u({entityKey:m,entityKind:c(`item`)}),se=u({entityKey:m,entityKind:c(`document`,`item`,`query`)}),ce={id:m,entryId:m,sessionKey:m,storeName:m,storeType:c(`document`,`collection`,`listQuery`),operation:m,input:g,enqueuedAt:l,entityRefs:o(se),createdAt:l,updatedAt:l,attachedUploadIds:p(m).optionalKey(),dependencyUploadIds:o(m).optionalKey()},le=s(`kind`,{conflict:{...ce,kind:c(`conflict`),conflict:g},"retry-exhausted":{...ce,kind:c(`retry-exhausted`),lastReplayError:u({message:m})}}),ue={network:{enabled:!1},outage:{enabled:!1},mutationQueueing:{network:`allow`,outage:`allow`}},de=u({e:c(1).optionalKey(),a:c(1).optionalKey()}),fe=u({n:de.optionalKey(),o:de.optionalKey(),u:l.optionalKey(),lf:l.optionalKey(),lr:l.optionalKey()});function pe(e){return e.enabled&&e.active}function me(e){return e.network.active||e.outage.active}function he(e){let t=d(e,fe).unwrapOrNull();return t===null?!1:t.n?.a===1||t.o?.a===1}function ge(e){if(e.length===0)return`invalid-conflict-payload`;if(typeof e[0]==`string`){let t=e[0];for(let n of e.slice(1)){if(typeof n!=`string`)return JSON.stringify(e);t+=`; ${n}`}return t}return JSON.stringify(e)}function _e(e){return e.code===`invalid-conflict-payload`&&e.validationError?ge(e.validationError):e.code}var ve=class extends Error{code;operation;kind;rawValue;validationError;constructor(e){super(_e(e)),this.name=`OfflineResolutionConflictParseError`,this.code=e.code,this.operation=e.operation,this.kind=e.kind,this.rawValue=e.rawValue,this.validationError=e.validationError}};function ye(){let e=new Set,t=!1;function n(){t||(t=!0,queueMicrotask(()=>{t=!1,e.clear()}))}return{has:t=>e.has(t),remember:t=>{e.add(t),n()},clear:t=>{e.delete(t)},clearAll:()=>{e.clear()}}}function be(e,t){if(!e)return()=>!1;if(typeof e==`function`)return e;let n=new Set(e.map(t));return e=>n.has(t(e))}function N(e){return e.length}function P(e){let t=JSON.stringify(e);return{rawValue:t,sizeBytes:N(t)}}function F(e){let t=new Set,n=0;for(let t of e.entries)e.isProtected(t)||(n+=e.getSizeBytes(t));if(n<=e.maxBytes){for(let n of e.entries)t.add(e.getKey(n));return t}let r=[...e.entries].sort((t,n)=>{let r=e.isProtected(t),i=e.isProtected(n);if(r&&!i)return-1;if(!r&&i)return 1;let a=e.isPinned(t),o=e.isPinned(n);return a&&!o?-1:!a&&o?1:e.getLastAccessAt(n)-e.getLastAccessAt(t)}),i=0;for(let n of r){let r=e.getKey(n);if(e.isProtected(n)){t.add(r);continue}let a=e.getSizeBytes(n);if(e.isPinned(n)){t.add(r),i+=a;continue}i+a<=e.maxBytes&&(t.add(r),i+=a)}return t}const xe={localSync:{collection:64*1024,listItem:64*1024,listQuery:32*1024},async:{collection:128*1024,listItem:128*1024,listQuery:64*1024}};function Se(e){return e===`local-sync`||e===`localSync`?`localSync`:`async`}function Ce(e){switch(e){case`collection.item`:return`collection`;case`listQuery.item`:return`listItem`;case`listQuery.query`:return`listQuery`}}function we(e){return xe[Se(e.adapter)][e.kind]}function I(e){return we({adapter:e.adapter,kind:Ce(e.scopeKind)})}function L(e){switch(e){case`document`:case`collection.item`:case`listQuery.item`:case`listQuery.query`:case`offline.queue`:case`offline.conflict`:case`offline.entity`:case`__internal.protected`:return e;default:return null}}const Te=336*60*60*1e3,R=`tsdf._am.g`;function z(e){return String(Math.floor(e/216e5))}function B(e){return n(e)?e:null}function V(e){return e?.o===!0}function Ee(e){let t=new Set;for(let n of e)V(n.customMetadata)&&t.add(n.key);return t}function De(e){if(typeof window>`u`)return!1;try{return he(k(localStorage.getItem(`tsdf.${e}._o_.s`))?.value.d??null)}catch{return!1}}function H(e,t){if(t)return{...e??{},o:!0};let{o:n,...r}=e??{};return Object.keys(r).length>0?r:void 0}function U(e){let t={...e.currentCustomMetadata??{},...e.nextCustomMetadata??{}},n=Object.keys(t).length>0?t:void 0;return e.protectedKeysSnapshotSet===null?H(n,V(e.nextCustomMetadata)||V(e.currentCustomMetadata)):H(n,e.protectedKeysSnapshotSet?.has($({...e.scope,key:e.key}))===!0||V(e.nextCustomMetadata)||V(e.currentCustomMetadata))}const Oe=u({b:l.optionalKey(),k:o(m).optionalKey()});function ke(e){let t=Object.entries(e).filter(([e])=>e!==`a`&&e!==`v`&&e!==`z`);if(t.length!==0)return Object.fromEntries(t)}function Ae(e){let t=B(e);if(t===null||typeof t.a!=`number`||`v`in t&&t.v!==void 0&&typeof t.v!=`number`||`z`in t&&t.z!==void 0&&typeof t.z!=`number`)return null;let n=ke(t);return{lastAccessAt:t.a,...typeof t.z==`number`?{sizeBytes:t.z}:{},version:typeof t.v==`number`?t.v:1,...n?{customMetadata:n}:{}}}function je(e){let t={a:e.lastAccessAt,...e.sizeBytes===void 0?{}:{z:e.sizeBytes},...e.version===1?{}:{v:e.version}},n=e.customMetadata;if(n===void 0)return t;if(`a`in n||`v`in n||`z`in n)throw Error(`[TSDF] Async storage custom metadata cannot use reserved keys "a", "v", or "z".`);return{...t,...n}}function Me(e){return N(e.serializedValue)+N(JSON.stringify(je({lastAccessAt:e.lastAccessAt,sizeBytes:void 0,version:e.version,...e.customMetadata?{customMetadata:e.customMetadata}:{}})))}function Ne(e){let t=B(e)?.e;if(t===void 0)return e===null?new Map:null;let n=B(t);if(n===null)return null;let r=new Map;for(let[e,t]of Object.entries(n)){let n=Ae(t);if(n===null)return null;r.set(e,n)}return r}function Pe(e,t,n){return E({...e!==void 0&&e!==t?{maxBytes:e}:{},...n.size>0?{pinnedKeys:[...n]}:{}})}function Fe(e){let t=d(e,Oe).unwrapOrNull();return t===null||t.b!==void 0&&(!Number.isInteger(t.b)||t.b<0)?null:E({...t.b===void 0?{}:{maxBytes:t.b},...t.k===void 0?{}:{pinnedKeys:t.k}})}function Ie(e){if(e!==null)return{...e.maxBytes===void 0?{}:{b:e.maxBytes},...e.pinnedKeys!==void 0&&e.pinnedKeys.length>0?{k:e.pinnedKeys}:{}}}function Le(e){let t=Ie(e.staticPolicy);return{e:Object.fromEntries([...e.entries.entries()].map(([e,t])=>[e,je(t)])),...t===void 0?{}:{s:t}}}function Re(e){switch(e.kind){case`collection.item`:return{maxBytes:I({adapter:`async`,scopeKind:`collection.item`})};case`listQuery.item`:return{maxBytes:I({adapter:`async`,scopeKind:`listQuery.item`})};case`listQuery.query`:return{maxBytes:I({adapter:`async`,scopeKind:`listQuery.query`})};default:return null}}function ze(e,t){if(t===null)return null;let n=Re(e);return E({maxBytes:t.maxBytes!==void 0&&t.maxBytes!==n?.maxBytes?t.maxBytes:void 0,pinnedKeys:t.pinnedKeys})}function Be(e,t){let n=Re(e);return n===null?t:E({maxBytes:t?.maxBytes??n.maxBytes,pinnedKeys:t?.pinnedKeys})}async function Ve(e,t,n){return n.length===0?[]:e.getMany(t,n)}function W(t){return e(t).__tsdfManagedStorage??null}async function G(e,t,n){let r=W(e);if(r?.readNamespaceIndexState!==void 0)return r.readNamespaceIndexState(t,n);if(n!=null&&!n.includes(`_i`))return{entries:null,exists:!1,staticPolicy:null,valid:!0};let i=n!=null,a=await e.get(t,`_i`);if(a===null)return i?{entries:null,exists:!0,staticPolicy:null,valid:!1}:{entries:null,exists:!1,staticPolicy:null,valid:!0};let o=B(a),s=Ne(a);return s===null?{entries:null,exists:!0,staticPolicy:null,valid:!1}:{entries:s,exists:!0,staticPolicy:Fe(o?.s),valid:!0}}function He(e){return e===null?null:{maxBytes:e.maxBytes,pinnedKeys:e.pinnedKeys?[...e.pinnedKeys]:void 0}}function Ue(e){return{lastAccessAt:e.lastAccessAt,sizeBytes:e.sizeBytes,version:e.version,customMetadata:e.customMetadata?t(e.customMetadata):void 0}}function K(e){let t=null;if(e.entries!==null){t=new Map;for(let[n,r]of e.entries)t.set(n,Ue(r))}return{entries:t,exists:e.exists,staticPolicy:He(e.staticPolicy),valid:e.valid}}function We(e){switch(e){case`clear`:case`commit`:case`remove`:case`startup-cleanup`:return e;default:return null}}function Ge(e){let t=B(e);if(t===null||t.kind!==`namespace-invalidated`||t.protocolVersion!==1)return null;let n=B(t.scope);if(n===null||typeof n.kind!=`string`||typeof n.sessionKey!=`string`||typeof n.storeName!=`string`)return null;let r=L(n.kind);if(r===null)return null;let i=We(t.reason);return i===null?null:{kind:`namespace-invalidated`,protocolVersion:1,reason:i,scope:{kind:r,sessionKey:n.sessionKey,storeName:n.storeName}}}const q=[];let J,Ke=!1;function Y(){let e=[],t=[];for(let n of q){let r=n.deref();r!==void 0&&(e.push(r),t.push(n))}return q.length=0,q.push(...t),e}function qe(){for(let e of Y())e.clearAllCachedReads()}function Je(e,t){for(let n of Y())n!==e&&n.onRemoteCacheInvalidation(t)}function Ye(e){let t=Ge(e.data);if(t!==null)for(let e of Y())e.onRemoteCacheInvalidation(t)}function Xe(){if(Ke||=(document.addEventListener(`visibilitychange`,()=>{document.hidden||qe()}),typeof window<`u`&&window.addEventListener(`pageshow`,()=>{qe()}),!0),J===void 0)try{J=new BroadcastChannel(`tsdf-async-storage-cache-v1`),J.addEventListener(`message`,Ye)}catch{J=null}}function Ze(e){Xe(),q.push(new WeakRef(e))}function Qe(e){let t=B(e);if(t===null)return null;let n=t.lca;return n!==null&&typeof n!=`number`?null:{lastSuccessfulCleanupAt:n}}function X(){return{lastSuccessfulCleanupAt:null}}var $e=class{constructor(e,t){this.adapter=e,this.scope=t}async get(e,t={}){await this.adapter.flushPendingNamespaceCommit(this.scope,[e]);let n=(await this.adapter.readManagedEntries(this.scope,[e])).get(e)??null;if(!n)return null;let r=Date.now(),i=t.touch??`coarse`;return this.adapter.shouldEnqueueTouch(this.scope,e,n.metadata.lastAccessAt,i,r)&&this.commit({touches:[{key:e,lastAccessAt:r}]}).catch(()=>{}),n}async getMany(e,t={}){if(e.length===0)return[];let n=[...new Set(e)];await this.adapter.flushPendingNamespaceCommit(this.scope,n);let r=await this.adapter.readManagedEntries(this.scope,n),i=new Map,a=[],o=Date.now(),s=t.touch??`coarse`;for(let e of n){let t=r.get(e)??null;i.set(e,t),t!==null&&this.adapter.shouldEnqueueTouch(this.scope,e,t.metadata.lastAccessAt,s,o)&&a.push(e)}return a.length>0&&this.commit({touches:a.map(e=>({key:e,lastAccessAt:o}))}).catch(()=>{}),e.map(e=>i.get(e)??null)}commit(e){return this.adapter.queueCommitToNamespace(this.scope,e)}async listKeys(){return await this.adapter.flushPendingNamespaceCommit(this.scope),this.adapter.listManagedKeys(this.scope)}async listMetadata(e={}){return await this.adapter.flushPendingNamespaceCommit(this.scope),this.adapter.listManagedMetadata(this.scope,e)}async listMetadataByFilter(e){return await this.adapter.flushPendingNamespaceCommit(this.scope),this.adapter.listManagedMetadata(this.scope,e)}async clear(){await this.adapter.flushPendingNamespaceCommit(this.scope),await this.adapter.clearManagedNamespace(this.scope)}};const Z=new WeakMap;function Q(e,t){return JSON.stringify([e,t])}function et(e,t,n,r){let i=Z.get(e)??new Map;i.set(Q(t,n),r),Z.set(e,i)}function tt(e,t,n){let r=Z.get(e);r!==void 0&&(r.delete(Q(t,n)),r.size===0&&Z.delete(e))}var nt=class{kind=`async`;#e=r({maxCacheSize:500});#t=r({maxCacheSize:5e3});#n=new Map;#r=new Map;#i=new Map;#a=0;#o=new Map;#s=!1;constructor(e){this.driver=e,Ze(this)}async#c(e,t){return re(`tsdf-async-write:${e}`,`[TSDF] navigator.locks is unavailable; async persistentStorage is using unlocked writer coordination.`,t)}openNamespace(e){return this.#r.set(y(e),e),this.#H(),new $e(this,e)}async clearSession(e){await this.#c(e,async()=>{await this.#d(e);let t=await this.#R(e);await Promise.all(t.map(e=>this.#_(e)))})}async readProtectedStorageKeys(e,t=this.driver){let n=M(e);if(n!==null&&n.size>0)return new Set(n);let r=W(t);if(r?.readProtectedStorageKeys!==void 0)return new Set(await r.readProtectedStorageKeys(e));let i=await this.#$(t,e),a=await Promise.all(i.map(async({knownRecordKeys:e,scope:n})=>{let r=await this.#g(t,n,{knownRecordKeys:e,order:`key`}),i=[];for(let e of r)V(e.customMetadata)&&i.push($({...n,key:e.key}));return i}));return new Set(a.flat())}async syncSessionProtectedKeys(e,t,n=[]){let r=new Set(t),i=new Set(n),a=[...[...r].filter(e=>!i.has(e)),...[...i].filter(e=>!r.has(e))];if(a.length===0)return;let o=new Map;for(let t of a){let n=ee(t);if(n===null||n.sessionKey!==e)continue;let i={sessionKey:n.sessionKey,storeName:n.storeName,kind:n.kind},a=y(i),s=o.get(a);if(s!==void 0){s.protectionByKey.set(n.key,r.has(t));continue}o.set(a,{scope:i,protectionByKey:new Map([[n.key,r.has(t)]])})}await this.#c(e,async()=>{await this.#d(e);let t=W(this.driver);if(t?.syncSessionProtectedKeys!==void 0){await t.syncSessionProtectedKeys(e,r);for(let{scope:e}of o.values())this.#A(e),this.#L(e,`commit`);return}await Promise.all([...o.values()].map(async({scope:e,protectionByKey:t})=>{let n=await this.#m(this.driver,e),r=n.valid&&n.entries!==null?n.entries:new Map,i=!1;for(let[e,n]of t.entries()){let t=r.get(e);if(t===void 0||V(t.customMetadata)===n)continue;let a=H(t.customMetadata,n),o={...t};a===void 0?delete o.customMetadata:o.customMetadata=a,r.set(e,o),i=!0}i&&(await this.#h(this.driver,e,{entries:r,staticPolicy:E(n.staticPolicy)}),this.#A(e),this.#L(e,`commit`))}))})}resetForTests(){for(let e of this.#i.values())e.cancelFlush?.();this.clearAllCachedReads(),this.#n.clear(),this.#r.clear(),this.#i.clear(),this.#o.clear(),this.#s=!1,this.driver.__resetForTests?.()}shouldEnqueueTouch(e,t,n,r,i){if(r===`never`)return!1;let a=z(i);if(r!==`force`&&z(n)===a)return!1;let o=y(e),s=`${o}::${t}`;if(this.#o.get(s)===a)return!1;let c=this.#i.get(o)?.touches.get(t);return c===void 0||z(c)!==a}#l(e,t){return t.some(t=>e.upserts.has(t)||e.removes.has(t)||e.inFlightBarrierKeys?.has(t)===!0)}async queueCommitToNamespace(t,n){let r=this.#z(t),i=Date.now();for(let e of n.touches??[])r.touches.set(e.key,e.lastAccessAt??i);for(let e of n.removes??[])r.upserts.delete(e),r.touches.delete(e),r.removes.add(e);`staticPolicy`in n&&(r.hasStaticPolicyUpdate=!0,r.staticPolicy=n.staticPolicy??null);for(let t of n.upserts??[])r.removes.delete(t.key),r.upserts.set(t.key,e(t));return this.#B(r),new Promise((e,t)=>{r.waiters.push({resolve:e,reject:t})})}async flushPendingNamespaceCommit(e,t){let n=y(e),r=this.#i.get(n);r&&(t!==void 0&&t.length>0&&!this.#l(r,t)||await this.#c(e.sessionKey,async()=>{await this.#u(e,t)}))}async#u(e,t){let n=y(e),r=this.#i.get(n);if(!r||t!==void 0&&t.length>0&&!this.#l(r,t))return;if(r.flushPromise){await r.flushPromise;return}r.cancelFlush?.(),r.cancelFlush=null;let i=[...r.upserts.values()],a=[...r.removes],o=r.hasStaticPolicyUpdate,s=r.staticPolicy,c=[...r.touches.entries()].map(([e,t])=>({key:e,lastAccessAt:t})),l=new Set([...r.upserts.keys(),...r.removes]),u=[...r.waiters];if(r.hasStaticPolicyUpdate=!1,r.upserts=new Map,r.removes=new Set,r.staticPolicy=null,r.touches=new Map,r.waiters=[],r.inFlightBarrierKeys=l.size>0?l:null,i.length===0&&a.length===0&&c.length===0&&!o){this.#i.delete(n);for(let e of u)e.resolve();return}r.flushPromise=this.#y(e,{upserts:i,removes:a,...o?{staticPolicy:s}:{},touches:c}).then(()=>{let e=z(Date.now());for(let e of c)this.#o.set(`${n}::${e.key}`,z(e.lastAccessAt));for(let t of i)this.#o.set(`${n}::${t.key}`,e);this.#V(e);for(let e of u)e.resolve()}).catch(e=>{for(let t of u)t.reject(e);throw e}).finally(()=>{if(r.inFlightBarrierKeys=null,r.flushPromise=null,r.waiters.length===0){this.#i.delete(n);return}this.#B(r)}),await r.flushPromise}async flushAllPendingNamespaceCommits(){await Promise.all([...this.#i.values()].map(e=>this.flushPendingNamespaceCommit(e.scope)))}async#d(e){await Promise.all([...this.#i.values()].filter(t=>t.scope.sessionKey===e).map(e=>this.#u(e.scope)))}clearRecentTouchedBucketsForNamespace(e){let t=`${y(e)}::`;for(let e of this.#o.keys())e.startsWith(t)&&this.#o.delete(e)}async#f(e,t,n){let r=await this.#m(e,t,{knownRecordKeys:n});return r.valid&&r.entries!==null?r.entries:new Map}async#p(e,t,n){let r=await this.#m(e,t,{knownRecordKeys:n});return r.valid?E(r.staticPolicy):null}async#m(e,t,n={}){let r=n.knownRecordKeys,i=y(t),a=e===this.driver;if(r!=null){if(!r.includes(`_i`))return this.#A(t),{entries:null,exists:!1,staticPolicy:null,valid:!0};if(a){let e=await this.#e.getAsync(i);if(e!==void 0)return K(e)}}if(!a)return G(e,t,r);let o=this.#P(t);return K(await this.#e.getOrInsertAsync(i,async({skipCaching:n})=>{let i=await G(e,t,r);return this.#F(o)&&this.#I(i)?K(i):n(i)}))}async#h(e,t,n,r=!0){r&&this.#N(t);let i=W(e);if(i?.persistNamespaceIndexState!==void 0){await i.persistNamespaceIndexState(t,n),n.entries.size===0?this.#O(t):this.#E(t,{entries:n.entries,exists:!0,staticPolicy:n.staticPolicy,valid:!0});return}if(n.entries.size===0){await this.#S(e,t,[`_i`]),this.#O(t);return}await this.#x(e,t,[{key:`_i`,value:Le(n)}]),this.#E(t,{entries:n.entries,exists:!0,staticPolicy:n.staticPolicy,valid:!0})}async readManagedEntries(t,n){let r=W(this.driver);if(r?.readManagedEntries!==void 0)return e(await r.readManagedEntries(t,n));let i=await this.#f(this.driver,t),a=n.filter(e=>i.has(e)),o=await this.#T(this.driver,t,a),s=new Map;for(let[e,t]of a.entries())s.set(t,o[e]??null);let c=new Map,l=[];for(let t of n){let n=i.get(t);if(n===void 0){c.set(t,null);continue}let r=s.get(t)??null;if(r===null){l.push(t),c.set(t,null);continue}c.set(t,{value:e(r),metadata:e(this.#v(t,n))})}return l.length>0&&await this.#b(this.driver,t,l),c}async listManagedMetadata(e,t={}){return this.#g(this.driver,e,t)}async#g(t,n,r={}){let i=W(t);if(i?.listManagedMetadata!==void 0)return e(await i.listManagedMetadata(n,r));let a=await this.#f(t,n,r.knownRecordKeys),o=[];for(let[e,t]of a.entries())o.push(this.#v(e,t));if(r.filter!==void 0){let{filter:t}=r;return e(o.filter(e=>e.customMetadata[t.key]===t.equals).sort((e,t)=>D(e,t,r.order??`key`)))}return o.sort((e,t)=>D(e,t,r.order??`key`)),e(o)}async listManagedKeys(e){let t=W(this.driver);return t?.listManagedKeys===void 0?[...(await this.#f(this.driver,e)).keys()].sort((e,t)=>e.localeCompare(t)):t.listManagedKeys(e)}async clearManagedNamespace(e){await this.#c(e.sessionKey,async()=>{await this.#_(e)})}async#_(e){let t=W(this.driver);t?.clearManagedNamespace===void 0?await this.driver.clear(e):await t.clearManagedNamespace(e),this.#A(e),this.#L(e,`clear`);let n=y(e);this.#r.delete(n),this.#i.delete(n),this.clearRecentTouchedBucketsForNamespace(e)}#v(e,t){return{key:e,payloadRef:C(e),writtenAt:t.lastAccessAt,lastAccessAt:t.lastAccessAt,sizeBytes:t.sizeBytes,version:t.version,customMetadata:t.customMetadata??{}}}async#y(e,t){let n=t.upserts??[],r=[...new Set(t.removes??[])],a=t.touches??[],o=[...new Set(a.map(e=>e.key))],s=W(this.driver);if(s?.applyManagedCommit!==void 0){await s.applyManagedCommit(e,t,{mergeOfflineProtectionMetadata:(t,n,r)=>U({currentCustomMetadata:r,key:t,nextCustomMetadata:n,protectedKeysSnapshotSet:M(e.sessionKey),scope:e})}),this.#N(e),this.#O(e);for(let t of r)this.#k(e,t);for(let t of n)this.#D(e,t.key,{value:t.value});this.#L(e,`commit`);return}let c=await this.#m(this.driver,e),l=c.valid&&c.entries!==null?c.entries:new Map,u=Date.now(),d=new Map(a.map(e=>[e.key,e.lastAccessAt??u])),f=[],p=r.map(e=>C(e)),m=!1,h=E(c.staticPolicy);for(let e of r)m=l.delete(e)||m;if(`staticPolicy`in t){let e=E(t.staticPolicy??null);i(h,e)||(h=e,m=!0)}let g=M(e.sessionKey);for(let t of n){let n=l.get(t.key),r=U({currentCustomMetadata:n?.customMetadata,key:t.key,nextCustomMetadata:t.metadata,protectedKeysSnapshotSet:g,scope:e}),a=d.get(t.key)??n?.lastAccessAt??u,o=t.serializedValue===void 0?P(t.value):{rawValue:t.serializedValue},s=e.kind===`document`?void 0:Me({customMetadata:r,lastAccessAt:a,serializedValue:o.rawValue,version:t.version}),c={lastAccessAt:a,version:t.version,...s===void 0?{}:{sizeBytes:s},...r?{customMetadata:r}:{}};f.push({key:C(t.key),serializedValue:o.rawValue,...s===void 0?{}:{sizeBytes:s},value:t.value}),!(n!==void 0&&n.lastAccessAt===c.lastAccessAt&&n.sizeBytes===c.sizeBytes&&n.version===c.version&&i(n.customMetadata,c.customMetadata))&&(l.set(t.key,c),m=!0)}if(o.length>0){let e=new Set(n.map(e=>e.key));for(let t of o){if(e.has(t))continue;let n=l.get(t);if(!n)continue;let r=d.get(t)??u;n.lastAccessAt!==r&&(l.set(t,{...n,lastAccessAt:r}),m=!0)}}await Promise.all([p.length>0?this.#S(this.driver,e,p):Promise.resolve(),f.length>0?this.#x(this.driver,e,f):Promise.resolve()]),this.#N(e);for(let t of r)this.#k(e,t);for(let t of n)this.#D(e,t.key,{value:t.value});m?await this.#h(this.driver,e,{entries:l,staticPolicy:h},!1):this.#E(e,{entries:c.valid?l:null,exists:c.exists,staticPolicy:c.staticPolicy,valid:c.valid}),this.#L(e,`commit`)}async#b(e,t,n){let r=[...new Set(n)];r.length!==0&&await this.#c(t.sessionKey,async()=>{let n=await this.#m(e,t);await this.#S(e,t,r.map(e=>C(e)));for(let e of r)this.#k(t,e);if(n.valid&&n.entries!==null){let i=!1;for(let e of r)i=n.entries.delete(e)||i;i&&await this.#h(e,t,{entries:n.entries,staticPolicy:E(n.staticPolicy)})}this.#L(t,`remove`)})}async#x(e,t,n){n.length!==0&&await e.setMany(t,n)}async#S(e,t,n){n.length!==0&&await e.removeMany(t,n)}#C(){let e=localStorage.getItem(R);if(e===null)return X();try{return Qe(JSON.parse(e))??X()}catch{return X()}}#w(e){localStorage.setItem(R,JSON.stringify({lca:e.lastSuccessfulCleanupAt}))}clearAllCachedReads(){this.#a+=1,this.#e.clear(),this.#t.clear()}onRemoteCacheInvalidation(e){this.#A(e.scope)}async#T(e,n,r){if(r.length===0)return[];if(e!==this.driver)return Ve(e,n,r.map(e=>C(e)));let i=this.#P(n),a=new Map,o=[];for(let e of r){let t=this.#j(n,e);if(this.#t.has(t)){a.set(e,this.#t.getAsync(t).then(e=>e??null));continue}o.push(e)}if(o.length>0){let r=Ve(e,n,o.map(e=>C(e)));for(let[e,s]of o.entries()){let o=this.#j(n,s),c=this.#t.setAsync(o,async({skipCaching:n})=>{let a=(await r)[e]??null,o=a===null?null:{value:t(a)};return this.#F(i)?o===null?n(null):o:n(o)});a.set(s,c)}}return Promise.all(r.map(async e=>{let n=await a.get(e);return n==null?null:t(n.value)}))}#E(e,t){if(!this.#I(t)){this.#e.delete(y(e));return}this.#e.set(y(e),K(t))}#D(e,n,r){this.#t.set(this.#j(e,n),{value:t(r.value)})}#O(e){this.#e.delete(y(e))}#k(e,t){this.#t.delete(this.#j(e,t))}#A(e){let t=`${y(e)}::`;this.#N(e),this.#O(e);for(let e of this.#t[` cache`].map.keys())e.startsWith(t)&&this.#t.delete(e)}#j(e,t){return`${y(e)}::${t}`}#M(e){return this.#n.get(e)??0}#N(e){let t=y(e);this.#n.set(t,this.#M(t)+1)}#P(e){let t=y(e);return{globalGeneration:this.#a,namespaceGeneration:this.#M(t),namespaceId:t}}#F(e){return e.globalGeneration===this.#a&&e.namespaceGeneration===this.#M(e.namespaceId)}#I(e){return e.valid&&e.exists&&e.entries!==null}#L(e,t){let n={kind:`namespace-invalidated`,protocolVersion:1,reason:t,scope:e};Je(this,n),J?.postMessage(n)}async#R(e,t=this.driver){return(await t.listScopes(e)).filter(e=>e.kind!==`__internal.protected`)}#z(e){let t=y(e),n=this.#i.get(t);if(n)return n;let r={scope:e,cancelFlush:null,inFlightBarrierKeys:null,flushPromise:null,hasStaticPolicyUpdate:!1,removes:new Set,staticPolicy:null,touches:new Map,upserts:new Map,waiters:[]};return this.#i.set(t,r),r}#B(e){if(e.cancelFlush!==null||e.flushPromise!==null)return;let t=setTimeout(()=>{e.cancelFlush=null,this.flushPendingNamespaceCommit(e.scope)},40);e.cancelFlush=()=>clearTimeout(t)}#V(e){for(let[t,n]of this.#o)n!==e&&this.#o.delete(t)}#H(){this.#s||(this.#s=!0,v(()=>{this.#U().catch(()=>{})}))}async#U(){document.hidden&&await a(2e3),await re(`tsdf-async-storage-maintenance`,`[TSDF] navigator.locks is unavailable; async OPFS startup cleanup is using unlocked coordination.`,async()=>{let e=this.#C(),t=Date.now();e.lastSuccessfulCleanupAt!==null&&t-e.lastSuccessfulCleanupAt<432e5||(await this.#W(),this.#w({lastSuccessfulCleanupAt:Date.now()}))})}async#W(){await this.flushAllPendingNamespaceCommits();let e=await this.#ee(async e=>{let t=await this.#$(e),n=new Map;for(let e of t){let t=n.get(e.scope.sessionKey);t===void 0?n.set(e.scope.sessionKey,[e]):t.push(e)}return(await Promise.all([...n.entries()].map(async([t,n])=>this.#c(t,async()=>(await this.#d(t),this.#G(e,{discoveredScopes:n,sessionKey:t})))))).flat()});for(let t of e)this.#A(t),this.#L(t,`startup-cleanup`)}async#G(t,n={}){let r=e(t),i=n.discoveredScopes??await this.#$(t,n.sessionKey),a=Date.now(),o=[...new Set(i.map(({scope:e})=>e.sessionKey))],s=new Set(o.filter(e=>De(e))),c=new Map(o.map(e=>[e,M(e)])),l=Z.get(this)??new Map,u=new Map;for(let e of i){let t=Q(e.scope.sessionKey,e.scope.storeName),n=u.get(t);n===void 0?u.set(t,[e]):n.push(e)}let d=[];for(let[e,t]of u){let n=l.get(e);n!==void 0&&d.push({callback:n,scopes:t,storeKey:e})}let[f,p]=await Promise.all([Promise.all(d.map(({callback:e,scopes:n})=>e({discoveredScopes:n,driver:t,now:a}))),Promise.all(i.map(async({knownRecordKeys:e,scope:n})=>this.#Y({driver:t,knownRecordKeys:e,now:a,protectedRefs:c.get(n.sessionKey)??void 0,skipExpiration:s.has(n.sessionKey),scope:n})))]),m=new Map(p.map(e=>[y(e.scope),e])),h=[];for(let e of f){for(let t of e.scopePlans){let e=y(t.scope),n=m.get(e);m.set(e,this.#q(n??{deleteAction:null,persistEntries:null,scope:t.scope},{deleteAction:t.deleteKeys.length===0?null:this.#X({keys:t.deleteKeys,scope:t.scope}),persistEntries:t.persistEntries??null,persistStaticPolicy:t.persistStaticPolicy,scope:t.scope}))}for(let t of e.storeDeletePlans??[])h.push(t)}let g=[...m.values()],_=r.cleanupRemoveKnownStoreDir===void 0?[]:this.#J({customStoreDeletePlanStoreKeys:new Set(h.map(e=>Q(e.representativeScope.sessionKey,e.representativeScope.storeName))),discoveredScopesByStore:u,scopePlansByNamespaceId:m}),v=[...h,..._],b=[],x=new Map,S=new Set,C=new Set,w=new Set(_.flatMap(e=>e.removedKeysByScope.map(({scope:e})=>y(e))));if(r.cleanupRemoveKnownStoreDir!==void 0){let e=r.cleanupRemoveKnownStoreDir,t=await Promise.all(v.map(async t=>{let n=[...new Set(t.removedKeysByScope.flatMap(({keys:e})=>e))];return{removed:await e(t.representativeScope,n),storeDeletePlan:t}}));for(let{removed:e,storeDeletePlan:n}of t)if(e){for(let{keys:e,scope:t}of n.removedKeysByScope)r.cleanupFinalizeRemovedRecords?.(t,e);r.cleanupFinalizeRemovedStoreDir?.(n.representativeScope,[]),S.add(n.representativeScope.sessionKey);for(let{scope:e}of n.removedKeysByScope){let t=y(e);x.set(t,e),C.add(t),w.add(t)}}}let ee=await Promise.allSettled(g.flatMap(e=>w.has(y(e.scope))||e.deleteAction===null?[]:[this.#Z(r,e.deleteAction)]));for(let e of ee){if(e.status!==`fulfilled`)continue;let t=e.value;switch(t.kind){case`removeRecords`:{if(t.removedKeys.length>0&&(r.cleanupFinalizeRemovedRecords?.(t.action.scope,t.removedKeys),x.set(y(t.action.scope),t.action.scope)),!t.allSucceeded)continue;let e=m.get(y(t.action.scope));e!==void 0&&e.persistEntries!==null&&b.push({entries:e.persistEntries,staticPolicy:e.persistStaticPolicy,scope:e.scope});continue}case`removeStoreDir`:if(!t.removed)continue;r.cleanupFinalizeRemovedStoreDir?.(t.action.scope,t.action.keys),S.add(t.action.scope.sessionKey),C.add(y(t.action.scope));continue}}for(let e of g)w.has(y(e.scope))||e.deleteAction!==null||e.persistEntries===null||b.push({entries:e.persistEntries,staticPolicy:e.persistStaticPolicy,scope:e.scope});let T=[...S].flatMap(e=>this.#Q(r,g,C,e)?[{kind:`removeSessionDir`,sessionKey:e}]:[]),E=Promise.allSettled(T.map(e=>this.#Z(r,e))),D=Promise.all(b.map(async({entries:e,scope:n,staticPolicy:r})=>{e!==null&&await this.#h(t,n,{entries:e,staticPolicy:r===void 0?await this.#p(t,n):r})})),[O]=await Promise.all([E,D]);for(let{scope:e}of b)x.set(y(e),e);for(let e of O){if(e.status!==`fulfilled`)continue;let t=e.value;t.kind!==`removeSessionDir`||!t.removed||r.cleanupFinalizeRemovedSessionDir?.(t.action.sessionKey)}return[...x.values()]}#K(e,t){if(e===null)return t;if(t===null)return e;let n=new Map;for(let[r,i]of e.entries())t.has(r)&&n.set(r,i);return n.size>0?n:null}#q(e,t){let n=this.#K(e.persistEntries,t.persistEntries),r=e=>e!==null&&e.kind!==`removeSessionDir`?e.keys:[],i=[...new Set([...r(e.deleteAction),...r(t.deleteAction)])].filter(e=>n===null||e!==`_i`);return{deleteAction:i.length===0?null:this.#X({keys:i,scope:e.scope}),persistEntries:n,persistStaticPolicy:t.persistStaticPolicy===void 0?e.persistStaticPolicy:t.persistStaticPolicy,scope:e.scope}}#J(e){let t=[];for(let[n,r]of e.discoveredScopesByStore){if(e.customStoreDeletePlanStoreKeys.has(n))continue;let i=[],a=new Set,o=r.length>0;for(let t of r){let n=t.knownRecordKeys,r=e.scopePlansByNamespaceId.get(y(t.scope));if(n===null||r===void 0||r.persistEntries!==null||r.deleteAction===null){o=!1;break}let s=new Set(r.deleteAction.kind===`removeSessionDir`?[]:r.deleteAction.keys);if(!n.every(e=>s.has(e))){o=!1;break}for(let e of n)a.add(e);i.push({keys:[...s],scope:t.scope})}if(!o)continue;let s=new Set(i.flatMap(({keys:e})=>e));if(s.size!==a.size||[...a].some(e=>!s.has(e)))continue;let c=r[0]?.scope;c!==void 0&&t.push({removedKeysByScope:i,representativeScope:c})}return t}async#Y(e){let t=e.knownRecordKeys??await e.driver.listKeys(e.scope),n=await G(e.driver,e.scope,t),r=new Set,a=[];for(let e of t)e.startsWith(`__tsdf_payload__:`)?r.add(e.slice(17)):e!==`_i`&&a.push(e);if(!n.valid||n.entries===null){let r=t.filter(e=>e!==`_i`||n.exists);return{deleteAction:r.length===0?null:this.#X({keys:r,scope:e.scope}),persistEntries:null,persistStaticPolicy:null,scope:e.scope}}let o=new Map,s=E(n.staticPolicy),c=ze(e.scope,s),l=Be(e.scope,c),u=new Set(a),d=[];for(let[t,i]of n.entries.entries()){let n=V(i.customMetadata)||e.protectedRefs?.has($({...e.scope,key:t}))===!0;if(r.has(t)){if(!n&&!e.skipExpiration&&e.now-i.lastAccessAt>12096e5){u.add(C(t));continue}o.set(t,i),d.push({itemKey:t,lastAccessAt:i.lastAccessAt,protected:n,sizeBytes:i.sizeBytes??0})}}for(let e of r)n.entries.has(e)||u.add(C(e));if(l?.maxBytes!==void 0){let e=new Set(l.pinnedKeys??[]),t=F({entries:d,getKey:e=>e.itemKey,getLastAccessAt:e=>e.lastAccessAt,getSizeBytes:e=>e.sizeBytes,isPinned:t=>e.has(t.itemKey),isProtected:e=>e.protected,maxBytes:l.maxBytes});for(let{itemKey:e}of d)t.has(e)||(u.add(C(e)),o.delete(e))}let f=o.size!==n.entries.size||a.length>0||!i(s,c),p=[...u];return f&&o.size===0&&p.push(`_i`),{deleteAction:p.length===0?null:this.#X({keys:p,scope:e.scope}),persistEntries:f&&o.size>0?o:null,persistStaticPolicy:f&&o.size>0?c:void 0,scope:e.scope}}#X(e){return{kind:`removeRecords`,keys:[...new Set(e.keys)],scope:e.scope}}async#Z(e,t){switch(t.kind){case`removeRecords`:{let n=e.cleanupRemoveKnownRecords===void 0?await this.#S(e,t.scope,t.keys).then(()=>t.keys):await e.cleanupRemoveKnownRecords(t.scope,t.keys);return{action:t,allSucceeded:n.length===t.keys.length,kind:`removeRecords`,removedKeys:n}}case`removeStoreDir`:return{action:t,kind:`removeStoreDir`,removed:e.cleanupRemoveKnownStoreDir===void 0?!1:await e.cleanupRemoveKnownStoreDir(t.scope,t.keys)};case`removeSessionDir`:return{action:t,kind:`removeSessionDir`,removed:e.cleanupRemoveKnownSessionDir===void 0?!1:await e.cleanupRemoveKnownSessionDir(t.sessionKey)}}}#Q(e,t,n,r){if(e.cleanupRemoveKnownSessionDir===void 0)return!1;let i=t.filter(e=>e.scope.sessionKey===r);return i.length>0&&i.every(e=>n.has(y(e.scope)))}async#$(e,t){return(await e.listScopesWithKnownRecordKeys(t)).filter(({scope:e})=>e.kind!==`__internal.protected`)}async#ee(t){let n=e(this.driver);return typeof n.withIsolatedCleanupDriver==`function`?n.withIsolatedCleanupDriver(t):t(this.driver)}};function rt(e){return new nt(e)}function $(e){return w(e)}export{A,T as B,pe as C,ae as D,le as E,b as F,w as H,y as I,C as L,O as M,k as N,M as O,D as P,S as R,me as S,oe as T,v as U,x as V,F as _,Me as a,fe as b,G as c,tt as d,L as f,N as g,ye as h,rt as i,ne as j,ie as k,et as l,be as m,Te as n,Ee as o,I as p,Pe as r,U as s,R as t,$ as u,P as v,he as w,ue as x,ve as y,E as z};
@@ -0,0 +1,6 @@
1
+ import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-DkNgE_f9.js";
2
+
3
+ //#region src/persistentStorage/asyncStorageAdapter.d.ts
4
+ declare function createAsyncStorageAdapter(driver: AsyncStorageDriver): AsyncStorageAdapter;
5
+ //#endregion
6
+ export { createAsyncStorageAdapter as t };
@@ -0,0 +1 @@
1
+ import{t as e}from"./opfsPersistentStorage-DS-SWDSq.js";import{n as t}from"./indexedDbPersistentStorage-JYXvMjTG.js";export{t as indexedDbPersistentStorage,e as opfsPersistentStorage};
@@ -0,0 +1,12 @@
1
+ import { t as AsyncStorageAdapter } from "./types-DkNgE_f9.js";
2
+ //#region src/persistentStorage/indexedDbAsyncStorageAdapter.d.ts
3
+ type IndexedDbPersistentStorageOptions$1 = {
4
+ databaseName?: string;
5
+ };
6
+ //#endregion
7
+ //#region src/persistentStorage/indexedDbPersistentStorage.d.ts
8
+ declare const indexedDbPersistentStorage: AsyncStorageAdapter;
9
+ type IndexedDbPersistentStorageOptions = IndexedDbPersistentStorageOptions$1;
10
+ declare function createIndexedDbPersistentStorage(options?: IndexedDbPersistentStorageOptions): AsyncStorageAdapter;
11
+ //#endregion
12
+ export { type IndexedDbPersistentStorageOptions, createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./indexedDbPersistentStorage-JYXvMjTG.js";export{t as createIndexedDbPersistentStorage,e as indexedDbPersistentStorage};
@@ -0,0 +1 @@
1
+ import{B as e,F as t,H as n,I as r,L as i,P as a,R as o,V as s,a as c,i as l,v as u,z as d}from"./asyncStorageAdapter-CgG3vm0t.js";import{__LEGIT_CAST__ as f}from"@ls-stack/utils/saferTyping";import{isObject as p}from"@ls-stack/utils/typeGuards";const m=`entries`,h=`namespacePolicies`,g=`meta`,_=`maintenance`;function v(e){return[e.sessionKey,e.storeName,t(e.kind)]}function y(e,t){return[T(e.sessionKey,e.storeName,e.kind),t]}function b(e){return IDBKeyRange.bound(y(e,``),y(e,`￿`))}function x(e){let t=T(e.sessionKey,e.storeName,e.kind);return IDBKeyRange.bound([t,-(2**53-1)],[t,2**53-1])}function S(e,t){return IDBKeyRange.only([T(e.sessionKey,e.storeName,e.kind),t])}function C(e){return IDBKeyRange.only([T(e.sessionKey,e.storeName,e.kind),1])}function w(e){return v(e)}function T(e,t,n){return o({sessionKey:e,storeName:t,kind:n})}function E(e){if(!Array.isArray(e)||e.length<3)return null;let[t,n,r]=e;if(typeof t!=`string`||typeof n!=`string`)return null;let i=typeof r==`string`?s(r):null;return i===null?null:{kind:i,sessionKey:t,storeName:n}}function D(e){return!Array.isArray(e)||e.length<2?null:typeof e[1]==`string`?e[1]:null}function O(e){if(e===void 0)return{};let{g:t,o:n,p:r,...i}=e;return{...typeof t==`string`?{group:t}:{},...n===!0?{offlineProtected:!0}:{},...`p`in e?{payload:r}:{},...Object.keys(i).length>0?{extraMetadata:i}:{}}}function k(e){let t={...e.extraMetadata??{},...e.group===void 0?{}:{g:e.group},...e.offlineProtected===!0?{o:!0}:{},...e.payload===void 0?{}:{p:e.payload}};return Object.keys(t).length>0?t:void 0}function A(e){return k({extraMetadata:e.m,group:e.g,offlineProtected:e.o===1?!0:void 0,payload:e.p})}function j(e){let t=A(e);return{lastAccessAt:e.a,...typeof e.z==`number`?{sizeBytes:e.z}:{},version:e.v??1,...t?{customMetadata:t}:{}}}function M(e,t){return{customMetadata:A(t)??{},key:e,lastAccessAt:t.a,payloadRef:i(e),...typeof t.z==`number`?{sizeBytes:t.z}:{},version:t.v??1,writtenAt:t.a}}const N=new Set([`a`,`d`,`f`,`g`,`h`,`i`,`m`,`o`,`p`,`v`,`z`]),P=new Set([`p`,`s`]);function F(e){return f(e)}function I(e){return f(e)}function L(e){return f(e)}function R(e){if(e==null)return null;if(!p(e))return;let t=F(e);if(Object.keys(t).some(e=>e!==`b`&&e!==`k`))return;let n=t.b;if(n!==void 0&&(typeof n!=`number`||!Number.isInteger(n)||n<0))return;let r=t.k===void 0?void 0:B(t.k);if(r!==null)return d({...typeof t.b==`number`?{maxBytes:t.b}:{},...r===void 0?{}:{pinnedKeys:r}})}function z(e){let t=d(e);return t===null?null:{...t.maxBytes===void 0?{}:{b:t.maxBytes},...t.pinnedKeys!==void 0&&t.pinnedKeys.length>0?{k:t.pinnedKeys}:{}}}function B(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`string`)return null;t.push(n)}return t}function V(e){if(!p(e))return!1;let t=F(e);if(Object.keys(t).some(e=>!N.has(e)))return!1;let n=t.f;return typeof t.i==`string`&&typeof t.a==`number`&&`d`in t&&(t.v===void 0||typeof t.v==`number`)&&(t.z===void 0||typeof t.z==`number`)&&(t.m===void 0||p(t.m))&&(t.g===void 0||typeof t.g==`string`)&&(t.o===void 0||t.o===1)&&(n===void 0||n instanceof Array&&n.every(e=>typeof e==`string`))&&(t.h===void 0||t.h===1)}function H(e){if(!p(e))return!1;let t=F(e);return Object.keys(t).some(e=>!P.has(e))||typeof t.s!=`string`||!(`p`in t)?!1:t.p===null||R(t.p)!==void 0}function U(e){return e===void 0?null:R(e.p)??null}function W(e,t){return{d:t}}function G(e){return c({customMetadata:e.customMetadata,lastAccessAt:e.lastAccessAt,serializedValue:e.serializedValue??u(e.value).rawValue,version:e.version})}function K(e,t){return t.d}function q(e){return new Promise((t,n)=>{e.onsuccess=()=>t(f(e.result)),e.onerror=()=>n(e.error??Error(`IndexedDB request failed.`))})}function J(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??Error(`IndexedDB transaction failed.`)),e.onabort=()=>n(e.error??Error(`IndexedDB transaction aborted.`))})}async function Y(e,t){await new Promise((n,r)=>{e.onerror=()=>r(e.error??Error(`IndexedDB cursor request failed.`)),e.onsuccess=async()=>{let i=e.result;if(i===null){n();return}try{await t(i),i.continue()}catch(e){r(e instanceof Error?e:Error(`IndexedDB cursor callback failed.`))}}})}function X(e){return new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onerror=()=>n(r.error??Error(`IndexedDB deleteDatabase failed.`)),r.onblocked=()=>t(),r.onsuccess=()=>t()})}async function Z(e){let t=e.transaction(g,`readonly`),n=await q(t.objectStore(g).get(_));await J(t);let r=n?.v;if(!p(r))return{lastSuccessfulCleanupAt:null};let i=F(r);if(!(`lca`in i))return{lastSuccessfulCleanupAt:null};let a=i.lca;return{lastSuccessfulCleanupAt:typeof a==`number`||a===null?a:null}}async function Q(e,t){let n=e.transaction(g,`readwrite`);n.objectStore(g).put({k:_,v:{lca:t.lastSuccessfulCleanupAt}}),await J(n)}var ee=class{__tsdfManagedStorage={applyManagedCommit:this.applyManagedCommit.bind(this),clearManagedNamespace:this.clearManagedNamespace.bind(this),listManagedKeys:this.listManagedKeys.bind(this),listManagedMetadata:this.listManagedMetadata.bind(this),persistNamespaceIndexState:this.persistNamespaceIndexState.bind(this),readProtectedStorageKeys:this.readProtectedStorageKeys.bind(this),readManagedEntries:this.readManagedEntries.bind(this),readNamespaceIndexState:this.readNamespaceIndexState.bind(this),syncSessionProtectedKeys:this.syncSessionProtectedKeys.bind(this)};#e=null;constructor(e=`tsdf-persistent-storage-compact-alpha-reset`,t=void 0){this.databaseName=e,this.instrumentation=t}async get(t,n){let r=e(n);if(r.recordKind===`payload`){let e=await this.#t(t,r.userKey);return e===null?null:K(t,e)}if(r.rawKey!==`_i`)return null;let i=await this.readNamespaceIndexState(t);return!i.exists||!i.valid||i.entries===null?null:{e:Object.fromEntries([...i.entries.entries()].map(([e,t])=>[e,{a:t.lastAccessAt,...t.version===1?{}:{v:t.version},...t.sizeBytes===void 0?{}:{z:t.sizeBytes},...t.customMetadata??{}}])),...i.staticPolicy===null?{}:{s:i.staticPolicy}}}async set(e,t,n){await this.setMany(e,[{key:t,value:n}])}async remove(e,t){await this.removeMany(e,[t])}async getMany(e,t){return Promise.all(t.map(t=>this.get(e,t)))}async setMany(t,n){for(let r of n){let n=e(r.key);if(n.recordKind===`payload`){let e=await this.#t(t,n.userKey),i=e?.a??Date.now();await this.#n(t,{customMetadata:e===null?void 0:A(e),key:n.userKey,lastAccessAt:i,value:r.value,version:e?.v??1});continue}if(n.rawKey===`_i`){let e=this.#r(r.value);e!==null&&await this.persistNamespaceIndexState(t,e)}}}async removeMany(t,n){let r=(await this.#i()).transaction([m,h],`readwrite`),i=r.objectStore(m),a=r.objectStore(h),o=!1,s=!1;for(let r of n){let n=e(r);if(n.recordKind===`payload`){i.delete(y(t,n.userKey)),o=!0;continue}n.rawKey===`_i`&&(a.delete(w(t)),s=!0)}if(o&&!s){let e=i.count(b(t));e.onsuccess=()=>{e.result===0&&a.delete(w(t))}}await J(r),this.instrumentation?.onRemoveMany?.(t,n),this.instrumentation?.record({keys:[...n].sort((e,t)=>e.localeCompare(t)),scope:t,time:Date.now(),type:`removeManagedRecords`})}async listKeys(e){let t=await this.readNamespaceIndexState(e);if(!t.exists||t.entries===null)return[];let n=[...t.entries.keys()].map(e=>i(e));return n.push(`_i`),n.sort((e,t)=>e.localeCompare(t))}async clear(e){await this.clearManagedNamespace(e)}async listScopes(e){return(await this.listScopesWithKnownRecordKeys(e)).map(({scope:e})=>e)}async listScopesWithKnownRecordKeys(e){let t=(await this.#i()).transaction([m,h],`readonly`),n=t.objectStore(m),a=t.objectStore(h),o=[];return await Y(e===void 0?a.openCursor():a.index(`bySession`).openCursor(IDBKeyRange.only(e)),async e=>{let t=E(e.primaryKey);if(t===null)return;let r=new Set([`_i`]);await Y(n.openCursor(b(t)),e=>{let t=D(e.primaryKey);t!==null&&r.add(i(t))}),o.push({knownRecordKeys:[...r].sort((e,t)=>e.localeCompare(t)),scope:t})}),await J(t),o.sort((e,t)=>r(e.scope).localeCompare(r(t.scope))),this.instrumentation?.record({scopeIds:o.map(({scope:e})=>r(e)),...e===void 0?{}:{sessionKey:e},time:Date.now(),type:`listScopesWithKnownRecordKeys`}),o}async readManagedEntries(e,t){let n=(await this.#i()).transaction(m,`readonly`),r=n.objectStore(m),i=[...new Set(t)],a=new Map;return await Promise.all(i.map(async t=>{let n=await q(r.get(y(e,t)));if(!V(n)){a.set(t,null);return}let i=I(n);a.set(t,{metadata:M(t,i),value:f(K(e,i))})})),await J(n),this.instrumentation?.record({keys:i,resultKeys:[...a.entries()].flatMap(([e,t])=>t===null?[]:[e]).sort((e,t)=>e.localeCompare(t)),scope:e,time:Date.now(),type:`readManagedEntries`}),a}async listManagedMetadata(e,t={}){let n=t.order??`key`,r=(await this.#i()).transaction(m,`readonly`),i=r.objectStore(m),o=[],s=`key`;t.filter?.key===`g`&&typeof t.filter.equals==`string`&&n===`key`?(s=`group`,await Y(i.index(`byScopeGroup`).openCursor(S(e,t.filter.equals)),e=>{let t=e.value,n=D(e.primaryKey);!V(t)||n===null||o.push(M(n,I(t)))})):n===`lru-asc`||n===`lru-desc`?(s=`lru`,await Y(i.index(`byScopeLastAccessAt`).openCursor(x(e),n===`lru-desc`?`prev`:`next`),e=>{let t=e.value,n=D(e.primaryKey);!V(t)||n===null||o.push(M(n,I(t)))})):await Y(i.openCursor(b(e)),e=>{let t=e.value,n=D(e.primaryKey);!V(t)||n===null||o.push(M(n,I(t)))}),await J(r);let c=t.filter,l=c===void 0?o:o.filter(e=>e.customMetadata[c.key]===c.equals);return s!==`lru`&&l.sort((e,t)=>a(e,t,n)),this.instrumentation?.record({order:n,resultKeys:l.map(e=>e.key),scope:e,time:Date.now(),type:`listManagedMetadata`,usedIndex:s}),l}async listManagedKeys(e){return(await this.listManagedMetadata(e,{order:`key`})).map(e=>e.key)}async clearManagedNamespace(e){let t=(await this.#i()).transaction([m,h],`readwrite`),n=t.objectStore(m),r=t.objectStore(h);await Y(n.openCursor(b(e)),e=>{e.delete()}),r.delete(w(e)),await J(t),this.instrumentation?.onClearManagedNamespace?.(e),this.instrumentation?.record({scope:e,time:Date.now(),type:`clearManagedNamespace`})}async applyManagedCommit(e,t,n){let r=(await this.#i()).transaction([m,h],`readwrite`),i=r.objectStore(m),a=r.objectStore(h),o=t.upserts??[],s=[...new Set(t.removes??[])],c=t.touches??[],l=T(e.sessionKey,e.storeName,e.kind),u=[...new Set([...s,...c.map(e=>e.key),...o.map(e=>e.key)])],f=new Map,p=Date.now(),g=new Map(c.map(e=>[e.key,e.lastAccessAt??p])),_=await q(a.get(w(e))),v=H(_)?U(L(_)):null;await Promise.all(u.map(async t=>{let n=await q(i.get(y(e,t)));V(n)&&f.set(t,I(n))}));for(let t of s)i.delete(y(e,t));let x=new Set(o.map(e=>e.key));for(let t of o){let r=f.get(t.key),a=n.mergeOfflineProtectionMetadata(t.key,t.metadata,r===void 0?void 0:A(r)),{extraMetadata:o,group:s,offlineProtected:c,payload:u}=O(a),d=g.get(t.key)??r?.a??p,m=e.kind===`document`?void 0:G({customMetadata:a,lastAccessAt:d,serializedValue:t.serializedValue,value:t.value,version:t.version}),h=W(e,t.value);await q(i.put({a:d,...h,...s===void 0?{}:{g:s},i:l,...o===void 0?{}:{m:o},...c===!0?{o:1}:{},...u===void 0?{}:{p:u},...t.version===1?{}:{v:t.version},...m===void 0?{}:{z:m}},y(e,t.key)))}for(let t of c){if(x.has(t.key))continue;let n=f.get(t.key);if(n===void 0)continue;let r=t.lastAccessAt??p;n.a!==r&&await q(i.put({...n,a:r},y(e,t.key)))}let S=`staticPolicy`in t?d(t.staticPolicy):void 0;await q(i.count(b(e)))===0?a.delete(w(e)):await q(a.put({p:z(S??v),s:e.sessionKey},w(e))),await J(r),this.instrumentation?.onApplyManagedCommit?.(e,t),this.instrumentation?.record({removes:s,scope:e,staticPolicyChanged:`staticPolicy`in t,time:Date.now(),touches:c.map(e=>e.key).sort((e,t)=>e.localeCompare(t)),type:`applyManagedCommit`,upserts:o.map(e=>e.key).sort((e,t)=>e.localeCompare(t))})}async readNamespaceIndexState(e,t){let n=(await this.#i()).transaction([m,h],`readonly`),r=n.objectStore(m),i=n.objectStore(h),a=new Map,o=0;await Y(r.openCursor(b(e)),e=>{let t=e.value,n=D(e.primaryKey);if(!V(t)){o+=1;return}if(n===null){o+=1;return}a.set(n,j(I(t)))});let s=await q(i.get(w(e)));if(await J(n),o>0){let t={entries:null,exists:a.size>0||s!==void 0,staticPolicy:null,valid:!1};return this.instrumentation?.record({exists:t.exists,keyCount:a.size,scope:e,time:Date.now(),type:`readManagedIndexState`,valid:t.valid}),t}if(s!==void 0&&!H(s)){let t={entries:null,exists:!0,staticPolicy:null,valid:!1};return this.instrumentation?.record({exists:t.exists,keyCount:a.size,scope:e,time:Date.now(),type:`readManagedIndexState`,valid:t.valid}),t}let c=s!==void 0||a.size>0;if(s===void 0&&a.size>0||s!==void 0&&a.size===0){let t={entries:null,exists:c,staticPolicy:null,valid:!1};return this.instrumentation?.record({exists:t.exists,keyCount:a.size,scope:e,time:Date.now(),type:`readManagedIndexState`,valid:t.valid}),t}let l={entries:a,exists:s!==void 0,staticPolicy:U(s===void 0?void 0:L(s)),valid:!0};return this.instrumentation?.record({exists:l.exists,keyCount:l.entries.size,scope:e,time:Date.now(),type:`readManagedIndexState`,valid:l.valid}),l}async persistNamespaceIndexState(e,t){let n=await this.#i(),r=new Map,i=n.transaction(m,`readonly`),a=i.objectStore(m),o=[...t.entries.keys()];await Promise.all(o.map(async t=>{let n=await q(a.get(y(e,t)));V(n)&&r.set(t,I(n))})),await J(i);let s=n.transaction([m,h],`readwrite`),c=s.objectStore(m),l=s.objectStore(h);for(let[n,i]of t.entries.entries()){let t=r.get(n);if(t===void 0)continue;let{extraMetadata:a,group:o,offlineProtected:s,payload:l}=O(i.customMetadata);c.put({...t,a:i.lastAccessAt,...o===void 0?{}:{g:o},...o===void 0?{g:void 0}:{},...a===void 0?{}:{m:a},...a===void 0?{m:void 0}:{},...s===!0?{o:1}:{},...s===!0?{}:{o:void 0},...l===void 0?{}:{p:l},...l===void 0?{p:void 0}:{},...i.version===1?{}:{v:i.version},...i.version===1?{v:void 0}:{},...i.sizeBytes===void 0?{}:{z:i.sizeBytes},...i.sizeBytes===void 0?{z:void 0}:{}},y(e,n))}t.entries.size===0?l.delete(w(e)):l.put({p:z(t.staticPolicy),s:e.sessionKey},w(e)),await J(s),this.instrumentation?.onPersistNamespaceIndexState?.(e,t),this.instrumentation?.record({keyCount:t.entries.size,scope:e,staticPolicy:t.staticPolicy,time:Date.now(),type:`persistManagedIndexState`})}async readProtectedStorageKeys(e){let t=(await this.#i()).transaction([m,h],`readonly`),r=t.objectStore(m),i=t.objectStore(h),a=[];return await Y(i.index(`bySession`).openCursor(IDBKeyRange.only(e)),async e=>{let t=E(e.primaryKey);t!==null&&await Y(r.index(`byScopeOfflineProtected`).openCursor(C(t)),e=>{let r=D(e.primaryKey),i=e.value;!V(i)||r===null||a.push(n({...t,key:r}))})}),await J(t),this.instrumentation?.record({sessionKey:e,time:Date.now(),type:`readProtectedStorageKeys`,values:[...a].sort((e,t)=>e.localeCompare(t))}),a}async syncSessionProtectedKeys(e,t){let r=new Set(t),i=(await this.#i()).transaction([m,h],`readwrite`),a=i.objectStore(m);await Y(i.objectStore(h).index(`bySession`).openCursor(IDBKeyRange.only(e)),async e=>{let t=E(e.primaryKey);t!==null&&await Y(a.openCursor(b(t)),e=>{let i=e.value,a=D(e.primaryKey);if(!V(i)||a===null)return;let o=I(i),s=n({...t,key:a}),c=r.has(s);if(o.o===1===c)return;let l={...o,...c?{o:1}:{o:void 0}};e.update(l)})}),await J(i),this.instrumentation?.record({sessionKey:e,time:Date.now(),type:`syncSessionProtectedKeys`,values:[...r].sort((e,t)=>e.localeCompare(t))})}async readMaintenanceState(){return Z(await this.#i())}async writeMaintenanceState(e){await Q(await this.#i(),e)}async __resetForTests(){this.#e!==null&&((await this.#e).close(),this.#e=null),await X(this.databaseName),this.instrumentation?.reset()}async __inspectStructureForTests(){let e=await this.#i(),t=[];for(let n of[...e.objectStoreNames].sort((e,t)=>e.localeCompare(t))){let r=e.transaction(n,`readonly`),i=r.objectStore(n),a=[...i.indexNames].sort((e,t)=>e.localeCompare(t)).map(e=>{let t=i.index(e);return{keyPath:t.keyPath,multiEntry:t.multiEntry,name:t.name,unique:t.unique}}),[o,s]=await Promise.all([q(i.getAllKeys()),q(i.getAll())]);await J(r),t.push({autoIncrement:i.autoIncrement,indexes:a,keyPath:i.keyPath,name:n,rows:o.map((e,t)=>({key:e,value:s[t]}))})}return{stores:t,version:e.version}}async#t(e,t){let n=(await this.#i()).transaction(m,`readonly`),r=await q(n.objectStore(m).get(y(e,t)));return await J(n),V(r)?I(r):null}async#n(e,t){let n=(await this.#i()).transaction([m,h],`readwrite`),r=n.objectStore(m),i=n.objectStore(h),a=await q(i.get(w(e))),{extraMetadata:o,group:s,offlineProtected:c,payload:l}=O(t.customMetadata),u=e.kind===`document`?void 0:G({customMetadata:t.customMetadata,lastAccessAt:t.lastAccessAt,value:t.value,version:t.version}),d=W(e,t.value);r.put({a:t.lastAccessAt,...d,...s===void 0?{}:{g:s},i:T(e.sessionKey,e.storeName,e.kind),...o===void 0?{}:{m:o},...c===!0?{o:1}:{},...l===void 0?{}:{p:l},...t.version===1?{}:{v:t.version},...u===void 0?{}:{z:u}},y(e,t.key)),i.put({p:z(U(H(a)?L(a):void 0)),s:e.sessionKey},w(e)),await J(n)}#r(e){if(!p(e))return null;let t=F(e),n=t.e;if(!p(n))return null;let r=F(n),i=new Map;for(let[e,t]of Object.entries(r)){if(!p(t))return null;let n=F(t);if(typeof n.a!=`number`)return null;let r=Object.fromEntries(Object.entries(n).filter(([e])=>e!==`a`&&e!==`v`&&e!==`z`));i.set(e,{...Object.keys(r).length>0?{customMetadata:r}:{},lastAccessAt:n.a,...typeof n.z==`number`?{sizeBytes:n.z}:{},version:typeof n.v==`number`?n.v:1})}let a=R(t.s);return a===void 0?null:{entries:i,staticPolicy:a}}async#i(){return this.#e===null&&(this.#e=new Promise((e,t)=>{let n=indexedDB.open(this.databaseName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(m)&&e.deleteObjectStore(m),e.objectStoreNames.contains(h)&&e.deleteObjectStore(h);let t=e.createObjectStore(m);t.createIndex(`byScopeLastAccessAt`,[`i`,`a`],{unique:!1}),t.createIndex(`byScopeGroup`,[`i`,`g`],{unique:!1}),t.createIndex(`byScopeOfflineProtected`,[`i`,`o`],{unique:!1}),e.createObjectStore(h).createIndex(`bySession`,`s`,{unique:!1}),e.objectStoreNames.contains(g)||e.createObjectStore(g,{keyPath:`k`})},n.onerror=()=>t(n.error??Error(`IndexedDB open failed.`)),n.onsuccess=()=>e(n.result)})),this.#e}};function $(e={}){return l(new ee(e.databaseName))}const te=$();function ne(e={}){return $(e)}export{te as n,ne as t};