tsdf 18.4.0 → 18.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as removeAsyncMaintenanceEntriesIfUnchanged, B as offlineResolutionRecordSchema, C as getDefaultMaxBytesForScope, D as isQuotaExceededError, E as getSerializedStringSize, F as defaultOfflineRuntimeConfig, G as warnIfNavigatorLockUnavailable, H as getSessionProtectedKeysSnapshot, I as getIsOfflineModeFromStatus, K as createCompactLocalStorageEntry, L as isModeEffectivelyActive, M as OfflineResolutionActionError, N as OfflineResolutionConflictParseError, O as keepEntriesWithinByteBudget, P as compactOfflineStatusSnapshotSchema, R as isOfflineModeStatusValue, S as resolveTSDFLogger, T as createTimedKeySet, U as setSessionProtectedKeysSnapshot, V as clearSessionProtectedKeysSnapshot, W as getNavigatorLockManager, Z as getPayloadRecordKey, _ as OFFLINE_SESSION_STATUS_STORE_NAME, a as estimateManagedAsyncStorageEntrySizeBytes, at as createIdleCleanupContext, b as emitTSDFDebugLog, c as getRemovableStoresAsyncStorage, d as readAsyncStorageNamespaceIndexStateUsingDriver, f as registerAsyncStartupStoreCleanup, g as parseAsyncStorageNamespaceKind, h as unregisterAsyncStartupStoreCleanup, it as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, j as serializeJsonForStorage, k as keepEntriesWithinByteBudgetDuringIdle, l as isAsyncStorageMetadataOfflineProtected, m as serializeProtectedRef$1, nt as parsePersistedAsyncNamespaceKind, o as getAsyncStorageMaintenanceRemoveBatchSize, ot as scheduleIdleCleanup, p as removeAsyncStorageNamespaceEntriesIfUnchanged, q as parseCompactLocalStorageEntry, r as buildPersistedStaticPolicy, rt as serializeProtectedRef, s as getProtectedKeysFromMetadata, st as scheduleInitialMaintenanceCleanup, u as mergeManagedAsyncStorageCustomMetadata, v as getOfflineSessionStatusStorageKey, w as createShouldIgnoreItemPredicate, x as getTSDFDebugTimingMs, y as logPersistentStorageQuotaCleanup, z as offlineItemEntityRefSchema } from "./asyncStorageAdapter-NrI38v4g.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-amwSWm_p.js";
1
+ import { A as removeAsyncMaintenanceEntriesIfUnchanged, B as offlineResolutionRecordSchema, C as getDefaultMaxBytesForScope, D as isQuotaExceededError, E as getSerializedStringSize, F as defaultOfflineRuntimeConfig, G as warnIfNavigatorLockUnavailable, H as getSessionProtectedKeysSnapshot, I as getIsOfflineModeFromStatus, K as createCompactLocalStorageEntry, L as isModeEffectivelyActive, M as OfflineResolutionActionError, N as OfflineResolutionConflictParseError, O as keepEntriesWithinByteBudget, P as compactOfflineStatusSnapshotSchema, R as isOfflineModeStatusValue, S as resolveTSDFLogger, T as createTimedKeySet, U as setSessionProtectedKeysSnapshot, V as clearSessionProtectedKeysSnapshot, W as getNavigatorLockManager, Z as getPayloadRecordKey, _ as OFFLINE_SESSION_STATUS_STORE_NAME, a as estimateManagedAsyncStorageEntrySizeBytes, at as createIdleCleanupContext, b as emitTSDFDebugLog, c as getRemovableStoresAsyncStorage, d as readAsyncStorageNamespaceIndexStateUsingDriver, f as registerAsyncStartupStoreCleanup, g as parseAsyncStorageNamespaceKind, h as unregisterAsyncStartupStoreCleanup, it as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, j as serializeJsonForStorage, k as keepEntriesWithinByteBudgetDuringIdle, l as isAsyncStorageMetadataOfflineProtected, m as serializeProtectedRef$1, nt as parsePersistedAsyncNamespaceKind, o as getAsyncStorageMaintenanceRemoveBatchSize, ot as scheduleIdleCleanup, p as removeAsyncStorageNamespaceEntriesIfUnchanged, q as parseCompactLocalStorageEntry, r as buildPersistedStaticPolicy, rt as serializeProtectedRef, s as getProtectedKeysFromMetadata, st as scheduleInitialMaintenanceCleanup, u as mergeManagedAsyncStorageCustomMetadata, v as getOfflineSessionStatusStorageKey, w as createShouldIgnoreItemPredicate, x as getTSDFDebugTimingMs, y as logPersistentStorageQuotaCleanup, z as offlineItemEntityRefSchema } from "./asyncStorageAdapter-D6IVBzPg.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-CwmY3O1r.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
5
  import { deepEqual } from "@ls-stack/utils/deepEqual";
@@ -7,7 +7,7 @@ import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
7
7
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
8
8
  import { evtmitter } from "evtmitter";
9
9
  import { klona } from "klona/json";
10
- import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
10
+ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
11
11
  import { Result, isResult, resultify, unknownToError } from "t-result";
12
12
  import { Store, useSubscribeToStore } from "t-state";
13
13
  import { useOnChange } from "@ls-stack/react-utils/useOnChange";
@@ -221,6 +221,7 @@ const compactListQueryLocalStorageEntrySchema = rc_object({
221
221
  o: rc_boolean.withFallback(false).optionalKey(),
222
222
  p: rc_unknown,
223
223
  h: rc_boolean.withFallback(false).optionalKey(),
224
+ m: rc_boolean.withFallback(false).optionalKey(),
224
225
  v: rc_number.optionalKey()
225
226
  });
226
227
  function isCompactListQueryLocalStorageKey(storageKey) {
@@ -238,6 +239,7 @@ function parseCompactListQueryLocalStorageEntry(raw) {
238
239
  offlineProtected: parsed.o === true,
239
240
  payload: parsed.p,
240
241
  hasMore: parsed.h === true,
242
+ ...parsed.m === true ? { missingItems: true } : {},
241
243
  version: parsed.v
242
244
  };
243
245
  }
@@ -247,6 +249,7 @@ function createCompactListQueryLocalStorageEntry(entry) {
247
249
  i: entry.items,
248
250
  p: entry.payload,
249
251
  ...entry.hasMore ? { h: true } : {},
252
+ ...entry.missingItems ? { m: true } : {},
250
253
  ...entry.offlineProtected ? { o: true } : {},
251
254
  ...entry.version !== void 0 ? { v: entry.version } : {}
252
255
  };
