tsdf 18.3.1 → 18.4.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
@@ -2909,7 +2909,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2909
2909
  }
2910
2910
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2911
2911
  async function clearAllSessionStorage(sessionKey) {
2912
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Daewq7dv.js");
2912
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-BFn-BuAl.js");
2913
2913
  await Promise.all([
2914
2914
  clearSessionStorage(sessionKey, "local-sync"),
2915
2915
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -3774,6 +3774,34 @@ function isOfflineResolutionRecordForStore(resolution, operations) {
3774
3774
  return resolution.operation in operations;
3775
3775
  }
3776
3776
  //#endregion
3777
+ //#region src/persistentStorage/offline/offlineStoreError.typeGuards.ts
3778
+ /**
3779
+ * Whether `error` is the error TSDF reports for a fetch that could not
3780
+ * complete because the offline session is in offline mode (the request is not
3781
+ * sent while offline).
3782
+ *
3783
+ * TSDF only exposes it on reads that have nothing cached to return
3784
+ * (`status: 'error'`): a document, item or query that is returning cached data
3785
+ * stays `success` with `error: null` while offline, so this is the state the
3786
+ * app has to explain to the user ("not available offline").
3787
+ *
3788
+ * Accepts the `error` of hooks and state getters and the `StoreFetchError` of
3789
+ * the `awaitFetch` methods. The error is matched by its whole shape, not only
3790
+ * by `id`, so an app error whose `errorNormalizer` happens to use the
3791
+ * `'offline'` id is not mistaken for it.
3792
+ *
3793
+ * @example
3794
+ * ```tsx
3795
+ * const { data, error } = store.useDocument();
3796
+ *
3797
+ * if (isOfflineStoreError(error)) return <NotAvailableOffline />;
3798
+ * if (error) return <ErrorMessage error={error} />;
3799
+ * ```
3800
+ */
3801
+ function isOfflineStoreError(error) {
3802
+ return !!error && error.id === "offline" && error.code === 0 && error.message === "Offline";
3803
+ }
3804
+ //#endregion
3777
3805
  //#region src/persistentStorage/offline/overlayStoreLifecycle.ts
3778
3806
  function rebindOfflineOverlayEntries(overlayStore, itemKeyRewrites, createReboundOverlay) {
3779
3807
  if (itemKeyRewrites.length === 0) return;
@@ -4297,6 +4325,67 @@ function normalizeUploadFile(file, fallbackName) {
4297
4325
  });
4298
4326
  }
4299
4327
  //#endregion
4328
+ //#region src/persistentStorage/offline/entityMetadata.ts
4329
+ function createOfflineEntityLookup(entities) {
4330
+ const entitiesByKey = /* @__PURE__ */ new Map();
4331
+ for (const entity of entities) entitiesByKey.set(entity.entityKey, entity);
4332
+ return entitiesByKey;
4333
+ }
4334
+ const storeEntityLookupsBySessionEntities = /* @__PURE__ */ new WeakMap();
4335
+ const emptyEntityLookup = /* @__PURE__ */ new Map();
4336
+ /**
4337
+ * Entities of one store keyed by entity key, for a snapshot of the session's
4338
+ * entities (all stores). The lookups are built once per snapshot and shared by
4339
+ * every reader, so per-item readers (one per rendered row) do a keyed read
4340
+ * instead of each scanning the whole session on every change.
4341
+ */
4342
+ function getOfflineStoreEntityLookup(sessionEntities, storeName) {
4343
+ let lookupsByStoreName = storeEntityLookupsBySessionEntities.get(sessionEntities);
4344
+ if (!lookupsByStoreName) {
4345
+ lookupsByStoreName = /* @__PURE__ */ new Map();
4346
+ for (const entity of sessionEntities) {
4347
+ let lookup = lookupsByStoreName.get(entity.storeName);
4348
+ if (!lookup) {
4349
+ lookup = /* @__PURE__ */ new Map();
4350
+ lookupsByStoreName.set(entity.storeName, lookup);
4351
+ }
4352
+ lookup.set(entity.entityKey, entity);
4353
+ }
4354
+ storeEntityLookupsBySessionEntities.set(sessionEntities, lookupsByStoreName);
4355
+ }
4356
+ return lookupsByStoreName.get(storeName) ?? emptyEntityLookup;
4357
+ }
4358
+ function toItemOfflineState(entity) {
4359
+ if (entity?.entityKind !== "item") return null;
4360
+ return {
4361
+ syncState: entity.syncState,
4362
+ pendingMutations: entity.pendingMutations,
4363
+ requiresResolution: entity.requiresResolution,
4364
+ isUnsentCreation: entity.tempId !== void 0
4365
+ };
4366
+ }
4367
+ function getIsPendingOfflineSync(entity) {
4368
+ return !!entity && !entity.requiresResolution;
4369
+ }
4370
+ function hasPendingOfflineSync(entitiesByKey, entityKeys) {
4371
+ for (const entityKey of entityKeys) if (getIsPendingOfflineSync(entitiesByKey.get(entityKey))) return true;
4372
+ return false;
4373
+ }
4374
+ function shouldApplyOfflineOverlay(entity, overlay) {
4375
+ return !!entity && (!entity.requiresResolution || entity.blockedResolutionCount > 0 || entity.childResolutionCount > 0 || typeof overlay === "object" && overlay !== null && "keepVisibleWhileResolutionRequired" in overlay && overlay.keepVisibleWhileResolutionRequired === true);
4376
+ }
4377
+ /**
4378
+ * Batch-filters offline overlays to only include entries with a pending sync
4379
+ * (entity exists and does not require resolution). Use this instead of calling
4380
+ * {@link getActiveOfflineOverlay} per item when all active overlays are needed
4381
+ * at once.
4382
+ */
4383
+ function filterActiveOfflineOverlays(entitiesByKey, overlays) {
4384
+ const result = {};
4385
+ for (const [entityKey, overlay] of Object.entries(overlays)) if (shouldApplyOfflineOverlay(entitiesByKey.get(entityKey), overlay)) result[entityKey] = overlay;
4386
+ return result;
4387
+ }
4388
+ //#endregion
4300
4389
  //#region src/persistentStorage/offline/sessionCoordinator.ts
4301
4390
  function stripInternalEntityPayload(entity) {
4302
4391
  if (!("payload" in entity)) return entity;
@@ -4593,9 +4682,34 @@ var SessionOfflineCoordinator = class {
4593
4682
  #onPersistentStorageError;
4594
4683
  #uploadsConfig;
4595
4684
  #uploads = /* @__PURE__ */ new Map();
4685
+ #storedUploadsRestore = null;
4686
+ /**
4687
+ * Ids other tabs deleted while this tab's stored uploads were being listed,
4688
+ * so the list result can't bring them back. `null` outside the listing.
4689
+ */
4690
+ #uploadsRemovedWhileListing = null;
4596
4691
  #referencedUploadIds = /* @__PURE__ */ new Set();
4597
4692
  #uploadQueue;
4598
4693
  #uploadPromisesById = /* @__PURE__ */ new Map();
4694
+ /**
4695
+ * Uploads released by work that left the queue but not deleted yet: a store
4696
+ * had not reported its references, or the upload was still being sent.
4697
+ */
4698
+ #pendingUploadReleases = /* @__PURE__ */ new Set();
4699
+ /**
4700
+ * Files attached to a mutation that is still being queued: saved before the
4701
+ * queue entry that references them, so unused-mutation-upload cleanup must
4702
+ * skip them until a store reports that reference.
4703
+ */
4704
+ #stagedMutationUploadIds = /* @__PURE__ */ new Set();
4705
+ /**
4706
+ * Refs of uploads that were uploaded and then released, so data still
4707
+ * holding their ids (optimistic or draft state) resolves to the same ref
4708
+ * for the rest of the session instead of failing.
4709
+ */
4710
+ #releasedUploadRefs = /* @__PURE__ */ new Map();
4711
+ /** Adapter removals in flight, awaited before the same id is read or saved. */
4712
+ #uploadRemovals = /* @__PURE__ */ new Map();
4599
4713
  #uploadCleanupTimer = null;
4600
4714
  #uploadOnlineSessionStartedAt = null;
4601
4715
  #uploadOnlineSessionStabilizationTimer = null;
@@ -4696,6 +4810,10 @@ var SessionOfflineCoordinator = class {
4696
4810
  this.#registrations.get(message.storeName)?.onRemoteWorkDiscarded?.(message.discardedWork, message.removedTempEntityKeys);
4697
4811
  return;
4698
4812
  }
4813
+ if (message.kind === "offline-uploads-removed") {
4814
+ this.#applyRemoteUploadsRemoved(message.ids, message.releasedRefs);
4815
+ return;
4816
+ }
4699
4817
  this.#applyRemoteSnapshot(message);
4700
4818
  }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, (noteFocusChange) => {
4701
4819
  if (!isWindowAvailable()) return () => {};
@@ -4753,16 +4871,12 @@ var SessionOfflineCoordinator = class {
4753
4871
  }
4754
4872
  this.#protectedKeys = [...protectedKeys].sort();
4755
4873
  setSessionProtectedKeysSnapshot(this.sessionKey, this.#protectedKeys);
4756
- if (this.#uploadsConfig) try {
4757
- const uploads = await this.#uploadsConfig.adapter.list(this.sessionKey);
4874
+ if (this.#uploadsConfig) {
4875
+ await this.#restoreStoredUploads();
4758
4876
  if (hydrationToken === this.#hydrationToken) {
4759
- this.#uploads = new Map([...uploads.map((upload) => [upload.id, upload]), ...this.#uploads]);
4760
- this.#syncUploadsState();
4761
4877
  this.#scheduleUploadOnlineSessionStabilization();
4762
4878
  this.#refreshUploadRetention();
4763
4879
  }
4764
- } catch (error) {
4765
- this.#onPersistentStorageError?.(error);
4766
4880
  }
4767
4881
  this.#persistSessionSnapshot();
4768
4882
  }
@@ -4857,13 +4971,13 @@ var SessionOfflineCoordinator = class {
4857
4971
  });
4858
4972
  }
4859
4973
  /** Tells the other tabs that this tab discarded queued work of a store. */
4860
- publishWorkDiscarded(storeName, discardedWork, removedTempEntityKeys) {
4974
+ publishWorkDiscarded(storeName, discardedWork, removedEntityKeys) {
4861
4975
  if (this.#disposed) return;
4862
4976
  this.#browserTabs.coordinator.publish({
4863
4977
  kind: "offline-work-discarded",
4864
4978
  storeName,
4865
4979
  discardedWork,
4866
- removedTempEntityKeys
4980
+ removedTempEntityKeys: removedEntityKeys
4867
4981
  });
4868
4982
  }
4869
4983
  /**
@@ -4922,7 +5036,12 @@ var SessionOfflineCoordinator = class {
4922
5036
  }
4923
5037
  async saveUpload(args) {
4924
5038
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
5039
+ await this.#restoreStoredUploads();
5040
+ await this.#waitForUploadRemoval(args.id);
4925
5041
  if (this.#uploadPromisesById.has(args.id)) throw new Error(`Cannot change upload "${args.id}" while it is queued or uploading`);
5042
+ this.#pendingUploadReleases.delete(args.id);
5043
+ this.#releasedUploadRefs.delete(args.id);
5044
+ if (args.source === "mutation") this.#stagedMutationUploadIds.add(args.id);
4926
5045
  const existing = this.#uploads.get(args.id);
4927
5046
  const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt(), args.metadata, args.storeName);
4928
5047
  await this.#saveUploadRecord(nextRecord);
@@ -4941,13 +5060,66 @@ var SessionOfflineCoordinator = class {
4941
5060
  return (await this.#getUploadRecord(id))?.file ?? null;
4942
5061
  }
4943
5062
  async deleteUpload(id) {
5063
+ await this.#restoreStoredUploads();
4944
5064
  if (this.#referencedUploadIds.has(id)) throw new Error(`Cannot delete upload "${id}" while it is still referenced`);
4945
5065
  if (this.#uploadPromisesById.has(id)) throw new Error(`Cannot delete upload "${id}" while it is uploading`);
4946
- if (!this.#uploadsConfig) return;
4947
- this.#uploads.delete(id);
4948
- await this.#uploadsConfig.adapter.remove(this.sessionKey, id);
4949
- this.#syncUploadsState();
4950
- this.#refreshUploadRetention();
5066
+ this.#stagedMutationUploadIds.delete(id);
5067
+ this.#releasedUploadRefs.delete(id);
5068
+ await this.#removeUploads([id]);
5069
+ }
5070
+ /**
5071
+ * Deletes the given staged uploads unless queued work still needs them.
5072
+ *
5073
+ * Store controllers call this after a queue entry or resolution record left
5074
+ * the queue for good (replayed, discarded, superseded, cancelled), passing
5075
+ * the uploads that work depended on. It must run after the store synced its
5076
+ * remaining references: they are aggregated session-wide, so an upload is
5077
+ * kept while a queue entry or resolution record of any store references it.
5078
+ *
5079
+ * Uploads no queued work referenced are never passed here: the app stages a
5080
+ * file before it queues the mutation, so being unreferenced alone must not
5081
+ * delete an upload. Those are left to `deleteUpload` and to the retention
5082
+ * window.
5083
+ */
5084
+ async deleteUnreferencedUploads(uploadIds) {
5085
+ if (this.#disposed) return;
5086
+ for (const id of uploadIds) this.#pendingUploadReleases.add(id);
5087
+ await this.#releasePendingUploads();
5088
+ }
5089
+ /**
5090
+ * Deletes the released uploads nothing references anymore. Runs again when
5091
+ * the last store reports its references and when a released upload that was
5092
+ * still being sent settles.
5093
+ */
5094
+ async #releasePendingUploads() {
5095
+ if (this.#pendingUploadReleases.size === 0) return;
5096
+ await this.#restoreStoredUploads();
5097
+ const cannotRelease = () => this.#disposed || this.#pendingUploadReleases.size === 0 || this.#storeContributions.size !== this.#registrations.size;
5098
+ if (cannotRelease()) return;
5099
+ const missingIds = [...this.#pendingUploadReleases].filter((id) => !this.#uploads.has(id) && !this.#uploadPromisesById.has(id));
5100
+ if (missingIds.length > 0) {
5101
+ try {
5102
+ await Promise.all(missingIds.map((id) => this.#getUploadRecord(id)));
5103
+ } catch (error) {
5104
+ this.#onPersistentStorageError?.(error);
5105
+ }
5106
+ if (cannotRelease()) return;
5107
+ }
5108
+ const removableIds = [];
5109
+ for (const id of this.#pendingUploadReleases) {
5110
+ if (this.#uploadPromisesById.has(id)) continue;
5111
+ this.#pendingUploadReleases.delete(id);
5112
+ const upload = this.#uploads.get(id);
5113
+ if (upload && !this.#referencedUploadIds.has(id)) {
5114
+ if (upload.state === "uploaded" && upload.resolvedRef !== void 0) this.#releasedUploadRefs.set(id, upload.resolvedRef);
5115
+ removableIds.push(id);
5116
+ }
5117
+ }
5118
+ try {
5119
+ await this.#removeUploads(removableIds);
5120
+ } catch (error) {
5121
+ this.#onPersistentStorageError?.(error);
5122
+ }
4951
5123
  }
4952
5124
  async resolveUploadIds(uploadIds) {
4953
5125
  const entries = await Promise.all(uploadIds.map(async (id) => {
@@ -4955,6 +5127,57 @@ var SessionOfflineCoordinator = class {
4955
5127
  }));
4956
5128
  return Object.fromEntries(entries);
4957
5129
  }
5130
+ /**
5131
+ * Resolves the dependency uploads of a replaying operation. A failure is
5132
+ * returned with the id of the upload that caused it instead of thrown, and
5133
+ * leaves that upload `pending`: replay classifies the failure first and
5134
+ * calls `markUploadFailed` only when it gives up on the operation.
5135
+ */
5136
+ async resolveReplayUploadIds(uploadIds) {
5137
+ const failures = [];
5138
+ const entries = await Promise.all(uploadIds.map(async (id) => {
5139
+ try {
5140
+ return [id, await this.#ensureUploadResolved(id, true)];
5141
+ } catch (error) {
5142
+ failures.push({
5143
+ failedUploadId: id,
5144
+ error
5145
+ });
5146
+ throw error;
5147
+ }
5148
+ })).catch(() => null);
5149
+ return failures[0] ?? { refs: Object.fromEntries(entries ?? []) };
5150
+ }
5151
+ /**
5152
+ * Marks the dependency uploads of an operation as `failed` after replay
5153
+ * moved it to manual resolution. Uploads still being sent are marked if
5154
+ * they fail too. Uploads that are not waiting on a failure (restarted or
5155
+ * uploaded meanwhile) are left untouched.
5156
+ *
5157
+ * Never rejects: the state only drives the upload UI, so a storage error is
5158
+ * reported instead of interrupting the replay.
5159
+ */
5160
+ async markUploadsFailed(ids) {
5161
+ const reportError = (error) => this.#onPersistentStorageError?.(error);
5162
+ const settledIds = [];
5163
+ for (const id of ids) {
5164
+ const inFlight = this.#uploadPromisesById.get(id);
5165
+ if (!inFlight) {
5166
+ settledIds.push(id);
5167
+ continue;
5168
+ }
5169
+ inFlight.catch(() => this.#markUploadFailed(id)).catch(reportError);
5170
+ }
5171
+ await Promise.all(settledIds.map((id) => this.#markUploadFailed(id).catch(reportError)));
5172
+ }
5173
+ async #markUploadFailed(id) {
5174
+ const record = this.#uploads.get(id);
5175
+ if (record?.state !== "pending" || !record.lastError) return;
5176
+ await this.#updateUploadState({
5177
+ id,
5178
+ state: "failed"
5179
+ });
5180
+ }
4958
5181
  isLeader() {
4959
5182
  return this.#browserTabs.priority.getPriorityRank() <= 1;
4960
5183
  }
@@ -5113,6 +5336,11 @@ var SessionOfflineCoordinator = class {
5113
5336
  const nextEnabled = this.#isNetworkEnabled();
5114
5337
  const nextActive = active;
5115
5338
  this.#classifiedNetworkActive = nextActive ? options.classified ?? this.#classifiedNetworkActive : false;
5339
+ const currentStatus = this.store.state.status;
5340
+ if (currentStatus.network.enabled === nextEnabled && currentStatus.network.active === nextActive && !(nextActive && options.recordFailureAt) && (options.recoveryCheckAt === void 0 || options.recoveryCheckAt === currentStatus.lastRecoveryCheckAt)) {
5341
+ this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5342
+ return;
5343
+ }
5116
5344
  this.#updateStatus((current) => ({
5117
5345
  ...current,
5118
5346
  network: {
@@ -5205,10 +5433,38 @@ var SessionOfflineCoordinator = class {
5205
5433
  const initial = this.#getCurrentOfflineState();
5206
5434
  if (typeof initial === "boolean") this.setNetworkActive(initial, { classified: false });
5207
5435
  }
5436
+ /**
5437
+ * Lists the stored uploads into memory, once per coordinator. Every upload
5438
+ * operation that reads or changes a record waits for it first: the in-memory
5439
+ * map is only authoritative after the stored records are in it, and a list
5440
+ * result applied over newer changes would drop saved uploads and bring
5441
+ * deleted ones back.
5442
+ */
5443
+ #restoreStoredUploads() {
5444
+ if (!this.#uploadsConfig) return void 0;
5445
+ return this.#storedUploadsRestore ??= this.#listStoredUploads(this.#uploadsConfig);
5446
+ }
5447
+ async #listStoredUploads(uploadsConfig) {
5448
+ const removedWhileListing = /* @__PURE__ */ new Set();
5449
+ this.#uploadsRemovedWhileListing = removedWhileListing;
5450
+ try {
5451
+ 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]);
5453
+ this.#syncUploadsState();
5454
+ } catch (error) {
5455
+ this.#onPersistentStorageError?.(error);
5456
+ } finally {
5457
+ this.#uploadsRemovedWhileListing = null;
5458
+ }
5459
+ }
5208
5460
  async #getUploadRecord(id) {
5209
5461
  const existing = this.#uploads.get(id);
5210
5462
  if (existing) return existing;
5211
5463
  if (!this.#uploadsConfig) return null;
5464
+ await this.#restoreStoredUploads();
5465
+ const restored = this.#uploads.get(id);
5466
+ if (restored) return restored;
5467
+ await this.#waitForUploadRemoval(id);
5212
5468
  const loaded = await this.#uploadsConfig.adapter.load(this.sessionKey, id);
5213
5469
  const current = this.#uploads.get(id);
5214
5470
  if (current) return current;
@@ -5218,8 +5474,17 @@ var SessionOfflineCoordinator = class {
5218
5474
  }
5219
5475
  return loaded;
5220
5476
  }
5477
+ async #waitForUploadRemoval(id) {
5478
+ let removal = this.#uploadRemovals.get(id);
5479
+ while (removal) {
5480
+ await removal;
5481
+ removal = this.#uploadRemovals.get(id);
5482
+ }
5483
+ }
5221
5484
  async #saveUploadRecord(record) {
5222
5485
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
5486
+ const removal = this.#uploadRemovals.get(record.id);
5487
+ if (removal) await removal;
5223
5488
  this.#uploads.set(record.id, record);
5224
5489
  await this.#uploadsConfig.adapter.save(this.sessionKey, record.id, record);
5225
5490
  this.#syncUploadsState();
@@ -5295,7 +5560,11 @@ var SessionOfflineCoordinator = class {
5295
5560
  const expiredIdSet = new Set(expiredIds);
5296
5561
  if (expiredIdSet.size > 0) {
5297
5562
  for (const id of expiredIdSet) this.#uploads.delete(id);
5298
- await Promise.all(expiredIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
5563
+ try {
5564
+ await Promise.all(expiredIds.map((id) => this.#removeStoredUpload(uploadsConfig, id)));
5565
+ } finally {
5566
+ this.#publishUploadsRemoved(expiredIds);
5567
+ }
5299
5568
  didChange = true;
5300
5569
  }
5301
5570
  if (token !== this.#uploadRetentionToken || this.#disposed) return;
@@ -5316,7 +5585,7 @@ var SessionOfflineCoordinator = class {
5316
5585
  this.#publishSnapshot();
5317
5586
  }
5318
5587
  #buildNextUploadRecord(current, args) {
5319
- return {
5588
+ const nextRecord = {
5320
5589
  ...current,
5321
5590
  state: args.state,
5322
5591
  updatedAt: Date.now(),
@@ -5324,6 +5593,8 @@ var SessionOfflineCoordinator = class {
5324
5593
  ...args.progress !== void 0 ? { progress: args.progress } : {},
5325
5594
  ...args.lastError !== void 0 ? { lastError: args.lastError } : {}
5326
5595
  };
5596
+ if (args.state === "uploaded") delete nextRecord.lastError;
5597
+ return nextRecord;
5327
5598
  }
5328
5599
  async #updateUploadState(args) {
5329
5600
  const current = await this.#getUploadRecord(args.id);
@@ -5335,9 +5606,13 @@ var SessionOfflineCoordinator = class {
5335
5606
  } else await this.#saveUploadRecord(nextRecord);
5336
5607
  return nextRecord;
5337
5608
  }
5338
- async #ensureUploadResolved(id) {
5609
+ async #ensureUploadResolved(id, forReplay = false) {
5339
5610
  const existingRecord = await this.#getUploadRecord(id);
5340
- if (!existingRecord) throw new Error(`Unknown offline upload "${id}"`);
5611
+ if (!existingRecord) {
5612
+ const releasedRef = this.#releasedUploadRefs.get(id);
5613
+ if (releasedRef !== void 0) return releasedRef;
5614
+ throw new Error(`Unknown offline upload "${id}"`);
5615
+ }
5341
5616
  if (existingRecord.state === "uploaded" && existingRecord.resolvedRef !== void 0) return existingRecord.resolvedRef;
5342
5617
  const existingPromise = this.#uploadPromisesById.get(id);
5343
5618
  if (existingPromise) return existingPromise;
@@ -5345,7 +5620,11 @@ var SessionOfflineCoordinator = class {
5345
5620
  const uploadsConfig = this.#uploadsConfig;
5346
5621
  const uploadPromise = this.#uploadQueue.resultifyAdd(async () => {
5347
5622
  const queuedRecord = await this.#getUploadRecord(id);
5348
- if (!queuedRecord) throw new Error(`Unknown offline upload "${id}"`);
5623
+ if (!queuedRecord) {
5624
+ const releasedRef = this.#releasedUploadRefs.get(id);
5625
+ if (releasedRef !== void 0) return releasedRef;
5626
+ throw new Error(`Unknown offline upload "${id}"`);
5627
+ }
5349
5628
  if (queuedRecord.state === "uploaded" && queuedRecord.resolvedRef !== void 0) return queuedRecord.resolvedRef;
5350
5629
  const file = queuedRecord.file;
5351
5630
  await this.#updateUploadState({
@@ -5386,7 +5665,7 @@ var SessionOfflineCoordinator = class {
5386
5665
  } catch (error) {
5387
5666
  await this.#updateUploadState({
5388
5667
  id,
5389
- state: "failed",
5668
+ state: forReplay ? "pending" : "failed",
5390
5669
  lastError: { message: error instanceof Error ? error.message : "Upload failed" }
5391
5670
  });
5392
5671
  throw error;
@@ -5396,20 +5675,67 @@ var SessionOfflineCoordinator = class {
5396
5675
  return result.value;
5397
5676
  }).finally(() => {
5398
5677
  this.#uploadPromisesById.delete(id);
5678
+ if (this.#pendingUploadReleases.has(id)) this.#releasePendingUploads();
5399
5679
  });
5400
5680
  this.#uploadPromisesById.set(id, uploadPromise);
5401
5681
  return uploadPromise;
5402
5682
  }
5403
5683
  async #cleanupUnusedMutationUploads() {
5684
+ await this.#removeUploads([...this.#uploads.values()].filter((upload) => upload.source === "mutation" && (upload.storeName !== void 0 ? this.#registrations.has(upload.storeName) : [...this.#registrations.keys()].some((storeName) => upload.id.startsWith(`${storeName}:`)))).map((upload) => upload.id).filter((id) => !this.#referencedUploadIds.has(id) && !this.#uploadPromisesById.has(id) && !this.#stagedMutationUploadIds.has(id)));
5685
+ }
5686
+ async #removeUploads(ids) {
5404
5687
  const uploadsConfig = this.#uploadsConfig;
5405
- if (!uploadsConfig) return;
5406
- const removableIds = [...this.#uploads.values()].filter((upload) => upload.source === "mutation" && (upload.storeName !== void 0 ? this.#registrations.has(upload.storeName) : [...this.#registrations.keys()].some((storeName) => upload.id.startsWith(`${storeName}:`)))).map((upload) => upload.id).filter((id) => !this.#referencedUploadIds.has(id) && !this.#uploadPromisesById.has(id));
5407
- if (removableIds.length === 0) return;
5408
- for (const id of removableIds) this.#uploads.delete(id);
5409
- await Promise.all(removableIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
5688
+ if (!uploadsConfig || ids.length === 0) return;
5689
+ try {
5690
+ await Promise.all(ids.map((id) => {
5691
+ this.#uploads.delete(id);
5692
+ return this.#removeStoredUpload(uploadsConfig, id);
5693
+ }));
5694
+ } finally {
5695
+ this.#publishUploadsRemoved(ids);
5696
+ }
5410
5697
  this.#syncUploadsState();
5411
5698
  this.#refreshUploadRetention();
5412
5699
  }
5700
+ /** Tells the other tabs that this tab deleted these stored uploads. */
5701
+ #publishUploadsRemoved(ids) {
5702
+ if (this.#disposed || ids.length === 0 || !this.hasOtherTabs()) return;
5703
+ const releasedRefs = [];
5704
+ for (const id of ids) {
5705
+ const ref = this.#releasedUploadRefs.get(id);
5706
+ if (ref !== void 0) releasedRefs.push([id, ref]);
5707
+ }
5708
+ this.#browserTabs.coordinator.publish({
5709
+ kind: "offline-uploads-removed",
5710
+ ids: [...ids],
5711
+ releasedRefs
5712
+ });
5713
+ }
5714
+ #applyRemoteUploadsRemoved(ids, releasedRefs) {
5715
+ const removedIds = new Set(ids);
5716
+ for (const id of removedIds) {
5717
+ this.#releasedUploadRefs.delete(id);
5718
+ this.#pendingUploadReleases.delete(id);
5719
+ this.#uploads.delete(id);
5720
+ this.#uploadsRemovedWhileListing?.add(id);
5721
+ }
5722
+ for (const [id, ref] of releasedRefs) this.#releasedUploadRefs.set(id, ref);
5723
+ const { uploads } = this.store.state;
5724
+ if (uploads.some((upload) => removedIds.has(upload.id))) this.store.setPartialState({ uploads: uploads.filter((upload) => !removedIds.has(upload.id)) }, { action: "offline-session-uploads" });
5725
+ }
5726
+ /**
5727
+ * Removes an upload from the adapter, tracking the removal so a save or
5728
+ * load of the same id waits for it.
5729
+ */
5730
+ #removeStoredUpload(uploadsConfig, id) {
5731
+ const removal = uploadsConfig.adapter.remove(this.sessionKey, id);
5732
+ const settled = removal.then(() => {}, () => {});
5733
+ this.#uploadRemovals.set(id, settled);
5734
+ settled.then(() => {
5735
+ if (this.#uploadRemovals.get(id) === settled) this.#uploadRemovals.delete(id);
5736
+ });
5737
+ return removal;
5738
+ }
5413
5739
  /**
5414
5740
  * The session-wide lists: this tab's own stores, plus what other tabs
5415
5741
  * reported for the stores this tab has not attached.
@@ -5492,6 +5818,7 @@ var SessionOfflineCoordinator = class {
5492
5818
  }
5493
5819
  if (publish) this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
5494
5820
  this.#referencedUploadIds = referencedUploadIds;
5821
+ for (const id of this.#stagedMutationUploadIds) if (referencedUploadIds.has(id)) this.#stagedMutationUploadIds.delete(id);
5495
5822
  if (!arraysEqual(this.#protectedKeys, nextProtectedKeys)) {
5496
5823
  this.#protectedKeys = nextProtectedKeys;
5497
5824
  setSessionProtectedKeysSnapshot(this.sessionKey, nextProtectedKeys);
@@ -5503,7 +5830,10 @@ var SessionOfflineCoordinator = class {
5503
5830
  }, { action: "offline-session-aggregate" });
5504
5831
  this.#persistSessionSnapshot();
5505
5832
  if (publish) this.#publishSnapshot();
5506
- if (publish && this.#uploadsConfig && this.#uploads.size > 0 && this.#storeContributions.size === this.#registrations.size) this.#cleanupUnusedMutationUploads();
5833
+ if (publish && this.#uploadsConfig && this.#storeContributions.size === this.#registrations.size) {
5834
+ if (this.#uploads.size > 0) this.#cleanupUnusedMutationUploads();
5835
+ this.#releasePendingUploads();
5836
+ }
5507
5837
  }
5508
5838
  #stampLocalStatus(status) {
5509
5839
  return {
@@ -5935,12 +6265,26 @@ function useOfflineStoreEntities(args) {
5935
6265
  return useMemo(() => entities.map(stripInternalEntityPayload), [entities]);
5936
6266
  }
5937
6267
  /**
5938
- * React hook returning offline status for a session or inactive scope.
6268
+ * React hook returning the offline state of one item of a store, or `null`
6269
+ * when the item has no offline work. It reads the item through the keyed
6270
+ * lookup shared by all readers and keeps the previous result while the state
6271
+ * is unchanged, so a component re-renders only when its own item changes.
5939
6272
  */
5940
- function useOfflineStoreStatus(args) {
5941
- const coordinator = useSessionOfflineCoordinator(resolveOfflineSessionScope(args.sessionKey, args.inactiveScope), false);
5942
- const statusSelector = useCallback((state) => state.status, []);
5943
- return coordinator.store.useSelector(statusSelector);
6273
+ function useOfflineStoreItemState(sessionKey, inactiveScope, storeName, itemKey) {
6274
+ 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]);
6276
+ return coordinator.store.useSelector(itemStateSelector, { equalityFn: deepEqual });
6277
+ }
6278
+ /**
6279
+ * React hook returning whether a session or inactive scope is in offline mode.
6280
+ * Only this flag is selected, so the other status changes (e.g. `updatedAt`)
6281
+ * don't re-render the store hooks using it.
6282
+ */
6283
+ function useOfflineStoreIsOfflineMode(args) {
6284
+ return useSessionOfflineCoordinator(resolveOfflineSessionScope(args.sessionKey, args.inactiveScope), false).store.useSelector(selectIsOfflineMode);
6285
+ }
6286
+ function selectIsOfflineMode(state) {
6287
+ return state.status.isOfflineMode;
5944
6288
  }
5945
6289
  /**
5946
6290
  * React hook returning offline conflict/retry resolutions for a specific store in a session.
@@ -6025,6 +6369,16 @@ function deserializeCompactOfflineEntityRef(value) {
6025
6369
  entityKind: fromCompactOfflineEntityKind(compactKind)
6026
6370
  };
6027
6371
  }
6372
+ /**
6373
+ * An entity with several queued mutations reports the most urgent state among
6374
+ * them, so it shows `syncing` while any of its mutations is being sent.
6375
+ */
6376
+ const entitySyncStatePriority = {
6377
+ pending: 0,
6378
+ syncing: 1,
6379
+ "needs-confirmation": 2,
6380
+ "resolution-required": 3
6381
+ };
6028
6382
  function toCompactOfflineEntitySyncState(state) {
6029
6383
  switch (state) {
6030
6384
  case "pending": return "p";
@@ -6451,9 +6805,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6451
6805
  else resolutions.delete(resolutionId);
6452
6806
  });
6453
6807
  },
6454
- onRemoteWorkDiscarded: (discardedWork, removedTempEntityKeys) => {
6808
+ onRemoteWorkDiscarded: (discardedWork, removedEntityKeys) => {
6455
6809
  applyRecordChangeFromAnotherTab(() => {
6456
- revalidateDiscardedWork(discardedWork, new Set(removedTempEntityKeys));
6810
+ revalidateDiscardedWork(discardedWork, new Set(removedEntityKeys));
6457
6811
  });
6458
6812
  },
6459
6813
  onRemoteTempReconciled: (tempId, finalPayload) => {
@@ -6480,6 +6834,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6480
6834
  entryIdsFromAnotherTab.clear();
6481
6835
  resolutions.clear();
6482
6836
  for (const entry of loadedQueueEntries.values()) queueEntries.set(entry.id, entry);
6837
+ const droppedResolutions = [];
6483
6838
  for (const resolution of loadedResolutionEntries.values()) {
6484
6839
  if (!rc_parse(resolution, offlineResolutionRecordSchema).ok) {
6485
6840
  current.resolutionNamespace.remove(resolution.id);
@@ -6487,6 +6842,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6487
6842
  }
6488
6843
  if (!operations[resolution.operation]) {
6489
6844
  current.resolutionNamespace.remove(resolution.id);
6845
+ droppedResolutions.push(resolution);
6490
6846
  continue;
6491
6847
  }
6492
6848
  resolutions.set(resolution.id, resolution);
@@ -6494,6 +6850,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6494
6850
  nextQueueOrder = getNextQueueOrder(loadedQueueEntries.values());
6495
6851
  hydratedSessionKey = current.sessionKey;
6496
6852
  refreshDerivedState(current);
6853
+ deleteOrphanedDependencyUploads(current, droppedResolutions);
6497
6854
  })().finally(() => {
6498
6855
  hydratedPromise = null;
6499
6856
  });
@@ -6672,7 +7029,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6672
7029
  ...createEntityBase(ref),
6673
7030
  kind: reduceOfflineEntityKind(existing?.kind, operationKind),
6674
7031
  pendingMutations: (existing?.pendingMutations ?? 0) + 1,
6675
- syncState: existing?.syncState === "needs-confirmation" ? existing.syncState : entry.syncState,
7032
+ syncState: existing && entitySyncStatePriority[existing.syncState] > entitySyncStatePriority[entry.syncState] ? existing.syncState : entry.syncState,
6676
7033
  requiresResolution: existing?.requiresResolution ?? false,
6677
7034
  blockedByResolutionIds,
6678
7035
  childResolutionIds,
@@ -6954,11 +7311,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6954
7311
  };
6955
7312
  }
6956
7313
  async function buildOperationExecuteContext(args) {
6957
- const [fileEntries, resolvedRefsById] = await Promise.all([Promise.all(Object.entries(args.entry.attachedUploadIds ?? {}).map(async ([uploadId, storedUploadId]) => {
7314
+ const fileEntries = await Promise.all(Object.entries(args.entry.attachedUploadIds ?? {}).map(async ([uploadId, storedUploadId]) => {
6958
7315
  const file = await args.current.session.loadUpload(storedUploadId);
6959
7316
  if (!file) throw new Error(`Missing offline upload "${storedUploadId}"`);
6960
7317
  return [uploadId, file];
6961
- })), args.current.session.resolveUploadIds(args.entry.dependencyUploadIds ?? [])]);
7318
+ }));
6962
7319
  const filesById = Object.fromEntries(fileEntries);
6963
7320
  return {
6964
7321
  ...buildOperationBaseContext({
@@ -6968,7 +7325,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6968
7325
  }),
6969
7326
  uploads: {
6970
7327
  filesById,
6971
- resolvedRefsById
7328
+ resolvedRefsById: args.resolvedRefsById
6972
7329
  }
6973
7330
  };
6974
7331
  }
@@ -7142,6 +7499,21 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7142
7499
  session.session.publishResolutionChange(storeName, resolutionId, null);
7143
7500
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
7144
7501
  }
7502
+ /**
7503
+ * Deletes the staged uploads that work items depended on, after those items
7504
+ * left the queue for good (replayed, discarded, superseded, cancelled).
7505
+ *
7506
+ * Call it after `refreshDerivedState`, which reports the references that
7507
+ * remain: the session keeps every upload a queue entry or resolution record
7508
+ * of any store still needs. Attached uploads need no call, the session drops
7509
+ * them as soon as nothing references them.
7510
+ */
7511
+ async function deleteOrphanedDependencyUploads(current, removedWorkItems) {
7512
+ if (!isActiveSessionState(current)) return;
7513
+ const uploadIds = removedWorkItems.flatMap((workItem) => workItem.dependencyUploadIds ?? []);
7514
+ if (uploadIds.length === 0) return;
7515
+ await current.session.deleteUnreferencedUploads(uploadIds);
7516
+ }
7145
7517
  function collectTempCreateDescendants(args) {
7146
7518
  const sourcesByEntityKey = new Map([[args.parentEntityKey, {
7147
7519
  entityKey: args.parentEntityKey,
@@ -7208,6 +7580,33 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7208
7580
  pendingEntity: void 0
7209
7581
  });
7210
7582
  }
7583
+ /**
7584
+ * Removes the items a discarded `create` without temp entity (the app
7585
+ * generated the id on the client) added to the store, like the rollback of a
7586
+ * temp create, and adds their keys to `removedEntityKeys`. Like removed temp
7587
+ * entities, they are not refetched: the server most likely never got them.
7588
+ * If an earlier replay attempt did create one, the store's list
7589
+ * revalidation brings it back.
7590
+ */
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;
7595
+ const payload = getPayloadForEntityRef({
7596
+ operationName: workItem.operation,
7597
+ input: workItem.input,
7598
+ entityKey: ref.entityKey
7599
+ });
7600
+ if (payload === void 0) continue;
7601
+ storeAdapter.rollbackPendingEntity?.({
7602
+ operationName: workItem.operation,
7603
+ input: workItem.input,
7604
+ tempId: payload,
7605
+ pendingEntity: void 0
7606
+ });
7607
+ removedEntityKeys.add(ref.entityKey);
7608
+ }
7609
+ }
7211
7610
  async function promoteBlockedTempCreateDescendants(args) {
7212
7611
  const descendantQueueEntries = /* @__PURE__ */ new Map();
7213
7612
  for (const entityKey of getTempLifecycleEntityKeys(args.parentEntry)) {
@@ -7223,6 +7622,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7223
7622
  }
7224
7623
  }
7225
7624
  async function persistManualResolutionChain(args) {
7625
+ await args.current.session.markUploadsFailed(args.parentEntry.dependencyUploadIds ?? []);
7226
7626
  await persistResolution(args.parentResolution, args.current, true);
7227
7627
  await removeEntry(args.parentEntry.id, args.current, true);
7228
7628
  await promoteBlockedTempCreateDescendants({
@@ -7239,8 +7639,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7239
7639
  await removeResolution(args.resolution.id, args.current, true);
7240
7640
  const parentEntityKeys = getTempLifecycleEntityKeys(args.resolution);
7241
7641
  if (parentEntityKeys.length === 0) {
7642
+ const removedEntityKeys = /* @__PURE__ */ new Set();
7643
+ rollbackClientIdCreatedItems(args.resolution, removedEntityKeys);
7242
7644
  refreshDerivedState(args.current);
7243
- revalidateDiscardedWorkInEveryTab(args.current, [args.resolution], /* @__PURE__ */ new Set());
7645
+ revalidateDiscardedWorkInEveryTab(args.current, [args.resolution], removedEntityKeys);
7646
+ await deleteOrphanedDependencyUploads(args.current, [args.resolution]);
7244
7647
  return;
7245
7648
  }
7246
7649
  const descendantQueueEntries = /* @__PURE__ */ new Map();
@@ -7255,38 +7658,42 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7255
7658
  }
7256
7659
  for (const queueEntry of descendantQueueEntries.values()) await removeEntry(queueEntry.id, args.current, true);
7257
7660
  for (const resolution of descendantResolutions.values()) await removeResolution(resolution.id, args.current, true);
7258
- for (const queueEntry of descendantQueueEntries.values()) rollbackTempCreatePendingEntity(queueEntry);
7259
- for (const resolution of descendantResolutions.values()) rollbackTempCreatePendingEntity(resolution);
7661
+ const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7662
+ const removedEntityKeys = new Set(parentEntityKeys);
7663
+ for (const workItem of discardedWork) {
7664
+ rollbackTempCreatePendingEntity(workItem);
7665
+ rollbackClientIdCreatedItems(workItem, removedEntityKeys);
7666
+ for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedEntityKeys.add(entityKey);
7667
+ }
7260
7668
  rollbackTempCreatePendingEntity(args.resolution);
7261
7669
  refreshDerivedState(args.current);
7262
- const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7263
- const removedTempEntityKeys = new Set(parentEntityKeys);
7264
- for (const workItem of discardedWork) for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedTempEntityKeys.add(entityKey);
7265
- revalidateDiscardedWorkInEveryTab(args.current, discardedWork, removedTempEntityKeys);
7670
+ revalidateDiscardedWorkInEveryTab(args.current, discardedWork, removedEntityKeys);
7671
+ await deleteOrphanedDependencyUploads(args.current, [args.resolution, ...discardedWork]);
7266
7672
  }
7267
7673
  /**
7268
7674
  * {@link revalidateDiscardedWork} in this tab and in the other tabs with the
7269
7675
  * store: each one may show the discarded optimistic changes.
7270
7676
  */
7271
- function revalidateDiscardedWorkInEveryTab(current, discardedWork, removedTempEntityKeys) {
7272
- revalidateDiscardedWork(discardedWork, removedTempEntityKeys);
7677
+ function revalidateDiscardedWorkInEveryTab(current, discardedWork, removedEntityKeys) {
7678
+ revalidateDiscardedWork(discardedWork, removedEntityKeys);
7273
7679
  if (!discardedWork.some((workItem) => workItem.entityRefs.length > 0)) return;
7274
7680
  current.session.publishWorkDiscarded(storeName, discardedWork.map(({ operation, input, entityRefs }) => ({
7275
7681
  operation,
7276
7682
  input,
7277
7683
  entityRefs
7278
- })), [...removedTempEntityKeys]);
7684
+ })), [...removedEntityKeys]);
7279
7685
  }
7280
7686
  /**
7281
7687
  * Refetches the entities discarded queued work referenced (its optimistic
7282
- * changes cannot be rolled back locally), except the removed temp entities
7283
- * and the entities other changes still wait for a decision on: a refetch
7688
+ * changes cannot be rolled back locally), except the entities the discard
7689
+ * removed (temp entities and items of discarded creations) and the
7690
+ * entities other changes still wait for a decision on: a refetch
7284
7691
  * would replace those changes. The recovery revalidation refetches them
7285
7692
  * once the last one is handled.
7286
7693
  */
7287
- function revalidateDiscardedWork(discardedWork, removedTempEntityKeys) {
7694
+ function revalidateDiscardedWork(discardedWork, removedEntityKeys) {
7288
7695
  const entities = [];
7289
- const skippedEntityKeys = new Set(removedTempEntityKeys);
7696
+ const skippedEntityKeys = new Set(removedEntityKeys);
7290
7697
  for (const resolution of resolutions.values()) for (const ref of resolution.entityRefs) skippedEntityKeys.add(ref.entityKey);
7291
7698
  for (const workItem of discardedWork) for (const ref of workItem.entityRefs) {
7292
7699
  if (skippedEntityKeys.has(ref.entityKey)) continue;
@@ -7360,6 +7767,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7360
7767
  input: validatedInput
7361
7768
  }),
7362
7769
  upload: args.upload,
7770
+ attachedUploadIds: args.attachedUploadIds,
7363
7771
  tempIds: args.tempIds,
7364
7772
  entityRefs: args.entityRefs
7365
7773
  };
@@ -7383,14 +7791,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7383
7791
  return result;
7384
7792
  }
7385
7793
  async function planPreparedMutation(args) {
7386
- const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue, replacedResolutionId } = args;
7794
+ const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, attachedUploadIds, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue, replacedResolutionId } = args;
7387
7795
  const tempEntity = operation.tempEntity;
7388
7796
  const tempEntities = operation.tempEntities;
7389
7797
  if (operation.accumulation && operation.supersedes) throw new Error(`Offline operation "${operationName}" cannot configure accumulation and supersedes together`);
7390
7798
  if (tempEntity && tempEntities) throw new Error(`Offline operation "${operationName}" cannot configure tempEntity and tempEntities together`);
7391
7799
  if (storeType === "document" && (tempEntity || tempEntities)) throw new Error(`Document offline operation "${operationName}" does not support tempEntity or tempEntities`);
7392
7800
  if ((tempEntity || tempEntities) && "onSuccessExecute" in operation) throw new Error(`Offline operation "${operationName}" cannot configure onSuccessExecute when tempEntity or tempEntities is present`);
7393
- if (operation.accumulation && upload !== void 0) throw new Error(`Offline operation "${operationName}" cannot configure direct uploads together with accumulation`);
7801
+ if (operation.accumulation && (upload !== void 0 || attachedUploadIds !== void 0)) throw new Error(`Offline operation "${operationName}" cannot configure direct uploads together with accumulation`);
7394
7802
  const rawEntityRefs = getOperationRawEntityRefs(operation, operationName, validatedInput);
7395
7803
  const resolvedEntityRefs = resolveNormalizedRefs(rawEntityRefs);
7396
7804
  const hasTempLifecycle = tempEntity !== void 0 || tempEntities !== void 0;
@@ -7486,6 +7894,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7486
7894
  queueOrder,
7487
7895
  entityRefs,
7488
7896
  attachedUploads: upload,
7897
+ attachedUploadIds,
7489
7898
  dependencyUploadIds: dependencyUploadIds.length > 0 ? dependencyUploadIds : void 0,
7490
7899
  tempIds
7491
7900
  });
