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