@@ -1285,7 +1288,8 @@ const persistedListQueryItemDataSchema = rc_object({
1285
1288
  const persistedListQueryDataSchema = rc_object({
1286
1289
  payload: rc_unknown,
1287
1290
  items: rc_array(rc_string),
1288
- hasMore: rc_boolean
1291
+ hasMore: rc_boolean,
1292
+ missingItems: rc_boolean.optional()
1289
1293
  });
1290
1294
  function normalizePersistentStorageDataSchema(schema) {
1291
1295
  if ("storeSchema" in schema) return {
@@ -1374,7 +1378,8 @@ function parsePersistedListQueryData(value, payloadSchema) {
1374
1378
  return {
1375
1379
  payload,
1376
1380
  items: result.value.items,
1377
- hasMore: result.value.hasMore
1381
+ hasMore: result.value.hasMore,
1382
+ ...result.value.missingItems ? { missingItems: true } : {}
1378
1383
  };
1379
1384
  }
1380
1385
  //#endregion
@@ -1937,8 +1942,9 @@ async function touchLocalStorageKeyWithThrottle(key, touch) {
1937
1942
  function getLocalStorageMaxAgeMs() {
1938
1943
  return getManagedLocalStorageRuntimeConfig().maxAgeMs;
1939
1944
  }
1940
- function isOfflineNetworkModeActiveSync(networkConfig) {
1941
- if (!networkConfig?.enabled) return false;
1945
+ function isOfflineNetworkModeActiveSync(sessionConfig) {
1946
+ const networkConfig = sessionConfig?.network;
1947
+ if (!networkConfig?.enabled || sessionConfig?.enabled?.() === false) return false;
1942
1948
  try {
1943
1949
  return (networkConfig.getIsOffline?.() ?? navigator.onLine === false) === true;
1944
1950
  } catch {
@@ -2209,6 +2215,7 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2209
2215
  const debugContext = import.meta.env.DEV ? createPersistentStorageDebugContext(adapter, config.storeName, config.debugLogger, config.entryPrefix, void 0, asyncNamespaceKind) : void 0;
2210
2216
  const effectiveAsyncValueCodec = asyncValueCodec ?? valueCodec;
2211
2217
  const localCodec = toLocalStorageValueCodec(valueCodec);
2218
+ const allowExpiredRead = UNSENT_OFFLINE_WORK_ENTRY_PREFIXES.includes(config.entryPrefix);
2212
2219
  const checkLocalStorageLeftovers = config.entryPrefix === "lq" ? null : createLocalStorageLeftoversCheck(config.storeName, (storageKey) => localPersistentStorage.getManifestKeyForPrefix(`${storageKey}.${config.entryPrefix}.`), onPersistentStorageError);
2213
2220
  scheduleAdapterExpirationScan(adapter);
2214
2221
  function getPrefix() {
@@ -2398,7 +2405,8 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2398
2405
  const key = `${prefix}${entryKey}`;
2399
2406
  const entry = readStorageEntryFromLocalStorageSync(key, version, {
2400
2407
  metadata: "namespace",
2401
- namespacePrefix: prefix
2408
+ namespacePrefix: prefix,
2409
+ allowExpiredRead
2402
2410
  }, localCodec);
2403
2411
  if (import.meta.env.DEV) logPersistentStorageOperation(withPersistentStorageDebugKey(context, key), "read-entry", entry ? "success" : "miss", startTime, { touch: options.touch });
2404
2412
  return entry;
@@ -2909,7 +2917,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2909
2917
  }
2910
2918
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2911
2919
  async function clearAllSessionStorage(sessionKey) {
2912
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-BFn-BuAl.js");
2920
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-CBMshtkY.js");
2913
2921
  await Promise.all([
2914
2922
  clearSessionStorage(sessionKey, "local-sync"),
2915
2923
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -3093,7 +3101,7 @@ function setupCollectionPersistence(config, options = {}) {
3093
3101
  let knownPersistedKeys = null;
3094
3102
  let maintenanceManifestKey = null;
3095
3103
  function isOfflineNetworkActive() {
3096
- return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig().network);
3104
+ return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig());
3097
3105
  }
3098
3106
  function clearSaveTimer() {
3099
3107
  if (saveTimer !== null) {
@@ -3751,7 +3759,7 @@ async function runHybridOfflineMutation(controller, offline, upload, directMutat
3751
3759
  upload
3752
3760
  });
3753
3761
  if (prepared.initialAction === "queue") {
3754
- await prepared.queueMutation();
3762
+ await prepared.queueMutation(false);
3755
3763
  return { kind: "queued" };
3756
3764
  }
3757
3765
  try {
@@ -3763,7 +3771,7 @@ async function runHybridOfflineMutation(controller, offline, upload, directMutat
3763
3771
  };
3764
3772
  } catch (error) {
3765
3773
  if (!await prepared.classifyError(error)) throw error;
3766
- await prepared.queueMutation();
3774
+ await prepared.queueMutation(true);
3767
3775
  return { kind: "queued" };
3768
3776
  }
3769
3777
  }
@@ -4288,6 +4296,50 @@ function parseSyncMessage(message, storeType) {
4288
4296
  }
4289
4297
  //#endregion
4290
4298
  //#region src/persistentStorage/offlineUploadsShared.ts
4299
+ /**
4300
+ * Parses an upload ref that came from storage or from another tab.
4301
+ *
4302
+ * @returns The parsed ref, or `undefined` when it does not match the schema.
4303
+ */
4304
+ function parseRestoredUploadRef(schema, resolvedRef) {
4305
+ if ("~standard" in schema) {
4306
+ const result = schema["~standard"].validate(resolvedRef);
4307
+ if (isPromise(result) || result.issues) return void 0;
4308
+ return result.value;
4309
+ }
4310
+ const result = schema.parse(resolvedRef);
4311
+ return result.ok ? result.value : void 0;
4312
+ }
4313
+ /**
4314
+ * Applies the outcome of {@link parseRestoredUploadRef} to a restored upload.
4315
+ *
4316
+ * An upload whose ref failed the schema goes back to `pending` without the
4317
+ * ref, so its staged file is uploaded again the next time the ref is needed.
4318
+ */
4319
+ function applyRestoredUploadRef(upload, parsedRef) {
4320
+ if (parsedRef !== void 0) return parsedRef === upload.resolvedRef ? upload : {
4321
+ ...upload,
4322
+ resolvedRef: parsedRef
4323
+ };
4324
+ const pendingUpload = {
4325
+ ...upload,
4326
+ state: "pending"
4327
+ };
4328
+ delete pendingUpload.resolvedRef;
4329
+ delete pendingUpload.progress;
4330
+ return pendingUpload;
4331
+ }
4332
+ function createEmptyUploadFile(status) {
4333
+ return {
4334
+ status,
4335
+ url: null,
4336
+ file: null,
4337
+ error: null
4338
+ };
4339
+ }
4340
+ const idleUploadFile = createEmptyUploadFile("idle");
4341
+ const loadingUploadFile = createEmptyUploadFile("loading");
4342
+ const missingUploadFile = createEmptyUploadFile("missing");
4291
4343
  function stripStoredUploadFile(record) {
4292
4344
  const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, storeName: _storeName, ...upload } = record;
4293
4345
  return upload;
@@ -4355,13 +4407,19 @@ function getOfflineStoreEntityLookup(sessionEntities, storeName) {
4355
4407
  }
4356
4408
  return lookupsByStoreName.get(storeName) ?? emptyEntityLookup;
4357
4409
  }
4358
- function toItemOfflineState(entity) {
4410
+ /**
4411
+ * @param attemptedCreationEntityIds - ids of the session's temp entities
4412
+ * whose creation was already sent or waits for a manual resolution
4413
+ */
4414
+ function toItemOfflineState(entity, attemptedCreationEntityIds) {
4359
4415
  if (entity?.entityKind !== "item") return null;
4416
+ const isUnsentCreation = entity.tempId !== void 0;
4360
4417
  return {
4361
4418
  syncState: entity.syncState,
4362
4419
  pendingMutations: entity.pendingMutations,
4363
4420
  requiresResolution: entity.requiresResolution,
4364
- isUnsentCreation: entity.tempId !== void 0
4421
+ isUnsentCreation,
4422
+ creationAttempted: isUnsentCreation && attemptedCreationEntityIds.includes(entity.id)
4365
4423
  };
4366
4424
  }
4367
4425
  function getIsPendingOfflineSync(entity) {
@@ -4392,6 +4450,7 @@ function stripInternalEntityPayload(entity) {
4392
4450
  const { payload: _payload, ...publicEntity } = entity;
4393
4451
  return publicEntity;
4394
4452
  }
4453
+ function noop() {}
4395
4454
  const DEFAULT_OUTAGE_RECOVERY_PROBE = {
4396
4455
  initialIntervalMs: 3e4,
4397
4456
  maxIntervalMs: 3e5,
@@ -4404,7 +4463,12 @@ const DEFAULT_NETWORK_RECOVERY_PROBE = {
4404
4463
  backoffMultiplier: 2,
4405
4464
  jitterRatio: .2
4406
4465
  };
4466
+ const DEFAULT_HEALTH_CHECK_TIMEOUT_MS = 1e4;
4407
4467
  const defaultGetIsOffline = () => !navigator.onLine;
4468
+ const INACTIVE_MODE = {
4469
+ enabled: false,
4470
+ active: false
4471
+ };
4408
4472
  const defaultStatusBySession = /* @__PURE__ */ new Map();
4409
4473
  const registry = /* @__PURE__ */ new Map();
4410
4474
  const uploadsConfigByOfflineSession = /* @__PURE__ */ new WeakMap();
@@ -4465,6 +4529,7 @@ function recheckIsSessionInOfflineMode(sessionKey) {
4465
4529
  const DEFAULT_UPLOAD_CONCURRENCY = 3;
4466
4530
  const OFFLINE_UPLOAD_RETENTION_MS = 10080 * 60 * 1e3;
4467
4531
  const OFFLINE_UPLOAD_RETENTION_STABLE_ONLINE_MS = 5e3;
4532
+ const UPLOAD_FILE_RELEASE_DELAY_MS = 1e3;
4468
4533
  function createDefaultStatus(sessionKey) {
4469
4534
  return {
4470
4535
  sessionKey,
@@ -4577,6 +4642,7 @@ function normalizeRecoveryProbe(config, defaults) {
4577
4642
  }
4578
4643
  function toCanonicalConfig(config) {
4579
4644
  return {
4645
+ isSessionEnabled: config?.enabled,
4580
4646
  hasNetworkConfig: config?.network !== void 0,
4581
4647
  networkEnabledByDefault: config?.network?.enabled ?? false,
4582
4648
  networkListenToBrowserEvents: config?.network?.listenToBrowserEvents ?? true,
@@ -4591,6 +4657,8 @@ function toCanonicalConfig(config) {
4591
4657
  },
4592
4658
  classifyFailure: config?.classifyFailure,
4593
4659
  classifyRetriableFailure: config?.classifyRetryableFailure,
4660
+ healthCheck: config?.healthCheck?.check,
4661
+ healthCheckTimeoutMs: config?.healthCheck?.timeoutMs ?? DEFAULT_HEALTH_CHECK_TIMEOUT_MS,
4594
4662
  outageRecoveryCheck: config?.outage?.recoveryCheck,
4595
4663
  outageRecoveryProbe: normalizeRecoveryProbe(config?.outage?.recoveryProbe, DEFAULT_OUTAGE_RECOVERY_PROBE)
4596
4664
  };
@@ -4609,16 +4677,10 @@ function sameProbeConfig(left, right) {
4609
4677
  }
4610
4678
  const persistedLocalSessionSnapshotSchema = rc_object({ d: compactOfflineStatusSnapshotSchema });
4611
4679
  function sameCanonicalConfig(left, right) {
4612
- return left.hasNetworkConfig === right.hasNetworkConfig && left.networkEnabledByDefault === right.networkEnabledByDefault && left.networkListenToBrowserEvents === right.networkListenToBrowserEvents && left.getIsOffline === right.getIsOffline && left.networkRecoveryCheck === right.networkRecoveryCheck && sameProbeConfig(left.networkRecoveryProbe, right.networkRecoveryProbe) && left.hasOutageConfig === right.hasOutageConfig && left.outageEnabledByDefault === right.outageEnabledByDefault && left.mutationQueueingByDefault.network === right.mutationQueueingByDefault.network && left.mutationQueueingByDefault.outage === right.mutationQueueingByDefault.outage && left.classifyFailure === right.classifyFailure && left.classifyRetriableFailure === right.classifyRetriableFailure && left.outageRecoveryCheck === right.outageRecoveryCheck && sameProbeConfig(left.outageRecoveryProbe, right.outageRecoveryProbe);
4680
+ return left.isSessionEnabled === right.isSessionEnabled && left.hasNetworkConfig === right.hasNetworkConfig && left.networkEnabledByDefault === right.networkEnabledByDefault && left.networkListenToBrowserEvents === right.networkListenToBrowserEvents && left.getIsOffline === right.getIsOffline && left.networkRecoveryCheck === right.networkRecoveryCheck && sameProbeConfig(left.networkRecoveryProbe, right.networkRecoveryProbe) && left.hasOutageConfig === right.hasOutageConfig && left.outageEnabledByDefault === right.outageEnabledByDefault && left.mutationQueueingByDefault.network === right.mutationQueueingByDefault.network && left.mutationQueueingByDefault.outage === right.mutationQueueingByDefault.outage && left.classifyFailure === right.classifyFailure && left.classifyRetriableFailure === right.classifyRetriableFailure && left.healthCheck === right.healthCheck && left.healthCheckTimeoutMs === right.healthCheckTimeoutMs && left.outageRecoveryCheck === right.outageRecoveryCheck && sameProbeConfig(left.outageRecoveryProbe, right.outageRecoveryProbe);
4613
4681
  }
4614
4682
  function sameUploadsConfig(left, right) {
4615
- return left?.adapter === right?.adapter && left?.upload === right?.upload && (left?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY) === (right?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY);
4616
- }
4617
- function eraseOfflineSession(session) {
4618
- return __LEGIT_CAST__(session);
4619
- }
4620
- function eraseUploadsConfig(uploads) {
4621
- return __LEGIT_CAST__(uploads);
4683
+ return left?.adapter === right?.adapter && left?.upload === right?.upload && left?.resolvedRefSchema === right?.resolvedRefSchema && (left?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY) === (right?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY);
4622
4684
  }
4623
4685
  function castUploads(uploads) {
4624
4686
  return __LEGIT_CAST__(uploads);
@@ -4692,6 +4754,11 @@ var SessionOfflineCoordinator = class {
4692
4754
  #uploadQueue;
4693
4755
  #uploadPromisesById = /* @__PURE__ */ new Map();
4694
4756
  /**
4757
+ * Validation outcome of the refs in the latest remote snapshot, so a ref
4758
+ * repeated across snapshots is parsed once per record version.
4759
+ */
4760
+ #remoteUploadRefValidations = /* @__PURE__ */ new Map();
4761
+ /**
4695
4762
  * Uploads released by work that left the queue but not deleted yet: a store
4696
4763
  * had not reported its references, or the upload was still being sent.
4697
4764
  */
@@ -4714,6 +4781,7 @@ var SessionOfflineCoordinator = class {
4714
4781
  #uploadOnlineSessionStartedAt = null;
4715
4782
  #uploadOnlineSessionStabilizationTimer = null;
4716
4783
  #uploadRetentionToken = 0;
4784
+ #uploadFiles = /* @__PURE__ */ new Map();
4717
4785
  #cleanupNetworkListeners = null;
4718
4786
  #canonicalConfig;
4719
4787
  #hasCanonicalConfig;
@@ -4725,7 +4793,16 @@ var SessionOfflineCoordinator = class {
4725
4793
  #recoveryTimer = null;
4726
4794
  #scheduledRecoveryMode = null;
4727
4795
  #recoveryAttempt = 0;
4796
+ /** Health check in flight, shared by every caller asking meanwhile. */
4797
+ #healthCheckInFlight = null;
4728
4798
  #classifiedNetworkActive = false;
4799
+ /** Last value of the session gate applied to the status. */
4800
+ #appliedSessionEnabled = true;
4801
+ /**
4802
+ * The gate reopened and no green cycle ran since: mutations queued before
4803
+ * it closed are waiting for one to be replayed.
4804
+ */
4805
+ #gateReopenedWithoutReplay = false;
4729
4806
  /** Tabs of this session that sent anything on the session channel. */
4730
4807
  #otherTabIds = /* @__PURE__ */ new Set();
4731
4808
  #networkEnabledOverride;
@@ -4768,6 +4845,7 @@ var SessionOfflineCoordinator = class {
4768
4845
  state: () => ({
4769
4846
  status: bootstrappedLocalSnapshot?.status ?? resolveDefaultStatus(sessionKey, { bootstrapStatusFromLocalStorage: shouldBootstrapFromStorage }),
4770
4847
  entities: [],
4848
+ attemptedCreationEntityIds: [],
4771
4849
  resolutions: [],
4772
4850
  uploads: [],
4773
4851
  hasQueuedMutations: false
@@ -4940,6 +5018,19 @@ var SessionOfflineCoordinator = class {
4940
5018
  this.#refreshAggregates(!isRemoteChange);
4941
5019
  if (replayHeadChanged) this.#notifyGreenCycle();
4942
5020
  }
5021
+ /**
5022
+ * Lets the other stores of the session drop the queued work they declared
5023
+ * as `cancelledWith` entities of `sourceStoreName` that will never exist on
5024
+ * the server.
5025
+ */
5026
+ async notifyTempEntitiesCancelled(sourceStoreName, cancelledEntityKeys, getEntityKey) {
5027
+ const pendingCleanups = [];
5028
+ for (const registration of this.#registrations.values()) {
5029
+ if (registration.storeName === sourceStoreName || !registration.onTempEntitiesCancelled) continue;
5030
+ pendingCleanups.push(registration.onTempEntitiesCancelled(sourceStoreName, cancelledEntityKeys, getEntityKey));
5031
+ }
5032
+ for (const result of await Promise.allSettled(pendingCleanups)) if (result.status === "rejected") this.#onPersistentStorageError?.(result.reason);
5033
+ }
4943
5034
  /** Tells the other tabs that this tab saved or removed (`null`) a queue entry. */
4944
5035
  publishQueueEntryChange(storeName, entryId, entry) {
4945
5036
  if (this.#disposed) return;
@@ -5059,6 +5150,28 @@ var SessionOfflineCoordinator = class {
5059
5150
  async loadUpload(id) {
5060
5151
  return (await this.#getUploadRecord(id))?.file ?? null;
5061
5152
  }
5153
+ /**
5154
+ * Latest staged file state for `id`. The first read (while rendering) starts
5155
+ * tracking the id, so a file the session already holds is returned right
5156
+ * away instead of going through a `loading` render.
5157
+ */
5158
+ getUploadFile(id) {
5159
+ return this.#getUploadFileEntry(id).value;
5160
+ }
5161
+ /**
5162
+ * Registers a consumer of the staged file for `id`. Consumers of the same id
5163
+ * share one entry, so the file is read and its object URL is created once.
5164
+ */
5165
+ subscribeUploadFile(id, onChange) {
5166
+ const entry = this.#getUploadFileEntry(id);
5167
+ const listener = () => onChange();
5168
+ clearTimeout(entry.releaseTimer);
5169
+ entry.listeners.add(listener);
5170
+ return () => {
5171
+ entry.listeners.delete(listener);
5172
+ if (entry.listeners.size === 0) this.#scheduleUploadFileRelease(id, entry);
5173
+ };
5174
+ }
5062
5175
  async deleteUpload(id) {
5063
5176
  await this.#restoreStoredUploads();
5064
5177
  if (this.#referencedUploadIds.has(id)) throw new Error(`Cannot delete upload "${id}" while it is still referenced`);
@@ -5182,6 +5295,7 @@ var SessionOfflineCoordinator = class {
5182
5295
  return this.#browserTabs.priority.getPriorityRank() <= 1;
5183
5296
  }
5184
5297
  isReplayBlocked() {
5298
+ if (!this.#syncSessionGate()) return true;
5185
5299
  if (this.store.state.status.isOfflineMode) return true;
5186
5300
  const { network, outage } = this.store.state.status;
5187
5301
  if (!outage.enabled && outage.active) return true;
@@ -5210,11 +5324,46 @@ var SessionOfflineCoordinator = class {
5210
5324
  #browserReportsOnline() {
5211
5325
  return !isWindowAvailable() || navigator.onLine !== false;
5212
5326
  }
5327
+ /**
5328
+ * Reads the session gate (`offlineSession.enabled`): while it is closed the
5329
+ * session behaves as if no offline session existed.
5330
+ */
5331
+ #isSessionEnabled() {
5332
+ return this.#canonicalConfig.isSessionEnabled?.() ?? true;
5333
+ }
5213
5334
  #isNetworkEnabled() {
5214
- return this.#canonicalConfig.hasNetworkConfig && (this.#networkEnabledOverride ?? this.#canonicalConfig.networkEnabledByDefault);
5335
+ return this.#canonicalConfig.hasNetworkConfig && (this.#networkEnabledOverride ?? this.#canonicalConfig.networkEnabledByDefault) && this.#isSessionEnabled();
5215
5336
  }
5216
5337
  #isOutageEnabled() {
5217
- return this.#canonicalConfig.hasOutageConfig && (this.#outageEnabledOverride ?? this.#canonicalConfig.outageEnabledByDefault);
5338
+ return this.#canonicalConfig.hasOutageConfig && (this.#outageEnabledOverride ?? this.#canonicalConfig.outageEnabledByDefault) && this.#isSessionEnabled();
5339
+ }
5340
+ /**
5341
+ * Applies a flip of the session gate to the status: closing it leaves
5342
+ * offline mode, whatever the cause. Returns whether the gate is open.
5343
+ *
5344
+ * Every status write runs it first, so the flip is applied whichever path
5345
+ * notices it (a fetch, a recovery check, another tab's snapshot...).
5346
+ */
5347
+ #syncSessionGate() {
5348
+ const enabled = this.#isSessionEnabled();
5349
+ if (enabled === this.#appliedSessionEnabled) return enabled;
5350
+ this.#appliedSessionEnabled = enabled;
5351
+ if (enabled) this.#gateReopenedWithoutReplay = true;
5352
+ const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5353
+ this.#updateStatus((current) => ({
5354
+ ...current,
5355
+ network: {
5356
+ enabled: this.#isNetworkEnabled(),
5357
+ active: current.network.active
5358
+ },
5359
+ outage: {
5360
+ enabled: this.#isOutageEnabled(),
5361
+ active: current.outage.active
5362
+ }
5363
+ }));
5364
+ this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5365
+ this.#handleConnectivityChange(wasEffectivelyOffline, false);
5366
+ return enabled;
5218
5367
  }
5219
5368
  #assertModeIsConfigured(mode) {
5220
5369
  if (mode === "network" ? this.#canonicalConfig.hasNetworkConfig : this.#canonicalConfig.hasOutageConfig) return;
@@ -5304,7 +5453,7 @@ var SessionOfflineCoordinator = class {
5304
5453
  this.setNetworkActive(true, { classified: false });
5305
5454
  return true;
5306
5455
  }
5307
- if (this.#classifiedNetworkActive && this.#browserReportsOnline() && this.#canonicalConfig.networkRecoveryCheck) {
5456
+ if (this.#classifiedNetworkActive && this.#browserReportsOnline() && (this.#canonicalConfig.networkRecoveryCheck || this.#canonicalConfig.healthCheck)) {
5308
5457
  this.#syncRecoveryProbe();
5309
5458
  return true;
5310
5459
  }
@@ -5324,13 +5473,16 @@ var SessionOfflineCoordinator = class {
5324
5473
  });
5325
5474
  }
5326
5475
  async refreshNetworkState() {
5476
+ const sessionEnabled = this.#syncSessionGate();
5327
5477
  const token = ++this.#networkStateToken;
5478
+ if (!sessionEnabled) return false;
5328
5479
  const detectedOffline = this.#getCurrentOfflineState();
5329
- if (typeof detectedOffline === "boolean") return Promise.resolve(this.#applyRefreshedNetworkState(token, detectedOffline));
5330
- const resolvedDetectedOffline = await Promise.resolve(detectedOffline);
5331
- return this.#applyRefreshedNetworkState(token, resolvedDetectedOffline);
5480
+ const isOffline = this.#applyRefreshedNetworkState(token, typeof detectedOffline === "boolean" ? detectedOffline : await detectedOffline);
5481
+ if (this.#gateReopenedWithoutReplay && !isOffline && !this.isReplayBlocked()) this.#notifyGreenCycle();
5482
+ return isOffline;
5332
5483
  }
5333
5484
  setNetworkActive(active, options = {}) {
5485
+ this.#syncSessionGate();
5334
5486
  const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5335
5487
  const wasReplayBlocked = this.isReplayBlocked();
5336
5488
  const nextEnabled = this.#isNetworkEnabled();
@@ -5353,6 +5505,7 @@ var SessionOfflineCoordinator = class {
5353
5505
  this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5354
5506
  }
5355
5507
  setOutageActive(active, options = {}) {
5508
+ this.#syncSessionGate();
5356
5509
  const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5357
5510
  const wasReplayBlocked = this.isReplayBlocked();
5358
5511
  const nextEnabled = this.#isOutageEnabled();
@@ -5369,10 +5522,24 @@ var SessionOfflineCoordinator = class {
5369
5522
  this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5370
5523
  }
5371
5524
  async classifyFailure(error, ctx) {
5372
- if (!this.#canonicalConfig.classifyFailure) return "ignore";
5373
- const token = this.getClassificationToken();
5374
- const result = await this.#canonicalConfig.classifyFailure(error, ctx);
5375
- if (!this.isCurrentClassificationToken(token)) return "ignore";
5525
+ if (!this.#canClassifyFailures()) return "ignore";
5526
+ const { classifyFailure, healthCheck } = this.#canonicalConfig;
5527
+ let result = "unknown";
5528
+ if (classifyFailure) {
5529
+ const token = this.getClassificationToken();
5530
+ result = await classifyFailure(error, ctx);
5531
+ if (!this.#canClassifyFailures()) return "ignore";
5532
+ if (result !== "unknown" && !this.isCurrentClassificationToken(token)) return "ignore";
5533
+ }
5534
+ if (result === "unknown") {
5535
+ if (!healthCheck) return "ignore";
5536
+ if (this.store.state.status.outage.active) return "outage";
5537
+ if (this.store.state.status.network.active) return "network";
5538
+ const health = await this.#checkHealth(healthCheck);
5539
+ if (health === null || health === "up") return "ignore";
5540
+ result = health === "outage" ? "outage" : "network";
5541
+ if (this.store.state.status[result].active) return result;
5542
+ }
5376
5543
  if (result === "outage") {
5377
5544
  if (!this.#isOutageEnabled() && !this.store.state.status.outage.active) return "ignore";
5378
5545
  this.setOutageActive(true);
@@ -5388,6 +5555,49 @@ var SessionOfflineCoordinator = class {
5388
5555
  }
5389
5556
  return "ignore";
5390
5557
  }
5558
+ /**
5559
+ * Runs `offlineSession.healthCheck`. While a check is in flight every
5560
+ * caller (failing requests, a recovery tick) gets that same call instead of
5561
+ * starting its own. A finished answer is not kept: an `up` reused for a
5562
+ * later failure could hide an outage that started right after it.
5563
+ *
5564
+ * Resolves with `null` when the check gave no answer (it threw or timed
5565
+ * out), which callers treat as "nothing learned".
5566
+ */
5567
+ #checkHealth(check) {
5568
+ this.#healthCheckInFlight ??= this.#requestHealth(check).finally(() => {
5569
+ this.#healthCheckInFlight = null;
5570
+ });
5571
+ return this.#healthCheckInFlight;
5572
+ }
5573
+ async #requestHealth(check) {
5574
+ const abortController = new AbortController();
5575
+ let timeout;
5576
+ try {
5577
+ return await Promise.race([check({
5578
+ sessionKey: this.sessionKey,
5579
+ signal: abortController.signal
5580
+ }), new Promise((resolve) => {
5581
+ timeout = setTimeout(() => {
5582
+ abortController.abort();
5583
+ resolve(null);
5584
+ }, this.#canonicalConfig.healthCheckTimeoutMs);
5585
+ })]);
5586
+ } catch {
5587
+ return null;
5588
+ } finally {
5589
+ clearTimeout(timeout);
5590
+ }
5591
+ }
5592
+ /**
5593
+ * Whether classifying a failure can change anything: the session gate has
5594
+ * to be open, with a mode enabled or still active (waiting to recover).
5595
+ */
5596
+ #canClassifyFailures() {
5597
+ if (!this.#isSessionEnabled()) return false;
5598
+ const { network, outage } = this.store.state.status;
5599
+ return network.active || outage.active || this.#isNetworkEnabled() || this.#isOutageEnabled();
5600
+ }
5391
5601
  async classifyRetriableFailure(error, ctx) {
5392
5602
  if (!this.#canonicalConfig.classifyRetriableFailure) return false;
5393
5603
  const token = this.getRetriableFailureToken();
@@ -5397,6 +5607,7 @@ var SessionOfflineCoordinator = class {
5397
5607
  }
5398
5608
  #notifyGreenCycle() {
5399
5609
  if (this.store.state.status.isOfflineMode || !this.isLeader()) return;
5610
+ this.#gateReopenedWithoutReplay = false;
5400
5611
  this.#refreshUploadRetention();
5401
5612
  for (const registration of this.#registrations.values()) registration.onGreenCycle?.();
5402
5613
  }
@@ -5449,7 +5660,7 @@ var SessionOfflineCoordinator = class {
5449
5660
  this.#uploadsRemovedWhileListing = removedWhileListing;
5450
5661
  try {
5451
5662
  const uploads = await uploadsConfig.adapter.list(this.sessionKey);
5452
- this.#uploads = new Map([...uploads.filter((upload) => !removedWhileListing.has(upload.id)).map((upload) => [upload.id, upload]), ...this.#uploads]);
5663
+ this.#uploads = new Map([...uploads.filter((upload) => !removedWhileListing.has(upload.id)).map((upload) => [upload.id, this.#validateRestoredUpload(upload)]), ...this.#uploads]);
5453
5664
  this.#syncUploadsState();
5454
5665
  } catch (error) {
5455
5666
  this.#onPersistentStorageError?.(error);
@@ -5468,11 +5679,101 @@ var SessionOfflineCoordinator = class {
5468
5679
  const loaded = await this.#uploadsConfig.adapter.load(this.sessionKey, id);
5469
5680
  const current = this.#uploads.get(id);
5470
5681
  if (current) return current;
5471
- if (loaded) {
5472
- this.#uploads.set(id, loaded);
5473
- this.#syncUploadsState();
5682
+ if (!loaded) return null;
5683
+ const validated = this.#validateRestoredUpload(loaded);
5684
+ this.#uploads.set(id, validated);
5685
+ this.#syncUploadsState();
5686
+ return validated;
5687
+ }
5688
+ /**
5689
+ * Checks the ref of an upload record restored from the adapter against the
5690
+ * configured `resolvedRefSchema`. Records enter `#uploads` once, so each
5691
+ * stored ref is parsed once.
5692
+ */
5693
+ #validateRestoredUpload(upload) {
5694
+ const schema = this.#uploadsConfig?.resolvedRefSchema;
5695
+ if (schema === void 0 || upload.resolvedRef === void 0) return upload;
5696
+ return applyRestoredUploadRef(upload, parseRestoredUploadRef(schema, upload.resolvedRef));
5697
+ }
5698
+ /** Checks the refs published by another tab against `resolvedRefSchema`. */
5699
+ #validateRemoteUploads(uploads) {
5700
+ const schema = this.#uploadsConfig?.resolvedRefSchema;
5701
+ if (schema === void 0) return uploads;
5702
+ const previousValidations = this.#remoteUploadRefValidations;
5703
+ this.#remoteUploadRefValidations = /* @__PURE__ */ new Map();
5704
+ return uploads.map((upload) => {
5705
+ if (upload.resolvedRef === void 0) return upload;
5706
+ const previous = previousValidations.get(upload.id);
5707
+ const validation = previous?.updatedAt === upload.updatedAt ? previous : {
5708
+ updatedAt: upload.updatedAt,
5709
+ parsedRef: parseRestoredUploadRef(schema, upload.resolvedRef)
5710
+ };
5711
+ this.#remoteUploadRefValidations.set(upload.id, validation);
5712
+ return applyRestoredUploadRef(upload, validation.parsedRef);
5713
+ });
5714
+ }
5715
+ #getUploadFileEntry(id) {
5716
+ const existingEntry = this.#uploadFiles.get(id);
5717
+ if (existingEntry) return existingEntry;
5718
+ const entry = {
5719
+ listeners: /* @__PURE__ */ new Set(),
5720
+ value: loadingUploadFile,
5721
+ releaseTimer: void 0
5722
+ };
5723
+ this.#uploadFiles.set(id, entry);
5724
+ if (!this.#syncUploadFile(id, entry)) this.#loadUploadFile(id, entry);
5725
+ this.#scheduleUploadFileRelease(id, entry);
5726
+ return entry;
5727
+ }
5728
+ /**
5729
+ * Drops the file and revokes its object URL once no hook has consumed the
5730
+ * entry for a moment. The delay keeps the URL stable across StrictMode's
5731
+ * effect replay and components that remount right away.
5732
+ */
5733
+ #scheduleUploadFileRelease(id, entry) {
5734
+ entry.releaseTimer = setTimeout(() => {
5735
+ this.#uploadFiles.delete(id);
5736
+ this.#setUploadFile(entry, loadingUploadFile);
5737
+ }, UPLOAD_FILE_RELEASE_DELAY_MS);
5738
+ }
5739
+ #setUploadFile(entry, value) {
5740
+ const previousUrl = entry.value.url;
5741
+ entry.value = value;
5742
+ if (previousUrl !== null) URL.revokeObjectURL(previousUrl);
5743
+ for (const listener of entry.listeners) listener();
5744
+ }
5745
+ /**
5746
+ * Aligns a consumed upload file with the in-memory upload records. Returns
5747
+ * `false` when the session holds no record for the id.
5748
+ */
5749
+ #syncUploadFile(id, entry) {
5750
+ const file = this.#uploads.get(id)?.file;
5751
+ if (!file) {
5752
+ if (entry.value.file) this.#setUploadFile(entry, missingUploadFile);
5753
+ return false;
5754
+ }
5755
+ if (entry.value.file !== file) this.#setUploadFile(entry, {
5756
+ status: "success",
5757
+ url: URL.createObjectURL(file),
5758
+ file,
5759
+ error: null
5760
+ });
5761
+ return true;
5762
+ }
5763
+ async #loadUploadFile(id, entry) {
5764
+ let failure;
5765
+ try {
5766
+ await this.#getUploadRecord(id);
5767
+ } catch (error) {
5768
+ failure = unknownToError(error);
5474
5769
  }
5475
- return loaded;
5770
+ if (this.#uploadFiles.get(id) !== entry || this.#syncUploadFile(id, entry) || entry.value.status !== "loading") return;
5771
+ this.#setUploadFile(entry, failure ? {
5772
+ status: "error",
5773
+ url: null,
5774
+ file: null,
5775
+ error: failure
5776
+ } : missingUploadFile);
5476
5777
  }
5477
5778
  async #waitForUploadRemoval(id) {
5478
5779
  let removal = this.#uploadRemovals.get(id);
@@ -5583,6 +5884,7 @@ var SessionOfflineCoordinator = class {
5583
5884
  const uploads = [...this.#uploads.values()].map(stripStoredUploadFile).sort((left, right) => left.id.localeCompare(right.id));
5584
5885
  this.store.setPartialState({ uploads }, { action: "offline-session-uploads" });
5585
5886
  this.#publishSnapshot();
5887
+ for (const [id, entry] of this.#uploadFiles) this.#syncUploadFile(id, entry);
5586
5888
  }
5587
5889
  #buildNextUploadRecord(current, args) {
5588
5890
  const nextRecord = {
@@ -5692,9 +5994,9 @@ var SessionOfflineCoordinator = class {
5692
5994
  return this.#removeStoredUpload(uploadsConfig, id);
5693
5995
  }));
5694
5996
  } finally {
5997
+ this.#syncUploadsState();
5695
5998
  this.#publishUploadsRemoved(ids);
5696
5999
  }
5697
- this.#syncUploadsState();
5698
6000
  this.#refreshUploadRetention();
5699
6001
  }
5700
6002
  /** Tells the other tabs that this tab deleted these stored uploads. */
@@ -5719,9 +6021,17 @@ var SessionOfflineCoordinator = class {
5719
6021
  this.#uploads.delete(id);
5720
6022
  this.#uploadsRemovedWhileListing?.add(id);
5721
6023
  }
5722
- for (const [id, ref] of releasedRefs) this.#releasedUploadRefs.set(id, ref);
6024
+ const schema = this.#uploadsConfig?.resolvedRefSchema;
6025
+ for (const [id, ref] of releasedRefs) {
6026
+ const parsedRef = schema === void 0 ? ref : parseRestoredUploadRef(schema, ref);
6027
+ if (parsedRef !== void 0) this.#releasedUploadRefs.set(id, parsedRef);
6028
+ }
5723
6029
  const { uploads } = this.store.state;
5724
6030
  if (uploads.some((upload) => removedIds.has(upload.id))) this.store.setPartialState({ uploads: uploads.filter((upload) => !removedIds.has(upload.id)) }, { action: "offline-session-uploads" });
6031
+ for (const id of removedIds) {
6032
+ const entry = this.#uploadFiles.get(id);
6033
+ if (entry) this.#syncUploadFile(id, entry);
6034
+ }
5725
6035
  }
5726
6036
  /**
5727
6037
  * Removes an upload from the adapter, tracking the removal so a save or
@@ -5742,21 +6052,25 @@ var SessionOfflineCoordinator = class {
5742
6052
  */
5743
6053
  #buildItemLists() {
5744
6054
  const allEntities = [];
6055
+ const attemptedCreationEntityIds = [];
5745
6056
  const allResolutions = [];
5746
6057
  let hasQueuedMutations = false;
5747
6058
  for (const contribution of this.#storeContributions.values()) {
5748
6059
  if (contribution.replayHead !== null) hasQueuedMutations = true;
5749
6060
  allEntities.push(...contribution.entities);
6061
+ attemptedCreationEntityIds.push(...contribution.attemptedCreationEntityIds);
5750
6062
  allResolutions.push(...contribution.resolutions);
5751
6063
  }
5752
6064
  for (const [storeName, items] of this.#remoteStoreItems) {
5753
6065
  if (this.#storeContributions.has(storeName)) continue;
5754
6066
  if (items.hasQueuedMutations) hasQueuedMutations = true;
5755
6067
  allEntities.push(...items.entities);
6068
+ attemptedCreationEntityIds.push(...items.attemptedCreationEntityIds);
5756
6069
  allResolutions.push(...items.resolutions);
5757
6070
  }
5758
6071
  return {
5759
6072
  entities: dedupeById(allEntities),
6073
+ attemptedCreationEntityIds,
5760
6074
  resolutions: dedupeById(allResolutions),
5761
6075
  hasQueuedMutations
5762
6076
  };
@@ -5770,7 +6084,7 @@ var SessionOfflineCoordinator = class {
5770
6084
  existing.push(...contribution.protectedKeys);
5771
6085
  nextProtectedKeysByAdapter.set(contribution.adapter, existing);
5772
6086
  }
5773
- const { entities, resolutions, hasQueuedMutations } = this.#buildItemLists();
6087
+ const { entities, attemptedCreationEntityIds, resolutions, hasQueuedMutations } = this.#buildItemLists();
5774
6088
  for (const [adapter, keys] of nextProtectedKeysByAdapter) nextProtectedKeysByAdapter.set(adapter, [...new Set(keys)].sort());
5775
6089
  const nextProtectedKeys = [...new Set([...nextProtectedKeysByAdapter.values()].flat())].sort();
5776
6090
  const adaptersToSync = publish ? new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]) : /* @__PURE__ */ new Set();
@@ -5825,6 +6139,7 @@ var SessionOfflineCoordinator = class {
5825
6139
  }
5826
6140
  this.store.setPartialState({
5827
6141
  entities,
6142
+ attemptedCreationEntityIds,
5828
6143
  resolutions,
5829
6144
  hasQueuedMutations
5830
6145
  }, { action: "offline-session-aggregate" });
@@ -5843,13 +6158,19 @@ var SessionOfflineCoordinator = class {
5843
6158
  };
5844
6159
  }
5845
6160
  #deriveLocalStatus(status) {
5846
- const isOfflineMode = getIsOfflineModeFromStatus(status);
5847
- return this.#stampLocalStatus({
6161
+ const gatedStatus = this.#isSessionEnabled() ? status : {
5848
6162
  ...status,
6163
+ network: INACTIVE_MODE,
6164
+ outage: INACTIVE_MODE
6165
+ };
6166
+ const isOfflineMode = getIsOfflineModeFromStatus(gatedStatus);
6167
+ return this.#stampLocalStatus({
6168
+ ...gatedStatus,
5849
6169
  isOfflineMode
5850
6170
  });
5851
6171
  }
5852
6172
  #updateStatus(updater) {
6173
+ this.#syncSessionGate();
5853
6174
  const derived = this.#deriveLocalStatus(updater(this.store.state.status));
5854
6175
  this.store.setPartialState({ status: derived }, { action: "offline-session-status" });
5855
6176
  this.#persistSessionSnapshot();
@@ -5870,23 +6191,30 @@ var SessionOfflineCoordinator = class {
5870
6191
  status,
5871
6192
  storeNames: [...this.#storeContributions.keys()],
5872
6193
  entities: contributions.flatMap((contribution) => contribution.entities),
6194
+ attemptedCreationEntityIds: contributions.flatMap((contribution) => contribution.attemptedCreationEntityIds),
5873
6195
  resolutions: contributions.flatMap((contribution) => contribution.resolutions),
5874
6196
  uploads: this.store.state.uploads,
5875
6197
  queuedStoreNames: [...this.#storeContributions].filter(([, contribution]) => contribution.replayHead !== null).map(([storeName]) => storeName)
5876
6198
  });
5877
6199
  }
5878
6200
  #applyRemoteSnapshot(message) {
5879
- for (const storeName of message.storeNames) this.#remoteStoreItems.set(storeName, {
5880
- entities: message.entities.filter((entity) => entity.storeName === storeName),
5881
- resolutions: message.resolutions.filter((resolution) => resolution.storeName === storeName),
5882
- hasQueuedMutations: message.queuedStoreNames.includes(storeName)
5883
- });
6201
+ const attemptedCreationEntityIds = message.attemptedCreationEntityIds;
6202
+ for (const storeName of message.storeNames) {
6203
+ const entities = message.entities.filter((entity) => entity.storeName === storeName);
6204
+ this.#remoteStoreItems.set(storeName, {
6205
+ entities,
6206
+ attemptedCreationEntityIds: attemptedCreationEntityIds ? entities.filter((entity) => attemptedCreationEntityIds.includes(entity.id)).map((entity) => entity.id) : [],
6207
+ resolutions: message.resolutions.filter((resolution) => resolution.storeName === storeName),
6208
+ hasQueuedMutations: message.queuedStoreNames.includes(storeName)
6209
+ });
6210
+ }
5884
6211
  if (message.sentAt < this.#lastRemoteSnapshotAt) {
5885
6212
  this.store.setPartialState(this.#buildItemLists(), { action: "offline-session-remote" });
5886
6213
  this.#persistSessionSnapshot();
5887
6214
  return;
5888
6215
  }
5889
6216
  this.#lastRemoteSnapshotAt = message.sentAt;
6217
+ this.#syncSessionGate();
5890
6218
  const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5891
6219
  const wasReplayBlocked = this.isReplayBlocked();
5892
6220
  const isDetectedOffline = this.#isNetworkEnabled() && (this.store.state.status.network.active && !this.#classifiedNetworkActive || !this.#browserReportsOnline());
@@ -5902,7 +6230,7 @@ var SessionOfflineCoordinator = class {
5902
6230
  updatedAt: Date.now()
5903
6231
  }),
5904
6232
  ...this.#buildItemLists(),
5905
- uploads: message.uploads
6233
+ uploads: this.#validateRemoteUploads(message.uploads)
5906
6234
  }, { action: "offline-session-remote" });
5907
6235
  if (!isDetectedOffline) this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5908
6236
  this.#persistSessionSnapshot();
@@ -5946,20 +6274,22 @@ var SessionOfflineCoordinator = class {
5946
6274
  return Math.max(0, Math.round(baseDelay + (Math.random() * jitter * 2 - jitter)));
5947
6275
  }
5948
6276
  #getDesiredRecoveryTarget() {
5949
- if (!this.isLeader() || this.#registrations.size === 0) return null;
5950
- if (this.store.state.status.network.active && this.#classifiedNetworkActive && this.#browserReportsOnline() && this.#canonicalConfig.networkRecoveryCheck) return {
6277
+ if (this.#disposed || !this.isLeader() || this.#registrations.size === 0) return null;
6278
+ const { networkRecoveryCheck, outageRecoveryCheck, healthCheck } = this.#canonicalConfig;
6279
+ if (this.store.state.status.network.active && this.#classifiedNetworkActive && this.#browserReportsOnline() && (networkRecoveryCheck || healthCheck)) return {
5951
6280
  mode: "network",
5952
- recoveryCheck: this.#canonicalConfig.networkRecoveryCheck,
6281
+ recoveryCheck: networkRecoveryCheck,
5953
6282
  recoveryProbe: this.#canonicalConfig.networkRecoveryProbe
5954
6283
  };
5955
- if (this.store.state.status.outage.active && !this.store.state.status.network.active && this.#canonicalConfig.outageRecoveryCheck) return {
6284
+ if (this.store.state.status.outage.active && !this.store.state.status.network.active && (outageRecoveryCheck || healthCheck)) return {
5956
6285
  mode: "outage",
5957
- recoveryCheck: this.#canonicalConfig.outageRecoveryCheck,
6286
+ recoveryCheck: outageRecoveryCheck,
5958
6287
  recoveryProbe: this.#canonicalConfig.outageRecoveryProbe
5959
6288
  };
5960
6289
  return null;
5961
6290
  }
5962
6291
  #scheduleRecoveryProbe(target) {
6292
+ if (this.#recoveryTimer !== null) clearTimeout(this.#recoveryTimer);
5963
6293
  this.#scheduledRecoveryMode = target.mode;
5964
6294
  this.#recoveryTimer = setTimeout(() => {
5965
6295
  this.#recoveryTimer = null;
@@ -5968,14 +6298,22 @@ var SessionOfflineCoordinator = class {
5968
6298
  }, this.#getRecoveryProbeDelay(target.recoveryProbe));
5969
6299
  }
5970
6300
  async #runRecoveryProbe(target) {
6301
+ this.#syncSessionGate();
5971
6302
  const nextTarget = this.#getDesiredRecoveryTarget();
5972
6303
  if (nextTarget === null || nextTarget.mode !== target.mode) return;
6304
+ const { healthCheck, outageRecoveryCheck } = this.#canonicalConfig;
5973
6305
  let recovered = false;
5974
- try {
6306
+ let health = null;
6307
+ if (nextTarget.recoveryCheck) try {
5975
6308
  recovered = await nextTarget.recoveryCheck({ sessionKey: this.sessionKey });
5976
6309
  } catch {
5977
6310
  recovered = false;
5978
6311
  }
6312
+ else if (healthCheck) {
6313
+ health = await this.#checkHealth(healthCheck);
6314
+ recovered = health === "up";
6315
+ }
6316
+ if (this.#disposed) return;
5979
6317
  const recoveryCheckAt = Date.now();
5980
6318
  if (recovered) {
5981
6319
  this.#recoveryAttempt = 0;
@@ -5984,11 +6322,28 @@ var SessionOfflineCoordinator = class {
5984
6322
  classified: false,
5985
6323
  recoveryCheckAt
5986
6324
  });
6325
+ if (health === "up" && !outageRecoveryCheck && this.store.state.status.outage.active && !this.store.state.status.network.active) this.setOutageActive(false, { recoveryCheckAt });
5987
6326
  return;
5988
6327
  }
5989
6328
  this.setOutageActive(false, { recoveryCheckAt });
5990
6329
  return;
5991
6330
  }
6331
+ if (target.mode === "network" && health === "outage") {
6332
+ if (!this.store.state.status.outage.active && this.#isOutageEnabled()) this.setOutageActive(true, { recoveryCheckAt });
6333
+ this.setNetworkActive(false, {
6334
+ classified: false,
6335
+ recoveryCheckAt
6336
+ });
6337
+ return;
6338
+ }
6339
+ if (target.mode === "outage" && health === "unreachable" && this.#isNetworkEnabled()) {
6340
+ this.setNetworkActive(true, {
6341
+ classified: true,
6342
+ recordFailureAt: true,
6343
+ recoveryCheckAt
6344
+ });
6345
+ return;
6346
+ }
5992
6347
  this.#updateStatus((current) => ({
5993
6348
  ...current,
5994
6349
  lastRecoveryCheckAt: recoveryCheckAt
@@ -6078,7 +6433,7 @@ function getGlobalOfflineResolutions(sessionKey) {
6078
6433
  return registry.get(sessionKey)?.getResolutions() ?? [];
6079
6434
  }
6080
6435
  function getOfflineSessionUploadsConfig(session) {
6081
- return __LEGIT_CAST__(uploadsConfigByOfflineSession.get(eraseOfflineSession(session)));
6436
+ return uploadsConfigByOfflineSession.get(session);
6082
6437
  }
6083
6438
  function getOfflineSessionAppVersion(session) {
6084
6439
  return appVersionByOfflineSession.get(session);
@@ -6103,13 +6458,13 @@ function createOfflineSession(args) {
6103
6458
  config,
6104
6459
  ...args.appVersion !== void 0 ? { appVersion: args.appVersion } : void 0,
6105
6460
  ...import.meta.env.DEV ? { debugLogger: args.debugLogger } : void 0,
6106
- uploads: eraseUploadsConfig(uploads),
6461
+ uploads,
6107
6462
  bootstrapStatusFromLocalStorage
6108
6463
  });
6109
6464
  }
6110
6465
  function useSessionCoordinator() {
6111
6466
  const activeSessionKey = getSessionKey();
6112
- return useConfiguredSessionOfflineCoordinator(activeSessionKey === false ? resolveOfflineSessionScope(false, inactiveScope) : activeSessionKey, activeSessionKey === false ? void 0 : config, eraseUploadsConfig(activeSessionKey === false ? void 0 : uploads), activeSessionKey !== false, import.meta.env.DEV ? args.debugLogger : void 0, args.appVersion);
6467
+ return useConfiguredSessionOfflineCoordinator(activeSessionKey === false ? resolveOfflineSessionScope(false, inactiveScope) : activeSessionKey, activeSessionKey === false ? void 0 : config, activeSessionKey === false ? void 0 : uploads, activeSessionKey !== false, import.meta.env.DEV ? args.debugLogger : void 0, args.appVersion);
6113
6468
  }
6114
6469
  const session = {
6115
6470
  getSessionKey,
@@ -6200,10 +6555,14 @@ function createOfflineSession(args) {
6200
6555
  const coordinator = useSessionCoordinator();
6201
6556
  const uploadsSelector = useCallback((state) => state.uploads, []);
6202
6557
  return castUploads(coordinator.store.useSelector(uploadsSelector, { equalityFn: deepEqual }));
6558
+ },
6559
+ useOfflineUploadFile: (id) => {
6560
+ const coordinator = useSessionCoordinator();
6561
+ return useSyncExternalStore(useCallback((onChange) => id ? coordinator.subscribeUploadFile(id, onChange) : noop, [coordinator, id]), useCallback(() => id ? coordinator.getUploadFile(id) : idleUploadFile, [coordinator, id]));
6203
6562
  }
6204
6563
  };
6205
- uploadsConfigByOfflineSession.set(eraseOfflineSession(session), eraseUploadsConfig(uploads));
6206
- appVersionByOfflineSession.set(eraseOfflineSession(session), args.appVersion);
6564
+ uploadsConfigByOfflineSession.set(session, uploads);
6565
+ appVersionByOfflineSession.set(session, args.appVersion);
6207
6566
  return session;
6208
6567
  }
6209
6568
  function useSessionOfflineCoordinator(sessionKey, bootstrapStatusFromLocalStorage = false) {
@@ -6272,7 +6631,7 @@ function useOfflineStoreEntities(args) {
6272
6631
  */
6273
6632
  function useOfflineStoreItemState(sessionKey, inactiveScope, storeName, itemKey) {
6274
6633
  const coordinator = useSessionOfflineCoordinator(resolveOfflineSessionScope(sessionKey, inactiveScope), false);
6275
- const itemStateSelector = useCallback((state) => storeName === void 0 || itemKey === null ? null : toItemOfflineState(getOfflineStoreEntityLookup(state.entities, storeName).get(itemKey)), [itemKey, storeName]);
6634
+ const itemStateSelector = useCallback((state) => storeName === void 0 || itemKey === null ? null : toItemOfflineState(getOfflineStoreEntityLookup(state.entities, storeName).get(itemKey), state.attemptedCreationEntityIds), [itemKey, storeName]);
6276
6635
  return coordinator.store.useSelector(itemStateSelector, { equalityFn: deepEqual });
6277
6636
  }
6278
6637
  /**
@@ -6319,7 +6678,7 @@ const compactOfflineEntitySchema = rc_object({
6319
6678
  a: rc_number,
6320
6679
  u: rc_number,
6321
6680
  t: rc_unknown.optionalKey(),
6322
- v: rc_unknown.optionalKey()
6681
+ y: rc_unknown.optionalKey()
6323
6682
  });
6324
6683
  const compactOfflineQueueEntrySchema = rc_object({
6325
6684
  d: rc_string,
@@ -6514,9 +6873,20 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6514
6873
  const replayRetryIntervalMs = sessionConfig.replayRetry?.intervalMs ?? DEFAULT_REPLAY_RETRY_INTERVAL_MS;
6515
6874
  const queueEntries = /* @__PURE__ */ new Map();
6516
6875
  const resolutions = /* @__PURE__ */ new Map();
6876
+ const hasCancelledWithOperations = Object.values(operations).some((operation) => operation.cancelledWith !== void 0);
6877
+ const unknownOperationUploadIds = /* @__PURE__ */ new Map();
6878
+ function trackUnknownOperationUploads(recordKey, record) {
6879
+ const uploadIds = record ? [...Object.values(record.attachedUploadIds ?? {}), ...record.dependencyUploadIds ?? []] : [];
6880
+ if (uploadIds.length > 0) unknownOperationUploadIds.set(recordKey, uploadIds);
6881
+ else unknownOperationUploadIds.delete(recordKey);
6882
+ }
6517
6883
  const countedReplayFailures = /* @__PURE__ */ new Map();
6518
6884
  const entryIdsFromAnotherTab = /* @__PURE__ */ new Set();
6519
6885
  const resolvedEntityRefBySerializedRef = /* @__PURE__ */ new Map();
6886
+ /** Reads the session gate (`offlineSession.enabled`). */
6887
+ function isSessionEnabled() {
6888
+ return sessionConfig.enabled?.() !== false;
6889
+ }
6520
6890
  function getActiveMutationQueueingCause(current) {
6521
6891
  const status = current.session.getStatus();
6522
6892
  if (isModeEffectivelyActive(status.network)) return "network";
@@ -6542,10 +6912,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6542
6912
  * Whether mutations queued earlier for the entities this mutation affects
6543
6913
  * or depends on (`dependsOn`), or that depend on an entity this mutation
6544
6914
  * affects, are still waiting to reach the server (queued, replaying or
6545
- * unconfirmed).
6915
+ * unconfirmed), or the creation of one of those entities waits for a manual
6916
+ * resolution.
6546
6917
  */
6547
6918
  function hasQueuedWorkForSameEntities(prepared) {
6548
- if (queueEntries.size === 0) return false;
6919
+ if (queueEntries.size === 0 && resolutions.size === 0) return false;
6549
6920
  const affectedEntityRefs = prepared.entityRefs ?? resolveNormalizedRefs(getOperationRawEntityRefs(prepared.operation, prepared.operationName, prepared.validatedInput));
6550
6921
  const entityRefs = [...affectedEntityRefs, ...prepared.operation.dependsOn ? resolveNormalizedRefs(prepared.operation.dependsOn({ input: prepared.validatedInput })) : []];
6551
6922
  for (const entry of queueEntries.values()) {
@@ -6553,7 +6924,13 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6553
6924
  const queuedDependencyKeys = getDependencyBlockerEntityKeys(entry);
6554
6925
  if (affectedEntityRefs.some((entityRef) => queuedDependencyKeys.has(entityRef.entityKey))) return true;
6555
6926
  }
6556
- return false;
6927
+ if ((prepared.operation.accumulation || prepared.operation.supersedes) && findHeldWorkResolutions((resolution) => resolution.entityRefs.some((resolutionRef) => affectedEntityRefs.some((entityRef) => isSameEntityRef(entityRef, resolutionRef)))).length > 0) return true;
6928
+ return isHeldBehindTempCreateResolution({
6929
+ operation: prepared.operationName,
6930
+ input: prepared.validatedInput,
6931
+ entityRefs,
6932
+ tempIds: prepared.tempIds
6933
+ });
6557
6934
  }
6558
6935
  function getInitialOfflineMutationAction(current, prepared) {
6559
6936
  if (!current.session.getStatus().isOfflineMode) return hasQueuedWorkForSameEntities(prepared) ? "queue" : "run";
@@ -6627,6 +7004,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6627
7004
  queueEntries.clear();
6628
7005
  entryIdsFromAnotherTab.clear();
6629
7006
  resolutions.clear();
7007
+ unknownOperationUploadIds.clear();
6630
7008
  nextQueueOrder = 0;
6631
7009
  hydratedSessionKey = null;
6632
7010
  hydratedPromise = null;
@@ -6742,7 +7120,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6742
7120
  a: entity.createdAt,
6743
7121
  u: entity.updatedAt,
6744
7122
  ...entity.tempId !== void 0 ? { t: entity.tempId } : {},
6745
- ...entity.payload !== void 0 ? { v: entity.payload } : {}
7123
+ ...entity.payload !== void 0 ? { y: entity.payload } : {}
6746
7124
  };
6747
7125
  },
6748
7126
  deserialize(raw) {
@@ -6769,7 +7147,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6769
7147
  createdAt: compactEntity.a,
6770
7148
  updatedAt: compactEntity.u,
6771
7149
  ...compactEntity.t !== void 0 ? { tempId: __LEGIT_CAST__(compactEntity.t) } : {},
6772
- ...compactEntity.v !== void 0 ? { payload: __LEGIT_CAST__(compactEntity.v) } : {}
7150
+ ...compactEntity.y !== void 0 ? { payload: __LEGIT_CAST__(compactEntity.y) } : {}
6773
7151
  };
6774
7152
  }
6775
7153
  } });
@@ -6784,15 +7162,20 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6784
7162
  onOfflineCycle: () => {
6785
7163
  resetReplayRetryState();
6786
7164
  },
7165
+ onTempEntitiesCancelled: hasCancelledWithOperations ? discardWorkCancelledWithExternalTempEntities : void 0,
6787
7166
  onRemoteQueueEntryChange: (entryId, entry) => {
6788
7167
  applyRecordChangeFromAnotherTab(() => {
6789
7168
  if (entry) {
6790
7169
  nextQueueOrder = Math.max(nextQueueOrder, getQueueOrder(entry) + 1);
6791
- if (!operations[entry.operation]) return;
7170
+ if (!operations[entry.operation]) {
7171
+ trackUnknownOperationUploads(`q:${entryId}`, entry);
7172
+ return;
7173
+ }
6792
7174
  queueEntries.set(entryId, entry);
6793
7175
  entryIdsFromAnotherTab.add(entryId);
6794
7176
  return;
6795
7177
  }
7178
+ trackUnknownOperationUploads(`q:${entryId}`, null);
6796
7179
  queueEntries.delete(entryId);
6797
7180
  entryIdsFromAnotherTab.delete(entryId);
6798
7181
  countedReplayFailures.delete(entryId);
@@ -6801,8 +7184,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6801
7184
  },
6802
7185
  onRemoteResolutionChange: (resolutionId, resolution) => {
6803
7186
  applyRecordChangeFromAnotherTab(() => {
6804
- if (resolution && rc_parse(resolution, offlineResolutionRecordSchema).ok && operations[resolution.operation]) resolutions.set(resolutionId, resolution);
7187
+ const parsedResolution = resolution && rc_parse(resolution, offlineResolutionRecordSchema).ok ? resolution : null;
7188
+ if (parsedResolution && operations[parsedResolution.operation]) resolutions.set(resolutionId, parsedResolution);
6805
7189
  else resolutions.delete(resolutionId);
7190
+ trackUnknownOperationUploads(`r:${resolutionId}`, parsedResolution && !operations[parsedResolution.operation] ? parsedResolution : null);
6806
7191
  });
6807
7192
  },
6808
7193
  onRemoteWorkDiscarded: (discardedWork, removedEntityKeys) => {
@@ -6833,24 +7218,20 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6833
7218
  queueEntries.clear();
6834
7219
  entryIdsFromAnotherTab.clear();
6835
7220
  resolutions.clear();
6836
- for (const entry of loadedQueueEntries.values()) queueEntries.set(entry.id, entry);
6837
- const droppedResolutions = [];
7221
+ unknownOperationUploadIds.clear();
7222
+ for (const entry of loadedQueueEntries.values()) if (operations[entry.operation]) queueEntries.set(entry.id, entry);
7223
+ else trackUnknownOperationUploads(`q:${entry.id}`, entry);
6838
7224
  for (const resolution of loadedResolutionEntries.values()) {
6839
7225
  if (!rc_parse(resolution, offlineResolutionRecordSchema).ok) {
6840
7226
  current.resolutionNamespace.remove(resolution.id);
6841
7227
  continue;
6842
7228
  }
6843
- if (!operations[resolution.operation]) {
6844
- current.resolutionNamespace.remove(resolution.id);
6845
- droppedResolutions.push(resolution);
6846
- continue;
6847
- }
6848
- resolutions.set(resolution.id, resolution);
7229
+ if (operations[resolution.operation]) resolutions.set(resolution.id, resolution);
7230
+ else trackUnknownOperationUploads(`r:${resolution.id}`, resolution);
6849
7231
  }
6850
7232
  nextQueueOrder = getNextQueueOrder(loadedQueueEntries.values());
6851
7233
  hydratedSessionKey = current.sessionKey;
6852
7234
  refreshDerivedState(current);
6853
- deleteOrphanedDependencyUploads(current, droppedResolutions);
6854
7235
  })().finally(() => {
6855
7236
  hydratedPromise = null;
6856
7237
  });
@@ -7009,6 +7390,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7009
7390
  const sessionState = session;
7010
7391
  const dependencySnapshot = createResolutionDependencySnapshot();
7011
7392
  const entitiesByKey = /* @__PURE__ */ new Map();
7393
+ const attemptedCreationEntityKeys = /* @__PURE__ */ new Set();
7012
7394
  function createEntityBase(ref) {
7013
7395
  return {
7014
7396
  id: buildEntityId(sessionState.sessionKey, storeName, ref.entityKey),
@@ -7025,6 +7407,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7025
7407
  const existing = entitiesByKey.get(ref.entityKey);
7026
7408
  const childResolutionIds = dependencySnapshot.childResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
7027
7409
  const blockedByResolutionIds = dependencySnapshot.blockedByResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
7410
+ const tempId = getTempIdForEntityRef({
7411
+ entityRefs: entry.entityRefs,
7412
+ tempIds: entry.tempIds,
7413
+ entityKey: ref.entityKey
7414
+ });
7028
7415
  entitiesByKey.set(ref.entityKey, {
7029
7416
  ...createEntityBase(ref),
7030
7417
  kind: reduceOfflineEntityKind(existing?.kind, operationKind),
@@ -7037,17 +7424,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7037
7424
  childResolutionCount: childResolutionIds.length,
7038
7425
  createdAt: existing?.createdAt ?? entry.createdAt,
7039
7426
  updatedAt: entry.updatedAt,
7040
- tempId: getTempIdForEntityRef({
7041
- entityRefs: entry.entityRefs,
7042
- tempIds: entry.tempIds,
7043
- entityKey: ref.entityKey
7044
- }) ?? existing?.tempId,
7427
+ tempId: tempId ?? existing?.tempId,
7045
7428
  payload: getPayloadForEntityRef({
7046
7429
  operationName: entry.operation,
7047
7430
  input: entry.input,
7048
7431
  entityKey: ref.entityKey
7049
7432
  }) ?? existing?.payload
7050
7433
  });
7434
+ if (tempId !== void 0 && !isUnsentQueueEntry(entry)) attemptedCreationEntityKeys.add(ref.entityKey);
7051
7435
  }
7052
7436
  }
7053
7437
  for (const resolution of resolutions.values()) {
@@ -7056,6 +7440,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7056
7440
  const existing = entitiesByKey.get(ref.entityKey);
7057
7441
  const childResolutionIds = dependencySnapshot.childResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
7058
7442
  const blockedByResolutionIds = dependencySnapshot.blockedByResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
7443
+ const tempId = getTempIdForEntityRef({
7444
+ entityRefs: resolution.entityRefs,
7445
+ tempIds: resolution.tempIds,
7446
+ entityKey: ref.entityKey
7447
+ });
7059
7448
  entitiesByKey.set(ref.entityKey, {
7060
7449
  ...createEntityBase(ref),
7061
7450
  kind: reduceOfflineEntityKind(existing?.kind, operationKind),
@@ -7068,22 +7457,19 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7068
7457
  childResolutionCount: childResolutionIds.length,
7069
7458
  createdAt: existing?.createdAt ?? resolution.createdAt,
7070
7459
  updatedAt: resolution.updatedAt,
7071
- tempId: getTempIdForEntityRef({
7072
- entityRefs: resolution.entityRefs,
7073
- tempIds: resolution.tempIds,
7074
- entityKey: ref.entityKey
7075
- }) ?? existing?.tempId,
7460
+ tempId: tempId ?? existing?.tempId,
7076
7461
  payload: getPayloadForEntityRef({
7077
7462
  operationName: resolution.operation,
7078
7463
  input: resolution.input,
7079
7464
  entityKey: ref.entityKey
7080
7465
  }) ?? existing?.payload
7081
7466
  });
7467
+ if (tempId !== void 0 && !isHeldWorkResolution(resolution, dependencySnapshot)) attemptedCreationEntityKeys.add(ref.entityKey);
7082
7468
  }
7083
7469
  }
7084
7470
  const entities = [...entitiesByKey.values()].sort((left, right) => left.id.localeCompare(right.id));
7085
7471
  const derivedResolutions = buildDerivedResolutionRecords(dependencySnapshot);
7086
- const referencedUploadIds = [...new Set([...queueEntries.values(), ...resolutions.values()].flatMap((entry) => [...Object.values(entry.attachedUploadIds ?? {}), ...entry.dependencyUploadIds ?? []]))].sort((left, right) => left.localeCompare(right));
7472
+ const referencedUploadIds = [...new Set([...[...queueEntries.values(), ...resolutions.values()].flatMap((entry) => [...Object.values(entry.attachedUploadIds ?? {}), ...entry.dependencyUploadIds ?? []]), ...[...unknownOperationUploadIds.values()].flat()])].sort((left, right) => left.localeCompare(right));
7087
7473
  const protectedKeys = storeAdapter.getProtectedCacheKeys(entities.map((entity) => ({
7088
7474
  entityKey: entity.entityKey,
7089
7475
  entityKind: entity.entityKind
@@ -7096,6 +7482,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7096
7482
  sessionState.session.syncStoreData(storeName, {
7097
7483
  adapter,
7098
7484
  entities,
7485
+ attemptedCreationEntityIds: entities.filter((entity) => attemptedCreationEntityKeys.has(entity.entityKey)).map((entity) => entity.id),
7099
7486
  resolutions: derivedResolutions,
7100
7487
  referencedUploadIds,
7101
7488
  protectedKeys,
@@ -7166,15 +7553,21 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7166
7553
  let candidate = null;
7167
7554
  for (const entry of args.entries ?? queueEntries.values()) {
7168
7555
  if (entry.operation !== args.operationName) continue;
7169
- if (entry.syncState !== "pending") continue;
7170
- if (entry.attempts > 0) continue;
7556
+ if (!isUnsentQueueEntry(entry)) continue;
7171
7557
  if (entryIdsFromAnotherTab.has(entry.id)) continue;
7172
7558
  if (entry.tempIds && entry.tempIds.length > 0) continue;
7173
7559
  if (normalizeEntityRefs(entry.entityRefs) !== normalizedEntityRefs) continue;
7174
- if (!candidate || compareQueueEntries(entry, candidate) < 0) candidate = entry;
7560
+ if (!candidate || compareQueueEntries(entry, candidate) > 0) candidate = entry;
7175
7561
  }
7176
7562
  return candidate;
7177
7563
  }
7564
+ /**
7565
+ * Whether the entry was never sent: only then can it be dropped or merged
7566
+ * without the server possibly having applied it.
7567
+ */
7568
+ function isUnsentQueueEntry(entry) {
7569
+ return entry.syncState === "pending" && entry.attempts === 0;
7570
+ }
7178
7571
  function isSameEntityRef(left, right) {
7179
7572
  return left?.entityKind === right?.entityKind && left?.entityKey === right?.entityKey;
7180
7573
  }
@@ -7206,7 +7599,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7206
7599
  const targetRef = args.entityRefs[0];
7207
7600
  if (!targetRef) throw new Error(`Superseding offline operation "${args.operationName}" is missing its entity ref`);
7208
7601
  return [...args.entries ?? queueEntries.values()].filter((entry) => {
7209
- return entry.syncState === "pending" && entry.attempts === 0 && entry.entityRefs.length === 1 && getQueueOrder(entry) < args.queueOrder && matchesSupersededOperation({
7602
+ return isUnsentQueueEntry(entry) && entry.entityRefs.length === 1 && getQueueOrder(entry) < args.queueOrder && matchesSupersededOperation({
7210
7603
  candidateOperationName: entry.operation,
7211
7604
  operationName: args.operationName,
7212
7605
  supersedes: args.supersedes
@@ -7404,6 +7797,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7404
7797
  const tempEntities = operation.tempEntities;
7405
7798
  if (!tempEntity && !tempEntities) return;
7406
7799
  if (!storeAdapter.reconcileTempEntity) return;
7800
+ try {
7801
+ await storeAdapter.loadTempEntities?.(args.tempIds, getReplayedTempEntityQueries(tempEntity, args.input, args.tempIds));
7802
+ } catch {}
7407
7803
  if (tempEntity) {
7408
7804
  const tempId = args.tempIds[0];
7409
7805
  if (tempId === void 0) return;
@@ -7452,6 +7848,33 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7452
7848
  });
7453
7849
  }
7454
7850
  }
7851
+ /**
7852
+ * The queries a replayed temp entity was declared into, so the lists that
7853
+ * are only in persistent storage are loaded and receive the final entity.
7854
+ * Only a `tempEntity` declaration is computed again, never the batch
7855
+ * builder: the server already applied the mutation, so app code must not
7856
+ * run (or throw) again here.
7857
+ */
7858
+ function getReplayedTempEntityQueries(tempEntity, input, tempIds) {
7859
+ const tempId = tempIds[0];
7860
+ if (!tempEntity?.addToQueries || tempId === void 0) return [];
7861
+ try {
7862
+ const addToQueries = typeof tempEntity.addToQueries === "function" ? tempEntity.addToQueries(input, tempId) : tempEntity.addToQueries;
7863
+ return addToQueries ? [addToQueries] : [];
7864
+ } catch {
7865
+ return [];
7866
+ }
7867
+ }
7868
+ /**
7869
+ * Loads the queries the pending entities are declared into that are only in
7870
+ * persistent storage, so they receive the entities. Returns `undefined`
7871
+ * when there is nothing to load.
7872
+ */
7873
+ function loadPendingEntityQueries(pendingEntities) {
7874
+ const addToQueries = pendingEntities.flatMap((pendingEntity) => pendingEntity.addToQueries ? [pendingEntity.addToQueries] : []);
7875
+ if (addToQueries.length === 0) return void 0;
7876
+ return storeAdapter.loadTempEntities?.([], addToQueries)?.catch(() => {});
7877
+ }
7455
7878
  async function persistEntry(entry, current, skipRefresh) {
7456
7879
  const session = current ?? ensureActiveSession();
7457
7880
  if (!session) return;
@@ -7581,6 +8004,48 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7581
8004
  });
7582
8005
  }
7583
8006
  /**
8007
+ * Whether the work targets or depends on a temp entity whose creation is
8008
+ * held in a manual resolution. Such work cannot be sent (the server does
8009
+ * not know the entity) until that resolution is decided.
8010
+ */
8011
+ function isHeldBehindTempCreateResolution(workItem) {
8012
+ for (const resolution of resolutions.values()) for (const entityKey of getTempLifecycleEntityKeys(resolution)) if (workItemDependsOnDependencySource({
8013
+ workItem,
8014
+ dependencySource: {
8015
+ entityKey,
8016
+ resolutionId: resolution.id,
8017
+ sourceType: "resolution"
8018
+ }
8019
+ })) return true;
8020
+ return false;
8021
+ }
8022
+ /**
8023
+ * The resolutions holding work behind a temp creation that waits for a
8024
+ * manual resolution, among those `matches` accepts. That work was never sent
8025
+ * (it waits for the creation), so like an unsent queue entry it can still be
8026
+ * merged into or superseded by a later mutation of the same entity.
8027
+ * Otherwise the later mutation would be sent first, and the held work
8028
+ * replayed over it once the creation is retried.
8029
+ */
8030
+ function findHeldWorkResolutions(matches, excludedResolutionId) {
8031
+ if (resolutions.size === 0) return [];
8032
+ const heldResolutions = [];
8033
+ for (const resolution of resolutions.values()) {
8034
+ if (resolution.id === excludedResolutionId || !matches(resolution) || !isHeldWorkResolution(resolution)) continue;
8035
+ heldResolutions.push(resolution);
8036
+ }
8037
+ return heldResolutions.sort(compareResolutionRecords);
8038
+ }
8039
+ /**
8040
+ * Work held behind a temp creation waiting for a decision, never sent. A
8041
+ * `dependencySnapshot` of the current resolutions answers it without
8042
+ * scanning them again.
8043
+ */
8044
+ function isHeldWorkResolution(resolution, dependencySnapshot) {
8045
+ if (resolution.kind !== "retry-exhausted" || resolution.lastReplayError.message !== BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE) return false;
8046
+ return dependencySnapshot ? dependencySnapshot.blockedByResolutionIdsByResolutionId.has(resolution.id) : isHeldBehindTempCreateResolution(resolution);
8047
+ }
8048
+ /**
7584
8049
  * Removes the items a discarded `create` without temp entity (the app
7585
8050
  * generated the id on the client) added to the store, like the rollback of a
7586
8051
  * temp create, and adds their keys to `removedEntityKeys`. Like removed temp
@@ -7588,14 +8053,12 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7588
8053
  * If an earlier replay attempt did create one, the store's list
7589
8054
  * revalidation brings it back.
7590
8055
  */
7591
- function rollbackClientIdCreatedItems(workItem, removedEntityKeys) {
7592
- if (getOperationLifecycleKind(workItem.operation) !== "create" || isTempCreateOperation(workItem.operation)) return;
7593
- for (const ref of workItem.entityRefs) {
7594
- if (ref.entityKind !== "item") continue;
8056
+ function rollbackClientIdCreatedItems(workItem, removedEntityKeys, unsentEntityKeys, cancelledEntityKeys) {
8057
+ for (const entityKey of getClientIdCreatedEntityKeys(workItem)) {
7595
8058
  const payload = getPayloadForEntityRef({
7596
8059
  operationName: workItem.operation,
7597
8060
  input: workItem.input,
7598
- entityKey: ref.entityKey
8061
+ entityKey
7599
8062
  });
7600
8063
  if (payload === void 0) continue;
7601
8064
  storeAdapter.rollbackPendingEntity?.({
@@ -7604,9 +8067,18 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7604
8067
  tempId: payload,
7605
8068
  pendingEntity: void 0
7606
8069
  });
7607
- removedEntityKeys.add(ref.entityKey);
8070
+ removedEntityKeys.add(entityKey);
8071
+ if (unsentEntityKeys.has(entityKey)) cancelledEntityKeys.add(entityKey);
7608
8072
  }
7609
8073
  }
8074
+ /**
8075
+ * Keys of the items a `create` without temp entity adds to the store with
8076
+ * a client-generated id.
8077
+ */
8078
+ function getClientIdCreatedEntityKeys(workItem) {
8079
+ if (getOperationLifecycleKind(workItem.operation) !== "create" || isTempCreateOperation(workItem.operation)) return [];
8080
+ return workItem.entityRefs.filter((entityRef) => entityRef.entityKind === "item").map((entityRef) => entityRef.entityKey);
8081
+ }
7610
8082
  async function promoteBlockedTempCreateDescendants(args) {
7611
8083
  const descendantQueueEntries = /* @__PURE__ */ new Map();
7612
8084
  for (const entityKey of getTempLifecycleEntityKeys(args.parentEntry)) {
@@ -7635,40 +8107,103 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7635
8107
  function isPersistedResolutionBlocked(resolution) {
7636
8108
  return (createResolutionDependencySnapshot().blockedResolutionIdsByResolutionId.get(resolution.id)?.size ?? 0) > 0;
7637
8109
  }
7638
- async function discardTempCreateResolutionChain(args) {
7639
- await removeResolution(args.resolution.id, args.current, true);
7640
- const parentEntityKeys = getTempLifecycleEntityKeys(args.resolution);
7641
- if (parentEntityKeys.length === 0) {
7642
- const removedEntityKeys = /* @__PURE__ */ new Set();
7643
- rollbackClientIdCreatedItems(args.resolution, removedEntityKeys);
7644
- refreshDerivedState(args.current);
7645
- revalidateDiscardedWorkInEveryTab(args.current, [args.resolution], removedEntityKeys);
7646
- await deleteOrphanedDependencyUploads(args.current, [args.resolution]);
7647
- return;
7648
- }
8110
+ /**
8111
+ * Drops everything that only made sense with temp entities that will never
8112
+ * exist on the server, because their creation (`tempCreates`, already
8113
+ * removed by the caller) was cancelled before being sent or discarded:
8114
+ *
8115
+ * - the queued work and manual resolutions of this store that target or
8116
+ * depend on those entities, or on the items an unsent dropped creation
8117
+ * added with a client-generated id, recursively
8118
+ * - the temp entities themselves, and the items the dropped work created
8119
+ * with a client-generated id
8120
+ * - the work of other stores declared as `cancelledWith` those entities,
8121
+ * or the items unsent dropped creations added with a client-generated id
8122
+ *
8123
+ * The server entities the dropped work changed optimistically are
8124
+ * refetched, and the staged uploads only the dropped work and `tempCreates`
8125
+ * depended on are deleted.
8126
+ */
8127
+ async function discardTempLifecycles(current, tempCreates) {
7649
8128
  const descendantQueueEntries = /* @__PURE__ */ new Map();
7650
8129
  const descendantResolutions = /* @__PURE__ */ new Map();
8130
+ const parentEntityKeys = [];
8131
+ const unsentClientIdEntityKeys = /* @__PURE__ */ new Set();
8132
+ function addUnsentClientIdCreation(workItem) {
8133
+ for (const entityKey of getClientIdCreatedEntityKeys(workItem)) {
8134
+ parentEntityKeys.push(entityKey);
8135
+ unsentClientIdEntityKeys.add(entityKey);
8136
+ }
8137
+ }
8138
+ for (const tempCreate of tempCreates) {
8139
+ parentEntityKeys.push(...getTempLifecycleEntityKeys(tempCreate));
8140
+ if ("syncState" in tempCreate ? isUnsentQueueEntry(tempCreate) : isHeldBehindTempCreateResolution(tempCreate)) addUnsentClientIdCreation(tempCreate);
8141
+ }
7651
8142
  for (const entityKey of parentEntityKeys) {
7652
- const descendants = collectTempCreateDescendants({
7653
- parentEntityKey: entityKey,
7654
- parentResolutionId: args.resolution.id
7655
- });
7656
- for (const queueEntry of descendants.queueEntries) descendantQueueEntries.set(queueEntry.id, queueEntry);
7657
- for (const resolution of descendants.resolutions) descendantResolutions.set(resolution.id, resolution);
7658
- }
7659
- for (const queueEntry of descendantQueueEntries.values()) await removeEntry(queueEntry.id, args.current, true);
7660
- for (const resolution of descendantResolutions.values()) await removeResolution(resolution.id, args.current, true);
7661
- const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7662
- const removedEntityKeys = new Set(parentEntityKeys);
7663
- for (const workItem of discardedWork) {
8143
+ const descendants = collectTempCreateDescendants({ parentEntityKey: entityKey });
8144
+ for (const queueEntry of descendants.queueEntries) {
8145
+ if (descendantQueueEntries.has(queueEntry.id)) continue;
8146
+ descendantQueueEntries.set(queueEntry.id, queueEntry);
8147
+ if (isUnsentQueueEntry(queueEntry)) addUnsentClientIdCreation(queueEntry);
8148
+ }
8149
+ for (const resolution of descendants.resolutions) {
8150
+ if (descendantResolutions.has(resolution.id)) continue;
8151
+ descendantResolutions.set(resolution.id, resolution);
8152
+ addUnsentClientIdCreation(resolution);
8153
+ }
8154
+ }
8155
+ for (const queueEntry of descendantQueueEntries.values()) await removeEntry(queueEntry.id, current, true);
8156
+ for (const resolution of descendantResolutions.values()) await removeResolution(resolution.id, current, true);
8157
+ const droppedDescendants = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
8158
+ const removedEntityKeys = /* @__PURE__ */ new Set();
8159
+ const cancelledEntityKeys = /* @__PURE__ */ new Set();
8160
+ for (const workItem of [...droppedDescendants, ...tempCreates]) {
8161
+ rollbackClientIdCreatedItems(workItem, removedEntityKeys, unsentClientIdEntityKeys, cancelledEntityKeys);
8162
+ for (const entityKey of getTempLifecycleEntityKeys(workItem)) {
8163
+ removedEntityKeys.add(entityKey);
8164
+ cancelledEntityKeys.add(entityKey);
8165
+ }
8166
+ if (!workItem.tempIds || !isTempCreateOperation(workItem.operation)) continue;
7664
8167
  rollbackTempCreatePendingEntity(workItem);
7665
- rollbackClientIdCreatedItems(workItem, removedEntityKeys);
7666
- for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedEntityKeys.add(entityKey);
7667
8168
  }
7668
- rollbackTempCreatePendingEntity(args.resolution);
7669
- refreshDerivedState(args.current);
7670
- revalidateDiscardedWorkInEveryTab(args.current, discardedWork, removedEntityKeys);
7671
- await deleteOrphanedDependencyUploads(args.current, [args.resolution, ...discardedWork]);
8169
+ refreshDerivedState(current);
8170
+ const discardedWork = [...droppedDescendants];
8171
+ for (const tempCreate of tempCreates) if (getTempLifecycleEntityKeys(tempCreate).length === 0) discardedWork.push(tempCreate);
8172
+ revalidateDiscardedWorkInEveryTab(current, discardedWork, removedEntityKeys);
8173
+ await deleteOrphanedDependencyUploads(current, [...tempCreates, ...droppedDescendants]);
8174
+ if (cancelledEntityKeys.size > 0) await current.session.notifyTempEntitiesCancelled(storeName, cancelledEntityKeys, getEntityKeyOfPayload);
8175
+ }
8176
+ async function discardTempCreateResolutionChain(args) {
8177
+ await removeResolution(args.resolution.id, args.current, true);
8178
+ await discardTempLifecycles(args.current, [args.resolution]);
8179
+ }
8180
+ /** Key of an entity payload of this store, as its entity refs hold it. */
8181
+ function getEntityKeyOfPayload(entityRef) {
8182
+ return resolveNormalizedRefs([entityRef])[0]?.entityKey;
8183
+ }
8184
+ /**
8185
+ * Another store of the session reported entities created offline that will
8186
+ * never exist on the server: drops the work of this store declared as
8187
+ * `cancelledWith` one of them, with its own temp lifecycles.
8188
+ */
8189
+ async function discardWorkCancelledWithExternalTempEntities(sourceStoreName, cancelledEntityKeys, getSourceEntityKey) {
8190
+ await hydrateIfNeeded();
8191
+ const current = ensureActiveSession();
8192
+ if (!current) return;
8193
+ function isCancelled(workItem) {
8194
+ const externalEntityRefs = operations[workItem.operation]?.cancelledWith?.({ input: workItem.input });
8195
+ return externalEntityRefs !== void 0 && externalEntityRefs.some((externalEntityRef) => {
8196
+ if (externalEntityRef.storeName !== sourceStoreName) return false;
8197
+ const entityKey = getSourceEntityKey(externalEntityRef.entityRef);
8198
+ return entityKey !== void 0 && cancelledEntityKeys.has(entityKey);
8199
+ });
8200
+ }
8201
+ const cancelledQueueEntries = [...queueEntries.values()].filter((entry) => entry.syncState !== "syncing" && isCancelled(entry));
8202
+ const cancelledResolutions = [...resolutions.values()].filter(isCancelled);
8203
+ if (cancelledQueueEntries.length === 0 && cancelledResolutions.length === 0) return;
8204
+ for (const queueEntry of cancelledQueueEntries) await removeEntry(queueEntry.id, current, true);
8205
+ for (const resolution of cancelledResolutions) await removeResolution(resolution.id, current, true);
8206
+ await discardTempLifecycles(current, [...cancelledQueueEntries, ...cancelledResolutions]);
7672
8207
  }
7673
8208
  /**
7674
8209
  * {@link revalidateDiscardedWork} in this tab and in the other tabs with the
@@ -7710,6 +8245,64 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7710
8245
  if (entities.length === 0) return;
7711
8246
  storeAdapter.revalidateDiscardedEntities?.(entities, resolutions.size > 0);
7712
8247
  }
8248
+ /**
8249
+ * Queues `resolutionsToRequeue` again, in order, and removes them.
8250
+ * `sentResolutionId` is the resolution whose attempts were exhausted: the
8251
+ * server may have applied it.
8252
+ */
8253
+ async function requeueResolutions(current, resolutionsToRequeue, sentResolutionId) {
8254
+ const { queueOrders, nextQueueOrderValue } = previewQueueOrders(resolutionsToRequeue.length);
8255
+ nextQueueOrder = nextQueueOrderValue;
8256
+ const nextEntries = resolutionsToRequeue.map((resolution, index) => {
8257
+ const queueOrder = queueOrders[index];
8258
+ if (queueOrder === void 0) throw new Error("Missing queue order for replay resolution requeue");
8259
+ const entry = operations[resolution.operation] ? buildFreshQueueEntry({
8260
+ current,
8261
+ operation: resolution.operation,
8262
+ input: resolution.input,
8263
+ entityRefs: resolution.entityRefs,
8264
+ queueOrder,
8265
+ attachedUploadIds: resolution.attachedUploadIds,
8266
+ dependencyUploadIds: resolution.dependencyUploadIds,
8267
+ tempIds: resolution.tempIds
8268
+ }) : null;
8269
+ if (entry && resolution.id === sentResolutionId && !(resolution.kind === "retry-exhausted" && resolution.lastReplayError.message === BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE)) entry.attempts = 1;
8270
+ return {
8271
+ resolution,
8272
+ entry
8273
+ };
8274
+ });
8275
+ for (const nextEntry of nextEntries) {
8276
+ if (!nextEntry.entry) continue;
8277
+ await persistEntry(nextEntry.entry, current, true);
8278
+ }
8279
+ for (const resolution of resolutionsToRequeue) await removeResolution(resolution.id, current, true);
8280
+ storeAdapter.captureQueuedMutationOverlays?.({
8281
+ sessionKey: current.sessionKey,
8282
+ entityRefs: nextEntries.flatMap((nextEntry) => {
8283
+ return nextEntry.entry?.entityRefs ?? [];
8284
+ })
8285
+ });
8286
+ refreshDerivedState(current);
8287
+ await deleteOrphanedDependencyUploads(current, nextEntries.flatMap((nextEntry) => nextEntry.entry ? [] : [nextEntry.resolution]));
8288
+ await ensureReplayScheduled();
8289
+ }
8290
+ /**
8291
+ * Removes from `descendants` the ones that also wait for a creation still
8292
+ * held in a resolution outside them (other than `decidedResolutionId`),
8293
+ * directly or behind one such descendant: they cannot be sent yet and go
8294
+ * with the decision about that creation.
8295
+ */
8296
+ function dropDescendantsHeldElsewhere(descendants, dependencySnapshot, decidedResolutionId) {
8297
+ let removedHeldDescendant = true;
8298
+ while (removedHeldDescendant) {
8299
+ removedHeldDescendant = false;
8300
+ for (const resolution of descendants.values()) if ((dependencySnapshot.blockedByResolutionIdsByResolutionId.get(resolution.id) ?? []).some((blockerId) => blockerId !== decidedResolutionId && !descendants.has(blockerId))) {
8301
+ descendants.delete(resolution.id);
8302
+ removedHeldDescendant = true;
8303
+ }
8304
+ }
8305
+ }
7713
8306
  function collectRetryResolutionChain(args) {
7714
8307
  if (args.scope === "self") return [args.resolution];
7715
8308
  const dependencySnapshot = createResolutionDependencySnapshot();
@@ -7724,6 +8317,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7724
8317
  descendantResolutions.set(resolution.id, resolution);
7725
8318
  }
7726
8319
  }
8320
+ dropDescendantsHeldElsewhere(descendantResolutions, dependencySnapshot, args.resolution.id);
7727
8321
  const orderedDescendants = [];
7728
8322
  const remainingDescendants = [...descendantResolutions.values()].sort(compareResolutionRecords);
7729
8323
  const orderedIds = /* @__PURE__ */ new Set();
@@ -7791,7 +8385,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7791
8385
  return result;
7792
8386
  }
7793
8387
  async function planPreparedMutation(args) {
7794
- const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, attachedUploadIds, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue, replacedResolutionId } = args;
8388
+ const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, attachedUploadIds, tempIds: preparedTempIds, entityRefs: preparedEntityRefs, mayHaveBeenApplied }, queueOrder, workingQueue, replacedResolutionId } = args;
7795
8389
  const tempEntity = operation.tempEntity;
7796
8390
  const tempEntities = operation.tempEntities;
7797
8391
  if (operation.accumulation && operation.supersedes) throw new Error(`Offline operation "${operationName}" cannot configure accumulation and supersedes together`);
@@ -7826,26 +8420,33 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7826
8420
  const now = Date.now();
7827
8421
  const pendingEntities = !storeAdapter.applyPendingEntity ? [] : tempEntity && tempIds?.[0] !== void 0 ? [{
7828
8422
  tempId: tempIds[0],
7829
- pendingEntity: tempEntity.buildPendingEntity(validatedInput, tempIds[0])
8423
+ pendingEntity: tempEntity.buildPendingEntity(validatedInput, tempIds[0]),
8424
+ addToQueries: typeof tempEntity.addToQueries === "function" ? tempEntity.addToQueries(validatedInput, tempIds[0]) : tempEntity.addToQueries,
8425
+ loadedFields: tempEntity.loadedFields
7830
8426
  }] : tempEntities && tempIds ? orderByTempIds({
7831
8427
  operationName,
7832
8428
  label: "Temp entities",
7833
8429
  tempIds,
7834
8430
  items: tempEntities.buildPendingEntities(validatedInput, tempIds).map((entry) => ({
7835
8431
  tempId: castTempLifecyclePayload(entry.tempId),
7836
- pendingEntity: entry.pendingEntity
8432
+ pendingEntity: entry.pendingEntity,
8433
+ addToQueries: entry.addToQueries,
8434
+ loadedFields: entry.loadedFields
7837
8435
  }))
7838
8436
  }) : [];
7839
8437
  if (operation.accumulation && (!tempIds || tempIds.length === 0)) {
7840
- const existingEntry = findAccumulationCandidate({
8438
+ const normalizedEntityRefs = normalizeEntityRefs(entityRefs);
8439
+ const heldResolution = findHeldWorkResolutions((resolution) => resolution.operation === operationName && (resolution.tempIds?.length ?? 0) === 0 && normalizeEntityRefs(resolution.entityRefs) === normalizedEntityRefs, replacedResolutionId).at(-1);
8440
+ const existingEntry = heldResolution ? void 0 : findAccumulationCandidate({
7841
8441
  operationName,
7842
8442
  entityRefs,
7843
8443
  entries: workingQueue.values()
7844
8444
  });
7845
- if (existingEntry) {
8445
+ const existingWork = heldResolution ?? existingEntry;
8446
+ if (existingWork) {
7846
8447
  const mergedInput = await operation.accumulation.mergeInput({
7847
8448
  sessionKey: current.sessionKey,
7848
- existingInput: existingEntry.input,
8449
+ existingInput: existingWork.input,
7849
8450
  incomingInput: validatedInput
7850
8451
  });
7851
8452
  const validatedMergedInput = validateWithSchema(operation.inputSchema, mergedInput);
@@ -7854,22 +8455,63 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7854
8455
  operationName,
7855
8456
  input: validatedMergedInput
7856
8457
  });
7857
- const nextEntry = {
7858
- ...existingEntry,
7859
- input: validatedMergedInput,
7860
- dependencyUploadIds: mergedDependencyUploadIds.length > 0 ? mergedDependencyUploadIds : void 0,
7861
- updatedAt: now
7862
- };
7863
- workingQueue.set(nextEntry.id, nextEntry);
7864
- return {
7865
- operationName,
7866
- validatedInput,
7867
- tempIds,
7868
- pendingEntities,
7869
- nextEntry,
7870
- removedEntries: [existingEntry],
7871
- accumulatedEntry: existingEntry
7872
- };
8458
+ const dependencyUploadIdsOfMerge = mergedDependencyUploadIds.length > 0 ? mergedDependencyUploadIds : void 0;
8459
+ if (heldResolution) {
8460
+ const nextResolution = {
8461
+ ...heldResolution,
8462
+ input: validatedMergedInput,
8463
+ dependencyUploadIds: dependencyUploadIdsOfMerge,
8464
+ updatedAt: now
8465
+ };
8466
+ if (isHeldBehindTempCreateResolution(nextResolution)) return {
8467
+ operationName,
8468
+ validatedInput,
8469
+ tempIds,
8470
+ pendingEntities,
8471
+ removedEntries: [],
8472
+ replacedResolution: nextResolution,
8473
+ accumulatedResolution: heldResolution
8474
+ };
8475
+ const nextEntry = buildFreshQueueEntry({
8476
+ current,
8477
+ operation: operationName,
8478
+ input: validatedMergedInput,
8479
+ queueOrder,
8480
+ entityRefs: heldResolution.entityRefs,
8481
+ dependencyUploadIds: dependencyUploadIdsOfMerge
8482
+ });
8483
+ workingQueue.set(nextEntry.id, nextEntry);
8484
+ return {
8485
+ operationName,
8486
+ validatedInput,
8487
+ tempIds,
8488
+ pendingEntities,
8489
+ nextEntry,
8490
+ removedEntries: [],
8491
+ removedResolutions: [heldResolution],
8492
+ accumulatedResolution: heldResolution
8493
+ };
8494
+ }
8495
+ if (existingEntry) {
8496
+ const nextEntry = {
8497
+ ...existingEntry,
8498
+ input: validatedMergedInput,
8499
+ dependencyUploadIds: dependencyUploadIdsOfMerge,
8500
+ updatedAt: now
8501
+ };
8502
+ if (!isHeldBehindTempCreateResolution(nextEntry)) {
8503
+ workingQueue.set(nextEntry.id, nextEntry);
8504
+ return {
8505
+ operationName,
8506
+ validatedInput,
8507
+ tempIds,
8508
+ pendingEntities,
8509
+ nextEntry,
8510
+ removedEntries: [existingEntry],
8511
+ accumulatedEntry: existingEntry
8512
+ };
8513
+ }
8514
+ }
7873
8515
  }
7874
8516
  }
7875
8517
  const supersededEntries = operation.supersedes ? findSupersededEntries({
@@ -7879,13 +8521,22 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7879
8521
  supersedes: operation.supersedes,
7880
8522
  entries: workingQueue.values()
7881
8523
  }) : [];
8524
+ const supersedes = operation.supersedes;
8525
+ const supersededResolutions = supersedes ? findHeldWorkResolutions((resolution) => resolution.entityRefs.length === 1 && isSameEntityRef(resolution.entityRefs[0], entityRefs[0]) && matchesSupersededOperation({
8526
+ candidateOperationName: resolution.operation,
8527
+ operationName,
8528
+ supersedes
8529
+ }), replacedResolutionId) : [];
7882
8530
  for (const entry of supersededEntries) workingQueue.delete(entry.id);
7883
- if (operation.supersedes?.dropSelfIfTempLifecycleCancelled && supersededEntries.some((entry) => entry.tempIds !== void 0 && entry.tempIds.length > 0)) return {
8531
+ const cancelledTempCreates = supersedes?.dropSelfIfTempLifecycleCancelled ? [...supersededEntries, ...supersededResolutions].filter((workItem) => (workItem.tempIds?.length ?? 0) > 0 || getClientIdCreatedEntityKeys(workItem).length > 0) : [];
8532
+ if (cancelledTempCreates.length > 0) return {
7884
8533
  operationName,
7885
8534
  validatedInput,
7886
8535
  tempIds,
7887
8536
  pendingEntities,
7888
- removedEntries: supersededEntries
8537
+ removedEntries: supersededEntries,
8538
+ removedResolutions: supersededResolutions,
8539
+ cancelledTempCreates
7889
8540
  };
7890
8541
  const nextEntry = buildFreshQueueEntry({
7891
8542
  current,
@@ -7898,6 +8549,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7898
8549
  dependencyUploadIds: dependencyUploadIds.length > 0 ? dependencyUploadIds : void 0,
7899
8550
  tempIds
7900
8551
  });
8552
+ if (mayHaveBeenApplied && getClientIdCreatedEntityKeys(nextEntry).length > 0) nextEntry.attempts = 1;
7901
8553
  workingQueue.set(nextEntry.id, nextEntry);
7902
8554
  return {
7903
8555
  operationName,
@@ -7905,7 +8557,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7905
8557
  tempIds,
7906
8558
  pendingEntities,
7907
8559
  nextEntry,
7908
- removedEntries: supersededEntries
8560
+ removedEntries: supersededEntries,
8561
+ removedResolutions: supersededResolutions
7909
8562
  };
7910
8563
  }
7911
8564
  async function queuePreparedMutations(preparedMutation, replacedResolutionId) {
@@ -7915,7 +8568,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7915
8568
  const queueOrder = queueOrders[0];
7916
8569
  if (queueOrder === void 0) throw new Error("Missing queue order for prepared offline mutation");
7917
8570
  let plannedMutation;
7918
- do
8571
+ let pendingEntityQueriesLoaded = false;
8572
+ for (;;) {
7919
8573
  plannedMutation = await planPreparedMutation({
7920
8574
  current,
7921
8575
  preparedMutation,
@@ -7923,7 +8577,17 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7923
8577
  workingQueue: new Map(queueEntries),
7924
8578
  replacedResolutionId
7925
8579
  });
7926
- while (plannedMutation.accumulatedEntry && queueEntries.get(plannedMutation.accumulatedEntry.id) !== plannedMutation.accumulatedEntry);
8580
+ if (!pendingEntityQueriesLoaded) {
8581
+ pendingEntityQueriesLoaded = true;
8582
+ const loading = loadPendingEntityQueries(plannedMutation.pendingEntities);
8583
+ if (loading) {
8584
+ await loading;
8585
+ continue;
8586
+ }
8587
+ }
8588
+ if ((!plannedMutation.accumulatedEntry || queueEntries.get(plannedMutation.accumulatedEntry.id) === plannedMutation.accumulatedEntry) && (!plannedMutation.accumulatedResolution || resolutions.get(plannedMutation.accumulatedResolution.id) === plannedMutation.accumulatedResolution)) break;
8589
+ }
8590
+ const blockedResolution = plannedMutation.nextEntry && isHeldBehindTempCreateResolution(plannedMutation.nextEntry) ? buildRetryExhaustedResolutionRecord(current, plannedMutation.nextEntry, { message: BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE }) : void 0;
7927
8591
  const persistedMutations = [];
7928
8592
  const persistedUploadIds = [];
7929
8593
  const appliedPendingMutations = [];
@@ -7932,7 +8596,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7932
8596
  const appliedMutation = {
7933
8597
  ...plannedMutation,
7934
8598
  removedEntriesApplied: [],
7935
- touchedNextEntry: false
8599
+ removedResolutionsApplied: [],
8600
+ touchedNextEntry: false,
8601
+ touchedReplacedResolution: false
7936
8602
  };
7937
8603
  persistedMutations.push(appliedMutation);
7938
8604
  if (preparedMutation.upload && plannedMutation.nextEntry) {
@@ -7957,7 +8623,16 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7957
8623
  }
7958
8624
  if (plannedMutation.nextEntry) {
7959
8625
  appliedMutation.touchedNextEntry = true;
7960
- await persistEntry(plannedMutation.nextEntry, current, true);
8626
+ if (blockedResolution) await persistResolution(blockedResolution, current, true);
8627
+ else await persistEntry(plannedMutation.nextEntry, current, true);
8628
+ }
8629
+ if (plannedMutation.replacedResolution) {
8630
+ appliedMutation.touchedReplacedResolution = true;
8631
+ await persistResolution(plannedMutation.replacedResolution, current, true);
8632
+ }
8633
+ for (const removedResolution of plannedMutation.removedResolutions ?? []) {
8634
+ appliedMutation.removedResolutionsApplied.push(removedResolution);
8635
+ await removeResolution(removedResolution.id, current, true);
7961
8636
  }
7962
8637
  nextQueueOrder = nextQueueOrderValue;
7963
8638
  if (storeAdapter.applyPendingEntity && plannedMutation.pendingEntities.length > 0) {
@@ -7965,7 +8640,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7965
8640
  operationName: plannedMutation.operationName,
7966
8641
  input: plannedMutation.validatedInput,
7967
8642
  tempId: pendingEntity.tempId,
7968
- pendingEntity: pendingEntity.pendingEntity
8643
+ pendingEntity: pendingEntity.pendingEntity,
8644
+ addToQueries: pendingEntity.addToQueries,
8645
+ loadedFields: pendingEntity.loadedFields
7969
8646
  });
7970
8647
  appliedPendingMutations.push({
7971
8648
  operationName: plannedMutation.operationName,
@@ -7973,9 +8650,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7973
8650
  pendingEntities: plannedMutation.pendingEntities
7974
8651
  });
7975
8652
  }
7976
- if (plannedMutation.nextEntry) storeAdapter.captureQueuedMutationOverlays?.({
8653
+ const queuedWork = plannedMutation.nextEntry ?? plannedMutation.replacedResolution;
8654
+ if (queuedWork) storeAdapter.captureQueuedMutationOverlays?.({
7977
8655
  sessionKey: current.sessionKey,
7978
- entityRefs: plannedMutation.nextEntry.entityRefs
8656
+ entityRefs: queuedWork.entityRefs
7979
8657
  });
7980
8658
  } catch (error) {
7981
8659
  for (const mutation of appliedPendingMutations.reverse()) for (const pendingEntity of [...mutation.pendingEntities].reverse()) storeAdapter.rollbackPendingEntity?.({
@@ -7990,16 +8668,25 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7990
8668
  for (const mutation of persistedMutations.reverse()) {
7991
8669
  const nextEntryReplacesRemovedEntry = mutation.nextEntry !== void 0 && mutation.removedEntries.some((removedEntry) => removedEntry.id === mutation.nextEntry?.id);
7992
8670
  if (mutation.touchedNextEntry && mutation.nextEntry) {
7993
- if (!nextEntryReplacesRemovedEntry) await removeEntry(mutation.nextEntry.id, current, true);
8671
+ if (blockedResolution) await removeResolution(blockedResolution.id, current, true);
8672
+ else if (!nextEntryReplacesRemovedEntry) await removeEntry(mutation.nextEntry.id, current, true);
7994
8673
  }
7995
8674
  for (const removedEntry of nextEntryReplacesRemovedEntry ? [...mutation.removedEntries].reverse() : [...mutation.removedEntriesApplied].reverse()) await persistEntry(removedEntry, current, true);
8675
+ if (mutation.touchedReplacedResolution && mutation.accumulatedResolution) await persistResolution(mutation.accumulatedResolution, current, true);
8676
+ for (const removedResolution of [...mutation.removedResolutionsApplied].reverse()) await persistResolution(removedResolution, current, true);
7996
8677
  }
7997
8678
  nextQueueOrder = previousNextQueueOrder;
7998
8679
  refreshDerivedState(current);
7999
8680
  throw error;
8000
8681
  }
8001
- refreshDerivedState(current);
8002
- if (plannedMutation.removedEntries.length > 0) await deleteOrphanedDependencyUploads(current, plannedMutation.removedEntries);
8682
+ const { cancelledTempCreates } = plannedMutation;
8683
+ let supersededWork = [...plannedMutation.removedEntries, ...plannedMutation.removedResolutions ?? []];
8684
+ if (plannedMutation.replacedResolution && plannedMutation.accumulatedResolution) supersededWork.push(plannedMutation.accumulatedResolution);
8685
+ if (cancelledTempCreates) {
8686
+ await discardTempLifecycles(current, cancelledTempCreates);
8687
+ supersededWork = supersededWork.filter((workItem) => !cancelledTempCreates.includes(workItem));
8688
+ } else refreshDerivedState(current);
8689
+ if (supersededWork.length > 0) await deleteOrphanedDependencyUploads(current, supersededWork);
8003
8690
  await ensureReplayScheduled();
8004
8691
  }
8005
8692
  async function ensureReplayScheduled() {
@@ -8100,11 +8787,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8100
8787
  createdAt: nextEntry.createdAt
8101
8788
  })) return;
8102
8789
  const operation = operations[nextEntry.operation];
8103
- if (!operation) {
8104
- await removeEntry(nextEntry.id, current);
8105
- deleteOrphanedDependencyUploads(current, [nextEntry]);
8106
- continue;
8107
- }
8790
+ if (!operation) return;
8108
8791
  const shouldCheckSkipBeforeRetry = nextEntry.syncState === "needs-confirmation";
8109
8792
  const conflictHandling = operation.conflictHandling;
8110
8793
  const replayCheckBaseCtx = buildOperationBaseContext({
@@ -8193,8 +8876,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8193
8876
  };
8194
8877
  if (failedUploadId !== void 0) failureCtx.uploadId = failedUploadId;
8195
8878
  const classification = await current.session.classifyFailure(error, failureCtx);
8196
- const allowReplayRetry = classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, failureCtx) : false;
8197
- if (classification !== "ignore" || current.session.getStatus().isOfflineMode) {
8879
+ const sessionEnabled = isSessionEnabled();
8880
+ const allowReplayRetry = sessionEnabled && classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, failureCtx) : false;
8881
+ if (!sessionEnabled || classification !== "ignore" || current.session.getStatus().isOfflineMode) {
8198
8882
  entryToUse = {
8199
8883
  ...entryToUse,
8200
8884
  attempts: entryToUse.attempts + 1,
@@ -8254,7 +8938,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8254
8938
  await current.session.refreshNetworkState();
8255
8939
  return {
8256
8940
  initialAction: getInitialOfflineMutationAction(current, prepared),
8257
- queueMutation: () => queuePreparedMutations(prepared),
8941
+ queueMutation: (afterDirectAttempt) => queuePreparedMutations(afterDirectAttempt ? {
8942
+ ...prepared,
8943
+ mayHaveBeenApplied: true
8944
+ } : prepared),
8258
8945
  handleDirectSuccess: () => clearOfflineStatusOnSuccess(prepared.currentSessionKey),
8259
8946
  classifyError: async (error) => {
8260
8947
  const preparedCurrent = ensureActiveSession();
@@ -8281,7 +8968,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8281
8968
  function getItemOfflineState(itemKey) {
8282
8969
  const current = ensureActiveSession();
8283
8970
  if (!current) return null;
8284
- return toItemOfflineState(getOfflineStoreEntityLookup(current.session.store.state.entities, storeName).get(itemKey));
8971
+ const sessionState = current.session.store.state;
8972
+ return toItemOfflineState(getOfflineStoreEntityLookup(sessionState.entities, storeName).get(itemKey), sessionState.attemptedCreationEntityIds);
8285
8973
  }
8286
8974
  function getOfflineResolutions() {
8287
8975
  return buildDerivedResolutionRecords();
@@ -8311,43 +8999,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8311
8999
  });
8312
9000
  return;
8313
9001
  }
8314
- const resolutionsToRetry = collectRetryResolutionChain({
9002
+ await requeueResolutions(current, collectRetryResolutionChain({
8315
9003
  resolution: resolutionRecord,
8316
9004
  scope: resolutionAction?.scope ?? "self-and-descendants"
8317
- });
8318
- const { queueOrders, nextQueueOrderValue } = previewQueueOrders(resolutionsToRetry.length);
8319
- nextQueueOrder = nextQueueOrderValue;
8320
- const nextEntries = resolutionsToRetry.map((retryResolution, index) => {
8321
- const queueOrder = queueOrders[index];
8322
- if (queueOrder === void 0) throw new Error("Missing queue order for replay resolution requeue");
8323
- return {
8324
- resolution: retryResolution,
8325
- entry: operations[retryResolution.operation] ? buildFreshQueueEntry({
8326
- current,
8327
- operation: retryResolution.operation,
8328
- input: retryResolution.input,
8329
- entityRefs: retryResolution.entityRefs,
8330
- queueOrder,
8331
- attachedUploadIds: retryResolution.attachedUploadIds,
8332
- dependencyUploadIds: retryResolution.dependencyUploadIds,
8333
- tempIds: retryResolution.tempIds
8334
- }) : null
8335
- };
8336
- });
8337
- for (const nextEntry of nextEntries) {
8338
- if (!nextEntry.entry) continue;
8339
- await persistEntry(nextEntry.entry, current, true);
8340
- }
8341
- for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
8342
- storeAdapter.captureQueuedMutationOverlays?.({
8343
- sessionKey: current.sessionKey,
8344
- entityRefs: nextEntries.flatMap((nextEntry) => {
8345
- return nextEntry.entry?.entityRefs ?? [];
8346
- })
8347
- });
8348
- refreshDerivedState(current);
8349
- await deleteOrphanedDependencyUploads(current, nextEntries.flatMap((nextEntry) => nextEntry.entry ? [] : [nextEntry.resolution]));
8350
- await ensureReplayScheduled();
9005
+ }), resolutionRecord.id);
8351
9006
  return;
8352
9007
  }
8353
9008
  const resolutionAction = isObject(resolution) ? resolution : null;
@@ -8359,16 +9014,35 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8359
9014
  });
8360
9015
  return;
8361
9016
  }
9017
+ const heldDescendantIds = (action === "requeue" || action === "commit") && getTempLifecycleEntityKeys(resolutionRecord).length > 0 ? collectRetryResolutionChain({
9018
+ resolution: resolutionRecord,
9019
+ scope: "self-and-descendants"
9020
+ }).slice(1).map((descendant) => descendant.id) : [];
9021
+ const requeueHeldDescendants = async () => {
9022
+ const heldDescendants = /* @__PURE__ */ new Map();
9023
+ for (const id of heldDescendantIds) {
9024
+ const descendant = resolutions.get(id);
9025
+ if (descendant) heldDescendants.set(id, descendant);
9026
+ }
9027
+ if (heldDescendants.size === 0) return;
9028
+ dropDescendantsHeldElsewhere(heldDescendants, createResolutionDependencySnapshot(), void 0);
9029
+ if (heldDescendants.size === 0) return;
9030
+ await requeueResolutions(current, [...heldDescendants.values()], void 0);
9031
+ };
8362
9032
  if (action === "requeue") {
8363
- await queuePreparedMutations(prepareMutationWithSession(current, {
8364
- operation: operationName,
8365
- input: resolutionAction?.input,
8366
- attachedUploadIds: resolutionRecord.attachedUploadIds,
8367
- tempIds: resolutionRecord.tempIds,
8368
- entityRefs: resolutionRecord.entityRefs
8369
- }), resolutionId);
9033
+ await queuePreparedMutations({
9034
+ ...prepareMutationWithSession(current, {
9035
+ operation: operationName,
9036
+ input: resolutionAction?.input,
9037
+ attachedUploadIds: resolutionRecord.attachedUploadIds,
9038
+ tempIds: resolutionRecord.tempIds,
9039
+ entityRefs: resolutionRecord.entityRefs
9040
+ }),
9041
+ mayHaveBeenApplied: true
9042
+ }, resolutionId);
8370
9043
  await removeResolution(resolutionId, current);
8371
9044
  await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
9045
+ await requeueHeldDescendants();
8372
9046
  return;
8373
9047
  }
8374
9048
  if (action === "commit") {
@@ -8383,6 +9057,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8383
9057
  });
8384
9058
  await removeResolution(resolutionId, current);
8385
9059
  await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
9060
+ await requeueHeldDescendants();
8386
9061
  return;
8387
9062
  }
8388
9063
  throw new Error("Invalid offline resolution action");
@@ -8411,6 +9086,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8411
9086
  function shouldTreatFetchAsOffline() {
8412
9087
  const current = ensureActiveSession();
8413
9088
  if (!current) return false;
9089
+ if (!isSessionEnabled()) {
9090
+ current.session.refreshNetworkState();
9091
+ return false;
9092
+ }
8414
9093
  return shouldTreatFutureOperationsAsOffline(current);
8415
9094
  }
8416
9095
  async function handleFetchSuccess() {
@@ -8419,7 +9098,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8419
9098
  await clearOfflineStatusOnSuccess(current.sessionKey);
8420
9099
  }
8421
9100
  function canQueueMutation() {
8422
- return !isDisposed && getSessionKey() !== false;
9101
+ if (isDisposed || getSessionKey() === false) return false;
9102
+ if (isSessionEnabled()) return true;
9103
+ ensureActiveSession()?.session.refreshNetworkState();
9104
+ return false;
8423
9105
  }
8424
9106
  async function prepareForFetch() {
8425
9107
  await hydrateIfNeeded();
@@ -9462,7 +10144,8 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
9462
10144
  useOfflineStatus: getOfflineStatus,
9463
10145
  useOfflineEntities: () => EMPTY_OFFLINE_ENTITIES,
9464
10146
  useOfflineResolutions: () => EMPTY_OFFLINE_RESOLUTIONS,
9465
- useOfflineUploads: () => emptyUploads
10147
+ useOfflineUploads: () => emptyUploads,
10148
+ useOfflineUploadFile: (id) => id ? missingUploadFile : idleUploadFile
9466
10149
  };
9467
10150
  }
9468
10151
  function createStoreManager(options) {
@@ -9527,7 +10210,8 @@ function createStoreManager(options) {
9527
10210
  useOfflineStatus: () => resolvedOfflineSession.useOfflineStatus(),
9528
10211
  useOfflineEntities: () => resolvedOfflineSession.useOfflineEntities(),
9529
10212
  useOfflineResolutions: () => resolvedOfflineSession.useOfflineResolutions(),
9530
- useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
10213
+ useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads(),
10214
+ useOfflineUploadFile: (id) => resolvedOfflineSession.useOfflineUploadFile(id)
9531
10215
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
9532
10216
  const storeManager = {
9533
10217
  getSessionKey: options.getSessionKey,
@@ -9617,7 +10301,7 @@ function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
9617
10301
  };
9618
10302
  }
9619
10303
  function resolveStoreManagerOfflineSession(storeManager, storeName, usesOfflineStorage) {
9620
- const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(storeManager));
10304
+ const offlineSession = storeManagerOfflineSessionRegistry.get(storeManager);
9621
10305
  if (!usesOfflineStorage) return null;
9622
10306
  if (!offlineSession) throw new Error(`[tsdf] Store "${storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
9623
10307
  return offlineSession;
@@ -10663,6 +11347,14 @@ function createCollectionStore(storeOptions) {
10663
11347
  finalPayload
10664
11348
  });
10665
11349
  },
11350
+ loadTempEntities: async (tempIds) => {
11351
+ if (!persistence?.hasAsyncPreload) return;
11352
+ const unloadedItemKeys = filterAndMap(tempIds, (tempId) => {
11353
+ const itemKey = getItemKey(__LEGIT_CAST__(tempId));
11354
+ return Object.hasOwn(store.state, itemKey) ? false : itemKey;
11355
+ });
11356
+ if (unloadedItemKeys.length > 0) await persistence.preloadItems(unloadedItemKeys);
11357
+ },
10666
11358
  applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
10667
11359
  storeEvents.emit("tempEntityReconciled", {
10668
11360
  tempId: __LEGIT_CAST__(tempId),
@@ -11251,18 +11943,18 @@ function createCollectionStore(storeOptions) {
11251
11943
  const payloadToUse = payload === null ? [] : payload;
11252
11944
  const affectedItems = Array.isArray(payloadToUse) ? payloadToUse : [payloadToUse];
11253
11945
  const affectedItemEntries = getItemsKeyArray(payloadToUse);
11254
- if (offline && offlineController && !offlineController.canQueueMutation()) return Result.err(toStoreMutationError(new OfflineSessionUnavailableError(), errorNormalizer));
11255
11946
  const mutationId = getAutoIncrementId();
11256
11947
  storeEvents.emit("mutationStart", {
11257
11948
  mutationId,
11258
11949
  items: affectedItems
11259
11950
  });
11260
11951
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
11261
- let accepted = false;
11262
- const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
11952
+ const runOnlineMutation = async () => ({
11263
11953
  kind: "online",
11264
11954
  data: await directMutation()
11265
- }), (exception, rollbacks) => {
11955
+ });
11956
+ let accepted = false;
11957
+ const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => offlineController?.canQueueMutation() ? runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : runOnlineMutation() : runOnlineMutation, (exception, rollbacks) => {
11266
11958
  const error = toStoreMutationError(exception, errorNormalizer);
11267
11959
  const revertedItems = /* @__PURE__ */ new Map();
11268
11960
  const changedItems = /* @__PURE__ */ new Map();
@@ -11603,7 +12295,7 @@ function setupDocumentPersistence(config) {
11603
12295
  let preloadPromise = null;
11604
12296
  let syncHydrationMissKnown = false;
11605
12297
  function isOfflineNetworkActive() {
11606
- return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig().network);
12298
+ return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig());
11607
12299
  }
11608
12300
  function readSyncHydratedDocumentData() {
11609
12301
  if (localStorageAdapter === null) return null;
@@ -12148,18 +12840,18 @@ function createDocumentStore(storeOptions) {
12148
12840
  const pendingDebounceRollbacks = /* @__PURE__ */ new Map();
12149
12841
  const optimisticMutations = createOptimisticMutationTracker();
12150
12842
  async function performMutation({ optimisticUpdate, mutation, debounce, silentErrors, revalidateOnSuccess, offline, upload }) {
12151
- if (offline && offlineController && !offlineController.canQueueMutation()) return Result.err(toStoreMutationError(new OfflineSessionUnavailableError(), errorNormalizer));
12152
12843
  const mutationId = getAutoIncrementId();
12153
12844
  storeEvents.emit("mutationStart", { mutationId });
12154
12845
  const directMutation = async () => unwrapTSDFResult(await mutation({
12155
12846
  updateState,
12156
12847
  currentState: store.state.data
12157
12848
  }));
12158
- let accepted = false;
12159
- const result = await performMutationWithLifecycle(startMutation, offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
12849
+ const runOnlineMutation = async () => ({
12160
12850
  kind: "online",
12161
12851
  data: await directMutation()
12162
- }), (exception, rollbacks) => {
12852
+ });
12853
+ let accepted = false;
12854
+ const result = await performMutationWithLifecycle(startMutation, offline ? () => offlineController?.canQueueMutation() ? runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : runOnlineMutation() : runOnlineMutation, (exception, rollbacks) => {
12163
12855
  let data = store.state.data;
12164
12856
  let changedSince = false;
12165
12857
  for (let i = rollbacks.length - 1; i >= 0; i--) {
@@ -12426,6 +13118,14 @@ function toItemState(persisted, dataSchema, shouldIgnoreItem) {
12426
13118
  loadedFields
12427
13119
  };
12428
13120
  }
13121
+ /**
13122
+ * Whether the rows left of a persisted list are its first rows, so only its
13123
+ * end is missing (e.g. cut by the byte budget). Like `maxQuerySize`
13124
+ * truncation, such a list is still a loaded list that has more pages.
13125
+ */
13126
+ function isOnlyTailMissing(remainingItemKeys, persistedItemKeys) {
13127
+ return remainingItemKeys.length > 0 && isStrictItemKeyPrefix(remainingItemKeys, persistedItemKeys);
13128
+ }
12429
13129
  function limitPersistedQueryItems(itemKeys, hasMore, maxQuerySize) {
12430
13130
  const limitedItemKeys = itemKeys.slice(0, maxQuerySize);
12431
13131
  return {
@@ -12610,6 +13310,7 @@ function setupListQueryPersistence(config, options = {}) {
12610
13310
  const querySizeBytesByKey = /* @__PURE__ */ new Map();
12611
13311
  const hydratedPersistedItemKeys = /* @__PURE__ */ new Set();
12612
13312
  const hydratedPersistedQueryKeys = /* @__PURE__ */ new Set();
13313
+ const incompleteRestoredQueryKeys = /* @__PURE__ */ new Set();
12613
13314
  const budgetEvictedItemRecency = /* @__PURE__ */ new Map();
12614
13315
  const budgetEvictedQueryRecency = /* @__PURE__ */ new Map();
12615
13316
  const syncHydrationItemMissCache = createTimedKeySet();
@@ -12619,7 +13320,7 @@ function setupListQueryPersistence(config, options = {}) {
12619
13320
  let maintenanceCallbackKey = null;
12620
13321
  const pendingLocalQueryReconciliationSessions = /* @__PURE__ */ new Set();
12621
13322
  function isOfflineNetworkActive() {
12622
- return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig().network);
13323
+ return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig());
12623
13324
  }
12624
13325
  function clearSaveTimer() {
12625
13326
  if (saveTimer !== null) {
@@ -12676,6 +13377,7 @@ function setupListQueryPersistence(config, options = {}) {
12676
13377
  items: entry.items,
12677
13378
  hasMore: entry.hasMore,
12678
13379
  lastAccessAt: entry.lastAccessAt,
13380
+ missingItems: entry.missingItems === true,
12679
13381
  offlineProtected: entry.offlineProtected,
12680
13382
  rawValue: rawEntry,
12681
13383
  sizeBytes
@@ -12762,6 +13464,7 @@ function setupListQueryPersistence(config, options = {}) {
12762
13464
  payload: data.payload,
12763
13465
  items: data.items,
12764
13466
  hasMore: data.hasMore,
13467
+ missingItems: data.missingItems,
12765
13468
  version
12766
13469
  }));
12767
13470
  rememberQueryMetadataSize(queryKey, sizeBytes);
@@ -12869,6 +13572,7 @@ function setupListQueryPersistence(config, options = {}) {
12869
13572
  payload: entry.payload,
12870
13573
  items: entry.items,
12871
13574
  hasMore: entry.hasMore,
13575
+ missingItems: entry.missingItems,
12872
13576
  version
12873
13577
  }));
12874
13578
  rememberQueryMetadataSize(queryKey, sizeBytes);
@@ -13046,6 +13750,7 @@ function setupListQueryPersistence(config, options = {}) {
13046
13750
  }
13047
13751
  function forgetPersistedQuery(queryKey) {
13048
13752
  hydratedPersistedQueryKeys.delete(queryKey);
13753
+ incompleteRestoredQueryKeys.delete(queryKey);
13049
13754
  querySnapshotByKey.delete(queryKey);
13050
13755
  querySizeBytesByKey.delete(queryKey);
13051
13756
  knownPersistedQueryKeys?.delete(queryKey);
@@ -13181,11 +13886,21 @@ function setupListQueryPersistence(config, options = {}) {
13181
13886
  const snapshot = querySnapshotByKey.get(queryKey);
13182
13887
  return snapshot ? parseHydratedQuerySnapshot(snapshot) : void 0;
13183
13888
  }
13184
- function filterRetainableHydratedSuffix(suffixItemKeys) {
13185
- return suffixItemKeys.filter((itemKey) => {
13889
+ /**
13890
+ * Returns the cached rows that can follow a refreshed first page. Stops at
13891
+ * the first row that can't be restored: keeping the rows after it would
13892
+ * save a list with a hole that is later restored as a complete one. The
13893
+ * query still has more pages, so the rows left out are loaded again.
13894
+ */
13895
+ function getRetainableHydratedSuffix(previousPersistedQuery, suffixItemKeys) {
13896
+ if (previousPersistedQuery.missingItems) return [];
13897
+ const retainable = [];
13898
+ for (const itemKey of suffixItemKeys) {
13186
13899
  const hydratedItem = readHydratedItem(itemKey);
13187
- return hydratedItem?.item != null && !shouldIgnoreItem(hydratedItem.itemQuery.payload);
13188
- });
13900
+ if (hydratedItem?.item == null || shouldIgnoreItem(hydratedItem.itemQuery.payload)) break;
13901
+ retainable.push(itemKey);
13902
+ }
13903
+ return retainable;
13189
13904
  }
13190
13905
  async function hydrateMissingAsyncItems(itemKeys) {
13191
13906
  if (localStorageAdapter !== null) return;
@@ -13229,7 +13944,8 @@ function setupListQueryPersistence(config, options = {}) {
13229
13944
  const persistedQuery = parsePersistedListQueryData({
13230
13945
  payload: entry.payload,
13231
13946
  items: entry.items,
13232
- hasMore: entry.hasMore
13947
+ hasMore: entry.hasMore,
13948
+ missingItems: entry.missingItems
13233
13949
  }, config.queryPayloadSchema);
13234
13950
  if (!persistedQuery) {
13235
13951
  syncHydrationQueryMissCache.remember(queryKey);
@@ -13244,24 +13960,43 @@ function setupListQueryPersistence(config, options = {}) {
13244
13960
  rememberHydratedQuery(queryKey, {
13245
13961
  payload: persistedQuery.payload,
13246
13962
  items: persistedQuery.items,
13247
- hasMore: persistedQuery.hasMore
13963
+ hasMore: persistedQuery.hasMore,
13964
+ ...persistedQuery.missingItems ? { missingItems: true } : {}
13248
13965
  }, getSerializedStringSize(rawEntry));
13249
13966
  return persistedQuery;
13250
13967
  }
13251
- function buildHydratedQueryState(persistedQuery) {
13252
- const limitedQuery = limitPersistedQueryItems(persistedQuery.items.filter((itemKey) => {
13253
- return readHydratedItem(itemKey) !== void 0;
13254
- }), persistedQuery.hasMore, maxQuerySize);
13968
+ /**
13969
+ * Builds the state of a query restored from storage. A persisted query
13970
+ * lists the rows it had when it was saved. When some of them can no longer
13971
+ * be restored (evicted by the byte budget, discarded on read, ...), the rows
13972
+ * that are left are still restored. If only the end of the list is missing,
13973
+ * it is restored as loaded with more pages, like `maxQuerySize` truncation.
13974
+ * Otherwise (a gap before a row that is left, or no row left) the query is
13975
+ * not restored as loaded: it would be reported as a complete `success` with
13976
+ * a list missing rows. A query that was not loaded is reported as `loading`
13977
+ * and always fetched, and fails with the offline error while offline.
13978
+ */
13979
+ function createRestoredQueryState(queryKey, persistedQuery, restoredItemKeys) {
13980
+ const hasAllRows = !persistedQuery.missingItems && restoredItemKeys.length === persistedQuery.items.length;
13981
+ const isTailMissing = !hasAllRows && !persistedQuery.missingItems && isOnlyTailMissing(restoredItemKeys, persistedQuery.items);
13982
+ const wasLoaded = hasAllRows || isTailMissing;
13983
+ const limitedQuery = limitPersistedQueryItems(restoredItemKeys, persistedQuery.hasMore || isTailMissing, maxQuerySize);
13984
+ if (!wasLoaded) incompleteRestoredQueryKeys.add(queryKey);
13255
13985
  return {
13256
13986
  error: null,
13257
13987
  hasMore: limitedQuery.hasMore,
13258
13988
  items: limitedQuery.itemKeys,
13259
13989
  payload: persistedQuery.payload,
13260
13990
  refetchOnMount: "lowPriority",
13261
- status: "success",
13262
- wasLoaded: true
13991
+ status: wasLoaded ? "success" : "loading",
13992
+ wasLoaded
13263
13993
  };
13264
13994
  }
13995
+ function buildHydratedQueryState(queryKey, persistedQuery) {
13996
+ return createRestoredQueryState(queryKey, persistedQuery, persistedQuery.items.filter((itemKey) => {
13997
+ return readHydratedItem(itemKey) !== void 0;
13998
+ }));
13999
+ }
13265
14000
  function createInitialState(baseState) {
13266
14001
  syncMaintenanceRegistration();
13267
14002
  return baseState;
@@ -13273,7 +14008,7 @@ function setupListQueryPersistence(config, options = {}) {
13273
14008
  }
13274
14009
  function readHydratedQuery(queryKey) {
13275
14010
  const persistedQuery = readPersistedQueryData(queryKey);
13276
- return persistedQuery ? buildHydratedQueryState(persistedQuery) : void 0;
14011
+ return persistedQuery ? buildHydratedQueryState(queryKey, persistedQuery) : void 0;
13277
14012
  }
13278
14013
  function resolveAsyncPreloadedItem(itemKey, cached, currentGeneration) {
13279
14014
  if (currentGeneration !== generation || !storeRef) return false;
@@ -13367,18 +14102,9 @@ function setupListQueryPersistence(config, options = {}) {
13367
14102
  if (!persistedQuery) return false;
13368
14103
  const activeStore = storeRef;
13369
14104
  for (const itemKey of persistedQuery.items) preloadItem(itemKey);
13370
- const limitedQuery = limitPersistedQueryItems(persistedQuery.items.filter((itemKey) => {
14105
+ materializeHydratedQueryState(queryKey, createRestoredQueryState(queryKey, persistedQuery, persistedQuery.items.filter((itemKey) => {
13371
14106
  return activeStore.state.items[itemKey] !== void 0 && activeStore.state.itemQueries[itemKey] !== void 0;
13372
- }), persistedQuery.hasMore, maxQuerySize);
13373
- materializeHydratedQueryState(queryKey, {
13374
- error: null,
13375
- hasMore: limitedQuery.hasMore,
13376
- items: limitedQuery.itemKeys,
13377
- payload: persistedQuery.payload,
13378
- refetchOnMount: "lowPriority",
13379
- status: "success",
13380
- wasLoaded: true
13381
- });
14107
+ })));
13382
14108
  return true;
13383
14109
  }
13384
14110
  const existingPromise = pendingQueryPreloads.get(queryKey);
@@ -13396,23 +14122,15 @@ function setupListQueryPersistence(config, options = {}) {
13396
14122
  await preloadItems(persistedQuery.items);
13397
14123
  if (currentGeneration !== generation || activeStore !== storeRef) return false;
13398
14124
  if (activeStore.state.queries[queryKey] !== void 0) return true;
13399
- const limitedQuery = limitPersistedQueryItems(persistedQuery.items.filter((itemKey) => {
14125
+ const filteredItemKeys = persistedQuery.items.filter((itemKey) => {
13400
14126
  return activeStore.state.items[itemKey] !== void 0 && activeStore.state.itemQueries[itemKey] !== void 0;
13401
- }), persistedQuery.hasMore, maxQuerySize);
14127
+ });
13402
14128
  suppressedPersistedStateFlushes++;
13403
14129
  activeStore.setState({
13404
14130
  ...activeStore.state,
13405
14131
  queries: {
13406
14132
  ...activeStore.state.queries,
13407
- [queryKey]: {
13408
- error: null,
13409
- hasMore: limitedQuery.hasMore,
13410
- items: limitedQuery.itemKeys,
13411
- payload: persistedQuery.payload,
13412
- refetchOnMount: "lowPriority",
13413
- status: "success",
13414
- wasLoaded: true
13415
- }
14133
+ [queryKey]: createRestoredQueryState(queryKey, persistedQuery, filteredItemKeys)
13416
14134
  }
13417
14135
  });
13418
14136
  return true;
@@ -13726,18 +14444,23 @@ function setupListQueryPersistence(config, options = {}) {
13726
14444
  knownPersistedQueryKeys = null;
13727
14445
  return;
13728
14446
  }
13729
- const limitedQuery = limitPersistedQueryItems(queryData.items.filter((itemKey) => keptItemKeys.has(itemKey)), queryData.hasMore, maxQuerySize);
14447
+ const filteredItems = queryData.items.filter((itemKey) => keptItemKeys.has(itemKey));
14448
+ const hasMissingRows = filteredItems.length < queryData.items.length;
14449
+ const isTailMissing = hasMissingRows && !queryData.missingItems && isOnlyTailMissing(filteredItems, queryData.items);
14450
+ const limitedQuery = limitPersistedQueryItems(filteredItems, queryData.hasMore || isTailMissing, maxQuerySize);
13730
14451
  if (limitedQuery.itemKeys.length === queryData.items.length && limitedQuery.hasMore === queryData.hasMore) continue;
13731
14452
  const nextQueryData = {
13732
14453
  payload: queryData.payload,
13733
14454
  items: limitedQuery.itemKeys,
13734
- hasMore: limitedQuery.hasMore
14455
+ hasMore: limitedQuery.hasMore,
14456
+ ...queryData.missingItems || hasMissingRows && !isTailMissing ? { missingItems: true } : {}
13735
14457
  };
13736
14458
  let saved = true;
13737
14459
  if (idleContext === void 0) await saveLocalStorageQueryEntry(queryData.queryKey, nextQueryData);
13738
14460
  else if (localMaintenanceScope !== void 0) saved = await saveLocalStorageQueryEntryIfUnchanged(queryData, nextQueryData, idleContext, localMaintenanceScope);
13739
14461
  else saved = false;
13740
14462
  if (!saved) staleQueryFound = true;
14463
+ else if (querySnapshotByKey.has(queryData.queryKey)) querySnapshotByKey.set(queryData.queryKey, JSON.stringify(nextQueryData));
13741
14464
  }
13742
14465
  if (staleQueryFound) {
13743
14466
  knownPersistedQueryKeys = null;
@@ -13848,7 +14571,14 @@ function setupListQueryPersistence(config, options = {}) {
13848
14571
  const persistedQueryItemKeys = /* @__PURE__ */ new Set();
13849
14572
  for (const [, query] of queryEntries) for (const itemKey of query.items) queryReferencedItemKeys.add(itemKey);
13850
14573
  for (const [queryKey, query] of queryEntries) {
13851
- if (query.status !== "success" && !query.wasLoaded) continue;
14574
+ if (query.status !== "success" && !query.wasLoaded) {
14575
+ if (incompleteRestoredQueryKeys.has(queryKey)) {
14576
+ nextQueryKeys.add(queryKey);
14577
+ for (const itemKey of query.items) persistedQueryItemKeys.add(itemKey);
14578
+ }
14579
+ continue;
14580
+ }
14581
+ if (incompleteRestoredQueryKeys.size > 0) incompleteRestoredQueryKeys.delete(queryKey);
13852
14582
  const filteredItems = query.items.filter((itemKey) => {
13853
14583
  const hasItemInState = Object.hasOwn(state.items, itemKey);
13854
14584
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
@@ -13863,7 +14593,7 @@ function setupListQueryPersistence(config, options = {}) {
13863
14593
  if (previousPersistedQuery && isStrictItemKeyPrefix(filteredItems, previousPersistedQuery.items)) {
13864
14594
  const suffixItemKeys = previousPersistedQuery.items.slice(filteredItems.length);
13865
14595
  await hydrateMissingAsyncItems(suffixItemKeys);
13866
- const cachedSuffix = filterRetainableHydratedSuffix(suffixItemKeys);
14596
+ const cachedSuffix = getRetainableHydratedSuffix(previousPersistedQuery, suffixItemKeys);
13867
14597
  queryItemsToPersist = [...filteredItems, ...cachedSuffix];
13868
14598
  }
13869
14599
  }
@@ -14012,6 +14742,7 @@ function setupListQueryPersistence(config, options = {}) {
14012
14742
  const finalPersistedQueryKeys = new Set(previousKnownLocalQueryKeys);
14013
14743
  for (const [queryKey, query] of queryEntries) {
14014
14744
  if (query.status !== "success" && !query.wasLoaded) continue;
14745
+ if (incompleteRestoredQueryKeys.size > 0) incompleteRestoredQueryKeys.delete(queryKey);
14015
14746
  const filteredItems = query.items.filter((itemKey) => {
14016
14747
  const hasItemInState = Object.hasOwn(state.items, itemKey);
14017
14748
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
@@ -14026,7 +14757,7 @@ function setupListQueryPersistence(config, options = {}) {
14026
14757
  if (previousPersistedQuery && isStrictItemKeyPrefix(filteredItems, previousPersistedQuery.items)) {
14027
14758
  const suffixItemKeys = previousPersistedQuery.items.slice(filteredItems.length);
14028
14759
  await hydrateMissingAsyncItems(suffixItemKeys);
14029
- const cachedSuffix = filterRetainableHydratedSuffix(suffixItemKeys);
14760
+ const cachedSuffix = getRetainableHydratedSuffix(previousPersistedQuery, suffixItemKeys);
14030
14761
  queryItemsToPersist = [...filteredItems, ...cachedSuffix];
14031
14762
  }
14032
14763
  }
@@ -14043,6 +14774,7 @@ function setupListQueryPersistence(config, options = {}) {
14043
14774
  for (const queryKey of previousKnownLocalQueryKeys) {
14044
14775
  if (finalQueryDataByKey.has(queryKey)) continue;
14045
14776
  if (!hydratedPersistedQueryKeys.has(queryKey)) continue;
14777
+ if (incompleteRestoredQueryKeys.has(queryKey)) continue;
14046
14778
  finalPersistedQueryKeys.delete(queryKey);
14047
14779
  }
14048
14780
  const commitTimestamp = Date.now();
@@ -14317,6 +15049,7 @@ function setupListQueryPersistence(config, options = {}) {
14317
15049
  pendingQueryPreloads.clear();
14318
15050
  hydratedPersistedItemKeys.clear();
14319
15051
  hydratedPersistedQueryKeys.clear();
15052
+ incompleteRestoredQueryKeys.clear();
14320
15053
  syncHydrationItemMissCache.clearAll();
14321
15054
  syncHydrationQueryMissCache.clearAll();
14322
15055
  knownPersistedItemKeys = null;
@@ -14352,6 +15085,7 @@ function setupListQueryPersistence(config, options = {}) {
14352
15085
  budgetEvictedQueryRecency.clear();
14353
15086
  hydratedPersistedItemKeys.clear();
14354
15087
  hydratedPersistedQueryKeys.clear();
15088
+ incompleteRestoredQueryKeys.clear();
14355
15089
  syncHydrationItemMissCache.clearAll();
14356
15090
  syncHydrationQueryMissCache.clearAll();
14357
15091
  await Promise.all([itemNamespace.clear(), clearLocalStorageQueries()]);
@@ -15239,7 +15973,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
15239
15973
  function loadMoreFromHydratedQuery(queryKey, queryState, loadSize, fields) {
15240
15974
  if (!persistence) return "skipped";
15241
15975
  const hydratedQuery = persistence.readHydratedQuery(queryKey);
15242
- if (!hydratedQuery) return "skipped";
15976
+ if (!hydratedQuery?.wasLoaded) return "skipped";
15243
15977
  if (!isStrictItemKeyPrefix(queryState.items, hydratedQuery.items)) return "skipped";
15244
15978
  const start = queryState.items.length;
15245
15979
  const end = Math.min(start + loadSize, hydratedQuery.items.length);
@@ -15330,7 +16064,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
15330
16064
  let query = getQueryStateByKey(queryKey);
15331
16065
  if (isOfflineStoreError(query?.error)) {
15332
16066
  const hydratedQuery = persistence?.readHydratedQuery(queryKey);
15333
- if (hydratedQuery) {
16067
+ if (hydratedQuery?.wasLoaded) {
15334
16068
  query = hydratedQuery;
15335
16069
  store.produceState((draft) => {
15336
16070
  draft.queries[queryKey] = hydratedQuery;
@@ -16149,11 +16883,12 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
16149
16883
  }
16150
16884
  return someItemWasUpdated;
16151
16885
  }
16152
- function addItemToState(itemPayload, data, options = {}) {
16886
+ function addItemToState(itemPayload, data, options = {}, loadedFields) {
16153
16887
  const itemKey = getItemKey(itemPayload);
16154
16888
  store.batch(() => {
16155
16889
  store.produceState((draftState) => {
16156
16890
  draftState.items[itemKey] = data;
16891
+ if (loadedFields !== void 0) draftState.itemLoadedFields[itemKey] = loadedFields;
16157
16892
  draftState.itemQueries[itemKey] = {
16158
16893
  status: "success",
16159
16894
  wasLoaded: true,
@@ -16222,7 +16957,6 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
16222
16957
  }
16223
16958
  async function performMutation(payload, { optimisticUpdate, mutation, silentErrors, revalidateOnSuccess, onSuccess, onError, debounce, offline, upload }) {
16224
16959
  const payloadToUse = payload === null ? [] : payload;
16225
- if (offline && offlineController && !offlineController.canQueueMutation()) return Result.err(toStoreMutationError(new OfflineSessionUnavailableError(), errorNormalizer));
16226
16960
  const affectedItemEntries = optimisticUpdate ? getItemsKeyArray(payloadToUse) : void 0;
16227
16961
  const affectedItems = affectedItemEntries ? affectedItemEntries.map(({ payload: p }) => p) : resolveAffectedItems(payloadToUse);
16228
16962
  const normalizedRevalidateOnSuccess = normalizeRevalidateOnSuccessOption(revalidateOnSuccess);
@@ -16238,6 +16972,10 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
16238
16972
  items: affectedItems
16239
16973
  });
16240
16974
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
16975
+ const runOnlineMutation = async () => ({
16976
+ kind: "online",
16977
+ data: await directMutation()
16978
+ });
16241
16979
  let accepted = false;
16242
16980
  const result = await performMutationWithLifecycle(() => {
16243
16981
  const endBaseMutations = startItemMutation(payloadToUse);
@@ -16245,10 +16983,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
16245
16983
  endBaseMutations();
16246
16984
  for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
16247
16985
  };
16248
- }, offline ? () => runHybridOfflineMutation(offlineController, offline, upload, directMutation) : async () => ({
16249
- kind: "online",
16250
- data: await directMutation()
16251
- }), (exception, rollbacks) => {
16986
+ }, offline ? () => offlineController?.canQueueMutation() ? runHybridOfflineMutation(offlineController, offline, upload, directMutation) : runOnlineMutation() : runOnlineMutation, (exception, rollbacks) => {
16252
16987
  const error = toStoreMutationError(exception, errorNormalizer);
16253
16988
  revertOptimisticMutations(rollbacks, mutationId);
16254
16989
  if (onMutationError) onMutationError(exception, { silentErrors });
@@ -17099,6 +17834,14 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
17099
17834
  }
17100
17835
  //#endregion
17101
17836
  //#region src/listQueryStore/useMultipleListQueries.ts
17837
+ /**
17838
+ * Whether the cached query has rows after `items` that offline `loadMore` can
17839
+ * append. A cached list missing some of its rows can't: its next rows may come
17840
+ * after a missing row.
17841
+ */
17842
+ function canLoadMoreFromCachedQuery(items, cachedQuery) {
17843
+ return cachedQuery?.wasLoaded === true && isStrictItemKeyPrefix(items, cachedQuery.items);
17844
+ }
17102
17845
  function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, omitPayload: allItemsOmitPayload, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, loadSize: allItemsLoadSize, debouncePayload }, store, events, getQueryKey, registerActiveQueries, touchQueries, getQueryState, readFallbackQueryState, preloadQueries, preloadQueriesBeforePaint, preloadDerivedQueryItems, readFallbackItemState, scheduleAutomaticListQueryFetch, queryInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, partialResources, derivedQueries, isOfflineMode, offlineEntities, offlineOverlays) {
17103
17846
  const isOffScreenFromContext = useContext(IsOffScreenContext);
17104
17847
  const queriesWithId = useMemo(() => {
@@ -17278,7 +18021,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17278
18021
  };
17279
18022
  const groupKey = derivedQueries.getQueryGroup(queryConfig.payload);
17280
18023
  if (!isOfflineMode && !stickyDerived) {
17281
- const groupQueries = Object.values(state.queries).filter((query) => derivedQueries.getQueryGroup(query.payload) === groupKey).map((query) => ({
18024
+ const groupQueries = Object.values(state.queries).filter((query) => query.wasLoaded && derivedQueries.getQueryGroup(query.payload) === groupKey).map((query) => ({
17282
18025
  payload: query.payload,
17283
18026
  hasMore: query.hasMore,
17284
18027
  itemCount: query.items.length
@@ -17427,7 +18170,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17427
18170
  itemPayload: state.itemQueries[itemKey]?.payload
17428
18171
  })),
17429
18172
  error,
17430
- hasMore: isOfflineMode ? !!readFallbackQueryState && effectiveQuery.query.hasMore && isStrictItemKeyPrefix(effectiveQuery.query.items, readFallbackQueryState(queryKey)?.items ?? []) : effectiveQuery.query.hasMore,
18173
+ hasMore: isOfflineMode ? effectiveQuery.query.hasMore && canLoadMoreFromCachedQuery(effectiveQuery.query.items, readFallbackQueryState?.(queryKey)) : effectiveQuery.query.hasMore,
17431
18174
  isDerived: effectiveQuery.isDerived,
17432
18175
  ...loadingFields ? { loadingFields } : {},
17433
18176
  isLoading: status === "loading",
@@ -17457,7 +18200,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17457
18200
  if (result.status !== "loading" && result.status !== "idle") return result;
17458
18201
  if (queryConfig && readFallbackQueryState && !store.state.queries[queryConfig.key]?.wasLoaded && !(derivedQueries && (isOfflineMode || stickyDerivedQueryKeys.has(queryConfig.key)))) {
17459
18202
  const fallbackQuery = readFallbackQueryState(queryConfig.key);
17460
- if (fallbackQuery && readFallbackItemState) {
18203
+ if (fallbackQuery?.wasLoaded && readFallbackItemState) {
17461
18204
  const visibleItemKeys = getVisibleQueryItemKeys(result.queryKey, fallbackQuery.items);
17462
18205
  const requestedFields = Array.isArray(queryConfig.fields) ? queryConfig.fields : void 0;
17463
18206
  const requiresFullItems = queryConfig.fields === "*";
@@ -17991,7 +18734,7 @@ function createListQueryStore(storeOptions) {
17991
18734
  }
17992
18735
  let offlineController = null;
17993
18736
  function isOfflineFetchModeActive() {
17994
- return (offlineController?.shouldTreatFetchAsOffline() ?? false) || resolvedOfflineConfig?.session.getOfflineStatus().isOfflineMode === true || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
18737
+ return (offlineController?.shouldTreatFetchAsOffline() ?? false) || resolvedOfflineConfig?.session.getOfflineStatus().isOfflineMode === true || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig());
17995
18738
  }
17996
18739
  const offlineFetchController = {
17997
18740
  prepareForFetch: () => offlineController?.prepareForFetch() ?? Promise.resolve(),
@@ -18274,9 +19017,9 @@ function createListQueryStore(storeOptions) {
18274
19017
  if (sessionKey === false) return [];
18275
19018
  return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "listQuery.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
18276
19019
  },
18277
- applyPendingEntity: ({ tempId, pendingEntity }) => {
19020
+ applyPendingEntity: ({ tempId, pendingEntity, addToQueries, loadedFields }) => {
18278
19021
  if (!pendingEntity || typeof pendingEntity !== "object") return;
18279
- addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
19022
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity), addToQueries && { addItemToQueries: addToQueries }, partialResources ? loadedFields : void 0);
18280
19023
  },
18281
19024
  rollbackPendingEntity: ({ tempId }) => {
18282
19025
  deleteItemState(__LEGIT_CAST__(tempId));
@@ -18284,6 +19027,7 @@ function createListQueryStore(storeOptions) {
18284
19027
  reconcileTempEntity: ({ tempId, reconciliation }) => {
18285
19028
  reconcileOfflineTempItem(tempId, reconciliation.finalPayload, reconciliation.finalData);
18286
19029
  },
19030
+ loadTempEntities: (tempIds, addToQueries) => loadOfflineTempEntities(__LEGIT_CAST__(tempIds), addToQueries),
18287
19031
  applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
18288
19032
  if (!runWithoutBroadcast(() => reconcileOfflineTempItem(tempId, finalPayload, void 0))) emitTempItemReconciled(tempId, finalPayload);
18289
19033
  },
@@ -18389,6 +19133,23 @@ function createListQueryStore(storeOptions) {
18389
19133
  });
18390
19134
  }
18391
19135
  /**
19136
+ * Loads offline temp items, and the queries they are declared into, that are
19137
+ * only in persistent storage: the queries then receive the pending items,
19138
+ * and reconciliation reads the items' data and loaded fields from memory.
19139
+ * Returns `undefined` when there is nothing to load.
19140
+ */
19141
+ function loadOfflineTempEntities(tempPayloads, addToQueries) {
19142
+ if (!persistence) return void 0;
19143
+ const unloadedItemKeys = filterAndMap(tempPayloads, (tempPayload) => {
19144
+ const itemKey = getItemKey(tempPayload);
19145
+ return store.state.items[itemKey] === void 0 ? itemKey : false;
19146
+ });
19147
+ const unloadedQueries = /* @__PURE__ */ new Map();
19148
+ for (const { queries } of addToQueries) for (const { key, payload } of getQueriesKeyArray(queries)) if (store.state.queries[key] === void 0) unloadedQueries.set(key, payload);
19149
+ if (unloadedItemKeys.length === 0 && unloadedQueries.size === 0) return;
19150
+ return Promise.all([unloadedItemKeys.length > 0 && persistence.preloadItems(unloadedItemKeys), unloadedQueries.size > 0 && preloadQueryFromPersistentStorage([...unloadedQueries.values()])]);
19151
+ }
19152
+ /**
18392
19153
  * Replaces an offline temp item with its final one, in place in every query
18393
19154
  * that lists it. Returns `false` when there is no data for the final item.
18394
19155
  */
@@ -18404,8 +19165,9 @@ function createListQueryStore(storeOptions) {
18404
19165
  queryKey,
18405
19166
  index: query.items.indexOf(tempItemKey)
18406
19167
  })).filter(({ index }) => index !== -1);
19168
+ const tempLoadedFields = store.state.itemLoadedFields[tempItemKey];
18407
19169
  deleteItemState(tempPayload);
18408
- addItemToState(finalPayload, finalData);
19170
+ addItemToState(finalPayload, finalData, void 0, tempLoadedFields);
18409
19171
  emitTempItemReconciled(tempId, finalPayloadValue);
18410
19172
  if (queryMemberships.length === 0) return true;
18411
19173
  store.produceState((draft) => {
@@ -18666,7 +19428,7 @@ function createListQueryStore(storeOptions) {
18666
19428
  return useOfflineStoreIsOfflineMode({
18667
19429
  sessionKey: getSessionKeyForRuntime(),
18668
19430
  inactiveScope: id
18669
- }) || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
19431
+ }) || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig());
18670
19432
  }
18671
19433
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
18672
19434
  const offlineEntities = useOfflineStoreEntities({
@@ -18891,8 +19653,8 @@ function createListQueryStore(storeOptions) {
18891
19653
  touchUpdatedItemEntries(itemEntries);
18892
19654
  return wasUpdated;
18893
19655
  }
18894
- function addItemToState(itemPayload, data, options) {
18895
- addItemToStateBase(itemPayload, data, options);
19656
+ function addItemToState(itemPayload, data, options, loadedFields) {
19657
+ addItemToStateBase(itemPayload, data, options, loadedFields);
18896
19658
  touchUpdatedItemEntries([{
18897
19659
  itemKey: getItemKey(itemPayload),
18898
19660
  payload: itemPayload