tsdf 17.0.0-alpha.8 → 17.0.0-beta.0
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/dist/async-storage.d.ts +1 -1
- package/dist/async-storage.js +2 -1
- package/dist/asyncStorageAdapter-CGfnsd9m.js +1945 -0
- package/dist/{asyncStorageAdapter-kvAIhrBD.d.ts → asyncStorageAdapter-CMohMeKm.d.ts} +1 -1
- package/dist/asyncStorageAdapters-BpfM2_Y6.js +3 -0
- package/dist/indexed-db-storage.d.ts +4 -2
- package/dist/indexed-db-storage.js +2 -1
- package/dist/indexedDbPersistentStorage-DC9GsYHH.js +954 -0
- package/dist/main.d.ts +355 -414
- package/dist/main.js +16046 -1
- package/dist/opfs-storage.d.ts +1 -1
- package/dist/opfs-storage.js +2 -1
- package/dist/{opfsPersistentStorage-D_fecOJg.d.ts → opfsPersistentStorage-Ci0JcCo5.d.ts} +1 -1
- package/dist/opfsPersistentStorage-DqJXzF7M.js +892 -0
- package/dist/{types-DkNgE_f9.d.ts → types-D0ttVGmj.d.ts} +395 -65
- package/docs/README.md +16 -16
- package/docs/batch-fetching.md +1 -1
- package/docs/browser-tabs-sync.md +5 -2
- package/docs/collection-store.md +26 -24
- package/docs/document-store.md +8 -6
- package/docs/fetch-scheduling.md +18 -14
- package/docs/list-query-store.md +37 -35
- package/docs/mutations.md +2 -0
- package/docs/offline.md +2 -2
- package/docs/offset-pagination.md +1 -4
- package/docs/optimistic-list-updates.md +13 -17
- package/docs/partial-resources.md +26 -1
- package/docs/persistent-storage.md +4 -2
- package/docs/real-time-updates.md +7 -5
- package/docs/store-manager.md +41 -14
- package/package.json +6 -3
- package/dist/asyncStorageAdapter-CgG3vm0t.js +0 -1
- package/dist/asyncStorageAdapters-eagaD77Y.js +0 -1
- package/dist/indexedDbPersistentStorage-JYXvMjTG.js +0 -1
- package/dist/opfsPersistentStorage-DS-SWDSq.js +0 -1
|
@@ -8,16 +8,16 @@ TSDF has built-in support for real-time data sources like WebSockets or Server-S
|
|
|
8
8
|
const storeManager = createStoreManager({
|
|
9
9
|
getSessionKey: () => currentTenantId ?? false,
|
|
10
10
|
errorNormalizer: normalizeError,
|
|
11
|
+
dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) => {
|
|
12
|
+
if (windowIsNotFocused) return lastFetchDuration * 10;
|
|
13
|
+
return lastFetchDuration * 2;
|
|
14
|
+
},
|
|
11
15
|
});
|
|
12
16
|
|
|
13
17
|
const store = createDocumentStore<Data>({
|
|
14
18
|
id: 'document-data',
|
|
15
19
|
storeManager,
|
|
16
20
|
usesRealTimeUpdates: true,
|
|
17
|
-
dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) => {
|
|
18
|
-
if (windowIsNotFocused) return lastFetchDuration * 10;
|
|
19
|
-
return lastFetchDuration * 2;
|
|
20
|
-
},
|
|
21
21
|
// ...other options
|
|
22
22
|
});
|
|
23
23
|
```
|
|
@@ -77,7 +77,7 @@ websocket.on('task-changed', ({ taskId }) => {
|
|
|
77
77
|
|
|
78
78
|
## Adaptive Throttling
|
|
79
79
|
|
|
80
|
-
The `dynamicRealtimeThrottleMs` function controls how often real-time invalidations trigger actual fetches. It receives the duration of the last fetch and whether the window is focused:
|
|
80
|
+
The `dynamicRealtimeThrottleMs` function controls how often real-time invalidations trigger actual fetches. TSDF defaults to `100ms` while focused and `1000ms` while the window is in the background. Configure it once on `createStoreManager(...)` to share a custom default across stores, or on an individual store to override the manager default. It receives the duration of the last fetch and whether the window is focused:
|
|
81
81
|
|
|
82
82
|
```ts
|
|
83
83
|
dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) => {
|
|
@@ -90,6 +90,8 @@ dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) => {
|
|
|
90
90
|
|
|
91
91
|
This prevents the UI from being overwhelmed by rapid updates while keeping data fresh.
|
|
92
92
|
|
|
93
|
+
When the window regains focus, any refetch still waiting on the background throttle is re-evaluated with the focused throttle: it fires immediately if the focused interval has already elapsed, or is rescheduled to the shorter focused delay. Returning to a tab never has to wait out the rest of a long background window.
|
|
94
|
+
|
|
93
95
|
## Transport Reconnection
|
|
94
96
|
|
|
95
97
|
When your WebSocket or SSE connection drops and reconnects, events may have been missed. Call the manager-level `onTransportReconnect()` once for the shared transport:
|
package/docs/store-manager.md
CHANGED
|
@@ -16,8 +16,11 @@ const storeManager = createStoreManager({
|
|
|
16
16
|
id: 'unknown-error',
|
|
17
17
|
message: error.message,
|
|
18
18
|
}),
|
|
19
|
-
lowPriorityThrottleMs:
|
|
20
|
-
baseCoalescingWindowMs:
|
|
19
|
+
lowPriorityThrottleMs: 40 * 60 * 1_000,
|
|
20
|
+
baseCoalescingWindowMs: 16,
|
|
21
|
+
backgroundCoalescingDelayMs: 3_000,
|
|
22
|
+
dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) =>
|
|
23
|
+
windowIsNotFocused ? lastFetchDuration * 10 : lastFetchDuration * 2,
|
|
21
24
|
blockWindowClose: null,
|
|
22
25
|
revalidateOnWindowFocus: true,
|
|
23
26
|
onMutationError: (error) => {
|
|
@@ -26,29 +29,53 @@ const storeManager = createStoreManager({
|
|
|
26
29
|
onPersistentStorageError: (error) => {
|
|
27
30
|
console.error('TSDF persistence failed', error);
|
|
28
31
|
},
|
|
32
|
+
debugLogger: true,
|
|
29
33
|
});
|
|
30
34
|
```
|
|
31
35
|
|
|
32
36
|
Options:
|
|
33
37
|
|
|
34
|
-
| Option
|
|
35
|
-
|
|
|
36
|
-
| `getSessionKey`
|
|
37
|
-
| `errorNormalizer`
|
|
38
|
-
| `lowPriorityThrottleMs`
|
|
39
|
-
| `baseCoalescingWindowMs`
|
|
40
|
-
| `
|
|
41
|
-
| `
|
|
42
|
-
| `
|
|
43
|
-
| `
|
|
44
|
-
| `
|
|
38
|
+
| Option | Required | Description |
|
|
39
|
+
| ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
40
|
+
| `getSessionKey` | Yes | Returns the active tenant/account key. Return `false` while no session is ready. |
|
|
41
|
+
| `errorNormalizer` | Yes | Converts thrown `Error` values into TSDF's shared `StoreError` shape. |
|
|
42
|
+
| `lowPriorityThrottleMs` | No | Default minimum interval between low-priority fetches for attached stores. Defaults to 40 minutes (`2_400_000ms`). |
|
|
43
|
+
| `baseCoalescingWindowMs` | No | Default window to group fetch requests for attached stores. Defaults to `16ms`. |
|
|
44
|
+
| `backgroundCoalescingDelayMs` | No | Extra browser-tab coalescing delay applied only while a tab is in the background. Defaults to `3000ms`. |
|
|
45
|
+
| `dynamicRealtimeThrottleMs` | No | Default adaptive throttle for real-time updates in attached stores. Defaults to `100ms` focused and `1000ms` in the background. Store options override it. |
|
|
46
|
+
| `blockWindowClose` | No | Shared window-close blocker for mutations in attached stores. Defaults to `null`. |
|
|
47
|
+
| `revalidateOnWindowFocus` | No | Default focus revalidation policy for attached stores. Store options override it. |
|
|
48
|
+
| `onMutationError` | No | Global fallback for mutation failures when a store does not provide its own handler. |
|
|
49
|
+
| `onPersistentStorageError` | No | Global fallback for persistent storage failures when a store does not provide its own handler. |
|
|
50
|
+
| `debugLogger` | No | Enables verbose development-only browser-tab sync, focus revalidation, and persistent-storage debug logs. Pass `true` or a logger function. |
|
|
51
|
+
| `logger` | No | Enables low-volume production-safe logs such as persistent-storage quota cleanup. Defaults to console logging; pass `false` to disable or a function to customize. |
|
|
52
|
+
| `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
|
|
45
53
|
|
|
46
54
|
The session key is used by browser-tab sync, persistent storage, and offline state. Stores with the same `id` but different session keys are isolated.
|
|
47
55
|
|
|
48
|
-
Stores inherit the manager's `lowPriorityThrottleMs` and `
|
|
56
|
+
Stores inherit the manager's `lowPriorityThrottleMs`, `baseCoalescingWindowMs`, and `dynamicRealtimeThrottleMs` unless they provide their own store-level overrides. `backgroundCoalescingDelayMs` and `blockWindowClose` are manager-only so browser-tab background coordination and window-close mutation protection stay consistent across attached stores. The built-in `dynamicRealtimeThrottleMs` default returns `100ms` while focused and `1000ms` while the window is in the background.
|
|
49
57
|
|
|
50
58
|
Store-level options can explicitly disable inherited defaults when the option supports disabling: use `revalidateOnWindowFocus: false`, `onMutationError: null`, or `persistentStorage.onPersistentStorageError: null`.
|
|
51
59
|
|
|
60
|
+
## Debug Logging
|
|
61
|
+
|
|
62
|
+
Pass `debugLogger: true` to log browser-tab sync operations, focus revalidation decisions, and persistent-storage operations through `console.log`, `console.warn`, and `console.error` in development. Browser-tab sync logs include lifecycle, leader changes, publish/receive events, and skipped messages. Focus revalidation logs report when `revalidateOnWindowFocus` triggers, is dynamically disabled, or is skipped because real-time updates own freshness. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Async persistent storage adapters emit timed `adapter-operation` entries with `durationMs` so slow OPFS, IndexedDB, or custom driver paths can be inspected.
|
|
63
|
+
|
|
64
|
+
Low-volume production-safe signals are logged by default through `console.log`, `console.warn`, and `console.error`. Today this includes persistent-storage `quota-cleanup` entries. Pass `logger: false` to disable them, or pass a function to route them to your own tooling.
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const storeManager = createStoreManager({
|
|
68
|
+
getSessionKey: () => currentTenantId ?? false,
|
|
69
|
+
errorNormalizer: normalizeError,
|
|
70
|
+
debugLogger: ({ level, message, details }) => {
|
|
71
|
+
observability[level](message, details);
|
|
72
|
+
},
|
|
73
|
+
logger: ({ level, message, details }) => {
|
|
74
|
+
observability[level](message, details);
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
52
79
|
## Store Registry
|
|
53
80
|
|
|
54
81
|
The manager tracks attached stores:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tsdf",
|
|
3
|
-
"version": "17.0.0-
|
|
3
|
+
"version": "17.0.0-beta.0",
|
|
4
4
|
"description": "A data fetching solution based on t-state",
|
|
5
5
|
"license": "PolyForm-Noncommercial-1.0.0",
|
|
6
6
|
"author": "Lucas Santos",
|
|
@@ -92,11 +92,14 @@
|
|
|
92
92
|
"test:playwright": "playwright test",
|
|
93
93
|
"test:coverage": "vitest run --coverage",
|
|
94
94
|
"test:all": "vitest --run && playwright test",
|
|
95
|
-
"lint": "pnpm
|
|
95
|
+
"lint": "pnpm lint:lib && pnpm --filter @tsdf/playground lint",
|
|
96
|
+
"lint:lib": "pnpm tsc && pnpm tsc:isolated && pnpm eslint",
|
|
96
97
|
"eslint": "eslint src/ tests/ --fix",
|
|
97
|
-
"format": "oxfmt src/ tests/",
|
|
98
|
+
"format": "oxfmt src/ tests/ apps/playground/src/",
|
|
98
99
|
"tsc": "tsgo -p tsconfig.prod.json && tsgo -p tsconfig.playwright-fixture.json",
|
|
99
100
|
"tsc:isolated": "tsgo -p tsconfig.isolated.json",
|
|
101
|
+
"dev": "pnpm --filter @tsdf/playground dev",
|
|
102
|
+
"playground:build": "pnpm --filter @tsdf/playground build",
|
|
100
103
|
"build": "pnpm lint && pnpm test:all && pnpm build:no-test",
|
|
101
104
|
"build:no-test": "tsdown",
|
|
102
105
|
"pre-publish": "pnpm build",
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{B as e,F as t,I as n,L as r,V as i,i as a}from"./asyncStorageAdapter-CgG3vm0t.js";import{getCompositeKey as o}from"@ls-stack/utils/getCompositeKey";import{__LEGIT_CAST__ as s}from"@ls-stack/utils/saferTyping";import{isObject as c}from"@ls-stack/utils/typeGuards";import{createCache as l}from"@ls-stack/utils/cache";import{asPossiblyUndefined as u}from"@ls-stack/utils/typingFnUtils";import{murmur3 as d}from"@ls-stack/utils/hash";const f=`tsdf`,p=`.json`;function m(e){switch(e){case`collection.item`:case`listQuery.item`:case`listQuery.query`:return!0;default:return!1}}function h(e){return encodeURIComponent(e)}function g(e){return decodeURIComponent(e)}function _(e){return h(e).replaceAll(`.`,`%2E`)}function v(...e){return e.filter(e=>e.length>0).join(`/`)}function y(e){switch(e){case`payload`:return`p`;case`raw`:return`r`}}function b(e){switch(e){case`p`:return`payload`;case`r`:return`raw`;default:return null}}function x(e,t){return e.kind===`document`&&t===`d`?`e`:_(t)}function S(e,t){return e===`document`&&t===`e`?`d`:g(t)}function C(t){return e(t)}function w(e,t){switch(e){case`payload`:return r(t);case`raw`:return t}}function T(e,n){let r=C(n),i=t(e.kind);return r.recordKind===`raw`?[i,_(r.rawKey),y(`raw`)].join(`.`)+p:[i,m(e.kind)?`h~${d(n,`uint32`)}`:x(e,r.userKey),y(`payload`)].join(`.`)+p}function E(e,t){if(!m(e.kind)||!c(t))return null;let n=t;if(!(`p`in n))return null;switch(e.kind){case`collection.item`:case`listQuery.item`:case`listQuery.query`:return r(o(n.p));default:return null}}function D(e){if(!e.endsWith(p))return null;let t=e.slice(0,-5).split(`.`);if(t.length!==3)return null;let n=t[0]??``,r=t[1]??``,a=t[2]??``,o=i(n);if(o===null)return null;let s=b(a);return s===null?null:s===`payload`&&m(o)&&r.startsWith(`h~`)?{kind:o,key:null,isHashedPayload:!0}:{kind:o,key:s===`raw`?g(r):w(s,S(o,r)),isHashedPayload:!1}}async function O(){let e=u(globalThis.navigator)?.storage;if(e?.getDirectory===void 0)throw Error(`[TSDF] OPFS is unavailable in this environment.`);return e.getDirectory()}async function k(e,t){try{return await e.getDirectoryHandle(t)}catch{return null}}async function A(e,t){try{return await e.getFileHandle(t)}catch{return null}}const j=a(new class{#e=null;#t={cleanupKnowledge:null,dirCache:l({maxCacheSize:500}),fileCache:l({maxCacheSize:1e4}),readValueCache:null};async get(e,t){let[n]=await this.getMany(e,[t]);return n??null}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 this.#r(e,t,this.#t)}async setMany(e,t){await this.#i(e,t,this.#t)}async removeMany(e,t){await this.#a(e,t,this.#t)}async listKeys(e){return this.#o(e,this.#t)}async clear(e){await this.#s(e,this.#t)}async listScopes(e){return this.#c(e,this.#t)}async listScopesWithKnownRecordKeys(e){return this.#l(e,this.#t)}async withIsolatedCleanupDriver(e){let t={cleanupKnowledge:{knownRemainingEntryCountByStorePath:new Map,knownStorePathsBySessionPath:new Map},dirCache:this.#t.dirCache.clone(),fileCache:this.#t.fileCache.clone(),readValueCache:new Map};return e(this.#n(t))}async cleanupRemoveKnownRecords(e,t){return this.#T(e,t,this.#t)}async cleanupRemoveKnownStoreDir(e,t){return this.#E(e,t,this.#t)}async cleanupRemoveKnownSessionDir(e){return this.#D(e,this.#t)}cleanupFinalizeRemovedRecords(e,t){this.#O(e,t,this.#t)}cleanupFinalizeRemovedStoreDir(e,t){this.#k(e,t,this.#t)}cleanupFinalizeRemovedSessionDir(e){this.#A(e,this.#t)}__resetForTests(){this.#e=null,this.#t.dirCache.clear(),this.#t.fileCache.clear()}#n(e){return{cleanupFinalizeRemovedRecords:(t,n)=>this.#O(t,n,e),cleanupFinalizeRemovedSessionDir:t=>this.#A(t,e),cleanupFinalizeRemovedStoreDir:(t,n)=>this.#k(t,n,e),cleanupRemoveKnownRecords:(t,n)=>this.#T(t,n,e),cleanupRemoveKnownSessionDir:t=>this.#D(t,e),cleanupRemoveKnownStoreDir:(t,n)=>this.#E(t,n,e),get:(t,n)=>this.#r(t,[n],e).then(([e])=>e??null),set:(t,n,r)=>this.#i(t,[{key:n,value:r}],e),remove:(t,n)=>this.#a(t,[n],e),listKeys:t=>this.#o(t,e),clear:t=>this.#s(t,e),listScopes:t=>this.#c(t,e),listScopesWithKnownRecordKeys:t=>this.#l(t,e),getMany:(t,n)=>this.#r(t,n,e),setMany:(t,n)=>this.#i(t,n,e),removeMany:(t,n)=>this.#a(t,n,e)}}async#r(e,t,n){if(t.length===0)return[];let r=await this.#y(e,{create:!1,cacheContext:n});return r===null?t.map(()=>null):Promise.all(t.map(async t=>{let i=await this.#b(e,t,{create:!1,cacheContext:n,storeDir:r});return i===null?null:this.#C(this.#_(e,t),i,n)}))}async#i(e,t,n){t.length!==0&&await Promise.all(t.map(t=>this.#w(e,t,n)))}async#a(e,t,n){let r=[...new Set(t)];if(r.length===0)return;let i=await this.#y(e,{create:!1,cacheContext:n});if(i===null||await this.#F(e,r,n))return;let a=await Promise.all(r.map(async t=>{let r=T(e,t);try{return await i.removeEntry(r),!0}catch{return!1}finally{this.#j(e,t,n)}}));this.#z(this.#g(e),n,a.filter(Boolean).length),this.#P(r,n)&&await this.#L(e,n)}async#o(e,t){let{resolvedEntries:n}=await this.#x(e,t);return n.map(e=>e.key).sort((e,t)=>e.localeCompare(t))}async#s(e,t){let n=await this.#y(e,{create:!1,cacheContext:t});if(n===null)return;let{allFileNames:r,resolvedEntries:i}=await this.#x(e,t),a=i.map(e=>e.key);if(r.length===a.length&&await this.#F(e,a,t))return;let o=this.#g(e),s=await Promise.all(r.map(async e=>{try{return await n.removeEntry(e),!0}catch{return!1}finally{this.#M(v(o,e),t)}}));this.#z(o,t,s.filter(Boolean).length),await this.#L(e,t)}async#c(e,t){return(await this.#l(e,t)).map(({scope:e})=>e)}async#l(e,t){let r=await this.#p(e,t),i=new Map;for(let e of r){if(e.handle===null)continue;let r=e.handle;this.#R(e.path,t,new Set);let a=g(e.name),o=await this.#H(r,e.path,t),s=await Promise.all(o.map(async e=>{let n=g(e.name);return{...await this.#u(e.handle,a,n,t),storeEntry:e}})),c=new Set;for(let{storeEntry:e,invalidEntryNames:a,knownEntryCount:o,scopeEntries:l}of s){if(await this.#V(e.handle,a,t),o>0)c.add(e.path);else if(t.cleanupKnowledge!==null&&a.length>0)try{await r.removeEntry(e.name,{recursive:!0}),this.#N(e.path,t)}catch{}t.cleanupKnowledge?.knownRemainingEntryCountByStorePath.set(e.path,o);for(let e of l){let t=n(e.scope),r=i.get(t);if(r!==void 0){r.knownRecordKeys.push(...e.knownRecordKeys);continue}i.set(t,e)}}if(this.#R(e.path,t,c),t.cleanupKnowledge!==null&&c.size===0)try{await(await this.#m()).removeEntry(e.name,{recursive:!0}),this.#N(e.path,t),this.#B(e.path,t)}catch{}}let a=[...i.values()];for(let e of a)e.knownRecordKeys.sort((e,t)=>e.localeCompare(t));return a.sort((e,t)=>{let n=e.scope.sessionKey.localeCompare(t.scope.sessionKey);if(n!==0)return n;let r=e.scope.storeName.localeCompare(t.scope.storeName);return r===0?e.scope.kind.localeCompare(t.scope.kind):r})}async#u(e,t,n,r){let i=[],a=this.#g({sessionKey:t,storeName:n}),o=new Map;for await(let[t,n]of e.entries()){if(n.kind!==`file`){i.push(t);continue}let e=D(t);if(e===null){i.push(t);continue}let r=s(n),c=o.get(e.kind)??[];c.push({fileHandle:r,fileName:t,filePath:v(a,t),isHashedPayload:e.isHashedPayload,key:e.key}),o.set(e.kind,c)}let c=[],l=0;for(let[e,a]of o){let o={sessionKey:t,storeName:n,kind:e},s=[],u=a.filter(e=>e.isHashedPayload),d=0,f=null,p=null;for(let e of a)e.isHashedPayload||e.key===null||(s.push(e.key),d+=1,e.key===`_i`&&(p=e.fileHandle,f=e.filePath,r.fileCache.set(this.#_(o,e.key),e.fileHandle)));if(u.length>0){let e=await this.#S(o,u,p,f,r);s.push(...e.resolvedEntries.map(e=>e.key)),d+=e.resolvedEntries.length,i.push(...e.invalidEntryNames)}d!==0&&(l+=d,s.sort((e,t)=>e.localeCompare(t)),c.push({knownRecordKeys:s,scope:o}))}return{invalidEntryNames:i,knownEntryCount:l,scopeEntries:c}}async#d(e,t,n,r,i){let a=await this.#C(t,r,i),o=a===null?null:E(e,a);return o!==null&&T(e,o)===n?o:null}async#f(e,t,n){if(t===null||e===null)return null;let i=await this.#C(e,t,n);if(!c(i))return null;let a=i.e;return typeof a!=`object`||!a||Array.isArray(a)?null:Object.keys(a).map(e=>r(e))}async#p(e,t){let n=await this.#m();return e===void 0?await this.#H(n,f,t):[{handle:await this.#v(e,{create:!1,cacheContext:t}),name:h(e),path:this.#h(e)}]}async#m(){return this.#e===null&&(this.#e=(async()=>(await O()).getDirectoryHandle(f,{create:!0}))()),this.#e}#h(e){return v(f,h(e))}#g(e){return v(this.#h(e.sessionKey),h(e.storeName))}#_(e,t){return v(this.#g(e),T(e,t))}async#v(e,t){let n=await this.#m(),r=this.#h(e),i=h(e);if(t.create){let e=await t.cacheContext.dirCache.getAsync(r);return e===void 0?t.cacheContext.dirCache.getOrInsertAsync(r,async()=>n.getDirectoryHandle(i,{create:!0})):e}let a=await t.cacheContext.dirCache.getAsync(r);return a===void 0?t.cacheContext.dirCache.getOrInsertAsync(r,async()=>k(n,i),{skipCachingWhen:e=>e===null}):a}async#y(e,t){let n=await this.#v(e.sessionKey,t);if(n===null)return null;let r=this.#g(e),i=h(e.storeName);if(t.create){let e=await t.cacheContext.dirCache.getAsync(r);return e===void 0?t.cacheContext.dirCache.getOrInsertAsync(r,async()=>n.getDirectoryHandle(i,{create:!0})):e}let a=await t.cacheContext.dirCache.getAsync(r);return a===void 0?t.cacheContext.dirCache.getOrInsertAsync(r,async()=>k(n,i),{skipCachingWhen:e=>e===null}):a}async#b(e,t,n){let r=T(e,t),i=v(this.#g(e),r);if(n.create){let e=await n.cacheContext.fileCache.getAsync(i);return e===void 0?n.cacheContext.fileCache.getOrInsertAsync(i,async()=>n.storeDir.getFileHandle(r,{create:!0})):e}let a=await n.cacheContext.fileCache.getAsync(i);return a===void 0?n.cacheContext.fileCache.getOrInsertAsync(i,async()=>A(n.storeDir,r),{skipCachingWhen:e=>e===null}):a}async#x(e,t){let n=await this.#y(e,{create:!1,cacheContext:t});if(n===null)return{allFileNames:[],resolvedEntries:[]};let r=[],i=[],a=[],o=null,c=null,l=this.#g(e);for await(let[t,u]of n.entries()){if(u.kind!==`file`)continue;let n=D(t);if(n===null||n.kind!==e.kind)continue;r.push(t);let d=v(l,t),f=s(u);if(n.isHashedPayload){a.push({fileHandle:f,fileName:t,filePath:d,isHashedPayload:!0,key:null});continue}n.key!==null&&(i.push({fileName:t,key:n.key}),n.key===`_i`&&(c=f,o=d))}return a.length>0&&i.push(...(await this.#S(e,a,c,o,t)).resolvedEntries),i.sort((e,t)=>e.key.localeCompare(t.key)),{allFileNames:r,resolvedEntries:i}}async#S(e,t,n,r,i){let a=new Map(t.map(e=>[e.fileName,e])),o=[],s=[],c=await this.#f(r,n,i);if(c!==null){let n=new Set,r=this.#g(e);for(let t of c){let s=T(e,t),c=a.get(s);c!==void 0&&(n.add(s),o.push({fileName:c.fileName,key:t}),i.fileCache.set(v(r,s),c.fileHandle))}return s.push(...t.flatMap(e=>n.has(e.fileName)?[]:[e.fileName])),{invalidEntryNames:s,resolvedEntries:o}}let l=await Promise.all(t.map(async t=>({file:t,key:await this.#d(e,t.filePath,t.fileName,t.fileHandle,i)})));for(let{file:e,key:t}of l){if(t===null){s.push(e.fileName);continue}o.push({fileName:e.fileName,key:t}),i.fileCache.set(e.filePath,e.fileHandle)}return{invalidEntryNames:s,resolvedEntries:o}}async#C(e,t,n){let r=n.readValueCache;if(r?.has(e)===!0)return r.get(e)??null;try{let n=await t.getFile(),i=JSON.parse(await n.text());return r?.set(e,i),i}catch{return r?.set(e,null),null}}async#w(e,t,n){let r;for(let i=0;i<2;i+=1)try{let r=await this.#y(e,{create:!0,cacheContext:n});if(r===null)throw Error(`[TSDF] Failed to open OPFS store directory.`);let i=await this.#b(e,t.key,{create:!0,cacheContext:n,storeDir:r});if(i===null)throw Error(`[TSDF] Failed to open OPFS file handle.`);let a=await i.createWritable(),o=t.serializedValue??JSON.stringify(t.value);try{await a.write(o)}finally{await a.close()}n.readValueCache?.set(this.#_(e,t.key),t.value);return}catch(a){if(i>0)throw r;r=a,this.#j(e,t.key,n),this.#N(this.#g(e),n),this.#N(this.#h(e.sessionKey),n)}}async#T(e,t,n){if(t.length===0)return[];let r=await this.#y(e,{create:!1,cacheContext:n});return r===null?[]:(await Promise.all(t.map(async t=>{let n=T(e,t);try{return await r.removeEntry(n),t}catch{return null}}))).flatMap(e=>e===null?[]:[e])}async#E(e,t,n){let r=n.cleanupKnowledge;if(r===null)return!1;let i=this.#g(e),a=r.knownRemainingEntryCountByStorePath.get(i);if(a===void 0||a!==t.length)return!1;let o=await this.#v(e.sessionKey,{create:!1,cacheContext:n});if(o===null)return!1;try{return await o.removeEntry(h(e.storeName),{recursive:!0}),!0}catch{return!1}}async#D(e,t){if(t.cleanupKnowledge===null)return!1;let n=this.#h(e),r=t.cleanupKnowledge.knownStorePathsBySessionPath.get(n);if(r!==void 0&&r.size>0)return!1;let i=await this.#m();try{return await i.removeEntry(h(e),{recursive:!0}),!0}catch{return!1}}#O(e,t,n){for(let r of t)this.#j(e,r,n);this.#z(this.#g(e),n,t.length)}#k(e,t,n){for(let r of t)this.#j(e,r,n);let r=this.#h(e.sessionKey),i=this.#g(e);this.#N(i,n),n.cleanupKnowledge?.knownStorePathsBySessionPath.get(r)?.delete(i),n.cleanupKnowledge?.knownRemainingEntryCountByStorePath.delete(i)}#A(e,t){let n=this.#h(e);this.#N(n,t),this.#B(n,t)}#j(e,t,n){let r=this.#_(e,t);this.#M(r,n)}#M(e,t){t.fileCache.delete(e),t.readValueCache?.delete(e),t!==this.#t&&this.#t.fileCache.delete(e)}#N(e,t){t.dirCache.delete(e),t!==this.#t&&this.#t.dirCache.delete(e)}#P(e,t){return t.cleanupKnowledge===null?e.includes(`_i`):!0}async#F(e,t,n){let r=n.cleanupKnowledge;if(r===null)return!1;let i=this.#g(e),a=r.knownRemainingEntryCountByStorePath.get(i);if(a===void 0||a!==t.length)return!1;let o=await this.#v(e.sessionKey,{create:!1,cacheContext:n});if(o===null)return!1;for(let r of t)this.#j(e,r,n);try{await o.removeEntry(h(e.storeName),{recursive:!0})}catch{return!1}return await this.#I(e,n),!0}async#I(e,t){let n=await this.#m(),r=this.#h(e.sessionKey),i=this.#g(e);this.#N(i,t),t.cleanupKnowledge?.knownStorePathsBySessionPath.get(r)?.delete(i),t.cleanupKnowledge?.knownRemainingEntryCountByStorePath.delete(i);let a=t.cleanupKnowledge?.knownStorePathsBySessionPath.get(r);if(a!==void 0&&a.size>0)return;let o=!1;try{await n.removeEntry(h(e.sessionKey),{recursive:t.cleanupKnowledge!==null}),o=!0}catch{}finally{o&&(this.#N(r,t),this.#B(r,t))}}async#L(e,t){let n=this.#g(e),r=await this.#v(e.sessionKey,{create:!1,cacheContext:t});if(r===null)return;let i=t.cleanupKnowledge?.knownRemainingEntryCountByStorePath.get(n);if(i!==void 0&&i>0)return;let a=!1;try{await r.removeEntry(h(e.storeName),{recursive:t.cleanupKnowledge!==null}),a=!0}catch{}a&&await this.#I(e,t)}#R(e,t,n){t.cleanupKnowledge?.knownStorePathsBySessionPath.set(e,n)}#z(e,t,n){if(n===0)return;let r=t.cleanupKnowledge;if(r===null)return;let i=r.knownRemainingEntryCountByStorePath.get(e);i!==void 0&&r.knownRemainingEntryCountByStorePath.set(e,Math.max(0,i-n))}#B(e,t){t.cleanupKnowledge?.knownStorePathsBySessionPath.delete(e)}async#V(e,t,n){n.cleanupKnowledge===null||t.length===0||await Promise.all(t.map(async t=>{try{await e.removeEntry(t,{recursive:!0})}catch{}}))}async#H(e,t,n){let r=[],i=[];for await(let a of e.values()){if(a.kind!==`directory`){i.push(a.name);continue}let e=s(a),o=v(t,a.name);n.dirCache.set(o,e),r.push({handle:e,name:a.name,path:o})}return await this.#V(e,i,n),r.sort((e,t)=>e.name.localeCompare(t.name)),r}});export{h as a,O as i,k as n,A as r,j as t};
|