tsdf 17.0.0-alpha.10 → 17.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as getNavigatorLockManager, C as isModeEffectivelyActive, D as clearSessionProtectedKeysSnapshot, E as offlineResolutionRecordSchema, H as serializeProtectedRef, L as getPayloadRecordKey, M as createCompactLocalStorageEntry, N as parseCompactLocalStorageEntry, O as getSessionProtectedKeysSnapshot, S as getIsOfflineModeFromStatus, T as offlineItemEntityRefSchema, U as scheduleIdleCleanup, V as parsePersistedAsyncNamespaceKind, _ as keepEntriesWithinByteBudget, a as estimateManagedAsyncStorageEntrySizeBytes, b as compactOfflineStatusSnapshotSchema, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as getSerializedStringSize, h as createTimedKeySet, j as warnIfNavigatorLockUnavailable, k as setSessionProtectedKeysSnapshot, l as registerAsyncStartupStoreCleanup, m as createShouldIgnoreItemPredicate, o as getProtectedKeysFromMetadata, p as getDefaultMaxBytesForScope, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as serializeJsonForStorage, w as isOfflineModeStatusValue, x as defaultOfflineRuntimeConfig, y as OfflineResolutionConflictParseError } from "./asyncStorageAdapter-BZSj1ZO5.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-BO_uDxe4.js";
1
+ import { A as getNavigatorLockManager, C as isModeEffectivelyActive, D as clearSessionProtectedKeysSnapshot, E as offlineResolutionRecordSchema, H as serializeProtectedRef, L as getPayloadRecordKey, M as createCompactLocalStorageEntry, N as parseCompactLocalStorageEntry, O as getSessionProtectedKeysSnapshot, S as getIsOfflineModeFromStatus, T as offlineItemEntityRefSchema, U as scheduleIdleCleanup, V as parsePersistedAsyncNamespaceKind, _ as keepEntriesWithinByteBudget, a as estimateManagedAsyncStorageEntrySizeBytes, b as compactOfflineStatusSnapshotSchema, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as getSerializedStringSize, h as createTimedKeySet, j as warnIfNavigatorLockUnavailable, k as setSessionProtectedKeysSnapshot, l as registerAsyncStartupStoreCleanup, m as createShouldIgnoreItemPredicate, o as getProtectedKeysFromMetadata, p as getDefaultMaxBytesForScope, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as serializeJsonForStorage, w as isOfflineModeStatusValue, x as defaultOfflineRuntimeConfig, y as OfflineResolutionConflictParseError } from "./asyncStorageAdapter-CSzvgl3s.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-3c1zSDZi.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
5
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
@@ -66,7 +66,7 @@ function createLruCacheRuntime() {
66
66
  /** @internal */
67
67
  const CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS = 3600 * 1e3;
68
68
  /** @internal */
69
- function createIdleThrottledScheduler({ throttleMs, run }) {
69
+ function createIdleThrottledScheduler(throttleMs, run) {
70
70
  let pendingTimer = null;
71
71
  let cancelIdleRun = null;
72
72
  let isScheduled = false;
@@ -1312,18 +1312,18 @@ function ensureAsyncNamespaceKind(entryPrefix) {
1312
1312
  * forced manifest keys are coalesced and a global sweep request wins over
1313
1313
  * targeted maintenance because it already covers the full cleanup pass.
1314
1314
  */
1315
- function scheduleLocalStorageMaintenance(options = {}) {
1316
- if (options.forceManifestKeys === void 0) {
1315
+ function scheduleLocalStorageMaintenance(forceManifestKeys) {
1316
+ if (forceManifestKeys === void 0) {
1317
1317
  localStorageGlobalMaintenanceRequested = true;
1318
1318
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1319
- } else if (!localStorageGlobalMaintenanceRequested) for (const manifestKey of options.forceManifestKeys) scheduledLocalStorageMaintenanceManifestKeys.add(manifestKey);
1319
+ } else if (!localStorageGlobalMaintenanceRequested) for (const manifestKey of forceManifestKeys) scheduledLocalStorageMaintenanceManifestKeys.add(manifestKey);
1320
1320
  if (cancelScheduledLocalStorageMaintenance !== null) return;
1321
1321
  cancelScheduledLocalStorageMaintenance = scheduleIdleCleanup(() => {
1322
1322
  cancelScheduledLocalStorageMaintenance = null;
1323
- const forceManifestKeys = localStorageGlobalMaintenanceRequested ? void 0 : [...scheduledLocalStorageMaintenanceManifestKeys];
1323
+ const maintenanceManifestKeys = localStorageGlobalMaintenanceRequested ? void 0 : [...scheduledLocalStorageMaintenanceManifestKeys];
1324
1324
  localStorageGlobalMaintenanceRequested = false;
1325
1325
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1326
- localPersistentStorage.runMaintenance(forceManifestKeys);
1326
+ localPersistentStorage.runMaintenance(maintenanceManifestKeys);
1327
1327
  });
1328
1328
  }
1329
1329
  function preserveOfflineProtectionFlag(sessionKey, storageKey, nextMeta, currentMeta) {
@@ -2175,16 +2175,16 @@ function getStorageKeyForStore(sessionKey, storeName) {
2175
2175
  function getStoragePrefixForStoreNamespace(sessionKey, storeName, entryPrefix) {
2176
2176
  return `${getStorageKey(sessionKey, storeName)}.${entryPrefix}.`;
2177
2177
  }
2178
- function createProtectedStorageKey(args) {
2179
- if ((args.backend ?? "localStorage") === "localStorage") {
2180
- if (args.kind === "document" && args.key === "d") return getStorageKeyForStore(args.sessionKey, args.storeName);
2181
- return `${getStoragePrefixForStoreNamespace(args.sessionKey, args.storeName, args.kind)}${args.key}`;
2178
+ function createProtectedStorageKey(sessionKey, storeName, kind, key, backend = "localStorage") {
2179
+ if (backend === "localStorage") {
2180
+ if (kind === "document" && key === "d") return getStorageKeyForStore(sessionKey, storeName);
2181
+ return `${getStoragePrefixForStoreNamespace(sessionKey, storeName, kind)}${key}`;
2182
2182
  }
2183
2183
  return serializeProtectedRef({
2184
- sessionKey: args.sessionKey,
2185
- storeName: args.storeName,
2186
- kind: ensureAsyncNamespaceKind(args.kind),
2187
- key: args.key
2184
+ sessionKey,
2185
+ storeName,
2186
+ kind: ensureAsyncNamespaceKind(kind),
2187
+ key
2188
2188
  });
2189
2189
  }
2190
2190
  function readManifestPayloadMeta(meta) {
@@ -2205,7 +2205,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2205
2205
  }
2206
2206
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2207
2207
  async function clearAllSessionStorage(sessionKey) {
2208
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-DbyKyARM.js");
2208
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-W8bChTBu.js");
2209
2209
  await Promise.all([
2210
2210
  clearSessionStorage(sessionKey, "local-sync"),
2211
2211
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -2295,10 +2295,7 @@ function toCollectionItemState(persisted, dataSchema, shouldIgnoreItem) {
2295
2295
  function setupCollectionPersistence(config, options = {}) {
2296
2296
  assertValidPersistentStoreName(config.storeName);
2297
2297
  const version = config.version;
2298
- const defaultMaxBytes = getDefaultMaxBytesForScope({
2299
- adapter: config.adapter,
2300
- scopeKind: "collection.item"
2301
- });
2298
+ const defaultMaxBytes = getDefaultMaxBytesForScope(config.adapter, "collection.item");
2302
2299
  const maxBytes = config.maxBytes ?? defaultMaxBytes;
2303
2300
  const resolveItemKey = options.getItemKey ?? ((payload) => getCompositeKey(payload));
2304
2301
  const pinnedItemKeys = new Set((config.pinnedItems ?? []).map((payload) => resolveItemKey(payload)));
@@ -2349,18 +2346,8 @@ function setupCollectionPersistence(config, options = {}) {
2349
2346
  const asyncNamespaceScope = getAsyncNamespaceScope();
2350
2347
  if (asyncNamespaceScope === null) return JSON.stringify(args.value).length;
2351
2348
  const serializedValue = serializeJsonForStorage(args.value.data);
2352
- return estimateManagedAsyncStorageEntrySizeBytes({
2353
- customMetadata: mergeManagedAsyncStorageCustomMetadata({
2354
- currentCustomMetadata: args.currentCustomMetadata,
2355
- key: args.itemKey,
2356
- nextCustomMetadata: { p: args.value.payload },
2357
- protectedKeysSnapshotSet: args.protectedKeysSnapshotSet,
2358
- scope: asyncNamespaceScope
2359
- }),
2360
- lastAccessAt: args.lastAccessAt,
2361
- serializedValue: serializedValue.rawValue,
2362
- version: version ?? 1
2363
- });
2349
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, { p: args.value.payload }, args.protectedKeysSnapshotSet, asyncNamespaceScope, args.itemKey);
2350
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
2364
2351
  }
2365
2352
  let storeRef = null;
2366
2353
  let unsubscribe = null;
@@ -2434,15 +2421,7 @@ function setupCollectionPersistence(config, options = {}) {
2434
2421
  protected: protectedItemKeys.has(itemKey),
2435
2422
  sizeBytes: rememberPersistedMetadataSize(itemKey, metadata.sizeBytes)
2436
2423
  }));
2437
- const keptKeys = keepEntriesWithinByteBudget({
2438
- entries: candidateEntries,
2439
- getKey: (entry) => entry.itemKey,
2440
- getLastAccessAt: (entry) => entry.lastAccessAt,
2441
- getSizeBytes: (entry) => entry.sizeBytes,
2442
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2443
- isProtected: (entry) => entry.protected,
2444
- maxBytes: effectiveStaticPolicy.maxBytes
2445
- });
2424
+ const keptKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
2446
2425
  for (const { itemKey } of candidateEntries) {
2447
2426
  if (keptKeys.has(itemKey)) continue;
2448
2427
  deleteKeys.add(getPayloadRecordKey(itemKey));
@@ -2707,15 +2686,7 @@ function setupCollectionPersistence(config, options = {}) {
2707
2686
  await Promise.all(ignoredEntries.map(({ itemKey }) => namespace.remove(itemKey)));
2708
2687
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2709
2688
  }
2710
- const keptKeys = keepEntriesWithinByteBudget({
2711
- entries: filteredEntries,
2712
- getKey: (entry) => entry.itemKey,
2713
- getLastAccessAt: (entry) => entry.lastAccessAt,
2714
- getSizeBytes: (entry) => entry.sizeBytes,
2715
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2716
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
2717
- maxBytes
2718
- });
2689
+ const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2719
2690
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2720
2691
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2721
2692
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2743,15 +2714,7 @@ function setupCollectionPersistence(config, options = {}) {
2743
2714
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2744
2715
  }
2745
2716
  const filteredEntries = validEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
2746
- const keptKeys = keepEntriesWithinByteBudget({
2747
- entries: filteredEntries,
2748
- getKey: (entry) => entry.itemKey,
2749
- getLastAccessAt: (entry) => entry.lastAccessAt,
2750
- getSizeBytes: (entry) => entry.sizeBytes,
2751
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2752
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
2753
- maxBytes
2754
- });
2717
+ const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2755
2718
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2756
2719
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2757
2720
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2874,15 +2837,7 @@ function setupCollectionPersistence(config, options = {}) {
2874
2837
  if (metadataByKey.has(entry.itemKey)) pendingRemoves.add(entry.itemKey);
2875
2838
  }
2876
2839
  const remainingCandidates = candidateEntries.filter(({ itemKey }) => !pendingRemoves.has(itemKey));
2877
- const keptKeys = keepEntriesWithinByteBudget({
2878
- entries: remainingCandidates,
2879
- getKey: (entry) => entry.itemKey,
2880
- getLastAccessAt: (entry) => entry.lastAccessAt,
2881
- getSizeBytes: (entry) => entry.sizeBytes,
2882
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2883
- isProtected: (entry) => entry.protected,
2884
- maxBytes
2885
- });
2840
+ const keptKeys = keepEntriesWithinByteBudget(remainingCandidates, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, maxBytes);
2886
2841
  if (keptKeys.size !== remainingCandidates.length) {
2887
2842
  for (const { itemKey } of remainingCandidates) {
2888
2843
  if (keptKeys.has(itemKey)) continue;
@@ -2915,7 +2870,7 @@ function setupCollectionPersistence(config, options = {}) {
2915
2870
  } else knownPersistedKeys = null;
2916
2871
  if (localStorageAdapter !== null && maintenanceManifestKey !== null) {
2917
2872
  const nextKnownPersistedBytes = getKnownPersistedBytes(knownPersistedKeys);
2918
- if (hasIgnoreItemFilter || nextKnownPersistedBytes === null || nextKnownPersistedBytes > maxBytes) scheduleLocalStorageMaintenance({ forceManifestKeys: [maintenanceManifestKey] });
2873
+ if (hasIgnoreItemFilter || nextKnownPersistedBytes === null || nextKnownPersistedBytes > maxBytes) scheduleLocalStorageMaintenance([maintenanceManifestKey]);
2919
2874
  return;
2920
2875
  }
2921
2876
  const sessionKey = config.getSessionKey();
@@ -2998,7 +2953,7 @@ function setupCollectionPersistence(config, options = {}) {
2998
2953
  }
2999
2954
  //#endregion
3000
2955
  //#region src/persistentStorage/offline/mutationRuntime.ts
3001
- async function runHybridOfflineMutation({ controller, offline, upload, directMutation }) {
2956
+ async function runHybridOfflineMutation(controller, offline, upload, directMutation) {
3002
2957
  if (!offline || !controller) throw new Error("runHybridOfflineMutation requires an offline mutation and controller");
3003
2958
  const prepared = await controller.prepareForMutation({
3004
2959
  offline,
@@ -3029,14 +2984,14 @@ function isOfflineResolutionRecordForStore(resolution, operations) {
3029
2984
  }
3030
2985
  //#endregion
3031
2986
  //#region src/persistentStorage/offline/overlayStoreLifecycle.ts
3032
- function rebindOfflineOverlayEntries(args) {
3033
- if (args.itemKeyRewrites.length === 0) return;
3034
- args.overlayStore.produceState((draft) => {
3035
- for (const { previousItemKey, nextItemKey } of args.itemKeyRewrites) {
2987
+ function rebindOfflineOverlayEntries(overlayStore, itemKeyRewrites, createReboundOverlay) {
2988
+ if (itemKeyRewrites.length === 0) return;
2989
+ overlayStore.produceState((draft) => {
2990
+ for (const { previousItemKey, nextItemKey } of itemKeyRewrites) {
3036
2991
  if (previousItemKey === nextItemKey) continue;
3037
2992
  const existingOverlay = draft[previousItemKey];
3038
2993
  if (existingOverlay === void 0) continue;
3039
- if (draft[nextItemKey] === void 0) draft[nextItemKey] = args.createReboundOverlay({
2994
+ if (draft[nextItemKey] === void 0) draft[nextItemKey] = createReboundOverlay({
3040
2995
  existingOverlay,
3041
2996
  nextItemKey
3042
2997
  });
@@ -3045,28 +3000,27 @@ function rebindOfflineOverlayEntries(args) {
3045
3000
  }
3046
3001
  });
3047
3002
  }
3048
- function captureOfflineOverlayEntries(args) {
3049
- const targetItemKeys = [...new Set(args.itemKeys)];
3003
+ function captureOfflineOverlayEntries(overlayStore, itemKeys, createOverlay) {
3004
+ const targetItemKeys = [...new Set(itemKeys)];
3050
3005
  if (targetItemKeys.length === 0) return;
3051
- args.overlayStore.produceState((draft) => {
3006
+ overlayStore.produceState((draft) => {
3052
3007
  for (const itemKey of targetItemKeys) {
3053
3008
  const existingOverlay = draft[itemKey];
3054
3009
  if (existingOverlay?.keepVisibleWhileResolutionRequired) {
3055
3010
  existingOverlay.keepVisibleWhileResolutionRequired = false;
3056
3011
  continue;
3057
3012
  }
3058
- draft[itemKey] = args.createOverlay(itemKey);
3013
+ draft[itemKey] = createOverlay(itemKey);
3059
3014
  }
3060
3015
  });
3061
3016
  }
3062
3017
  //#endregion
3063
3018
  //#region src/utils/browserTabsPriority.ts
3064
- const DEFAULT_HEARTBEAT_MS = 5e3;
3065
- const DEFAULT_PRESENCE_TTL_MS = 15e3;
3066
3019
  const DEFAULT_FETCH_LEASE_MS = 1e4;
3020
+ const DEFAULT_BACKGROUND_COALESCING_DELAY_MS$1 = 3e3;
3067
3021
  const COALESCING_WINDOW_STEP_MS = 1e3;
3068
3022
  /** @internal */
3069
- function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getWindowIsFocused, onWindowFocusChange, publishStatus, timings, onLeaderChange }) {
3023
+ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWindowIsFocused, onWindowFocusChange, publishStatus, timings, onLeaderChange) {
3070
3024
  const knownTabs = /* @__PURE__ */ new Map();
3071
3025
  const remoteFetchLeases = /* @__PURE__ */ new Map();
3072
3026
  let lastLeaderTabId;
@@ -3076,25 +3030,18 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3076
3030
  lastFocusedAt: getWindowIsFocused() ? Date.now() : 0,
3077
3031
  lastPresenceAt: Date.now()
3078
3032
  };
3079
- const heartbeatMs = timings?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
3080
- const presenceTtlMs = timings?.presenceTtlMs ?? DEFAULT_PRESENCE_TTL_MS;
3081
3033
  function resolveFetchLeaseMs(lastFetchDuration) {
3082
3034
  const configuredLeaseMs = timings?.fetchLeaseMs;
3083
3035
  if (typeof configuredLeaseMs === "function") return Math.max(0, configuredLeaseMs(lastFetchDuration));
3084
3036
  if (typeof configuredLeaseMs === "number") return Math.max(0, configuredLeaseMs);
3085
3037
  return Math.max(lastFetchDuration * 3, DEFAULT_FETCH_LEASE_MS);
3086
3038
  }
3087
- function pruneStaleTabs() {
3088
- const now = Date.now();
3089
- for (const [remoteTabId, presence] of knownTabs) if (now - presence.lastPresenceAt > presenceTtlMs) knownTabs.delete(remoteTabId);
3090
- }
3091
3039
  function pruneExpiredRemoteLeases() {
3092
3040
  const now = Date.now();
3093
3041
  for (const [targetKey, lease] of remoteFetchLeases) if (lease.expiresAt <= now) remoteFetchLeases.delete(targetKey);
3094
3042
  }
3095
3043
  function getRankedLiveTabs() {
3096
3044
  if (!getIsEnabled()) return [localPresence];
3097
- pruneStaleTabs();
3098
3045
  return [localPresence, ...knownTabs.values()].sort((a, b) => {
3099
3046
  if (a.isFocused !== b.isFocused) return a.isFocused ? -1 : 1;
3100
3047
  if (a.lastFocusedAt !== b.lastFocusedAt) return b.lastFocusedAt - a.lastFocusedAt;
@@ -3166,7 +3113,7 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3166
3113
  if (baseCoalescingWindowMs <= 0) return baseCoalescingWindowMs;
3167
3114
  const coalescingRank = getCoalescingRank();
3168
3115
  if (coalescingRank <= 0) return baseCoalescingWindowMs;
3169
- return baseCoalescingWindowMs + coalescingRank * COALESCING_WINDOW_STEP_MS;
3116
+ return baseCoalescingWindowMs + Math.max(0, timings?.backgroundCoalescingDelayMs ?? DEFAULT_BACKGROUND_COALESCING_DELAY_MS$1) + (coalescingRank - 1) * COALESCING_WINDOW_STEP_MS;
3170
3117
  }
3171
3118
  function onTabStatusMessage(remoteTabId, message) {
3172
3119
  if (!getIsEnabled()) return;
@@ -3211,13 +3158,8 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3211
3158
  remoteFetchLeases.clear();
3212
3159
  }
3213
3160
  let cleanupFocusListeners;
3214
- let heartbeatInterval;
3215
- const shouldRunHeartbeat = transportEnabled && heartbeatMs > 0 && true;
3216
3161
  if (transportEnabled) {
3217
3162
  publishLocalStatus();
3218
- if (shouldRunHeartbeat) heartbeatInterval = setInterval(() => {
3219
- publishLocalStatus();
3220
- }, heartbeatMs);
3221
3163
  if (onWindowFocusChange) cleanupFocusListeners = onWindowFocusChange(() => {
3222
3164
  noteLocalFocusState();
3223
3165
  });
@@ -3246,7 +3188,6 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3246
3188
  reset,
3247
3189
  close() {
3248
3190
  cleanupFocusListeners?.();
3249
- if (heartbeatInterval) clearInterval(heartbeatInterval);
3250
3191
  reset();
3251
3192
  knownTabs.clear();
3252
3193
  }
@@ -3290,11 +3231,10 @@ function getDefaultTransportFactory() {
3290
3231
  };
3291
3232
  }
3292
3233
  /** @internal */
3293
- function createBrowserTabsCoordinator(options) {
3294
- const { storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory = getDefaultTransportFactory() } = options;
3295
- const debugLogger = import.meta.env.DEV ? options.debugLogger : void 0;
3234
+ function createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, tabId = createBrowserTabsTabId()) {
3235
+ const resolvedTransportFactory = transportFactory ?? getDefaultTransportFactory();
3236
+ const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3296
3237
  const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3297
- const tabId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
3298
3238
  let seq = 0;
3299
3239
  const lastSeenSeqByTab = /* @__PURE__ */ new Map();
3300
3240
  let currentSessionKey;
@@ -3330,7 +3270,7 @@ function createBrowserTabsCoordinator(options) {
3330
3270
  }
3331
3271
  return nextSessionKey;
3332
3272
  }
3333
- const transport = transportFactory({
3273
+ const transport = resolvedTransportFactory({
3334
3274
  channelName,
3335
3275
  onMessage(rawMessage) {
3336
3276
  const localSessionKey = refreshSessionKey();
@@ -3434,57 +3374,58 @@ function createBrowserTabsCoordinator(options) {
3434
3374
  };
3435
3375
  }
3436
3376
  /** @internal */
3437
- function createBrowserTabsCoordinatorWithPriority(options) {
3438
- const { storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, getWindowIsFocused, onWindowFocusChange, priorityTimings } = options;
3439
- const debugLogger = import.meta.env.DEV ? options.debugLogger : void 0;
3377
+ function createBrowserTabsCoordinatorWithPriority(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, getWindowIsFocused, onWindowFocusChange, priorityTimings, tabId) {
3378
+ const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3440
3379
  const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3441
3380
  const priorityRef = { current: null };
3442
- const coordinator = createBrowserTabsCoordinator({
3443
- storeType,
3444
- storeKey,
3445
- getSessionKey,
3446
- onMessage,
3447
- onSessionChange(sessionKey, previousSessionKey) {
3448
- priorityRef.current?.reset();
3449
- if (sessionKey !== false && coordinator.enabled) priorityRef.current?.publishLocalStatus();
3450
- onSessionChange?.(sessionKey, previousSessionKey);
3451
- },
3452
- transportFactory,
3453
- ...import.meta.env.DEV ? { debugLogger: options.debugLogger } : void 0
3454
- });
3455
- const priority = createBrowserTabsPriority({
3456
- transportEnabled: coordinator.enabled,
3457
- getIsEnabled: () => coordinator.isSessionActive(),
3458
- tabId: coordinator.tabId,
3459
- getWindowIsFocused,
3460
- onWindowFocusChange,
3461
- publishStatus: (status) => {
3462
- coordinator.publish(__LEGIT_CAST__(status));
3463
- },
3464
- timings: priorityTimings,
3465
- ...import.meta.env.DEV ? { onLeaderChange(details) {
3466
- if (!debugLogger) return;
3467
- emitTSDFDebugLog(debugLogger, {
3468
- area: "browser-tabs",
3469
- level: "log",
3470
- message: "browser-tab sync leader changed",
3471
- operation: "leader-change",
3472
- details: {
3473
- channelName,
3474
- storeKey,
3475
- storeType,
3476
- tabId: details.localTabId,
3477
- ...details
3478
- }
3479
- });
3480
- } } : void 0
3481
- });
3381
+ const coordinator = createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, (sessionKey, previousSessionKey) => {
3382
+ priorityRef.current?.reset();
3383
+ if (sessionKey !== false && coordinator.enabled) priorityRef.current?.publishLocalStatus();
3384
+ onSessionChange?.(sessionKey, previousSessionKey);
3385
+ }, transportFactory, debugLoggerInput, tabId);
3386
+ const priority = createBrowserTabsPriority(coordinator.enabled, () => coordinator.isSessionActive(), coordinator.tabId, getWindowIsFocused, onWindowFocusChange, (status) => {
3387
+ coordinator.publish(__LEGIT_CAST__(status));
3388
+ }, priorityTimings, import.meta.env.DEV ? (details) => {
3389
+ if (!debugLogger) return;
3390
+ emitTSDFDebugLog(debugLogger, {
3391
+ area: "browser-tabs",
3392
+ level: "log",
3393
+ message: "browser-tab sync leader changed",
3394
+ operation: "leader-change",
3395
+ details: {
3396
+ channelName,
3397
+ storeKey,
3398
+ storeType,
3399
+ tabId: details.localTabId,
3400
+ ...details
3401
+ }
3402
+ });
3403
+ } : void 0);
3482
3404
  priorityRef.current = priority;
3483
3405
  return {
3484
3406
  coordinator,
3485
3407
  priority
3486
3408
  };
3487
3409
  }
3410
+ /** @internal */
3411
+ function createBrowserTabsPresencePriority(options) {
3412
+ const priorityRef = { current: null };
3413
+ const { coordinator, priority } = createBrowserTabsCoordinatorWithPriority("presence", "manager", options.getSessionKey, (message) => {
3414
+ priorityRef.current?.onTabStatusMessage(message.tabId, message);
3415
+ }, void 0, options.transportFactory, import.meta.env.DEV ? options.debugLogger : void 0, options.getWindowIsFocused, options.onWindowFocusChange, options.priorityTimings);
3416
+ priorityRef.current = priority;
3417
+ return {
3418
+ priority,
3419
+ tabId: coordinator.tabId,
3420
+ close() {
3421
+ coordinator.close();
3422
+ priority.close();
3423
+ }
3424
+ };
3425
+ }
3426
+ function createBrowserTabsTabId() {
3427
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
3428
+ }
3488
3429
  function toBrowserTabsSyncVersion(meta, consistency) {
3489
3430
  return {
3490
3431
  tabId: meta.tabId,
@@ -3520,25 +3461,25 @@ function stripStoredUploadFile(record) {
3520
3461
  const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, ...upload } = record;
3521
3462
  return upload;
3522
3463
  }
3523
- function createStoredUploadRecord(args) {
3524
- const file = normalizeUploadFile(args.file, args.id);
3464
+ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt) {
3465
+ const file = normalizeUploadFile(fileInput, id);
3525
3466
  const now = Date.now();
3526
- const createdAt = args.createdAt ?? now;
3467
+ const createdAt = createdAtInput ?? now;
3527
3468
  const updatedAt = now;
3528
3469
  return {
3529
- id: args.id,
3530
- sessionKey: args.sessionKey,
3531
- source: args.source,
3532
- state: args.state ?? "pending",
3470
+ id,
3471
+ sessionKey,
3472
+ source,
3473
+ state: state ?? "pending",
3533
3474
  fileName: file.name,
3534
3475
  mimeType: file.type,
3535
3476
  sizeBytes: file.size,
3536
3477
  createdAt,
3537
3478
  updatedAt,
3538
- ...args.resolvedRef !== void 0 ? { resolvedRef: args.resolvedRef } : {},
3539
- ...args.progress !== void 0 ? { progress: args.progress } : {},
3540
- ...args.lastError !== void 0 ? { lastError: args.lastError } : {},
3541
- ...args.lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt: args.lastOnlineSessionStartedAt } : {},
3479
+ ...resolvedRef !== void 0 ? { resolvedRef } : {},
3480
+ ...progress !== void 0 ? { progress } : {},
3481
+ ...lastError !== void 0 ? { lastError } : {},
3482
+ ...lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt } : {},
3542
3483
  file,
3543
3484
  lastModified: file.lastModified
3544
3485
  };
@@ -3853,21 +3794,14 @@ var SessionOfflineCoordinator = class {
3853
3794
  })
3854
3795
  });
3855
3796
  this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
3856
- this.#browserTabs = createBrowserTabsCoordinatorWithPriority({
3857
- storeType: "offline",
3858
- storeKey: `session:${sessionKey}`,
3859
- getSessionKey: () => this.sessionKey,
3860
- getWindowIsFocused: () => !isWindowAvailable() || !document.hidden,
3861
- onMessage: (message) => {
3862
- if (message.kind === "tab-status") {
3863
- this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
3864
- this.#refreshLeadership();
3865
- return;
3866
- }
3867
- this.#applyRemoteSnapshot(message);
3868
- },
3869
- ...import.meta.env.DEV ? { debugLogger } : void 0
3870
- });
3797
+ this.#browserTabs = createBrowserTabsCoordinatorWithPriority("offline", `session:${sessionKey}`, () => this.sessionKey, (message) => {
3798
+ if (message.kind === "tab-status") {
3799
+ this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
3800
+ this.#refreshLeadership();
3801
+ return;
3802
+ }
3803
+ this.#applyRemoteSnapshot(message);
3804
+ }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, void 0, void 0);
3871
3805
  this.#refreshLeadership();
3872
3806
  if (shouldBootstrapFromStorage) this.hydrate();
3873
3807
  if (this.#hasCanonicalConfig) this.#refreshNetworkConfig();
@@ -4029,14 +3963,7 @@ var SessionOfflineCoordinator = class {
4029
3963
  async saveUpload(args) {
4030
3964
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
4031
3965
  const existing = this.#uploads.get(args.id);
4032
- const nextRecord = createStoredUploadRecord({
4033
- id: args.id,
4034
- sessionKey: this.sessionKey,
4035
- file: args.file,
4036
- source: args.source ?? "manual",
4037
- createdAt: existing?.createdAt,
4038
- lastOnlineSessionStartedAt: this.#getCurrentUploadOnlineSessionStartedAt()
4039
- });
3966
+ const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt());
4040
3967
  await this.#saveUploadRecord(nextRecord);
4041
3968
  }
4042
3969
  async replaceUpload(args) {
@@ -5173,10 +5100,9 @@ function initializeOfflineStoreController(controller) {
5173
5100
  controller.ensureReplayScheduled();
5174
5101
  });
5175
5102
  }
5176
- function createOfflineStoreController(options) {
5177
- const { storeName, storeType, getSessionKey, onPersistentStorageError, adapter, storeAdapter, offlineSession, operations } = options;
5103
+ function createOfflineStoreController(storeName, storeType, getSessionKey, onPersistentStorageError, debugLogger, adapter, storeAdapter, offlineSession, operations) {
5178
5104
  const sessionConfig = offlineSession.getConfig();
5179
- const activeDebugLogger = import.meta.env.DEV ? options.debugLogger : void 0;
5105
+ const activeDebugLogger = import.meta.env.DEV ? debugLogger : void 0;
5180
5106
  const replayQueue = createAsyncQueue({
5181
5107
  concurrency: 1,
5182
5108
  autoStart: true
@@ -7579,8 +7505,9 @@ var RequestScheduler = class {
7579
7505
  };
7580
7506
  //#endregion
7581
7507
  //#region src/storeManager.ts
7582
- const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 5;
7583
- const DEFAULT_BASE_COALESCING_WINDOW_MS = 10;
7508
+ const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 2400 * 1e3;
7509
+ const DEFAULT_BASE_COALESCING_WINDOW_MS = 16;
7510
+ const DEFAULT_BACKGROUND_COALESCING_DELAY_MS = 3e3;
7584
7511
  function defaultDynamicRealtimeThrottleMs({ windowIsNotFocused }) {
7585
7512
  return windowIsNotFocused ? 1e3 : 100;
7586
7513
  }
@@ -7663,6 +7590,7 @@ function createStoreManager(options) {
7663
7590
  useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
7664
7591
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
7665
7592
  const registry = {
7593
+ browserTabsPresence: void 0,
7666
7594
  nextStoreRegistrationId: 0,
7667
7595
  stores: /* @__PURE__ */ new Map()
7668
7596
  };
@@ -7674,6 +7602,7 @@ function createStoreManager(options) {
7674
7602
  storeDefaults: Object.freeze({
7675
7603
  lowPriorityThrottleMs: options.lowPriorityThrottleMs ?? DEFAULT_LOW_PRIORITY_THROTTLE_MS,
7676
7604
  baseCoalescingWindowMs: options.baseCoalescingWindowMs ?? DEFAULT_BASE_COALESCING_WINDOW_MS,
7605
+ backgroundCoalescingDelayMs: options.backgroundCoalescingDelayMs ?? DEFAULT_BACKGROUND_COALESCING_DELAY_MS,
7677
7606
  dynamicRealtimeThrottleMs: options.dynamicRealtimeThrottleMs ?? defaultDynamicRealtimeThrottleMs,
7678
7607
  blockWindowClose: options.blockWindowClose ?? null,
7679
7608
  revalidateOnWindowFocus: options.revalidateOnWindowFocus
@@ -7696,9 +7625,13 @@ function createStoreManager(options) {
7696
7625
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
7697
7626
  return storeManager;
7698
7627
  }
7699
- function registerStoreWithManager(storeManager, store) {
7628
+ function getRegistryOrThrow(storeManager) {
7700
7629
  const registry = storeManagerRegistry.get(storeManager);
7701
7630
  if (!registry) throw new Error("[tsdf] storeManager must be created with createStoreManager(...)");
7631
+ return registry;
7632
+ }
7633
+ function registerStoreWithManager(storeManager, store) {
7634
+ const registry = getRegistryOrThrow(storeManager);
7702
7635
  let hasDuplicateId = false;
7703
7636
  for (const registeredStore of registry.stores.values()) if (registeredStore.id === store.id) {
7704
7637
  hasDuplicateId = true;
@@ -7710,23 +7643,45 @@ function registerStoreWithManager(storeManager, store) {
7710
7643
  registry.stores.set(registrationId, store);
7711
7644
  return () => {
7712
7645
  registry.stores.delete(registrationId);
7646
+ if (registry.stores.size === 0) {
7647
+ registry.browserTabsPresence?.close();
7648
+ registry.browserTabsPresence = void 0;
7649
+ }
7713
7650
  };
7714
7651
  }
7715
- function resolveStoreManagerOfflineSession(args) {
7716
- const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(args.storeManager));
7717
- if (!args.usesOfflineStorage) return null;
7718
- if (!offlineSession) throw new Error(`[tsdf] Store "${args.storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
7652
+ function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
7653
+ const registry = getRegistryOrThrow(storeManager);
7654
+ const presence = registry.browserTabsPresence ??= createBrowserTabsPresencePriority({
7655
+ getSessionKey: storeManager.getSessionKey,
7656
+ getWindowIsFocused: options.getWindowIsFocused,
7657
+ onWindowFocusChange: options.onWindowFocusChange,
7658
+ transportFactory: options.transportFactory,
7659
+ ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
7660
+ priorityTimings: {
7661
+ backgroundCoalescingDelayMs: storeManager.storeDefaults.backgroundCoalescingDelayMs,
7662
+ ...options.priorityTimings
7663
+ }
7664
+ });
7665
+ return {
7666
+ priority: presence.priority,
7667
+ tabId: presence.tabId
7668
+ };
7669
+ }
7670
+ function resolveStoreManagerOfflineSession(storeManager, storeName, usesOfflineStorage) {
7671
+ const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(storeManager));
7672
+ if (!usesOfflineStorage) return null;
7673
+ if (!offlineSession) throw new Error(`[tsdf] Store "${storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
7719
7674
  return offlineSession;
7720
7675
  }
7721
- function validateStoreManagerSessionConsistency(args) {
7722
- const sessionKey = args.getSessionKey();
7723
- const offlineSessionKey = args.offlineSession.getSessionKey();
7724
- if (sessionKey !== offlineSessionKey) throw new Error(`[tsdf] Store "${args.storeName}" is attached to offline session "${offlineSessionKey}" but storeManager.getSessionKey() returned "${sessionKey}"`);
7676
+ function validateStoreManagerSessionConsistency(storeName, offlineSession, getSessionKey) {
7677
+ const sessionKey = getSessionKey();
7678
+ const offlineSessionKey = offlineSession.getSessionKey();
7679
+ if (sessionKey !== offlineSessionKey) throw new Error(`[tsdf] Store "${storeName}" is attached to offline session "${offlineSessionKey}" but storeManager.getSessionKey() returned "${sessionKey}"`);
7725
7680
  return sessionKey;
7726
7681
  }
7727
7682
  //#endregion
7728
7683
  //#region src/utils/performMutation.ts
7729
- async function performMutationWithLifecycle({ startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose }) {
7684
+ async function performMutationWithLifecycle(startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose) {
7730
7685
  const endMutation = startMutation();
7731
7686
  if (optimisticUpdate?.() === false) {
7732
7687
  endMutation();
@@ -7758,7 +7713,7 @@ async function performMutationWithLifecycle({ startMutation, mutation, onError,
7758
7713
  //#endregion
7759
7714
  //#region src/utils/storeFocusLifecycle.ts
7760
7715
  /** @internal */
7761
- function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate }) {
7716
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate, debug) {
7762
7717
  let cleanupFocusListener = null;
7763
7718
  let cleanupReconnectFocusListener = null;
7764
7719
  let reconnectCooldownTimeoutId = null;
@@ -7778,6 +7733,19 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7778
7733
  if (typeof revalidateOnWindowFocus === "function") return revalidateOnWindowFocus();
7779
7734
  return !!revalidateOnWindowFocus;
7780
7735
  }
7736
+ const logWindowFocusRevalidate = import.meta.env.DEV && debug?.debugLogger ? (message, details) => {
7737
+ emitTSDFDebugLog(debug.debugLogger, {
7738
+ area: "focus",
7739
+ level: "log",
7740
+ message,
7741
+ operation: "window-focus-revalidate",
7742
+ details: {
7743
+ storeId: debug.storeId,
7744
+ storeType: debug.storeType,
7745
+ ...details
7746
+ }
7747
+ });
7748
+ } : void 0;
7781
7749
  function runTransportReconnectRevalidate() {
7782
7750
  lastTransportReconnectRevalidateAt = Date.now();
7783
7751
  onTransportReconnectRevalidate();
@@ -7816,9 +7784,28 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7816
7784
  clearReconnectCooldownTimeout();
7817
7785
  hasPendingReconnectRevalidateOnFocus = false;
7818
7786
  lastTransportReconnectRevalidateAt = Number.NEGATIVE_INFINITY;
7819
- if (!revalidateOnWindowFocus || usesRealTimeUpdates) return;
7787
+ if (!revalidateOnWindowFocus) return;
7788
+ if (usesRealTimeUpdates) {
7789
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
7790
+ reason: "real-time-updates",
7791
+ status: "skipped"
7792
+ });
7793
+ return;
7794
+ }
7820
7795
  cleanupFocusListener = onWindowFocus(() => {
7821
- if (isFocusRevalidationEnabled()) onWindowFocusRevalidate();
7796
+ if (!isFocusRevalidationEnabled()) {
7797
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
7798
+ policy: "dynamic",
7799
+ reason: "dynamic-disabled",
7800
+ status: "skipped"
7801
+ });
7802
+ return;
7803
+ }
7804
+ logWindowFocusRevalidate?.("window focus revalidation triggered", {
7805
+ policy: typeof revalidateOnWindowFocus === "function" ? "dynamic" : "enabled",
7806
+ status: "triggered"
7807
+ });
7808
+ onWindowFocusRevalidate();
7822
7809
  });
7823
7810
  }
7824
7811
  function dispose() {
@@ -7852,7 +7839,7 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7852
7839
  //#endregion
7853
7840
  //#region src/collectionStore/collectionCacheLimits.ts
7854
7841
  /** @internal */
7855
- function createCollectionCacheLimits({ store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup }) {
7842
+ function createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup) {
7856
7843
  let isEnforcingCacheLimits = false;
7857
7844
  function enforceCacheLimits() {
7858
7845
  if (maxItems === void 0 || isEnforcingCacheLimits) return;
@@ -7897,7 +7884,7 @@ const offlineConnectivityError = {
7897
7884
  function normalizeFetchResultError(fetchResult, errorNormalizer) {
7898
7885
  return fetchResult.offline ? offlineConnectivityError : normalizeStoreError(fetchResult.error, errorNormalizer);
7899
7886
  }
7900
- async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7887
+ async function runOfflineAwareFetch(controller, fetcher, operationName) {
7901
7888
  await controller?.prepareForFetch?.();
7902
7889
  const shouldTreatFetchAsOffline = () => controller?.shouldTreatFetchAsOffline?.() ?? controller?.getSessionStatus()?.isOfflineMode ?? false;
7903
7890
  if (shouldTreatFetchAsOffline()) return {
@@ -7926,7 +7913,7 @@ async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7926
7913
  }
7927
7914
  //#endregion
7928
7915
  //#region src/utils/reusePrevIfEqual.ts
7929
- function reusePrevIfEqual({ prev, current }) {
7916
+ function reusePrevIfEqual(prev, current) {
7930
7917
  if (prev === void 0) return current;
7931
7918
  if (deepEqual(prev, current)) return prev;
7932
7919
  return current;
@@ -7963,10 +7950,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
7963
7950
  }
7964
7951
  if (batchFetchFn && requests.length > 1) try {
7965
7952
  const payloads = requests.map((r) => r.payload);
7966
- const fetchResult = await runOfflineAwareFetch({
7967
- controller: offlineController,
7968
- fetcher: () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__")
7969
- });
7953
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__"));
7970
7954
  if (!fetchResult.ok) {
7971
7955
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
7972
7956
  store.produceState((draft) => {
@@ -8000,10 +7984,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8000
7984
  item.status = "error";
8001
7985
  results.set(itemId, false);
8002
7986
  } else if (result !== void 0) try {
8003
- item.data = reusePrevIfEqual({
8004
- current: unwrapMaybeTSDFResult(result),
8005
- prev: item.data
8006
- });
7987
+ item.data = reusePrevIfEqual(item.data, unwrapMaybeTSDFResult(result));
8007
7988
  item.status = "success";
8008
7989
  item.wasLoaded = true;
8009
7990
  results.set(itemId, true);
@@ -8039,10 +8020,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8039
8020
  }
8040
8021
  const fetchPromises = requests.map(async ({ requestId: itemId, payload }) => {
8041
8022
  try {
8042
- const fetchResult = await runOfflineAwareFetch({
8043
- controller: offlineController,
8044
- fetcher: () => fetchFn(klona(payload), fetchCtx.signal)
8045
- });
8023
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchFn(klona(payload), fetchCtx.signal));
8046
8024
  if (!fetchResult.ok) {
8047
8025
  if (fetchCtx.shouldAbort()) {
8048
8026
  results.set(itemId, false);
@@ -8071,10 +8049,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8071
8049
  store.produceState((draft) => {
8072
8050
  const item = draft[itemId];
8073
8051
  if (!item) return;
8074
- item.data = reusePrevIfEqual({
8075
- current: data,
8076
- prev: item.data
8077
- });
8052
+ item.data = reusePrevIfEqual(item.data, data);
8078
8053
  item.status = "success";
8079
8054
  item.wasLoaded = true;
8080
8055
  }, { action: "fetch-success" });
@@ -8307,8 +8282,7 @@ function createFieldsResourceSignature(fields) {
8307
8282
  if (fields === void 0) return "";
8308
8283
  return JSON.stringify(Array.from(new Set(fields)).sort());
8309
8284
  }
8310
- function shouldScheduleAutomaticFetch(options) {
8311
- const { wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false } = options;
8285
+ function shouldScheduleAutomaticFetch(wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false) {
8312
8286
  if (disableRefetches) return !wasLoaded;
8313
8287
  if (disableRefetchOnMount) return shouldFetch;
8314
8288
  if (skipFreshFetch && !shouldFetch) return false;
@@ -8503,14 +8477,7 @@ function useMultipleItems$1(items, { selector, returnIdleStatus: allItemsReturnI
8503
8477
  const shouldFetch = requiredFetch || !!itemState.refetchOnMount;
8504
8478
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemId)) continue;
8505
8479
  ignoreItemsInRefetchOnMount.add(itemId);
8506
- if (shouldScheduleAutomaticFetch({
8507
- wasLoaded: itemState?.wasLoaded,
8508
- shouldFetch,
8509
- requiredFetch,
8510
- disableRefetches,
8511
- disableRefetchOnMount,
8512
- refetchOnMount: itemState?.refetchOnMount ?? false
8513
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, itemId, itemState?.status)) scheduleAutomaticFetch(fetchType, payload);
8480
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount) && tryClaimAutomaticFetchSlot(automaticRetryState, itemId, itemState?.status)) scheduleAutomaticFetch(fetchType, payload);
8514
8481
  }
8515
8482
  }
8516
8483
  for (const itemId of removedQueries) ignoreItemsInRefetchOnMount.delete(itemId);
@@ -8551,18 +8518,9 @@ function createCollectionStore(storeOptions) {
8551
8518
  let offlineOverlaySessionKey = null;
8552
8519
  const itemCacheRuntime = createLruCacheRuntime();
8553
8520
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
8554
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
8555
- storeManager,
8556
- storeName: id,
8557
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
8558
- });
8521
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
8559
8522
  const getSessionKeyBase = storeManager.getSessionKey;
8560
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
8561
- storeManager,
8562
- storeName: id,
8563
- offlineSession: resolvedOfflineSession,
8564
- getSessionKey: getSessionKeyBase
8565
- });
8523
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
8566
8524
  const errorNormalizer = storeManager.errorNormalizer;
8567
8525
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
8568
8526
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -8596,100 +8554,76 @@ function createCollectionStore(storeOptions) {
8596
8554
  offlineOverlayStore.setState({});
8597
8555
  }
8598
8556
  function rebindOfflineOverlays(itemKeyRewrites) {
8599
- rebindOfflineOverlayEntries({
8600
- itemKeyRewrites,
8601
- overlayStore: offlineOverlayStore,
8602
- createReboundOverlay: ({ existingOverlay, nextItemKey }) => ({
8603
- data: existingOverlay.data ?? null,
8604
- payload: store.state[nextItemKey]?.payload ?? existingOverlay.payload,
8605
- keepVisibleWhileResolutionRequired: true
8606
- })
8607
- });
8557
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
8558
+ data: existingOverlay.data ?? null,
8559
+ payload: store.state[nextItemKey]?.payload ?? existingOverlay.payload,
8560
+ keepVisibleWhileResolutionRequired: true
8561
+ }));
8608
8562
  }
8609
8563
  function captureOfflineOverlays(itemKeys) {
8610
- captureOfflineOverlayEntries({
8611
- itemKeys,
8612
- overlayStore: offlineOverlayStore,
8613
- createOverlay: (itemKey) => {
8614
- const item = store.state[itemKey];
8615
- return {
8616
- data: item ? klona(item.data) : null,
8617
- payload: item ? klona(item.payload) : void 0
8618
- };
8619
- }
8564
+ captureOfflineOverlayEntries(offlineOverlayStore, itemKeys, (itemKey) => {
8565
+ const item = store.state[itemKey];
8566
+ return {
8567
+ data: item ? klona(item.data) : null,
8568
+ payload: item ? klona(item.payload) : void 0
8569
+ };
8620
8570
  });
8621
8571
  }
8622
8572
  const resolvedOfflineConfig = resolvedPersistentStorageConfig?.offline;
8623
8573
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_COLLECTION_OFFLINE_OPERATIONS);
8624
8574
  const offlineOperationsForRuntime = resolvedOfflineOperations;
8625
- const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController({
8626
- storeName: id,
8627
- storeType: "collection",
8628
- getSessionKey: getSessionKeyForRuntime,
8629
- onPersistentStorageError: resolvedPersistentStorageConfig.onPersistentStorageError,
8630
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8631
- adapter: resolvedPersistentStorageConfig.adapter,
8632
- offlineSession: resolvedOfflineConfig.session,
8633
- operations: __LEGIT_CAST__(offlineOperationsForRuntime),
8634
- storeAdapter: {
8635
- normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
8636
- const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
8637
- if (normalizedRef !== null) return normalizedRef;
8638
- return {
8639
- entityKey: getItemKey(__LEGIT_CAST__(ref)),
8640
- entityKind: "item"
8641
- };
8642
- }),
8643
- getProtectedCacheKeys: (entityRefs) => {
8644
- const sessionKey = getSessionKeyForRuntime();
8645
- if (sessionKey === false) return [];
8646
- return entityRefs.map((ref) => createProtectedStorageKey({
8647
- backend: resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage",
8648
- sessionKey,
8649
- storeName: id,
8650
- kind: "collection.item",
8651
- key: ref.entityKey
8652
- }));
8653
- },
8654
- applyPendingEntity: ({ tempId, pendingEntity }) => {
8655
- if (!pendingEntity || typeof pendingEntity !== "object") return;
8656
- addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
8657
- },
8658
- rollbackPendingEntity: ({ tempId }) => {
8659
- deleteItemState(__LEGIT_CAST__(tempId));
8660
- },
8661
- reconcileTempEntity: ({ tempId, reconciliation }) => {
8662
- const tempPayload = __LEGIT_CAST__(tempId);
8663
- const currentItem = getItemState(tempPayload);
8664
- const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem?.data ?? void 0;
8665
- if (finalData === void 0) return;
8666
- deleteItemState(tempPayload);
8667
- const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
8668
- addItemToState(finalPayload, finalData);
8669
- storeEvents.emit("tempEntityReconciled", {
8670
- tempId: tempPayload,
8671
- finalPayload
8672
- });
8673
- },
8674
- captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
8675
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8676
- captureOfflineOverlays(entityRefs.flatMap((ref) => {
8677
- return ref.entityKind === "item" ? [ref.entityKey] : [];
8678
- }));
8679
- },
8680
- rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
8681
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8682
- rebindOfflineOverlays(itemKeyRewrites);
8683
- },
8684
- syncEntityOverlays: ({ entities, sessionKey }) => {
8685
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8686
- const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
8687
- offlineOverlayStore.produceState((draft) => {
8688
- for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
8689
- });
8690
- }
8575
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "collection", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
8576
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
8577
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
8578
+ if (normalizedRef !== null) return normalizedRef;
8579
+ return {
8580
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
8581
+ entityKind: "item"
8582
+ };
8583
+ }),
8584
+ getProtectedCacheKeys: (entityRefs) => {
8585
+ const sessionKey = getSessionKeyForRuntime();
8586
+ if (sessionKey === false) return [];
8587
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "collection.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
8588
+ },
8589
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
8590
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
8591
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
8592
+ },
8593
+ rollbackPendingEntity: ({ tempId }) => {
8594
+ deleteItemState(__LEGIT_CAST__(tempId));
8595
+ },
8596
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
8597
+ const tempPayload = __LEGIT_CAST__(tempId);
8598
+ const currentItem = getItemState(tempPayload);
8599
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem?.data ?? void 0;
8600
+ if (finalData === void 0) return;
8601
+ deleteItemState(tempPayload);
8602
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
8603
+ addItemToState(finalPayload, finalData);
8604
+ storeEvents.emit("tempEntityReconciled", {
8605
+ tempId: tempPayload,
8606
+ finalPayload
8607
+ });
8608
+ },
8609
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
8610
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8611
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
8612
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
8613
+ }));
8614
+ },
8615
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
8616
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8617
+ rebindOfflineOverlays(itemKeyRewrites);
8618
+ },
8619
+ syncEntityOverlays: ({ entities, sessionKey }) => {
8620
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8621
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
8622
+ offlineOverlayStore.produceState((draft) => {
8623
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
8624
+ });
8691
8625
  }
8692
- }) : null;
8626
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
8693
8627
  function touchItems(itemKeys) {
8694
8628
  itemCacheRuntime.touch(itemKeys, (itemKey) => {
8695
8629
  return store.state[itemKey] !== void 0;
@@ -8931,10 +8865,6 @@ function createCollectionStore(storeOptions) {
8931
8865
  return getKnownScheduler(message.itemKey)?.isMutationInProgress(message.itemKey) ?? false;
8932
8866
  }
8933
8867
  function handleRemoteMessage(message) {
8934
- if (message.kind === "tab-status") {
8935
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
8936
- return;
8937
- }
8938
8868
  if (message.kind === "fetch-start") {
8939
8869
  const scheduler = getSchedulerForTargetKey(message.targetKey);
8940
8870
  scheduler?.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -8953,21 +8883,16 @@ function createCollectionStore(storeOptions) {
8953
8883
  }
8954
8884
  applyRemoteItemSnapshot(message, candidateVersion);
8955
8885
  }
8956
- const { coordinator: browserTabsSync, priority: browserTabsPriority } = createBrowserTabsCoordinatorWithPriority({
8957
- storeType: "collection",
8958
- storeKey: id,
8959
- getSessionKey: getSessionKeyForRuntime,
8960
- onMessage: handleRemoteMessage,
8961
- onSessionChange() {
8962
- lastCollectionSyncVersions.clear();
8963
- clearOfflineOverlays();
8964
- },
8965
- transportFactory: testOptions?.browserTabsTransportFactory,
8966
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8886
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
8967
8887
  getWindowIsFocused,
8968
8888
  onWindowFocusChange: testOptions?.onWindowFocusChange,
8889
+ transportFactory: testOptions?.browserTabsTransportFactory,
8969
8890
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
8970
8891
  });
8892
+ const browserTabsSync = createBrowserTabsCoordinator("collection", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
8893
+ lastCollectionSyncVersions.clear();
8894
+ clearOfflineOverlays();
8895
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
8971
8896
  async function executeBatchFetch$1(requests, fetchCtx, batchKey) {
8972
8897
  const results = await executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchFn, errorNormalizer, batchKey, offlineController);
8973
8898
  const successfulRequests = requests.filter(({ requestId }) => results.get(requestId) === true);
@@ -9246,50 +9171,37 @@ function createCollectionStore(storeOptions) {
9246
9171
  item: klona(store.state[itemKey])
9247
9172
  })) : [];
9248
9173
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
9249
- const result = await performMutationWithLifecycle({
9250
- startMutation: () => startMutation(payloadToUse),
9251
- optimisticUpdate: optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse)) : void 0,
9252
- debounce: _debounce,
9253
- blockWindowClose: blockWindowClose ?? void 0,
9254
- mutation: offline ? () => runHybridOfflineMutation({
9255
- controller: __LEGIT_CAST__(offlineController),
9256
- offline,
9257
- upload,
9258
- directMutation
9259
- }) : async () => ({
9260
- kind: "online",
9261
- data: await directMutation()
9262
- }),
9263
- onSuccess: (result) => {
9264
- if (revalidateOnSuccess && affectedItems.length > 0) invalidateItem(payloadToUse);
9265
- if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
9266
- },
9267
- onError: (exception) => {
9268
- const error = toStoreMutationError(exception, errorNormalizer);
9269
- if (optimisticRollbackSnapshots.length > 0) {
9270
- const restoredItemKeys = [];
9271
- runWithBroadcastConsistency("confirmed", () => {
9272
- store.produceState((draft) => {
9273
- for (const snapshot of optimisticRollbackSnapshots) {
9274
- if (snapshot.item === void 0) {
9275
- delete draft[snapshot.itemKey];
9276
- continue;
9277
- }
9278
- draft[snapshot.itemKey] = snapshot.item;
9279
- }
9280
- }, { action: "rollback-mutation-error" });
9174
+ const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9175
+ kind: "online",
9176
+ data: await directMutation()
9177
+ }), (exception) => {
9178
+ const error = toStoreMutationError(exception, errorNormalizer);
9179
+ if (optimisticRollbackSnapshots.length > 0) {
9180
+ const restoredItemKeys = [];
9181
+ runWithBroadcastConsistency("confirmed", () => {
9182
+ store.produceState((draft) => {
9281
9183
  for (const snapshot of optimisticRollbackSnapshots) {
9282
- if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9283
- else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9284
- publishItemSnapshot(snapshot.itemKey);
9184
+ if (snapshot.item === void 0) {
9185
+ delete draft[snapshot.itemKey];
9186
+ continue;
9187
+ }
9188
+ draft[snapshot.itemKey] = snapshot.item;
9285
9189
  }
9286
- });
9287
- if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9288
- }
9289
- if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9290
- return error;
9291
- }
9292
- });
9190
+ }, { action: "rollback-mutation-error" });
9191
+ for (const snapshot of optimisticRollbackSnapshots) {
9192
+ if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9193
+ else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9194
+ publishItemSnapshot(snapshot.itemKey);
9195
+ }
9196
+ });
9197
+ if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9198
+ }
9199
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9200
+ return error;
9201
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse)) : void 0, (result) => {
9202
+ if (revalidateOnSuccess && affectedItems.length > 0) invalidateItem(payloadToUse);
9203
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
9204
+ }, _debounce, blockWindowClose ?? void 0);
9293
9205
  storeEvents.emit("mutationEnd", {
9294
9206
  mutationId,
9295
9207
  items: affectedItems,
@@ -9298,31 +9210,17 @@ function createCollectionStore(storeOptions) {
9298
9210
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
9299
9211
  return result;
9300
9212
  }
9301
- const focusLifecycle = createStoreFocusLifecycle({
9302
- revalidateOnWindowFocus: resolvedRevalidateOnWindowFocus,
9303
- usesRealTimeUpdates,
9304
- transportReconnectCooldownMs,
9305
- getWindowIsFocused,
9306
- onWindowFocus: testOptions?.onWindowFocus ?? onWindowFocus,
9307
- onWindowFocusRevalidate: () => {
9308
- invalidateItem(() => true, "lowPriority");
9309
- },
9310
- onTransportReconnectRevalidate: () => {
9311
- invalidateItem(() => true, "realtimeUpdate");
9312
- }
9313
- });
9314
- const { enforceCacheLimits } = createCollectionCacheLimits({
9315
- store,
9316
- maxItems,
9317
- itemCacheRuntime,
9318
- isProtectedFromEviction,
9319
- cleanupItemResources,
9320
- onStateCleanup
9321
- });
9322
- const cacheLimitEnforcementScheduler = createIdleThrottledScheduler({
9323
- throttleMs: CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS,
9324
- run: enforceCacheLimits
9325
- });
9213
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9214
+ invalidateItem(() => true, "lowPriority");
9215
+ }, () => {
9216
+ invalidateItem(() => true, "realtimeUpdate");
9217
+ }, import.meta.env.DEV ? {
9218
+ debugLogger: storeManager.debugLogger,
9219
+ storeId: id,
9220
+ storeType: "collection"
9221
+ } : void 0);
9222
+ const { enforceCacheLimits } = createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup);
9223
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
9326
9224
  function scheduleCacheLimitEnforcement() {
9327
9225
  cacheLimitEnforcementScheduler.schedule();
9328
9226
  }
@@ -9358,7 +9256,6 @@ function createCollectionStore(storeOptions) {
9358
9256
  clearOfflineOverlays();
9359
9257
  itemCacheRuntime.clearAll();
9360
9258
  cacheLimitEnforcementScheduler.cancel();
9361
- browserTabsPriority.reset();
9362
9259
  persistence?.dispose();
9363
9260
  persistence?.clear();
9364
9261
  store.setState(persistence?.createInitialState({}) ?? {});
@@ -9381,7 +9278,6 @@ function createCollectionStore(storeOptions) {
9381
9278
  itemCacheRuntime.clearAll();
9382
9279
  cacheLimitEnforcementScheduler.cancel();
9383
9280
  browserTabsSync.close();
9384
- browserTabsPriority.close();
9385
9281
  focusLifecycle.dispose();
9386
9282
  persistence?.dispose();
9387
9283
  offlineController?.dispose();
@@ -9709,18 +9605,9 @@ function createDocumentStore(storeOptions) {
9709
9605
  let initialStatus = "idle";
9710
9606
  let initialError = null;
9711
9607
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
9712
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
9713
- storeManager,
9714
- storeName: id,
9715
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
9716
- });
9608
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
9717
9609
  const getSessionKeyBase = storeManager.getSessionKey;
9718
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
9719
- storeManager,
9720
- storeName: id,
9721
- offlineSession: resolvedOfflineSession,
9722
- getSessionKey: getSessionKeyBase
9723
- });
9610
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
9724
9611
  const errorNormalizer = storeManager.errorNormalizer;
9725
9612
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
9726
9613
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -9743,55 +9630,39 @@ function createDocumentStore(storeOptions) {
9743
9630
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_DOCUMENT_OFFLINE_OPERATIONS);
9744
9631
  if (import.meta.env.DEV) assertDocumentOfflineOperations(__LEGIT_CAST__(resolvedOfflineOperations));
9745
9632
  const offlineOperationsForRuntime = resolvedOfflineOperations;
9746
- const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController({
9747
- storeName: id,
9748
- storeType: "document",
9749
- getSessionKey: getSessionKeyForRuntime,
9750
- onPersistentStorageError: resolvedPersistentStorageConfig.onPersistentStorageError,
9751
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9752
- adapter: resolvedPersistentStorageConfig.adapter,
9753
- offlineSession: resolvedOfflineConfig.session,
9754
- operations: __LEGIT_CAST__(offlineOperationsForRuntime),
9755
- storeAdapter: {
9756
- getEntityRefs: () => [{
9757
- entityKey: DOC_TARGET_KEY,
9758
- entityKind: "document"
9759
- }],
9760
- normalizeEntityRefs: () => [{
9761
- entityKey: DOC_TARGET_KEY,
9762
- entityKind: "document"
9763
- }],
9764
- getProtectedCacheKeys: () => {
9765
- const sessionKey = getSessionKeyForRuntime();
9766
- if (sessionKey === false) return [];
9767
- return [createProtectedStorageKey({
9768
- backend: resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage",
9769
- sessionKey,
9770
- storeName: id,
9771
- kind: "document",
9772
- key: "d"
9773
- })];
9774
- },
9775
- applyPendingEntity: ({ pendingEntity }) => {
9776
- if (!pendingEntity || typeof pendingEntity !== "object") return;
9777
- updateState((draft) => Object.assign(draft, pendingEntity));
9778
- },
9779
- reconcileTempEntity: ({ reconciliation }) => {
9780
- if (!reconciliation.finalData || typeof reconciliation.finalData !== "object") return;
9781
- updateState((draft) => Object.assign(draft, reconciliation.finalData));
9782
- },
9783
- captureQueuedMutationOverlays: ({ sessionKey }) => {
9784
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9785
- offlineOverlayStore.setState({ data: klona(store.state.data) });
9786
- },
9787
- syncEntityOverlays: ({ entities, sessionKey }) => {
9788
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9789
- if (!entities.some((entity) => {
9790
- return entity.entityKey === DOC_TARGET_KEY;
9791
- })) offlineOverlayStore.setState(null);
9792
- }
9633
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "document", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
9634
+ getEntityRefs: () => [{
9635
+ entityKey: DOC_TARGET_KEY,
9636
+ entityKind: "document"
9637
+ }],
9638
+ normalizeEntityRefs: () => [{
9639
+ entityKey: DOC_TARGET_KEY,
9640
+ entityKind: "document"
9641
+ }],
9642
+ getProtectedCacheKeys: () => {
9643
+ const sessionKey = getSessionKeyForRuntime();
9644
+ if (sessionKey === false) return [];
9645
+ return [createProtectedStorageKey(sessionKey, id, "document", "d", resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage")];
9646
+ },
9647
+ applyPendingEntity: ({ pendingEntity }) => {
9648
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
9649
+ updateState((draft) => Object.assign(draft, pendingEntity));
9650
+ },
9651
+ reconcileTempEntity: ({ reconciliation }) => {
9652
+ if (!reconciliation.finalData || typeof reconciliation.finalData !== "object") return;
9653
+ updateState((draft) => Object.assign(draft, reconciliation.finalData));
9654
+ },
9655
+ captureQueuedMutationOverlays: ({ sessionKey }) => {
9656
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9657
+ offlineOverlayStore.setState({ data: klona(store.state.data) });
9658
+ },
9659
+ syncEntityOverlays: ({ entities, sessionKey }) => {
9660
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9661
+ if (!entities.some((entity) => {
9662
+ return entity.entityKey === DOC_TARGET_KEY;
9663
+ })) offlineOverlayStore.setState(null);
9793
9664
  }
9794
- }) : null;
9665
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
9795
9666
  const store = new Store({
9796
9667
  debugName: id,
9797
9668
  state: () => persistence?.createInitialState({
@@ -9849,10 +9720,7 @@ function createDocumentStore(storeOptions) {
9849
9720
  }
9850
9721
  runWithoutBroadcast(() => {
9851
9722
  store.setPartialState({
9852
- data: reusePrevIfEqual({
9853
- prev: store.state.data,
9854
- current: message.data
9855
- }),
9723
+ data: reusePrevIfEqual(store.state.data, message.data),
9856
9724
  error: null,
9857
9725
  status: "success",
9858
9726
  refetchOnMount: false
@@ -9865,10 +9733,6 @@ function createDocumentStore(storeOptions) {
9865
9733
  return message.consistency === "confirmed" && scheduler.isMutationInProgress(DOC_REQUEST_ID);
9866
9734
  }
9867
9735
  function handleRemoteMessage(message) {
9868
- if (message.kind === "tab-status") {
9869
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
9870
- return;
9871
- }
9872
9736
  if (message.kind === "fetch-start") {
9873
9737
  if (!hasLocalDocumentState()) return;
9874
9738
  scheduler.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -9888,21 +9752,16 @@ function createDocumentStore(storeOptions) {
9888
9752
  }
9889
9753
  applyRemoteDocumentSnapshot(message, candidateVersion);
9890
9754
  }
9891
- const { coordinator: browserTabsSync, priority: browserTabsPriority } = createBrowserTabsCoordinatorWithPriority({
9892
- storeType: "document",
9893
- storeKey: id,
9894
- getSessionKey: getSessionKeyForRuntime,
9895
- onMessage: handleRemoteMessage,
9896
- onSessionChange() {
9897
- lastDocumentSyncVersion = void 0;
9898
- clearOfflineOverlay();
9899
- },
9900
- transportFactory: testOptions?.browserTabsTransportFactory,
9901
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9755
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
9902
9756
  getWindowIsFocused,
9903
9757
  onWindowFocusChange: testOptions?.onWindowFocusChange,
9758
+ transportFactory: testOptions?.browserTabsTransportFactory,
9904
9759
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
9905
9760
  });
9761
+ const browserTabsSync = createBrowserTabsCoordinator("document", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
9762
+ lastDocumentSyncVersion = void 0;
9763
+ clearOfflineOverlay();
9764
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
9906
9765
  async function executeFetch(fetchCtx) {
9907
9766
  const currentStatus = store.state.status;
9908
9767
  const wasLoadedBeforeFetch = currentStatus === "success";
@@ -9912,10 +9771,7 @@ function createDocumentStore(storeOptions) {
9912
9771
  refetchOnMount: false
9913
9772
  }, { action: currentStatus === "success" ? "fetch-start-refetching" : "fetch-start-loading" });
9914
9773
  try {
9915
- const result = await runOfflineAwareFetch({
9916
- controller: offlineController,
9917
- fetcher: () => fetchFn(fetchCtx.signal)
9918
- });
9774
+ const result = await runOfflineAwareFetch(offlineController, () => fetchFn(fetchCtx.signal));
9919
9775
  if (!result.ok) {
9920
9776
  if (result.offline) {
9921
9777
  store.setPartialState(wasLoadedBeforeFetch ? {
@@ -9932,10 +9788,7 @@ function createDocumentStore(storeOptions) {
9932
9788
  const data = result.data;
9933
9789
  if (fetchCtx.shouldAbort()) return false;
9934
9790
  store.setPartialState({
9935
- data: reusePrevIfEqual({
9936
- prev: store.state.data,
9937
- current: data
9938
- }),
9791
+ data: reusePrevIfEqual(store.state.data, data),
9939
9792
  status: "success"
9940
9793
  }, { action: "fetch-success" });
9941
9794
  return true;
@@ -9987,19 +9840,15 @@ function createDocumentStore(storeOptions) {
9987
9840
  usesRealTimeUpdates
9988
9841
  });
9989
9842
  if (initialStatus !== "idle" || initialData !== null || initialError !== null) scheduler.setLastFetchStartTimeForRequest(DOC_REQUEST_ID, testOptions?.initialLastFetchStartTime ?? 0);
9990
- const focusLifecycle = createStoreFocusLifecycle({
9991
- revalidateOnWindowFocus: resolvedRevalidateOnWindowFocus,
9992
- usesRealTimeUpdates,
9993
- transportReconnectCooldownMs,
9994
- getWindowIsFocused,
9995
- onWindowFocus: testOptions?.onWindowFocus ?? onWindowFocus,
9996
- onWindowFocusRevalidate: () => {
9997
- invalidateData("lowPriority");
9998
- },
9999
- onTransportReconnectRevalidate: () => {
10000
- invalidateData("realtimeUpdate");
10001
- }
10002
- });
9843
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9844
+ invalidateData("lowPriority");
9845
+ }, () => {
9846
+ invalidateData("realtimeUpdate");
9847
+ }, import.meta.env.DEV ? {
9848
+ debugLogger: storeManager.debugLogger,
9849
+ storeId: id,
9850
+ storeType: "document"
9851
+ } : void 0);
10003
9852
  persistence?.attach(store);
10004
9853
  initializeOfflineStoreController(offlineController);
10005
9854
  function scheduleFetch(fetchType, options) {
@@ -10085,7 +9934,6 @@ function createDocumentStore(storeOptions) {
10085
9934
  scheduler.reset();
10086
9935
  lastDocumentSyncVersion = void 0;
10087
9936
  clearOfflineOverlay();
10088
- browserTabsPriority.reset();
10089
9937
  persistence?.dispose();
10090
9938
  persistence?.clear();
10091
9939
  store.setState({
@@ -10106,7 +9954,6 @@ function createDocumentStore(storeOptions) {
10106
9954
  lastDocumentSyncVersion = void 0;
10107
9955
  clearOfflineOverlay();
10108
9956
  browserTabsSync.close();
10109
- browserTabsPriority.close();
10110
9957
  focusLifecycle.dispose();
10111
9958
  persistence?.dispose();
10112
9959
  offlineController?.dispose();
@@ -10123,32 +9970,19 @@ function createDocumentStore(storeOptions) {
10123
9970
  updateState,
10124
9971
  currentState: store.state.data
10125
9972
  }));
10126
- const result = await performMutationWithLifecycle({
10127
- startMutation,
10128
- optimisticUpdate: optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data)) : void 0,
10129
- debounce,
10130
- blockWindowClose: blockWindowClose ?? void 0,
10131
- mutation: offline ? () => runHybridOfflineMutation({
10132
- controller: __LEGIT_CAST__(offlineController),
10133
- offline,
10134
- upload,
10135
- directMutation
10136
- }) : async () => ({
10137
- kind: "online",
10138
- data: await directMutation()
10139
- }),
10140
- onSuccess: (result) => {
10141
- if (revalidateOnSuccess && result.kind === "online") invalidateData();
10142
- },
10143
- onError: (exception) => {
10144
- if (optimisticUpdate) runWithBroadcastConsistency("confirmed", () => {
10145
- store.setKey("data", optimisticRollbackSnapshot ?? null, { action: "rollback-mutation-error" });
10146
- publishDocumentSnapshot();
10147
- });
10148
- if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
10149
- return toStoreMutationError(exception, errorNormalizer);
10150
- }
10151
- });
9973
+ const result = await performMutationWithLifecycle(startMutation, offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9974
+ kind: "online",
9975
+ data: await directMutation()
9976
+ }), (exception) => {
9977
+ if (optimisticUpdate) runWithBroadcastConsistency("confirmed", () => {
9978
+ store.setKey("data", optimisticRollbackSnapshot ?? null, { action: "rollback-mutation-error" });
9979
+ publishDocumentSnapshot();
9980
+ });
9981
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9982
+ return toStoreMutationError(exception, errorNormalizer);
9983
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data)) : void 0, (result) => {
9984
+ if (revalidateOnSuccess && result.kind === "online") invalidateData();
9985
+ }, debounce, blockWindowClose ?? void 0);
10152
9986
  storeEvents.emit("mutationEnd", {
10153
9987
  mutationId,
10154
9988
  status: result.ok ? "success" : result.error === mutationSkipped ? "skipped" : "error"
@@ -10221,16 +10055,7 @@ function createDocumentStore(storeOptions) {
10221
10055
  }
10222
10056
  if (disabled) return;
10223
10057
  const fetchType = store.state.refetchOnMount || "lowPriority";
10224
- const wasLoaded = store.state.status === "success" || store.state.status === "refetching";
10225
- const requiredFetch = store.state.status === "idle" || store.state.status === "error";
10226
- if (shouldScheduleAutomaticFetch({
10227
- wasLoaded,
10228
- shouldFetch: requiredFetch || !!store.state.refetchOnMount,
10229
- requiredFetch,
10230
- disableRefetches: !!disableRefetches,
10231
- disableRefetchOnMount: !!disableRefetchOnMount,
10232
- refetchOnMount: store.state.refetchOnMount
10233
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, DOC_TARGET_KEY, store.state.status)) scheduleFetch(fetchType);
10058
+ if (shouldScheduleAutomaticFetch(store.state.status === "success" || store.state.status === "refetching", store.state.status === "idle" || store.state.status === "error" || !!store.state.refetchOnMount, !!disableRefetches, !!disableRefetchOnMount) && tryClaimAutomaticFetchSlot(automaticRetryState, DOC_TARGET_KEY, store.state.status)) scheduleFetch(fetchType);
10234
10059
  })();
10235
10060
  return () => {
10236
10061
  effectState.cancelled = true;
@@ -10397,14 +10222,8 @@ function readManifestGroupMeta(meta) {
10397
10222
  function setupListQueryPersistence(config, options = {}) {
10398
10223
  assertValidPersistentStoreName(config.storeName);
10399
10224
  const version = config.version;
10400
- const defaultMaxItemBytes = getDefaultMaxBytesForScope({
10401
- adapter: config.adapter,
10402
- scopeKind: "listQuery.item"
10403
- });
10404
- const defaultMaxQueryBytes = getDefaultMaxBytesForScope({
10405
- adapter: config.adapter,
10406
- scopeKind: "listQuery.query"
10407
- });
10225
+ const defaultMaxItemBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.item");
10226
+ const defaultMaxQueryBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.query");
10408
10227
  const maxItemBytes = config.maxItemBytes ?? defaultMaxItemBytes;
10409
10228
  const maxQueryBytes = config.maxQueryBytes ?? defaultMaxQueryBytes;
10410
10229
  const maxQuerySize = config.maxQuerySize ?? DEFAULT_MAX_QUERY_SIZE;
@@ -10507,38 +10326,18 @@ function setupListQueryPersistence(config, options = {}) {
10507
10326
  const asyncItemNamespaceScope = getAsyncItemNamespaceScope();
10508
10327
  if (asyncItemNamespaceScope === null) return JSON.stringify(args.value).length;
10509
10328
  const serializedValue = serializeJsonForStorage(args.value.data);
10510
- return estimateManagedAsyncStorageEntrySizeBytes({
10511
- customMetadata: mergeManagedAsyncStorageCustomMetadata({
10512
- currentCustomMetadata: args.currentCustomMetadata,
10513
- key: args.itemKey,
10514
- nextCustomMetadata: args.nextCustomMetadata,
10515
- protectedKeysSnapshotSet: args.protectedKeysSnapshotSet,
10516
- scope: asyncItemNamespaceScope
10517
- }),
10518
- lastAccessAt: args.lastAccessAt,
10519
- serializedValue: serializedValue.rawValue,
10520
- version: version ?? 1
10521
- });
10329
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, args.nextCustomMetadata, args.protectedKeysSnapshotSet, asyncItemNamespaceScope, args.itemKey);
10330
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10522
10331
  }
10523
10332
  function estimateAsyncQueryEntrySizeBytes(args) {
10524
10333
  const asyncQueryNamespaceScope = getAsyncQueryNamespaceScope();
10525
10334
  if (asyncQueryNamespaceScope === null) return JSON.stringify(args.value).length;
10526
10335
  const serializedValue = serializeJsonForStorage(args.value.items);
10527
- return estimateManagedAsyncStorageEntrySizeBytes({
10528
- customMetadata: mergeManagedAsyncStorageCustomMetadata({
10529
- currentCustomMetadata: args.currentCustomMetadata,
10530
- key: args.queryKey,
10531
- nextCustomMetadata: {
10532
- ...args.value.hasMore ? { h: true } : {},
10533
- p: args.value.payload
10534
- },
10535
- protectedKeysSnapshotSet: args.protectedKeysSnapshotSet,
10536
- scope: asyncQueryNamespaceScope
10537
- }),
10538
- lastAccessAt: args.lastAccessAt,
10539
- serializedValue: serializedValue.rawValue,
10540
- version: version ?? 1
10541
- });
10336
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, {
10337
+ ...args.value.hasMore ? { h: true } : {},
10338
+ p: args.value.payload
10339
+ }, args.protectedKeysSnapshotSet, asyncQueryNamespaceScope, args.queryKey);
10340
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10542
10341
  }
10543
10342
  let storeRef = null;
10544
10343
  let unsubscribe = null;
@@ -11288,15 +11087,7 @@ function setupListQueryPersistence(config, options = {}) {
11288
11087
  };
11289
11088
  });
11290
11089
  if (invalidPayloadQueryKeys.length > 0) await Promise.all(invalidPayloadQueryKeys.map((queryKey) => removeLocalStorageQueryEntry(queryKey)));
11291
- const keptQueryKeys = keepEntriesWithinByteBudget({
11292
- entries: filteredEntries,
11293
- getKey: (entry) => entry.queryKey,
11294
- getLastAccessAt: (entry) => entry.lastAccessAt,
11295
- getSizeBytes: (entry) => entry.sizeBytes,
11296
- isPinned: (entry) => pinnedQueryKeys.has(entry.queryKey),
11297
- isProtected: (entry) => entry.offlineProtected,
11298
- maxBytes: maxQueryBytes
11299
- });
11090
+ const keptQueryKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11300
11091
  await Promise.all(filteredEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11301
11092
  for (const { queryKey } of filteredEntries) if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11302
11093
  knownPersistedQueryKeys = keptQueryKeys;
@@ -11320,15 +11111,7 @@ function setupListQueryPersistence(config, options = {}) {
11320
11111
  });
11321
11112
  }
11322
11113
  if (invalidQueryKeys.length > 0) await Promise.all(invalidQueryKeys.map((queryKey) => queryNamespace.remove(queryKey)));
11323
- const keptQueryKeys = keepEntriesWithinByteBudget({
11324
- entries: validEntries,
11325
- getKey: (entry) => entry.queryKey,
11326
- getLastAccessAt: (entry) => entry.lastAccessAt,
11327
- getSizeBytes: (entry) => entry.sizeBytes,
11328
- isPinned: (entry) => pinnedQueryKeys.has(entry.queryKey),
11329
- isProtected: (entry) => protectedQueryKeys.has(entry.queryKey),
11330
- maxBytes: maxQueryBytes
11331
- });
11114
+ const keptQueryKeys = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
11332
11115
  await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
11333
11116
  for (const entry of validEntries) {
11334
11117
  const { queryKey } = entry;
@@ -11367,15 +11150,7 @@ function setupListQueryPersistence(config, options = {}) {
11367
11150
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11368
11151
  }
11369
11152
  const persistedItemEntries = hydratedItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11370
- const keptItemKeys = keepEntriesWithinByteBudget({
11371
- entries: persistedItemEntries,
11372
- getKey: (entry) => entry.itemKey,
11373
- getLastAccessAt: (entry) => entry.lastAccessAt,
11374
- getSizeBytes: (entry) => entry.sizeBytes,
11375
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
11376
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
11377
- maxBytes: maxItemBytes
11378
- });
11153
+ const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11379
11154
  const evictedItemKeys = /* @__PURE__ */ new Set();
11380
11155
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11381
11156
  evictedItemKeys.add(itemKey);
@@ -11425,15 +11200,7 @@ function setupListQueryPersistence(config, options = {}) {
11425
11200
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11426
11201
  }
11427
11202
  const persistedItemEntries = validItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11428
- const keptItemKeys = keepEntriesWithinByteBudget({
11429
- entries: persistedItemEntries,
11430
- getKey: (entry) => entry.itemKey,
11431
- getLastAccessAt: (entry) => entry.lastAccessAt,
11432
- getSizeBytes: (entry) => entry.sizeBytes,
11433
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
11434
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
11435
- maxBytes: maxItemBytes
11436
- });
11203
+ const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11437
11204
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => itemNamespace.remove(itemKey)));
11438
11205
  for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11439
11206
  knownPersistedItemKeys = keptItemKeys;
@@ -11603,7 +11370,7 @@ function setupListQueryPersistence(config, options = {}) {
11603
11370
  if (localStorageAdapter !== null) {
11604
11371
  const nextKnownPersistedItemBytes = getKnownPersistedItemBytes(knownPersistedItemKeys);
11605
11372
  const nextKnownPersistedQueryBytes = getKnownPersistedQueryBytes(knownPersistedQueryKeys);
11606
- if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance({ forceManifestKeys: [maintenanceCallbackKey] });
11373
+ if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance([maintenanceCallbackKey]);
11607
11374
  return;
11608
11375
  }
11609
11376
  const sessionKey = config.getSessionKey();
@@ -11697,15 +11464,7 @@ function setupListQueryPersistence(config, options = {}) {
11697
11464
  sizeBytes
11698
11465
  });
11699
11466
  }
11700
- const keptQueryKeys = keepEntriesWithinByteBudget({
11701
- entries: candidateEntries,
11702
- getKey: (entry) => entry.queryKey,
11703
- getLastAccessAt: (entry) => entry.lastAccessAt,
11704
- getSizeBytes: (entry) => entry.sizeBytes,
11705
- isPinned: (entry) => pinnedQueryKeys.has(entry.queryKey),
11706
- isProtected: (entry) => entry.offlineProtected,
11707
- maxBytes: maxQueryBytes
11708
- });
11467
+ const keptQueryKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11709
11468
  finalPersistedQueryKeys.clear();
11710
11469
  for (const queryKey of keptQueryKeys) finalPersistedQueryKeys.add(queryKey);
11711
11470
  const evictedQueryKeys = [];
@@ -11797,15 +11556,7 @@ function setupListQueryPersistence(config, options = {}) {
11797
11556
  sizeBytes
11798
11557
  });
11799
11558
  }
11800
- const keptItemKeys = keepEntriesWithinByteBudget({
11801
- entries: itemCandidateEntries,
11802
- getKey: (entry) => entry.itemKey,
11803
- getLastAccessAt: (entry) => entry.lastAccessAt,
11804
- getSizeBytes: (entry) => entry.sizeBytes,
11805
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
11806
- isProtected: (entry) => entry.offlineProtected,
11807
- maxBytes: maxItemBytes
11808
- });
11559
+ const keptItemKeys = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11809
11560
  finalPersistedItemKeys.clear();
11810
11561
  for (const itemKey of keptItemKeys) finalPersistedItemKeys.add(itemKey);
11811
11562
  const evictedItemKeys = [];
@@ -11994,10 +11745,7 @@ function excludeLoadedFields(loadedFields, requestedFields) {
11994
11745
  function applyPartialItemMerge(draft, itemKey, data, fields, partialResources) {
11995
11746
  const prev = draft.items[itemKey] ?? void 0;
11996
11747
  const merged = partialResources.mergeItems(prev, data);
11997
- draft.items[itemKey] = reusePrevIfEqual({
11998
- current: merged,
11999
- prev
12000
- });
11748
+ draft.items[itemKey] = reusePrevIfEqual(prev, merged);
12001
11749
  if (fields && fields.length > 0) {
12002
11750
  const existingFields = draft.itemLoadedFields[itemKey] ?? [];
12003
11751
  const fieldSet = new Set([...existingFields, ...fields]);
@@ -12011,10 +11759,7 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12011
11759
  const results = /* @__PURE__ */ new Map();
12012
11760
  function applyItemResult(draft, itemKey, data, fields) {
12013
11761
  if (partialResources) applyPartialItemMerge(draft, itemKey, data, fields, partialResources);
12014
- else draft.items[itemKey] = reusePrevIfEqual({
12015
- current: data,
12016
- prev: draft.items[itemKey] ?? void 0
12017
- });
11762
+ else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12018
11763
  }
12019
11764
  function clearSatisfiedItemInvalidationFields(draft, itemKey, requestFields) {
12020
11765
  const invalidationFields = draft.itemFieldInvalidationFields[itemKey];
@@ -12057,13 +11802,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12057
11802
  payload: r.payload.payload,
12058
11803
  fields: r.payload.fields
12059
11804
  }));
12060
- const fetchResult = await runOfflineAwareFetch({
12061
- controller: offlineController,
12062
- fetcher: () => batchFetchItemFn(batchRequests, {
12063
- signal: fetchCtx.signal,
12064
- batchKey: batchKey ?? "__default__"
12065
- })
12066
- });
11805
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchItemFn(batchRequests, {
11806
+ signal: fetchCtx.signal,
11807
+ batchKey: batchKey ?? "__default__"
11808
+ }));
12067
11809
  if (!fetchResult.ok) {
12068
11810
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
12069
11811
  store.produceState((draft) => {
@@ -12139,13 +11881,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12139
11881
  }
12140
11882
  const fetchPromises = requests.map(async ({ requestId: itemKey, payload: requestData }) => {
12141
11883
  try {
12142
- const fetchResult = await runOfflineAwareFetch({
12143
- controller: offlineController,
12144
- fetcher: () => fetchItemFn(klona(requestData.payload), {
12145
- signal: fetchCtx.signal,
12146
- fields: requestData.fields
12147
- })
12148
- });
11884
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchItemFn(klona(requestData.payload), {
11885
+ signal: fetchCtx.signal,
11886
+ fields: requestData.fields
11887
+ }));
12149
11888
  if (!fetchResult.ok) {
12150
11889
  if (fetchCtx.shouldAbort()) {
12151
11890
  results.set(itemKey, false);
@@ -12221,10 +11960,7 @@ function applyFetchedItems(draft, queryKey, items, hasMore, fields, getItemKey,
12221
11960
  if (remainingFields.length > 0) draft.itemFieldInvalidationFields[itemKey] = remainingFields;
12222
11961
  else delete draft.itemFieldInvalidationFields[itemKey];
12223
11962
  }
12224
- } else draft.items[itemKey] = reusePrevIfEqual({
12225
- current: data,
12226
- prev: draft.items[itemKey] ?? void 0
12227
- });
11963
+ } else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12228
11964
  if (!existingItemKeys.has(itemKey)) {
12229
11965
  query.items.push(itemKey);
12230
11966
  existingItemKeys.add(itemKey);
@@ -12286,13 +12022,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12286
12022
  stopOnError: true,
12287
12023
  rejectPendingOnError: true
12288
12024
  });
12289
- const chunkResultPromises = chunks.map((chunk) => queue.resultifyAdd(() => runOfflineAwareFetch({
12290
- controller: offlineController,
12291
- fetcher: () => normalizedFetchListFn(payload, chunk.offset, chunk.limit, {
12292
- signal: fetchCtx.signal,
12293
- fields
12294
- })
12295
- }).then((result) => {
12025
+ const chunkResultPromises = chunks.map((chunk) => queue.resultifyAdd(() => runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, chunk.offset, chunk.limit, {
12026
+ signal: fetchCtx.signal,
12027
+ fields
12028
+ })).then((result) => {
12296
12029
  if (!result.ok) throw result.offline ? offlineConnectivityError : result.error;
12297
12030
  return result.data;
12298
12031
  })));
@@ -12301,13 +12034,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12301
12034
  const lastChunk = successResults[successResults.length - 1];
12302
12035
  hasMore = lastChunk ? lastChunk.hasMore : false;
12303
12036
  } else {
12304
- const fetchResult = await runOfflineAwareFetch({
12305
- controller: offlineController,
12306
- fetcher: () => normalizedFetchListFn(payload, offset, limit, {
12307
- signal: fetchCtx.signal,
12308
- fields
12309
- })
12310
- });
12037
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, offset, limit, {
12038
+ signal: fetchCtx.signal,
12039
+ fields
12040
+ }));
12311
12041
  if (!fetchResult.ok) throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
12312
12042
  const result = fetchResult.data;
12313
12043
  allItems = result.items;
@@ -12349,7 +12079,7 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12349
12079
  //#endregion
12350
12080
  //#region src/listQueryStore/createFetchApi.ts
12351
12081
  /** @internal */
12352
- function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, dynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, syncHydrationEnabled = false, preloadQueries: preloadQueries_, preloadItems: preloadItems_, persistence, testInitialLastFetchStartTime, onQueryFetchStart, onQueryFetchSettled, onItemFetchStart, onItemFetchSettled, offlineController }) {
12082
+ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, dynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, syncHydrationEnabled, preloadQueries_, preloadItems_, persistence, testInitialLastFetchStartTime, onQueryFetchStart, onQueryFetchSettled, onItemFetchStart, onItemFetchSettled, offlineController) {
12353
12083
  const noFetchItemFnError = "No fetchItemFn was provided";
12354
12084
  const querySchedulers = /* @__PURE__ */ new Map();
12355
12085
  const queryInitialFetchStartTime = /* @__PURE__ */ new Map();
@@ -13066,7 +12796,7 @@ const GET_ALL = () => true;
13066
12796
  //#endregion
13067
12797
  //#region src/listQueryStore/createMutationApi.ts
13068
12798
  /** @internal */
13069
- function createMutationApi({ store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent }) {
12799
+ function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent) {
13070
12800
  const storeEvents = evtmitter();
13071
12801
  const deferredOptimisticQueryInvalidationsStack = [];
13072
12802
  const optimisticMutationQueryContextStack = [];
@@ -13466,55 +13196,42 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13466
13196
  items: affectedItems
13467
13197
  });
13468
13198
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
13469
- const result = await performMutationWithLifecycle({
13470
- startMutation: () => {
13471
- const endBaseMutations = startItemMutation(payloadToUse);
13472
- return () => {
13473
- endBaseMutations();
13474
- for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
13475
- };
13476
- },
13477
- optimisticUpdate: optimisticUpdate ? () => {
13478
- deferredOptimisticQueryInvalidationsStack.push(deferredOptimisticQueryInvalidations);
13479
- optimisticMutationQueryContextStack.push(optimisticMutationQueryContext);
13480
- try {
13481
- return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse));
13482
- } finally {
13483
- optimisticMutationQueryContextStack.pop();
13484
- deferredOptimisticQueryInvalidationsStack.pop();
13485
- }
13486
- } : void 0,
13487
- debounce,
13488
- blockWindowClose: blockWindowClose ?? void 0,
13489
- mutation: offline ? () => runHybridOfflineMutation({
13490
- controller: offlineController,
13491
- offline,
13492
- upload,
13493
- directMutation
13494
- }) : async () => ({
13495
- kind: "online",
13496
- data: await directMutation()
13497
- }),
13498
- onSuccess: (result) => {
13499
- const successInvalidationQueryPayloads = result.kind === "online" ? getSuccessInvalidationQueryPayloads(deferredOptimisticQueryInvalidations, normalizedRevalidateOnSuccess.queryFilter, normalizedRevalidateOnSuccess.shouldRevalidate) : [];
13500
- if (result.kind === "online" && (normalizedRevalidateOnSuccess.shouldRevalidate || successInvalidationQueryPayloads.length > 0)) invalidateQueryAndItems({
13501
- itemPayload: !normalizedRevalidateOnSuccess.includeItems || affectedItems.length === 0 ? false : payloadToUse,
13502
- queryPayload: successInvalidationQueryPayloads.length > 0 ? successInvalidationQueryPayloads : false
13503
- });
13504
- if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
13505
- },
13506
- onError: (exception) => {
13507
- const error = toStoreMutationError(exception, errorNormalizer);
13508
- const queryRollbackSnapshots = [...optimisticMutationQueryContext.queryRollbackSnapshots.values()];
13509
- if (itemRollbackSnapshots.length > 0 || queryRollbackSnapshots.length) restoreMutationRollbackState({
13510
- itemSnapshots: itemRollbackSnapshots,
13511
- querySnapshots: queryRollbackSnapshots
13512
- });
13513
- if (onMutationError) onMutationError(exception, { silentErrors });
13514
- if (onError) onError(error);
13515
- return error;
13516
- }
13517
- });
13199
+ const result = await performMutationWithLifecycle(() => {
13200
+ const endBaseMutations = startItemMutation(payloadToUse);
13201
+ return () => {
13202
+ endBaseMutations();
13203
+ for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
13204
+ };
13205
+ }, offline ? () => runHybridOfflineMutation(offlineController, offline, upload, directMutation) : async () => ({
13206
+ kind: "online",
13207
+ data: await directMutation()
13208
+ }), (exception) => {
13209
+ const error = toStoreMutationError(exception, errorNormalizer);
13210
+ const queryRollbackSnapshots = [...optimisticMutationQueryContext.queryRollbackSnapshots.values()];
13211
+ if (itemRollbackSnapshots.length > 0 || queryRollbackSnapshots.length) restoreMutationRollbackState({
13212
+ itemSnapshots: itemRollbackSnapshots,
13213
+ querySnapshots: queryRollbackSnapshots
13214
+ });
13215
+ if (onMutationError) onMutationError(exception, { silentErrors });
13216
+ if (onError) onError(error);
13217
+ return error;
13218
+ }, optimisticUpdate ? () => {
13219
+ deferredOptimisticQueryInvalidationsStack.push(deferredOptimisticQueryInvalidations);
13220
+ optimisticMutationQueryContextStack.push(optimisticMutationQueryContext);
13221
+ try {
13222
+ return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse));
13223
+ } finally {
13224
+ optimisticMutationQueryContextStack.pop();
13225
+ deferredOptimisticQueryInvalidationsStack.pop();
13226
+ }
13227
+ } : void 0, (result) => {
13228
+ const successInvalidationQueryPayloads = result.kind === "online" ? getSuccessInvalidationQueryPayloads(deferredOptimisticQueryInvalidations, normalizedRevalidateOnSuccess.queryFilter, normalizedRevalidateOnSuccess.shouldRevalidate) : [];
13229
+ if (result.kind === "online" && (normalizedRevalidateOnSuccess.shouldRevalidate || successInvalidationQueryPayloads.length > 0)) invalidateQueryAndItems({
13230
+ itemPayload: !normalizedRevalidateOnSuccess.includeItems || affectedItems.length === 0 ? false : payloadToUse,
13231
+ queryPayload: successInvalidationQueryPayloads.length > 0 ? successInvalidationQueryPayloads : false
13232
+ });
13233
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
13234
+ }, debounce, blockWindowClose ?? void 0);
13518
13235
  storeEvents.emit("mutationEnd", {
13519
13236
  mutationId,
13520
13237
  items: affectedItems,
@@ -13542,7 +13259,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13542
13259
  //#endregion
13543
13260
  //#region src/listQueryStore/listQueryCacheLimits.ts
13544
13261
  /** @internal */
13545
- function createListQueryCacheLimits({ store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup }) {
13262
+ function createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup) {
13546
13263
  let isEnforcingCacheLimits = false;
13547
13264
  function getReferencedItemKeysFromQueries(queryKeys = Object.keys(store.state.queries)) {
13548
13265
  const referencedItemKeys = /* @__PURE__ */ new Set();
@@ -14198,15 +13915,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14198
13915
  }
14199
13916
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemKey)) continue;
14200
13917
  ignoreItemsInRefetchOnMount.add(itemKey);
14201
- if (shouldScheduleAutomaticFetch({
14202
- wasLoaded: itemState?.wasLoaded,
14203
- shouldFetch,
14204
- requiredFetch,
14205
- disableRefetches,
14206
- disableRefetchOnMount,
14207
- refetchOnMount: itemState?.refetchOnMount ?? false,
14208
- skipFreshFetch: !!partialResources
14209
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, itemState?.status)) scheduleAutomaticItemFetch(fetchType, payload, { fields: fieldsToFetch });
13918
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, itemState?.status)) scheduleAutomaticItemFetch(fetchType, payload, { fields: fieldsToFetch });
14210
13919
  }
14211
13920
  for (const itemKey of removedItems) ignoreItemsInRefetchOnMount.delete(itemKey);
14212
13921
  })();
@@ -14754,15 +14463,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14754
14463
  }
14755
14464
  if (!shouldFetch && ignoreQueriesInRefetchOnMount.has(queryId)) continue;
14756
14465
  ignoreQueriesInRefetchOnMount.add(queryId);
14757
- if (shouldScheduleAutomaticFetch({
14758
- wasLoaded: effectiveQueryState?.wasLoaded,
14759
- shouldFetch,
14760
- requiredFetch,
14761
- disableRefetches,
14762
- disableRefetchOnMount,
14763
- refetchOnMount: queryState?.refetchOnMount ?? false,
14764
- skipFreshFetch: !!partialResources
14765
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
14466
+ if (shouldScheduleAutomaticFetch(effectiveQueryState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
14766
14467
  stickyDerivedQueryKeys.delete(queryId);
14767
14468
  scheduleAutomaticListQueryFetch(fetchType, payload, loadSize, { fields: fieldsToFetch });
14768
14469
  }
@@ -14950,18 +14651,9 @@ function createListQueryStore(storeOptions) {
14950
14651
  if (fields === "*") return void 0;
14951
14652
  return fields;
14952
14653
  }
14953
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
14954
- storeManager,
14955
- storeName: id,
14956
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
14957
- });
14654
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
14958
14655
  const getSessionKeyBase = storeManager.getSessionKey;
14959
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
14960
- storeManager,
14961
- storeName: id,
14962
- offlineSession: resolvedOfflineSession,
14963
- getSessionKey: getSessionKeyBase
14964
- });
14656
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
14965
14657
  const errorNormalizer = storeManager.errorNormalizer;
14966
14658
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
14967
14659
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -15081,11 +14773,20 @@ function createListQueryStore(storeOptions) {
15081
14773
  lastFetchDuration,
15082
14774
  windowIsNotFocused: !getWindowIsFocused()
15083
14775
  });
14776
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
14777
+ getWindowIsFocused,
14778
+ onWindowFocusChange: testOptions?.onWindowFocusChange,
14779
+ transportFactory: testOptions?.browserTabsTransportFactory,
14780
+ priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
14781
+ });
15084
14782
  function getCoalescingWindowMs() {
15085
- return browserTabsPriority?.getCoalescingWindowMs(baseCoalescingWindowMs) ?? baseCoalescingWindowMs;
14783
+ return browserTabsPriority.getCoalescingWindowMs(baseCoalescingWindowMs);
15086
14784
  }
15087
- let browserTabsSync = null;
15088
- let browserTabsPriority = null;
14785
+ const browserTabsSync = createBrowserTabsCoordinator("listQuery", id, getSessionKeyForRuntime, handleRemoteBrowserTabsMessage, () => {
14786
+ lastQuerySyncVersions.clear();
14787
+ lastItemSyncVersions.clear();
14788
+ clearOfflineOverlays();
14789
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
15089
14790
  function getQueryTargetKey(queryKey) {
15090
14791
  return `query:${queryKey}`;
15091
14792
  }
@@ -15119,7 +14820,7 @@ function createListQueryStore(storeOptions) {
15119
14820
  const query = store.state.queries[queryKey];
15120
14821
  if (!query) return;
15121
14822
  const items = getQuerySnapshotItems(query);
15122
- const message = browserTabsSync?.publish({
14823
+ const message = browserTabsSync.publish({
15123
14824
  kind: "list-query-snapshot",
15124
14825
  queryKey,
15125
14826
  consistency,
@@ -15132,7 +14833,7 @@ function createListQueryStore(storeOptions) {
15132
14833
  }
15133
14834
  function publishItemSnapshot(itemKey, consistency = currentBroadcastConsistency) {
15134
14835
  if (remoteApplyDepth > 0) return;
15135
- const message = browserTabsSync?.publish({
14836
+ const message = browserTabsSync.publish({
15136
14837
  kind: "list-item-snapshot",
15137
14838
  itemKey,
15138
14839
  consistency,
@@ -15194,212 +14895,142 @@ function createListQueryStore(storeOptions) {
15194
14895
  preloaded: results[index] ?? false
15195
14896
  }));
15196
14897
  }
15197
- const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers } = createFetchApi({
15198
- store,
15199
- normalizedFetchListFn,
15200
- offsetPagination,
15201
- fetchItemFn,
15202
- batchFetchItemFn,
15203
- getItemsBatchKey,
15204
- errorNormalizer,
15205
- partialResources,
15206
- lowPriorityThrottleMs,
15207
- getCoalescingWindowMs,
15208
- mediumPriorityDelayMs,
15209
- dynamicRealtimeThrottleMs: wrappedDynamicRealtimeThrottleMs,
15210
- onSchedulerEvent,
15211
- usesRealTimeUpdates,
15212
- defaultQuerySize,
15213
- maxItemBatchSize,
15214
- getQueryKey,
15215
- getItemKey,
15216
- normalizeFieldsOption,
15217
- syncHydrationEnabled: !!persistence && !persistence.hasAsyncPreload,
15218
- preloadQueries: persistence ? (queryKeys) => persistence.preloadQueries(queryKeys) : void 0,
15219
- preloadItems: persistence ? (itemKeys) => persistence.preloadItems(itemKeys) : void 0,
15220
- persistence,
15221
- testInitialLastFetchStartTime: testOptions?.initialLastFetchStartTime,
15222
- offlineController: offlineFetchController,
15223
- onQueryFetchStart: (requests, startedAt) => {
15224
- const queryKey = requests[0]?.requestId;
15225
- if (!queryKey) return;
15226
- browserTabsSync?.publish({
15227
- kind: "fetch-start",
15228
- targetKey: getQueryTargetKey(queryKey),
15229
- requestIds: requests.map(({ requestId }) => requestId),
15230
- startedAt
14898
+ const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers } = createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, wrappedDynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, !!persistence && !persistence.hasAsyncPreload, persistence ? (queryKeys) => persistence.preloadQueries(queryKeys) : void 0, persistence ? (itemKeys) => persistence.preloadItems(itemKeys) : void 0, persistence, testOptions?.initialLastFetchStartTime, (requests, startedAt) => {
14899
+ const queryKey = requests[0]?.requestId;
14900
+ if (!queryKey) return;
14901
+ browserTabsSync.publish({
14902
+ kind: "fetch-start",
14903
+ targetKey: getQueryTargetKey(queryKey),
14904
+ requestIds: requests.map(({ requestId }) => requestId),
14905
+ startedAt
14906
+ });
14907
+ }, ({ requests, results, startedAt, duration }) => {
14908
+ pruneItemInvalidationTracking();
14909
+ const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
14910
+ if (successfulQueryKeys.length > 0) {
14911
+ touchQueries(successfulQueryKeys);
14912
+ touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
14913
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
14914
+ }
14915
+ const firstQueryKey = successfulQueryKeys[0];
14916
+ if (firstQueryKey) {
14917
+ browserTabsSync.publish({
14918
+ kind: "fetch-success",
14919
+ targetKey: getQueryTargetKey(firstQueryKey),
14920
+ requestIds: successfulQueryKeys,
14921
+ startedAt,
14922
+ duration
15231
14923
  });
15232
- },
15233
- onItemFetchStart: (requests, startedAt) => {
15234
- const firstRequest = requests[0];
15235
- if (!firstRequest) return;
15236
- const payload = firstRequest.payload.payload;
15237
- const batchKey = getItemBatchKey(payload);
15238
- const targetKey = batchKey === false ? getItemTargetKey(firstRequest.requestId) : getItemBatchTargetKey(batchKey);
15239
- browserTabsSync?.publish({
15240
- kind: "fetch-start",
14924
+ for (const queryKey of successfulQueryKeys) publishQuerySnapshot(queryKey, "confirmed");
14925
+ }
14926
+ }, (requests, startedAt) => {
14927
+ const firstRequest = requests[0];
14928
+ if (!firstRequest) return;
14929
+ const payload = firstRequest.payload.payload;
14930
+ const batchKey = getItemBatchKey(payload);
14931
+ const targetKey = batchKey === false ? getItemTargetKey(firstRequest.requestId) : getItemBatchTargetKey(batchKey);
14932
+ browserTabsSync.publish({
14933
+ kind: "fetch-start",
14934
+ targetKey,
14935
+ requestIds: requests.map(({ requestId }) => requestId),
14936
+ startedAt
14937
+ });
14938
+ }, ({ requests, results, startedAt, duration }) => {
14939
+ pruneItemInvalidationTracking();
14940
+ const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
14941
+ if (successfulItems.length > 0) {
14942
+ touchItems(successfulItems.map(({ itemKey }) => itemKey));
14943
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
14944
+ }
14945
+ const firstSuccessfulItem = successfulItems[0];
14946
+ if (firstSuccessfulItem) {
14947
+ const payload = requests[0]?.payload.payload;
14948
+ const batchKey = payload ? getItemBatchKey(payload) : false;
14949
+ const targetKey = batchKey === false ? getItemTargetKey(firstSuccessfulItem.itemKey) : getItemBatchTargetKey(batchKey);
14950
+ browserTabsSync.publish({
14951
+ kind: "fetch-success",
15241
14952
  targetKey,
15242
- requestIds: requests.map(({ requestId }) => requestId),
15243
- startedAt
14953
+ requestIds: successfulItems.map(({ itemKey }) => itemKey),
14954
+ startedAt,
14955
+ duration
15244
14956
  });
14957
+ for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
14958
+ }
14959
+ }, offlineFetchController);
14960
+ const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, invalidateQueryAndItems, invalidateItem, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, resolvedOnMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, (event) => {
14961
+ events.emit("invalidateQuery", event);
14962
+ }, (event) => {
14963
+ events.emit("invalidateItem", event);
14964
+ }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0);
14965
+ if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
14966
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
14967
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
14968
+ if (normalizedRef !== null) return normalizedRef;
14969
+ return {
14970
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
14971
+ entityKind: "item"
14972
+ };
14973
+ }),
14974
+ getProtectedCacheKeys: (entityRefs) => {
14975
+ const sessionKey = getSessionKeyForRuntime();
14976
+ if (sessionKey === false) return [];
14977
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "listQuery.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
15245
14978
  },
15246
- onQueryFetchSettled: ({ requests, results, startedAt, duration }) => {
15247
- pruneItemInvalidationTracking();
15248
- const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
15249
- if (successfulQueryKeys.length > 0) {
15250
- touchQueries(successfulQueryKeys);
15251
- touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
15252
- if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15253
- }
15254
- const firstQueryKey = successfulQueryKeys[0];
15255
- if (firstQueryKey) {
15256
- browserTabsSync?.publish({
15257
- kind: "fetch-success",
15258
- targetKey: getQueryTargetKey(firstQueryKey),
15259
- requestIds: successfulQueryKeys,
15260
- startedAt,
15261
- duration
15262
- });
15263
- for (const queryKey of successfulQueryKeys) publishQuerySnapshot(queryKey, "confirmed");
15264
- }
14979
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
14980
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
14981
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
15265
14982
  },
15266
- onItemFetchSettled: ({ requests, results, startedAt, duration }) => {
15267
- pruneItemInvalidationTracking();
15268
- const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
15269
- if (successfulItems.length > 0) {
15270
- touchItems(successfulItems.map(({ itemKey }) => itemKey));
15271
- if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15272
- }
15273
- const firstSuccessfulItem = successfulItems[0];
15274
- if (firstSuccessfulItem) {
15275
- const payload = requests[0]?.payload.payload;
15276
- const batchKey = payload ? getItemBatchKey(payload) : false;
15277
- const targetKey = batchKey === false ? getItemTargetKey(firstSuccessfulItem.itemKey) : getItemBatchTargetKey(batchKey);
15278
- browserTabsSync?.publish({
15279
- kind: "fetch-success",
15280
- targetKey,
15281
- requestIds: successfulItems.map(({ itemKey }) => itemKey),
15282
- startedAt,
15283
- duration
15284
- });
15285
- for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
15286
- }
15287
- }
15288
- });
15289
- const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, invalidateQueryAndItems, invalidateItem, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi({
15290
- store,
15291
- fetchItemFn,
15292
- partialResources,
15293
- optimisticListUpdates,
15294
- onInvalidateQuery,
15295
- onInvalidateItem,
15296
- onMutationError: resolvedOnMutationError,
15297
- errorNormalizer,
15298
- getItemKey,
15299
- getQueriesKeyArray,
15300
- getQueriesRelatedToItem,
15301
- getItemsKeyArray,
15302
- getOrCreateItemScheduler,
15303
- getOrCreateQueryScheduler,
15304
- deleteItemFetchResources,
15305
- emitInvalidateQuery: (event) => {
15306
- events.emit("invalidateQuery", event);
14983
+ rollbackPendingEntity: ({ tempId }) => {
14984
+ deleteItemState(__LEGIT_CAST__(tempId));
15307
14985
  },
15308
- emitInvalidateItem: (event) => {
15309
- events.emit("invalidateItem", event);
14986
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
14987
+ const tempPayload = __LEGIT_CAST__(tempId);
14988
+ const tempItemKey = getItemKey(tempPayload);
14989
+ const currentItem = getItemState(tempPayload);
14990
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
14991
+ if (finalData === void 0) return;
14992
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
14993
+ const finalItemKey = getItemKey(finalPayload);
14994
+ const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
14995
+ queryKey,
14996
+ index: query.items.indexOf(tempItemKey)
14997
+ })).filter(({ index }) => index !== -1);
14998
+ deleteItemState(tempPayload);
14999
+ addItemToState(finalPayload, finalData);
15000
+ storeEvents.emit("tempEntityReconciled", {
15001
+ tempId: tempPayload,
15002
+ finalPayload
15003
+ });
15004
+ if (queryMemberships.length === 0) return;
15005
+ store.produceState((draft) => {
15006
+ for (const { queryKey, index } of queryMemberships) {
15007
+ const query = notNullish(draft.queries[queryKey]);
15008
+ const existingIndex = query.items.indexOf(finalItemKey);
15009
+ if (existingIndex !== -1) query.items.splice(existingIndex, 1);
15010
+ query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
15011
+ }
15012
+ }, { action: "offline-reconcile-temp-item" });
15013
+ touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
15014
+ for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
15310
15015
  },
15311
- blockWindowClose,
15312
- offlineController: resolvedOfflineConfig ? offlineMutationController : null,
15313
- runWithBroadcastConsistency,
15314
- publishQuerySnapshot,
15315
- publishItemSnapshot,
15316
- onOfflineTimelineEvent: void 0
15317
- });
15318
- if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController({
15319
- storeName: id,
15320
- storeType: "listQuery",
15321
- getSessionKey: getSessionKeyForRuntime,
15322
- onPersistentStorageError: resolvedPersistentStorageConfig.onPersistentStorageError,
15323
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
15324
- adapter: resolvedPersistentStorageConfig.adapter,
15325
- offlineSession: resolvedOfflineConfig.session,
15326
- operations: __LEGIT_CAST__(offlineOperationsForRuntime),
15327
- storeAdapter: {
15328
- normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
15329
- const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
15330
- if (normalizedRef !== null) return normalizedRef;
15331
- return {
15332
- entityKey: getItemKey(__LEGIT_CAST__(ref)),
15333
- entityKind: "item"
15334
- };
15335
- }),
15336
- getProtectedCacheKeys: (entityRefs) => {
15337
- const sessionKey = getSessionKeyForRuntime();
15338
- if (sessionKey === false) return [];
15339
- return entityRefs.map((ref) => createProtectedStorageKey({
15340
- backend: resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage",
15341
- sessionKey,
15342
- storeName: id,
15343
- kind: "listQuery.item",
15344
- key: ref.entityKey
15345
- }));
15346
- },
15347
- applyPendingEntity: ({ tempId, pendingEntity }) => {
15348
- if (!pendingEntity || typeof pendingEntity !== "object") return;
15349
- addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
15350
- },
15351
- rollbackPendingEntity: ({ tempId }) => {
15352
- deleteItemState(__LEGIT_CAST__(tempId));
15353
- },
15354
- reconcileTempEntity: ({ tempId, reconciliation }) => {
15355
- const tempPayload = __LEGIT_CAST__(tempId);
15356
- const tempItemKey = getItemKey(tempPayload);
15357
- const currentItem = getItemState(tempPayload);
15358
- const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
15359
- if (finalData === void 0) return;
15360
- const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
15361
- const finalItemKey = getItemKey(finalPayload);
15362
- const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
15363
- queryKey,
15364
- index: query.items.indexOf(tempItemKey)
15365
- })).filter(({ index }) => index !== -1);
15366
- deleteItemState(tempPayload);
15367
- addItemToState(finalPayload, finalData);
15368
- storeEvents.emit("tempEntityReconciled", {
15369
- tempId: tempPayload,
15370
- finalPayload
15371
- });
15372
- if (queryMemberships.length === 0) return;
15373
- store.produceState((draft) => {
15374
- for (const { queryKey, index } of queryMemberships) {
15375
- const query = notNullish(draft.queries[queryKey]);
15376
- const existingIndex = query.items.indexOf(finalItemKey);
15377
- if (existingIndex !== -1) query.items.splice(existingIndex, 1);
15378
- query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
15379
- }
15380
- }, { action: "offline-reconcile-temp-item" });
15381
- touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
15382
- for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
15383
- },
15384
- captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
15385
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15386
- captureOfflineOverlays(entityRefs.flatMap((ref) => {
15387
- return ref.entityKind === "item" ? [ref.entityKey] : [];
15388
- }));
15389
- },
15390
- rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
15391
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15392
- rebindOfflineOverlays(itemKeyRewrites);
15393
- },
15394
- syncEntityOverlays: ({ entities, sessionKey }) => {
15395
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15396
- const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
15397
- offlineOverlayStore.produceState((draft) => {
15398
- for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
15399
- });
15400
- }
15016
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
15017
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15018
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
15019
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
15020
+ }));
15021
+ },
15022
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
15023
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15024
+ rebindOfflineOverlays(itemKeyRewrites);
15025
+ },
15026
+ syncEntityOverlays: ({ entities, sessionKey }) => {
15027
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15028
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
15029
+ offlineOverlayStore.produceState((draft) => {
15030
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
15031
+ });
15401
15032
  }
15402
- });
15033
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime));
15403
15034
  function applyLoadedFieldsFromSnapshot(draft, itemKey, loadedFields) {
15404
15035
  if (loadedFields.length > 0) {
15405
15036
  const existingLoadedFields = draft.itemLoadedFields[itemKey] ?? [];
@@ -15438,16 +15069,12 @@ function createListQueryStore(storeOptions) {
15438
15069
  offlineOverlayStore.setState({});
15439
15070
  }
15440
15071
  function rebindOfflineOverlays(itemKeyRewrites) {
15441
- rebindOfflineOverlayEntries({
15442
- itemKeyRewrites,
15443
- overlayStore: offlineOverlayStore,
15444
- createReboundOverlay: ({ existingOverlay, nextItemKey }) => ({
15445
- item: existingOverlay.item ?? null,
15446
- itemPayload: store.state.itemQueries[nextItemKey]?.payload ?? existingOverlay.itemPayload,
15447
- queryMemberships: existingOverlay.queryMemberships,
15448
- keepVisibleWhileResolutionRequired: true
15449
- })
15450
- });
15072
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
15073
+ item: existingOverlay.item ?? null,
15074
+ itemPayload: store.state.itemQueries[nextItemKey]?.payload ?? existingOverlay.itemPayload,
15075
+ queryMemberships: existingOverlay.queryMemberships,
15076
+ keepVisibleWhileResolutionRequired: true
15077
+ }));
15451
15078
  }
15452
15079
  function captureOfflineOverlays(itemKeys) {
15453
15080
  const targetItemKeySet = new Set(itemKeys);
@@ -15460,18 +15087,14 @@ function createListQueryStore(storeOptions) {
15460
15087
  if (!queryMemberships) continue;
15461
15088
  queryMemberships[queryKey] = index;
15462
15089
  }
15463
- captureOfflineOverlayEntries({
15464
- itemKeys: [...targetItemKeySet],
15465
- overlayStore: offlineOverlayStore,
15466
- createOverlay: (itemKey) => {
15467
- const item = store.state.items[itemKey];
15468
- const itemPayload = store.state.itemQueries[itemKey]?.payload;
15469
- return {
15470
- item: item == null ? null : klona(item),
15471
- itemPayload: itemPayload === void 0 ? void 0 : klona(itemPayload),
15472
- queryMemberships: queryMembershipsByItemKey.get(itemKey) ?? {}
15473
- };
15474
- }
15090
+ captureOfflineOverlayEntries(offlineOverlayStore, [...targetItemKeySet], (itemKey) => {
15091
+ const item = store.state.items[itemKey];
15092
+ const itemPayload = store.state.itemQueries[itemKey]?.payload;
15093
+ return {
15094
+ item: item == null ? null : klona(item),
15095
+ itemPayload: itemPayload === void 0 ? void 0 : klona(itemPayload),
15096
+ queryMemberships: queryMembershipsByItemKey.get(itemKey) ?? {}
15097
+ };
15475
15098
  });
15476
15099
  }
15477
15100
  function isQueryProtectedFromEviction(queryKey, query) {
@@ -15586,10 +15209,6 @@ function createListQueryStore(storeOptions) {
15586
15209
  return false;
15587
15210
  }
15588
15211
  function handleRemoteBrowserTabsMessage(message) {
15589
- if (message.kind === "tab-status") {
15590
- browserTabsPriority?.onTabStatusMessage(message.tabId, message);
15591
- return;
15592
- }
15593
15212
  if (message.kind === "fetch-start") {
15594
15213
  syncRemoteFetchStart(message.targetKey, message.requestIds, message.startedAt);
15595
15214
  return;
@@ -15631,22 +15250,6 @@ function createListQueryStore(storeOptions) {
15631
15250
  }
15632
15251
  applyRemoteQuerySnapshot(message);
15633
15252
  }
15634
- ({coordinator: browserTabsSync, priority: browserTabsPriority} = createBrowserTabsCoordinatorWithPriority({
15635
- storeType: "listQuery",
15636
- storeKey: id,
15637
- getSessionKey: getSessionKeyForRuntime,
15638
- onMessage: handleRemoteBrowserTabsMessage,
15639
- onSessionChange() {
15640
- lastQuerySyncVersions.clear();
15641
- lastItemSyncVersions.clear();
15642
- clearOfflineOverlays();
15643
- },
15644
- transportFactory: testOptions?.browserTabsTransportFactory,
15645
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
15646
- getWindowIsFocused,
15647
- onWindowFocusChange: testOptions?.onWindowFocusChange,
15648
- priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
15649
- }));
15650
15253
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
15651
15254
  const offlineEntities = useOfflineStoreEntities({
15652
15255
  sessionKey: getSessionKeyForRuntime(),
@@ -15702,43 +15305,23 @@ function createListQueryStore(storeOptions) {
15702
15305
  function useFindItem$1(findItemFn, options = {}) {
15703
15306
  return useFindItem(findItemFn, options, store, registerActiveStandaloneItems, touchItems);
15704
15307
  }
15705
- const focusLifecycle = createStoreFocusLifecycle({
15706
- revalidateOnWindowFocus: resolvedRevalidateOnWindowFocus,
15707
- usesRealTimeUpdates,
15708
- transportReconnectCooldownMs,
15709
- getWindowIsFocused,
15710
- onWindowFocus: testOptions?.onWindowFocus ?? onWindowFocus,
15711
- onWindowFocusRevalidate: () => {
15712
- invalidateQueryAndItems({
15713
- all: true,
15714
- type: "lowPriority"
15715
- });
15716
- },
15717
- onTransportReconnectRevalidate: () => {
15718
- invalidateQueryAndItems({
15719
- all: true,
15720
- type: "realtimeUpdate"
15721
- });
15722
- }
15723
- });
15724
- const { enforceCacheLimits } = createListQueryCacheLimits({
15725
- store,
15726
- maxItems,
15727
- maxQueries,
15728
- itemCacheRuntime,
15729
- queryCacheRuntime,
15730
- isQueryProtectedFromEviction,
15731
- isStandaloneItemProtectedFromEviction,
15732
- cleanupItemStateMetadata,
15733
- cleanupQueryStateMetadata,
15734
- deleteQueryFetchResources,
15735
- deleteItemFetchResources,
15736
- onStateCleanup
15737
- });
15738
- const cacheLimitEnforcementScheduler = createIdleThrottledScheduler({
15739
- throttleMs: CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS,
15740
- run: enforceCacheLimits
15741
- });
15308
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
15309
+ invalidateQueryAndItems({
15310
+ all: true,
15311
+ type: "lowPriority"
15312
+ });
15313
+ }, () => {
15314
+ invalidateQueryAndItems({
15315
+ all: true,
15316
+ type: "realtimeUpdate"
15317
+ });
15318
+ }, import.meta.env.DEV ? {
15319
+ debugLogger: storeManager.debugLogger,
15320
+ storeId: id,
15321
+ storeType: "listQuery"
15322
+ } : void 0);
15323
+ const { enforceCacheLimits } = createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup);
15324
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
15742
15325
  function scheduleCacheLimitEnforcement() {
15743
15326
  cacheLimitEnforcementScheduler.schedule();
15744
15327
  }
@@ -15778,7 +15361,6 @@ function createListQueryStore(storeOptions) {
15778
15361
  queryCacheRuntime.clearAll();
15779
15362
  itemCacheRuntime.clearAll();
15780
15363
  cacheLimitEnforcementScheduler.cancel();
15781
- browserTabsPriority?.reset();
15782
15364
  persistence?.dispose();
15783
15365
  persistence?.clear();
15784
15366
  store.setState(persistence?.createInitialState({
@@ -15810,8 +15392,7 @@ function createListQueryStore(storeOptions) {
15810
15392
  queryCacheRuntime.clearAll();
15811
15393
  itemCacheRuntime.clearAll();
15812
15394
  cacheLimitEnforcementScheduler.cancel();
15813
- browserTabsSync?.close();
15814
- browserTabsPriority?.close();
15395
+ browserTabsSync.close();
15815
15396
  focusLifecycle.dispose();
15816
15397
  persistence?.dispose();
15817
15398
  offlineController?.dispose();