@@ -7590,6 +7999,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7590
7999
  throw error;
7591
8000
  }
7592
8001
  refreshDerivedState(current);
8002
+ if (plannedMutation.removedEntries.length > 0) await deleteOrphanedDependencyUploads(current, plannedMutation.removedEntries);
7593
8003
  await ensureReplayScheduled();
7594
8004
  }
7595
8005
  async function ensureReplayScheduled() {
@@ -7692,6 +8102,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7692
8102
  const operation = operations[nextEntry.operation];
7693
8103
  if (!operation) {
7694
8104
  await removeEntry(nextEntry.id, current);
8105
+ deleteOrphanedDependencyUploads(current, [nextEntry]);
7695
8106
  continue;
7696
8107
  }
7697
8108
  const shouldCheckSkipBeforeRetry = nextEntry.syncState === "needs-confirmation";
@@ -7708,6 +8119,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7708
8119
  lastAttemptAt: Date.now()
7709
8120
  };
7710
8121
  await persistEntry(entryToUse, current);
8122
+ let failedUploadId;
7711
8123
  try {
7712
8124
  const replayCheckCtx = Boolean(shouldCheckSkipBeforeRetry && operation.shouldSkipSync || conflictHandling) ? {
7713
8125
  ...replayCheckBaseCtx,
@@ -7717,6 +8129,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7717
8129
  if (!replayCheckCtx) throw new Error("Replay check context was not prepared");
7718
8130
  if (await operation.shouldSkipSync(replayCheckCtx)) {
7719
8131
  await removeEntry(entryToUse.id, current);
8132
+ deleteOrphanedDependencyUploads(current, [entryToUse]);
7720
8133
  continue;
7721
8134
  }
7722
8135
  }
@@ -7742,9 +8155,15 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7742
8155
  });
