tsdf 18.3.1 → 18.5.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.
@@ -1,966 +0,0 @@
1
- import { $ as matchesConditionalRemove, J as compareMetadata, Q as getPersistedNamespaceId, X as getNamespaceId, Y as encodePersistedAsyncNamespaceKind, Z as getPayloadRecordKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as emitTSDFDebugLog, et as normalizeStaticPolicy, i as createAsyncStorageAdapter, j as serializeJsonForStorage, nt as parsePersistedAsyncNamespaceKind, rt as serializeProtectedRef, tt as parseAsyncStorageRecordKey, x as getTSDFDebugTimingMs } from "./asyncStorageAdapter-NrI38v4g.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
- "g",
111
- "i",
112
- "m",
113
- "o",
114
- "p",
115
- "v",
116
- "z"
117
- ]);
118
- const INDEXED_DB_NAMESPACE_POLICY_RECORD_KEYS = new Set(["p", "s"]);
119
- function toRecordValue(value) {
120
- return __LEGIT_CAST__(value);
121
- }
122
- function toEntryRecordValue(value) {
123
- return __LEGIT_CAST__(value);
124
- }
125
- function toNamespacePolicyRecordValue(value) {
126
- return __LEGIT_CAST__(value);
127
- }
128
- function parseIndexedDbPersistedStaticPolicy(value) {
129
- if (value === null || value === void 0) return null;
130
- if (!isObject(value)) return void 0;
131
- const record = toRecordValue(value);
132
- if (Object.keys(record).some((key) => key !== "b" && key !== "k")) return;
133
- const rawMaxBytes = record.b;
134
- if (rawMaxBytes !== void 0 && (typeof rawMaxBytes !== "number" || !Number.isInteger(rawMaxBytes) || rawMaxBytes < 0)) return;
135
- const validatedPinnedKeys = record.k === void 0 ? void 0 : validateStringArray(record.k);
136
- if (validatedPinnedKeys === null) return void 0;
137
- return normalizeStaticPolicy({
138
- ...typeof record.b === "number" ? { maxBytes: record.b } : {},
139
- ...validatedPinnedKeys !== void 0 ? { pinnedKeys: validatedPinnedKeys } : {}
140
- });
141
- }
142
- function serializeIndexedDbPersistedStaticPolicy(policy) {
143
- const normalizedPolicy = normalizeStaticPolicy(policy);
144
- if (normalizedPolicy === null) return null;
145
- return {
146
- ...normalizedPolicy.maxBytes !== void 0 ? { b: normalizedPolicy.maxBytes } : {},
147
- ...normalizedPolicy.pinnedKeys !== void 0 && normalizedPolicy.pinnedKeys.length > 0 ? { k: normalizedPolicy.pinnedKeys } : {}
148
- };
149
- }
150
- function validateStringArray(value) {
151
- if (!Array.isArray(value)) return null;
152
- const result = [];
153
- for (const entry of value) {
154
- if (typeof entry !== "string") return null;
155
- result.push(entry);
156
- }
157
- return result;
158
- }
159
- function isValidEntryRecord(record) {
160
- if (!isObject(record)) return false;
161
- const recordValue = toRecordValue(record);
162
- if (Object.keys(recordValue).some((key) => !INDEXED_DB_ENTRY_RECORD_KEYS.has(key))) return false;
163
- 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);
164
- }
165
- function isValidNamespacePolicyRecord(record) {
166
- if (!isObject(record)) return false;
167
- const recordValue = toRecordValue(record);
168
- if (Object.keys(recordValue).some((key) => !INDEXED_DB_NAMESPACE_POLICY_RECORD_KEYS.has(key))) return false;
169
- if (typeof recordValue.s !== "string" || !("p" in recordValue)) return false;
170
- return recordValue.p === null || parseIndexedDbPersistedStaticPolicy(recordValue.p) !== void 0;
171
- }
172
- function getStaticPolicyFromScopeRecord(record) {
173
- if (record === void 0) return null;
174
- return parseIndexedDbPersistedStaticPolicy(record.p) ?? null;
175
- }
176
- function compactEntryValue(scope, value) {
177
- return { d: value };
178
- }
179
- function estimateIndexedDbManagedEntrySizeBytes(args) {
180
- return estimateManagedAsyncStorageEntrySizeBytes(args.serializedValue ?? serializeJsonForStorage(args.value).rawValue, args.lastAccessAt, args.version, args.customMetadata);
181
- }
182
- function expandEntryValue(scope, record) {
183
- return record.d;
184
- }
185
- function openRequestAsPromise(request) {
186
- return new Promise((resolve, reject) => {
187
- request.onsuccess = () => resolve(__LEGIT_CAST__(request.result));
188
- request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB request failed."));
189
- });
190
- }
191
- function transactionDone(transaction) {
192
- return new Promise((resolve, reject) => {
193
- transaction.oncomplete = () => resolve();
194
- transaction.onerror = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB transaction failed."));
195
- transaction.onabort = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB transaction aborted."));
196
- });
197
- }
198
- async function iterateCursor(request, callback) {
199
- await new Promise((resolve, reject) => {
200
- request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB cursor request failed."));
201
- request.onsuccess = async () => {
202
- const cursor = request.result;
203
- if (cursor === null) {
204
- resolve();
205
- return;
206
- }
207
- try {
208
- await callback(cursor);
209
- cursor.continue();
210
- } catch (error) {
211
- reject(error instanceof Error ? error : /* @__PURE__ */ new Error("IndexedDB cursor callback failed."));
212
- }
213
- };
214
- });
215
- }
216
- function deleteDatabase(databaseName) {
217
- return new Promise((resolve, reject) => {
218
- const request = indexedDB.deleteDatabase(databaseName);
219
- request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB deleteDatabase failed."));
220
- request.onblocked = () => resolve();
221
- request.onsuccess = () => resolve();
222
- });
223
- }
224
- async function getMaintenanceState(database) {
225
- const transaction = database.transaction(INDEXED_DB_META_STORE, "readonly");
226
- const value = await openRequestAsPromise(transaction.objectStore(INDEXED_DB_META_STORE).get(INDEXED_DB_MAINTENANCE_META_KEY));
227
- await transactionDone(transaction);
228
- const recordValue = value?.v;
229
- if (!isObject(recordValue)) return { lastSuccessfulCleanupAt: null };
230
- const metadataRecord = toRecordValue(recordValue);
231
- if (!("lca" in metadataRecord)) return { lastSuccessfulCleanupAt: null };
232
- const lastSuccessfulCleanupAt = metadataRecord.lca;
233
- return { lastSuccessfulCleanupAt: typeof lastSuccessfulCleanupAt === "number" || lastSuccessfulCleanupAt === null ? lastSuccessfulCleanupAt : null };
234
- }
235
- async function setMaintenanceState(database, value) {
236
- const transaction = database.transaction(INDEXED_DB_META_STORE, "readwrite");
237
- transaction.objectStore(INDEXED_DB_META_STORE).put({
238
- k: INDEXED_DB_MAINTENANCE_META_KEY,
239
- v: { lca: value.lastSuccessfulCleanupAt }
240
- });
241
- await transactionDone(transaction);
242
- }
243
- var IndexedDbAsyncStorageDriver = class {
244
- debugLogger;
245
- __tsdfManagedStorage = {
246
- applyManagedCommit: this.applyManagedCommit.bind(this),
247
- clearManagedNamespace: this.clearManagedNamespace.bind(this),
248
- listManagedKeys: this.listManagedKeys.bind(this),
249
- listManagedMetadata: this.listManagedMetadata.bind(this),
250
- persistNamespaceIndexState: this.persistNamespaceIndexState.bind(this),
251
- readProtectedStorageKeys: this.readProtectedStorageKeys.bind(this),
252
- readManagedEntries: this.readManagedEntries.bind(this),
253
- readNamespaceIndexState: this.readNamespaceIndexState.bind(this),
254
- syncSessionProtectedKeys: this.syncSessionProtectedKeys.bind(this)
255
- };
256
- #databasePromise = null;
257
- #instrumentation;
258
- databaseName;
259
- storageId;
260
- constructor(databaseName = DEFAULT_INDEXED_DB_NAME, instrumentation = void 0) {
261
- this.databaseName = databaseName;
262
- this.storageId = `indexedDb:${databaseName}`;
263
- this.#instrumentation = instrumentation;
264
- }
265
- async get(scope, key) {
266
- const parsedKey = parseAsyncStorageRecordKey(key);
267
- if (parsedKey.recordKind === "payload") {
268
- const entry = await this.#getEntry(scope, parsedKey.userKey);
269
- return entry === null ? null : expandEntryValue(scope, entry);
270
- }
271
- if (parsedKey.rawKey !== "_i") return null;
272
- const state = await this.readNamespaceIndexState(scope);
273
- if (!state.exists || !state.valid || state.entries === null) return null;
274
- return {
275
- e: Object.fromEntries([...state.entries.entries()].map(([entryKey, metadata]) => [entryKey, {
276
- a: metadata.lastAccessAt,
277
- ...metadata.version !== 1 ? { v: metadata.version } : {},
278
- ...metadata.sizeBytes !== void 0 ? { z: metadata.sizeBytes } : {},
279
- ...metadata.customMetadata ?? {}
280
- }])),
281
- ...state.staticPolicy !== null ? { s: state.staticPolicy } : {}
282
- };
283
- }
284
- async set(scope, key, value) {
285
- await this.setMany(scope, [{
286
- key,
287
- value
288
- }]);
289
- }
290
- async remove(scope, key) {
291
- await this.removeMany(scope, [key]);
292
- }
293
- async getMany(scope, keys) {
294
- return Promise.all(keys.map((key) => this.get(scope, key)));
295
- }
296
- async setMany(scope, entries) {
297
- for (const entry of entries) {
298
- const parsedKey = parseAsyncStorageRecordKey(entry.key);
299
- if (parsedKey.recordKind === "payload") {
300
- const existing = await this.#getEntry(scope, parsedKey.userKey);
301
- const lastAccessAt = existing?.a ?? Date.now();
302
- await this.#putEntryRecord(scope, {
303
- customMetadata: existing === null ? void 0 : getCustomMetadataFromEntryRecord(existing),
304
- key: parsedKey.userKey,
305
- lastAccessAt,
306
- value: entry.value,
307
- version: existing?.v ?? 1
308
- });
309
- continue;
310
- }
311
- if (parsedKey.rawKey === "_i") {
312
- const state = this.#parsePersistedIndexState(entry.value);
313
- if (state !== null) await this.persistNamespaceIndexState(scope, state);
314
- }
315
- }
316
- }
317
- async removeMany(scope, keys) {
318
- const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
319
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
320
- const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
321
- const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
322
- let removedAnyEntry = false;
323
- let removedScope = false;
324
- for (const key of keys) {
325
- const parsedKey = parseAsyncStorageRecordKey(key);
326
- if (parsedKey.recordKind === "payload") {
327
- entryStore.delete(createEntryPrimaryKey(scope, parsedKey.userKey));
328
- removedAnyEntry = true;
329
- continue;
330
- }
331
- if (parsedKey.rawKey === "_i") {
332
- policyStore.delete(createScopePolicyKey(scope));
333
- removedScope = true;
334
- }
335
- }
336
- if (removedAnyEntry && !removedScope) {
337
- const countRequest = entryStore.count(createScopeKeyRange(scope));
338
- countRequest.onsuccess = () => {
339
- if (countRequest.result === 0) policyStore.delete(createScopePolicyKey(scope));
340
- };
341
- }
342
- await transactionDone(transaction);
343
- if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-records", startTime, {
344
- keyCount: keys.length,
345
- objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE]
346
- });
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 startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
370
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
371
- const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
372
- const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
373
- const discoveredScopes = [];
374
- await iterateCursor(sessionKey === void 0 ? policyStore.openKeyCursor() : policyStore.index("bySession").openKeyCursor(IDBKeyRange.only(sessionKey)), async (cursor) => {
375
- const scope = getScopeFromPrimaryKey(cursor.primaryKey);
376
- if (scope === null) return;
377
- const keys = new Set(["_i"]);
378
- await iterateCursor(entryStore.openKeyCursor(createScopeKeyRange(scope)), (entryCursor) => {
379
- const entryKey = getEntryKeyFromPrimaryKey(entryCursor.primaryKey);
380
- if (entryKey === null) return;
381
- keys.add(getPayloadRecordKey(entryKey));
382
- });
383
- discoveredScopes.push({
384
- knownRecordKeys: [...keys].sort((left, right) => left.localeCompare(right)),
385
- scope
386
- });
387
- });
388
- await transactionDone(transaction);
389
- if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(void 0, "list-scopes", startTime, {
390
- count: discoveredScopes.length,
391
- objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
392
- ...sessionKey !== void 0 ? { sessionKey } : {}
393
- });
394
- discoveredScopes.sort((left, right) => getNamespaceId(left.scope).localeCompare(getNamespaceId(right.scope)));
395
- this.#instrumentation?.record({
396
- scopeIds: discoveredScopes.map(({ scope }) => getNamespaceId(scope)),
397
- ...sessionKey !== void 0 ? { sessionKey } : {},
398
- time: Date.now(),
399
- type: "listScopesWithKnownRecordKeys"
400
- });
401
- return discoveredScopes;
402
- }
403
- async readManagedEntries(scope, keys) {
404
- const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
405
- const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
406
- const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
407
- const uniqueKeys = [...new Set(keys)];
408
- const result = /* @__PURE__ */ new Map();
409
- await Promise.all(uniqueKeys.map(async (key) => {
410
- const record = await openRequestAsPromise(store.get(createEntryPrimaryKey(scope, key)));
411
- if (!isValidEntryRecord(record)) {
412
- result.set(key, null);
413
- return;
414
- }
415
- const entryRecord = toEntryRecordValue(record);
416
- result.set(key, {
417
- metadata: toPublicMetadata(key, entryRecord),
418
- value: __LEGIT_CAST__(expandEntryValue(scope, entryRecord))
419
- });
420
- }));
421
- await transactionDone(transaction);
422
- if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "read-records", startTime, {
423
- hitCount: [...result.values()].filter((value) => value !== null).length,
424
- keyCount: uniqueKeys.length,
425
- objectStores: [INDEXED_DB_ENTRY_STORE]
426
- });
427
- this.#instrumentation?.record({
428
- keys: uniqueKeys,
429
- resultKeys: [...result.entries()].flatMap(([key, value]) => value === null ? [] : [key]).sort((left, right) => left.localeCompare(right)),
430
- scope,
431
- time: Date.now(),
432
- type: "readManagedEntries"
433
- });
434
- return result;
435
- }
436
- async listManagedMetadata(scope, args = {}) {
437
- const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
438
- const order = args.order ?? "key";
439
- const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
440
- const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
441
- const entries = [];
442
- let usedIndex = "key";
443
- if (args.filter?.key === "g" && typeof args.filter.equals === "string" && order === "key") {
444
- usedIndex = "group";
445
- await iterateCursor(store.index("byScopeGroup").openCursor(createScopeGroupRange(scope, args.filter.equals)), (cursor) => {
446
- const record = cursor.value;
447
- const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
448
- if (!isValidEntryRecord(record) || entryKey === null) return;
449
- entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
450
- });
451
- } else if (order === "lru-asc" || order === "lru-desc") {
452
- usedIndex = "lru";
453
- await iterateCursor(store.index("byScopeLastAccessAt").openCursor(createScopeLastAccessRange(scope), order === "lru-desc" ? "prev" : "next"), (cursor) => {
454
- const record = cursor.value;
455
- const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
456
- if (!isValidEntryRecord(record) || entryKey === null) return;
457
- entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
458
- });
459
- } else await iterateCursor(store.openCursor(createScopeKeyRange(scope)), (cursor) => {
460
- const record = cursor.value;
461
- const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
462
- if (!isValidEntryRecord(record) || entryKey === null) return;
463
- entries.push(toPublicMetadata(entryKey, toEntryRecordValue(record)));
464
- });
465
- await transactionDone(transaction);
466
- const filter = args.filter;
467
- const filteredEntries = filter === void 0 ? entries : entries.filter((entry) => entry.customMetadata[filter.key] === filter.equals);
468
- if (usedIndex !== "lru") filteredEntries.sort((left, right) => compareMetadata(left, right, order));
469
- if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-record-metadata", startTime, {
470
- count: filteredEntries.length,
471
- objectStores: [INDEXED_DB_ENTRY_STORE],
472
- order,
473
- usedIndex
474
- });
475
- this.#instrumentation?.record({
476
- order,
477
- resultKeys: filteredEntries.map((entry) => entry.key),
478
- scope,
479
- time: Date.now(),
480
- type: "listManagedMetadata",
481
- usedIndex
482
- });
483
- return filteredEntries;
484
- }
485
- async listManagedKeys(scope) {
486
- return (await this.listManagedMetadata(scope, { order: "key" })).map((entry) => entry.key);
487
- }
488
- async clearManagedNamespace(scope) {
489
- const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
490
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
491
- const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
492
- const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
493
- await iterateCursor(entryStore.openCursor(createScopeKeyRange(scope)), (cursor) => {
494
- cursor.delete();
495
- });
496
- policyStore.delete(createScopePolicyKey(scope));
497
- await transactionDone(transaction);
498
- if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "clear-records", startTime, { objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE] });
499
- this.#instrumentation?.onClearManagedNamespace?.(scope);
500
- this.#instrumentation?.record({
501
- scope,
502
- time: Date.now(),
503
- type: "clearManagedNamespace"
504
- });
505
- }
506
- async applyManagedCommit(scope, args, helpers) {
507
- const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
508
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
509
- const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
510
- const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
511
- const upserts = args.upserts ?? [];
512
- const removes = [...new Set(args.removes ?? [])];
513
- const conditionalRemoves = args.conditionalRemoves ?? [];
514
- const touches = args.touches ?? [];
515
- const scopeId = createScopeId(scope.sessionKey, scope.storeName, scope.kind);
516
- const uniqueKeys = [...new Set([
517
- ...removes,
518
- ...conditionalRemoves.map((remove) => remove.key),
519
- ...touches.map((touch) => touch.key),
520
- ...upserts.map((upsert) => upsert.key)
521
- ])];
522
- const existingEntries = /* @__PURE__ */ new Map();
523
- const now = Date.now();
524
- const touchTimestamps = new Map(touches.map((touch) => [touch.key, touch.lastAccessAt ?? now]));
525
- const rawScopeRecord = await openRequestAsPromise(policyStore.get(createScopePolicyKey(scope)));
526
- const existingStaticPolicy = isValidNamespacePolicyRecord(rawScopeRecord) ? getStaticPolicyFromScopeRecord(toNamespacePolicyRecordValue(rawScopeRecord)) : null;
527
- await Promise.all(uniqueKeys.map(async (key) => {
528
- const record = await openRequestAsPromise(entryStore.get(createEntryPrimaryKey(scope, key)));
529
- if (isValidEntryRecord(record)) existingEntries.set(key, toEntryRecordValue(record));
530
- }));
531
- const staleConditionalRemoveKeys = /* @__PURE__ */ new Set();
532
- for (const remove of conditionalRemoves) {
533
- const existing = existingEntries.get(remove.key);
534
- if (existing === void 0) continue;
535
- if (matchesConditionalRemove(remove, existing.a, existing.z, existing.v ?? 1, existing.o === 1)) removes.push(remove.key);
536
- else staleConditionalRemoveKeys.add(remove.key);
537
- }
538
- for (const key of removes) entryStore.delete(createEntryPrimaryKey(scope, key));
539
- const upsertKeySet = new Set(upserts.map((upsert) => upsert.key));
540
- for (const upsert of upserts) {
541
- const existing = existingEntries.get(upsert.key);
542
- const customMetadata = helpers.mergeOfflineProtectionMetadata(upsert.key, upsert.metadata, existing === void 0 ? void 0 : getCustomMetadataFromEntryRecord(existing));
543
- const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(customMetadata);
544
- const nextLastAccessAt = touchTimestamps.get(upsert.key) ?? existing?.a ?? now;
545
- const sizeBytes = scope.kind !== "document" ? estimateIndexedDbManagedEntrySizeBytes({
546
- customMetadata,
547
- lastAccessAt: nextLastAccessAt,
548
- serializedValue: upsert.serializedValue,
549
- value: upsert.value,
550
- version: upsert.version
551
- }) : void 0;
552
- const compactValue = compactEntryValue(scope, upsert.value);
553
- await openRequestAsPromise(entryStore.put({
554
- a: nextLastAccessAt,
555
- ...compactValue,
556
- ...group !== void 0 ? { g: group } : {},
557
- i: scopeId,
558
- ...extraMetadata !== void 0 ? { m: extraMetadata } : {},
559
- ...offlineProtected === true ? { o: 1 } : {},
560
- ...payload !== void 0 ? { p: payload } : {},
561
- ...upsert.version !== 1 ? { v: upsert.version } : {},
562
- ...sizeBytes !== void 0 ? { z: sizeBytes } : {}
563
- }, createEntryPrimaryKey(scope, upsert.key)));
564
- }
565
- for (const touch of touches) {
566
- if (upsertKeySet.has(touch.key)) continue;
567
- const existing = existingEntries.get(touch.key);
568
- if (existing === void 0) continue;
569
- const nextLastAccessAt = touch.lastAccessAt ?? now;
570
- if (existing.a === nextLastAccessAt) continue;
571
- await openRequestAsPromise(entryStore.put({
572
- ...existing,
573
- a: nextLastAccessAt
574
- }, createEntryPrimaryKey(scope, touch.key)));
575
- }
576
- const normalizedStaticPolicy = "staticPolicy" in args ? normalizeStaticPolicy(args.staticPolicy) : void 0;
577
- if (await openRequestAsPromise(entryStore.count(createScopeKeyRange(scope))) === 0) policyStore.delete(createScopePolicyKey(scope));
578
- else await openRequestAsPromise(policyStore.put({
579
- p: serializeIndexedDbPersistedStaticPolicy(normalizedStaticPolicy ?? existingStaticPolicy),
580
- s: scope.sessionKey
581
- }, createScopePolicyKey(scope)));
582
- await transactionDone(transaction);
583
- if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-records", startTime, {
584
- objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
585
- removes: removes.length,
586
- touches: touches.length,
587
- upserts: upserts.length
588
- });
589
- this.#instrumentation?.onApplyManagedCommit?.(scope, args);
590
- this.#instrumentation?.record({
591
- removes,
592
- scope,
593
- staticPolicyChanged: "staticPolicy" in args,
594
- time: Date.now(),
595
- touches: touches.map((touch) => touch.key).sort((left, right) => left.localeCompare(right)),
596
- type: "applyManagedCommit",
597
- upserts: upserts.map((upsert) => upsert.key).sort((left, right) => left.localeCompare(right))
598
- });
599
- return staleConditionalRemoveKeys;
600
- }
601
- async readNamespaceIndexState(scope, knownRecordKeys_) {
602
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
603
- const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
604
- const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
605
- const entries = /* @__PURE__ */ new Map();
606
- let invalidEntryCount = 0;
607
- await iterateCursor(entryStore.openCursor(createScopeKeyRange(scope)), (cursor) => {
608
- const record = cursor.value;
609
- const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
610
- if (!isValidEntryRecord(record)) {
611
- invalidEntryCount += 1;
612
- return;
613
- }
614
- if (entryKey === null) {
615
- invalidEntryCount += 1;
616
- return;
617
- }
618
- entries.set(entryKey, toMetadataRecord(toEntryRecordValue(record)));
619
- });
620
- const rawPolicy = await openRequestAsPromise(policyStore.get(createScopePolicyKey(scope)));
621
- await transactionDone(transaction);
622
- if (invalidEntryCount > 0) {
623
- const result = {
624
- entries: null,
625
- exists: entries.size > 0 || rawPolicy !== void 0,
626
- staticPolicy: null,
627
- valid: false
628
- };
629
- this.#instrumentation?.record({
630
- exists: result.exists,
631
- keyCount: entries.size,
632
- scope,
633
- time: Date.now(),
634
- type: "readManagedIndexState",
635
- valid: result.valid
636
- });
637
- return result;
638
- }
639
- if (rawPolicy !== void 0 && !isValidNamespacePolicyRecord(rawPolicy)) {
640
- const result = {
641
- entries: null,
642
- exists: true,
643
- staticPolicy: null,
644
- valid: false
645
- };
646
- this.#instrumentation?.record({
647
- exists: result.exists,
648
- keyCount: entries.size,
649
- scope,
650
- time: Date.now(),
651
- type: "readManagedIndexState",
652
- valid: result.valid
653
- });
654
- return result;
655
- }
656
- const exists = rawPolicy !== void 0 || entries.size > 0;
657
- if (rawPolicy === void 0 && entries.size > 0 || rawPolicy !== void 0 && entries.size === 0) {
658
- const result = {
659
- entries: null,
660
- exists,
661
- staticPolicy: null,
662
- valid: false
663
- };
664
- this.#instrumentation?.record({
665
- exists: result.exists,
666
- keyCount: entries.size,
667
- scope,
668
- time: Date.now(),
669
- type: "readManagedIndexState",
670
- valid: result.valid
671
- });
672
- return result;
673
- }
674
- const result = {
675
- entries,
676
- exists: rawPolicy !== void 0,
677
- staticPolicy: getStaticPolicyFromScopeRecord(rawPolicy === void 0 ? void 0 : toNamespacePolicyRecordValue(rawPolicy)),
678
- valid: true
679
- };
680
- this.#instrumentation?.record({
681
- exists: result.exists,
682
- keyCount: result.entries.size,
683
- scope,
684
- time: Date.now(),
685
- type: "readManagedIndexState",
686
- valid: result.valid
687
- });
688
- return result;
689
- }
690
- async persistNamespaceIndexState(scope, state) {
691
- const database = await this.#getDatabase();
692
- const existingEntries = /* @__PURE__ */ new Map();
693
- const readTransaction = database.transaction(INDEXED_DB_ENTRY_STORE, "readonly");
694
- const readStore = readTransaction.objectStore(INDEXED_DB_ENTRY_STORE);
695
- const desiredKeys = [...state.entries.keys()];
696
- await Promise.all(desiredKeys.map(async (key) => {
697
- const existing = await openRequestAsPromise(readStore.get(createEntryPrimaryKey(scope, key)));
698
- if (isValidEntryRecord(existing)) existingEntries.set(key, toEntryRecordValue(existing));
699
- }));
700
- await transactionDone(readTransaction);
701
- const writeTransaction = database.transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
702
- const entryStore = writeTransaction.objectStore(INDEXED_DB_ENTRY_STORE);
703
- const policyStore = writeTransaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
704
- for (const [key, metadata] of state.entries.entries()) {
705
- const existing = existingEntries.get(key);
706
- if (existing === void 0) continue;
707
- const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(metadata.customMetadata);
708
- entryStore.put({
709
- ...existing,
710
- a: metadata.lastAccessAt,
711
- ...group !== void 0 ? { g: group } : {},
712
- ...group === void 0 ? { g: void 0 } : {},
713
- ...extraMetadata !== void 0 ? { m: extraMetadata } : {},
714
- ...extraMetadata === void 0 ? { m: void 0 } : {},
715
- ...offlineProtected === true ? { o: 1 } : {},
716
- ...offlineProtected !== true ? { o: void 0 } : {},
717
- ...payload !== void 0 ? { p: payload } : {},
718
- ...payload === void 0 ? { p: void 0 } : {},
719
- ...metadata.version !== 1 ? { v: metadata.version } : {},
720
- ...metadata.version === 1 ? { v: void 0 } : {},
721
- ...metadata.sizeBytes !== void 0 ? { z: metadata.sizeBytes } : {},
722
- ...metadata.sizeBytes === void 0 ? { z: void 0 } : {}
723
- }, createEntryPrimaryKey(scope, key));
724
- }
725
- if (state.entries.size === 0) policyStore.delete(createScopePolicyKey(scope));
726
- else policyStore.put({
727
- p: serializeIndexedDbPersistedStaticPolicy(state.staticPolicy),
728
- s: scope.sessionKey
729
- }, createScopePolicyKey(scope));
730
- await transactionDone(writeTransaction);
731
- this.#instrumentation?.onPersistNamespaceIndexState?.(scope, state);
732
- this.#instrumentation?.record({
733
- keyCount: state.entries.size,
734
- scope,
735
- staticPolicy: state.staticPolicy,
736
- time: Date.now(),
737
- type: "persistManagedIndexState"
738
- });
739
- }
740
- async readProtectedStorageKeys(sessionKey) {
741
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
742
- const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
743
- const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
744
- const values = [];
745
- await iterateCursor(policyStore.index("bySession").openCursor(IDBKeyRange.only(sessionKey)), async (scopeCursor) => {
746
- const scope = getScopeFromPrimaryKey(scopeCursor.primaryKey);
747
- if (scope === null) return;
748
- await iterateCursor(entryStore.index("byScopeOfflineProtected").openCursor(createScopeOfflineProtectedRange(scope)), (entryCursor) => {
749
- const entryKey = getEntryKeyFromPrimaryKey(entryCursor.primaryKey);
750
- const record = entryCursor.value;
751
- if (!isValidEntryRecord(record) || entryKey === null) return;
752
- values.push(serializeProtectedRef({
753
- ...scope,
754
- key: entryKey
755
- }));
756
- });
757
- });
758
- await transactionDone(transaction);
759
- this.#instrumentation?.record({
760
- sessionKey,
761
- time: Date.now(),
762
- type: "readProtectedStorageKeys",
763
- values: [...values].sort((left, right) => left.localeCompare(right))
764
- });
765
- return values;
766
- }
767
- async syncSessionProtectedKeys(sessionKey, protectedKeys) {
768
- const nextProtectedKeys = new Set(protectedKeys);
769
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
770
- const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
771
- await iterateCursor(transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE).index("bySession").openCursor(IDBKeyRange.only(sessionKey)), async (scopeCursor) => {
772
- const scope = getScopeFromPrimaryKey(scopeCursor.primaryKey);
773
- if (scope === null) return;
774
- await iterateCursor(store.openCursor(createScopeKeyRange(scope)), (cursor) => {
775
- const record = cursor.value;
776
- const entryKey = getEntryKeyFromPrimaryKey(cursor.primaryKey);
777
- if (!isValidEntryRecord(record) || entryKey === null) return;
778
- const entryRecord = toEntryRecordValue(record);
779
- const ref = serializeProtectedRef({
780
- ...scope,
781
- key: entryKey
782
- });
783
- const shouldProtect = nextProtectedKeys.has(ref);
784
- if (entryRecord.o === 1 === shouldProtect) return;
785
- const nextRecord = {
786
- ...entryRecord,
787
- ...shouldProtect ? { o: 1 } : { o: void 0 }
788
- };
789
- cursor.update(nextRecord);
790
- });
791
- });
792
- await transactionDone(transaction);
793
- this.#instrumentation?.record({
794
- sessionKey,
795
- time: Date.now(),
796
- type: "syncSessionProtectedKeys",
797
- values: [...nextProtectedKeys].sort((left, right) => left.localeCompare(right))
798
- });
799
- }
800
- async readMaintenanceState() {
801
- return getMaintenanceState(await this.#getDatabase());
802
- }
803
- async writeMaintenanceState(value) {
804
- await setMaintenanceState(await this.#getDatabase(), value);
805
- }
806
- async __resetForTests() {
807
- if (this.#databasePromise !== null) {
808
- (await this.#databasePromise).close();
809
- this.#databasePromise = null;
810
- }
811
- await deleteDatabase(this.databaseName);
812
- this.#instrumentation?.reset();
813
- }
814
- async __inspectStructureForTests() {
815
- const database = await this.#getDatabase();
816
- const stores = [];
817
- for (const storeName of [...database.objectStoreNames].sort((left, right) => left.localeCompare(right))) {
818
- const transaction = database.transaction(storeName, "readonly");
819
- const store = transaction.objectStore(storeName);
820
- const indexes = [...store.indexNames].sort((left, right) => left.localeCompare(right)).map((indexName) => {
821
- const index = store.index(indexName);
822
- return {
823
- keyPath: index.keyPath,
824
- multiEntry: index.multiEntry,
825
- name: index.name,
826
- unique: index.unique
827
- };
828
- });
829
- const [keys, values] = await Promise.all([openRequestAsPromise(store.getAllKeys()), openRequestAsPromise(store.getAll())]);
830
- await transactionDone(transaction);
831
- stores.push({
832
- autoIncrement: store.autoIncrement,
833
- indexes,
834
- keyPath: store.keyPath,
835
- name: storeName,
836
- rows: keys.map((key, index) => ({
837
- key,
838
- value: values[index]
839
- }))
840
- });
841
- }
842
- return {
843
- stores,
844
- version: database.version
845
- };
846
- }
847
- async #getEntry(scope, key) {
848
- const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
849
- const record = await openRequestAsPromise(transaction.objectStore(INDEXED_DB_ENTRY_STORE).get(createEntryPrimaryKey(scope, key)));
850
- await transactionDone(transaction);
851
- return isValidEntryRecord(record) ? toEntryRecordValue(record) : null;
852
- }
853
- async #putEntryRecord(scope, args) {
854
- const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
855
- const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
856
- const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
857
- const existingScopeRecord = await openRequestAsPromise(policyStore.get(createScopePolicyKey(scope)));
858
- const { extraMetadata, group, offlineProtected, payload } = splitCustomMetadata(args.customMetadata);
859
- const sizeBytes = scope.kind !== "document" ? estimateIndexedDbManagedEntrySizeBytes({
860
- customMetadata: args.customMetadata,
861
- lastAccessAt: args.lastAccessAt,
862
- value: args.value,
863
- version: args.version
864
- }) : void 0;
865
- const compactValue = compactEntryValue(scope, args.value);
866
- entryStore.put({
867
- a: args.lastAccessAt,
868
- ...compactValue,
869
- ...group !== void 0 ? { g: group } : {},
870
- i: createScopeId(scope.sessionKey, scope.storeName, scope.kind),
871
- ...extraMetadata !== void 0 ? { m: extraMetadata } : {},
872
- ...offlineProtected === true ? { o: 1 } : {},
873
- ...payload !== void 0 ? { p: payload } : {},
874
- ...args.version !== 1 ? { v: args.version } : {},
875
- ...sizeBytes !== void 0 ? { z: sizeBytes } : {}
876
- }, createEntryPrimaryKey(scope, args.key));
877
- policyStore.put({
878
- p: serializeIndexedDbPersistedStaticPolicy(getStaticPolicyFromScopeRecord(isValidNamespacePolicyRecord(existingScopeRecord) ? toNamespacePolicyRecordValue(existingScopeRecord) : void 0)),
879
- s: scope.sessionKey
880
- }, createScopePolicyKey(scope));
881
- await transactionDone(transaction);
882
- }
883
- #parsePersistedIndexState(value) {
884
- if (!isObject(value)) return null;
885
- const recordValue = toRecordValue(value);
886
- const rawEntries = recordValue.e;
887
- if (!isObject(rawEntries)) return null;
888
- const rawEntriesRecord = toRecordValue(rawEntries);
889
- const entries = /* @__PURE__ */ new Map();
890
- for (const [key, rawMetadata] of Object.entries(rawEntriesRecord)) {
891
- if (!isObject(rawMetadata)) return null;
892
- const rawMetadataRecord = toRecordValue(rawMetadata);
893
- if (typeof rawMetadataRecord.a !== "number") return null;
894
- const customMetadata = Object.fromEntries(Object.entries(rawMetadataRecord).filter(([metadataKey]) => metadataKey !== "a" && metadataKey !== "v" && metadataKey !== "z"));
895
- entries.set(key, {
896
- ...Object.keys(customMetadata).length > 0 ? { customMetadata } : {},
897
- lastAccessAt: rawMetadataRecord.a,
898
- ...typeof rawMetadataRecord.z === "number" ? { sizeBytes: rawMetadataRecord.z } : {},
899
- version: typeof rawMetadataRecord.v === "number" ? rawMetadataRecord.v : 1
900
- });
901
- }
902
- const staticPolicy = parseIndexedDbPersistedStaticPolicy(recordValue.s);
903
- if (staticPolicy === void 0) return null;
904
- return {
905
- entries,
906
- staticPolicy
907
- };
908
- }
909
- async #getDatabase() {
910
- if (this.#databasePromise !== null) return this.#databasePromise;
911
- this.#databasePromise = new Promise((resolve, reject) => {
912
- const request = indexedDB.open(this.databaseName, INDEXED_DB_VERSION);
913
- request.onupgradeneeded = () => {
914
- const database = request.result;
915
- if (database.objectStoreNames.contains(INDEXED_DB_ENTRY_STORE)) database.deleteObjectStore(INDEXED_DB_ENTRY_STORE);
916
- if (database.objectStoreNames.contains(INDEXED_DB_NAMESPACE_POLICY_STORE)) database.deleteObjectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
917
- const entryStore = database.createObjectStore(INDEXED_DB_ENTRY_STORE);
918
- entryStore.createIndex("byScopeLastAccessAt", ["i", "a"], { unique: false });
919
- entryStore.createIndex("byScopeGroup", ["i", "g"], { unique: false });
920
- entryStore.createIndex("byScopeOfflineProtected", ["i", "o"], { unique: false });
921
- database.createObjectStore(INDEXED_DB_NAMESPACE_POLICY_STORE).createIndex("bySession", "s", { unique: false });
922
- if (!database.objectStoreNames.contains(INDEXED_DB_META_STORE)) database.createObjectStore(INDEXED_DB_META_STORE, { keyPath: "k" });
923
- };
924
- request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB open failed."));
925
- request.onsuccess = () => resolve(request.result);
926
- });
927
- return this.#databasePromise;
928
- }
929
- #logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
930
- if (!import.meta.env.DEV) return;
931
- if (startTime === null) return;
932
- if (!this.debugLogger) return;
933
- const status = typeof details.status === "string" ? details.status : "success";
934
- emitTSDFDebugLog(this.debugLogger, {
935
- area: "persistent-storage",
936
- level: "log",
937
- message: `persistent storage adapter ${adapterOperation} ${status}`,
938
- operation: "adapter-operation",
939
- details: {
940
- adapter: "async",
941
- adapterName: "indexeddb",
942
- adapterOperation,
943
- databaseName: this.databaseName,
944
- durationMs: getTSDFDebugTimingMs() - startTime,
945
- status,
946
- ...scope !== void 0 ? {
947
- namespaceKind: scope.kind,
948
- sessionKey: scope.sessionKey,
949
- storeName: scope.storeName
950
- } : {},
951
- ...details
952
- }
953
- });
954
- }
955
- };
956
- function createIndexedDbPersistentStorage$1(options = {}) {
957
- return createAsyncStorageAdapter(new IndexedDbAsyncStorageDriver(options.databaseName));
958
- }
959
- //#endregion
960
- //#region src/persistentStorage/indexedDbPersistentStorage.ts
961
- const indexedDbPersistentStorage = /* @__PURE__ */ createIndexedDbPersistentStorage$1();
962
- function createIndexedDbPersistentStorage(options = {}) {
963
- return createIndexedDbPersistentStorage$1(options);
964
- }
965
- //#endregion
966
- export { indexedDbPersistentStorage as n, createIndexedDbPersistentStorage as t };