tsdf 17.0.0-alpha.8 → 17.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/async-storage.d.ts +1 -1
  2. package/dist/async-storage.js +2 -1
  3. package/dist/asyncStorageAdapter-CGfnsd9m.js +1945 -0
  4. package/dist/{asyncStorageAdapter-kvAIhrBD.d.ts → asyncStorageAdapter-CMohMeKm.d.ts} +1 -1
  5. package/dist/asyncStorageAdapters-BpfM2_Y6.js +3 -0
  6. package/dist/indexed-db-storage.d.ts +4 -2
  7. package/dist/indexed-db-storage.js +2 -1
  8. package/dist/indexedDbPersistentStorage-DC9GsYHH.js +954 -0
  9. package/dist/main.d.ts +355 -414
  10. package/dist/main.js +16046 -1
  11. package/dist/opfs-storage.d.ts +1 -1
  12. package/dist/opfs-storage.js +2 -1
  13. package/dist/{opfsPersistentStorage-D_fecOJg.d.ts → opfsPersistentStorage-Ci0JcCo5.d.ts} +1 -1
  14. package/dist/opfsPersistentStorage-DqJXzF7M.js +892 -0
  15. package/dist/{types-DkNgE_f9.d.ts → types-D0ttVGmj.d.ts} +395 -65
  16. package/docs/README.md +16 -16
  17. package/docs/batch-fetching.md +1 -1
  18. package/docs/browser-tabs-sync.md +5 -2
  19. package/docs/collection-store.md +26 -24
  20. package/docs/document-store.md +8 -6
  21. package/docs/fetch-scheduling.md +18 -14
  22. package/docs/list-query-store.md +37 -35
  23. package/docs/mutations.md +2 -0
  24. package/docs/offline.md +2 -2
  25. package/docs/offset-pagination.md +1 -4
  26. package/docs/optimistic-list-updates.md +13 -17
  27. package/docs/partial-resources.md +26 -1
  28. package/docs/persistent-storage.md +4 -2
  29. package/docs/real-time-updates.md +7 -5
  30. package/docs/store-manager.md +41 -14
  31. package/package.json +6 -3
  32. package/dist/asyncStorageAdapter-CgG3vm0t.js +0 -1
  33. package/dist/asyncStorageAdapters-eagaD77Y.js +0 -1
  34. package/dist/indexedDbPersistentStorage-JYXvMjTG.js +0 -1
  35. package/dist/opfsPersistentStorage-DS-SWDSq.js +0 -1
