tsdf 17.0.1 → 17.0.3

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,7 +1,8 @@
1
- import { $ as scheduleIdleCleanup, A as getIsOfflineModeFromStatus, B as createCompactLocalStorageEntry, C as isQuotaExceededError, D as OfflineResolutionConflictParseError, E as serializeJsonForStorage, F as clearSessionProtectedKeysSnapshot, G as getPayloadRecordKey, I as getSessionProtectedKeysSnapshot, L as setSessionProtectedKeysSnapshot, M as isOfflineModeStatusValue, N as offlineItemEntityRefSchema, O as compactOfflineStatusSnapshotSchema, P as offlineResolutionRecordSchema, Q as createIdleCleanupContext, R as getNavigatorLockManager, S as getSerializedStringSize, T as keepEntriesWithinByteBudgetDuringIdle, V as parseCompactLocalStorageEntry, X as serializeProtectedRef, Y as parsePersistedAsyncNamespaceKind, Z as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, _ as getTSDFDebugTimingMs, a as estimateManagedAsyncStorageEntrySizeBytes, b as createShouldIgnoreItemPredicate, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as emitTSDFDebugLog, h as logPersistentStorageQuotaCleanup, j as isModeEffectivelyActive, k as defaultOfflineRuntimeConfig, l as registerAsyncStartupStoreCleanup, m as getOfflineSessionStatusStorageKey, o as getProtectedKeysFromMetadata, p as OFFLINE_SESSION_STATUS_STORE_NAME, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as resolveTSDFLogger, w as keepEntriesWithinByteBudget, x as createTimedKeySet, y as getDefaultMaxBytesForScope, z as warnIfNavigatorLockUnavailable } from "./asyncStorageAdapter-BuGjbXYA.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-D_k77Srq.js";
1
+ import { A as serializeJsonForStorage, B as getSessionProtectedKeysSnapshot, C as createShouldIgnoreItemPredicate, D as keepEntriesWithinByteBudget, E as isQuotaExceededError, F as isModeEffectivelyActive, G as parseCompactLocalStorageEntry, H as getNavigatorLockManager, I as isOfflineModeStatusValue, L as offlineItemEntityRefSchema, M as compactOfflineStatusSnapshotSchema, N as defaultOfflineRuntimeConfig, O as keepEntriesWithinByteBudgetDuringIdle, P as getIsOfflineModeFromStatus, R as offlineResolutionRecordSchema, S as getDefaultMaxBytesForScope, T as getSerializedStringSize, U as warnIfNavigatorLockUnavailable, V as setSessionProtectedKeysSnapshot, W as createCompactLocalStorageEntry, Y as getPayloadRecordKey, _ as getOfflineSessionStatusStorageKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, c as isAsyncStorageMetadataOfflineProtected, d as registerAsyncStartupStoreCleanup, et as parsePersistedAsyncNamespaceKind, f as removeAsyncStorageNamespaceEntriesIfUnchanged, g as OFFLINE_SESSION_STATUS_STORE_NAME, h as parseAsyncStorageNamespaceKind, it as scheduleIdleCleanup, j as OfflineResolutionConflictParseError, k as removeAsyncMaintenanceEntriesIfUnchanged, l as mergeManagedAsyncStorageCustomMetadata, m as unregisterAsyncStartupStoreCleanup, nt as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, o as getAsyncStorageMaintenanceRemoveBatchSize, p as serializeProtectedRef$1, r as buildPersistedStaticPolicy, rt as createIdleCleanupContext, s as getProtectedKeysFromMetadata, tt as serializeProtectedRef, u as readAsyncStorageNamespaceIndexStateUsingDriver, v as logPersistentStorageQuotaCleanup, w as createTimedKeySet, x as resolveTSDFLogger, y as emitTSDFDebugLog, z as clearSessionProtectedKeysSnapshot } from "./asyncStorageAdapter-URS9eulL.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-JsSCNBTr.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
+ import { deepEqual } from "@ls-stack/utils/deepEqual";
5
6
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
6
7
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
7
8
  import { evtmitter } from "evtmitter";
@@ -14,8 +15,8 @@ import { useConst } from "@ls-stack/react-utils/useConst";
14
15
  import { useLatestValue } from "@ls-stack/react-utils/useLatestValue";
15
16
  import { useTimeout } from "@ls-stack/react-utils/useTimeout";
16
17
  import { isObject, isPromise } from "@ls-stack/utils/typeGuards";
17
- import { deepEqual } from "@ls-stack/utils/deepEqual";
18
18
  import { rc_array, rc_boolean, rc_literals, rc_number, rc_object, rc_parse, rc_parse_json, rc_record, rc_string, rc_union, rc_unknown } from "runcheck";
19
+ import { typedObjectKeys } from "@ls-stack/utils/typingFnUtils";
19
20
  import { createAsyncQueue } from "@ls-stack/utils/asyncQueue";
20
21
  import { awaitDebounce } from "@ls-stack/utils/awaitDebounce";
21
22
  import { useOnEvtmitterEvent } from "@evtmitter/react";
@@ -2096,17 +2097,22 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2096
2097
  if (sessionKey === false) return false;
2097
2098
  return `${getStorageKey(sessionKey, config.storeName)}.${config.entryPrefix}.`;
2098
2099
  }
2099
- function getAsyncNamespace() {
2100
+ function getAsyncNamespaceScope() {
2100
2101
  if (asyncAdapter === null) return null;
2101
2102
  const sessionKey = config.getSessionKey();
2102
2103
  if (sessionKey === false) return null;
2103
2104
  asyncAdapter.debugLogger = config.debugLogger;
2104
2105
  asyncAdapter.logger = config.logger;
2105
- return asyncAdapter.openNamespace({
2106
+ return {
2106
2107
  sessionKey,
2107
2108
  storeName: config.storeName,
2108
2109
  kind: asyncNamespaceKind
2109
- });
2110
+ };
2111
+ }
2112
+ function getAsyncNamespace() {
2113
+ const scope = getAsyncNamespaceScope();
2114
+ if (asyncAdapter === null || scope === null) return null;
2115
+ return asyncAdapter.openNamespace(scope);
2110
2116
  }
2111
2117
  if (asyncAdapter !== null) getAsyncNamespace();
2112
2118
  async function commit(args) {
@@ -2118,17 +2124,17 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2118
2124
  } : void 0;
2119
2125
  try {
2120
2126
  if (asyncAdapter !== null) {
2121
- const namespace = getAsyncNamespace();
2122
- if (!namespace) {
2127
+ const scope = getAsyncNamespaceScope();
2128
+ if (scope === null) {
2123
2129
  if (import.meta.env.DEV) logPersistentStorageOperation(debugContext, "commit", "skipped", startTime, {
2124
2130
  ...operationDetails,
2125
2131
  reason: "inactive-session"
2126
2132
  });
2127
2133
  return;
2128
2134
  }
2129
- await namespace.commit({
2135
+ const asyncArgs = {
2130
2136
  removes: args.removes,
2131
- staticPolicy: args.staticPolicy,
2137
+ ..."staticPolicy" in args ? { staticPolicy: args.staticPolicy } : {},
2132
2138
  touches: args.touches,
2133
2139
  upserts: args.upserts?.map((upsert) => ({
2134
2140
  key: upsert.key,
@@ -2144,7 +2150,8 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2144
2150
  version: asyncVersion,
2145
2151
  metadata: upsert.metadata ?? getManifestMeta?.(upsert.data, upsert.key)
2146
2152
  }))
2147
- });
2153
+ };
2154
+ await asyncAdapter.openNamespace(scope).commit(asyncArgs);
2148
2155
  if (import.meta.env.DEV) logPersistentStorageOperation(debugContext, "commit", "success", startTime, operationDetails);
2149
2156
  return;
2150
2157
  }
@@ -2650,8 +2657,32 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2650
2657
  }
2651
2658
  }
2652
2659
  function dispose() {}
2660
+ function getAsyncAdapter() {
2661
+ return asyncAdapter;
2662
+ }
2663
+ async function removeEntriesIfUnchanged(entries, removeEntries) {
2664
+ const scope = getAsyncNamespaceScope();
2665
+ if (asyncAdapter === null || scope === null) return null;
2666
+ const startTime = import.meta.env.DEV ? startPersistentStorageDebugTiming(debugContext) : null;
2667
+ const operationDetails = import.meta.env.DEV ? {
2668
+ removes: entries.length,
2669
+ touches: 0,
2670
+ upserts: 0
2671
+ } : void 0;
2672
+ try {
2673
+ const staleKeys = await removeEntries(asyncAdapter, scope, entries);
2674
+ if (import.meta.env.DEV) logPersistentStorageOperation(debugContext, "commit", "success", startTime, operationDetails);
2675
+ return staleKeys;
2676
+ } catch (error) {
2677
+ if (import.meta.env.DEV) logPersistentStorageOperation(debugContext, "commit", "error", startTime, operationDetails, error);
2678
+ onPersistentStorageError?.(error);
2679
+ return null;
2680
+ }
2681
+ }
2653
2682
  return {
2683
+ getAsyncAdapter,
2654
2684
  commit,
2685
+ removeEntriesIfUnchanged,
2655
2686
  readEntry,
2656
2687
  load,
2657
2688
  loadMany,
@@ -2758,7 +2789,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2758
2789
  }
2759
2790
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2760
2791
  async function clearAllSessionStorage(sessionKey) {
2761
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-ClUvxNQA.js");
2792
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Bxrrj_Mt.js");
2762
2793
  await Promise.all([
2763
2794
  clearSessionStorage(sessionKey, "local-sync"),
2764
2795
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -2808,6 +2839,7 @@ function scheduleAsyncStorageMaintenance(maintenanceKey, callback) {
2808
2839
  if (existing.cancel !== null) return;
2809
2840
  }
2810
2841
  const entry = existing ?? {
2842
+ activeContext: null,
2811
2843
  cancel: null,
2812
2844
  callback,
2813
2845
  running: false,
@@ -2815,11 +2847,16 @@ function scheduleAsyncStorageMaintenance(maintenanceKey, callback) {
2815
2847
  };
2816
2848
  entry.callback = callback;
2817
2849
  scheduledAsyncMaintenance.set(maintenanceKey, entry);
2818
- entry.cancel = scheduleIdleCleanup(() => {
2850
+ entry.cancel = scheduleIdleCleanup((deadline) => {
2819
2851
  entry.cancel = null;
2820
2852
  entry.running = true;
2821
- entry.callback().finally(() => {
2853
+ const context = createIdleCleanupContext(deadline);
2854
+ entry.activeContext = context;
2855
+ entry.callback(context).finally(() => {
2856
+ context.cancel();
2857
+ if (entry.activeContext === context) entry.activeContext = null;
2822
2858
  entry.running = false;
2859
+ if (scheduledAsyncMaintenance.get(maintenanceKey) !== entry) return;
2823
2860
  if (entry.rerunRequested) {
2824
2861
  entry.rerunRequested = false;
2825
2862
  scheduleAsyncStorageMaintenance(maintenanceKey, entry.callback);
@@ -3298,33 +3335,59 @@ function setupCollectionPersistence(config, options = {}) {
3298
3335
  logByteBudgetCleanup("maintenance", filteredEntries.length, knownPersistedKeys, unprotectedBytes);
3299
3336
  return;
3300
3337
  }
3338
+ if (idleContext === void 0) return;
3339
+ const isSessionCurrent = () => config.getSessionKey() === sessionKey;
3301
3340
  const metadataEntries = await listAllPersistentStorageNamespaceMetadata(namespace, { order: "lru-desc" });
3302
- if (metadataEntries.length === 0) return;
3303
- const protectedItemKeys = getProtectedKeysFromMetadata(metadataEntries);
3304
- const invalidEntries = [];
3305
- const validEntries = [];
3306
- for (const entry of metadataEntries) {
3341
+ if (!isSessionCurrent()) {
3342
+ knownPersistedKeys = null;
3343
+ return;
3344
+ }
3345
+ if (idleContext.isCanceled() || metadataEntries.length === 0) return;
3346
+ const protectedItemKeys = /* @__PURE__ */ new Set();
3347
+ const removalEntries = [];
3348
+ const ignoredItemKeys = /* @__PURE__ */ new Set();
3349
+ const filteredEntries = [];
3350
+ for (const [entryIndex, entry] of metadataEntries.entries()) {
3351
+ if (entryIndex % MAINTENANCE_SCAN_CHUNK_SIZE$1 === 0 && !await idleContext.yieldIfNeeded()) return;
3352
+ if (isAsyncStorageMetadataOfflineProtected(entry.customMetadata)) protectedItemKeys.add(entry.key);
3307
3353
  const payload = validateWithSchema(config.payloadSchema, readManifestPayloadMeta(entry.customMetadata));
3308
- if (payload === null) invalidEntries.push({ itemKey: entry.key });
3309
- else validEntries.push({
3310
- itemKey: entry.key,
3311
- lastAccessAt: entry.lastAccessAt,
3312
- payload,
3354
+ if (payload === null) {
3355
+ removalEntries.push(entry);
3356
+ continue;
3357
+ }
3358
+ if (shouldIgnoreItem(payload)) {
3359
+ ignoredItemKeys.add(entry.key);
3360
+ removalEntries.push(entry);
3361
+ continue;
3362
+ }
3363
+ filteredEntries.push({
3364
+ entry,
3313
3365
  sizeBytes: rememberPersistedMetadataSize(entry.key, entry.sizeBytes)
3314
3366
  });
3315
3367
  }
3316
- if (invalidEntries.length > 0) await Promise.all(invalidEntries.map(({ itemKey }) => namespace.remove(itemKey)));
3317
- const ignoredEntries = validEntries.filter(({ payload }) => shouldIgnoreItem(payload));
3318
- if (ignoredEntries.length > 0) {
3319
- await Promise.all(ignoredEntries.map(({ itemKey }) => namespace.remove(itemKey)));
3320
- for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
3368
+ const byteBudgetResult = await keepEntriesWithinByteBudgetDuringIdle(filteredEntries, ({ entry }) => entry.key, ({ entry }) => entry.lastAccessAt, ({ sizeBytes }) => sizeBytes, ({ entry }) => pinnedItemKeys.has(entry.key), ({ entry }) => protectedItemKeys.has(entry.key), maxBytes, idleContext);
3369
+ if (byteBudgetResult === null) return;
3370
+ const { keptKeys, unprotectedBytes } = byteBudgetResult;
3371
+ const budgetEvictedItemKeys = /* @__PURE__ */ new Set();
3372
+ for (const { entry } of filteredEntries) {
3373
+ if (keptKeys.has(entry.key)) continue;
3374
+ budgetEvictedItemKeys.add(entry.key);
3375
+ removalEntries.push(entry);
3376
+ }
3377
+ const removalResult = await removeAsyncMaintenanceEntriesIfUnchanged(removalEntries, isAsyncStorageMetadataOfflineProtected, (entries) => namespace.removeEntriesIfUnchanged(entries, removeAsyncStorageNamespaceEntriesIfUnchanged), (removedKeys) => {
3378
+ for (const itemKey of removedKeys) if (ignoredItemKeys.has(itemKey) || budgetEvictedItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
3379
+ }, getAsyncStorageMaintenanceRemoveBatchSize(namespace.getAsyncAdapter()), isSessionCurrent, idleContext);
3380
+ if (!removalResult.completed) {
3381
+ if (!isSessionCurrent()) knownPersistedKeys = null;
3382
+ return;
3383
+ }
3384
+ if (removalResult.hasStaleEntries) {
3385
+ knownPersistedKeys = null;
3386
+ scheduleAsyncStorageMaintenance(`collection:${sessionKey}:${config.storeName}`, evictStoredItems);
3387
+ return;
3321
3388
  }
3322
- const filteredEntries = validEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
3323
- const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
3389
+ knownPersistedKeys = keptKeys;
3324
3390
  logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
3325
- await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
3326
- for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
3327
- knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
3328
3391
  }
3329
3392
  async function flushPersistedState() {
3330
3393
  if (!storeRef) return;
@@ -3969,7 +4032,12 @@ function createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMess
3969
4032
  ...message,
3970
4033
  ...meta
3971
4034
  });
3972
- transport.postMessage(typedMessage);
4035
+ try {
4036
+ transport.postMessage(typedMessage);
4037
+ } catch (error) {
4038
+ if (import.meta.env.DEV) console.warn(`[tsdf] Failed to sync a "${message.kind}" message of the ${storeType} store "${storeKey}" with other browser tabs`, error);
4039
+ return null;
4040
+ }
3973
4041
  if (import.meta.env.DEV) logBrowserTabsOperation("log", "publish", "published message", {
3974
4042
  messageId: typedMessage.messageId,
3975
4043
  messageKind: typedMessage.kind,
@@ -7590,6 +7658,11 @@ var RequestScheduler = class {
7590
7658
  const { phase, pending } = this.#state;
7591
7659
  return phase.type !== "idle" || pending.scheduledRequests.size > 0 || pending.rtuDelayed.size > 0 || pending.mediumPriorityDelayed.size > 0;
7592
7660
  }
7661
+ /** Whether the request has a fetch in flight, queued or delayed */
7662
+ hasPendingRequest(requestId) {
7663
+ const { phase, pending } = this.#state;
7664
+ return pending.scheduledRequests.has(requestId) || pending.rtuDelayed.has(requestId) || pending.mediumPriorityDelayed.has(requestId) || phase.type === "coalescing" && phase.pendingRequests.has(requestId) || phase.type === "fetching" && (phase.fetchingRequests.has(requestId) || phase.rtuAfterFetch.has(requestId));
7665
+ }
7593
7666
  get fetchIsInProgress() {
7594
7667
  return this.#state.phase.type === "fetching";
7595
7668
  }
@@ -7613,7 +7686,10 @@ var RequestScheduler = class {
7613
7686
  if (startTime > this.#state.timing.lastFetchStartTime) this.#state.timing.lastFetchStartTime = startTime;
7614
7687
  }
7615
7688
  syncExternalFetchStart(requestIds, startedAt) {
7616
- for (const requestId of requestIds) this.setLastFetchStartTimeForRequest(requestId, startedAt);
7689
+ for (const requestId of requestIds) {
7690
+ if (this.#state.pending.mutationsInProgress.has(requestId)) continue;
7691
+ this.setLastFetchStartTimeForRequest(requestId, startedAt);
7692
+ }
7617
7693
  }
7618
7694
  syncExternalFetchSuccess(requestIds, startedAt, duration) {
7619
7695
  const previousStartTime = this.#state.timing.lastFetchStartTime;
@@ -7661,7 +7737,7 @@ var RequestScheduler = class {
7661
7737
  request.awaitCallbacks.push(() => resolve());
7662
7738
  });
7663
7739
  }
7664
- if (this.#state.phase.type === "fetching") {
7740
+ if (this.#state.phase.type === "fetching" && this.#state.phase.fetchId > this.#state.abort.abortBoundary) {
7665
7741
  const fetchingRequest = this.#state.phase.fetchingRequests.get(requestId);
7666
7742
  if (fetchingRequest) await new Promise((resolve) => {
7667
7743
  fetchingRequest.awaitCallbacks.push(() => resolve());
@@ -7673,7 +7749,6 @@ var RequestScheduler = class {
7673
7749
  const { phase, pending, abort } = this.#state;
7674
7750
  const currentCount = pending.mutationsInProgress.get(requestId) ?? 0;
7675
7751
  pending.mutationsInProgress.set(requestId, currentCount + 1);
7676
- abort.abortBoundary = abort.lastFetchId;
7677
7752
  if (phase.type === "coalescing") {
7678
7753
  const request = phase.pendingRequests.get(requestId);
7679
7754
  if (request) {
@@ -7685,21 +7760,58 @@ var RequestScheduler = class {
7685
7760
  this.#state.phase = { type: "idle" };
7686
7761
  }
7687
7762
  }
7688
- if (phase.type === "fetching") {
7689
- if (phase.fetchingRequests.has(requestId) && abort.controller) {
7690
- abort.controller.abort();
7691
- abort.controller = null;
7763
+ if (phase.type === "fetching" && phase.fetchId > abort.abortBoundary && phase.fetchingRequests.has(requestId)) {
7764
+ abort.abortBoundary = phase.fetchId;
7765
+ abort.controller?.abort();
7766
+ abort.controller = null;
7767
+ const addedAt = Date.now();
7768
+ for (const [fetchingRequestId, request] of phase.fetchingRequests) {
7769
+ this.#state.lastAbortedRequests.add(fetchingRequestId);
7770
+ let retry = pending.scheduledRequests.get(fetchingRequestId);
7771
+ if (retry) {
7772
+ if (this.#coalescePayload) retry.payload = this.#coalescePayload(request.payload, retry.payload);
7773
+ retry.priority = getHigherPriorityFetchType(retry.priority, request.priority);
7774
+ retry.remoteStartCancelable = false;
7775
+ } else {
7776
+ retry = {
7777
+ payload: request.payload,
7778
+ priority: request.priority,
7779
+ addedAt,
7780
+ awaitCallbacks: [],
7781
+ remoteStartCancelable: false
7782
+ };
7783
+ pending.scheduledRequests.set(fetchingRequestId, retry);
7784
+ }
7785
+ retry.awaitCallbacks.push(...request.awaitCallbacks);
7786
+ request.awaitCallbacks.length = 0;
7692
7787
  }
7693
7788
  }
7694
- return () => this.#endMutation(requestId);
7789
+ const lockState = this.#state;
7790
+ let ended = false;
7791
+ return () => {
7792
+ if (ended || this.#state !== lockState) return false;
7793
+ ended = true;
7794
+ return this.#endMutation(requestId);
7795
+ };
7695
7796
  }
7696
- reset() {
7797
+ /** `markWaitersAborted` resolves callers awaiting the discarded requests as
7798
+ * aborted, for store resets where the cleared state says nothing about the
7799
+ * resource. Without it they read the store's current state, e.g. not found
7800
+ * for a deleted item. */
7801
+ reset(markWaitersAborted = false) {
7697
7802
  const { phase, pending, abort } = this.#state;
7698
7803
  if (phase.type === "coalescing") clearTimeout(phase.timeoutId);
7699
7804
  for (const rtu of pending.rtuDelayed.values()) clearTimeout(rtu.timeoutId);
7700
7805
  for (const delayed of pending.mediumPriorityDelayed.values()) clearTimeout(delayed.timeoutId);
7701
7806
  if (abort.controller) abort.controller.abort();
7807
+ const discardedRequests = [...pending.scheduledRequests];
7808
+ if (phase.type === "coalescing") discardedRequests.push(...phase.pendingRequests);
7809
+ else if (phase.type === "fetching") discardedRequests.push(...phase.fetchingRequests);
7702
7810
  this.#state = this.#createInitialState();
7811
+ for (const [requestId, request] of discardedRequests) {
7812
+ if (markWaitersAborted) this.#state.lastAbortedRequests.add(requestId);
7813
+ this.#finalizePendingRequestCallbacks(request, true);
7814
+ }
7703
7815
  }
7704
7816
  /** Re-evaluates the pending delayed realtime update fetch against the
7705
7817
  * current dynamic throttle, rescheduling it sooner (or firing it right away
@@ -7731,6 +7843,7 @@ var RequestScheduler = class {
7731
7843
  const scheduledRequest = this.#state.pending.scheduledRequests.get(requestId);
7732
7844
  if (!scheduledRequest || !matchesShouldCancel(shouldCancel, requestId, scheduledRequest)) continue;
7733
7845
  this.#state.pending.scheduledRequests.delete(requestId);
7846
+ this.#state.lastAbortedRequests.delete(requestId);
7734
7847
  this.#finalizePendingRequestCallbacks(scheduledRequest, false);
7735
7848
  wasCancelled = true;
7736
7849
  }
@@ -7767,6 +7880,7 @@ var RequestScheduler = class {
7767
7880
  if (!isExplicitCancel && !this.#isRemoteStartCancelable(request)) continue;
7768
7881
  if (!matchesShouldCancel(shouldCancel, requestId, request)) continue;
7769
7882
  this.#state.phase.pendingRequests.delete(requestId);
7883
+ if (isExplicitCancel) this.#state.lastAbortedRequests.delete(requestId);
7770
7884
  this.#finalizePendingRequestCallbacks(request, !isExplicitCancel);
7771
7885
  wasCancelled = true;
7772
7886
  }
@@ -7788,8 +7902,8 @@ var RequestScheduler = class {
7788
7902
  this.#addToScheduledRequests(requestId, payload, fetchType, startTime, remoteStartCancelable);
7789
7903
  return "scheduled";
7790
7904
  }
7791
- if (this.#state.phase.type === "fetching") if (this.#shouldCurrentFetchBeAborted()) this.#forceAbortCurrentFetch();
7792
- else {
7905
+ if (this.#state.phase.type === "fetching" && this.#shouldCurrentFetchBeAborted()) this.#forceAbortCurrentFetch();
7906
+ if (this.#state.phase.type === "fetching") {
7793
7907
  this.#addToScheduledRequests(requestId, payload, fetchType, startTime, remoteStartCancelable);
7794
7908
  return "scheduled";
7795
7909
  }
@@ -7880,8 +7994,22 @@ var RequestScheduler = class {
7880
7994
  const prevFetchStartTime = this.#state.timing.lastFetchStartTime;
7881
7995
  this.#state.timing.lastFetchStartTime = startTime;
7882
7996
  for (const requestId of requests.keys()) this.setLastFetchStartTimeForRequest(requestId, startTime);
7997
+ const { rtuDelayed, mediumPriorityDelayed } = this.#state.pending;
7998
+ for (const [requestId, request] of requests) {
7999
+ if (this.#coalescePayload) {
8000
+ const delayedRtu = rtuDelayed.get(requestId);
8001
+ if (delayedRtu) request.payload = this.#coalescePayload(delayedRtu.payload, request.payload);
8002
+ const delayedMedium = mediumPriorityDelayed.get(requestId);
8003
+ if (delayedMedium) request.payload = this.#coalescePayload(delayedMedium.payload, request.payload);
8004
+ }
8005
+ this.#clearRtuDelayed(requestId);
8006
+ this.#cancelMediumPriority(requestId);
8007
+ }
7883
8008
  const fetchingRequests = /* @__PURE__ */ new Map();
7884
- for (const [requestId, request] of requests) fetchingRequests.set(requestId, { awaitCallbacks: [...request.awaitCallbacks] });
8009
+ for (const [requestId, request] of requests) fetchingRequests.set(requestId, {
8010
+ ...request,
8011
+ awaitCallbacks: [...request.awaitCallbacks]
8012
+ });
7885
8013
  this.#state.phase = {
7886
8014
  type: "fetching",
7887
8015
  fetchId,
@@ -7889,10 +8017,6 @@ var RequestScheduler = class {
7889
8017
  fetchingRequests,
7890
8018
  rtuAfterFetch: /* @__PURE__ */ new Map()
7891
8019
  };
7892
- for (const requestId of requests.keys()) {
7893
- this.#clearRtuDelayed(requestId);
7894
- this.#cancelMediumPriority(requestId);
7895
- }
7896
8020
  const shouldAbort = this.#createShouldAbort(fetchId, requests, abortController);
7897
8021
  const batchRequests = Array.from(requests.entries()).map(([requestId, request]) => ({
7898
8022
  requestId,
@@ -7909,9 +8033,9 @@ var RequestScheduler = class {
7909
8033
  results = /* @__PURE__ */ new Map();
7910
8034
  for (const requestId of requests.keys()) results.set(requestId, false);
7911
8035
  }
7912
- this.#state.abort.controller = null;
8036
+ if (this.#state.abort.controller === abortController) this.#state.abort.controller = null;
7913
8037
  if (!this.#isCurrentFetch(fetchId)) {
7914
- this.#state.timing.lastFetchStartTime = prevFetchStartTime;
8038
+ if (this.#state.abort.lastFetchId === fetchId) this.#state.timing.lastFetchStartTime = prevFetchStartTime;
7915
8039
  return false;
7916
8040
  }
7917
8041
  if (Array.from(results.values()).some((value) => value)) this.#state.timing.lastFetchDuration = Date.now() - startTime;
@@ -7921,12 +8045,15 @@ var RequestScheduler = class {
7921
8045
  const wasAborted = this.#state.lastAbortedRequests.has(requestId);
7922
8046
  for (const callback of awaitCallbacks) callback(wasAborted);
7923
8047
  }
8048
+ this.#rescheduleRtuAfterFetch(rtuAfterFetch);
8049
+ this.#flushScheduledRequests();
8050
+ return true;
8051
+ }
8052
+ #rescheduleRtuAfterFetch(rtuAfterFetch) {
7924
8053
  for (const rtu of rtuAfterFetch.values()) if (!this.#scheduleDelayedRTU(Date.now(), rtu.requestId, rtu.payload, rtu.remoteStartCancelable)) {
7925
8054
  this.#onEvent?.("scheduled-rt-fetch-started");
7926
8055
  this.#scheduleRequest(rtu.requestId, "highPriority", rtu.payload, void 0, rtu.remoteStartCancelable);
7927
8056
  }
7928
- this.#flushScheduledRequests();
7929
- return true;
7930
8057
  }
7931
8058
  #endMutation(requestId) {
7932
8059
  const currentCount = this.#state.pending.mutationsInProgress.get(requestId);
@@ -8159,6 +8286,8 @@ var RequestScheduler = class {
8159
8286
  for (const requestId of phase.fetchingRequests.keys()) this.#state.lastAbortedRequests.add(requestId);
8160
8287
  for (const [, { awaitCallbacks }] of phase.fetchingRequests) for (const callback of awaitCallbacks) callback(true);
8161
8288
  this.#state.phase = { type: "idle" };
8289
+ this.#rescheduleRtuAfterFetch(phase.rtuAfterFetch);
8290
+ this.#flushScheduledRequests();
8162
8291
  }
8163
8292
  #createShouldAbort(fetchId, requests, abortController) {
8164
8293
  return function shouldAbort() {
@@ -8167,8 +8296,10 @@ var RequestScheduler = class {
8167
8296
  const anyMutation = Array.from(requests.keys()).some((reqId) => pending.mutationsInProgress.has(reqId));
8168
8297
  const shouldAbortNow = shouldAbortFetch || anyMutation;
8169
8298
  if (shouldAbortNow) {
8170
- this.#state.lastFetchWasAborted = true;
8171
- for (const requestId of requests.keys()) this.#state.lastAbortedRequests.add(requestId);
8299
+ if (this.#isCurrentFetch(fetchId)) {
8300
+ this.#state.lastFetchWasAborted = true;
8301
+ for (const requestId of requests.keys()) this.#state.lastAbortedRequests.add(requestId);
8302
+ }
8172
8303
  abortController.abort();
8173
8304
  }
8174
8305
  return shouldAbortNow;
@@ -8364,32 +8495,131 @@ function validateStoreManagerSessionConsistency(storeName, offlineSession, getSe
8364
8495
  return sessionKey;
8365
8496
  }
8366
8497
  //#endregion
8498
+ //#region src/utils/optimisticMutationTracker.ts
8499
+ /**
8500
+ * Tracks the optimistic mutations of each entity, so a failed one can tell
8501
+ * whether a newer one may have been saved without changing the local state
8502
+ * (e.g. saving the same value), which reverting the failed one would
8503
+ * contradict. Mutations that fail or are skipped don't count.
8504
+ */
8505
+ function createOptimisticMutationTracker() {
8506
+ const entities = /* @__PURE__ */ new Map();
8507
+ return {
8508
+ start(key, mutationId) {
8509
+ const entity = entities.get(key);
8510
+ if (entity) entity.active.add(mutationId);
8511
+ else entities.set(key, {
8512
+ active: new Set([mutationId]),
8513
+ lastSucceededId: 0
8514
+ });
8515
+ },
8516
+ /**
8517
+ * Whether an optimistic mutation other than `selfId`, started after
8518
+ * `sinceId`, succeeded or is still in flight. `sinceId` is older than
8519
+ * `selfId` when the failing mutation reverts the updates of the debounced
8520
+ * calls it superseded.
8521
+ */
8522
+ hasNewer(key, sinceId, selfId) {
8523
+ const entity = entities.get(key);
8524
+ if (!entity) return false;
8525
+ if (entity.lastSucceededId > sinceId) return true;
8526
+ for (const id of entity.active) if (id > sinceId && id !== selfId) return true;
8527
+ return false;
8528
+ },
8529
+ /** Whether an optimistic mutation other than `selfId` is in flight */
8530
+ hasOtherInFlight(key, selfId) {
8531
+ const entity = entities.get(key);
8532
+ if (!entity) return false;
8533
+ for (const id of entity.active) if (id !== selfId) return true;
8534
+ return false;
8535
+ },
8536
+ /** `succeeded` is whether the server accepted the mutation */
8537
+ end(key, mutationId, succeeded) {
8538
+ const entity = entities.get(key);
8539
+ if (!entity?.active.delete(mutationId)) return;
8540
+ if (entity.active.size === 0) entities.delete(key);
8541
+ else if (succeeded) entity.lastSucceededId = Math.max(entity.lastSucceededId, mutationId);
8542
+ }
8543
+ };
8544
+ }
8545
+ //#endregion
8546
+ //#region src/utils/optimisticRollback.ts
8547
+ function revertFields(current, before, after) {
8548
+ const value = { ...current };
8549
+ let restored = false;
8550
+ let changed = false;
8551
+ for (const key of typedObjectKeys(after)) {
8552
+ if (before[key] === after[key]) continue;
8553
+ if (current[key] === after[key]) {
8554
+ value[key] = before[key];
8555
+ restored = true;
8556
+ } else changed = true;
8557
+ }
8558
+ return {
8559
+ value: restored ? value : current,
8560
+ changed
8561
+ };
8562
+ }
8563
+ /**
8564
+ * Reverts the change an optimistic update made to an entity (`before` ->
8565
+ * `after`) on top of its `current` value, one level deep and by reference:
8566
+ * fields still equal to `after` are restored and fields the update didn't
8567
+ * touch keep their current value. A field changed again since the update is
8568
+ * kept and reported as `changed`, so the caller can revalidate the entity.
8569
+ */
8570
+ function revertOptimisticChange(current, before, after) {
8571
+ if (current === after) return {
8572
+ value: before,
8573
+ changed: false
8574
+ };
8575
+ if (before === after) return {
8576
+ value: current,
8577
+ changed: false
8578
+ };
8579
+ if (!current || !before || !after) return {
8580
+ value: current,
8581
+ changed: true
8582
+ };
8583
+ return revertFields(current, before, after);
8584
+ }
8585
+ //#endregion
8367
8586
  //#region src/utils/performMutation.ts
8368
- async function performMutationWithLifecycle(startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose) {
8587
+ async function performMutationWithLifecycle(startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose, pendingDebounceRollbacks) {
8369
8588
  const endMutation = startMutation();
8370
- if (optimisticUpdate?.() === false) {
8371
- endMutation();
8372
- return Result.err(mutationSkipped);
8373
- }
8374
8589
  let unblockWindowClose = null;
8590
+ let rollbacks = [];
8591
+ let mutationSucceeded = false;
8375
8592
  try {
8593
+ if (optimisticUpdate?.((rollback) => {
8594
+ rollbacks.push(rollback);
8595
+ }) === false) {
8596
+ endMutation();
8597
+ return Result.err(mutationSkipped);
8598
+ }
8376
8599
  if (debounce) {
8377
8600
  unblockWindowClose = blockWindowClose?.().unblock ?? null;
8601
+ const debounceKey = getCompositeKey([debounce.context, debounce.payload]);
8602
+ const groupRollbacks = pendingDebounceRollbacks.get(debounceKey) ?? [];
8603
+ groupRollbacks.push(...rollbacks);
8604
+ pendingDebounceRollbacks.set(debounceKey, groupRollbacks);
8378
8605
  if (await awaitDebounce({
8379
- callId: [debounce.context, debounce.payload],
8606
+ callId: debounceKey,
8380
8607
  debounce: debounce.ms
8381
8608
  }) === "skip") {
8382
8609
  endMutation();
8383
8610
  return Result.err(mutationSkipped);
8384
8611
  }
8612
+ pendingDebounceRollbacks.delete(debounceKey);
8613
+ rollbacks = groupRollbacks;
8385
8614
  }
8386
8615
  const result = await mutation();
8616
+ mutationSucceeded = true;
8387
8617
  endMutation();
8388
- onSuccess?.(result);
8618
+ onSuccess?.(result, rollbacks);
8389
8619
  return Result.ok(result);
8390
8620
  } catch (exception) {
8391
8621
  endMutation();
8392
- return Result.err(onError(exception));
8622
+ return Result.err(onError(exception, mutationSucceeded ? [] : rollbacks));
8393
8623
  } finally {
8394
8624
  unblockWindowClose?.();
8395
8625
  }
@@ -8637,6 +8867,10 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8637
8867
  const payloads = requests.map((r) => r.payload);
8638
8868
  const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__"));
8639
8869
  if (!fetchResult.ok) {
8870
+ if (fetchCtx.shouldAbort()) {
8871
+ for (const { requestId } of requests) results.set(requestId, false);
8872
+ return results;
8873
+ }
8640
8874
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
8641
8875
  store.produceState((draft) => {
8642
8876
  for (const { requestId: itemId } of requests) {
@@ -8772,29 +9006,29 @@ function getPayloadDebounceOptions(debouncePayload) {
8772
9006
  trailing: true
8773
9007
  };
8774
9008
  }
8775
- function assertNoEnsureIsLoadedWithDebouncePayload(hookName, ensureIsLoaded, debouncePayload) {
8776
- if (!import.meta.env.PROD && ensureIsLoaded && shouldDebouncePayload(debouncePayload)) throw new Error(`${hookName} does not support using ensureIsLoaded together with debouncePayload.`);
9009
+ function assertNoRequireFreshDataWithDebouncePayload(hookName, requireFreshData, debouncePayload) {
9010
+ if (!import.meta.env.PROD && requireFreshData && shouldDebouncePayload(debouncePayload)) throw new Error(`${hookName} does not support using requireFreshData together with debouncePayload.`);
8777
9011
  }
8778
9012
  //#endregion
8779
- //#region src/utils/useEnsureIsLoaded.ts
8780
- function useEnsureIsLoaded(ensureIsLoaded, enabled, forceFetch) {
8781
- const isLoadedEvtEmitter = useConst(() => evtmitter());
8782
- const [isForceLoading, setIsForceLoading] = useState(true);
8783
- useOnChange(ensureIsLoaded && isForceLoading && enabled, ({ current }) => {
9013
+ //#region src/utils/useRequireFreshData.ts
9014
+ function useRequireFreshData(requireFreshData, enabled, forceFetch) {
9015
+ const refreshSettledEvtEmitter = useConst(() => evtmitter());
9016
+ const [isWaitingForRefresh, setIsWaitingForRefresh] = useState(true);
9017
+ useOnChange(requireFreshData && isWaitingForRefresh && enabled, ({ current }) => {
8784
9018
  if (current) forceFetch();
8785
9019
  }, { callOnMount: true });
8786
- useOnEvtmitterEvent(isLoadedEvtEmitter, "isLoaded", ({ payload: isLoaded }) => {
8787
- if (ensureIsLoaded && enabled && isLoaded) setIsForceLoading(false);
9020
+ useOnEvtmitterEvent(refreshSettledEvtEmitter, "refreshSettled", ({ payload: refreshSettled }) => {
9021
+ if (requireFreshData && enabled && refreshSettled) setIsWaitingForRefresh(false);
8788
9022
  });
8789
9023
  function useModifyResult(result) {
8790
- return useGetModifyResult(result, ensureIsLoaded, enabled, isForceLoading);
9024
+ return useGetModifyResult(result, requireFreshData, enabled, isWaitingForRefresh);
8791
9025
  }
8792
- return [useModifyResult, () => isLoadedEvtEmitter.emit("isLoaded", true)];
9026
+ return [useModifyResult, () => refreshSettledEvtEmitter.emit("refreshSettled", true)];
8793
9027
  }
8794
- function useGetModifyResult(result, ensureIsLoaded, enabled, isForceLoading) {
9028
+ function useGetModifyResult(result, requireFreshData, enabled, isWaitingForRefresh) {
8795
9029
  return useMemo(() => {
8796
- if (ensureIsLoaded) {
8797
- const newStatus = enabled && isForceLoading ? "loading" : result.status;
9030
+ if (requireFreshData) {
9031
+ const newStatus = enabled && isWaitingForRefresh ? "loading" : result.status;
8798
9032
  return {
8799
9033
  ...result,
8800
9034
  isLoading: newStatus === "loading",
@@ -8803,18 +9037,18 @@ function useGetModifyResult(result, ensureIsLoaded, enabled, isForceLoading) {
8803
9037
  }
8804
9038
  return result;
8805
9039
  }, [
8806
- ensureIsLoaded,
8807
- isForceLoading,
9040
+ requireFreshData,
9041
+ isWaitingForRefresh,
8808
9042
  result,
8809
9043
  enabled
8810
9044
  ]);
8811
9045
  }
8812
9046
  //#endregion
8813
9047
  //#region src/collectionStore/useItem.ts
8814
- function useItem$1(payload, { omitPayload, selector, ensureIsLoaded, returnRefetchingStatus, disableRefetches, disableRefetchOnMount, returnIdleStatus, isOffScreen, debouncePayload }, store, scheduleFetch, useMultipleItems) {
9048
+ function useItem$1(payload, { omitPayload, selector, requireFreshData, returnRefetchingStatus, disableRefetches, disableRefetchOnMount, returnIdleStatus, isOffScreen, debouncePayload }, store, scheduleFetch, useMultipleItems) {
8815
9049
  const isInvalidPayload = payload === "";
8816
9050
  const hasPayload = payload !== false && payload !== null && payload !== void 0 && payload !== "";
8817
- assertNoEnsureIsLoadedWithDebouncePayload("useItem", ensureIsLoaded, debouncePayload);
9051
+ assertNoRequireFreshDataWithDebouncePayload("useItem", requireFreshData, debouncePayload);
8818
9052
  const query = useMemo(() => hasPayload ? [{
8819
9053
  payload,
8820
9054
  omitPayload,
@@ -8861,15 +9095,15 @@ function useItem$1(payload, { omitPayload, selector, ensureIsLoaded, returnRefet
8861
9095
  selector
8862
9096
  ]);
8863
9097
  const fetchQuery = hasPayload ? query[0] : void 0;
8864
- const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(ensureIsLoaded, hasPayload, () => {
9098
+ const [useModifyResult, markRefreshSettled] = useRequireFreshData(requireFreshData, hasPayload, () => {
8865
9099
  if (fetchQuery) scheduleFetch("highPriority", fetchQuery.payload);
8866
9100
  });
8867
9101
  useSubscribeToStore(store, ({ observe }) => {
8868
- if (!ensureIsLoaded || !hasPayload || !result.itemStateKey) return;
9102
+ if (!requireFreshData || !hasPayload || !result.itemStateKey) return;
8869
9103
  observe.ifSelector((state) => {
8870
9104
  return state[result.itemStateKey]?.status;
8871
9105
  }).change.then(({ current }) => {
8872
- if (current === "success" || current === "error") emitIsLoadedEvt();
9106
+ if (current === "success" || current === "error") markRefreshSettled();
8873
9107
  });
8874
9108
  });
8875
9109
  return useModifyResult(result);
@@ -9195,6 +9429,13 @@ function createCollectionStore(storeOptions) {
9195
9429
  let remoteApplyDepth = 0;
9196
9430
  let currentBroadcastConsistency = "confirmed";
9197
9431
  const lastCollectionSyncVersions = /* @__PURE__ */ new Map();
9432
+ /**
9433
+ * Latest confirmed sibling-tab snapshot per item that was ignored because a
9434
+ * local mutation was in flight. Once the item's last mutation ends, it is
9435
+ * revalidated unless the local state already matches the snapshot, so the
9436
+ * tabs converge again.
9437
+ */
9438
+ const ignoredConfirmedSnapshots = /* @__PURE__ */ new Map();
9198
9439
  const offlineOverlayStore = new Store({
9199
9440
  debugName: `${id}:collection-offline-overlays`,
9200
9441
  state: () => ({})
@@ -9565,6 +9806,7 @@ function createCollectionStore(storeOptions) {
9565
9806
  if (!isBrowserTabsSyncVersionNewer(candidateVersion, lastCollectionSyncVersions.get(message.itemKey))) return;
9566
9807
  if (shouldIgnoreConfirmedRemoteCollectionSnapshot(message)) {
9567
9808
  lastCollectionSyncVersions.set(message.itemKey, candidateVersion);
9809
+ ignoredConfirmedSnapshots.set(message.itemKey, message);
9568
9810
  return;
9569
9811
  }
9570
9812
  applyRemoteItemSnapshot(message, candidateVersion);
@@ -9588,7 +9830,7 @@ function createCollectionStore(storeOptions) {
9588
9830
  }
9589
9831
  return results;
9590
9832
  }
9591
- function maybeDisposeBatchScheduler(payload) {
9833
+ function maybeDisposeBatchScheduler(itemKey, payload) {
9592
9834
  const batchKey = getBatchKey(payload);
9593
9835
  if (batchKey === false) return;
9594
9836
  const scheduler = batchKeySchedulers.get(batchKey);
@@ -9599,10 +9841,11 @@ function createCollectionStore(storeOptions) {
9599
9841
  })) {
9600
9842
  scheduler.reset();
9601
9843
  batchKeySchedulers.delete(batchKey);
9602
- }
9844
+ } else scheduler.cancelPendingRequests([itemKey]);
9603
9845
  }
9604
9846
  function cleanupItemResources(itemKey, payload) {
9605
9847
  invalidationWasTriggered.delete(itemKey);
9848
+ ignoredConfirmedSnapshots.delete(itemKey);
9606
9849
  itemKeyToPayload.delete(itemKey);
9607
9850
  itemCacheRuntime.clear(itemKey);
9608
9851
  const itemScheduler = perItemSchedulers.get(itemKey);
@@ -9610,7 +9853,7 @@ function createCollectionStore(storeOptions) {
9610
9853
  itemScheduler.reset();
9611
9854
  perItemSchedulers.delete(itemKey);
9612
9855
  }
9613
- maybeDisposeBatchScheduler(payload);
9856
+ maybeDisposeBatchScheduler(itemKey, payload);
9614
9857
  }
9615
9858
  function isProtectedFromEviction(itemKey, item) {
9616
9859
  if (itemCacheRuntime.isActive(itemKey)) return true;
@@ -9776,14 +10019,28 @@ function createCollectionStore(storeOptions) {
9776
10019
  return useItem$1(payload, options, store, scheduleFetch, useMultipleItems);
9777
10020
  }
9778
10021
  function startMutation(fetchParams) {
9779
- const itemKeys = getItemsKeyArray(fetchParams);
9780
- const endMutations = [];
9781
- for (const { itemKey, payload } of itemKeys) {
10022
+ const lockedItems = getItemsKeyArray(fetchParams).map(({ itemKey, payload }) => {
9782
10023
  const scheduler = getScheduler(itemKey, payload);
9783
- endMutations.push(scheduler.startMutation(itemKey));
9784
- }
10024
+ return {
10025
+ itemKey,
10026
+ payload,
10027
+ scheduler,
10028
+ endMutation: scheduler.startMutation(itemKey)
10029
+ };
10030
+ });
9785
10031
  return () => {
9786
- for (const endMutation of endMutations) endMutation();
10032
+ for (const { endMutation } of lockedItems) endMutation();
10033
+ if (ignoredConfirmedSnapshots.size === 0) return;
10034
+ const payloadsToRevalidate = [];
10035
+ for (const { itemKey, payload, scheduler } of lockedItems) {
10036
+ if (scheduler.isMutationInProgress(itemKey)) continue;
10037
+ const snapshot = ignoredConfirmedSnapshots.get(itemKey);
10038
+ if (!snapshot) continue;
10039
+ ignoredConfirmedSnapshots.delete(itemKey);
10040
+ const localData = store.state[itemKey]?.data ?? null;
10041
+ if (!deepEqual(snapshot.item?.data ?? null, localData)) payloadsToRevalidate.push(payload);
10042
+ }
10043
+ if (payloadsToRevalidate.length > 0) invalidateItem(payloadsToRevalidate);
9787
10044
  };
9788
10045
  }
9789
10046
  function addItemToState(fetchParams, data) {
@@ -9841,6 +10098,8 @@ function createCollectionStore(storeOptions) {
9841
10098
  }
9842
10099
  return someItemWasUpdated;
9843
10100
  }
10101
+ const pendingDebounceRollbacks = /* @__PURE__ */ new Map();
10102
+ const optimisticMutations = createOptimisticMutationTracker();
9844
10103
  async function performMutation(payload, { optimisticUpdate, mutation, silentErrors, revalidateOnSuccess, onSuccess, debounce: _debounce, offline, upload }) {
9845
10104
  const payloadToUse = payload === null ? [] : payload;
9846
10105
  const affectedItems = Array.isArray(payloadToUse) ? payloadToUse : [payloadToUse];
@@ -9851,43 +10110,97 @@ function createCollectionStore(storeOptions) {
9851
10110
  mutationId,
9852
10111
  items: affectedItems
9853
10112
  });
9854
- const optimisticRollbackSnapshots = optimisticUpdate ? affectedItemEntries.map(({ itemKey, payload: itemPayload }) => ({
9855
- itemKey,
9856
- payload: itemPayload,
9857
- item: klona(store.state[itemKey])
9858
- })) : [];
9859
10113
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
10114
+ let accepted = false;
9860
10115
  const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9861
10116
  kind: "online",
9862
10117
  data: await directMutation()
9863
- }), (exception) => {
10118
+ }), (exception, rollbacks) => {
9864
10119
  const error = toStoreMutationError(exception, errorNormalizer);
9865
- if (optimisticRollbackSnapshots.length > 0) {
10120
+ const revertedItems = /* @__PURE__ */ new Map();
10121
+ const changedItems = /* @__PURE__ */ new Map();
10122
+ const oldestMutationIds = /* @__PURE__ */ new Map();
10123
+ for (let i = rollbacks.length - 1; i >= 0; i--) for (const rollback of rollbacks[i] ?? []) {
10124
+ const { itemKey, before, after } = rollback;
10125
+ oldestMutationIds.set(itemKey, rollback.mutationId);
10126
+ const current = revertedItems.has(itemKey) ? revertedItems.get(itemKey)?.item : store.state[itemKey];
10127
+ const reverted = !before && after && current && current.data === after.data ? {
10128
+ value: before,
10129
+ changed: false
10130
+ } : revertOptimisticChange(current, before, after);
10131
+ revertedItems.set(itemKey, {
10132
+ payload: rollback.payload,
10133
+ item: reverted.value
10134
+ });
10135
+ if (reverted.changed) changedItems.set(itemKey, rollback.payload);
10136
+ }
10137
+ for (const [itemKey, { item, payload: itemPayload }] of revertedItems) {
10138
+ const current = store.state[itemKey];
10139
+ if (item === current) {
10140
+ revertedItems.delete(itemKey);
10141
+ continue;
10142
+ }
10143
+ if (!optimisticMutations.hasNewer(itemKey, oldestMutationIds.get(itemKey) ?? mutationId, mutationId)) continue;
10144
+ if (!item && current) revertedItems.delete(itemKey);
10145
+ changedItems.set(itemKey, itemPayload);
10146
+ }
10147
+ if (revertedItems.size > 0) {
9866
10148
  const restoredItemKeys = [];
10149
+ const interruptedFetchPayloads = [];
10150
+ for (const rollbackGroup of rollbacks) for (const rollback of rollbackGroup) {
10151
+ const { itemKey } = rollback;
10152
+ if (rollback.before && rollback.hadPendingFetch && !store.state[itemKey] && revertedItems.get(itemKey)?.item && !interruptedFetchPayloads.includes(rollback.payload)) interruptedFetchPayloads.push(rollback.payload);
10153
+ }
9867
10154
  runWithBroadcastConsistency("confirmed", () => {
9868
10155
  store.produceState((draft) => {
9869
- for (const snapshot of optimisticRollbackSnapshots) {
9870
- if (snapshot.item === void 0) {
9871
- delete draft[snapshot.itemKey];
10156
+ for (const [itemKey, { item }] of revertedItems) {
10157
+ if (item === void 0) {
10158
+ delete draft[itemKey];
9872
10159
  continue;
9873
10160
  }
9874
- draft[snapshot.itemKey] = snapshot.item;
10161
+ draft[itemKey] = item;
9875
10162
  }
9876
10163
  }, { action: "rollback-mutation-error" });
9877
- for (const snapshot of optimisticRollbackSnapshots) {
9878
- if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9879
- else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9880
- publishItemSnapshot(snapshot.itemKey);
10164
+ for (const [itemKey, { item, payload: itemPayload }] of revertedItems) {
10165
+ if (item) restoredItemKeys.push(itemKey);
10166
+ else cleanupItemResources(itemKey, itemPayload);
10167
+ publishItemSnapshot(itemKey, changedItems.has(itemKey) || optimisticMutations.hasOtherInFlight(itemKey, mutationId) ? "optimistic" : "confirmed");
9881
10168
  }
9882
10169
  });
9883
10170
  if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
10171
+ if (interruptedFetchPayloads.length > 0) scheduleFetch("highPriority", interruptedFetchPayloads);
9884
10172
  }
10173
+ if (changedItems.size > 0) invalidateItem([...changedItems.values()]);
9885
10174
  if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9886
10175
  return error;
9887
- }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse)) : void 0, (result) => {
10176
+ }, optimisticUpdate ? (addRollback) => {
10177
+ const before = affectedItemEntries.map(({ itemKey, payload: itemPayload }) => {
10178
+ optimisticMutations.start(itemKey, mutationId);
10179
+ return {
10180
+ item: store.state[itemKey],
10181
+ hadPendingFetch: getScheduler(itemKey, itemPayload).hasPendingRequest(itemKey)
10182
+ };
10183
+ });
10184
+ try {
10185
+ return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse));
10186
+ } finally {
10187
+ addRollback(affectedItemEntries.map(({ itemKey, payload: itemPayload }, index) => ({
10188
+ itemKey,
10189
+ payload: itemPayload,
10190
+ before: before[index]?.item,
10191
+ after: store.state[itemKey],
10192
+ mutationId,
10193
+ hadPendingFetch: before[index]?.hadPendingFetch ?? false
10194
+ })));
10195
+ }
10196
+ } : void 0, (result) => {
10197
+ accepted = true;
9888
10198
  if (revalidateOnSuccess && affectedItems.length > 0) invalidateItem(payloadToUse);
9889
10199
  if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
9890
- }, _debounce, blockWindowClose ?? void 0);
10200
+ }, _debounce, blockWindowClose ?? void 0, pendingDebounceRollbacks).finally(() => {
10201
+ if (!optimisticUpdate) return;
10202
+ for (const { itemKey } of affectedItemEntries) optimisticMutations.end(itemKey, mutationId, accepted);
10203
+ });
9891
10204
  storeEvents.emit("mutationEnd", {
9892
10205
  mutationId,
9893
10206
  items: affectedItems,
@@ -9935,13 +10248,14 @@ function createCollectionStore(storeOptions) {
9935
10248
  }
9936
10249
  function reset() {
9937
10250
  if (isDisposed) return;
9938
- for (const scheduler of batchKeySchedulers.values()) scheduler.reset();
10251
+ for (const scheduler of batchKeySchedulers.values()) scheduler.reset(true);
9939
10252
  batchKeySchedulers.clear();
9940
10253
  itemKeyToPayload.clear();
9941
- for (const scheduler of perItemSchedulers.values()) scheduler.reset();
10254
+ for (const scheduler of perItemSchedulers.values()) scheduler.reset(true);
9942
10255
  perItemSchedulers.clear();
9943
10256
  invalidationWasTriggered.clear();
9944
10257
  lastCollectionSyncVersions.clear();
10258
+ ignoredConfirmedSnapshots.clear();
9945
10259
  clearOfflineOverlays();
9946
10260
  itemCacheRuntime.clearAll();
9947
10261
  cacheLimitEnforcementScheduler.cancel();
@@ -9956,13 +10270,14 @@ function createCollectionStore(storeOptions) {
9956
10270
  if (isDisposed) return;
9957
10271
  isDisposed = true;
9958
10272
  unregisterStoreFromManager();
9959
- for (const scheduler of batchKeySchedulers.values()) scheduler.reset();
10273
+ for (const scheduler of batchKeySchedulers.values()) scheduler.reset(true);
9960
10274
  batchKeySchedulers.clear();
9961
10275
  itemKeyToPayload.clear();
9962
- for (const scheduler of perItemSchedulers.values()) scheduler.reset();
10276
+ for (const scheduler of perItemSchedulers.values()) scheduler.reset(true);
9963
10277
  perItemSchedulers.clear();
9964
10278
  invalidationWasTriggered.clear();
9965
10279
  lastCollectionSyncVersions.clear();
10280
+ ignoredConfirmedSnapshots.clear();
9966
10281
  clearOfflineOverlays();
9967
10282
  itemCacheRuntime.clearAll();
9968
10283
  cacheLimitEnforcementScheduler.cancel();
@@ -9974,11 +10289,11 @@ function createCollectionStore(storeOptions) {
9974
10289
  /** Detects whether a specific item inside a collection item's data is still loading.
9975
10290
  * Useful when a collection item holds a list/record of sub-items and a component
9976
10291
  * displays one that may not be present yet. */
9977
- function useListItemIsLoading$2(payload, { itemId, selector, loadItemFallback, ensureIsLoaded }) {
10292
+ function useListItemIsLoading$2(payload, { itemId, selector, loadItemFallback, requireFreshData }) {
9978
10293
  const item = useItem(payload, {
9979
10294
  returnRefetchingStatus: true,
9980
10295
  selector,
9981
- ensureIsLoaded
10296
+ requireFreshData
9982
10297
  });
9983
10298
  const itemExists = item.data != null;
9984
10299
  const listIsLoading = item.isLoading;
@@ -9993,11 +10308,11 @@ function createCollectionStore(storeOptions) {
9993
10308
  /** Detects when a specific item inside a collection item's data has been deleted.
9994
10309
  * Only triggers after the sub-item was previously found and then disappears — not
9995
10310
  * during initial loading. */
9996
- function useListItemIsDeleted$2(payload, { itemId, selector, onDelete, ensureIsLoaded }) {
10311
+ function useListItemIsDeleted$2(payload, { itemId, selector, onDelete, requireFreshData }) {
9997
10312
  const item = useItem(payload, {
9998
10313
  returnRefetchingStatus: true,
9999
10314
  selector,
10000
- ensureIsLoaded
10315
+ requireFreshData
10001
10316
  });
10002
10317
  const itemExists = item.data != null;
10003
10318
  const listIsLoading = item.isLoading;
@@ -10010,11 +10325,11 @@ function createCollectionStore(storeOptions) {
10010
10325
  }
10011
10326
  /** Combined hook that returns `{ isLoading, isDeleted, data }` for a specific item
10012
10327
  * inside a collection item's data. Composes `useListItemIsLoading` and `useListItemIsDeleted`. */
10013
- function useListItem$2(payload, { itemId, selector, loadItemFallback, onDelete, ensureIsLoaded }) {
10328
+ function useListItem$2(payload, { itemId, selector, loadItemFallback, onDelete, requireFreshData }) {
10014
10329
  const item = useItem(payload, {
10015
10330
  returnRefetchingStatus: true,
10016
10331
  selector,
10017
- ensureIsLoaded
10332
+ requireFreshData
10018
10333
  });
10019
10334
  const itemExists = item.data != null;
10020
10335
  const listIsLoading = item.isLoading;
@@ -10279,6 +10594,12 @@ function createDocumentStore(storeOptions) {
10279
10594
  let remoteApplyDepth = 0;
10280
10595
  let currentBroadcastConsistency = "confirmed";
10281
10596
  let lastDocumentSyncVersion;
10597
+ /**
10598
+ * Latest confirmed sibling-tab snapshot ignored because a local mutation was
10599
+ * in flight. Once the last mutation ends, the document is revalidated unless
10600
+ * the local state already matches it, so the tabs converge again.
10601
+ */
10602
+ let ignoredConfirmedSnapshot = null;
10282
10603
  const offlineOverlayStore = new Store({
10283
10604
  debugName: `${id}:document-offline-overlay`,
10284
10605
  state: () => null
@@ -10438,6 +10759,7 @@ function createDocumentStore(storeOptions) {
10438
10759
  if (!isBrowserTabsSyncVersionNewer(candidateVersion, lastDocumentSyncVersion)) return;
10439
10760
  if (shouldIgnoreConfirmedRemoteDocumentSnapshot(message)) {
10440
10761
  lastDocumentSyncVersion = candidateVersion;
10762
+ ignoredConfirmedSnapshot = message;
10441
10763
  return;
10442
10764
  }
10443
10765
  applyRemoteDocumentSnapshot(message, candidateVersion);
@@ -10623,8 +10945,9 @@ function createDocumentStore(storeOptions) {
10623
10945
  }
10624
10946
  function reset() {
10625
10947
  if (isDisposed) return;
10626
- scheduler.reset();
10948
+ scheduler.reset(true);
10627
10949
  lastDocumentSyncVersion = void 0;
10950
+ ignoredConfirmedSnapshot = null;
10628
10951
  clearOfflineOverlay();
10629
10952
  persistence?.dispose();
10630
10953
  persistence?.clear();
@@ -10642,7 +10965,7 @@ function createDocumentStore(storeOptions) {
10642
10965
  if (isDisposed) return;
10643
10966
  isDisposed = true;
10644
10967
  unregisterStoreFromManager();
10645
- scheduler.reset();
10968
+ scheduler.reset(true);
10646
10969
  lastDocumentSyncVersion = void 0;
10647
10970
  clearOfflineOverlay();
10648
10971
  browserTabsSync.close();
@@ -10651,30 +10974,70 @@ function createDocumentStore(storeOptions) {
10651
10974
  offlineController?.dispose();
10652
10975
  }
10653
10976
  function startMutation() {
10654
- return scheduler.startMutation(DOC_REQUEST_ID);
10977
+ const endMutation = scheduler.startMutation(DOC_REQUEST_ID);
10978
+ return () => {
10979
+ const ended = endMutation();
10980
+ if (ignoredConfirmedSnapshot && !isDisposed && !scheduler.isMutationInProgress(DOC_REQUEST_ID)) {
10981
+ const snapshotData = ignoredConfirmedSnapshot.data;
10982
+ ignoredConfirmedSnapshot = null;
10983
+ if (!deepEqual(snapshotData, store.state.data)) invalidateData();
10984
+ }
10985
+ return ended;
10986
+ };
10655
10987
  }
10988
+ const pendingDebounceRollbacks = /* @__PURE__ */ new Map();
10989
+ const optimisticMutations = createOptimisticMutationTracker();
10656
10990
  async function performMutation({ optimisticUpdate, mutation, debounce, silentErrors, revalidateOnSuccess, offline, upload }) {
10657
10991
  if (offline && offlineController && !offlineController.canQueueMutation()) return Result.err(toStoreMutationError(new OfflineSessionUnavailableError(), errorNormalizer));
10658
10992
  const mutationId = getAutoIncrementId();
10659
10993
  storeEvents.emit("mutationStart", { mutationId });
10660
- const optimisticRollbackSnapshot = optimisticUpdate ? klona(store.state.data) : void 0;
10661
10994
  const directMutation = async () => unwrapTSDFResult(await mutation({
10662
10995
  updateState,
10663
10996
  currentState: store.state.data
10664
10997
  }));
10998
+ let accepted = false;
10665
10999
  const result = await performMutationWithLifecycle(startMutation, offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
10666
11000
  kind: "online",
10667
11001
  data: await directMutation()
10668
- }), (exception) => {
10669
- if (optimisticUpdate) runWithBroadcastConsistency("confirmed", () => {
10670
- store.setKey("data", optimisticRollbackSnapshot ?? null, { action: "rollback-mutation-error" });
10671
- publishDocumentSnapshot();
11002
+ }), (exception, rollbacks) => {
11003
+ let data = store.state.data;
11004
+ let changedSince = false;
11005
+ for (let i = rollbacks.length - 1; i >= 0; i--) {
11006
+ const rollback = rollbacks[i];
11007
+ if (!rollback || rollback.before === rollback.after) continue;
11008
+ if (data !== rollback.after) {
11009
+ changedSince = true;
11010
+ break;
11011
+ }
11012
+ data = rollback.before;
11013
+ }
11014
+ const reverted = data !== store.state.data;
11015
+ const revalidate = changedSince || reverted && optimisticMutations.hasNewer(DOC_REQUEST_ID, rollbacks[0]?.mutationId ?? mutationId, mutationId);
11016
+ if (reverted) runWithBroadcastConsistency("confirmed", () => {
11017
+ store.setKey("data", data, { action: "rollback-mutation-error" });
11018
+ publishDocumentSnapshot(revalidate || optimisticMutations.hasOtherInFlight(DOC_REQUEST_ID, mutationId) ? "optimistic" : "confirmed");
10672
11019
  });
11020
+ if (revalidate) invalidateData();
10673
11021
  if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
10674
11022
  return toStoreMutationError(exception, errorNormalizer);
10675
- }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data)) : void 0, (result) => {
11023
+ }, optimisticUpdate ? (addRollback) => {
11024
+ const before = store.state.data;
11025
+ optimisticMutations.start(DOC_REQUEST_ID, mutationId);
11026
+ try {
11027
+ return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data));
11028
+ } finally {
11029
+ addRollback({
11030
+ before,
11031
+ after: store.state.data,
11032
+ mutationId
11033
+ });
11034
+ }
11035
+ } : void 0, (result) => {
11036
+ accepted = true;
10676
11037
  if (revalidateOnSuccess && result.kind === "online") invalidateData();
10677
- }, debounce, blockWindowClose ?? void 0);
11038
+ }, debounce, blockWindowClose ?? void 0, pendingDebounceRollbacks).finally(() => {
11039
+ optimisticMutations.end(DOC_REQUEST_ID, mutationId, accepted);
11040
+ });
10678
11041
  storeEvents.emit("mutationEnd", {
10679
11042
  mutationId,
10680
11043
  status: result.ok ? "success" : result.error === mutationSkipped ? "skipped" : "error"
@@ -10682,7 +11045,7 @@ function createDocumentStore(storeOptions) {
10682
11045
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
10683
11046
  return result;
10684
11047
  }
10685
- function useDocument({ selector, isOffScreen: isOffScreenProp, disabled: disabledProp, returnRefetchingStatus, disableRefetchOnMount = globalDisableRefetchOnMount, returnIdleStatus: returnIdleStatusProp, ensureIsLoaded, disableRefetches } = {}) {
11048
+ function useDocument({ selector, isOffScreen: isOffScreenProp, disabled: disabledProp, returnRefetchingStatus, disableRefetchOnMount = globalDisableRefetchOnMount, returnIdleStatus: returnIdleStatusProp, requireFreshData, disableRefetches } = {}) {
10686
11049
  const offlineEntities = useOfflineStoreEntities({
10687
11050
  sessionKey: getSessionKeyForRuntime(),
10688
11051
  inactiveScope: id,
@@ -10758,12 +11121,12 @@ function createDocumentStore(storeOptions) {
10758
11121
  disableRefetches,
10759
11122
  disabled
10760
11123
  ]);
10761
- const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(ensureIsLoaded, !disabled, () => {
11124
+ const [useModifyResult, markRefreshSettled] = useRequireFreshData(requireFreshData, !disabled, () => {
10762
11125
  scheduleFetch("highPriority");
10763
11126
  });
10764
11127
  useSubscribeToStore(store, ({ observe }) => {
10765
11128
  observe.ifSelector((state) => state.status).change.then(({ current }) => {
10766
- if (current === "success" || current === "error") emitIsLoadedEvt();
11129
+ if (current === "success" || current === "error") markRefreshSettled();
10767
11130
  });
10768
11131
  });
10769
11132
  return useModifyResult(storeState);
@@ -10771,11 +11134,11 @@ function createDocumentStore(storeOptions) {
10771
11134
  /** Detects whether a specific item inside the document's data is still loading.
10772
11135
  * Useful when the document holds a list/record of items and a component displays
10773
11136
  * an individual item that may not be present yet. */
10774
- function useListItemIsLoading$1({ itemId, selector, loadItemFallback, ensureIsLoaded }) {
11137
+ function useListItemIsLoading$1({ itemId, selector, loadItemFallback, requireFreshData }) {
10775
11138
  const doc = useDocument({
10776
11139
  returnRefetchingStatus: true,
10777
11140
  selector,
10778
- ensureIsLoaded
11141
+ requireFreshData
10779
11142
  });
10780
11143
  const itemExists = doc.data != null;
10781
11144
  const listIsLoading = doc.isLoading;
@@ -10790,11 +11153,11 @@ function createDocumentStore(storeOptions) {
10790
11153
  /** Detects when a specific item inside the document's data has been deleted.
10791
11154
  * Only triggers after the item was previously found and then disappears — not
10792
11155
  * during initial loading. */
10793
- function useListItemIsDeleted$1({ itemId, selector, onDelete, ensureIsLoaded }) {
11156
+ function useListItemIsDeleted$1({ itemId, selector, onDelete, requireFreshData }) {
10794
11157
  const doc = useDocument({
10795
11158
  returnRefetchingStatus: true,
10796
11159
  selector,
10797
- ensureIsLoaded
11160
+ requireFreshData
10798
11161
  });
10799
11162
  const itemExists = doc.data != null;
10800
11163
  const listIsLoading = doc.isLoading;
@@ -10807,11 +11170,11 @@ function createDocumentStore(storeOptions) {
10807
11170
  }
10808
11171
  /** Combined hook that returns `{ isLoading, isDeleted, data }` for a specific item
10809
11172
  * inside the document's data. Composes `useListItemIsLoading` and `useListItemIsDeleted`. */
10810
- function useListItem$1({ itemId, selector, loadItemFallback, onDelete, ensureIsLoaded }) {
11173
+ function useListItem$1({ itemId, selector, loadItemFallback, onDelete, requireFreshData }) {
10811
11174
  const doc = useDocument({
10812
11175
  returnRefetchingStatus: true,
10813
11176
  selector,
10814
- ensureIsLoaded
11177
+ requireFreshData
10815
11178
  });
10816
11179
  const itemExists = doc.data != null;
10817
11180
  const listIsLoading = doc.isLoading;
@@ -12031,32 +12394,64 @@ function setupListQueryPersistence(config, options = {}) {
12031
12394
  managedQueryEntriesByKey
12032
12395
  };
12033
12396
  }
12397
+ const incompleteResult = {
12398
+ completed: false,
12399
+ keptQueryKeys: /* @__PURE__ */ new Set(),
12400
+ managedQueryEntriesByKey: null
12401
+ };
12402
+ if (idleContext === void 0) return incompleteResult;
12403
+ const sessionKey = config.getSessionKey();
12404
+ if (sessionKey === false) return incompleteResult;
12405
+ const isSessionCurrent = () => config.getSessionKey() === sessionKey;
12034
12406
  const metadataEntries = await listAllPersistentStorageNamespaceMetadata(queryNamespace, { order: "lru-desc" });
12035
- const protectedQueryKeys = getProtectedKeysFromMetadata(metadataEntries);
12036
- const invalidQueryKeys = [];
12407
+ if (!isSessionCurrent()) {
12408
+ knownPersistedQueryKeys = null;
12409
+ return incompleteResult;
12410
+ }
12411
+ if (idleContext.isCanceled()) return incompleteResult;
12412
+ const protectedQueryKeys = /* @__PURE__ */ new Set();
12413
+ const removalEntries = [];
12037
12414
  const validEntries = [];
12038
- for (const entry of metadataEntries) {
12039
- const payload = validateWithSchema(config.queryPayloadSchema, readManifestPayloadMeta(entry.customMetadata));
12040
- if (payload === null) invalidQueryKeys.push(entry.key);
12041
- else validEntries.push({
12042
- queryKey: entry.key,
12043
- payload,
12044
- lastAccessAt: entry.lastAccessAt,
12415
+ for (const [entryIndex, entry] of metadataEntries.entries()) {
12416
+ if (entryIndex % MAINTENANCE_SCAN_CHUNK_SIZE === 0 && !await idleContext.yieldIfNeeded()) return incompleteResult;
12417
+ if (isAsyncStorageMetadataOfflineProtected(entry.customMetadata)) protectedQueryKeys.add(entry.key);
12418
+ if (validateWithSchema(config.queryPayloadSchema, readManifestPayloadMeta(entry.customMetadata)) === null) {
12419
+ removalEntries.push(entry);
12420
+ continue;
12421
+ }
12422
+ validEntries.push({
12423
+ entry,
12045
12424
  sizeBytes: rememberQueryMetadataSize(entry.key, entry.sizeBytes)
12046
12425
  });
12047
12426
  }
12048
- if (invalidQueryKeys.length > 0) await Promise.all(invalidQueryKeys.map((queryKey) => queryNamespace.remove(queryKey)));
12049
- const { keptKeys: keptQueryKeys, unprotectedBytes: queryUnprotectedBytes } = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
12050
- logQueryByteBudgetCleanup("maintenance", validEntries.length, keptQueryKeys, queryUnprotectedBytes);
12051
- await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
12052
- for (const entry of validEntries) {
12053
- const { queryKey } = entry;
12054
- if (!keptQueryKeys.has(queryKey)) {
12427
+ const byteBudgetResult = await keepEntriesWithinByteBudgetDuringIdle(validEntries, ({ entry }) => entry.key, ({ entry }) => entry.lastAccessAt, ({ sizeBytes }) => sizeBytes, ({ entry }) => pinnedQueryKeys.has(entry.key), ({ entry }) => protectedQueryKeys.has(entry.key), maxQueryBytes, idleContext);
12428
+ if (byteBudgetResult === null) return incompleteResult;
12429
+ const { keptKeys: keptQueryKeys, unprotectedBytes } = byteBudgetResult;
12430
+ const budgetEvictedEntries = /* @__PURE__ */ new Map();
12431
+ for (const { entry } of validEntries) {
12432
+ if (keptQueryKeys.has(entry.key)) continue;
12433
+ budgetEvictedEntries.set(entry.key, entry);
12434
+ removalEntries.push(entry);
12435
+ }
12436
+ const removalResult = await removeAsyncMaintenanceEntriesIfUnchanged(removalEntries, isAsyncStorageMetadataOfflineProtected, (entries) => queryNamespace.removeEntriesIfUnchanged(entries, removeAsyncStorageNamespaceEntriesIfUnchanged), (removedKeys) => {
12437
+ for (const queryKey of removedKeys) {
12438
+ const entry = budgetEvictedEntries.get(queryKey);
12439
+ if (entry === void 0) continue;
12055
12440
  rememberBudgetEvictedEntry(budgetEvictedQueryRecency, queryKey, entry.lastAccessAt, querySnapshotByKey.get(queryKey), storeRef !== null && Object.hasOwn(storeRef.state.queries, queryKey));
12056
12441
  forgetPersistedQuery(queryKey);
12057
12442
  }
12443
+ }, getAsyncStorageMaintenanceRemoveBatchSize(queryNamespace.getAsyncAdapter()), isSessionCurrent, idleContext);
12444
+ if (!removalResult.completed) {
12445
+ if (!isSessionCurrent()) knownPersistedQueryKeys = null;
12446
+ return incompleteResult;
12447
+ }
12448
+ if (removalResult.hasStaleEntries) {
12449
+ knownPersistedQueryKeys = null;
12450
+ scheduleAsyncStorageMaintenance(`list-query:${sessionKey}:${config.storeName}`, runMaintenance);
12451
+ return incompleteResult;
12058
12452
  }
12059
- knownPersistedQueryKeys = keptQueryKeys;
12453
+ knownPersistedQueryKeys = metadataEntries.length === 0 ? null : keptQueryKeys;
12454
+ logQueryByteBudgetCleanup("maintenance", validEntries.length, keptQueryKeys, unprotectedBytes);
12060
12455
  return {
12061
12456
  completed: true,
12062
12457
  keptQueryKeys,
@@ -12187,35 +12582,63 @@ function setupListQueryPersistence(config, options = {}) {
12187
12582
  } else if (localMaintenanceScope !== void 0) pendingLocalQueryReconciliationSessions.delete(localMaintenanceScope.sessionKey);
12188
12583
  return;
12189
12584
  }
12585
+ if (idleContext === void 0 || sessionKey === false) return;
12586
+ const isSessionCurrent = () => config.getSessionKey() === sessionKey;
12190
12587
  const itemMetadataEntries = await listAllPersistentStorageNamespaceMetadata(itemNamespace, { order: "lru-desc" });
12191
- const protectedItemKeys = getProtectedKeysFromMetadata(itemMetadataEntries);
12192
- const invalidItemKeys = [];
12193
- const validItemEntries = [];
12194
- for (const entry of itemMetadataEntries) {
12588
+ if (!isSessionCurrent()) {
12589
+ knownPersistedItemKeys = null;
12590
+ return;
12591
+ }
12592
+ if (idleContext.isCanceled()) return;
12593
+ const protectedItemKeys = /* @__PURE__ */ new Set();
12594
+ const removalEntries = [];
12595
+ const ignoredItemKeys = /* @__PURE__ */ new Set();
12596
+ const persistedItemEntries = [];
12597
+ for (const [entryIndex, entry] of itemMetadataEntries.entries()) {
12598
+ if (entryIndex % MAINTENANCE_SCAN_CHUNK_SIZE === 0 && !await idleContext.yieldIfNeeded()) return;
12599
+ if (isAsyncStorageMetadataOfflineProtected(entry.customMetadata)) protectedItemKeys.add(entry.key);
12195
12600
  const payload = validateWithSchema(config.itemPayloadSchema, readManifestPayloadMeta(entry.customMetadata));
12196
- if (payload === null) invalidItemKeys.push(entry.key);
12197
- else validItemEntries.push({
12198
- itemKey: entry.key,
12199
- lastAccessAt: entry.lastAccessAt,
12200
- payload,
12601
+ if (payload === null) {
12602
+ removalEntries.push(entry);
12603
+ continue;
12604
+ }
12605
+ if (shouldIgnoreItem(payload)) {
12606
+ ignoredItemKeys.add(entry.key);
12607
+ removalEntries.push(entry);
12608
+ continue;
12609
+ }
12610
+ persistedItemEntries.push({
12611
+ entry,
12201
12612
  sizeBytes: rememberItemMetadataSize(entry.key, entry.sizeBytes)
12202
12613
  });
12203
12614
  }
12204
- if (invalidItemKeys.length > 0) await Promise.all(invalidItemKeys.map((itemKey) => itemNamespace.remove(itemKey)));
12205
- const ignoredItemEntries = validItemEntries.filter(({ payload }) => shouldIgnoreItem(payload));
12206
- if (ignoredItemEntries.length > 0) {
12207
- await Promise.all(ignoredItemEntries.map(({ itemKey }) => itemNamespace.remove(itemKey)));
12208
- for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
12615
+ const byteBudgetResult = await keepEntriesWithinByteBudgetDuringIdle(persistedItemEntries, ({ entry }) => entry.key, ({ entry }) => entry.lastAccessAt, ({ sizeBytes }) => sizeBytes, ({ entry }) => pinnedItemKeys.has(entry.key), ({ entry }) => protectedItemKeys.has(entry.key), maxItemBytes, idleContext);
12616
+ if (byteBudgetResult === null) return;
12617
+ const { keptKeys: keptItemKeys, unprotectedBytes } = byteBudgetResult;
12618
+ const budgetEvictedEntries = /* @__PURE__ */ new Map();
12619
+ for (const { entry } of persistedItemEntries) {
12620
+ if (keptItemKeys.has(entry.key)) continue;
12621
+ budgetEvictedEntries.set(entry.key, entry);
12622
+ removalEntries.push(entry);
12623
+ }
12624
+ const removalResult = await removeAsyncMaintenanceEntriesIfUnchanged(removalEntries, isAsyncStorageMetadataOfflineProtected, (entries) => itemNamespace.removeEntriesIfUnchanged(entries, removeAsyncStorageNamespaceEntriesIfUnchanged), (removedKeys) => {
12625
+ for (const itemKey of removedKeys) {
12626
+ const entry = budgetEvictedEntries.get(itemKey);
12627
+ if (entry !== void 0) rememberBudgetEvictedEntry(budgetEvictedItemRecency, itemKey, entry.lastAccessAt, itemSnapshotByKey.get(itemKey), storeRef !== null && storeRef.state.items[itemKey] != null);
12628
+ if (entry !== void 0 || ignoredItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
12629
+ }
12630
+ }, getAsyncStorageMaintenanceRemoveBatchSize(itemNamespace.getAsyncAdapter()), isSessionCurrent, idleContext);
12631
+ if (!removalResult.completed) {
12632
+ if (!isSessionCurrent()) knownPersistedItemKeys = null;
12633
+ return;
12209
12634
  }
12210
- const persistedItemEntries = validItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
12211
- const { keptKeys: keptItemKeys, unprotectedBytes } = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
12212
- logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
12213
- await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => itemNamespace.remove(itemKey)));
12214
- for (const { itemKey, lastAccessAt } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) {
12215
- rememberBudgetEvictedEntry(budgetEvictedItemRecency, itemKey, lastAccessAt, itemSnapshotByKey.get(itemKey), storeRef !== null && storeRef.state.items[itemKey] != null);
12216
- forgetPersistedItem(itemKey);
12635
+ if (removalResult.hasStaleEntries) {
12636
+ knownPersistedItemKeys = null;
12637
+ scheduleAsyncStorageMaintenance(`list-query:${sessionKey}:${config.storeName}`, runMaintenance);
12638
+ return;
12217
12639
  }
12218
- knownPersistedItemKeys = keptItemKeys;
12640
+ knownPersistedItemKeys = itemMetadataEntries.length === 0 ? null : keptItemKeys;
12641
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
12219
12642
  }
12220
12643
  async function flushPersistedState() {
12221
12644
  if (!storeRef) return;
@@ -12968,6 +13391,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12968
13391
  batchKey: batchKey ?? "__default__"
12969
13392
  }));
12970
13393
  if (!fetchResult.ok) {
13394
+ if (fetchCtx.shouldAbort()) {
13395
+ for (const { requestId } of requests) results.set(requestId, false);
13396
+ return results;
13397
+ }
12971
13398
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
12972
13399
  store.produceState((draft) => {
12973
13400
  for (const { requestId: itemKey } of requests) {
@@ -13166,9 +13593,11 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
13166
13593
  return results;
13167
13594
  }
13168
13595
  const fetchPromises = requests.map(async ({ requestId: queryKey, payload: fetchPayload }) => {
13169
- const { payload, offset, limit, fields } = fetchPayload;
13596
+ const { payload, limit, fields } = fetchPayload;
13597
+ const offset = !!offsetPagination && fetchPayload.type === "loadMore" && fetchPayload.offset > 0 ? Math.min(fetchPayload.offset, store.state.queries[queryKey]?.items.length ?? fetchPayload.offset) : fetchPayload.offset;
13598
+ const appendToExisting = !!offsetPagination && fetchPayload.type === "loadMore" && offset > 0;
13170
13599
  try {
13171
- const useChunkedInvalidation = offsetPagination && fetchPayload.type === "load" && limit > offsetPagination.maxInvalidationLimit;
13600
+ const useChunkedInvalidation = offsetPagination && !appendToExisting && limit > offsetPagination.maxInvalidationLimit;
13172
13601
  let allItems;
13173
13602
  let hasMore;
13174
13603
  if (useChunkedInvalidation) {
@@ -13208,7 +13637,6 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
13208
13637
  results.set(queryKey, false);
13209
13638
  return;
13210
13639
  }
13211
- const appendToExisting = !!offsetPagination && fetchPayload.type === "loadMore" && offset > 0;
13212
13640
  store.produceState((draft) => {
13213
13641
  applyFetchedItems(draft, queryKey, allItems, hasMore, fields, getItemKey, partialResources, appendToExisting);
13214
13642
  }, { action: "query-fetch-success" });
@@ -13439,7 +13867,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
13439
13867
  if (payload === void 0) return null;
13440
13868
  return getOrCreateItemScheduler(itemKey, payload);
13441
13869
  }
13442
- function maybeDisposeBatchScheduler(payload) {
13870
+ function maybeDisposeBatchScheduler(itemKey, payload) {
13443
13871
  const batchKey = getBatchKeyForPayload(payload);
13444
13872
  if (batchKey === false) return;
13445
13873
  const scheduler = batchKeySchedulers.get(batchKey);
@@ -13450,7 +13878,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
13450
13878
  })) {
13451
13879
  scheduler.reset();
13452
13880
  batchKeySchedulers.delete(batchKey);
13453
- }
13881
+ } else scheduler.cancelPendingRequests([itemKey]);
13454
13882
  }
13455
13883
  function deleteItemFetchResources(items) {
13456
13884
  for (const { itemKey, payload } of items) {
@@ -13461,7 +13889,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
13461
13889
  itemScheduler.reset();
13462
13890
  perItemSchedulers.delete(itemKey);
13463
13891
  }
13464
- maybeDisposeBatchScheduler(payload);
13892
+ maybeDisposeBatchScheduler(itemKey, payload);
13465
13893
  }
13466
13894
  }
13467
13895
  function deleteQueryFetchResources(queryKeys) {
@@ -13886,12 +14314,12 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
13886
14314
  return Result.ok(result.data);
13887
14315
  }
13888
14316
  function resetSchedulers() {
13889
- for (const scheduler of querySchedulers.values()) scheduler.reset();
14317
+ for (const scheduler of querySchedulers.values()) scheduler.reset(true);
13890
14318
  querySchedulers.clear();
13891
14319
  queryInitialFetchStartTime.clear();
13892
- for (const scheduler of batchKeySchedulers.values()) scheduler.reset();
14320
+ for (const scheduler of batchKeySchedulers.values()) scheduler.reset(true);
13893
14321
  batchKeySchedulers.clear();
13894
- for (const scheduler of perItemSchedulers.values()) scheduler.reset();
14322
+ for (const scheduler of perItemSchedulers.values()) scheduler.reset(true);
13895
14323
  perItemSchedulers.clear();
13896
14324
  itemInitialFetchStartTime.clear();
13897
14325
  itemKeyToPayload.clear();
@@ -13981,7 +14409,7 @@ const GET_ALL = () => true;
13981
14409
  //#endregion
13982
14410
  //#region src/listQueryStore/createMutationApi.ts
13983
14411
  /** @internal */
13984
- 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, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler) {
14412
+ 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, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler, onItemMutationsEnd) {
13985
14413
  const storeEvents = evtmitter();
13986
14414
  const deferredOptimisticQueryInvalidationsStack = [];
13987
14415
  const optimisticMutationQueryContextStack = [];
@@ -13990,40 +14418,158 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13990
14418
  if (typeof payload === "function") return getItemsKeyArray(payload).map((item) => item.payload);
13991
14419
  return [payload];
13992
14420
  }
13993
- function restoreMutationRollbackState({ itemSnapshots, querySnapshots }) {
13994
- if (itemSnapshots.length === 0 && querySnapshots.length === 0) return;
13995
- runWithBroadcastConsistency("confirmed", () => {
14421
+ const pendingDebounceRollbacks = /* @__PURE__ */ new Map();
14422
+ const optimisticMutations = createOptimisticMutationTracker();
14423
+ function getItemRollbackState(itemKey) {
14424
+ return {
14425
+ item: store.state.items[itemKey],
14426
+ itemQuery: store.state.itemQueries[itemKey],
14427
+ loadedFields: store.state.itemLoadedFields[itemKey],
14428
+ invalidationFields: store.state.itemFieldInvalidationFields[itemKey]
14429
+ };
14430
+ }
14431
+ function getItemInvalidationTracking(itemKey) {
14432
+ const pendingInvalidationFields = itemPendingInvalidationFields.get(itemKey);
14433
+ const droppedFieldInvalidations = itemDroppedFieldInvalidations.get(itemKey);
14434
+ return {
14435
+ pendingInvalidationFields: pendingInvalidationFields && new Map(pendingInvalidationFields),
14436
+ pendingFullInvalidation: itemsPendingFullInvalidation.get(itemKey),
14437
+ droppedFieldInvalidations: droppedFieldInvalidations && new Map(droppedFieldInvalidations),
14438
+ invalidationWasTriggered: itemInvalidationWasTriggered.has(itemKey)
14439
+ };
14440
+ }
14441
+ function revertOptimisticMutations(rollbacks, mutationId) {
14442
+ const revertedItems = /* @__PURE__ */ new Map();
14443
+ const revertedQueries = /* @__PURE__ */ new Map();
14444
+ const changedItems = /* @__PURE__ */ new Map();
14445
+ const keptDataItemKeys = /* @__PURE__ */ new Set();
14446
+ const changedQueryKeys = /* @__PURE__ */ new Set();
14447
+ const oldestMutationIds = /* @__PURE__ */ new Map();
14448
+ for (let i = rollbacks.length - 1; i >= 0; i--) {
14449
+ const rollback = rollbacks[i];
14450
+ if (!rollback) continue;
14451
+ for (const { itemKey, payload, before, after, trackingBefore, hadPendingFetch } of rollback.items) {
14452
+ oldestMutationIds.set(itemKey, rollback.mutationId);
14453
+ const reverted = revertedItems.get(itemKey);
14454
+ const current = reverted?.state ?? getItemRollbackState(itemKey);
14455
+ const { value, changed } = revertOptimisticChange(current, before, after);
14456
+ const isCreate = !before.item && !!after.item;
14457
+ const createReverted = isCreate && value.item === before.item;
14458
+ const metadataUnchanged = current.itemQuery === after.itemQuery && current.loadedFields === after.loadedFields && current.invalidationFields === after.invalidationFields;
14459
+ revertedItems.set(itemKey, {
14460
+ payload,
14461
+ state: createReverted ? before : isCreate ? current : value,
14462
+ tracking: createReverted || !isCreate && metadataUnchanged ? trackingBefore : reverted?.tracking,
14463
+ hadPendingFetch: hadPendingFetch || !!reverted?.hadPendingFetch
14464
+ });
14465
+ if (changed && !createReverted) changedItems.set(itemKey, payload);
14466
+ if (current.item !== after.item && before.item !== after.item) keptDataItemKeys.add(itemKey);
14467
+ }
14468
+ for (const queryRollback of rollback.queries) {
14469
+ const { queryKey } = queryRollback;
14470
+ const reverted = revertedQueries.get(queryKey);
14471
+ const current = reverted ? reverted.query : store.state.queries[queryKey];
14472
+ const { value, changed } = revertOptimisticChange(current, queryRollback.before, queryRollback.after);
14473
+ revertedQueries.set(queryKey, {
14474
+ query: value,
14475
+ invalidationWasTriggered: current?.refetchOnMount === queryRollback.after?.refetchOnMount ? queryRollback.invalidationWasTriggered : reverted?.invalidationWasTriggered
14476
+ });
14477
+ if (changed) changedQueryKeys.add(queryKey);
14478
+ }
14479
+ }
14480
+ const removedItemKeys = /* @__PURE__ */ new Set();
14481
+ for (const [itemKey, { payload, state }] of revertedItems) {
14482
+ const current = getItemRollbackState(itemKey);
14483
+ if (state.item === current.item && state.itemQuery === current.itemQuery && state.loadedFields === current.loadedFields && state.invalidationFields === current.invalidationFields) {
14484
+ revertedItems.delete(itemKey);
14485
+ continue;
14486
+ }
14487
+ if (state.item !== current.item && optimisticMutations.hasNewer(itemKey, oldestMutationIds.get(itemKey) ?? mutationId, mutationId)) {
14488
+ changedItems.set(itemKey, payload);
14489
+ keptDataItemKeys.add(itemKey);
14490
+ if (!state.item && current.item) {
14491
+ revertedItems.delete(itemKey);
14492
+ continue;
14493
+ }
14494
+ }
14495
+ if (!state.item && current.item) removedItemKeys.add(itemKey);
14496
+ }
14497
+ for (const [queryKey, reverted] of revertedQueries) {
14498
+ const { query } = reverted;
14499
+ if (query && query.items.some((itemKey) => removedItemKeys.has(itemKey))) reverted.query = {
14500
+ ...query,
14501
+ items: query.items.filter((itemKey) => !removedItemKeys.has(itemKey))
14502
+ };
14503
+ else if (query === store.state.queries[queryKey]) revertedQueries.delete(queryKey);
14504
+ }
14505
+ function addQueriesShowingKeptData() {
14506
+ for (const [queryKey, query] of Object.entries(store.state.queries)) if (query.items.some((itemKey) => keptDataItemKeys.has(itemKey))) changedQueryKeys.add(queryKey);
14507
+ }
14508
+ if (keptDataItemKeys.size > 0) addQueriesShowingKeptData();
14509
+ const interruptedFetches = [];
14510
+ const interruptedFetchPayloadsToInvalidate = [];
14511
+ for (const [itemKey, { state, hadPendingFetch }] of revertedItems) {
14512
+ const { itemQuery, loadedFields } = state;
14513
+ if (itemQuery && hadPendingFetch && !store.state.itemQueries[itemKey]) if (partialResources && !loadedFields) interruptedFetchPayloadsToInvalidate.push(itemQuery.payload);
14514
+ else interruptedFetches.push({
14515
+ itemKey,
14516
+ payload: itemQuery.payload,
14517
+ fields: loadedFields === "*" || !partialResources ? void 0 : loadedFields
14518
+ });
14519
+ }
14520
+ if (revertedItems.size > 0 || revertedQueries.size > 0) runWithBroadcastConsistency("confirmed", () => {
13996
14521
  store.produceState((draftState) => {
13997
- for (const snapshot of itemSnapshots) {
13998
- if (snapshot.item === void 0) delete draftState.items[snapshot.itemKey];
13999
- else draftState.items[snapshot.itemKey] = snapshot.item;
14000
- if (snapshot.itemQuery === void 0) delete draftState.itemQueries[snapshot.itemKey];
14001
- else draftState.itemQueries[snapshot.itemKey] = snapshot.itemQuery;
14002
- if (snapshot.loadedFields === void 0) delete draftState.itemLoadedFields[snapshot.itemKey];
14003
- else draftState.itemLoadedFields[snapshot.itemKey] = snapshot.loadedFields;
14004
- if (snapshot.invalidationFields === void 0) delete draftState.itemFieldInvalidationFields[snapshot.itemKey];
14005
- else draftState.itemFieldInvalidationFields[snapshot.itemKey] = snapshot.invalidationFields;
14522
+ for (const [itemKey, { state }] of revertedItems) {
14523
+ if (state.item === void 0) delete draftState.items[itemKey];
14524
+ else draftState.items[itemKey] = state.item;
14525
+ if (state.itemQuery === void 0) delete draftState.itemQueries[itemKey];
14526
+ else draftState.itemQueries[itemKey] = state.itemQuery;
14527
+ if (state.loadedFields === void 0) delete draftState.itemLoadedFields[itemKey];
14528
+ else draftState.itemLoadedFields[itemKey] = state.loadedFields;
14529
+ if (state.invalidationFields === void 0) delete draftState.itemFieldInvalidationFields[itemKey];
14530
+ else draftState.itemFieldInvalidationFields[itemKey] = state.invalidationFields;
14006
14531
  }
14007
- for (const snapshot of querySnapshots) if (snapshot.query === void 0) delete draftState.queries[snapshot.queryKey];
14008
- else draftState.queries[snapshot.queryKey] = snapshot.query;
14532
+ for (const [queryKey, { query }] of revertedQueries) if (query === void 0) delete draftState.queries[queryKey];
14533
+ else draftState.queries[queryKey] = query;
14009
14534
  }, { action: "rollback-mutation-error" });
14010
- for (const snapshot of itemSnapshots) {
14011
- if (snapshot.pendingInvalidationFields === void 0) itemPendingInvalidationFields.delete(snapshot.itemKey);
14012
- else itemPendingInvalidationFields.set(snapshot.itemKey, new Map(snapshot.pendingInvalidationFields));
14013
- if (snapshot.pendingFullInvalidation === void 0) itemsPendingFullInvalidation.delete(snapshot.itemKey);
14014
- else itemsPendingFullInvalidation.set(snapshot.itemKey, snapshot.pendingFullInvalidation);
14015
- if (snapshot.droppedFieldInvalidations === void 0) itemDroppedFieldInvalidations.delete(snapshot.itemKey);
14016
- else itemDroppedFieldInvalidations.set(snapshot.itemKey, new Map(snapshot.droppedFieldInvalidations));
14017
- if (snapshot.invalidationWasTriggered) itemInvalidationWasTriggered.add(snapshot.itemKey);
14018
- else itemInvalidationWasTriggered.delete(snapshot.itemKey);
14019
- publishItemSnapshot(snapshot.itemKey);
14020
- }
14021
- for (const snapshot of querySnapshots) {
14022
- if (snapshot.invalidationWasTriggered) queryInvalidationWasTriggered.add(snapshot.queryKey);
14023
- else queryInvalidationWasTriggered.delete(snapshot.queryKey);
14024
- publishQuerySnapshot(snapshot.queryKey);
14535
+ for (const [itemKey, { tracking }] of revertedItems) {
14536
+ if (tracking) {
14537
+ if (tracking.pendingInvalidationFields === void 0) itemPendingInvalidationFields.delete(itemKey);
14538
+ else itemPendingInvalidationFields.set(itemKey, tracking.pendingInvalidationFields);
14539
+ if (tracking.pendingFullInvalidation === void 0) itemsPendingFullInvalidation.delete(itemKey);
14540
+ else itemsPendingFullInvalidation.set(itemKey, tracking.pendingFullInvalidation);
14541
+ if (tracking.droppedFieldInvalidations) {
14542
+ const dropped = itemDroppedFieldInvalidations.get(itemKey);
14543
+ if (dropped) {
14544
+ for (const [field, record] of tracking.droppedFieldInvalidations) if (!dropped.has(field)) dropped.set(field, record);
14545
+ } else itemDroppedFieldInvalidations.set(itemKey, tracking.droppedFieldInvalidations);
14546
+ }
14547
+ if (tracking.invalidationWasTriggered) itemInvalidationWasTriggered.add(itemKey);
14548
+ else itemInvalidationWasTriggered.delete(itemKey);
14549
+ }
14550
+ publishItemSnapshot(itemKey, keptDataItemKeys.has(itemKey) || optimisticMutations.hasOtherInFlight(itemKey, mutationId) ? "optimistic" : "confirmed");
14551
+ }
14552
+ for (const [queryKey, { query, invalidationWasTriggered }] of revertedQueries) {
14553
+ if (invalidationWasTriggered === true) queryInvalidationWasTriggered.add(queryKey);
14554
+ else if (invalidationWasTriggered === false) queryInvalidationWasTriggered.delete(queryKey);
14555
+ publishQuerySnapshot(queryKey, changedQueryKeys.has(queryKey) || query?.items.some((itemKey) => keptDataItemKeys.has(itemKey) || optimisticMutations.hasOtherInFlight(itemKey, mutationId)) ? "optimistic" : "confirmed");
14025
14556
  }
14026
14557
  });
14558
+ if (keptDataItemKeys.size > 0) addQueriesShowingKeptData();
14559
+ const changedQueries = [];
14560
+ for (const queryKey of changedQueryKeys) {
14561
+ const query = store.state.queries[queryKey];
14562
+ if (query) changedQueries.push(query.payload);
14563
+ }
14564
+ for (const { itemKey, payload, fields } of interruptedFetches) getOrCreateItemScheduler(itemKey, payload).scheduleFetch(itemKey, "highPriority", {
14565
+ payload,
14566
+ fields
14567
+ });
14568
+ if (interruptedFetchPayloadsToInvalidate.length > 0) invalidateItem(interruptedFetchPayloadsToInvalidate);
14569
+ if (changedItems.size > 0 || changedQueries.length > 0) invalidateQueryAndItems({
14570
+ itemPayload: changedItems.size > 0 ? [...changedItems.values()] : false,
14571
+ queryPayload: changedQueries.length > 0 ? changedQueries : false
14572
+ });
14027
14573
  }
14028
14574
  function getCurrentOptimisticMutationQueryContext() {
14029
14575
  return optimisticMutationQueryContextStack[optimisticMutationQueryContextStack.length - 1];
@@ -14033,7 +14579,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14033
14579
  if (!context) return;
14034
14580
  if (!context.queryRollbackSnapshots.has(queryKey)) context.queryRollbackSnapshots.set(queryKey, {
14035
14581
  queryKey,
14036
- query: klona(store.state.queries[queryKey]),
14582
+ before: store.state.queries[queryKey],
14037
14583
  invalidationWasTriggered: queryInvalidationWasTriggered.has(queryKey)
14038
14584
  });
14039
14585
  if (context.lockedQueryKeys.has(queryKey)) return;
@@ -14280,6 +14826,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14280
14826
  }
14281
14827
  return () => {
14282
14828
  for (const endMutation of endMutations) endMutation();
14829
+ onItemMutationsEnd();
14283
14830
  };
14284
14831
  }
14285
14832
  function applyOptimisticListUpdates(itemKeys) {
@@ -14492,33 +15039,18 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14492
15039
  const affectedItems = affectedItemEntries ? affectedItemEntries.map(({ payload: p }) => p) : resolveAffectedItems(payloadToUse);
14493
15040
  const normalizedRevalidateOnSuccess = normalizeRevalidateOnSuccessOption(revalidateOnSuccess);
14494
15041
  const mutationId = getAutoIncrementId();
14495
- let itemRollbackSnapshots = [];
14496
15042
  const deferredOptimisticQueryInvalidations = /* @__PURE__ */ new Map();
14497
15043
  const optimisticMutationQueryContext = {
14498
15044
  dynamicQueryMutationEnders: [],
14499
15045
  lockedQueryKeys: /* @__PURE__ */ new Set(),
14500
15046
  queryRollbackSnapshots: /* @__PURE__ */ new Map()
14501
15047
  };
14502
- if (affectedItemEntries) itemRollbackSnapshots = affectedItemEntries.map(({ itemKey }) => {
14503
- const pendingInvalidationFields = itemPendingInvalidationFields.get(itemKey);
14504
- const droppedFieldInvalidations = itemDroppedFieldInvalidations.get(itemKey);
14505
- return {
14506
- itemKey,
14507
- item: klona(store.state.items[itemKey]),
14508
- itemQuery: klona(store.state.itemQueries[itemKey]),
14509
- loadedFields: klona(store.state.itemLoadedFields[itemKey]),
14510
- invalidationFields: klona(store.state.itemFieldInvalidationFields[itemKey]),
14511
- pendingInvalidationFields: pendingInvalidationFields && new Map(pendingInvalidationFields),
14512
- pendingFullInvalidation: itemsPendingFullInvalidation.get(itemKey),
14513
- droppedFieldInvalidations: droppedFieldInvalidations && new Map(droppedFieldInvalidations),
14514
- invalidationWasTriggered: itemInvalidationWasTriggered.has(itemKey)
14515
- };
14516
- });
14517
15048
  storeEvents.emit("mutationStart", {
14518
15049
  mutationId,
14519
15050
  items: affectedItems
14520
15051
  });
14521
15052
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
15053
+ let accepted = false;
14522
15054
  const result = await performMutationWithLifecycle(() => {
14523
15055
  const endBaseMutations = startItemMutation(payloadToUse);
14524
15056
  return () => {
@@ -14528,17 +15060,23 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14528
15060
  }, offline ? () => runHybridOfflineMutation(offlineController, offline, upload, directMutation) : async () => ({
14529
15061
  kind: "online",
14530
15062
  data: await directMutation()
14531
- }), (exception) => {
15063
+ }), (exception, rollbacks) => {
14532
15064
  const error = toStoreMutationError(exception, errorNormalizer);
14533
- const queryRollbackSnapshots = [...optimisticMutationQueryContext.queryRollbackSnapshots.values()];
14534
- if (itemRollbackSnapshots.length > 0 || queryRollbackSnapshots.length) restoreMutationRollbackState({
14535
- itemSnapshots: itemRollbackSnapshots,
14536
- querySnapshots: queryRollbackSnapshots
14537
- });
15065
+ revertOptimisticMutations(rollbacks, mutationId);
14538
15066
  if (onMutationError) onMutationError(exception, { silentErrors });
14539
15067
  if (onError) onError(error);
14540
15068
  return error;
14541
- }, optimisticUpdate ? () => {
15069
+ }, optimisticUpdate ? (addRollback) => {
15070
+ const itemSnapshots = (affectedItemEntries ?? []).map(({ itemKey, payload: itemPayload }) => {
15071
+ optimisticMutations.start(itemKey, mutationId);
15072
+ return {
15073
+ itemKey,
15074
+ payload: itemPayload,
15075
+ before: getItemRollbackState(itemKey),
15076
+ trackingBefore: getItemInvalidationTracking(itemKey),
15077
+ hadPendingFetch: !!fetchItemFn && getOrCreateItemScheduler(itemKey, itemPayload).hasPendingRequest(itemKey)
15078
+ };
15079
+ });
14542
15080
  deferredOptimisticQueryInvalidationsStack.push(deferredOptimisticQueryInvalidations);
14543
15081
  optimisticMutationQueryContextStack.push(optimisticMutationQueryContext);
14544
15082
  try {
@@ -14546,15 +15084,31 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14546
15084
  } finally {
14547
15085
  optimisticMutationQueryContextStack.pop();
14548
15086
  deferredOptimisticQueryInvalidationsStack.pop();
15087
+ addRollback({
15088
+ items: itemSnapshots.map((snapshot) => ({
15089
+ ...snapshot,
15090
+ after: getItemRollbackState(snapshot.itemKey)
15091
+ })),
15092
+ queries: Array.from(optimisticMutationQueryContext.queryRollbackSnapshots.values(), (snapshot) => ({
15093
+ ...snapshot,
15094
+ after: store.state.queries[snapshot.queryKey]
15095
+ })),
15096
+ mutationId,
15097
+ deferredQueryInvalidations: deferredOptimisticQueryInvalidations
15098
+ });
14549
15099
  }
14550
- } : void 0, (result) => {
15100
+ } : void 0, (result, rollbacks) => {
15101
+ accepted = true;
15102
+ for (const rollback of rollbacks) for (const [queryKey, queryPayload] of rollback.deferredQueryInvalidations) deferredOptimisticQueryInvalidations.set(queryKey, queryPayload);
14551
15103
  const successInvalidationQueryPayloads = result.kind === "online" ? getSuccessInvalidationQueryPayloads(deferredOptimisticQueryInvalidations, normalizedRevalidateOnSuccess.queryFilter, normalizedRevalidateOnSuccess.shouldRevalidate) : [];
14552
15104
  if (result.kind === "online" && (normalizedRevalidateOnSuccess.shouldRevalidate || successInvalidationQueryPayloads.length > 0)) invalidateQueryAndItems({
14553
15105
  itemPayload: !normalizedRevalidateOnSuccess.includeItems || affectedItems.length === 0 ? false : payloadToUse,
14554
15106
  queryPayload: successInvalidationQueryPayloads.length > 0 ? successInvalidationQueryPayloads : false
14555
15107
  });
14556
15108
  if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
14557
- }, debounce, blockWindowClose ?? void 0);
15109
+ }, debounce, blockWindowClose ?? void 0, pendingDebounceRollbacks).finally(() => {
15110
+ for (const { itemKey } of affectedItemEntries ?? []) optimisticMutations.end(itemKey, mutationId, accepted);
15111
+ });
14558
15112
  storeEvents.emit("mutationEnd", {
14559
15113
  mutationId,
14560
15114
  items: affectedItems,
@@ -14778,10 +15332,10 @@ function useFindItem(findItemFn, { selector }, store, registerActiveItems, touch
14778
15332
  }
14779
15333
  //#endregion
14780
15334
  //#region src/listQueryStore/useItem.ts
14781
- function useItem(itemPayload, { selector, ensureIsLoaded, loadFromStateOnly, disableRefetches, disableRefetchOnMount, returnIdleStatus, returnRefetchingStatus, showPartialAsRefetching, isOffScreen, fields, debouncePayload }, store, scheduleItemFetch, useMultipleItems) {
15335
+ function useItem(itemPayload, { selector, requireFreshData, loadFromStateOnly, disableRefetches, disableRefetchOnMount, returnIdleStatus, returnRefetchingStatus, showPartialAsRefetching, isOffScreen, fields, debouncePayload }, store, scheduleItemFetch, useMultipleItems) {
14782
15336
  const isInvalidPayload = itemPayload === "";
14783
15337
  const hasPayload = itemPayload !== false && itemPayload !== null && itemPayload !== void 0 && itemPayload !== "";
14784
- assertNoEnsureIsLoadedWithDebouncePayload("useItem", ensureIsLoaded, debouncePayload);
15338
+ assertNoRequireFreshDataWithDebouncePayload("useItem", requireFreshData, debouncePayload);
14785
15339
  const query = useMemo(() => hasPayload ? [{
14786
15340
  payload: itemPayload,
14787
15341
  fields,
@@ -14832,25 +15386,25 @@ function useItem(itemPayload, { selector, ensureIsLoaded, loadFromStateOnly, dis
14832
15386
  selector
14833
15387
  ]);
14834
15388
  const fetchQuery = hasPayload ? query[0] : void 0;
14835
- const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(ensureIsLoaded, hasPayload, () => {
15389
+ const [useModifyResult, markRefreshSettled] = useRequireFreshData(requireFreshData, hasPayload, () => {
14836
15390
  if (fetchQuery) scheduleItemFetch("highPriority", fetchQuery.payload, { fields: fetchQuery.fields });
14837
15391
  });
14838
15392
  useSubscribeToStore(store, ({ observe }) => {
14839
- if (!ensureIsLoaded || !hasPayload || !result.itemStateKey) return;
15393
+ if (!requireFreshData || !hasPayload || !result.itemStateKey) return;
14840
15394
  observe.ifSelector((state) => {
14841
15395
  return state.itemQueries[result.itemStateKey]?.status;
14842
15396
  }).change.then(({ current }) => {
14843
- if (current === "success" || current === "error") emitIsLoadedEvt();
15397
+ if (current === "success" || current === "error") markRefreshSettled();
14844
15398
  });
14845
15399
  });
14846
15400
  return useModifyResult(result);
14847
15401
  }
14848
15402
  //#endregion
14849
15403
  //#region src/listQueryStore/useListQuery.ts
14850
- function useListQuery(payload, { itemSelector, omitPayload, disableRefetches, disableRefetchOnMount, returnIdleStatus, returnRefetchingStatus, showPartialAsRefetching, loadSize, isOffScreen, ensureIsLoaded, fields, debouncePayload }, store, getQueryKey, scheduleListQueryFetch, useMultipleListQueries) {
15404
+ function useListQuery(payload, { itemSelector, omitPayload, disableRefetches, disableRefetchOnMount, returnIdleStatus, returnRefetchingStatus, showPartialAsRefetching, loadSize, isOffScreen, requireFreshData, fields, debouncePayload }, store, getQueryKey, scheduleListQueryFetch, useMultipleListQueries) {
14851
15405
  const isInvalidPayload = payload === "";
14852
15406
  const hasPayload = payload !== false && payload !== null && payload !== void 0 && payload !== "";
14853
- assertNoEnsureIsLoadedWithDebouncePayload("useListQuery", ensureIsLoaded, debouncePayload);
15407
+ assertNoRequireFreshDataWithDebouncePayload("useListQuery", requireFreshData, debouncePayload);
14854
15408
  const query = useMemo(() => hasPayload ? [{
14855
15409
  payload,
14856
15410
  fields,
@@ -14912,15 +15466,15 @@ function useListQuery(payload, { itemSelector, omitPayload, disableRefetches, di
14912
15466
  ]);
14913
15467
  const queryKey = hasPayload ? getQueryKey(payload) : "";
14914
15468
  const fetchQuery = hasPayload ? query[0] : void 0;
14915
- const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(ensureIsLoaded, hasPayload, () => {
15469
+ const [useModifyResult, markRefreshSettled] = useRequireFreshData(requireFreshData, hasPayload, () => {
14916
15470
  if (fetchQuery && hasPayload) scheduleListQueryFetch("highPriority", fetchQuery.payload, fetchQuery.loadSize, { fields: fetchQuery.fields });
14917
15471
  });
14918
15472
  useSubscribeToStore(store, ({ observe }) => {
14919
- if (!ensureIsLoaded || !hasPayload || !queryKey) return;
15473
+ if (!requireFreshData || !hasPayload || !queryKey) return;
14920
15474
  observe.ifSelector((state) => {
14921
15475
  return state.queries[queryKey]?.status;
14922
15476
  }).change.then(({ current }) => {
14923
- if (current === "success" || current === "error") emitIsLoadedEvt();
15477
+ if (current === "success" || current === "error") markRefreshSettled();
14924
15478
  });
14925
15479
  });
14926
15480
  return useModifyResult(result);
@@ -16116,6 +16670,14 @@ function createListQueryStore(storeOptions) {
16116
16670
  let currentBroadcastConsistency = "confirmed";
16117
16671
  const lastQuerySyncVersions = /* @__PURE__ */ new Map();
16118
16672
  const lastItemSyncVersions = /* @__PURE__ */ new Map();
16673
+ /**
16674
+ * Latest confirmed sibling-tab snapshots ignored because a local item
16675
+ * mutation was in flight. Once those mutations end, the affected items and
16676
+ * queries are revalidated unless the local state already matches the
16677
+ * snapshot, so the tabs converge again.
16678
+ */
16679
+ const ignoredConfirmedItemSnapshots = /* @__PURE__ */ new Map();
16680
+ const ignoredConfirmedQuerySnapshots = /* @__PURE__ */ new Map();
16119
16681
  const offlineOverlayStore = new Store({
16120
16682
  debugName: `${id}:list-query-offline-overlays`,
16121
16683
  state: () => ({})
@@ -16453,7 +17015,9 @@ function createListQueryStore(storeOptions) {
16453
17015
  events.emit("invalidateQuery", event);
16454
17016
  }, (event) => {
16455
17017
  events.emit("invalidateItem", event);
16456
- }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler);
17018
+ }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler, () => {
17019
+ revalidateAfterIgnoredConfirmedSnapshots();
17020
+ });
16457
17021
  if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
16458
17022
  normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
16459
17023
  const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
@@ -16744,10 +17308,39 @@ function createListQueryStore(storeOptions) {
16744
17308
  function querySnapshotHasLocallyMutatingItem(message) {
16745
17309
  for (const item of message.items) {
16746
17310
  if (!store.state.itemQueries[item.itemKey]) continue;
16747
- if (getKnownItemScheduler(item.itemKey)?.isMutationInProgress(item.itemKey)) return true;
17311
+ if (isItemMutationInProgress(item.itemKey)) return true;
16748
17312
  }
16749
17313
  return false;
16750
17314
  }
17315
+ function isItemMutationInProgress(itemKey) {
17316
+ return getKnownItemScheduler(itemKey)?.isMutationInProgress(itemKey) ?? false;
17317
+ }
17318
+ function localItemMatches(itemKey, item) {
17319
+ return deepEqual(item, store.state.items[itemKey] ?? null);
17320
+ }
17321
+ function revalidateAfterIgnoredConfirmedSnapshots() {
17322
+ if (ignoredConfirmedItemSnapshots.size === 0 && ignoredConfirmedQuerySnapshots.size === 0) return;
17323
+ const itemPayloads = [];
17324
+ for (const [itemKey, item] of ignoredConfirmedItemSnapshots) {
17325
+ if (isItemMutationInProgress(itemKey)) continue;
17326
+ ignoredConfirmedItemSnapshots.delete(itemKey);
17327
+ const itemQuery = store.state.itemQueries[itemKey];
17328
+ if (itemQuery && !localItemMatches(itemKey, item)) itemPayloads.push(itemQuery.payload);
17329
+ }
17330
+ const queryPayloads = [];
17331
+ for (const [queryKey, message] of ignoredConfirmedQuerySnapshots) {
17332
+ if (message.items.some(({ itemKey }) => isItemMutationInProgress(itemKey))) continue;
17333
+ ignoredConfirmedQuerySnapshots.delete(queryKey);
17334
+ const query = store.state.queries[queryKey];
17335
+ if (!query) continue;
17336
+ if (!(query.hasMore === message.query.hasMore && deepEqual(query.items, message.query.items) && message.items.every(({ itemKey, item }) => localItemMatches(itemKey, item)))) queryPayloads.push(query.payload);
17337
+ }
17338
+ if (itemPayloads.length === 0 && queryPayloads.length === 0) return;
17339
+ invalidateQueryAndItems({
17340
+ itemPayload: itemPayloads.length > 0 ? itemPayloads : false,
17341
+ queryPayload: queryPayloads.length > 0 ? queryPayloads : false
17342
+ });
17343
+ }
16751
17344
  function handleRemoteBrowserTabsMessage(message) {
16752
17345
  if (message.kind === "fetch-start") {
16753
17346
  syncRemoteFetchStart(message.targetKey, message.requestIds, message.startedAt);
@@ -16768,6 +17361,7 @@ function createListQueryStore(storeOptions) {
16768
17361
  }
16769
17362
  if (message.consistency === "confirmed" && itemScheduler?.isMutationInProgress(message.itemKey)) {
16770
17363
  lastItemSyncVersions.set(message.itemKey, candidateVersion);
17364
+ ignoredConfirmedItemSnapshots.set(message.itemKey, message.item);
16771
17365
  return;
16772
17366
  }
16773
17367
  applyRemoteItemSnapshot(message);
@@ -16786,6 +17380,7 @@ function createListQueryStore(storeOptions) {
16786
17380
  if (message.consistency === "confirmed" && querySnapshotHasLocallyMutatingItem(message)) {
16787
17381
  lastQuerySyncVersions.set(message.queryKey, candidateVersion);
16788
17382
  for (const item of message.items) lastItemSyncVersions.set(item.itemKey, candidateVersion);
17383
+ ignoredConfirmedQuerySnapshots.set(message.queryKey, message);
16789
17384
  return;
16790
17385
  }
16791
17386
  applyRemoteQuerySnapshot(message);
@@ -16897,6 +17492,8 @@ function createListQueryStore(storeOptions) {
16897
17492
  resetInvalidationTracking();
16898
17493
  lastQuerySyncVersions.clear();
16899
17494
  lastItemSyncVersions.clear();
17495
+ ignoredConfirmedItemSnapshots.clear();
17496
+ ignoredConfirmedQuerySnapshots.clear();
16900
17497
  clearOfflineOverlays();
16901
17498
  queryCacheRuntime.clearAll();
16902
17499
  itemCacheRuntime.clearAll();
@@ -16928,6 +17525,8 @@ function createListQueryStore(storeOptions) {
16928
17525
  resetInvalidationTracking();
16929
17526
  lastQuerySyncVersions.clear();
16930
17527
  lastItemSyncVersions.clear();
17528
+ ignoredConfirmedItemSnapshots.clear();
17529
+ ignoredConfirmedQuerySnapshots.clear();
16931
17530
  clearOfflineOverlays();
16932
17531
  queryCacheRuntime.clearAll();
16933
17532
  itemCacheRuntime.clearAll();