tsdf 17.0.0-alpha.8 → 17.0.0-alpha.9
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-kvAIhrBD.d.ts → asyncStorageAdapter-BMYAF6rt.d.ts} +1 -1
- package/dist/asyncStorageAdapter-BZSj1ZO5.js +1868 -0
- package/dist/asyncStorageAdapters-DbyKyARM.js +3 -0
- package/dist/indexed-db-storage.d.ts +4 -2
- package/dist/indexed-db-storage.js +2 -1
- package/dist/indexedDbPersistentStorage-DlUjN1qY.js +902 -0
- package/dist/main.d.ts +410 -244
- package/dist/main.js +16153 -1
- package/dist/opfs-storage.d.ts +1 -1
- package/dist/opfs-storage.js +2 -1
- package/dist/opfsPersistentStorage-BO_uDxe4.js +838 -0
- package/dist/{opfsPersistentStorage-D_fecOJg.d.ts → opfsPersistentStorage-CBnUebnf.d.ts} +1 -1
- package/dist/{types-DkNgE_f9.d.ts → types-2zQlbxtw.d.ts} +132 -63
- package/docs/README.md +14 -14
- package/docs/batch-fetching.md +1 -1
- package/docs/browser-tabs-sync.md +2 -0
- package/docs/collection-store.md +24 -22
- package/docs/document-store.md +4 -2
- package/docs/fetch-scheduling.md +7 -7
- package/docs/list-query-store.md +35 -33
- package/docs/mutations.md +2 -0
- package/docs/persistent-storage.md +2 -0
- package/docs/real-time-updates.md +5 -5
- package/docs/store-manager.md +31 -12
- 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
|
@@ -0,0 +1,902 @@
|
|
|
1
|
+
import { B as parseAsyncStorageRecordKey, F as encodePersistedAsyncNamespaceKind, H as serializeProtectedRef, I as getNamespaceId, L as getPayloadRecordKey, P as compareMetadata, R as getPersistedNamespaceId, V as parsePersistedAsyncNamespaceKind, a as estimateManagedAsyncStorageEntrySizeBytes, i as createAsyncStorageAdapter, v as serializeJsonForStorage, z as normalizeStaticPolicy } from "./asyncStorageAdapter-BZSj1ZO5.js";
|
|
2
|
+
import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
|
|
3
|
+
import { isObject } from "@ls-stack/utils/typeGuards";
|
|
4
|
+
//#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
|
|
5
|
+
const DEFAULT_INDEXED_DB_NAME = "tsdf-persistent-storage-compact-alpha-reset";
|
|
6
|
+
const INDEXED_DB_VERSION = 1;
|
|
7
|
+
const INDEXED_DB_ENTRY_STORE = "entries";
|
|
8
|
+
const INDEXED_DB_NAMESPACE_POLICY_STORE = "namespacePolicies";
|
|
9
|
+
const INDEXED_DB_META_STORE = "meta";
|
|
10
|
+
const INDEXED_DB_MAINTENANCE_META_KEY = "maintenance";
|
|
11
|
+
function createScopePrimaryKey(scope) {
|
|
12
|
+
return [
|
|
13
|
+
scope.sessionKey,
|
|
14
|
+
scope.storeName,
|
|
15
|
+
encodePersistedAsyncNamespaceKind(scope.kind)
|
|
16
|
+
];
|
|
17
|
+
}
|
|
18
|
+
function createEntryPrimaryKey(scope, key) {
|
|
19
|
+
return [createScopeId(scope.sessionKey, scope.storeName, scope.kind), key];
|
|
20
|
+
}
|
|
21
|
+
function createScopeKeyRange(scope) {
|
|
22
|
+
return IDBKeyRange.bound(createEntryPrimaryKey(scope, ""), createEntryPrimaryKey(scope, ""));
|
|
23
|
+
}
|
|
24
|
+
function createScopeLastAccessRange(scope) {
|
|
25
|
+
const scopeId = createScopeId(scope.sessionKey, scope.storeName, scope.kind);
|
|
26
|
+
return IDBKeyRange.bound([scopeId, Number.MIN_SAFE_INTEGER], [scopeId, Number.MAX_SAFE_INTEGER]);
|
|
27
|
+
}
|
|
28
|
+
function createScopeGroupRange(scope, group) {
|
|
29
|
+
return IDBKeyRange.only([createScopeId(scope.sessionKey, scope.storeName, scope.kind), group]);
|
|
30
|
+
}
|
|
31
|
+
function createScopeOfflineProtectedRange(scope) {
|
|
32
|
+
return IDBKeyRange.only([createScopeId(scope.sessionKey, scope.storeName, scope.kind), 1]);
|
|
33
|
+
}
|
|
34
|
+
function createScopePolicyKey(scope) {
|
|
35
|
+
return createScopePrimaryKey(scope);
|
|
36
|
+
}
|
|
37
|
+
function createScopeId(sessionKey, storeName, kind) {
|
|
38
|
+
return getPersistedNamespaceId({
|
|
39
|
+
sessionKey,
|
|
40
|
+
storeName,
|
|
41
|
+
kind
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function getScopeFromPrimaryKey(key) {
|
|
45
|
+
if (!Array.isArray(key) || key.length < 3) return null;
|
|
46
|
+
const [sessionKey, storeName, rawKind] = key;
|
|
47
|
+
if (typeof sessionKey !== "string" || typeof storeName !== "string") return null;
|
|
48
|
+
const kind = typeof rawKind === "string" ? parsePersistedAsyncNamespaceKind(rawKind) : null;
|
|
49
|
+
if (kind === null) return null;
|
|
50
|
+
return {
|
|
51
|
+
kind,
|
|
52
|
+
sessionKey,
|
|
53
|
+
storeName
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function getEntryKeyFromPrimaryKey(key) {
|
|
57
|
+
if (!Array.isArray(key) || key.length < 2) return null;
|
|
58
|
+
return typeof key[1] === "string" ? key[1] : null;
|
|
59
|
+
}
|
|
60
|
+
function splitCustomMetadata(customMetadata) {
|
|
61
|
+
if (customMetadata === void 0) return {};
|
|
62
|
+
const { g, o, p, ...rest } = customMetadata;
|
|
63
|
+
return {
|
|
64
|
+
...typeof g === "string" ? { group: g } : {},
|
|
65
|
+
...o === true ? { offlineProtected: true } : {},
|
|
66
|
+
..."p" in customMetadata ? { payload: p } : {},
|
|
67
|
+
...Object.keys(rest).length > 0 ? { extraMetadata: rest } : {}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function mergeCustomMetadata(fields) {
|
|
71
|
+
const result = {
|
|
72
|
+
...fields.extraMetadata ?? {},
|
|
73
|
+
...fields.group !== void 0 ? { g: fields.group } : {},
|
|
74
|
+
...fields.offlineProtected === true ? { o: true } : {},
|
|
75
|
+
...fields.payload !== void 0 ? { p: fields.payload } : {}
|
|
76
|
+
};
|
|
77
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
78
|
+
}
|
|
79
|
+
function getCustomMetadataFromEntryRecord(record) {
|
|
80
|
+
return mergeCustomMetadata({
|
|
81
|
+
extraMetadata: record.m,
|
|
82
|
+
group: record.g,
|
|
83
|
+
offlineProtected: record.o === 1 ? true : void 0,
|
|
84
|
+
payload: record.p
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
function toMetadataRecord(record) {
|
|
88
|
+
const customMetadata = getCustomMetadataFromEntryRecord(record);
|
|
89
|
+
return {
|
|
90
|
+
lastAccessAt: record.a,
|
|
91
|
+
...typeof record.z === "number" ? { sizeBytes: record.z } : {},
|
|
92
|
+
version: record.v ?? 1,
|
|
93
|
+
...customMetadata ? { customMetadata } : {}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function toPublicMetadata(key, record) {
|
|
97
|
+
return {
|
|
98
|
+
customMetadata: getCustomMetadataFromEntryRecord(record) ?? {},
|
|
99
|
+
key,
|
|
100
|
+
lastAccessAt: record.a,
|
|
101
|
+
payloadRef: getPayloadRecordKey(key),
|
|
102
|
+
...typeof record.z === "number" ? { sizeBytes: record.z } : {},
|
|
103
|
+
version: record.v ?? 1,
|
|
104
|
+
writtenAt: record.a
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const INDEXED_DB_ENTRY_RECORD_KEYS = new Set([
|
|
108
|
+
"a",
|
|
109
|
+
"d",
|
|
110
|
+
"f",
|
|
111
|
+
"g",
|
|
112
|
+
"h",
|
|
113
|
+
"i",
|
|
114
|
+
"m",
|
|
115
|
+
"o",
|
|
116
|
+
"p",
|
|
117
|
+
"v",
|
|
118
|
+
"z"
|
|
119
|
+
]);
|
|
120
|
+
const INDEXED_DB_NAMESPACE_POLICY_RECORD_KEYS = new Set(["p", "s"]);
|
|
121
|
+
function toRecordValue(value) {
|
|
122
|
+
return __LEGIT_CAST__(value);
|
|
123
|
+
}
|
|
124
|
+
function toEntryRecordValue(value) {
|
|
125
|
+
return __LEGIT_CAST__(value);
|
|
126
|
+
}
|
|
127
|
+
function toNamespacePolicyRecordValue(value) {
|
|
128
|
+
return __LEGIT_CAST__(value);
|
|
129
|
+
}
|
|
130
|
+
function parseIndexedDbPersistedStaticPolicy(value) {
|
|
131
|
+
if (value === null || value === void 0) return null;
|
|
132
|
+
if (!isObject(value)) return void 0;
|
|
133
|
+
const record = toRecordValue(value);
|
|
134
|
+
if (Object.keys(record).some((key) => key !== "b" && key !== "k")) return;
|
|
135
|
+
const rawMaxBytes = record.b;
|
|
136
|
+
if (rawMaxBytes !== void 0 && (typeof rawMaxBytes !== "number" || !Number.isInteger(rawMaxBytes) || rawMaxBytes < 0)) return;
|
|
137
|
+
const validatedPinnedKeys = record.k === void 0 ? void 0 : validateStringArray(record.k);
|
|
138
|
+
if (validatedPinnedKeys === null) return void 0;
|
|
139
|
+
return normalizeStaticPolicy({
|
|
140
|
+
...typeof record.b === "number" ? { maxBytes: record.b } : {},
|
|
141
|
+
...validatedPinnedKeys !== void 0 ? { pinnedKeys: validatedPinnedKeys } : {}
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
function serializeIndexedDbPersistedStaticPolicy(policy) {
|
|
145
|
+
const normalizedPolicy = normalizeStaticPolicy(policy);
|
|
146
|
+
if (normalizedPolicy === null) return null;
|
|
147
|
+
return {
|
|
148
|
+
...normalizedPolicy.maxBytes !== void 0 ? { b: normalizedPolicy.maxBytes } : {},
|
|
149
|
+
...normalizedPolicy.pinnedKeys !== void 0 && normalizedPolicy.pinnedKeys.length > 0 ? { k: normalizedPolicy.pinnedKeys } : {}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function validateStringArray(value) {
|
|
153
|
+
if (!Array.isArray(value)) return null;
|
|
154
|
+
const result = [];
|
|
155
|
+
for (const entry of value) {
|
|
156
|
+
if (typeof entry !== "string") return null;
|
|
157
|
+
result.push(entry);
|
|
158
|
+
}
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
function isValidEntryRecord(record) {
|
|
162
|
+
if (!isObject(record)) return false;
|
|
163
|
+
const recordValue = toRecordValue(record);
|
|
164
|
+
if (Object.keys(recordValue).some((key) => !INDEXED_DB_ENTRY_RECORD_KEYS.has(key))) return false;
|
|
165
|
+
const loadedFields = recordValue.f;
|
|
166
|
+
return typeof recordValue.i === "string" && typeof recordValue.a === "number" && "d" in recordValue && (recordValue.v === void 0 || typeof recordValue.v === "number") && (recordValue.z === void 0 || typeof recordValue.z === "number") && (recordValue.m === void 0 || isObject(recordValue.m)) && (recordValue.g === void 0 || typeof recordValue.g === "string") && (recordValue.o === void 0 || recordValue.o === 1) && (loadedFields === void 0 || loadedFields instanceof Array && loadedFields.every((value) => typeof value === "string")) && (recordValue.h === void 0 || recordValue.h === 1);
|
|
167
|
+
}
|
|
168
|
+
function isValidNamespacePolicyRecord(record) {
|
|
169
|
+
if (!isObject(record)) return false;
|
|
170
|
+
const recordValue = toRecordValue(record);
|
|
171
|
+
if (Object.keys(recordValue).some((key) => !INDEXED_DB_NAMESPACE_POLICY_RECORD_KEYS.has(key))) return false;
|
|
172
|
+
if (typeof recordValue.s !== "string" || !("p" in recordValue)) return false;
|
|
173
|
+
return recordValue.p === null || parseIndexedDbPersistedStaticPolicy(recordValue.p) !== void 0;
|
|
174
|
+
}
|
|
175
|
+
function getStaticPolicyFromScopeRecord(record) {
|
|
176
|
+
if (record === void 0) return null;
|
|
177
|
+
return parseIndexedDbPersistedStaticPolicy(record.p) ?? null;
|
|
178
|
+
}
|
|
179
|
+
function compactEntryValue(scope, value) {
|
|
180
|
+
return { d: value };
|
|
181
|
+
}
|
|
182
|
+
function estimateIndexedDbManagedEntrySizeBytes(args) {
|
|
183
|
+
return estimateManagedAsyncStorageEntrySizeBytes({
|
|
184
|
+
customMetadata: args.customMetadata,
|
|
185
|
+
lastAccessAt: args.lastAccessAt,
|
|
186
|
+
serializedValue: args.serializedValue ?? serializeJsonForStorage(args.value).rawValue,
|
|
187
|
+
version: args.version
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
function expandEntryValue(scope, record) {
|
|
191
|
+
return record.d;
|
|
192
|
+
}
|
|
193
|
+
function openRequestAsPromise(request) {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
request.onsuccess = () => resolve(__LEGIT_CAST__(request.result));
|
|
196
|
+
request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB request failed."));
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
function transactionDone(transaction) {
|
|
200
|
+
return new Promise((resolve, reject) => {
|
|
201
|
+
transaction.oncomplete = () => resolve();
|
|
202
|
+
transaction.onerror = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB transaction failed."));
|
|
203
|
+
transaction.onabort = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB transaction aborted."));
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
async function iterateCursor(request, callback) {
|
|
207
|
+
await new Promise((resolve, reject) => {
|
|
208
|
+
request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB cursor request failed."));
|
|
209
|
+
request.onsuccess = async () => {
|
|
210
|
+
const cursor = request.result;
|
|
211
|
+
if (cursor === null) {
|
|
212
|
+
resolve();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
await callback(cursor);
|
|
217
|
+
cursor.continue();
|
|
218
|
+
} catch (error) {
|
|
219
|
+
reject(error instanceof Error ? error : /* @__PURE__ */ new Error("IndexedDB cursor callback failed."));
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
function deleteDatabase(databaseName) {
|
|
225
|
+
return new Promise((resolve, reject) => {
|
|
226
|
+
const request = indexedDB.deleteDatabase(databaseName);
|
|
227
|
+
request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB deleteDatabase failed."));
|
|
228
|
+
request.onblocked = () => resolve();
|
|
229
|
+
request.onsuccess = () => resolve();
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
async function getMaintenanceState(database) {
|
|
233
|
+
const transaction = database.transaction(INDEXED_DB_META_STORE, "readonly");
|
|
234
|
+
const value = await openRequestAsPromise(transaction.objectStore(INDEXED_DB_META_STORE).get(INDEXED_DB_MAINTENANCE_META_KEY));
|
|
235
|
+
await transactionDone(transaction);
|
|
236
|
+
const recordValue = value?.v;
|
|
237
|
+
if (!isObject(recordValue)) return { lastSuccessfulCleanupAt: null };
|
|
238
|
+
const metadataRecord = toRecordValue(recordValue);
|
|
239
|
+
if (!("lca" in metadataRecord)) return { lastSuccessfulCleanupAt: null };
|
|
240
|
+
const lastSuccessfulCleanupAt = metadataRecord.lca;
|
|
241
|
+
return { lastSuccessfulCleanupAt: typeof lastSuccessfulCleanupAt === "number" || lastSuccessfulCleanupAt === null ? lastSuccessfulCleanupAt : null };
|
|
242
|
+
}
|
|
243
|
+
async function setMaintenanceState(database, value) {
|
|
244
|
+
const transaction = database.transaction(INDEXED_DB_META_STORE, "readwrite");
|
|
245
|
+
transaction.objectStore(INDEXED_DB_META_STORE).put({
|
|
246
|
+
k: INDEXED_DB_MAINTENANCE_META_KEY,
|
|
247
|
+
v: { lca: value.lastSuccessfulCleanupAt }
|
|
248
|
+
});
|
|
249
|
+
await transactionDone(transaction);
|
|
250
|
+
}
|
|
251
|
+
var IndexedDbAsyncStorageDriver = class {
|
|
252
|
+
__tsdfManagedStorage = {
|
|
253
|
+
applyManagedCommit: this.applyManagedCommit.bind(this),
|
|
254
|
+
clearManagedNamespace: this.clearManagedNamespace.bind(this),
|
|
255
|
+
listManagedKeys: this.listManagedKeys.bind(this),
|
|
256
|
+
listManagedMetadata: this.listManagedMetadata.bind(this),
|
|
257
|
+
persistNamespaceIndexState: this.persistNamespaceIndexState.bind(this),
|
|
258
|
+
readProtectedStorageKeys: this.readProtectedStorageKeys.bind(this),
|
|
259
|
+
readManagedEntries: this.readManagedEntries.bind(this),
|
|
260
|
+
readNamespaceIndexState: this.readNamespaceIndexState.bind(this),
|
|
261
|
+
syncSessionProtectedKeys: this.syncSessionProtectedKeys.bind(this)
|
|
262
|
+
};
|
|
263
|
+
#databasePromise = null;
|
|
264
|
+
#instrumentation;
|
|
265
|
+
databaseName;
|
|
266
|
+
constructor(databaseName = DEFAULT_INDEXED_DB_NAME, instrumentation = void 0) {
|
|
267
|
+
this.databaseName = databaseName;
|
|
268
|
+
this.#instrumentation = instrumentation;
|
|
269
|
+
}
|
|
270
|
+
async get(scope, key) {
|
|
271
|
+
const parsedKey = parseAsyncStorageRecordKey(key);
|
|
272
|
+
if (parsedKey.recordKind === "payload") {
|
|
273
|
+
const entry = await this.#getEntry(scope, parsedKey.userKey);
|
|
274
|
+
return entry === null ? null : expandEntryValue(scope, entry);
|
|
275
|
+
}
|
|
276
|
+
if (parsedKey.rawKey !== "_i") return null;
|
|
277
|
+
const state = await this.readNamespaceIndexState(scope);
|
|
278
|
+
if (!state.exists || !state.valid || state.entries === null) return null;
|
|
279
|
+
return {
|
|
280
|
+
e: Object.fromEntries([...state.entries.entries()].map(([entryKey, metadata]) => [entryKey, {
|
|
281
|
+
a: metadata.lastAccessAt,
|
|
282
|
+
...metadata.version !== 1 ? { v: metadata.version } : {},
|
|
283
|
+
...metadata.sizeBytes !== void 0 ? { z: metadata.sizeBytes } : {},
|
|
284
|
+
...metadata.customMetadata ?? {}
|
|
285
|
+
}])),
|
|
286
|
+
...state.staticPolicy !== null ? { s: state.staticPolicy } : {}
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
async set(scope, key, value) {
|
|
290
|
+
await this.setMany(scope, [{
|
|
291
|
+
key,
|
|
292
|
+
value
|
|
293
|
+
}]);
|
|
294
|
+
}
|
|
295
|
+
async remove(scope, key) {
|
|
296
|
+
await this.removeMany(scope, [key]);
|
|
297
|
+
}
|
|
298
|
+
async getMany(scope, keys) {
|
|
299
|
+
return Promise.all(keys.map((key) => this.get(scope, key)));
|
|
300
|
+
}
|
|
301
|
+
async setMany(scope, entries) {
|
|
302
|
+
for (const entry of entries) {
|
|
303
|
+
const parsedKey = parseAsyncStorageRecordKey(entry.key);
|
|
304
|
+
if (parsedKey.recordKind === "payload") {
|
|
305
|
+
const existing = await this.#getEntry(scope, parsedKey.userKey);
|
|
306
|
+
const lastAccessAt = existing?.a ?? Date.now();
|
|
307
|
+
await this.#putEntryRecord(scope, {
|
|
308
|
+
customMetadata: existing === null ? void 0 : getCustomMetadataFromEntryRecord(existing),
|
|
309
|
+
key: parsedKey.userKey,
|
|
310
|
+
lastAccessAt,
|
|
311
|
+
value: entry.value,
|
|
312
|
+
version: existing?.v ?? 1
|
|
313
|
+
});
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (parsedKey.rawKey === "_i") {
|
|
317
|
+
const state = this.#parsePersistedIndexState(entry.value);
|
|
318
|
+
if (state !== null) await this.persistNamespaceIndexState(scope, state);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async removeMany(scope, keys) {
|
|
323
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
324
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
325
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
326
|
+
let removedAnyEntry = false;
|
|
327
|
+
let removedScope = false;
|
|
328
|
+
for (const key of keys) {
|
|
329
|
+
const parsedKey = parseAsyncStorageRecordKey(key);
|
|
330
|
+
if (parsedKey.recordKind === "payload") {
|
|
331
|
+
entryStore.delete(createEntryPrimaryKey(scope, parsedKey.userKey));
|
|
332
|
+
removedAnyEntry = true;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (parsedKey.rawKey === "_i") {
|
|
336
|
+
policyStore.delete(createScopePolicyKey(scope));
|
|
337
|
+
removedScope = true;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (removedAnyEntry && !removedScope) {
|
|
341
|
+
const countRequest = entryStore.count(createScopeKeyRange(scope));
|
|
342
|
+
countRequest.onsuccess = () => {
|
|
343
|
+
if (countRequest.result === 0) policyStore.delete(createScopePolicyKey(scope));
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
await transactionDone(transaction);
|
|
347
|
+
this.#instrumentation?.onRemoveMany?.(scope, keys);
|
|
348
|
+
this.#instrumentation?.record({
|
|
349
|
+
keys: [...keys].sort((left, right) => left.localeCompare(right)),
|
|
350
|
+
scope,
|
|
351
|
+
time: Date.now(),
|
|
352
|
+
type: "removeManagedRecords"
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
async listKeys(scope) {
|
|
356
|
+
const state = await this.readNamespaceIndexState(scope);
|
|
357
|
+
if (!state.exists || state.entries === null) return [];
|
|
358
|
+
const keys = [...state.entries.keys()].map((key) => getPayloadRecordKey(key));
|
|
359
|
+
keys.push("_i");
|
|
360
|
+
return keys.sort((left, right) => left.localeCompare(right));
|
|
361
|
+
}
|
|
362
|
+
async clear(scope) {
|
|
363
|
+
await this.clearManagedNamespace(scope);
|
|
364
|
+
}
|
|
365
|
+
async listScopes(sessionKey) {
|
|
366
|
+
return (await this.listScopesWithKnownRecordKeys(sessionKey)).map(({ scope }) => scope);
|
|
367
|
+
}
|
|
368
|
+
async listScopesWithKnownRecordKeys(sessionKey) {
|
|
369
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
|
|
370
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
371
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
372
|
+
const discoveredScopes = [];
|
|
373
|
+
await iterateCursor(sessionKey === void 0 ? policyStore.openCursor() : policyStore.index("bySession").openCursor(IDBKeyRange.only(sessionKey)), async (cursor) => {
|
|
374
|
+
const scope = getScopeFromPrimaryKey(cursor.primaryKey);
|
|
375
|
+
if (scope === null) return;
|
|
376
|
+
const keys = new Set(["_i"]);
|
|
377
|
+
await iterateCursor(entryStore.openCursor(createScopeKeyRange(scope)), (entryCursor) => {
|
|
378
|
+
const entryKey = getEntryKeyFromPrimaryKey(entryCursor.primaryKey);
|
|
379
|
+
if (entryKey === null) return;
|
|
380
|
+
keys.add(getPayloadRecordKey(entryKey));
|
|
381
|
+
});
|
|
382
|
+
discoveredScopes.push({
|
|
383
|
+
knownRecordKeys: [...keys].sort((left, right) => left.localeCompare(right)),
|
|
384
|
+
scope
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
await transactionDone(transaction);
|
|
388
|
+
discoveredScopes.sort((left, right) => getNamespaceId(left.scope).localeCompare(getNamespaceId(right.scope)));
|
|
389
|
+
this.#instrumentation?.record({
|
|
390
|
+
scopeIds: discoveredScopes.map(({ scope }) => getNamespaceId(scope)),
|
|
391
|
+
...sessionKey !== void 0 ? { sessionKey } : {},
|
|
392
|
+
time: Date.now(),
|
|
393
|
+
type: "listScopesWithKnownRecordKeys"
|
|
394
|
+
});
|
|
395
|
+
return discoveredScopes;
|
|
396
|
+
}
|
|
397
|
+
async readManagedEntries(scope, keys) {
|
|
398
|
+
const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
399
|
+
const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
400
|
+
const uniqueKeys = [...new Set(keys)];
|
|
401
|
+
const result = /* @__PURE__ */ new Map();
|
|
402
|
+
await Promise.all(uniqueKeys.map(async (key) => {
|
|
403
|
+
const record = await openRequestAsPromise(store.get(createEntryPrimaryKey(scope, key)));
|
|
404
|
+
if (!isValidEntryRecord(record)) {
|
|
405
|
+
result.set(key, null);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
const entryRecord = toEntryRecordValue(record);
|
|
409
|
+
result.set(key, {
|
|
410
|
+
metadata: toPublicMetadata(key, entryRecord),
|
|
411
|
+
value: __LEGIT_CAST__(expandEntryValue(scope, entryRecord))
|
|
412
|
+
});
|
|
413
|
+
}));
|
|
414
|
+
await transactionDone(transaction);
|
|
415
|
+
this.#instrumentation?.record({
|
|
416
|
+
keys: uniqueKeys,
|
|
417
|
+
resultKeys: [...result.entries()].flatMap(([key, value]) => value === null ? [] : [key]).sort((left, right) => left.localeCompare(right)),
|
|
418
|
+
scope,
|
|
419
|
+
time: Date.now(),
|
|
420
|
+
type: "readManagedEntries"
|
|
421
|
+
});
|
|
422
|
+
return result;
|
|
423
|
+
}
|
|
424
|
+
async listManagedMetadata(scope, args = {}) {
|
|
425
|
+
const order = args.order ?? "key";
|
|
426
|
+
const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
427
|
+
const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
428
|
+
const entries = [];
|
|
429
|
+
let usedIndex = "key";
|
|
430
|
+
if (args.filter?.key === "g" && typeof args.filter.equals === "string" && order === "key") {
|
|
431
|
+
usedIndex = "group";
|
|
432
|
+
await iterateCursor(store.index("byScopeGroup").openCursor(createScopeGroupRange(scope, args.filter.equals)), (cursor) => {
|
|
433
|
+
const record = cursor.value;
|
|
434
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
435
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
436
|
+
entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
|
|
437
|
+
});
|
|
438
|
+
} else if (order === "lru-asc" || order === "lru-desc") {
|
|
439
|
+
usedIndex = "lru";
|
|
440
|
+
await iterateCursor(store.index("byScopeLastAccessAt").openCursor(createScopeLastAccessRange(scope), order === "lru-desc" ? "prev" : "next"), (cursor) => {
|
|
441
|
+
const record = cursor.value;
|
|
442
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
443
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
444
|
+
entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
|
|
445
|
+
});
|
|
446
|
+
} else await iterateCursor(store.openCursor(createScopeKeyRange(scope)), (cursor) => {
|
|
447
|
+
const record = cursor.value;
|
|
448
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
449
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
450
|
+
entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
|
|
451
|
+
});
|
|
452
|
+
await transactionDone(transaction);
|
|
453
|
+
const filter = args.filter;
|
|
454
|
+
const filteredEntries = filter === void 0 ? entries : entries.filter((entry) => entry.customMetadata[filter.key] === filter.equals);
|
|
455
|
+
if (usedIndex !== "lru") filteredEntries.sort((left, right) => compareMetadata(left, right, order));
|
|
456
|
+
this.#instrumentation?.record({
|
|
457
|
+
order,
|
|
458
|
+
resultKeys: filteredEntries.map((entry) => entry.key),
|
|
459
|
+
scope,
|
|
460
|
+
time: Date.now(),
|
|
461
|
+
type: "listManagedMetadata",
|
|
462
|
+
usedIndex
|
|
463
|
+
});
|
|
464
|
+
return filteredEntries;
|
|
465
|
+
}
|
|
466
|
+
async listManagedKeys(scope) {
|
|
467
|
+
return (await this.listManagedMetadata(scope, { order: "key" })).map((entry) => entry.key);
|
|
468
|
+
}
|
|
469
|
+
async clearManagedNamespace(scope) {
|
|
470
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
471
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
472
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
473
|
+
await iterateCursor(entryStore.openCursor(createScopeKeyRange(scope)), (cursor) => {
|
|
474
|
+
cursor.delete();
|
|
475
|
+
});
|
|
476
|
+
policyStore.delete(createScopePolicyKey(scope));
|
|
477
|
+
await transactionDone(transaction);
|
|
478
|
+
this.#instrumentation?.onClearManagedNamespace?.(scope);
|
|
479
|
+
this.#instrumentation?.record({
|
|
480
|
+
scope,
|
|
481
|
+
time: Date.now(),
|
|
482
|
+
type: "clearManagedNamespace"
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
async applyManagedCommit(scope, args, helpers) {
|
|
486
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
487
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
488
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
489
|
+
const upserts = args.upserts ?? [];
|
|
490
|
+
const removes = [...new Set(args.removes ?? [])];
|
|
491
|
+
const touches = args.touches ?? [];
|
|
492
|
+
const scopeId = createScopeId(scope.sessionKey, scope.storeName, scope.kind);
|
|
493
|
+
const uniqueKeys = [...new Set([
|
|
494
|
+
...removes,
|
|
495
|
+
...touches.map((touch) => touch.key),
|
|
496
|
+
...upserts.map((upsert) => upsert.key)
|
|
497
|
+
])];
|
|
498
|
+
const existingEntries = /* @__PURE__ */ new Map();
|
|
499
|
+
const now = Date.now();
|
|
500
|
+
const touchTimestamps = new Map(touches.map((touch) => [touch.key, touch.lastAccessAt ?? now]));
|
|
501
|
+
const rawScopeRecord = await openRequestAsPromise(policyStore.get(createScopePolicyKey(scope)));
|
|
502
|
+
const existingStaticPolicy = isValidNamespacePolicyRecord(rawScopeRecord) ? getStaticPolicyFromScopeRecord(toNamespacePolicyRecordValue(rawScopeRecord)) : null;
|
|
503
|
+
await Promise.all(uniqueKeys.map(async (key) => {
|
|
504
|
+
const record = await openRequestAsPromise(entryStore.get(createEntryPrimaryKey(scope, key)));
|
|
505
|
+
if (isValidEntryRecord(record)) existingEntries.set(key, toEntryRecordValue(record));
|
|
506
|
+
}));
|
|
507
|
+
for (const key of removes) entryStore.delete(createEntryPrimaryKey(scope, key));
|
|
508
|
+
const upsertKeySet = new Set(upserts.map((upsert) => upsert.key));
|
|
509
|
+
for (const upsert of upserts) {
|
|
510
|
+
const existing = existingEntries.get(upsert.key);
|
|
511
|
+
const customMetadata = helpers.mergeOfflineProtectionMetadata(upsert.key, upsert.metadata, existing === void 0 ? void 0 : getCustomMetadataFromEntryRecord(existing));
|
|
512
|
+
const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(customMetadata);
|
|
513
|
+
const nextLastAccessAt = touchTimestamps.get(upsert.key) ?? existing?.a ?? now;
|
|
514
|
+
const sizeBytes = scope.kind !== "document" ? estimateIndexedDbManagedEntrySizeBytes({
|
|
515
|
+
customMetadata,
|
|
516
|
+
lastAccessAt: nextLastAccessAt,
|
|
517
|
+
serializedValue: upsert.serializedValue,
|
|
518
|
+
value: upsert.value,
|
|
519
|
+
version: upsert.version
|
|
520
|
+
}) : void 0;
|
|
521
|
+
const compactValue = compactEntryValue(scope, upsert.value);
|
|
522
|
+
await openRequestAsPromise(entryStore.put({
|
|
523
|
+
a: nextLastAccessAt,
|
|
524
|
+
...compactValue,
|
|
525
|
+
...group !== void 0 ? { g: group } : {},
|
|
526
|
+
i: scopeId,
|
|
527
|
+
...extraMetadata !== void 0 ? { m: extraMetadata } : {},
|
|
528
|
+
...offlineProtected === true ? { o: 1 } : {},
|
|
529
|
+
...payload !== void 0 ? { p: payload } : {},
|
|
530
|
+
...upsert.version !== 1 ? { v: upsert.version } : {},
|
|
531
|
+
...sizeBytes !== void 0 ? { z: sizeBytes } : {}
|
|
532
|
+
}, createEntryPrimaryKey(scope, upsert.key)));
|
|
533
|
+
}
|
|
534
|
+
for (const touch of touches) {
|
|
535
|
+
if (upsertKeySet.has(touch.key)) continue;
|
|
536
|
+
const existing = existingEntries.get(touch.key);
|
|
537
|
+
if (existing === void 0) continue;
|
|
538
|
+
const nextLastAccessAt = touch.lastAccessAt ?? now;
|
|
539
|
+
if (existing.a === nextLastAccessAt) continue;
|
|
540
|
+
await openRequestAsPromise(entryStore.put({
|
|
541
|
+
...existing,
|
|
542
|
+
a: nextLastAccessAt
|
|
543
|
+
}, createEntryPrimaryKey(scope, touch.key)));
|
|
544
|
+
}
|
|
545
|
+
const normalizedStaticPolicy = "staticPolicy" in args ? normalizeStaticPolicy(args.staticPolicy) : void 0;
|
|
546
|
+
if (await openRequestAsPromise(entryStore.count(createScopeKeyRange(scope))) === 0) policyStore.delete(createScopePolicyKey(scope));
|
|
547
|
+
else await openRequestAsPromise(policyStore.put({
|
|
548
|
+
p: serializeIndexedDbPersistedStaticPolicy(normalizedStaticPolicy ?? existingStaticPolicy),
|
|
549
|
+
s: scope.sessionKey
|
|
550
|
+
}, createScopePolicyKey(scope)));
|
|
551
|
+
await transactionDone(transaction);
|
|
552
|
+
this.#instrumentation?.onApplyManagedCommit?.(scope, args);
|
|
553
|
+
this.#instrumentation?.record({
|
|
554
|
+
removes,
|
|
555
|
+
scope,
|
|
556
|
+
staticPolicyChanged: "staticPolicy" in args,
|
|
557
|
+
time: Date.now(),
|
|
558
|
+
touches: touches.map((touch) => touch.key).sort((left, right) => left.localeCompare(right)),
|
|
559
|
+
type: "applyManagedCommit",
|
|
560
|
+
upserts: upserts.map((upsert) => upsert.key).sort((left, right) => left.localeCompare(right))
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
async readNamespaceIndexState(scope, knownRecordKeys_) {
|
|
564
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
|
|
565
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
566
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
567
|
+
const entries = /* @__PURE__ */ new Map();
|
|
568
|
+
let invalidEntryCount = 0;
|
|
569
|
+
await iterateCursor(entryStore.openCursor(createScopeKeyRange(scope)), (cursor) => {
|
|
570
|
+
const record = cursor.value;
|
|
571
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
572
|
+
if (!isValidEntryRecord(record)) {
|
|
573
|
+
invalidEntryCount += 1;
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
if (entryKey === null) {
|
|
577
|
+
invalidEntryCount += 1;
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
entries.set(entryKey, toMetadataRecord(toEntryRecordValue(record)));
|
|
581
|
+
});
|
|
582
|
+
const rawPolicy = await openRequestAsPromise(policyStore.get(createScopePolicyKey(scope)));
|
|
583
|
+
await transactionDone(transaction);
|
|
584
|
+
if (invalidEntryCount > 0) {
|
|
585
|
+
const result = {
|
|
586
|
+
entries: null,
|
|
587
|
+
exists: entries.size > 0 || rawPolicy !== void 0,
|
|
588
|
+
staticPolicy: null,
|
|
589
|
+
valid: false
|
|
590
|
+
};
|
|
591
|
+
this.#instrumentation?.record({
|
|
592
|
+
exists: result.exists,
|
|
593
|
+
keyCount: entries.size,
|
|
594
|
+
scope,
|
|
595
|
+
time: Date.now(),
|
|
596
|
+
type: "readManagedIndexState",
|
|
597
|
+
valid: result.valid
|
|
598
|
+
});
|
|
599
|
+
return result;
|
|
600
|
+
}
|
|
601
|
+
if (rawPolicy !== void 0 && !isValidNamespacePolicyRecord(rawPolicy)) {
|
|
602
|
+
const result = {
|
|
603
|
+
entries: null,
|
|
604
|
+
exists: true,
|
|
605
|
+
staticPolicy: null,
|
|
606
|
+
valid: false
|
|
607
|
+
};
|
|
608
|
+
this.#instrumentation?.record({
|
|
609
|
+
exists: result.exists,
|
|
610
|
+
keyCount: entries.size,
|
|
611
|
+
scope,
|
|
612
|
+
time: Date.now(),
|
|
613
|
+
type: "readManagedIndexState",
|
|
614
|
+
valid: result.valid
|
|
615
|
+
});
|
|
616
|
+
return result;
|
|
617
|
+
}
|
|
618
|
+
const exists = rawPolicy !== void 0 || entries.size > 0;
|
|
619
|
+
if (rawPolicy === void 0 && entries.size > 0 || rawPolicy !== void 0 && entries.size === 0) {
|
|
620
|
+
const result = {
|
|
621
|
+
entries: null,
|
|
622
|
+
exists,
|
|
623
|
+
staticPolicy: null,
|
|
624
|
+
valid: false
|
|
625
|
+
};
|
|
626
|
+
this.#instrumentation?.record({
|
|
627
|
+
exists: result.exists,
|
|
628
|
+
keyCount: entries.size,
|
|
629
|
+
scope,
|
|
630
|
+
time: Date.now(),
|
|
631
|
+
type: "readManagedIndexState",
|
|
632
|
+
valid: result.valid
|
|
633
|
+
});
|
|
634
|
+
return result;
|
|
635
|
+
}
|
|
636
|
+
const result = {
|
|
637
|
+
entries,
|
|
638
|
+
exists: rawPolicy !== void 0,
|
|
639
|
+
staticPolicy: getStaticPolicyFromScopeRecord(rawPolicy === void 0 ? void 0 : toNamespacePolicyRecordValue(rawPolicy)),
|
|
640
|
+
valid: true
|
|
641
|
+
};
|
|
642
|
+
this.#instrumentation?.record({
|
|
643
|
+
exists: result.exists,
|
|
644
|
+
keyCount: result.entries.size,
|
|
645
|
+
scope,
|
|
646
|
+
time: Date.now(),
|
|
647
|
+
type: "readManagedIndexState",
|
|
648
|
+
valid: result.valid
|
|
649
|
+
});
|
|
650
|
+
return result;
|
|
651
|
+
}
|
|
652
|
+
async persistNamespaceIndexState(scope, state) {
|
|
653
|
+
const database = await this.#getDatabase();
|
|
654
|
+
const existingEntries = /* @__PURE__ */ new Map();
|
|
655
|
+
const readTransaction = database.transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
656
|
+
const readStore = readTransaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
657
|
+
const desiredKeys = [...state.entries.keys()];
|
|
658
|
+
await Promise.all(desiredKeys.map(async (key) => {
|
|
659
|
+
const existing = await openRequestAsPromise(readStore.get(createEntryPrimaryKey(scope, key)));
|
|
660
|
+
if (isValidEntryRecord(existing)) existingEntries.set(key, toEntryRecordValue(existing));
|
|
661
|
+
}));
|
|
662
|
+
await transactionDone(readTransaction);
|
|
663
|
+
const writeTransaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
664
|
+
const entryStore = writeTransaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
665
|
+
const policyStore = writeTransaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
666
|
+
for (const [key, metadata] of state.entries.entries()) {
|
|
667
|
+
const existing = existingEntries.get(key);
|
|
668
|
+
if (existing === void 0) continue;
|
|
669
|
+
const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(metadata.customMetadata);
|
|
670
|
+
entryStore.put({
|
|
671
|
+
...existing,
|
|
672
|
+
a: metadata.lastAccessAt,
|
|
673
|
+
...group !== void 0 ? { g: group } : {},
|
|
674
|
+
...group === void 0 ? { g: void 0 } : {},
|
|
675
|
+
...extraMetadata !== void 0 ? { m: extraMetadata } : {},
|
|
676
|
+
...extraMetadata === void 0 ? { m: void 0 } : {},
|
|
677
|
+
...offlineProtected === true ? { o: 1 } : {},
|
|
678
|
+
...offlineProtected !== true ? { o: void 0 } : {},
|
|
679
|
+
...payload !== void 0 ? { p: payload } : {},
|
|
680
|
+
...payload === void 0 ? { p: void 0 } : {},
|
|
681
|
+
...metadata.version !== 1 ? { v: metadata.version } : {},
|
|
682
|
+
...metadata.version === 1 ? { v: void 0 } : {},
|
|
683
|
+
...metadata.sizeBytes !== void 0 ? { z: metadata.sizeBytes } : {},
|
|
684
|
+
...metadata.sizeBytes === void 0 ? { z: void 0 } : {}
|
|
685
|
+
}, createEntryPrimaryKey(scope, key));
|
|
686
|
+
}
|
|
687
|
+
if (state.entries.size === 0) policyStore.delete(createScopePolicyKey(scope));
|
|
688
|
+
else policyStore.put({
|
|
689
|
+
p: serializeIndexedDbPersistedStaticPolicy(state.staticPolicy),
|
|
690
|
+
s: scope.sessionKey
|
|
691
|
+
}, createScopePolicyKey(scope));
|
|
692
|
+
await transactionDone(writeTransaction);
|
|
693
|
+
this.#instrumentation?.onPersistNamespaceIndexState?.(scope, state);
|
|
694
|
+
this.#instrumentation?.record({
|
|
695
|
+
keyCount: state.entries.size,
|
|
696
|
+
scope,
|
|
697
|
+
staticPolicy: state.staticPolicy,
|
|
698
|
+
time: Date.now(),
|
|
699
|
+
type: "persistManagedIndexState"
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
async readProtectedStorageKeys(sessionKey) {
|
|
703
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
|
|
704
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
705
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
706
|
+
const values = [];
|
|
707
|
+
await iterateCursor(policyStore.index("bySession").openCursor(IDBKeyRange.only(sessionKey)), async (scopeCursor) => {
|
|
708
|
+
const scope = getScopeFromPrimaryKey(scopeCursor.primaryKey);
|
|
709
|
+
if (scope === null) return;
|
|
710
|
+
await iterateCursor(entryStore.index("byScopeOfflineProtected").openCursor(createScopeOfflineProtectedRange(scope)), (entryCursor) => {
|
|
711
|
+
const entryKey = getEntryKeyFromPrimaryKey(entryCursor.primaryKey);
|
|
712
|
+
const record = entryCursor.value;
|
|
713
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
714
|
+
values.push(serializeProtectedRef({
|
|
715
|
+
...scope,
|
|
716
|
+
key: entryKey
|
|
717
|
+
}));
|
|
718
|
+
});
|
|
719
|
+
});
|
|
720
|
+
await transactionDone(transaction);
|
|
721
|
+
this.#instrumentation?.record({
|
|
722
|
+
sessionKey,
|
|
723
|
+
time: Date.now(),
|
|
724
|
+
type: "readProtectedStorageKeys",
|
|
725
|
+
values: [...values].sort((left, right) => left.localeCompare(right))
|
|
726
|
+
});
|
|
727
|
+
return values;
|
|
728
|
+
}
|
|
729
|
+
async syncSessionProtectedKeys(sessionKey, protectedKeys) {
|
|
730
|
+
const nextProtectedKeys = new Set(protectedKeys);
|
|
731
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
732
|
+
const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
733
|
+
await iterateCursor(transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE).index("bySession").openCursor(IDBKeyRange.only(sessionKey)), async (scopeCursor) => {
|
|
734
|
+
const scope = getScopeFromPrimaryKey(scopeCursor.primaryKey);
|
|
735
|
+
if (scope === null) return;
|
|
736
|
+
await iterateCursor(store.openCursor(createScopeKeyRange(scope)), (cursor) => {
|
|
737
|
+
const record = cursor.value;
|
|
738
|
+
const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
|
|
739
|
+
if (!isValidEntryRecord(record) || entryKey === null) return;
|
|
740
|
+
const entryRecord = toEntryRecordValue(record);
|
|
741
|
+
const ref = serializeProtectedRef({
|
|
742
|
+
...scope,
|
|
743
|
+
key: entryKey
|
|
744
|
+
});
|
|
745
|
+
const shouldProtect = nextProtectedKeys.has(ref);
|
|
746
|
+
if (entryRecord.o === 1 === shouldProtect) return;
|
|
747
|
+
const nextRecord = {
|
|
748
|
+
...entryRecord,
|
|
749
|
+
...shouldProtect ? { o: 1 } : { o: void 0 }
|
|
750
|
+
};
|
|
751
|
+
cursor.update(nextRecord);
|
|
752
|
+
});
|
|
753
|
+
});
|
|
754
|
+
await transactionDone(transaction);
|
|
755
|
+
this.#instrumentation?.record({
|
|
756
|
+
sessionKey,
|
|
757
|
+
time: Date.now(),
|
|
758
|
+
type: "syncSessionProtectedKeys",
|
|
759
|
+
values: [...nextProtectedKeys].sort((left, right) => left.localeCompare(right))
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
async readMaintenanceState() {
|
|
763
|
+
return getMaintenanceState(await this.#getDatabase());
|
|
764
|
+
}
|
|
765
|
+
async writeMaintenanceState(value) {
|
|
766
|
+
await setMaintenanceState(await this.#getDatabase(), value);
|
|
767
|
+
}
|
|
768
|
+
async __resetForTests() {
|
|
769
|
+
if (this.#databasePromise !== null) {
|
|
770
|
+
(await this.#databasePromise).close();
|
|
771
|
+
this.#databasePromise = null;
|
|
772
|
+
}
|
|
773
|
+
await deleteDatabase(this.databaseName);
|
|
774
|
+
this.#instrumentation?.reset();
|
|
775
|
+
}
|
|
776
|
+
async __inspectStructureForTests() {
|
|
777
|
+
const database = await this.#getDatabase();
|
|
778
|
+
const stores = [];
|
|
779
|
+
for (const storeName of [...database.objectStoreNames].sort((left, right) => left.localeCompare(right))) {
|
|
780
|
+
const transaction = database.transaction(storeName, "readonly");
|
|
781
|
+
const store = transaction.objectStore(storeName);
|
|
782
|
+
const indexes = [...store.indexNames].sort((left, right) => left.localeCompare(right)).map((indexName) => {
|
|
783
|
+
const index = store.index(indexName);
|
|
784
|
+
return {
|
|
785
|
+
keyPath: index.keyPath,
|
|
786
|
+
multiEntry: index.multiEntry,
|
|
787
|
+
name: index.name,
|
|
788
|
+
unique: index.unique
|
|
789
|
+
};
|
|
790
|
+
});
|
|
791
|
+
const [keys, values] = await Promise.all([openRequestAsPromise(store.getAllKeys()), openRequestAsPromise(store.getAll())]);
|
|
792
|
+
await transactionDone(transaction);
|
|
793
|
+
stores.push({
|
|
794
|
+
autoIncrement: store.autoIncrement,
|
|
795
|
+
indexes,
|
|
796
|
+
keyPath: store.keyPath,
|
|
797
|
+
name: storeName,
|
|
798
|
+
rows: keys.map((key, index) => ({
|
|
799
|
+
key,
|
|
800
|
+
value: values[index]
|
|
801
|
+
}))
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
stores,
|
|
806
|
+
version: database.version
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
async #getEntry(scope, key) {
|
|
810
|
+
const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
|
|
811
|
+
const record = await openRequestAsPromise(transaction.objectStore(INDEXED_DB_ENTRY_STORE).get(createEntryPrimaryKey(scope, key)));
|
|
812
|
+
await transactionDone(transaction);
|
|
813
|
+
return isValidEntryRecord(record) ? toEntryRecordValue(record) : null;
|
|
814
|
+
}
|
|
815
|
+
async #putEntryRecord(scope, args) {
|
|
816
|
+
const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
|
|
817
|
+
const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
|
|
818
|
+
const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
819
|
+
const existingScopeRecord = await openRequestAsPromise(policyStore.get(createScopePolicyKey(scope)));
|
|
820
|
+
const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(args.customMetadata);
|
|
821
|
+
const sizeBytes = scope.kind !== "document" ? estimateIndexedDbManagedEntrySizeBytes({
|
|
822
|
+
customMetadata: args.customMetadata,
|
|
823
|
+
lastAccessAt: args.lastAccessAt,
|
|
824
|
+
value: args.value,
|
|
825
|
+
version: args.version
|
|
826
|
+
}) : void 0;
|
|
827
|
+
const compactValue = compactEntryValue(scope, args.value);
|
|
828
|
+
entryStore.put({
|
|
829
|
+
a: args.lastAccessAt,
|
|
830
|
+
...compactValue,
|
|
831
|
+
...group !== void 0 ? { g: group } : {},
|
|
832
|
+
i: createScopeId(scope.sessionKey, scope.storeName, scope.kind),
|
|
833
|
+
...extraMetadata !== void 0 ? { m: extraMetadata } : {},
|
|
834
|
+
...offlineProtected === true ? { o: 1 } : {},
|
|
835
|
+
...payload !== void 0 ? { p: payload } : {},
|
|
836
|
+
...args.version !== 1 ? { v: args.version } : {},
|
|
837
|
+
...sizeBytes !== void 0 ? { z: sizeBytes } : {}
|
|
838
|
+
}, createEntryPrimaryKey(scope, args.key));
|
|
839
|
+
policyStore.put({
|
|
840
|
+
p: serializeIndexedDbPersistedStaticPolicy(getStaticPolicyFromScopeRecord(isValidNamespacePolicyRecord(existingScopeRecord) ? toNamespacePolicyRecordValue(existingScopeRecord) : void 0)),
|
|
841
|
+
s: scope.sessionKey
|
|
842
|
+
}, createScopePolicyKey(scope));
|
|
843
|
+
await transactionDone(transaction);
|
|
844
|
+
}
|
|
845
|
+
#parsePersistedIndexState(value) {
|
|
846
|
+
if (!isObject(value)) return null;
|
|
847
|
+
const recordValue = toRecordValue(value);
|
|
848
|
+
const rawEntries = recordValue.e;
|
|
849
|
+
if (!isObject(rawEntries)) return null;
|
|
850
|
+
const rawEntriesRecord = toRecordValue(rawEntries);
|
|
851
|
+
const entries = /* @__PURE__ */ new Map();
|
|
852
|
+
for (const [key, rawMetadata] of Object.entries(rawEntriesRecord)) {
|
|
853
|
+
if (!isObject(rawMetadata)) return null;
|
|
854
|
+
const rawMetadataRecord = toRecordValue(rawMetadata);
|
|
855
|
+
if (typeof rawMetadataRecord.a !== "number") return null;
|
|
856
|
+
const customMetadata = Object.fromEntries(Object.entries(rawMetadataRecord).filter(([metadataKey]) => metadataKey !== "a" && metadataKey !== "v" && metadataKey !== "z"));
|
|
857
|
+
entries.set(key, {
|
|
858
|
+
...Object.keys(customMetadata).length > 0 ? { customMetadata } : {},
|
|
859
|
+
lastAccessAt: rawMetadataRecord.a,
|
|
860
|
+
...typeof rawMetadataRecord.z === "number" ? { sizeBytes: rawMetadataRecord.z } : {},
|
|
861
|
+
version: typeof rawMetadataRecord.v === "number" ? rawMetadataRecord.v : 1
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
const staticPolicy = parseIndexedDbPersistedStaticPolicy(recordValue.s);
|
|
865
|
+
if (staticPolicy === void 0) return null;
|
|
866
|
+
return {
|
|
867
|
+
entries,
|
|
868
|
+
staticPolicy
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
async #getDatabase() {
|
|
872
|
+
if (this.#databasePromise !== null) return this.#databasePromise;
|
|
873
|
+
this.#databasePromise = new Promise((resolve, reject) => {
|
|
874
|
+
const request = indexedDB.open(this.databaseName, INDEXED_DB_VERSION);
|
|
875
|
+
request.onupgradeneeded = () => {
|
|
876
|
+
const database = request.result;
|
|
877
|
+
if (database.objectStoreNames.contains(INDEXED_DB_ENTRY_STORE)) database.deleteObjectStore(INDEXED_DB_ENTRY_STORE);
|
|
878
|
+
if (database.objectStoreNames.contains(INDEXED_DB_NAMESPACE_POLICY_STORE)) database.deleteObjectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
|
|
879
|
+
const entryStore = database.createObjectStore(INDEXED_DB_ENTRY_STORE);
|
|
880
|
+
entryStore.createIndex("byScopeLastAccessAt", ["i", "a"], { unique: false });
|
|
881
|
+
entryStore.createIndex("byScopeGroup", ["i", "g"], { unique: false });
|
|
882
|
+
entryStore.createIndex("byScopeOfflineProtected", ["i", "o"], { unique: false });
|
|
883
|
+
database.createObjectStore(INDEXED_DB_NAMESPACE_POLICY_STORE).createIndex("bySession", "s", { unique: false });
|
|
884
|
+
if (!database.objectStoreNames.contains(INDEXED_DB_META_STORE)) database.createObjectStore(INDEXED_DB_META_STORE, { keyPath: "k" });
|
|
885
|
+
};
|
|
886
|
+
request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB open failed."));
|
|
887
|
+
request.onsuccess = () => resolve(request.result);
|
|
888
|
+
});
|
|
889
|
+
return this.#databasePromise;
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
function createIndexedDbPersistentStorage$1(options = {}) {
|
|
893
|
+
return createAsyncStorageAdapter(new IndexedDbAsyncStorageDriver(options.databaseName));
|
|
894
|
+
}
|
|
895
|
+
//#endregion
|
|
896
|
+
//#region src/persistentStorage/indexedDbPersistentStorage.ts
|
|
897
|
+
const indexedDbPersistentStorage = /* @__PURE__ */ createIndexedDbPersistentStorage$1();
|
|
898
|
+
function createIndexedDbPersistentStorage(options = {}) {
|
|
899
|
+
return createIndexedDbPersistentStorage$1(options);
|
|
900
|
+
}
|
|
901
|
+
//#endregion
|
|
902
|
+
export { indexedDbPersistentStorage as n, createIndexedDbPersistentStorage as t };
|