@@ -0,0 +1,1945 @@
1
+ import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
2
+ import { klona } from "klona/json";
3
+ import { isObject } from "@ls-stack/utils/typeGuards";
4
+ import { createCache } from "@ls-stack/utils/cache";
5
+ import { deepEqual } from "@ls-stack/utils/deepEqual";
6
+ import { sleep } from "@ls-stack/utils/sleep";
7
+ import { rc_array, rc_discriminated_union, rc_literals, rc_number, rc_object, rc_parse, rc_parse_json, rc_record, rc_string, rc_tuple, rc_unknown } from "runcheck";
8
+ import { asPossiblyUndefined } from "@ls-stack/utils/typingFnUtils";
9
+ //#region src/persistentStorage/scheduleIdleCleanup.ts
10
+ /**
11
+ * Schedules a fire-and-forget cleanup callback during idle time.
12
+ * Uses `requestIdleCallback` when available, falls back to `setTimeout(fn, 2000)`.
13
+ */
14
+ function scheduleIdleCleanup(callback) {
15
+ if (typeof requestIdleCallback === "function") {
16
+ const idleCallbackId = requestIdleCallback(() => callback(), { timeout: 3e3 });
17
+ return () => cancelIdleCallback(idleCallbackId);
18
+ } else {
19
+ const timeoutId = setTimeout(callback, 2e3);
20
+ return () => clearTimeout(timeoutId);
21
+ }
22
+ }
23
+ const INITIAL_MAINTENANCE_CLEANUP_DELAY_MS = 1e4;
24
+ /**
25
+ * Gives startup maintenance a short grace period before using the regular
26
+ * idle cleanup scheduling.
27
+ */
28
+ function scheduleInitialMaintenanceCleanup(callback) {
29
+ if (typeof requestIdleCallback !== "function") {
30
+ const timeoutId = setTimeout(callback, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS + 2e3);
31
+ return () => clearTimeout(timeoutId);
32
+ }
33
+ let cancelIdleCleanup = null;
34
+ const timeoutId = setTimeout(() => {
35
+ cancelIdleCleanup = scheduleIdleCleanup(callback);
36
+ }, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS);
37
+ return () => {
38
+ clearTimeout(timeoutId);
39
+ cancelIdleCleanup?.();
40
+ };
41
+ }
42
+ //#endregion
43
+ //#region src/persistentStorage/asyncStorageShared.ts
44
+ const PAYLOAD_RECORD_PREFIX = "__tsdf_payload__:";
45
+ function getNamespaceId(scope) {
46
+ return JSON.stringify([
47
+ scope.sessionKey,
48
+ scope.storeName,
49
+ scope.kind
50
+ ]);
51
+ }
52
+ function encodePersistedAsyncNamespaceKind(kind) {
53
+ switch (kind) {
54
+ case "document": return "d";
55
+ case "collection.item": return "ci";
56
+ case "listQuery.item": return "li";
57
+ case "listQuery.query": return "lq";
58
+ case "offline.queue": return "oq";
59
+ case "offline.conflict": return "oc";
60
+ case "offline.entity": return "oe";
61
+ case "__internal.protected": return "ip";
62
+ }
63
+ }
64
+ function parsePersistedAsyncNamespaceKind(value) {
65
+ switch (value) {
66
+ case "d": return "document";
67
+ case "ci": return "collection.item";
68
+ case "li": return "listQuery.item";
69
+ case "lq": return "listQuery.query";
70
+ case "oq": return "offline.queue";
71
+ case "oc": return "offline.conflict";
72
+ case "oe": return "offline.entity";
73
+ case "ip": return "__internal.protected";
74
+ default: return null;
75
+ }
76
+ }
77
+ function getPersistedNamespaceId(scope) {
78
+ return JSON.stringify([
79
+ scope.sessionKey,
80
+ scope.storeName,
81
+ encodePersistedAsyncNamespaceKind(scope.kind)
82
+ ]);
83
+ }
84
+ function getPayloadRecordKey(key) {
85
+ return `${PAYLOAD_RECORD_PREFIX}${key}`;
86
+ }
87
+ function serializeProtectedRef$1(ref) {
88
+ return JSON.stringify([
89
+ ref.sessionKey,
90
+ ref.storeName,
91
+ encodePersistedAsyncNamespaceKind(ref.kind),
92
+ ref.key
93
+ ]);
94
+ }
95
+ function parseProtectedRef(value) {
96
+ const parsed = rc_parse_json(value, rc_tuple([
97
+ rc_string,
98
+ rc_string,
99
+ rc_string,
100
+ rc_string
101
+ ])).unwrapOrNull();
102
+ if (parsed === null) return null;
103
+ const [sessionKey, storeName, rawKind, key] = parsed;
104
+ const kind = parsePersistedAsyncNamespaceKind(rawKind);
105
+ if (kind === null) return null;
106
+ return {
107
+ sessionKey,
108
+ storeName,
109
+ kind,
110
+ key
111
+ };
112
+ }
113
+ function parseAsyncStorageRecordKey(key) {
114
+ if (key.startsWith("__tsdf_payload__:")) return {
115
+ recordKind: "payload",
116
+ userKey: key.slice(17)
117
+ };
118
+ return {
119
+ rawKey: key,
120
+ recordKind: "raw"
121
+ };
122
+ }
123
+ function normalizeStaticPolicy(policy) {
124
+ if (policy === void 0 || policy === null) return null;
125
+ const maxBytes = typeof policy.maxBytes === "number" && Number.isInteger(policy.maxBytes) && policy.maxBytes >= 0 ? policy.maxBytes : void 0;
126
+ const pinnedKeys = Array.isArray(policy.pinnedKeys) ? [...new Set(policy.pinnedKeys)].sort((left, right) => left.localeCompare(right)) : [];
127
+ if (maxBytes === void 0 && pinnedKeys.length === 0) return null;
128
+ return {
129
+ ...maxBytes !== void 0 ? { maxBytes } : {},
130
+ ...pinnedKeys.length > 0 ? { pinnedKeys } : {}
131
+ };
132
+ }
133
+ function compareMetadata(left, right, order) {
134
+ if (order === "key") return left.key.localeCompare(right.key);
135
+ if (left.lastAccessAt !== right.lastAccessAt) return order === "lru-asc" ? left.lastAccessAt - right.lastAccessAt : right.lastAccessAt - left.lastAccessAt;
136
+ return left.key.localeCompare(right.key);
137
+ }
138
+ //#endregion
139
+ //#region src/persistentStorage/compactLocalStorageEntry.ts
140
+ function createCompactLocalStorageEntry(value, version) {
141
+ if ("v" in value && value.v !== void 0) throw new Error("[TSDF] Compact localStorage entries cannot use the reserved \"v\" key.");
142
+ if (version === void 0) return value;
143
+ return {
144
+ ...value,
145
+ v: version
146
+ };
147
+ }
148
+ function parseCompactLocalStorageEntry(raw) {
149
+ if (raw === null) return null;
150
+ const value = rc_parse_json(raw, rc_unknown).unwrapOrNull();
151
+ if (value === null) return null;
152
+ if (!isObject(value) || !("d" in value)) return null;
153
+ if ("v" in value && value.v !== void 0 && typeof value.v !== "number") return null;
154
+ return {
155
+ value,
156
+ ...typeof value.v === "number" ? { version: value.v } : {}
157
+ };
158
+ }
159
+ //#endregion
160
+ //#region src/persistentStorage/navigatorLocks.ts
161
+ function getNavigatorLockManager() {
162
+ return asPossiblyUndefined(globalThis.navigator)?.locks ?? null;
163
+ }
164
+ const warnedLockUnavailable = /* @__PURE__ */ new Set();
165
+ function warnIfNavigatorLockUnavailable(warning) {
166
+ if (getNavigatorLockManager() !== null) return;
167
+ if (!warnedLockUnavailable.has(warning)) {
168
+ warnedLockUnavailable.add(warning);
169
+ console.warn(warning);
170
+ }
171
+ }
172
+ async function runWithNavigatorLock(lockName, unavailableWarning, callback) {
173
+ const lockManager = getNavigatorLockManager();
174
+ if (lockManager === null) {
175
+ warnIfNavigatorLockUnavailable(unavailableWarning);
176
+ return await callback();
177
+ }
178
+ return lockManager.request(lockName, callback);
179
+ }
180
+ //#endregion
181
+ //#region src/persistentStorage/offline/sessionProtectionRegistry.ts
182
+ const protectedKeysBySession = /* @__PURE__ */ new Map();
183
+ function setSessionProtectedKeysSnapshot(sessionKey, protectedKeys) {
184
+ protectedKeysBySession.set(sessionKey, new Set(protectedKeys));
185
+ }
186
+ function getSessionProtectedKeysSnapshot(sessionKey) {
187
+ return protectedKeysBySession.get(sessionKey) ?? null;
188
+ }
189
+ function clearSessionProtectedKeysSnapshot(sessionKey) {
190
+ protectedKeysBySession.delete(sessionKey);
191
+ }
192
+ //#endregion
193
+ //#region src/persistentStorage/offline/types.ts
194
+ /** Runtime schema for validating serialized offline item entity references. */
195
+ /** @internal */
196
+ const offlineItemEntityRefSchema = rc_object({
197
+ entityKey: rc_string,
198
+ entityKind: rc_literals("item")
199
+ });
200
+ const offlineResolutionEntityRefSchema = rc_object({
201
+ entityKey: rc_string,
202
+ entityKind: rc_literals("document", "item", "query")
203
+ });
204
+ const offlineResolutionBaseFields = {
205
+ id: rc_string,
206
+ entryId: rc_string,
207
+ sessionKey: rc_string,
208
+ storeName: rc_string,
209
+ storeType: rc_literals("document", "collection", "listQuery"),
210
+ operation: rc_string,
211
+ input: rc_unknown,
212
+ enqueuedAt: rc_number,
213
+ entityRefs: rc_array(offlineResolutionEntityRefSchema),
214
+ createdAt: rc_number,
215
+ updatedAt: rc_number,
216
+ attachedUploadIds: rc_record(rc_string).optionalKey(),
217
+ dependencyUploadIds: rc_array(rc_string).optionalKey()
218
+ };
219
+ /** Runtime schema for validating persisted offline resolution records on hydration. */
220
+ /** @internal */
221
+ const offlineResolutionRecordSchema = rc_discriminated_union("kind", {
222
+ conflict: {
223
+ ...offlineResolutionBaseFields,
224
+ kind: rc_literals("conflict"),
225
+ conflict: rc_unknown
226
+ },
227
+ "retry-exhausted": {
228
+ ...offlineResolutionBaseFields,
229
+ kind: rc_literals("retry-exhausted"),
230
+ lastReplayError: rc_object({ message: rc_string })
231
+ }
232
+ });
233
+ /** Default runtime config when offline is not configured or no session exists. */
234
+ const defaultOfflineRuntimeConfig = {
235
+ network: { enabled: false },
236
+ outage: { enabled: false },
237
+ mutationQueueing: {
238
+ network: "allow",
239
+ outage: "allow"
240
+ }
241
+ };
242
+ const compactOfflineStatusModeStateSchema = rc_object({
243
+ e: rc_literals(1).optionalKey(),
244
+ a: rc_literals(1).optionalKey()
245
+ });
246
+ /** Runtime schema for compact persisted offline status snapshots. */
247
+ /** @internal */
248
+ const compactOfflineStatusSnapshotSchema = rc_object({
249
+ n: compactOfflineStatusModeStateSchema.optionalKey(),
250
+ o: compactOfflineStatusModeStateSchema.optionalKey(),
251
+ u: rc_number.optionalKey(),
252
+ lf: rc_number.optionalKey(),
253
+ lr: rc_number.optionalKey()
254
+ });
255
+ function isModeEffectivelyActive(mode) {
256
+ return mode.enabled && mode.active;
257
+ }
258
+ function getIsOfflineModeFromStatus(status) {
259
+ return status.network.active || status.outage.active;
260
+ }
261
+ function isOfflineModeStatusValue(value) {
262
+ const status = rc_parse(value, compactOfflineStatusSnapshotSchema).unwrapOrNull();
263
+ if (status === null) return false;
264
+ return status.n?.a === 1 || status.o?.a === 1;
265
+ }
266
+ function formatSchemaValidationError(error) {
267
+ if (error.length === 0) return "invalid-conflict-payload";
268
+ if (typeof error[0] === "string") {
269
+ let message = error[0];
270
+ for (const entry of error.slice(1)) {
271
+ if (typeof entry !== "string") return JSON.stringify(error);
272
+ message += `; ${entry}`;
273
+ }
274
+ return message;
275
+ }
276
+ return JSON.stringify(error);
277
+ }
278
+ function getOfflineResolutionConflictParseErrorMessage(args) {
279
+ if (args.code === "invalid-conflict-payload" && args.validationError) return formatSchemaValidationError(args.validationError);
280
+ return args.code;
281
+ }
282
+ /** Error returned when decoding a stored offline conflict payload fails. */
283
+ var OfflineResolutionConflictParseError = class extends Error {
284
+ code;
285
+ operation;
286
+ kind;
287
+ rawValue;
288
+ validationError;
289
+ constructor(args) {
290
+ super(getOfflineResolutionConflictParseErrorMessage(args));
291
+ this.name = "OfflineResolutionConflictParseError";
292
+ this.code = args.code;
293
+ this.operation = args.operation;
294
+ this.kind = args.kind;
295
+ this.rawValue = args.rawValue;
296
+ this.validationError = args.validationError;
297
+ }
298
+ };
299
+ //#endregion
300
+ //#region src/persistentStorage/persistenceUtils.ts
301
+ /**
302
+ * Creates a key set that auto-clears entries after a microtask.
303
+ * Used to deduplicate sync storage reads within the same event loop tick.
304
+ */
305
+ function createTimedKeySet() {
306
+ const keys = /* @__PURE__ */ new Set();
307
+ let clearScheduled = false;
308
+ function scheduleClear() {
309
+ if (clearScheduled) return;
310
+ clearScheduled = true;
311
+ queueMicrotask(() => {
312
+ clearScheduled = false;
313
+ keys.clear();
314
+ });
315
+ }
316
+ return {
317
+ has: (key) => keys.has(key),
318
+ remember: (key) => {
319
+ keys.add(key);
320
+ scheduleClear();
321
+ },
322
+ clear: (key) => {
323
+ keys.delete(key);
324
+ },
325
+ clearAll: () => {
326
+ keys.clear();
327
+ }
328
+ };
329
+ }
330
+ function createShouldIgnoreItemPredicate(ignoreItems, resolveItemKey) {
331
+ if (!ignoreItems) return () => false;
332
+ if (typeof ignoreItems === "function") return ignoreItems;
333
+ const ignoredItemKeys = new Set(ignoreItems.map(resolveItemKey));
334
+ return (payload) => ignoredItemKeys.has(resolveItemKey(payload));
335
+ }
336
+ function getSerializedStringSize(value) {
337
+ return value.length;
338
+ }
339
+ function serializeJsonForStorage(value) {
340
+ const rawValue = JSON.stringify(value);
341
+ return {
342
+ rawValue,
343
+ sizeBytes: getSerializedStringSize(rawValue)
344
+ };
345
+ }
346
+ function keepEntriesWithinByteBudget(entries, getKey, getLastAccessAt, getSizeBytes, isPinned, isProtected, maxBytes) {
347
+ const keptKeys = /* @__PURE__ */ new Set();
348
+ let unprotectedBytes = 0;
349
+ for (const entry of entries) {
350
+ if (isProtected(entry)) continue;
351
+ unprotectedBytes += getSizeBytes(entry);
352
+ }
353
+ if (unprotectedBytes <= maxBytes) {
354
+ for (const entry of entries) keptKeys.add(getKey(entry));
355
+ return {
356
+ keptKeys,
357
+ unprotectedBytes
358
+ };
359
+ }
360
+ const sortedEntries = [...entries].sort((a, b) => {
361
+ const aProtected = isProtected(a);
362
+ const bProtected = isProtected(b);
363
+ if (aProtected && !bProtected) return -1;
364
+ if (!aProtected && bProtected) return 1;
365
+ const aPinned = isPinned(a);
366
+ const bPinned = isPinned(b);
367
+ if (aPinned && !bPinned) return -1;
368
+ if (!aPinned && bPinned) return 1;
369
+ return getLastAccessAt(b) - getLastAccessAt(a);
370
+ });
371
+ let keptUnprotectedBytes = 0;
372
+ for (const entry of sortedEntries) {
373
+ const key = getKey(entry);
374
+ if (isProtected(entry)) {
375
+ keptKeys.add(key);
376
+ continue;
377
+ }
378
+ const sizeBytes = getSizeBytes(entry);
379
+ if (isPinned(entry)) {
380
+ keptKeys.add(key);
381
+ keptUnprotectedBytes += sizeBytes;
382
+ continue;
383
+ }
384
+ if (keptUnprotectedBytes + sizeBytes <= maxBytes) {
385
+ keptKeys.add(key);
386
+ keptUnprotectedBytes += sizeBytes;
387
+ }
388
+ }
389
+ return {
390
+ keptKeys,
391
+ unprotectedBytes
392
+ };
393
+ }
394
+ //#endregion
395
+ //#region src/persistentStorage/persistentStorageDefaults.ts
396
+ const defaultMaxBytes = {
397
+ localSync: {
398
+ collection: 64 * 1024,
399
+ listItem: 64 * 1024,
400
+ listQuery: 32 * 1024
401
+ },
402
+ async: {
403
+ collection: 128 * 1024,
404
+ listItem: 128 * 1024,
405
+ listQuery: 64 * 1024
406
+ }
407
+ };
408
+ function getDefaultMaxBytesProfile(adapter) {
409
+ return adapter === "local-sync" || adapter === "localSync" ? "localSync" : "async";
410
+ }
411
+ function getDefaultMaxBytesKindForScope(scopeKind) {
412
+ switch (scopeKind) {
413
+ case "collection.item": return "collection";
414
+ case "listQuery.item": return "listItem";
415
+ case "listQuery.query": return "listQuery";
416
+ }
417
+ }
418
+ function getDefaultMaxBytesForAdapter(adapter, kind) {
419
+ return defaultMaxBytes[getDefaultMaxBytesProfile(adapter)][kind];
420
+ }
421
+ function getDefaultMaxBytesForScope(adapter, scopeKind) {
422
+ return getDefaultMaxBytesForAdapter(adapter, getDefaultMaxBytesKindForScope(scopeKind));
423
+ }
424
+ //#endregion
425
+ //#region src/debug.ts
426
+ function defaultConsoleDebugLogger(entry) {
427
+ const consoleForLevel = globalThis.console[entry.level];
428
+ if (typeof consoleForLevel !== "function") return;
429
+ const details = entry.details ? {
430
+ operation: entry.operation,
431
+ ...entry.details
432
+ } : { operation: entry.operation };
433
+ consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
434
+ }
435
+ function resolveTSDFLogger(logger) {
436
+ if (logger === void 0 || logger === false) return void 0;
437
+ if (logger === true) return defaultConsoleDebugLogger;
438
+ return logger;
439
+ }
440
+ function emitTSDFDebugLog(logger, entry) {
441
+ if (!logger) return;
442
+ try {
443
+ logger(entry);
444
+ } catch (error) {
445
+ globalThis.console.error("[tsdf:debug] Debug logger failed", error);
446
+ }
447
+ }
448
+ function getTSDFDebugTimingMs() {
449
+ if (!import.meta.env.DEV) return 0;
450
+ return Date.now();
451
+ }
452
+ //#endregion
453
+ //#region src/persistentStorage/quotaDebug.ts
454
+ function logPersistentStorageQuotaCleanup(args) {
455
+ emitTSDFDebugLog(args.logger, {
456
+ area: "persistent-storage",
457
+ details: {
458
+ adapter: args.adapter,
459
+ evictedEntries: args.evictedEntries,
460
+ keptEntries: args.keptEntries,
461
+ maxBytes: args.maxBytes,
462
+ namespaceKind: args.namespaceKind,
463
+ phase: args.phase,
464
+ quota: args.quota,
465
+ status: "success",
466
+ storeName: args.storeName,
467
+ totalEntries: args.totalEntries,
468
+ unprotectedBytes: args.unprotectedBytes
469
+ },
470
+ level: "log",
471
+ message: "persistent storage quota-cleanup success",
472
+ operation: "quota-cleanup"
473
+ });
474
+ }
475
+ //#endregion
476
+ //#region src/persistentStorage/types.ts
477
+ function parseAsyncStorageNamespaceKind(value) {
478
+ switch (value) {
479
+ case "document":
480
+ case "collection.item":
481
+ case "listQuery.item":
482
+ case "listQuery.query":
483
+ case "offline.queue":
484
+ case "offline.conflict":
485
+ case "offline.entity":
486
+ case "__internal.protected": return value;
487
+ default: return null;
488
+ }
489
+ }
490
+ const ASYNC_STORAGE_MAX_AGE_MS = 336 * 60 * 60 * 1e3;
491
+ const ASYNC_STORAGE_STARTUP_CLEANUP_COOLDOWN_MS = 720 * 60 * 1e3;
492
+ const ASYNC_STORAGE_RECENCY_BUCKET_MS = 360 * 60 * 1e3;
493
+ const ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY = "tsdf._am.g";
494
+ const ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX = "tsdf-async-write:";
495
+ const ASYNC_STORAGE_WRITER_LOCK_WARNING = "[TSDF] navigator.locks is unavailable; async persistentStorage is using unlocked writer coordination.";
496
+ const ASYNC_STARTUP_CLEANUP_LOCK_NAME = "tsdf-async-storage-maintenance";
497
+ const ASYNC_STARTUP_CLEANUP_LOCK_WARNING = "[TSDF] navigator.locks is unavailable; async OPFS startup cleanup is using unlocked coordination.";
498
+ const ASYNC_STORAGE_CACHE_INVALIDATION_CHANNEL_NAME = "tsdf-async-storage-cache-v1";
499
+ const ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE = 500;
500
+ const ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE = 5e3;
501
+ function getBucketId(timestamp) {
502
+ return String(Math.floor(timestamp / ASYNC_STORAGE_RECENCY_BUCKET_MS));
503
+ }
504
+ function getRecord(value) {
505
+ if (!isObject(value)) return null;
506
+ return value;
507
+ }
508
+ function isOfflineProtectedMetadata(customMetadata) {
509
+ return customMetadata?.o === true;
510
+ }
511
+ function getProtectedKeysFromMetadata(entries) {
512
+ const keys = /* @__PURE__ */ new Set();
513
+ for (const entry of entries) if (isOfflineProtectedMetadata(entry.customMetadata)) keys.add(entry.key);
514
+ return keys;
515
+ }
516
+ function isSessionOfflineInLocalStorage(sessionKey) {
517
+ if (typeof window === "undefined") return false;
518
+ try {
519
+ return isOfflineModeStatusValue(parseCompactLocalStorageEntry(localStorage.getItem(`tsdf.${sessionKey}._o_.s`))?.value.d ?? null);
520
+ } catch {
521
+ return false;
522
+ }
523
+ }
524
+ function setOfflineProtectionMetadata(customMetadata, offlineProtected) {
525
+ if (offlineProtected) return {
526
+ ...customMetadata ?? {},
527
+ o: true
528
+ };
529
+ const { o: _ignored, ...withoutOfflineMarker } = customMetadata ?? {};
530
+ return Object.keys(withoutOfflineMarker).length > 0 ? withoutOfflineMarker : void 0;
531
+ }
532
+ function mergeManagedAsyncStorageCustomMetadata(currentCustomMetadata, nextCustomMetadata, protectedKeysSnapshotSet, scope, key) {
533
+ const merged = {
534
+ ...currentCustomMetadata ?? {},
535
+ ...nextCustomMetadata ?? {}
536
+ };
537
+ const mergedCustomMetadata = Object.keys(merged).length > 0 ? merged : void 0;
538
+ if (protectedKeysSnapshotSet !== null) return setOfflineProtectionMetadata(mergedCustomMetadata, protectedKeysSnapshotSet?.has(serializeProtectedRef({
539
+ ...scope,
540
+ key
541
+ })) === true || isOfflineProtectedMetadata(nextCustomMetadata) || isOfflineProtectedMetadata(currentCustomMetadata));
542
+ return setOfflineProtectionMetadata(mergedCustomMetadata, isOfflineProtectedMetadata(nextCustomMetadata) || isOfflineProtectedMetadata(currentCustomMetadata));
543
+ }
544
+ const ASYNC_METADATA_LAST_ACCESS_AT_KEY = "a";
545
+ const ASYNC_METADATA_VERSION_KEY = "v";
546
+ const ASYNC_METADATA_SIZE_BYTES_KEY = "z";
547
+ const persistedStaticPolicySchema = rc_object({
548
+ b: rc_number.optionalKey(),
549
+ k: rc_array(rc_string).optionalKey()
550
+ });
551
+ function getInlineCustomMetadata(record) {
552
+ const customMetadataEntries = Object.entries(record).filter(([key]) => key !== ASYNC_METADATA_LAST_ACCESS_AT_KEY && key !== ASYNC_METADATA_VERSION_KEY && key !== ASYNC_METADATA_SIZE_BYTES_KEY);
553
+ if (customMetadataEntries.length === 0) return void 0;
554
+ return Object.fromEntries(customMetadataEntries);
555
+ }
556
+ function parseInternalManagedMetadataRecord(value) {
557
+ const record = getRecord(value);
558
+ if (record === null || typeof record.a !== "number" || "v" in record && record.v !== void 0 && typeof record.v !== "number" || "z" in record && record.z !== void 0 && typeof record.z !== "number") return null;
559
+ const customMetadata = getInlineCustomMetadata(record);
560
+ return {
561
+ lastAccessAt: record.a,
562
+ ...typeof record.z === "number" ? { sizeBytes: record.z } : {},
563
+ version: typeof record.v === "number" ? record.v : 1,
564
+ ...customMetadata ? { customMetadata } : {}
565
+ };
566
+ }
567
+ function serializeInternalManagedMetadataRecord(metadata) {
568
+ const serialized = {
569
+ [ASYNC_METADATA_LAST_ACCESS_AT_KEY]: metadata.lastAccessAt,
570
+ ...metadata.sizeBytes !== void 0 ? { [ASYNC_METADATA_SIZE_BYTES_KEY]: metadata.sizeBytes } : {},
571
+ ...metadata.version !== 1 ? { [ASYNC_METADATA_VERSION_KEY]: metadata.version } : {}
572
+ };
573
+ const customMetadata = metadata.customMetadata;
574
+ if (customMetadata === void 0) return serialized;
575
+ if (ASYNC_METADATA_LAST_ACCESS_AT_KEY in customMetadata || ASYNC_METADATA_VERSION_KEY in customMetadata || ASYNC_METADATA_SIZE_BYTES_KEY in customMetadata) throw new Error("[TSDF] Async storage custom metadata cannot use reserved keys \"a\", \"v\", or \"z\".");
576
+ return {
577
+ ...serialized,
578
+ ...customMetadata
579
+ };
580
+ }
581
+ function estimateManagedAsyncStorageEntrySizeBytes(serializedValue, lastAccessAt, version, customMetadata) {
582
+ return getSerializedStringSize(serializedValue) + getSerializedStringSize(JSON.stringify(serializeInternalManagedMetadataRecord({
583
+ lastAccessAt,
584
+ sizeBytes: void 0,
585
+ version,
586
+ ...customMetadata ? { customMetadata } : {}
587
+ })));
588
+ }
589
+ function parseIndexEntries(value) {
590
+ const rawEntries = getRecord(value)?.e;
591
+ if (rawEntries === void 0) return value === null ? /* @__PURE__ */ new Map() : null;
592
+ const entriesRecord = getRecord(rawEntries);
593
+ if (entriesRecord === null) return null;
594
+ const entries = /* @__PURE__ */ new Map();
595
+ for (const [key, rawEntry] of Object.entries(entriesRecord)) {
596
+ const parsed = parseInternalManagedMetadataRecord(rawEntry);
597
+ if (parsed === null) return null;
598
+ entries.set(key, parsed);
599
+ }
600
+ return entries;
601
+ }
602
+ /**
603
+ * Builds a persisted static policy from config values, omitting fields that
604
+ * match the provided default. Returns null when no overrides are needed.
605
+ */
606
+ function buildPersistedStaticPolicy(maxBytes, defaultMaxBytes, pinnedKeys) {
607
+ return normalizeStaticPolicy({
608
+ ...maxBytes !== void 0 && maxBytes !== defaultMaxBytes ? { maxBytes } : {},
609
+ ...pinnedKeys.size > 0 ? { pinnedKeys: [...pinnedKeys] } : {}
610
+ });
611
+ }
612
+ function parseStaticPolicy(value) {
613
+ const parsed = rc_parse(value, persistedStaticPolicySchema).unwrapOrNull();
614
+ if (parsed === null) return null;
615
+ if (parsed.b !== void 0 && (!Number.isInteger(parsed.b) || parsed.b < 0)) return null;
616
+ return normalizeStaticPolicy({
617
+ ...parsed.b !== void 0 ? { maxBytes: parsed.b } : {},
618
+ ...parsed.k !== void 0 ? { pinnedKeys: parsed.k } : {}
619
+ });
620
+ }
621
+ function serializeStaticPolicy(policy) {
622
+ if (policy === null) return void 0;
623
+ return {
624
+ ...policy.maxBytes !== void 0 ? { b: policy.maxBytes } : {},
625
+ ...policy.pinnedKeys !== void 0 && policy.pinnedKeys.length > 0 ? { k: policy.pinnedKeys } : {}
626
+ };
627
+ }
628
+ function serializeIndexState(state) {
629
+ const serializedStaticPolicy = serializeStaticPolicy(state.staticPolicy);
630
+ return {
631
+ e: Object.fromEntries([...state.entries.entries()].map(([key, metadata]) => [key, serializeInternalManagedMetadataRecord(metadata)])),
632
+ ...serializedStaticPolicy !== void 0 ? { s: serializedStaticPolicy } : {}
633
+ };
634
+ }
635
+ function getDefaultStaticPolicyForScope(scope) {
636
+ switch (scope.kind) {
637
+ case "collection.item": return { maxBytes: getDefaultMaxBytesForScope("async", "collection.item") };
638
+ case "listQuery.item": return { maxBytes: getDefaultMaxBytesForScope("async", "listQuery.item") };
639
+ case "listQuery.query": return { maxBytes: getDefaultMaxBytesForScope("async", "listQuery.query") };
640
+ default: return null;
641
+ }
642
+ }
643
+ /**
644
+ * Strips fields from a persisted static policy that match the scope's defaults,
645
+ * so only non-default overrides are stored.
646
+ * Expects already-normalized input.
647
+ */
648
+ function normalizePersistedStaticPolicyForScope(scope, persistedStaticPolicy) {
649
+ if (persistedStaticPolicy === null) return null;
650
+ const defaultPolicy = getDefaultStaticPolicyForScope(scope);
651
+ return normalizeStaticPolicy({
652
+ maxBytes: persistedStaticPolicy.maxBytes !== void 0 && persistedStaticPolicy.maxBytes !== defaultPolicy?.maxBytes ? persistedStaticPolicy.maxBytes : void 0,
653
+ pinnedKeys: persistedStaticPolicy.pinnedKeys
654
+ });
655
+ }
656
+ /**
657
+ * Merges a persisted static policy (already normalized for scope) with the
658
+ * scope's defaults to produce the effective policy.
659
+ * Expects already-normalized input.
660
+ */
661
+ function getEffectiveStaticPolicyForScope(scope, normalizedPersistedPolicy) {
662
+ const defaultPolicy = getDefaultStaticPolicyForScope(scope);
663
+ if (defaultPolicy === null) return normalizedPersistedPolicy;
664
+ return normalizeStaticPolicy({
665
+ maxBytes: normalizedPersistedPolicy?.maxBytes ?? defaultPolicy.maxBytes,
666
+ pinnedKeys: normalizedPersistedPolicy?.pinnedKeys
667
+ });
668
+ }
669
+ async function driverGetManyFrom(driver, scope, keys) {
670
+ if (keys.length === 0) return [];
671
+ return driver.getMany(scope, keys);
672
+ }
673
+ function getManagedDriverCapabilities(driver) {
674
+ return __LEGIT_CAST__(driver).__tsdfManagedStorage ?? null;
675
+ }
676
+ async function readAsyncStorageNamespaceIndexStateUsingDriver(driver, scope, knownRecordKeys) {
677
+ const managedCapabilities = getManagedDriverCapabilities(driver);
678
+ if (managedCapabilities?.readNamespaceIndexState !== void 0) return managedCapabilities.readNamespaceIndexState(scope, knownRecordKeys);
679
+ if (knownRecordKeys != null && !knownRecordKeys.includes("_i")) return {
680
+ entries: null,
681
+ exists: false,
682
+ staticPolicy: null,
683
+ valid: true
684
+ };
685
+ const indexKnownToExist = knownRecordKeys != null;
686
+ const rawIndex = await driver.get(scope, "_i");
687
+ if (rawIndex === null) return indexKnownToExist ? {
688
+ entries: null,
689
+ exists: true,
690
+ staticPolicy: null,
691
+ valid: false
692
+ } : {
693
+ entries: null,
694
+ exists: false,
695
+ staticPolicy: null,
696
+ valid: true
697
+ };
698
+ const record = getRecord(rawIndex);
699
+ const parsed = parseIndexEntries(rawIndex);
700
+ if (parsed === null) return {
701
+ entries: null,
702
+ exists: true,
703
+ staticPolicy: null,
704
+ valid: false
705
+ };
706
+ return {
707
+ entries: parsed,
708
+ exists: true,
709
+ staticPolicy: parseStaticPolicy(record?.s),
710
+ valid: true
711
+ };
712
+ }
713
+ function cloneStaticPolicy(policy) {
714
+ if (policy === null) return null;
715
+ return {
716
+ maxBytes: policy.maxBytes,
717
+ pinnedKeys: policy.pinnedKeys ? [...policy.pinnedKeys] : void 0
718
+ };
719
+ }
720
+ function cloneManagedMetadataRecord(metadata) {
721
+ return {
722
+ lastAccessAt: metadata.lastAccessAt,
723
+ sizeBytes: metadata.sizeBytes,
724
+ version: metadata.version,
725
+ customMetadata: metadata.customMetadata ? klona(metadata.customMetadata) : void 0
726
+ };
727
+ }
728
+ function cloneNamespaceIndexReadState(state) {
729
+ let entries = null;
730
+ if (state.entries !== null) {
731
+ entries = /* @__PURE__ */ new Map();
732
+ for (const [key, metadata] of state.entries) entries.set(key, cloneManagedMetadataRecord(metadata));
733
+ }
734
+ return {
735
+ entries,
736
+ exists: state.exists,
737
+ staticPolicy: cloneStaticPolicy(state.staticPolicy),
738
+ valid: state.valid
739
+ };
740
+ }
741
+ function parseCacheInvalidationReason(value) {
742
+ switch (value) {
743
+ case "clear":
744
+ case "commit":
745
+ case "remove":
746
+ case "startup-cleanup": return value;
747
+ default: return null;
748
+ }
749
+ }
750
+ function parseAsyncStorageCacheInvalidationMessage(value) {
751
+ const record = getRecord(value);
752
+ if (record === null || record.kind !== "namespace-invalidated" || record.protocolVersion !== 1) return null;
753
+ const scopeRecord = getRecord(record.scope);
754
+ if (scopeRecord === null || typeof scopeRecord.kind !== "string" || typeof scopeRecord.sessionKey !== "string" || typeof scopeRecord.storeName !== "string") return null;
755
+ const kind = parseAsyncStorageNamespaceKind(scopeRecord.kind);
756
+ if (kind === null) return null;
757
+ const reason = parseCacheInvalidationReason(record.reason);
758
+ if (reason === null) return null;
759
+ return {
760
+ kind: "namespace-invalidated",
761
+ protocolVersion: 1,
762
+ reason,
763
+ scope: {
764
+ kind,
765
+ sessionKey: scopeRecord.sessionKey,
766
+ storeName: scopeRecord.storeName
767
+ }
768
+ };
769
+ }
770
+ const asyncStorageReadCacheParticipants = [];
771
+ let asyncStorageCacheInvalidationChannel;
772
+ let asyncStorageReadCacheLifecycleReady = false;
773
+ function getLiveAsyncStorageReadCacheParticipants() {
774
+ const liveParticipants = [];
775
+ const retainedRefs = [];
776
+ for (const ref of asyncStorageReadCacheParticipants) {
777
+ const participant = ref.deref();
778
+ if (participant === void 0) continue;
779
+ liveParticipants.push(participant);
780
+ retainedRefs.push(ref);
781
+ }
782
+ asyncStorageReadCacheParticipants.length = 0;
783
+ asyncStorageReadCacheParticipants.push(...retainedRefs);
784
+ return liveParticipants;
785
+ }
786
+ function clearAllAsyncStorageReadCaches() {
787
+ for (const participant of getLiveAsyncStorageReadCacheParticipants()) participant.clearAllCachedReads();
788
+ }
789
+ function notifyLocalAsyncStorageReadCacheInvalidation(source, message) {
790
+ for (const participant of getLiveAsyncStorageReadCacheParticipants()) {
791
+ if (participant === source) continue;
792
+ participant.onRemoteCacheInvalidation(message);
793
+ }
794
+ }
795
+ function handleAsyncStorageCacheInvalidationEvent(event) {
796
+ const message = parseAsyncStorageCacheInvalidationMessage(event.data);
797
+ if (message === null) return;
798
+ for (const participant of getLiveAsyncStorageReadCacheParticipants()) participant.onRemoteCacheInvalidation(message);
799
+ }
800
+ function ensureAsyncStorageReadCacheLifecycle() {
801
+ if (!asyncStorageReadCacheLifecycleReady) {
802
+ document.addEventListener("visibilitychange", () => {
803
+ if (!document.hidden) clearAllAsyncStorageReadCaches();
804
+ });
805
+ if (typeof window !== "undefined") window.addEventListener("pageshow", () => {
806
+ clearAllAsyncStorageReadCaches();
807
+ });
808
+ asyncStorageReadCacheLifecycleReady = true;
809
+ }
810
+ if (asyncStorageCacheInvalidationChannel !== void 0) return;
811
+ try {
812
+ asyncStorageCacheInvalidationChannel = new BroadcastChannel(ASYNC_STORAGE_CACHE_INVALIDATION_CHANNEL_NAME);
813
+ asyncStorageCacheInvalidationChannel.addEventListener("message", handleAsyncStorageCacheInvalidationEvent);
814
+ } catch {
815
+ asyncStorageCacheInvalidationChannel = null;
816
+ }
817
+ }
818
+ function registerAsyncStorageReadCacheParticipant(participant) {
819
+ ensureAsyncStorageReadCacheLifecycle();
820
+ asyncStorageReadCacheParticipants.push(new WeakRef(participant));
821
+ }
822
+ function parseMaintenanceState(value) {
823
+ const record = getRecord(value);
824
+ if (record === null) return null;
825
+ const lastSuccessfulCleanupAt = record.lca;
826
+ if (lastSuccessfulCleanupAt !== null && typeof lastSuccessfulCleanupAt !== "number") return null;
827
+ return { lastSuccessfulCleanupAt };
828
+ }
829
+ function createDefaultMaintenanceState() {
830
+ return { lastSuccessfulCleanupAt: null };
831
+ }
832
+ var ManagedAsyncStorageNamespaceHandle = class {
833
+ #adapter;
834
+ #scope;
835
+ constructor(adapter, scope) {
836
+ this.#adapter = adapter;
837
+ this.#scope = scope;
838
+ }
839
+ async get(key, options = {}) {
840
+ await this.#adapter.flushPendingNamespaceCommit(this.#scope, [key]);
841
+ const entry = (await this.#adapter.readManagedEntries(this.#scope, [key])).get(key) ?? null;
842
+ if (!entry) return null;
843
+ const now = Date.now();
844
+ const touchMode = options.touch ?? "coarse";
845
+ if (this.#adapter.shouldEnqueueTouch(this.#scope, key, entry.metadata.lastAccessAt, touchMode, now)) this.commit({ touches: [{
846
+ key,
847
+ lastAccessAt: now
848
+ }] }).catch(() => {});
849
+ return entry;
850
+ }
851
+ async getMany(keys, options = {}) {
852
+ if (keys.length === 0) return [];
853
+ const uniqueKeys = [...new Set(keys)];
854
+ await this.#adapter.flushPendingNamespaceCommit(this.#scope, uniqueKeys);
855
+ const entries = await this.#adapter.readManagedEntries(this.#scope, uniqueKeys);
856
+ const entryByKey = /* @__PURE__ */ new Map();
857
+ const touches = [];
858
+ const now = Date.now();
859
+ const touchMode = options.touch ?? "coarse";
860
+ for (const key of uniqueKeys) {
861
+ const entry = entries.get(key) ?? null;
862
+ entryByKey.set(key, entry);
863
+ if (entry !== null && this.#adapter.shouldEnqueueTouch(this.#scope, key, entry.metadata.lastAccessAt, touchMode, now)) touches.push(key);
864
+ }
865
+ if (touches.length > 0) this.commit({ touches: touches.map((key) => ({
866
+ key,
867
+ lastAccessAt: now
868
+ })) }).catch(() => {});
869
+ return keys.map((key) => entryByKey.get(key) ?? null);
870
+ }
871
+ commit(args) {
872
+ return this.#adapter.queueCommitToNamespace(this.#scope, args);
873
+ }
874
+ async listKeys() {
875
+ await this.#adapter.flushPendingNamespaceCommit(this.#scope);
876
+ return this.#adapter.listManagedKeys(this.#scope);
877
+ }
878
+ async listMetadata(args = {}) {
879
+ await this.#adapter.flushPendingNamespaceCommit(this.#scope);
880
+ return this.#adapter.listManagedMetadata(this.#scope, args);
881
+ }
882
+ async listMetadataByFilter(args) {
883
+ await this.#adapter.flushPendingNamespaceCommit(this.#scope);
884
+ return this.#adapter.listManagedMetadata(this.#scope, args);
885
+ }
886
+ async clear() {
887
+ await this.#adapter.flushPendingNamespaceCommit(this.#scope);
888
+ await this.#adapter.clearManagedNamespace(this.#scope);
889
+ }
890
+ };
891
+ const registeredAsyncStartupStoreCleanupCallbacks = /* @__PURE__ */ new WeakMap();
892
+ function getStoreRegistryKey(sessionKey, storeName) {
893
+ return JSON.stringify([sessionKey, storeName]);
894
+ }
895
+ function registerAsyncStartupStoreCleanup(adapter, sessionKey, storeName, callback) {
896
+ const registry = registeredAsyncStartupStoreCleanupCallbacks.get(adapter) ?? /* @__PURE__ */ new Map();
897
+ registry.set(getStoreRegistryKey(sessionKey, storeName), callback);
898
+ registeredAsyncStartupStoreCleanupCallbacks.set(adapter, registry);
899
+ }
900
+ function unregisterAsyncStartupStoreCleanup(adapter, sessionKey, storeName) {
901
+ const registry = registeredAsyncStartupStoreCleanupCallbacks.get(adapter);
902
+ if (registry === void 0) return;
903
+ registry.delete(getStoreRegistryKey(sessionKey, storeName));
904
+ if (registry.size === 0) registeredAsyncStartupStoreCleanupCallbacks.delete(adapter);
905
+ }
906
+ var ManagedAsyncStorageAdapter = class {
907
+ kind = "async";
908
+ #driver;
909
+ #debugLogger;
910
+ #logger;
911
+ #cachedNamespaceIndexReads = createCache({ maxCacheSize: ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE });
912
+ #cachedPayloadReads = createCache({ maxCacheSize: ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE });
913
+ #namespaceReadCacheGenerations = /* @__PURE__ */ new Map();
914
+ #observedScopes = /* @__PURE__ */ new Map();
915
+ #pendingNamespaceCommits = /* @__PURE__ */ new Map();
916
+ #readCacheGeneration = 0;
917
+ #recentTouchedBuckets = /* @__PURE__ */ new Map();
918
+ #cancelStartupCleanup = null;
919
+ #startupCleanupScheduled = false;
920
+ constructor(driver) {
921
+ this.#driver = driver;
922
+ registerAsyncStorageReadCacheParticipant(this);
923
+ }
924
+ get debugLogger() {
925
+ return this.#debugLogger;
926
+ }
927
+ set debugLogger(debugLogger) {
928
+ this.#debugLogger = debugLogger;
929
+ this.#driver.debugLogger = debugLogger;
930
+ }
931
+ get logger() {
932
+ return this.#logger;
933
+ }
934
+ set logger(logger) {
935
+ this.#logger = logger;
936
+ this.#driver.logger = logger;
937
+ }
938
+ async #runWithSessionWriterLock(sessionKey, callback) {
939
+ return runWithNavigatorLock(`${ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX}${sessionKey}`, ASYNC_STORAGE_WRITER_LOCK_WARNING, callback);
940
+ }
941
+ openNamespace(scope) {
942
+ this.#observedScopes.set(getNamespaceId(scope), scope);
943
+ this.#scheduleStartupCleanupIfNeeded();
944
+ return new ManagedAsyncStorageNamespaceHandle(this, scope);
945
+ }
946
+ async clearSession(sessionKey) {
947
+ await this.#runWithSessionWriterLock(sessionKey, async () => {
948
+ await this.#flushPendingNamespaceCommitsForSessionUnlocked(sessionKey);
949
+ const scopesToClear = await this.#listDiscoveredScopes(sessionKey);
950
+ await Promise.all(scopesToClear.map((scope) => this.#clearManagedNamespaceUnlocked(scope)));
951
+ });
952
+ }
953
+ async readProtectedStorageKeys(sessionKey, driver = this.#driver) {
954
+ const protectedKeysSnapshot = getSessionProtectedKeysSnapshot(sessionKey);
955
+ if (protectedKeysSnapshot !== null && protectedKeysSnapshot.size > 0) return new Set(protectedKeysSnapshot);
956
+ const managedCapabilities = getManagedDriverCapabilities(driver);
957
+ if (managedCapabilities?.readProtectedStorageKeys !== void 0) return new Set(await managedCapabilities.readProtectedStorageKeys(sessionKey));
958
+ const discovered = await this.#listDiscoveredCleanupScopes(driver, sessionKey);
959
+ const protectedRefSets = await Promise.all(discovered.map(async ({ knownRecordKeys, scope }) => {
960
+ const metadataEntries = await this.#listManagedMetadataUsingDriver(driver, scope, {
961
+ knownRecordKeys,
962
+ order: "key"
963
+ });
964
+ const refs = [];
965
+ for (const entry of metadataEntries) if (isOfflineProtectedMetadata(entry.customMetadata)) refs.push(serializeProtectedRef({
966
+ ...scope,
967
+ key: entry.key
968
+ }));
969
+ return refs;
970
+ }));
971
+ return new Set(protectedRefSets.flat());
972
+ }
973
+ async syncSessionProtectedKeys(sessionKey, protectedKeys, previousProtectedKeys = []) {
974
+ const nextProtectedRefSet = new Set(protectedKeys);
975
+ const previousProtectedRefSet = new Set(previousProtectedKeys);
976
+ const changedProtectedRefs = [...[...nextProtectedRefSet].filter((entryRef) => !previousProtectedRefSet.has(entryRef)), ...[...previousProtectedRefSet].filter((entryRef) => !nextProtectedRefSet.has(entryRef))];
977
+ if (changedProtectedRefs.length === 0) return;
978
+ const updatesByScope = /* @__PURE__ */ new Map();
979
+ for (const entryRef of changedProtectedRefs) {
980
+ const parsedRef = parseProtectedRef(entryRef);
981
+ if (parsedRef === null || parsedRef.sessionKey !== sessionKey) continue;
982
+ const scope = {
983
+ sessionKey: parsedRef.sessionKey,
984
+ storeName: parsedRef.storeName,
985
+ kind: parsedRef.kind
986
+ };
987
+ const namespaceId = getNamespaceId(scope);
988
+ const existingScopeUpdate = updatesByScope.get(namespaceId);
989
+ if (existingScopeUpdate !== void 0) {
990
+ existingScopeUpdate.protectionByKey.set(parsedRef.key, nextProtectedRefSet.has(entryRef));
991
+ continue;
992
+ }
993
+ updatesByScope.set(namespaceId, {
994
+ scope,
995
+ protectionByKey: new Map([[parsedRef.key, nextProtectedRefSet.has(entryRef)]])
996
+ });
997
+ }
998
+ await this.#runWithSessionWriterLock(sessionKey, async () => {
999
+ await this.#flushPendingNamespaceCommitsForSessionUnlocked(sessionKey);
1000
+ const managedCapabilities = getManagedDriverCapabilities(this.#driver);
1001
+ if (managedCapabilities?.syncSessionProtectedKeys !== void 0) {
1002
+ await managedCapabilities.syncSessionProtectedKeys(sessionKey, nextProtectedRefSet);
1003
+ for (const { scope } of updatesByScope.values()) {
1004
+ this.#invalidateCachedNamespace(scope);
1005
+ this.#broadcastNamespaceInvalidation(scope, "commit");
1006
+ }
1007
+ return;
1008
+ }
1009
+ await Promise.all([...updatesByScope.values()].map(async ({ scope, protectionByKey }) => {
1010
+ const indexState = await this.#readNamespaceIndexStateUsingDriver(this.#driver, scope);
1011
+ const indexEntries = indexState.valid && indexState.entries !== null ? indexState.entries : /* @__PURE__ */ new Map();
1012
+ let changed = false;
1013
+ for (const [key, shouldProtect] of protectionByKey.entries()) {
1014
+ const existingMetadata = indexEntries.get(key);
1015
+ if (existingMetadata === void 0) continue;
1016
+ if (isOfflineProtectedMetadata(existingMetadata.customMetadata) === shouldProtect) continue;
1017
+ const nextCustomMetadata = setOfflineProtectionMetadata(existingMetadata.customMetadata, shouldProtect);
1018
+ const nextMetadata = { ...existingMetadata };
1019
+ if (nextCustomMetadata !== void 0) nextMetadata.customMetadata = nextCustomMetadata;
1020
+ else delete nextMetadata.customMetadata;
1021
+ indexEntries.set(key, nextMetadata);
1022
+ changed = true;
1023
+ }
1024
+ if (changed) {
1025
+ await this.#persistNamespaceIndexUsingDriver(this.#driver, scope, {
1026
+ entries: indexEntries,
1027
+ staticPolicy: normalizeStaticPolicy(indexState.staticPolicy)
1028
+ });
1029
+ this.#invalidateCachedNamespace(scope);
1030
+ this.#broadcastNamespaceInvalidation(scope, "commit");
1031
+ }
1032
+ }));
1033
+ });
1034
+ }
1035
+ resetForTests() {
1036
+ for (const pending of this.#pendingNamespaceCommits.values()) pending.cancelFlush?.();
1037
+ this.clearAllCachedReads();
1038
+ this.#namespaceReadCacheGenerations.clear();
1039
+ this.#observedScopes.clear();
1040
+ this.#pendingNamespaceCommits.clear();
1041
+ this.#recentTouchedBuckets.clear();
1042
+ this.#cancelStartupCleanup?.();
1043
+ this.#cancelStartupCleanup = null;
1044
+ this.#startupCleanupScheduled = false;
1045
+ this.#driver.__resetForTests?.();
1046
+ }
1047
+ shouldEnqueueTouch(scope, key, lastAccessAt, touchMode, now) {
1048
+ if (touchMode === "never") return false;
1049
+ const currentBucket = getBucketId(now);
1050
+ if (touchMode !== "force" && getBucketId(lastAccessAt) === currentBucket) return false;
1051
+ const namespaceKey = getNamespaceId(scope);
1052
+ const touchGuardKey = `${namespaceKey}::${key}`;
1053
+ if (this.#recentTouchedBuckets.get(touchGuardKey) === currentBucket) return false;
1054
+ const pendingTouch = this.#pendingNamespaceCommits.get(namespaceKey)?.touches.get(key);
1055
+ return pendingTouch === void 0 || getBucketId(pendingTouch) !== currentBucket;
1056
+ }
1057
+ #hasPendingBarrierForKeys(pending, keys) {
1058
+ return keys.some((key) => {
1059
+ return pending.upserts.has(key) || pending.removes.has(key) || pending.inFlightBarrierKeys?.has(key) === true;
1060
+ });
1061
+ }
1062
+ async queueCommitToNamespace(scope, args) {
1063
+ const pending = this.#getOrCreatePendingNamespaceCommit(scope);
1064
+ const now = Date.now();
1065
+ for (const touch of args.touches ?? []) pending.touches.set(touch.key, touch.lastAccessAt ?? now);
1066
+ for (const remove of args.removes ?? []) {
1067
+ pending.upserts.delete(remove);
1068
+ pending.touches.delete(remove);
1069
+ pending.removes.add(remove);
1070
+ }
1071
+ if ("staticPolicy" in args) {
1072
+ pending.hasStaticPolicyUpdate = true;
1073
+ pending.staticPolicy = args.staticPolicy ?? null;
1074
+ }
1075
+ for (const upsert of args.upserts ?? []) {
1076
+ pending.removes.delete(upsert.key);
1077
+ pending.upserts.set(upsert.key, __LEGIT_CAST__(upsert));
1078
+ }
1079
+ this.#schedulePendingNamespaceFlush(pending);
1080
+ return new Promise((resolve, reject) => {
1081
+ pending.waiters.push({
1082
+ resolve,
1083
+ reject
1084
+ });
1085
+ });
1086
+ }
1087
+ async flushPendingNamespaceCommit(scope, keys) {
1088
+ const namespaceKey = getNamespaceId(scope);
1089
+ const pending = this.#pendingNamespaceCommits.get(namespaceKey);
1090
+ if (!pending) return;
1091
+ if (keys !== void 0 && keys.length > 0 && !this.#hasPendingBarrierForKeys(pending, keys)) return;
1092
+ await this.#runWithSessionWriterLock(scope.sessionKey, async () => {
1093
+ await this.#flushPendingNamespaceCommitUnlocked(scope, keys);
1094
+ });
1095
+ }
1096
+ async #flushPendingNamespaceCommitUnlocked(scope, keys) {
1097
+ const namespaceKey = getNamespaceId(scope);
1098
+ const pending = this.#pendingNamespaceCommits.get(namespaceKey);
1099
+ if (!pending) return;
1100
+ if (keys !== void 0 && keys.length > 0 && !this.#hasPendingBarrierForKeys(pending, keys)) return;
1101
+ if (pending.flushPromise) {
1102
+ await pending.flushPromise;
1103
+ return;
1104
+ }
1105
+ pending.cancelFlush?.();
1106
+ pending.cancelFlush = null;
1107
+ const upserts = [...pending.upserts.values()];
1108
+ const removes = [...pending.removes];
1109
+ const hasStaticPolicyUpdate = pending.hasStaticPolicyUpdate;
1110
+ const staticPolicy = pending.staticPolicy;
1111
+ const touches = [...pending.touches.entries()].map(([key, lastAccessAt]) => ({
1112
+ key,
1113
+ lastAccessAt
1114
+ }));
1115
+ const inFlightBarrierKeys = new Set([...pending.upserts.keys(), ...pending.removes]);
1116
+ const waiters = [...pending.waiters];
1117
+ pending.hasStaticPolicyUpdate = false;
1118
+ pending.upserts = /* @__PURE__ */ new Map();
1119
+ pending.removes = /* @__PURE__ */ new Set();
1120
+ pending.staticPolicy = null;
1121
+ pending.touches = /* @__PURE__ */ new Map();
1122
+ pending.waiters = [];
1123
+ pending.inFlightBarrierKeys = inFlightBarrierKeys.size > 0 ? inFlightBarrierKeys : null;
1124
+ if (upserts.length === 0 && removes.length === 0 && touches.length === 0 && !hasStaticPolicyUpdate) {
1125
+ this.#pendingNamespaceCommits.delete(namespaceKey);
1126
+ for (const waiter of waiters) waiter.resolve();
1127
+ return;
1128
+ }
1129
+ pending.flushPromise = this.#applyManagedCommit(scope, {
1130
+ upserts,
1131
+ removes,
1132
+ ...hasStaticPolicyUpdate ? { staticPolicy } : {},
1133
+ touches
1134
+ }).then(() => {
1135
+ const currentBucket = getBucketId(Date.now());
1136
+ for (const touch of touches) this.#recentTouchedBuckets.set(`${namespaceKey}::${touch.key}`, getBucketId(touch.lastAccessAt));
1137
+ for (const upsert of upserts) this.#recentTouchedBuckets.set(`${namespaceKey}::${upsert.key}`, currentBucket);
1138
+ this.#pruneRecentTouchedBuckets(currentBucket);
1139
+ for (const waiter of waiters) waiter.resolve();
1140
+ }).catch((error) => {
1141
+ for (const waiter of waiters) waiter.reject(error);
1142
+ throw error;
1143
+ }).finally(() => {
1144
+ pending.inFlightBarrierKeys = null;
1145
+ pending.flushPromise = null;
1146
+ if (pending.waiters.length === 0) {
1147
+ this.#pendingNamespaceCommits.delete(namespaceKey);
1148
+ return;
1149
+ }
1150
+ this.#schedulePendingNamespaceFlush(pending);
1151
+ });
1152
+ await pending.flushPromise;
1153
+ }
1154
+ async flushAllPendingNamespaceCommits() {
1155
+ await Promise.all([...this.#pendingNamespaceCommits.values()].map((pending) => this.flushPendingNamespaceCommit(pending.scope)));
1156
+ }
1157
+ async #flushPendingNamespaceCommitsForSessionUnlocked(sessionKey) {
1158
+ await Promise.all([...this.#pendingNamespaceCommits.values()].filter((pending) => pending.scope.sessionKey === sessionKey).map((pending) => this.#flushPendingNamespaceCommitUnlocked(pending.scope)));
1159
+ }
1160
+ clearRecentTouchedBucketsForNamespace(scope) {
1161
+ const keyPrefix = `${getNamespaceId(scope)}::`;
1162
+ for (const key of this.#recentTouchedBuckets.keys()) if (key.startsWith(keyPrefix)) this.#recentTouchedBuckets.delete(key);
1163
+ }
1164
+ async #readNamespaceIndexEntriesUsingDriver(driver, scope, knownRecordKeys) {
1165
+ const state = await this.#readNamespaceIndexStateUsingDriver(driver, scope, { knownRecordKeys });
1166
+ return state.valid && state.entries !== null ? state.entries : /* @__PURE__ */ new Map();
1167
+ }
1168
+ async #readNamespaceIndexStaticPolicyUsingDriver(driver, scope, knownRecordKeys) {
1169
+ const state = await this.#readNamespaceIndexStateUsingDriver(driver, scope, { knownRecordKeys });
1170
+ return state.valid ? normalizeStaticPolicy(state.staticPolicy) : null;
1171
+ }
1172
+ async #readNamespaceIndexStateUsingDriver(driver, scope, args = {}) {
1173
+ const knownRecordKeys = args.knownRecordKeys;
1174
+ const namespaceKey = getNamespaceId(scope);
1175
+ const shouldUseCache = driver === this.#driver;
1176
+ if (knownRecordKeys != null) {
1177
+ if (!knownRecordKeys.includes("_i")) {
1178
+ this.#invalidateCachedNamespace(scope);
1179
+ return {
1180
+ entries: null,
1181
+ exists: false,
1182
+ staticPolicy: null,
1183
+ valid: true
1184
+ };
1185
+ }
1186
+ if (shouldUseCache) {
1187
+ const existing = await this.#cachedNamespaceIndexReads.getAsync(namespaceKey);
1188
+ if (existing !== void 0) return cloneNamespaceIndexReadState(existing);
1189
+ }
1190
+ }
1191
+ if (!shouldUseCache) return readAsyncStorageNamespaceIndexStateUsingDriver(driver, scope, knownRecordKeys);
1192
+ const cacheGeneration = this.#getReadCacheGenerationSnapshot(scope);
1193
+ return cloneNamespaceIndexReadState(await this.#cachedNamespaceIndexReads.getOrInsertAsync(namespaceKey, async ({ skipCaching }) => {
1194
+ const nextState = await readAsyncStorageNamespaceIndexStateUsingDriver(driver, scope, knownRecordKeys);
1195
+ if (!this.#isReadCacheGenerationSnapshotCurrent(cacheGeneration)) return skipCaching(nextState);
1196
+ return this.#shouldCacheNamespaceIndexState(nextState) ? cloneNamespaceIndexReadState(nextState) : skipCaching(nextState);
1197
+ }));
1198
+ }
1199
+ async #persistNamespaceIndexUsingDriver(driver, scope, state, advanceGeneration = true) {
1200
+ if (advanceGeneration) this.#advanceNamespaceReadCacheGeneration(scope);
1201
+ const managedCapabilities = getManagedDriverCapabilities(driver);
1202
+ if (managedCapabilities?.persistNamespaceIndexState !== void 0) {
1203
+ await managedCapabilities.persistNamespaceIndexState(scope, state);
1204
+ if (state.entries.size === 0) this.#invalidateCachedNamespaceIndexState(scope);
1205
+ else this.#setCachedNamespaceIndexState(scope, {
1206
+ entries: state.entries,
1207
+ exists: true,
1208
+ staticPolicy: state.staticPolicy,
1209
+ valid: true
1210
+ });
1211
+ return;
1212
+ }
1213
+ if (state.entries.size === 0) {
1214
+ await this.#driverRemoveManyFrom(driver, scope, ["_i"]);
1215
+ this.#invalidateCachedNamespaceIndexState(scope);
1216
+ return;
1217
+ }
1218
+ await this.#driverSetManyFrom(driver, scope, [{
1219
+ key: "_i",
1220
+ value: serializeIndexState(state)
1221
+ }]);
1222
+ this.#setCachedNamespaceIndexState(scope, {
1223
+ entries: state.entries,
1224
+ exists: true,
1225
+ staticPolicy: state.staticPolicy,
1226
+ valid: true
1227
+ });
1228
+ }
1229
+ async readManagedEntries(scope, keys) {
1230
+ const managedCapabilities = getManagedDriverCapabilities(this.#driver);
1231
+ if (managedCapabilities?.readManagedEntries !== void 0) return __LEGIT_CAST__(await managedCapabilities.readManagedEntries(scope, keys));
1232
+ const metadataByKey = await this.#readNamespaceIndexEntriesUsingDriver(this.#driver, scope);
1233
+ const payloadKeys = keys.filter((key) => metadataByKey.has(key));
1234
+ const payloadValues = await this.#readPayloadValuesUsingDriver(this.#driver, scope, payloadKeys);
1235
+ const payloadByKey = /* @__PURE__ */ new Map();
1236
+ for (const [index, key] of payloadKeys.entries()) payloadByKey.set(key, payloadValues[index] ?? null);
1237
+ const result = /* @__PURE__ */ new Map();
1238
+ const orphanedKeys = [];
1239
+ for (const key of keys) {
1240
+ const metadata = metadataByKey.get(key);
1241
+ if (metadata === void 0) {
1242
+ result.set(key, null);
1243
+ continue;
1244
+ }
1245
+ const rawPayload = payloadByKey.get(key) ?? null;
1246
+ if (rawPayload === null) {
1247
+ orphanedKeys.push(key);
1248
+ result.set(key, null);
1249
+ continue;
1250
+ }
1251
+ result.set(key, {
1252
+ value: __LEGIT_CAST__(rawPayload),
1253
+ metadata: __LEGIT_CAST__(this.#toPublicMetadata(key, metadata))
1254
+ });
1255
+ }
1256
+ if (orphanedKeys.length > 0) await this.#removeManagedKeysUsingDriver(this.#driver, scope, orphanedKeys);
1257
+ return result;
1258
+ }
1259
+ async listManagedMetadata(scope, args = {}) {
1260
+ return this.#listManagedMetadataUsingDriver(this.#driver, scope, args);
1261
+ }
1262
+ async #listManagedMetadataUsingDriver(driver, scope, args = {}) {
1263
+ const managedCapabilities = getManagedDriverCapabilities(driver);
1264
+ if (managedCapabilities?.listManagedMetadata !== void 0) return __LEGIT_CAST__(await managedCapabilities.listManagedMetadata(scope, args));
1265
+ const metadataEntries = await this.#readNamespaceIndexEntriesUsingDriver(driver, scope, args.knownRecordKeys);
1266
+ const validEntries = [];
1267
+ for (const [key, metadata] of metadataEntries.entries()) validEntries.push(this.#toPublicMetadata(key, metadata));
1268
+ if (args.filter !== void 0) {
1269
+ const { filter } = args;
1270
+ return __LEGIT_CAST__(validEntries.filter((entry) => entry.customMetadata[filter.key] === filter.equals).sort((left, right) => compareMetadata(left, right, args.order ?? "key")));
1271
+ }
1272
+ validEntries.sort((left, right) => compareMetadata(left, right, args.order ?? "key"));
1273
+ return __LEGIT_CAST__(validEntries);
1274
+ }
1275
+ async listManagedKeys(scope) {
1276
+ const managedCapabilities = getManagedDriverCapabilities(this.#driver);
1277
+ if (managedCapabilities?.listManagedKeys !== void 0) return managedCapabilities.listManagedKeys(scope);
1278
+ return [...(await this.#readNamespaceIndexEntriesUsingDriver(this.#driver, scope)).keys()].sort((left, right) => left.localeCompare(right));
1279
+ }
1280
+ async clearManagedNamespace(scope) {
1281
+ await this.#runWithSessionWriterLock(scope.sessionKey, async () => {
1282
+ await this.#clearManagedNamespaceUnlocked(scope);
1283
+ });
1284
+ }
1285
+ async #clearManagedNamespaceUnlocked(scope) {
1286
+ const managedCapabilities = getManagedDriverCapabilities(this.#driver);
1287
+ if (managedCapabilities?.clearManagedNamespace !== void 0) await managedCapabilities.clearManagedNamespace(scope);
1288
+ else await this.#driver.clear(scope);
1289
+ this.#invalidateCachedNamespace(scope);
1290
+ this.#broadcastNamespaceInvalidation(scope, "clear");
1291
+ const namespaceKey = getNamespaceId(scope);
1292
+ this.#observedScopes.delete(namespaceKey);
1293
+ this.#pendingNamespaceCommits.delete(namespaceKey);
1294
+ this.clearRecentTouchedBucketsForNamespace(scope);
1295
+ }
1296
+ #toPublicMetadata(key, metadata) {
1297
+ return {
1298
+ key,
1299
+ payloadRef: getPayloadRecordKey(key),
1300
+ writtenAt: metadata.lastAccessAt,
1301
+ lastAccessAt: metadata.lastAccessAt,
1302
+ sizeBytes: metadata.sizeBytes,
1303
+ version: metadata.version,
1304
+ customMetadata: metadata.customMetadata ?? {}
1305
+ };
1306
+ }
1307
+ async #applyManagedCommit(scope, args) {
1308
+ const upserts = args.upserts ?? [];
1309
+ const removes = [...new Set(args.removes ?? [])];
1310
+ const touches = args.touches ?? [];
1311
+ const touchedKeys = [...new Set(touches.map((touch) => touch.key))];
1312
+ const managedCapabilities = getManagedDriverCapabilities(this.#driver);
1313
+ if (managedCapabilities?.applyManagedCommit !== void 0) {
1314
+ await managedCapabilities.applyManagedCommit(scope, args, { mergeOfflineProtectionMetadata: (key, nextCustomMetadata, currentCustomMetadata) => mergeManagedAsyncStorageCustomMetadata(currentCustomMetadata, nextCustomMetadata, getSessionProtectedKeysSnapshot(scope.sessionKey), scope, key) });
1315
+ this.#advanceNamespaceReadCacheGeneration(scope);
1316
+ this.#invalidateCachedNamespaceIndexState(scope);
1317
+ for (const key of removes) this.#invalidateCachedPayloadValue(scope, key);
1318
+ for (const upsert of upserts) this.#setCachedPayloadValue(scope, upsert.key, { value: upsert.value });
1319
+ this.#broadcastNamespaceInvalidation(scope, "commit");
1320
+ return;
1321
+ }
1322
+ const currentIndexState = await this.#readNamespaceIndexStateUsingDriver(this.#driver, scope);
1323
+ const indexEntries = currentIndexState.valid && currentIndexState.entries !== null ? currentIndexState.entries : /* @__PURE__ */ new Map();
1324
+ const now = Date.now();
1325
+ const touchesByKey = new Map(touches.map((touch) => [touch.key, touch.lastAccessAt ?? now]));
1326
+ const setEntries = [];
1327
+ const removeEntries = removes.map((key) => getPayloadRecordKey(key));
1328
+ let indexChanged = false;
1329
+ let nextStaticPolicy = normalizeStaticPolicy(currentIndexState.staticPolicy);
1330
+ for (const key of removes) indexChanged = indexEntries.delete(key) || indexChanged;
1331
+ if ("staticPolicy" in args) {
1332
+ const normalizedNextStaticPolicy = normalizeStaticPolicy(args.staticPolicy ?? null);
1333
+ if (!deepEqual(nextStaticPolicy, normalizedNextStaticPolicy)) {
1334
+ nextStaticPolicy = normalizedNextStaticPolicy;
1335
+ indexChanged = true;
1336
+ }
1337
+ }
1338
+ const protectedKeysSnapshotSet = getSessionProtectedKeysSnapshot(scope.sessionKey);
1339
+ for (const upsert of upserts) {
1340
+ const existingMetadata = indexEntries.get(upsert.key);
1341
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(existingMetadata?.customMetadata, upsert.metadata, protectedKeysSnapshotSet, scope, upsert.key);
1342
+ const nextLastAccessAt = touchesByKey.get(upsert.key) ?? existingMetadata?.lastAccessAt ?? now;
1343
+ const serializedValue = upsert.serializedValue !== void 0 ? { rawValue: upsert.serializedValue } : serializeJsonForStorage(upsert.value);
1344
+ const nextSizeBytes = scope.kind !== "document" ? estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, nextLastAccessAt, upsert.version, customMetadata) : void 0;
1345
+ const nextMetadata = {
1346
+ lastAccessAt: nextLastAccessAt,
1347
+ version: upsert.version,
1348
+ ...nextSizeBytes !== void 0 ? { sizeBytes: nextSizeBytes } : {},
1349
+ ...customMetadata ? { customMetadata } : {}
1350
+ };
1351
+ setEntries.push({
1352
+ key: getPayloadRecordKey(upsert.key),
1353
+ serializedValue: serializedValue.rawValue,
1354
+ ...nextSizeBytes !== void 0 ? { sizeBytes: nextSizeBytes } : {},
1355
+ value: upsert.value
1356
+ });
1357
+ if (existingMetadata !== void 0 && existingMetadata.lastAccessAt === nextMetadata.lastAccessAt && existingMetadata.sizeBytes === nextMetadata.sizeBytes && existingMetadata.version === nextMetadata.version && deepEqual(existingMetadata.customMetadata, nextMetadata.customMetadata)) continue;
1358
+ indexEntries.set(upsert.key, nextMetadata);
1359
+ indexChanged = true;
1360
+ }
1361
+ if (touchedKeys.length > 0) {
1362
+ const upsertKeySet = new Set(upserts.map((upsert) => upsert.key));
1363
+ for (const key of touchedKeys) {
1364
+ if (upsertKeySet.has(key)) continue;
1365
+ const metadata = indexEntries.get(key);
1366
+ if (!metadata) continue;
1367
+ const nextLastAccessAt = touchesByKey.get(key) ?? now;
1368
+ if (metadata.lastAccessAt === nextLastAccessAt) continue;
1369
+ indexEntries.set(key, {
1370
+ ...metadata,
1371
+ lastAccessAt: nextLastAccessAt
1372
+ });
1373
+ indexChanged = true;
1374
+ }
1375
+ }
1376
+ await Promise.all([removeEntries.length > 0 ? this.#driverRemoveManyFrom(this.#driver, scope, removeEntries) : Promise.resolve(), setEntries.length > 0 ? this.#driverSetManyFrom(this.#driver, scope, setEntries) : Promise.resolve()]);
1377
+ this.#advanceNamespaceReadCacheGeneration(scope);
1378
+ for (const key of removes) this.#invalidateCachedPayloadValue(scope, key);
1379
+ for (const upsert of upserts) this.#setCachedPayloadValue(scope, upsert.key, { value: upsert.value });
1380
+ if (indexChanged) await this.#persistNamespaceIndexUsingDriver(this.#driver, scope, {
1381
+ entries: indexEntries,
1382
+ staticPolicy: nextStaticPolicy
1383
+ }, false);
1384
+ else this.#setCachedNamespaceIndexState(scope, {
1385
+ entries: currentIndexState.valid ? indexEntries : null,
1386
+ exists: currentIndexState.exists,
1387
+ staticPolicy: currentIndexState.staticPolicy,
1388
+ valid: currentIndexState.valid
1389
+ });
1390
+ this.#broadcastNamespaceInvalidation(scope, "commit");
1391
+ }
1392
+ async #removeManagedKeysUsingDriver(driver, scope, keys) {
1393
+ const uniqueKeys = [...new Set(keys)];
1394
+ if (uniqueKeys.length === 0) return;
1395
+ await this.#runWithSessionWriterLock(scope.sessionKey, async () => {
1396
+ const indexState = await this.#readNamespaceIndexStateUsingDriver(driver, scope);
1397
+ await this.#driverRemoveManyFrom(driver, scope, uniqueKeys.map((key) => getPayloadRecordKey(key)));
1398
+ for (const key of uniqueKeys) this.#invalidateCachedPayloadValue(scope, key);
1399
+ if (indexState.valid && indexState.entries !== null) {
1400
+ let changed = false;
1401
+ for (const key of uniqueKeys) changed = indexState.entries.delete(key) || changed;
1402
+ if (changed) await this.#persistNamespaceIndexUsingDriver(driver, scope, {
1403
+ entries: indexState.entries,
1404
+ staticPolicy: normalizeStaticPolicy(indexState.staticPolicy)
1405
+ });
1406
+ }
1407
+ this.#broadcastNamespaceInvalidation(scope, "remove");
1408
+ });
1409
+ }
1410
+ async #driverSetManyFrom(driver, scope, entries) {
1411
+ if (entries.length === 0) return;
1412
+ await driver.setMany(scope, entries);
1413
+ }
1414
+ async #driverRemoveManyFrom(driver, scope, keys) {
1415
+ if (keys.length === 0) return;
1416
+ await driver.removeMany(scope, keys);
1417
+ }
1418
+ #readMaintenanceState() {
1419
+ const raw = localStorage.getItem(ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY);
1420
+ if (raw === null) return createDefaultMaintenanceState();
1421
+ try {
1422
+ return parseMaintenanceState(JSON.parse(raw)) ?? createDefaultMaintenanceState();
1423
+ } catch {
1424
+ return createDefaultMaintenanceState();
1425
+ }
1426
+ }
1427
+ #writeMaintenanceState(state) {
1428
+ localStorage.setItem(ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY, JSON.stringify({ lca: state.lastSuccessfulCleanupAt }));
1429
+ }
1430
+ clearAllCachedReads() {
1431
+ this.#readCacheGeneration += 1;
1432
+ this.#cachedNamespaceIndexReads.clear();
1433
+ this.#cachedPayloadReads.clear();
1434
+ }
1435
+ onRemoteCacheInvalidation(message) {
1436
+ this.#invalidateCachedNamespace(message.scope);
1437
+ }
1438
+ async #readPayloadValuesUsingDriver(driver, scope, keys) {
1439
+ if (keys.length === 0) return [];
1440
+ if (!(driver === this.#driver)) return driverGetManyFrom(driver, scope, keys.map((key) => getPayloadRecordKey(key)));
1441
+ const cacheGeneration = this.#getReadCacheGenerationSnapshot(scope);
1442
+ const promisesByKey = /* @__PURE__ */ new Map();
1443
+ const uncachedKeys = [];
1444
+ for (const key of keys) {
1445
+ const payloadCacheKey = this.#getPayloadCacheKey(scope, key);
1446
+ if (this.#cachedPayloadReads.has(payloadCacheKey)) {
1447
+ promisesByKey.set(key, this.#cachedPayloadReads.getAsync(payloadCacheKey).then((state) => state ?? null));
1448
+ continue;
1449
+ }
1450
+ uncachedKeys.push(key);
1451
+ }
1452
+ if (uncachedKeys.length > 0) {
1453
+ const readPromise = driverGetManyFrom(driver, scope, uncachedKeys.map((key) => getPayloadRecordKey(key)));
1454
+ for (const [index, key] of uncachedKeys.entries()) {
1455
+ const payloadCacheKey = this.#getPayloadCacheKey(scope, key);
1456
+ const keyPromise = this.#cachedPayloadReads.setAsync(payloadCacheKey, async ({ skipCaching }) => {
1457
+ const value = (await readPromise)[index] ?? null;
1458
+ const nextState = value === null ? null : { value: klona(value) };
1459
+ if (!this.#isReadCacheGenerationSnapshotCurrent(cacheGeneration)) return skipCaching(nextState);
1460
+ return nextState === null ? skipCaching(null) : nextState;
1461
+ });
1462
+ promisesByKey.set(key, keyPromise);
1463
+ }
1464
+ }
1465
+ return Promise.all(keys.map(async (key) => {
1466
+ const state = await promisesByKey.get(key);
1467
+ return state === null || state === void 0 ? null : klona(state.value);
1468
+ }));
1469
+ }
1470
+ #setCachedNamespaceIndexState(scope, state) {
1471
+ if (!this.#shouldCacheNamespaceIndexState(state)) {
1472
+ this.#cachedNamespaceIndexReads.delete(getNamespaceId(scope));
1473
+ return;
1474
+ }
1475
+ this.#cachedNamespaceIndexReads.set(getNamespaceId(scope), cloneNamespaceIndexReadState(state));
1476
+ }
1477
+ #setCachedPayloadValue(scope, key, state) {
1478
+ this.#cachedPayloadReads.set(this.#getPayloadCacheKey(scope, key), { value: klona(state.value) });
1479
+ }
1480
+ #invalidateCachedNamespaceIndexState(scope) {
1481
+ this.#cachedNamespaceIndexReads.delete(getNamespaceId(scope));
1482
+ }
1483
+ #invalidateCachedPayloadValue(scope, key) {
1484
+ this.#cachedPayloadReads.delete(this.#getPayloadCacheKey(scope, key));
1485
+ }
1486
+ #invalidateCachedNamespace(scope) {
1487
+ const namespaceKey = `${getNamespaceId(scope)}::`;
1488
+ this.#advanceNamespaceReadCacheGeneration(scope);
1489
+ this.#invalidateCachedNamespaceIndexState(scope);
1490
+ for (const key of this.#cachedPayloadReads[" cache"].map.keys()) if (key.startsWith(namespaceKey)) this.#cachedPayloadReads.delete(key);
1491
+ }
1492
+ #getPayloadCacheKey(scope, key) {
1493
+ return `${getNamespaceId(scope)}::${key}`;
1494
+ }
1495
+ #getNamespaceReadCacheGeneration(namespaceId) {
1496
+ return this.#namespaceReadCacheGenerations.get(namespaceId) ?? 0;
1497
+ }
1498
+ #advanceNamespaceReadCacheGeneration(scope) {
1499
+ const namespaceId = getNamespaceId(scope);
1500
+ this.#namespaceReadCacheGenerations.set(namespaceId, this.#getNamespaceReadCacheGeneration(namespaceId) + 1);
1501
+ }
1502
+ #getReadCacheGenerationSnapshot(scope) {
1503
+ const namespaceId = getNamespaceId(scope);
1504
+ return {
1505
+ globalGeneration: this.#readCacheGeneration,
1506
+ namespaceGeneration: this.#getNamespaceReadCacheGeneration(namespaceId),
1507
+ namespaceId
1508
+ };
1509
+ }
1510
+ #isReadCacheGenerationSnapshotCurrent(snapshot) {
1511
+ return snapshot.globalGeneration === this.#readCacheGeneration && snapshot.namespaceGeneration === this.#getNamespaceReadCacheGeneration(snapshot.namespaceId);
1512
+ }
1513
+ #shouldCacheNamespaceIndexState(state) {
1514
+ return state.valid && state.exists && state.entries !== null;
1515
+ }
1516
+ #broadcastNamespaceInvalidation(scope, reason) {
1517
+ const message = {
1518
+ kind: "namespace-invalidated",
1519
+ protocolVersion: 1,
1520
+ reason,
1521
+ scope
1522
+ };
1523
+ notifyLocalAsyncStorageReadCacheInvalidation(this, message);
1524
+ asyncStorageCacheInvalidationChannel?.postMessage(message);
1525
+ }
1526
+ async #listDiscoveredScopes(sessionKey, driver = this.#driver) {
1527
+ return (await driver.listScopes(sessionKey)).filter((scope) => scope.kind !== "__internal.protected");
1528
+ }
1529
+ #getOrCreatePendingNamespaceCommit(scope) {
1530
+ const namespaceKey = getNamespaceId(scope);
1531
+ const existing = this.#pendingNamespaceCommits.get(namespaceKey);
1532
+ if (existing) return existing;
1533
+ const created = {
1534
+ scope,
1535
+ cancelFlush: null,
1536
+ inFlightBarrierKeys: null,
1537
+ flushPromise: null,
1538
+ hasStaticPolicyUpdate: false,
1539
+ removes: /* @__PURE__ */ new Set(),
1540
+ staticPolicy: null,
1541
+ touches: /* @__PURE__ */ new Map(),
1542
+ upserts: /* @__PURE__ */ new Map(),
1543
+ waiters: []
1544
+ };
1545
+ this.#pendingNamespaceCommits.set(namespaceKey, created);
1546
+ return created;
1547
+ }
1548
+ #schedulePendingNamespaceFlush(pending) {
1549
+ if (pending.cancelFlush !== null || pending.flushPromise !== null) return;
1550
+ const timeoutId = setTimeout(() => {
1551
+ pending.cancelFlush = null;
1552
+ this.flushPendingNamespaceCommit(pending.scope);
1553
+ }, 40);
1554
+ pending.cancelFlush = () => clearTimeout(timeoutId);
1555
+ }
1556
+ #pruneRecentTouchedBuckets(currentBucket) {
1557
+ for (const [key, bucket] of this.#recentTouchedBuckets) if (bucket !== currentBucket) this.#recentTouchedBuckets.delete(key);
1558
+ }
1559
+ #scheduleStartupCleanupIfNeeded() {
1560
+ if (this.#startupCleanupScheduled) return;
1561
+ this.#startupCleanupScheduled = true;
1562
+ this.#cancelStartupCleanup = scheduleInitialMaintenanceCleanup(() => {
1563
+ this.#cancelStartupCleanup = null;
1564
+ this.#runStartupCleanupIfDue().catch(() => {});
1565
+ });
1566
+ }
1567
+ async #runStartupCleanupIfDue() {
1568
+ if (document.hidden) await sleep(2e3);
1569
+ await runWithNavigatorLock(ASYNC_STARTUP_CLEANUP_LOCK_NAME, ASYNC_STARTUP_CLEANUP_LOCK_WARNING, async () => {
1570
+ const maintenance = this.#readMaintenanceState();
1571
+ const now = Date.now();
1572
+ if (maintenance.lastSuccessfulCleanupAt !== null && now - maintenance.lastSuccessfulCleanupAt < ASYNC_STORAGE_STARTUP_CLEANUP_COOLDOWN_MS) return;
1573
+ await this.#performStartupCleanup();
1574
+ this.#writeMaintenanceState({ lastSuccessfulCleanupAt: Date.now() });
1575
+ });
1576
+ }
1577
+ async #performStartupCleanup() {
1578
+ await this.flushAllPendingNamespaceCommits();
1579
+ const scopesToInvalidate = await this.#withCleanupDriver(async (driver) => {
1580
+ const discoveredScopes = await this.#listDiscoveredCleanupScopes(driver);
1581
+ const discoveredScopesBySession = /* @__PURE__ */ new Map();
1582
+ for (const discoveredScope of discoveredScopes) {
1583
+ const existing = discoveredScopesBySession.get(discoveredScope.scope.sessionKey);
1584
+ if (existing !== void 0) existing.push(discoveredScope);
1585
+ else discoveredScopesBySession.set(discoveredScope.scope.sessionKey, [discoveredScope]);
1586
+ }
1587
+ return (await Promise.all([...discoveredScopesBySession.entries()].map(async ([sessionKey, sessionDiscoveredScopes]) => this.#runWithSessionWriterLock(sessionKey, async () => {
1588
+ await this.#flushPendingNamespaceCommitsForSessionUnlocked(sessionKey);
1589
+ return this.#performStartupCleanupWithDriver(driver, {
1590
+ discoveredScopes: sessionDiscoveredScopes,
1591
+ sessionKey
1592
+ });
1593
+ })))).flat();
1594
+ });
1595
+ for (const scope of scopesToInvalidate) {
1596
+ this.#invalidateCachedNamespace(scope);
1597
+ this.#broadcastNamespaceInvalidation(scope, "startup-cleanup");
1598
+ }
1599
+ }
1600
+ async #performStartupCleanupWithDriver(driver, args = {}) {
1601
+ const cleanupActionDriver = __LEGIT_CAST__(driver);
1602
+ const discoveredScopes = args.discoveredScopes ?? await this.#listDiscoveredCleanupScopes(driver, args.sessionKey);
1603
+ const now = Date.now();
1604
+ const uniqueSessionKeys = [...new Set(discoveredScopes.map(({ scope }) => scope.sessionKey))];
1605
+ const offlineSessions = new Set(uniqueSessionKeys.filter((sessionKey) => isSessionOfflineInLocalStorage(sessionKey)));
1606
+ const protectedRefsBySession = new Map(uniqueSessionKeys.map((sessionKey) => [sessionKey, getSessionProtectedKeysSnapshot(sessionKey)]));
1607
+ const customStartupCallbacks = registeredAsyncStartupStoreCleanupCallbacks.get(this) ?? /* @__PURE__ */ new Map();
1608
+ const discoveredScopesByStore = /* @__PURE__ */ new Map();
1609
+ for (const discoveredScope of discoveredScopes) {
1610
+ const storeKey = getStoreRegistryKey(discoveredScope.scope.sessionKey, discoveredScope.scope.storeName);
1611
+ const existing = discoveredScopesByStore.get(storeKey);
1612
+ if (existing !== void 0) existing.push(discoveredScope);
1613
+ else discoveredScopesByStore.set(storeKey, [discoveredScope]);
1614
+ }
1615
+ const callbackEntries = [];
1616
+ for (const [storeKey, storeDiscoveredScopes] of discoveredScopesByStore) {
1617
+ const callback = customStartupCallbacks.get(storeKey);
1618
+ if (callback === void 0) continue;
1619
+ callbackEntries.push({
1620
+ callback,
1621
+ scopes: storeDiscoveredScopes,
1622
+ storeKey
1623
+ });
1624
+ }
1625
+ const [callbackResults, genericScopePlans] = await Promise.all([Promise.all(callbackEntries.map(({ callback, scopes }) => callback({
1626
+ discoveredScopes: scopes,
1627
+ driver,
1628
+ now
1629
+ }))), Promise.all(discoveredScopes.map(async ({ knownRecordKeys, scope }) => this.#planStartupCleanupForScope({
1630
+ driver,
1631
+ knownRecordKeys,
1632
+ now,
1633
+ protectedRefs: protectedRefsBySession.get(scope.sessionKey) ?? void 0,
1634
+ skipExpiration: offlineSessions.has(scope.sessionKey),
1635
+ scope
1636
+ })))]);
1637
+ const scopePlansByNamespaceId = new Map(genericScopePlans.map((plan) => [getNamespaceId(plan.scope), plan]));
1638
+ const customStoreDeletePlans = [];
1639
+ for (const result of callbackResults) {
1640
+ for (const scopePlan of result.scopePlans) {
1641
+ const namespaceId = getNamespaceId(scopePlan.scope);
1642
+ const existing = scopePlansByNamespaceId.get(namespaceId);
1643
+ scopePlansByNamespaceId.set(namespaceId, this.#mergeStartupCleanupScopePlan(existing ?? {
1644
+ deleteAction: null,
1645
+ persistEntries: null,
1646
+ scope: scopePlan.scope
1647
+ }, {
1648
+ deleteAction: scopePlan.deleteKeys.length === 0 ? null : this.#createStartupCleanupDeleteAction({
1649
+ keys: scopePlan.deleteKeys,
1650
+ scope: scopePlan.scope
1651
+ }),
1652
+ persistEntries: scopePlan.persistEntries ?? null,
1653
+ persistStaticPolicy: scopePlan.persistStaticPolicy,
1654
+ scope: scopePlan.scope
1655
+ }));
1656
+ }
1657
+ for (const storeDeletePlan of result.storeDeletePlans ?? []) customStoreDeletePlans.push(storeDeletePlan);
1658
+ }
1659
+ const scopePlans = [...scopePlansByNamespaceId.values()];
1660
+ const genericStoreDeletePlans = cleanupActionDriver.cleanupRemoveKnownStoreDir === void 0 ? [] : this.#planStartupCleanupStoreDeletes({
1661
+ customStoreDeletePlanStoreKeys: new Set(customStoreDeletePlans.map((storeDeletePlan) => getStoreRegistryKey(storeDeletePlan.representativeScope.sessionKey, storeDeletePlan.representativeScope.storeName))),
1662
+ discoveredScopesByStore,
1663
+ scopePlansByNamespaceId
1664
+ });
1665
+ const storeDeletePlans = [...customStoreDeletePlans, ...genericStoreDeletePlans];
1666
+ const persistPlans = [];
1667
+ const invalidatedScopesByNamespaceId = /* @__PURE__ */ new Map();
1668
+ const successfulStoreDeleteSessions = /* @__PURE__ */ new Set();
1669
+ const successfulStoreDeleteScopes = /* @__PURE__ */ new Set();
1670
+ const skippedScopeIds = new Set(genericStoreDeletePlans.flatMap((storeDeletePlan) => storeDeletePlan.removedKeysByScope.map(({ scope }) => getNamespaceId(scope))));
1671
+ if (cleanupActionDriver.cleanupRemoveKnownStoreDir !== void 0) {
1672
+ const removeStoreDir = cleanupActionDriver.cleanupRemoveKnownStoreDir;
1673
+ const storeDeleteResults = await Promise.all(storeDeletePlans.map(async (storeDeletePlan) => {
1674
+ const deleteKeys = [...new Set(storeDeletePlan.removedKeysByScope.flatMap(({ keys }) => keys))];
1675
+ return {
1676
+ removed: await removeStoreDir(storeDeletePlan.representativeScope, deleteKeys),
1677
+ storeDeletePlan
1678
+ };
1679
+ }));
1680
+ for (const { removed, storeDeletePlan } of storeDeleteResults) {
1681
+ if (!removed) continue;
1682
+ for (const { keys, scope } of storeDeletePlan.removedKeysByScope) cleanupActionDriver.cleanupFinalizeRemovedRecords?.(scope, keys);
1683
+ cleanupActionDriver.cleanupFinalizeRemovedStoreDir?.(storeDeletePlan.representativeScope, []);
1684
+ successfulStoreDeleteSessions.add(storeDeletePlan.representativeScope.sessionKey);
1685
+ for (const { scope } of storeDeletePlan.removedKeysByScope) {
1686
+ const namespaceId = getNamespaceId(scope);
1687
+ invalidatedScopesByNamespaceId.set(namespaceId, scope);
1688
+ successfulStoreDeleteScopes.add(namespaceId);
1689
+ skippedScopeIds.add(namespaceId);
1690
+ }
1691
+ }
1692
+ }
1693
+ const deleteResults = await Promise.allSettled(scopePlans.flatMap((plan) => {
1694
+ if (skippedScopeIds.has(getNamespaceId(plan.scope))) return [];
1695
+ return plan.deleteAction === null ? [] : [this.#runStartupCleanupDeleteAction(cleanupActionDriver, plan.deleteAction)];
1696
+ }));
1697
+ for (const settledResult of deleteResults) {
1698
+ if (settledResult.status !== "fulfilled") continue;
1699
+ const result = settledResult.value;
1700
+ switch (result.kind) {
1701
+ case "removeRecords": {
1702
+ if (result.removedKeys.length > 0) {
1703
+ cleanupActionDriver.cleanupFinalizeRemovedRecords?.(result.action.scope, result.removedKeys);
1704
+ invalidatedScopesByNamespaceId.set(getNamespaceId(result.action.scope), result.action.scope);
1705
+ }
1706
+ if (!result.allSucceeded) continue;
1707
+ const scopePlan = scopePlansByNamespaceId.get(getNamespaceId(result.action.scope));
1708
+ if (scopePlan !== void 0 && scopePlan.persistEntries !== null) persistPlans.push({
1709
+ entries: scopePlan.persistEntries,
1710
+ staticPolicy: scopePlan.persistStaticPolicy,
1711
+ scope: scopePlan.scope
1712
+ });
1713
+ continue;
1714
+ }
1715
+ case "removeStoreDir":
1716
+ if (!result.removed) continue;
1717
+ cleanupActionDriver.cleanupFinalizeRemovedStoreDir?.(result.action.scope, result.action.keys);
1718
+ successfulStoreDeleteSessions.add(result.action.scope.sessionKey);
1719
+ successfulStoreDeleteScopes.add(getNamespaceId(result.action.scope));
1720
+ continue;
1721
+ }
1722
+ }
1723
+ for (const scopePlan of scopePlans) {
1724
+ if (skippedScopeIds.has(getNamespaceId(scopePlan.scope)) || scopePlan.deleteAction !== null || scopePlan.persistEntries === null) continue;
1725
+ persistPlans.push({
1726
+ entries: scopePlan.persistEntries,
1727
+ staticPolicy: scopePlan.persistStaticPolicy,
1728
+ scope: scopePlan.scope
1729
+ });
1730
+ }
1731
+ const sessionDeletePlans = [...successfulStoreDeleteSessions].flatMap((sessionKey) => this.#shouldPlanStartupCleanupSessionDelete(cleanupActionDriver, scopePlans, successfulStoreDeleteScopes, sessionKey) ? [{
1732
+ kind: "removeSessionDir",
1733
+ sessionKey
1734
+ }] : []);
1735
+ const sessionDeletePromise = Promise.allSettled(sessionDeletePlans.map((action) => this.#runStartupCleanupDeleteAction(cleanupActionDriver, action)));
1736
+ const persistPromise = Promise.all(persistPlans.map(async ({ entries, scope, staticPolicy }) => {
1737
+ if (entries !== null) await this.#persistNamespaceIndexUsingDriver(driver, scope, {
1738
+ entries,
1739
+ staticPolicy: staticPolicy !== void 0 ? staticPolicy : await this.#readNamespaceIndexStaticPolicyUsingDriver(driver, scope)
1740
+ });
1741
+ }));
1742
+ const [sessionDeleteResults] = await Promise.all([sessionDeletePromise, persistPromise]);
1743
+ for (const { scope } of persistPlans) invalidatedScopesByNamespaceId.set(getNamespaceId(scope), scope);
1744
+ for (const settledResult of sessionDeleteResults) {
1745
+ if (settledResult.status !== "fulfilled") continue;
1746
+ const result = settledResult.value;
1747
+ if (result.kind !== "removeSessionDir" || !result.removed) continue;
1748
+ cleanupActionDriver.cleanupFinalizeRemovedSessionDir?.(result.action.sessionKey);
1749
+ }
1750
+ return [...invalidatedScopesByNamespaceId.values()];
1751
+ }
1752
+ #intersectPersistEntries(left, right) {
1753
+ if (left === null) return right;
1754
+ if (right === null) return left;
1755
+ const merged = /* @__PURE__ */ new Map();
1756
+ for (const [key, metadata] of left.entries()) if (right.has(key)) merged.set(key, metadata);
1757
+ return merged.size > 0 ? merged : null;
1758
+ }
1759
+ #mergeStartupCleanupScopePlan(left, right) {
1760
+ const mergedPersistEntries = this.#intersectPersistEntries(left.persistEntries, right.persistEntries);
1761
+ const getDeleteKeys = (action) => action !== null && action.kind !== "removeSessionDir" ? action.keys : [];
1762
+ const mergedDeleteKeys = [...new Set([...getDeleteKeys(left.deleteAction), ...getDeleteKeys(right.deleteAction)])].filter((key) => mergedPersistEntries === null || key !== "_i");
1763
+ return {
1764
+ deleteAction: mergedDeleteKeys.length === 0 ? null : this.#createStartupCleanupDeleteAction({
1765
+ keys: mergedDeleteKeys,
1766
+ scope: left.scope
1767
+ }),
1768
+ persistEntries: mergedPersistEntries,
1769
+ persistStaticPolicy: right.persistStaticPolicy !== void 0 ? right.persistStaticPolicy : left.persistStaticPolicy,
1770
+ scope: left.scope
1771
+ };
1772
+ }
1773
+ #planStartupCleanupStoreDeletes(args) {
1774
+ const storeDeletePlans = [];
1775
+ for (const [storeKey, discoveredScopes] of args.discoveredScopesByStore) {
1776
+ if (args.customStoreDeletePlanStoreKeys.has(storeKey)) continue;
1777
+ const removedKeysByScope = [];
1778
+ const discoveredKnownKeys = /* @__PURE__ */ new Set();
1779
+ let shouldDeleteWholeStore = discoveredScopes.length > 0;
1780
+ for (const discoveredScope of discoveredScopes) {
1781
+ const knownRecordKeys = discoveredScope.knownRecordKeys;
1782
+ const scopePlan = args.scopePlansByNamespaceId.get(getNamespaceId(discoveredScope.scope));
1783
+ if (knownRecordKeys === null || scopePlan === void 0 || scopePlan.persistEntries !== null || scopePlan.deleteAction === null) {
1784
+ shouldDeleteWholeStore = false;
1785
+ break;
1786
+ }
1787
+ const plannedDeleteKeys = new Set(scopePlan.deleteAction.kind !== "removeSessionDir" ? scopePlan.deleteAction.keys : []);
1788
+ if (!knownRecordKeys.every((knownKey) => plannedDeleteKeys.has(knownKey))) {
1789
+ shouldDeleteWholeStore = false;
1790
+ break;
1791
+ }
1792
+ for (const knownKey of knownRecordKeys) discoveredKnownKeys.add(knownKey);
1793
+ removedKeysByScope.push({
1794
+ keys: [...plannedDeleteKeys],
1795
+ scope: discoveredScope.scope
1796
+ });
1797
+ }
1798
+ if (!shouldDeleteWholeStore) continue;
1799
+ const plannedDeleteKeys = new Set(removedKeysByScope.flatMap(({ keys }) => keys));
1800
+ if (plannedDeleteKeys.size !== discoveredKnownKeys.size || [...discoveredKnownKeys].some((knownKey) => !plannedDeleteKeys.has(knownKey))) continue;
1801
+ const representativeScope = discoveredScopes[0]?.scope;
1802
+ if (representativeScope === void 0) continue;
1803
+ storeDeletePlans.push({
1804
+ removedKeysByScope,
1805
+ representativeScope
1806
+ });
1807
+ }
1808
+ return storeDeletePlans;
1809
+ }
1810
+ async #planStartupCleanupForScope(args) {
1811
+ const rawKeys = args.knownRecordKeys ?? await args.driver.listKeys(args.scope);
1812
+ const indexState = await readAsyncStorageNamespaceIndexStateUsingDriver(args.driver, args.scope, rawKeys);
1813
+ const payloadKeys = /* @__PURE__ */ new Set();
1814
+ const rawKeysToRemove = [];
1815
+ for (const key of rawKeys) if (key.startsWith("__tsdf_payload__:")) payloadKeys.add(key.slice(17));
1816
+ else if (key !== "_i") rawKeysToRemove.push(key);
1817
+ if (!indexState.valid || indexState.entries === null) {
1818
+ const keysToRemove = rawKeys.filter((key) => key !== "_i" || indexState.exists);
1819
+ return {
1820
+ deleteAction: keysToRemove.length === 0 ? null : this.#createStartupCleanupDeleteAction({
1821
+ keys: keysToRemove,
1822
+ scope: args.scope
1823
+ }),
1824
+ persistEntries: null,
1825
+ persistStaticPolicy: null,
1826
+ scope: args.scope
1827
+ };
1828
+ }
1829
+ const nextEntries = /* @__PURE__ */ new Map();
1830
+ const currentPersistedStaticPolicy = normalizeStaticPolicy(indexState.staticPolicy);
1831
+ const nextPersistedStaticPolicy = normalizePersistedStaticPolicyForScope(args.scope, currentPersistedStaticPolicy);
1832
+ const effectiveStaticPolicy = getEffectiveStaticPolicyForScope(args.scope, nextPersistedStaticPolicy);
1833
+ const payloadRecordKeysToRemove = new Set(rawKeysToRemove);
1834
+ const candidateEntries = [];
1835
+ for (const [key, metadata] of indexState.entries.entries()) {
1836
+ const isProtected = isOfflineProtectedMetadata(metadata.customMetadata) || args.protectedRefs?.has(serializeProtectedRef({
1837
+ ...args.scope,
1838
+ key
1839
+ })) === true;
1840
+ if (!payloadKeys.has(key)) continue;
1841
+ if (!isProtected && !args.skipExpiration && args.now - metadata.lastAccessAt > 12096e5) {
1842
+ payloadRecordKeysToRemove.add(getPayloadRecordKey(key));
1843
+ continue;
1844
+ }
1845
+ nextEntries.set(key, metadata);
1846
+ candidateEntries.push({
1847
+ itemKey: key,
1848
+ lastAccessAt: metadata.lastAccessAt,
1849
+ protected: isProtected,
1850
+ sizeBytes: metadata.sizeBytes ?? 0
1851
+ });
1852
+ }
1853
+ for (const payloadKey of payloadKeys) if (!indexState.entries.has(payloadKey)) payloadRecordKeysToRemove.add(getPayloadRecordKey(payloadKey));
1854
+ if (effectiveStaticPolicy?.maxBytes !== void 0) {
1855
+ const pinnedKeys = new Set(effectiveStaticPolicy.pinnedKeys ?? []);
1856
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
1857
+ const logger = args.driver.logger;
1858
+ const evictedEntries = candidateEntries.length - keptKeys.size;
1859
+ if (logger && evictedEntries > 0) {
1860
+ const scopeKind = args.scope.kind;
1861
+ logPersistentStorageQuotaCleanup({
1862
+ adapter: "async",
1863
+ logger,
1864
+ evictedEntries,
1865
+ keptEntries: keptKeys.size,
1866
+ maxBytes: effectiveStaticPolicy.maxBytes,
1867
+ namespaceKind: scopeKind,
1868
+ phase: "startup-cleanup",
1869
+ quota: scopeKind === "listQuery.item" ? "maxItemBytes" : scopeKind === "listQuery.query" ? "maxQueryBytes" : "maxBytes",
1870
+ storeName: args.scope.storeName,
1871
+ totalEntries: candidateEntries.length,
1872
+ unprotectedBytes
1873
+ });
1874
+ }
1875
+ for (const { itemKey } of candidateEntries) {
1876
+ if (keptKeys.has(itemKey)) continue;
1877
+ payloadRecordKeysToRemove.add(getPayloadRecordKey(itemKey));
1878
+ nextEntries.delete(itemKey);
1879
+ }
1880
+ }
1881
+ const indexChanged = nextEntries.size !== indexState.entries.size || rawKeysToRemove.length > 0 || !deepEqual(currentPersistedStaticPolicy, nextPersistedStaticPolicy);
1882
+ const deleteKeys = [...payloadRecordKeysToRemove];
1883
+ if (indexChanged && nextEntries.size === 0) deleteKeys.push("_i");
1884
+ return {
1885
+ deleteAction: deleteKeys.length === 0 ? null : this.#createStartupCleanupDeleteAction({
1886
+ keys: deleteKeys,
1887
+ scope: args.scope
1888
+ }),
1889
+ persistEntries: indexChanged && nextEntries.size > 0 ? nextEntries : null,
1890
+ persistStaticPolicy: indexChanged && nextEntries.size > 0 ? nextPersistedStaticPolicy : void 0,
1891
+ scope: args.scope
1892
+ };
1893
+ }
1894
+ #createStartupCleanupDeleteAction(args) {
1895
+ return {
1896
+ kind: "removeRecords",
1897
+ keys: [...new Set(args.keys)],
1898
+ scope: args.scope
1899
+ };
1900
+ }
1901
+ async #runStartupCleanupDeleteAction(cleanupActionDriver, action) {
1902
+ switch (action.kind) {
1903
+ case "removeRecords": {
1904
+ const removedKeys = cleanupActionDriver.cleanupRemoveKnownRecords !== void 0 ? await cleanupActionDriver.cleanupRemoveKnownRecords(action.scope, action.keys) : await this.#driverRemoveManyFrom(cleanupActionDriver, action.scope, action.keys).then(() => action.keys);
1905
+ return {
1906
+ action,
1907
+ allSucceeded: removedKeys.length === action.keys.length,
1908
+ kind: "removeRecords",
1909
+ removedKeys
1910
+ };
1911
+ }
1912
+ case "removeStoreDir": return {
1913
+ action,
1914
+ kind: "removeStoreDir",
1915
+ removed: cleanupActionDriver.cleanupRemoveKnownStoreDir === void 0 ? false : await cleanupActionDriver.cleanupRemoveKnownStoreDir(action.scope, action.keys)
1916
+ };
1917
+ case "removeSessionDir": return {
1918
+ action,
1919
+ kind: "removeSessionDir",
1920
+ removed: cleanupActionDriver.cleanupRemoveKnownSessionDir === void 0 ? false : await cleanupActionDriver.cleanupRemoveKnownSessionDir(action.sessionKey)
1921
+ };
1922
+ }
1923
+ }
1924
+ #shouldPlanStartupCleanupSessionDelete(cleanupActionDriver, scopePlans, successfulStoreDeleteScopes, sessionKey) {
1925
+ if (cleanupActionDriver.cleanupRemoveKnownSessionDir === void 0) return false;
1926
+ const sessionScopePlans = scopePlans.filter((plan) => plan.scope.sessionKey === sessionKey);
1927
+ return sessionScopePlans.length > 0 && sessionScopePlans.every((plan) => successfulStoreDeleteScopes.has(getNamespaceId(plan.scope)));
1928
+ }
1929
+ async #listDiscoveredCleanupScopes(driver, sessionKey) {
1930
+ return (await driver.listScopesWithKnownRecordKeys(sessionKey)).filter(({ scope }) => scope.kind !== "__internal.protected");
1931
+ }
1932
+ async #withCleanupDriver(callback) {
1933
+ const maybeCleanupCapableDriver = __LEGIT_CAST__(this.#driver);
1934
+ if (typeof maybeCleanupCapableDriver.withIsolatedCleanupDriver === "function") return maybeCleanupCapableDriver.withIsolatedCleanupDriver(callback);
1935
+ return callback(this.#driver);
1936
+ }
1937
+ };
1938
+ function createAsyncStorageAdapter(driver) {
1939
+ return new ManagedAsyncStorageAdapter(driver);
1940
+ }
1941
+ function serializeProtectedRef(ref) {
1942
+ return serializeProtectedRef$1(ref);
1943
+ }
1944
+ //#endregion
1945
+ export { offlineResolutionRecordSchema as A, getNamespaceId as B, OfflineResolutionConflictParseError as C, isModeEffectivelyActive as D, getIsOfflineModeFromStatus as E, warnIfNavigatorLockUnavailable as F, parsePersistedAsyncNamespaceKind as G, getPersistedNamespaceId as H, createCompactLocalStorageEntry as I, scheduleIdleCleanup as J, serializeProtectedRef$1 as K, parseCompactLocalStorageEntry as L, getSessionProtectedKeysSnapshot as M, setSessionProtectedKeysSnapshot as N, isOfflineModeStatusValue as O, getNavigatorLockManager as P, compareMetadata as R, serializeJsonForStorage as S, defaultOfflineRuntimeConfig as T, normalizeStaticPolicy as U, getPayloadRecordKey as V, parseAsyncStorageRecordKey as W, getDefaultMaxBytesForScope as _, estimateManagedAsyncStorageEntrySizeBytes as a, getSerializedStringSize as b, readAsyncStorageNamespaceIndexStateUsingDriver as c, unregisterAsyncStartupStoreCleanup as d, parseAsyncStorageNamespaceKind as f, resolveTSDFLogger as g, getTSDFDebugTimingMs as h, createAsyncStorageAdapter as i, clearSessionProtectedKeysSnapshot as j, offlineItemEntityRefSchema as k, registerAsyncStartupStoreCleanup as l, emitTSDFDebugLog as m, ASYNC_STORAGE_MAX_AGE_MS as n, getProtectedKeysFromMetadata as o, logPersistentStorageQuotaCleanup as p, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS as q, buildPersistedStaticPolicy as r, mergeManagedAsyncStorageCustomMetadata as s, ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY as t, serializeProtectedRef as u, createShouldIgnoreItemPredicate as v, compactOfflineStatusSnapshotSchema as w, keepEntriesWithinByteBudget as x, createTimedKeySet as y, encodePersistedAsyncNamespaceKind as z };