7743
8156
  continue;
7744
8157
  }
8158
+ const dependencyUploads = await current.session.resolveReplayUploadIds(entryToUse.dependencyUploadIds ?? []);
8159
+ if (dependencyUploads.failedUploadId !== void 0) {
8160
+ failedUploadId = dependencyUploads.failedUploadId;
8161
+ throw dependencyUploads.error;
8162
+ }
7745
8163
  const executeContext = __LEGIT_CAST__(await buildOperationExecuteContext({
7746
8164
  current,
7747
- entry: entryToUse
8165
+ entry: entryToUse,
8166
+ resolvedRefsById: dependencyUploads.refs
7748
8167
  }));
7749
8168
  const result = await operation.execute(executeContext);
7750
8169
  if (entryToUse.tempIds) await reconcileTempEntitiesFromResult({
@@ -7763,20 +8182,18 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7763
8182
  });
7764
8183
  if (isPromise(successfulExecuteSync)) await successfulExecuteSync;
7765
8184
  refreshDerivedState(current);
8185
+ deleteOrphanedDependencyUploads(current, [entryToUse]);
7766
8186
  } catch (error) {
7767
8187
  const lastError = { message: unknownToError(error).message };
7768
- const classification = await current.session.classifyFailure(error, {
7769
- phase: "sync",
7770
- storeType,
7771
- operationName: entryToUse.operation,
7772
- sessionKey: current.sessionKey
7773
- });
7774
- const allowReplayRetry = classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, {
8188
+ const failureCtx = {
7775
8189
  phase: "sync",
7776
8190
  storeType,
7777
8191
  operationName: entryToUse.operation,
7778
8192
  sessionKey: current.sessionKey
7779
- }) : false;
8193
+ };
8194
+ if (failedUploadId !== void 0) failureCtx.uploadId = failedUploadId;
8195
+ const classification = await current.session.classifyFailure(error, failureCtx);
8196
+ const allowReplayRetry = classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, failureCtx) : false;
7780
8197
  if (classification !== "ignore" || current.session.getStatus().isOfflineMode) {
7781
8198
  entryToUse = {
7782
8199
  ...entryToUse,
@@ -7802,7 +8219,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7802
8219
  lastError,
7803
8220
  allowReplayRetry
7804
8221
  };
7805
- if (allowReplayRetry && nextFailures >= replayRetryMaxFailures) {
8222
+ if (allowReplayRetry && nextFailures >= replayRetryMaxFailures || failedUploadId !== void 0 && !allowReplayRetry) {
7806
8223
  await persistManualResolutionChain({
7807
8224
  current,
7808
8225
  parentEntry: entryToUse,
@@ -7861,6 +8278,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7861
8278
  if (!current) return [];
7862
8279
  return current.session.getEntities().filter((entity) => entity.storeName === storeName);
7863
8280
  }
8281
+ function getItemOfflineState(itemKey) {
8282
+ const current = ensureActiveSession();
8283
+ if (!current) return null;
8284
+ return toItemOfflineState(getOfflineStoreEntityLookup(current.session.store.state.entities, storeName).get(itemKey));
8285
+ }
7864
8286
  function getOfflineResolutions() {
7865
8287
  return buildDerivedResolutionRecords();
7866
8288
  }
@@ -7874,6 +8296,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7874
8296
  const operation = operations[operationName];
7875
8297
  if (!operation) {
7876
8298
  await removeResolution(resolutionId, current);
8299
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
7877
8300
  return;
7878
8301
  }
7879
8302
  if (isPersistedResolutionBlocked(resolutionRecord)) throw new Error("Cannot resolve a blocked offline resolution before its blocking dependencies are cleared");
@@ -7923,6 +8346,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7923
8346
  })
7924
8347
  });
7925
8348
  refreshDerivedState(current);
8349
+ await deleteOrphanedDependencyUploads(current, nextEntries.flatMap((nextEntry) => nextEntry.entry ? [] : [nextEntry.resolution]));
7926
8350
  await ensureReplayScheduled();
7927
8351
  return;
7928
8352
  }
@@ -7939,10 +8363,12 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7939
8363
  await queuePreparedMutations(prepareMutationWithSession(current, {
7940
8364
  operation: operationName,
7941
8365
  input: resolutionAction?.input,
8366
+ attachedUploadIds: resolutionRecord.attachedUploadIds,
7942
8367
  tempIds: resolutionRecord.tempIds,
7943
8368
  entityRefs: resolutionRecord.entityRefs
7944
8369
  }), resolutionId);
7945
8370
  await removeResolution(resolutionId, current);
8371
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
7946
8372
  return;
7947
8373
  }
7948
8374
  if (action === "commit") {
@@ -7956,6 +8382,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7956
8382
  result: committedResult
7957
8383
  });
7958
8384
  await removeResolution(resolutionId, current);
8385
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
7959
8386
  return;
7960
8387
  }
7961
8388
  throw new Error("Invalid offline resolution action");
@@ -8007,6 +8434,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8007
8434
  prepareForMutation,
8008
8435
  queueMutation,
8009
8436
  getOfflineEntities,
8437
+ getItemOfflineState,
8010
8438
  getOfflineResolutions,
8011
8439
  parseOfflineResolutionConflict: parseConflictPayloadForResolution,
8012
8440
  resolveOfflineResolution,
@@ -9866,34 +10294,6 @@ function useRegisterActiveKeys(keys, registerActiveKeys, touchKeys) {
9866
10294
  * ```
9867
10295
  */
9868
10296
  const IsOffScreenContext = createContext(false);
9869
- //#endregion
9870
- //#region src/persistentStorage/offline/entityMetadata.ts
9871
- function createOfflineEntityLookup(entities) {
9872
- const entitiesByKey = /* @__PURE__ */ new Map();
9873
- for (const entity of entities) entitiesByKey.set(entity.entityKey, entity);
9874
- return entitiesByKey;
9875
- }
9876
- function getIsPendingOfflineSync(entity) {
9877
- return !!entity && !entity.requiresResolution;
9878
- }
9879
- function hasPendingOfflineSync(entitiesByKey, entityKeys) {
9880
- for (const entityKey of entityKeys) if (getIsPendingOfflineSync(entitiesByKey.get(entityKey))) return true;
9881
- return false;
9882
- }
9883
- function shouldApplyOfflineOverlay(entity, overlay) {
9884
- return !!entity && (!entity.requiresResolution || entity.blockedResolutionCount > 0 || entity.childResolutionCount > 0 || typeof overlay === "object" && overlay !== null && "keepVisibleWhileResolutionRequired" in overlay && overlay.keepVisibleWhileResolutionRequired === true);
9885
- }
9886
- /**
9887
- * Batch-filters offline overlays to only include entries with a pending sync
9888
- * (entity exists and does not require resolution). Use this instead of calling
9889
- * {@link getActiveOfflineOverlay} per item when all active overlays are needed
9890
- * at once.
9891
- */
9892
- function filterActiveOfflineOverlays(entitiesByKey, overlays) {
9893
- const result = {};
9894
- for (const [entityKey, overlay] of Object.entries(overlays)) if (shouldApplyOfflineOverlay(entitiesByKey.get(entityKey), overlay)) result[entityKey] = overlay;
9895
- return result;
9896
- }
9897
10297
  function observeAutomaticFetchStatus(state, signature, currentStatus) {
9898
10298
  if (currentStatus === "success") {
9899
10299
  state.delete(signature);
@@ -10639,7 +11039,7 @@ function createCollectionStore(storeOptions) {
10639
11039
  error: new AbortedStoreError()
10640
11040
  };
10641
11041
  let item = getItemFromStateOrPersistence(itemId, { materializeSyncState: true });
10642
- if (item?.error?.id === "offline") {
11042
+ if (isOfflineStoreError(item?.error)) {
10643
11043
  const hydratedItem = persistence?.readHydratedItem(itemId);
10644
11044
  if (hydratedItem?.data) {
10645
11045
  item = hydratedItem;
@@ -11127,6 +11527,8 @@ function createCollectionStore(storeOptions) {
11127
11527
  inactiveScope: id,
11128
11528
  storeName: resolvedPersistentStorageConfig ? id : void 0
11129
11529
  }),
11530
+ useItemOfflineState: (itemPayload) => useOfflineStoreItemState(getSessionKeyForRuntime(), id, resolvedPersistentStorageConfig ? id : void 0, itemPayload === false || itemPayload == null ? null : getItemKey(itemPayload)),
11531
+ getItemOfflineState: (itemPayload) => offlineController?.getItemOfflineState(getItemKey(itemPayload)) ?? null,
11130
11532
  useOfflineResolutions: () => useOfflineStoreResolutions({
11131
11533
  sessionKey: getSessionKeyForRuntime(),
11132
11534
  inactiveScope: id,
@@ -11532,7 +11934,6 @@ function createDocumentStore(storeOptions) {
11532
11934
  }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId, getStoreManagerAppVersion(storeManager));
11533
11935
  async function executeFetch(fetchCtx) {
11534
11936
  const currentStatus = store.state.status;
11535
- const wasLoadedBeforeFetch = currentStatus === "success";
11536
11937
  store.setPartialState({
11537
11938
  status: currentStatus === "success" ? "refetching" : "loading",
11538
11939
  error: null,
@@ -11542,7 +11943,7 @@ function createDocumentStore(storeOptions) {
11542
11943
  const result = await runOfflineAwareFetch(offlineController, () => fetchFn(fetchCtx.signal));
11543
11944
  if (!result.ok) {
11544
11945
  if (result.offline) {
11545
- store.setPartialState(wasLoadedBeforeFetch ? {
11946
+ store.setPartialState(store.state.data !== null ? {
11546
11947
  error: null,
11547
11948
  status: "success"
11548
11949
  } : {
@@ -14360,6 +14761,7 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14360
14761
  const { payload, limit, fields } = fetchPayload;
14361
14762
  const offset = !!offsetPagination && fetchPayload.type === "loadMore" && fetchPayload.offset > 0 ? Math.min(fetchPayload.offset, store.state.queries[queryKey]?.items.length ?? fetchPayload.offset) : fetchPayload.offset;
14362
14763
  const appendToExisting = !!offsetPagination && fetchPayload.type === "loadMore" && offset > 0;
14764
+ let failure = null;
14363
14765
  try {
14364
14766
  const useChunkedInvalidation = offsetPagination && !appendToExisting && limit > offsetPagination.maxInvalidationLimit;
14365
14767
  let allItems;
@@ -14380,7 +14782,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14380
14782
  signal: fetchCtx.signal,
14381
14783
  fields
14382
14784
  })).then((result) => {
14383
- if (!result.ok) throw result.offline ? offlineConnectivityError : result.error;
14785
+ if (!result.ok) {
14786
+ failure ??= result;
14787
+ throw result.offline ? offlineConnectivityError : result.error;
14788
+ }
14384
14789
  return result.data;
14385
14790
  })));
14386
14791
  const successResults = (await Promise.all(chunkResultPromises)).map((r) => r.unwrap());
@@ -14392,7 +14797,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14392
14797
  signal: fetchCtx.signal,
14393
14798
  fields
14394
14799
  }));
14395
- if (!fetchResult.ok) throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
14800
+ if (!fetchResult.ok) {
14801
+ failure = fetchResult;
14802
+ throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
14803
+ }
14396
14804
  const result = fetchResult.data;
14397
14805
  allItems = result.items;
14398
14806
  hasMore = result.hasMore;
@@ -14411,11 +14819,12 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14411
14819
  results.set(queryKey, false);
14412
14820
  return;
14413
14821
  }
14414
- const error = exception && typeof exception === "object" && "id" in exception && exception.id === "offline" ? offlineConnectivityError : normalizeStoreError(exception, errorNormalizer);
14822
+ const failedOffline = failure?.offline === true;
14823
+ const error = failedOffline ? offlineConnectivityError : normalizeStoreError(failure && !failure.offline ? failure.error : exception, errorNormalizer);
14415
14824
  store.produceState((draft) => {
14416
14825
  const query = draft.queries[queryKey];
14417
14826
  if (!query) return;
14418
- if (error === offlineConnectivityError && query.wasLoaded) {
14827
+ if (failedOffline && query.wasLoaded) {
14419
14828
  query.status = "success";
14420
14829
  query.error = null;
14421
14830
  } else {
@@ -14919,7 +15328,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
14919
15328
  hasMore: false
14920
15329
  };
14921
15330
  let query = getQueryStateByKey(queryKey);
14922
- if (query?.error?.id === "offline") {
15331
+ if (isOfflineStoreError(query?.error)) {
14923
15332
  const hydratedQuery = persistence?.readHydratedQuery(queryKey);
14924
15333
  if (hydratedQuery) {
14925
15334
  query = hydratedQuery;
@@ -15028,7 +15437,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
15028
15437
  error: new AbortedStoreError()
15029
15438
  };
15030
15439
  let itemState = readItemState(itemKey);
15031
- if (itemState?.itemQuery?.error?.id === "offline") {
15440
+ if (isOfflineStoreError(itemState?.itemQuery?.error)) {
15032
15441
  const hydratedItem = persistence?.readHydratedItem(itemKey);
15033
15442
  if (hydratedItem) {
15034
15443
  itemState = hydratedItem;
@@ -16265,7 +16674,7 @@ const cacheMissError = {
16265
16674
  id: "cache-miss",
16266
16675
  message: "Cache miss"
16267
16676
  };
16268
- function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, debouncePayload }, store, events, getItemKey, registerActiveItems, touchItems, scheduleAutomaticItemFetch, preloadItems, preloadItemsBeforePaint, readFallbackItemState, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays) {
16677
+ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, debouncePayload }, store, events, getItemKey, registerActiveItems, touchItems, scheduleAutomaticItemFetch, preloadItems, preloadItemsBeforePaint, readFallbackItemState, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays, isOfflineMode) {
16269
16678
  const isOffScreenFromContext = useContext(IsOffScreenContext);
16270
16679
  const queriesWithId = useMemo(() => {
16271
16680
  return items.map((itemProps) => {
@@ -16370,17 +16779,24 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16370
16779
  };
16371
16780
  }
16372
16781
  let status = itemQuery.status;
16782
+ let error = itemQuery.error;
16783
+ let hasMissingRequestedData = false;
16373
16784
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
16374
16785
  if (partialResources && Array.isArray(fields) && fields.length > 0 && (status === "success" || status === "refetching")) {
16375
16786
  if (getGenuinelyMissingRequestedFields(itemKey, {
16376
16787
  item: rawItemState,
16377
16788
  loadedFields
16378
- }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16789
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) {
16790
+ hasMissingRequestedData = true;
16791
+ status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16792
+ }
16379
16793
  } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
16380
16794
  const isIncomplete = !snapshotIsFullyLoaded(loadedFields, rawItemState, partialResources.inferFields) && !(itemsPendingFullInvalidation.has(itemKey) && hasCachedDataInState);
16381
16795
  const isStale = !isIncomplete && !snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, rawItemState, partialResources.inferFields, itemsPendingFullInvalidation);
16382
- if (isIncomplete) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16383
- else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
16796
+ if (isIncomplete) {
16797
+ hasMissingRequestedData = true;
16798
+ status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16799
+ } else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
16384
16800
  }
16385
16801
  if (partialResources && showPartialAsRefetching) {
16386
16802
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16391,12 +16807,20 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16391
16807
  }
16392
16808
  }
16393
16809
  if (partialResources && status === "refetching" && Array.isArray(fields) && fields.length > 0 && itemFieldInvalidationFields && !fields.some((f) => itemFieldInvalidationFields.includes(f))) status = "success";
16810
+ if (status === "refetching" && !hasMissingRequestedData && isOfflineMode && itemQuery.status === "success") {
16811
+ status = "success";
16812
+ loadingFields = void 0;
16813
+ }
16394
16814
  if (!returnRefetchingStatus && status === "refetching") status = "success";
16395
16815
  const shouldHideDataWhileLoading = status === "loading" && partialResources;
16816
+ if (hasMissingRequestedData && itemQuery.status === "success" && isOfflineMode) {
16817
+ status = "error";
16818
+ error = offlineConnectivityError;
16819
+ }
16396
16820
  return {
16397
16821
  itemStateKey: itemKey,
16398
16822
  status,
16399
- error: itemQuery.error,
16823
+ error,
16400
16824
  isLoading: status === "loading",
16401
16825
  ...loadingFields ? { loadingFields } : {},
16402
16826
  data: shouldHideDataWhileLoading ? selector ? selector(null, resolvedItemPayload) : __LEGIT_CAST__(null) : data,
@@ -16408,6 +16832,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16408
16832
  }, [
16409
16833
  activeOfflineOverlays,
16410
16834
  getUnresolvedPendingInvalidationFields,
16835
+ isOfflineMode,
16411
16836
  itemsPendingFullInvalidation,
16412
16837
  loadFromStateOnly,
16413
16838
  offlineEntitiesByKey,
@@ -16617,7 +17042,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16617
17042
  const hasMissingFields = missingFields.length > 0;
16618
17043
  const hasStaleInvalidatedFields = staleInvalidatedFields.length > 0;
16619
17044
  const shouldFetchForInvalidation = hasStaleInvalidatedFields && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
16620
- if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive) {
17045
+ if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive && !isOfflineMode) {
16621
17046
  shouldFetch = true;
16622
17047
  requiredFetch = true;
16623
17048
  fieldsToFetch = Array.from(new Set([...missingFields, ...staleInvalidatedFields]));
@@ -16628,7 +17053,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16628
17053
  const hasStaleFullInvalidation = hasUnresolvedFullInvalidation && !!item;
16629
17054
  const missingFullItem = !hasStaleFullInvalidation && (!snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation);
16630
17055
  const shouldFetchForInvalidation = !missingFullItem && (unresolvedPendingInvalidationFields.length > 0 || hasStaleFullInvalidation) && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
16631
- if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive) {
17056
+ if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive && !isOfflineMode) {
16632
17057
  shouldFetch = true;
16633
17058
  requiredFetch = true;
16634
17059
  fieldsToFetch = missingFullItem || hasStaleFullInvalidation ? "*" : unresolvedPendingInvalidationFields;
@@ -16659,6 +17084,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16659
17084
  fetchQueriesWithId,
16660
17085
  getUnresolvedPendingInvalidationFields,
16661
17086
  ignoreItemsInRefetchOnMount,
17087
+ isOfflineMode,
16662
17088
  itemHasMissingRequestedData,
16663
17089
  itemPendingInvalidationFields,
16664
17090
  itemsPendingFullInvalidation,
@@ -16932,6 +17358,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16932
17358
  let staleOrMissingRequestedFields;
16933
17359
  let hasAnyIncompleteItem = false;
16934
17360
  let hasAnyStaleItem = false;
17361
+ let hasMissingRequestedData = false;
16935
17362
  const statusCanBeOverridden = status === "success" || status === "refetching";
16936
17363
  if (partialResources && (statusCanBeOverridden || showPartialAsRefetching)) {
16937
17364
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16954,17 +17381,23 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16954
17381
  item: state.items[itemKey],
16955
17382
  loadedFields: state.itemLoadedFields[itemKey]
16956
17383
  }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0);
16957
- if (!hasCachedItemsInState) status = "loading";
16958
- else if (someItemMissingFieldDataInState) status = showPartialAsRefetching ? "refetching" : "loading";
16959
- else status = "refetching";
17384
+ if (!hasCachedItemsInState) {
17385
+ hasMissingRequestedData = true;
17386
+ status = "loading";
17387
+ } else if (someItemMissingFieldDataInState) {
17388
+ hasMissingRequestedData = true;
17389
+ status = showPartialAsRefetching ? "refetching" : "loading";
17390
+ } else status = "refetching";
16960
17391
  } else if (partialResources && fields === "*" && statusCanBeOverridden) {
16961
17392
  const hasAnyFieldInvalidation = effectiveQuery.query.items.some((itemKey) => {
16962
17393
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
16963
17394
  return !!itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0;
16964
17395
  });
16965
- if (hasAnyIncompleteItem) if (!hasCachedItemsInState) status = "loading";
16966
- else status = showPartialAsRefetching ? "refetching" : "loading";
16967
- else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
17396
+ if (hasAnyIncompleteItem) {
17397
+ hasMissingRequestedData = true;
17398
+ if (!hasCachedItemsInState) status = "loading";
17399
+ else status = showPartialAsRefetching ? "refetching" : "loading";
17400
+ } else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
16968
17401
  }
16969
17402
  if (partialResources && showPartialAsRefetching) {
16970
17403
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16975,15 +17408,25 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16975
17408
  if (pendingInvalidationFields.length > 0) loadingFields = pendingInvalidationFields;
16976
17409
  }
16977
17410
  }
17411
+ if (status === "refetching" && !hasMissingRequestedData && isOfflineMode && effectiveQuery.query.status === "success") {
17412
+ status = "success";
17413
+ loadingFields = void 0;
17414
+ }
16978
17415
  if (!returnRefetchingStatus && status === "refetching") status = "success";
17416
+ const shouldHideItemsWhileLoading = status === "loading" && partialResources;
17417
+ let error = effectiveQuery.query.error;
17418
+ if (hasMissingRequestedData && isOfflineMode && effectiveQuery.query.status === "success") {
17419
+ status = "error";
17420
+ error = offlineConnectivityError;
17421
+ }
16979
17422
  return {
16980
17423
  queryKey,
16981
17424
  status,
16982
- items: status === "loading" && partialResources ? [] : selectVisibleItems(visibleItemKeys, fields, (itemKey) => ({
17425
+ items: shouldHideItemsWhileLoading ? [] : selectVisibleItems(visibleItemKeys, fields, (itemKey) => ({
16983
17426
  item: state.items[itemKey],
16984
17427
  itemPayload: state.itemQueries[itemKey]?.payload
16985
17428
  })),
16986
- error: effectiveQuery.query.error,
17429
+ error,
16987
17430
  hasMore: isOfflineMode ? !!readFallbackQueryState && effectiveQuery.query.hasMore && isStrictItemKeyPrefix(effectiveQuery.query.items, readFallbackQueryState(queryKey)?.items ?? []) : effectiveQuery.query.hasMore,
16988
17431
  isDerived: effectiveQuery.isDerived,
16989
17432
  ...loadingFields ? { loadingFields } : {},
@@ -17215,7 +17658,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17215
17658
  requiredFetch = false;
17216
17659
  shouldFetch = !!queryState?.refetchOnMount;
17217
17660
  }
17218
- if (partialResources && !shouldFetch && effectiveQueryState) {
17661
+ if (partialResources && !shouldFetch && effectiveQueryState && !isOfflineMode) {
17219
17662
  const isQueryFetchInFlight = effectiveQueryState.status === "loading" || effectiveQueryState.status === "refetching" || effectiveQueryState.status === "loadingMore";
17220
17663
  if (Array.isArray(fields) && fields.length > 0) {
17221
17664
  let hasStaleOrMissingRequestedFields = false;
@@ -17307,6 +17750,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17307
17750
  itemsPendingFullInvalidation,
17308
17751
  getHighestPendingInvalidationPriority,
17309
17752
  getUnresolvedPendingInvalidationFields,
17753
+ isOfflineMode,
17310
17754
  queryItemsHaveMissingRequestedData,
17311
17755
  stickyDerivedQueryKeys
17312
17756
  ]);
@@ -18213,16 +18657,24 @@ function createListQueryStore(storeOptions) {
18213
18657
  }
18214
18658
  applyRemoteQuerySnapshot(message);
18215
18659
  }
18660
+ /**
18661
+ * Reactive version of `isOfflineFetchModeActive` for the hooks: it re-renders
18662
+ * them when the session enters or leaves offline mode, and, unlike the
18663
+ * session status getter, reads nothing that writes state during render.
18664
+ */
18665
+ function useIsStoreOfflineMode() {
18666
+ return useOfflineStoreIsOfflineMode({
18667
+ sessionKey: getSessionKeyForRuntime(),
18668
+ inactiveScope: id
18669
+ }) || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
18670
+ }
18216
18671
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
18217
18672
  const offlineEntities = useOfflineStoreEntities({
18218
18673
  sessionKey: getSessionKeyForRuntime(),
18219
18674
  inactiveScope: id,
18220
18675
  storeName: resolvedPersistentStorageConfig ? id : void 0
18221
18676
  });
18222
- const isStoreOfflineMode = useOfflineStoreStatus({
18223
- sessionKey: getSessionKeyForRuntime(),
18224
- inactiveScope: id
18225
- }).isOfflineMode || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
18677
+ const isStoreOfflineMode = useIsStoreOfflineMode();
18226
18678
  const offlineOverlaysSelector = useCallback((state) => {
18227
18679
  return state;
18228
18680
  }, []);
@@ -18242,7 +18694,8 @@ function createListQueryStore(storeOptions) {
18242
18694
  return state;
18243
18695
  }, []);
18244
18696
  const offlineOverlays = offlineOverlayStore.useSelector(offlineOverlaysSelector);
18245
- return useMultipleItems(items, options, store, events, getItemKey, registerActiveStandaloneItems, touchItems, scheduleAutomaticItemFetch, persistence ? (payloads) => persistence.maybeHydrateItems(payloads.map((payload) => getItemKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence?.readHydratedItem, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays);
18697
+ const isStoreOfflineMode = useIsStoreOfflineMode();
18698
+ return useMultipleItems(items, options, store, events, getItemKey, registerActiveStandaloneItems, touchItems, scheduleAutomaticItemFetch, persistence ? (payloads) => persistence.maybeHydrateItems(payloads.map((payload) => getItemKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence?.readHydratedItem, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays, isStoreOfflineMode);
18246
18699
  };
18247
18700
  const useItem$3 = function useItem$2(itemPayload, options = {}) {
18248
18701
  return useItem(itemPayload, options, store, scheduleItemFetch, useMultipleItems$3);
@@ -18490,6 +18943,8 @@ function createListQueryStore(storeOptions) {
18490
18943
  inactiveScope: id,
18491
18944
  storeName: resolvedPersistentStorageConfig ? id : void 0
18492
18945
  }),
18946
+ useItemOfflineState: (itemPayload) => useOfflineStoreItemState(getSessionKeyForRuntime(), id, resolvedPersistentStorageConfig ? id : void 0, itemPayload === false || itemPayload == null ? null : getItemKey(itemPayload)),
18947
+ getItemOfflineState: (itemPayload) => offlineController?.getItemOfflineState(getItemKey(itemPayload)) ?? null,
18493
18948
  useOfflineResolutions: () => useOfflineStoreResolutions({
18494
18949
  sessionKey: getSessionKeyForRuntime(),
18495
18950
  inactiveScope: id,
@@ -18706,4 +19161,4 @@ var OpfsOfflineUploadDriver = class {
18706
19161
  };
18707
19162
  const opfsOfflineUploadAdapter = new OpfsOfflineUploadDriver();
18708
19163
  //#endregion
18709
- export { GET_ALL, IsOffScreenContext, StoreFetchError, StoreMutationError, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
19164
+ export { GET_ALL, IsOffScreenContext, StoreFetchError, StoreMutationError, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, isOfflineStoreError, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };