@marktiderman/genesis-core 2.10.0 → 2.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -1
- package/dist/{chunk-LGTXQTHA.js → chunk-2VJQVAJD.js} +3 -3
- package/dist/{chunk-LGTXQTHA.js.map → chunk-2VJQVAJD.js.map} +1 -1
- package/dist/chunk-2WS4LGYU.js +47 -0
- package/dist/chunk-2WS4LGYU.js.map +1 -0
- package/dist/{chunk-KXVDDDJY.js → chunk-3B5O36DU.js} +105 -13
- package/dist/chunk-3B5O36DU.js.map +1 -0
- package/dist/{chunk-EHFYSJJA.js → chunk-42QPCDQF.js} +3 -3
- package/dist/{chunk-EHFYSJJA.js.map → chunk-42QPCDQF.js.map} +1 -1
- package/dist/{chunk-RK365SO2.js → chunk-AKF2RAGX.js} +8 -5
- package/dist/chunk-AKF2RAGX.js.map +1 -0
- package/dist/{chunk-4ZR7472O.js → chunk-LOJGHR5O.js} +4 -4
- package/dist/{chunk-4ZR7472O.js.map → chunk-LOJGHR5O.js.map} +1 -1
- package/dist/{chunk-ON2V4RXX.js → chunk-OC4OGB2K.js} +19 -11
- package/dist/chunk-OC4OGB2K.js.map +1 -0
- package/dist/{chunk-HQAVDVIH.js → chunk-POMTRNAL.js} +4 -4
- package/dist/{chunk-HQAVDVIH.js.map → chunk-POMTRNAL.js.map} +1 -1
- package/dist/{chunk-VDEW4AOS.js → chunk-PSFKIG27.js} +55 -6
- package/dist/chunk-PSFKIG27.js.map +1 -0
- package/dist/{chunk-37RWGNIO.js → chunk-VFT6QKZW.js} +114 -5
- package/dist/chunk-VFT6QKZW.js.map +1 -0
- package/dist/{chunk-VDS6REM3.js → chunk-VJGU6E4U.js} +5 -5
- package/dist/{chunk-VDS6REM3.js.map → chunk-VJGU6E4U.js.map} +1 -1
- package/dist/{chunk-ZCE3CHPX.js → chunk-XVRIWP7B.js} +3 -3
- package/dist/{chunk-ZCE3CHPX.js.map → chunk-XVRIWP7B.js.map} +1 -1
- package/dist/{chunk-7FVTGKTX.js → chunk-YDMKMNDS.js} +2 -2
- package/dist/{chunk-7FVTGKTX.js.map → chunk-YDMKMNDS.js.map} +1 -1
- package/dist/{chunk-6WV6ST67.js → chunk-YNXLPOAB.js} +97 -10
- package/dist/chunk-YNXLPOAB.js.map +1 -0
- package/dist/{chunk-7GW3QR63.js → chunk-ZHC3MDCS.js} +101 -18
- package/dist/chunk-ZHC3MDCS.js.map +1 -0
- package/dist/conversation/index.d.ts +195 -0
- package/dist/conversation/index.js +110 -0
- package/dist/conversation/index.js.map +1 -0
- package/dist/csv.d.ts +1 -1
- package/dist/errors.js +1 -2
- package/dist/form-types.d.ts +1 -1
- package/dist/gallery/index.d.ts +79 -0
- package/dist/gallery/index.js +64 -0
- package/dist/gallery/index.js.map +1 -0
- package/dist/hooks/index.d.ts +5 -4
- package/dist/hooks/index.js +18 -18
- package/dist/hooks/mutation-mode.d.ts +29 -2
- package/dist/hooks/mutation-mode.js +9 -4
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-capabilities.js +2 -2
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.js +4 -4
- package/dist/hooks/use-link-options.d.ts +1 -1
- package/dist/hooks/use-link-options.js +6 -6
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-live.js +3 -3
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-one.js +4 -4
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-relation-label.js +2 -2
- package/dist/hooks/use-resource-form.d.ts +14 -1
- package/dist/hooks/use-resource-form.js +12 -9
- package/dist/hooks/use-resource.d.ts +17 -3
- package/dist/hooks/use-resource.js +12 -8
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.js +21 -21
- package/dist/offline/index.d.ts +84 -0
- package/dist/offline/index.js +413 -0
- package/dist/offline/index.js.map +1 -0
- package/dist/provider/index.d.ts +60 -7
- package/dist/provider/index.js +3 -3
- package/dist/resource-view/index.d.ts +79 -4
- package/dist/resource-view/index.js +141 -19
- package/dist/resource-view/index.js.map +1 -1
- package/dist/schema/index.d.ts +4 -3
- package/dist/schema/index.js +2 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/{types-9WnGxZhj.d.ts → types-BzLv8yOm.d.ts} +8 -0
- package/dist/types-CsKSAKqs.d.ts +143 -0
- package/dist/{viewer-scope-bthEYSOB.d.ts → viewer-scope-Dx0N9AYk.d.ts} +3 -2
- package/dist/workspaces.d.ts +1 -1
- package/dist/{write-outcome-ZWlhhzRW.d.ts → write-outcome-DC5hORz-.d.ts} +1 -1
- package/dist/write-state-DVC4Yq9T.d.ts +58 -0
- package/package.json +15 -2
- package/dist/chunk-37RWGNIO.js.map +0 -1
- package/dist/chunk-6WV6ST67.js.map +0 -1
- package/dist/chunk-7GW3QR63.js.map +0 -1
- package/dist/chunk-KXVDDDJY.js.map +0 -1
- package/dist/chunk-ON2V4RXX.js.map +0 -1
- package/dist/chunk-PA6WJE5E.js +0 -115
- package/dist/chunk-PA6WJE5E.js.map +0 -1
- package/dist/chunk-RK365SO2.js.map +0 -1
- package/dist/chunk-VDEW4AOS.js.map +0 -1
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
export { useResource } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
5
|
-
import '../chunk-
|
|
1
|
+
export { useResource } from '../chunk-OC4OGB2K.js';
|
|
2
|
+
import '../chunk-7NUL32W7.js';
|
|
3
|
+
import '../chunk-XVRIWP7B.js';
|
|
4
|
+
import '../chunk-YNXLPOAB.js';
|
|
5
|
+
import '../chunk-2VJQVAJD.js';
|
|
6
|
+
import '../chunk-AJGVLF37.js';
|
|
6
7
|
import '../chunk-7PUFVNPB.js';
|
|
7
|
-
import '../chunk-
|
|
8
|
+
import '../chunk-PSFKIG27.js';
|
|
8
9
|
import '../chunk-ZYJUEJ4Z.js';
|
|
9
|
-
import '../chunk-
|
|
10
|
-
import '../chunk-
|
|
10
|
+
import '../chunk-AUVKRXRC.js';
|
|
11
|
+
import '../chunk-VFT6QKZW.js';
|
|
12
|
+
import '../chunk-HUNGCTRA.js';
|
|
13
|
+
import '../chunk-RYEXWQFD.js';
|
|
14
|
+
import '../chunk-LG6TUBVM.js';
|
|
11
15
|
//# sourceMappingURL=use-resource.js.map
|
|
12
16
|
//# sourceMappingURL=use-resource.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { QueryClient, MutationOptions } from '@tanstack/react-query';
|
|
2
|
-
import { I as InvalidationKey } from '../types-
|
|
2
|
+
import { I as InvalidationKey } from '../types-BzLv8yOm.js';
|
|
3
3
|
|
|
4
4
|
declare const WRITE_FAILED = "That didn't work. Try again.";
|
|
5
5
|
interface UseWriteOptions<A, R> {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { L as ListParams, b as Identifier } from './types-
|
|
2
|
-
export { A as ArrayFilter, c as AuditEntry, B as BaseRecord, d as BulkChange, e as BulkResult, C as CountMode, f as CreateParams, g as CreateResult, D as DataProvider, h as DataRow, i as DeleteParams, j as DeleteResult, k as FieldPermissions, l as FieldReference, F as FieldSchema, m as FieldType, n as FilterOperator, a as FilterParam, G as GetManyParams, o as GetManyResult, p as GetOneParams, q as GetOneResult, H as HistoryParams, r as ImportParams, I as InvalidationKey, s as ListResult, N as NullFilter, P as PaginationParam, t as ProviderCapabilities, R as RangeFilter, u as RecordComment, v as ResourceAccess, w as ResourceChangeEvent, x as ResourceContract, y as ResourceFormFieldDef, z as ResourceRelation, E as ResourceSchema, J as ResourceSummary, K as RowAction, M as RowFailure, O as RowOf, Q as ScalarFilter, T as SelectOption, S as SortParam, U as StorageType, V as SubscribeParams, X as UpdateParams, Y as UpdateResult, Z as VersionField, m as WidgetHint, W as WriteEvent, _ as defineResource } from './types-
|
|
3
|
-
export { D as DataWriteError, a as DataWriteErrorOptions, W as WriteOutcome, i as isDataWriteError } from './write-outcome-
|
|
4
|
-
export { CallRpcOptions, CreateOrAdoptOptions, CreateOrAdoptResult, DEFAULT_RPC_MESSAGES, DataProviderRoot, DataProviderRootProps, GenesisProvider, GenesisProviderProps, MockProviderOptions, PostgrestFieldErrors, RPC_FAILED, RpcClient, SupabaseClient, SupabaseClientInput, SupabaseProviderOptions, SupabaseRealtimeChannel, SupabaseRealtimePayload, SupabaseResourceConfig, SupabaseWriteContext, callRpc, createMockProvider, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, useDataProvider, useStorage, writeOutcomeFromCode } from './provider/index.js';
|
|
1
|
+
import { L as ListParams, b as Identifier } from './types-BzLv8yOm.js';
|
|
2
|
+
export { A as ArrayFilter, c as AuditEntry, B as BaseRecord, d as BulkChange, e as BulkResult, C as CountMode, f as CreateParams, g as CreateResult, D as DataProvider, h as DataRow, i as DeleteParams, j as DeleteResult, k as FieldPermissions, l as FieldReference, F as FieldSchema, m as FieldType, n as FilterOperator, a as FilterParam, G as GetManyParams, o as GetManyResult, p as GetOneParams, q as GetOneResult, H as HistoryParams, r as ImportParams, I as InvalidationKey, s as ListResult, N as NullFilter, P as PaginationParam, t as ProviderCapabilities, R as RangeFilter, u as RecordComment, v as ResourceAccess, w as ResourceChangeEvent, x as ResourceContract, y as ResourceFormFieldDef, z as ResourceRelation, E as ResourceSchema, J as ResourceSummary, K as RowAction, M as RowFailure, O as RowOf, Q as ScalarFilter, T as SelectOption, S as SortParam, U as StorageType, V as SubscribeParams, X as UpdateParams, Y as UpdateResult, Z as VersionField, m as WidgetHint, W as WriteEvent, _ as defineResource } from './types-BzLv8yOm.js';
|
|
3
|
+
export { D as DataWriteError, a as DataWriteErrorOptions, W as WriteOutcome, i as isDataWriteError } from './write-outcome-DC5hORz-.js';
|
|
4
|
+
export { CallRpcOptions, CreateOrAdoptOptions, CreateOrAdoptResult, DEFAULT_RPC_MESSAGES, DataProviderRoot, DataProviderRootProps, GenesisProvider, GenesisProviderProps, MockProviderOptions, PostgrestFieldErrors, RPC_FAILED, RpcClient, SupabaseClient, SupabaseClientInput, SupabaseProviderOptions, SupabaseRealtimeChannel, SupabaseRealtimePayload, SupabaseResourceConfig, SupabaseUpdateContext, SupabaseWriteContext, callRpc, createMockProvider, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, useDataProvider, useStorage, writeOutcomeFromCode } from './provider/index.js';
|
|
5
5
|
export { D as DataReadError, a as DataReadErrorOptions, R as ReadOutcome, i as isDataReadError, r as readFailureMessage } from './read-outcome-BnboMYOV.js';
|
|
6
6
|
export { S as StorageAdapter } from './types-DKcxHXxq.js';
|
|
7
7
|
export { createLocalStorageAdapter, createMemoryStorageAdapter, createNoopStorageAdapter } from './storage/index.js';
|
|
8
|
-
export { UseResourceOptions, UseResourceReturn, useResource } from './hooks/use-resource.js';
|
|
8
|
+
export { UpdateOptions, UseResourceOptions, UseResourceReturn, useResource } from './hooks/use-resource.js';
|
|
9
9
|
export { UseOneOptions, useOne } from './hooks/use-one.js';
|
|
10
10
|
export { UseRelationLabelOptions, loadRelationLabel, relationNamingField, useRelationLabel } from './hooks/use-relation-label.js';
|
|
11
11
|
export { LinkOption, LinkTarget, UseLinkOptionsOptions, UseLinkOptionsReturn, useLinkOptions } from './hooks/use-link-options.js';
|
|
@@ -14,7 +14,7 @@ export { useCapabilities } from './hooks/use-capabilities.js';
|
|
|
14
14
|
export { UseWriteOptions, UseWriteReturn, WRITE_FAILED, useWrite } from './hooks/use-write.js';
|
|
15
15
|
export { UseDraftReturn, useDraft } from './hooks/use-draft.js';
|
|
16
16
|
export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftAdoption, DraftController, DraftOptions, DraftSeed, DraftState, DraftStatus, DraftValue, isNetworkFailure, stableJson } from './hooks/draft-controller.js';
|
|
17
|
-
export { G as GenesisViewerRoles, N as NO_VIEWER, R as ResourceScope, V as Viewer, a as ViewerContext, b as ViewerScope, c as ViewerScopeProps, d as clearViewerCache, s as scopeClock, u as useOptionalViewerScope, e as useViewer, f as useViewerScope } from './viewer-scope-
|
|
17
|
+
export { G as GenesisViewerRoles, N as NO_VIEWER, R as ResourceScope, V as Viewer, a as ViewerContext, b as ViewerScope, c as ViewerScopeProps, d as clearViewerCache, s as scopeClock, u as useOptionalViewerScope, e as useViewer, f as useViewerScope } from './viewer-scope-Dx0N9AYk.js';
|
|
18
18
|
export { WorkspaceContext, WorkspaceScope, WorkspaceScopeProps, rememberedWorkspaceId, useWorkspace } from './hooks/index.js';
|
|
19
19
|
export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, LiveOptions, useLiveInvalidation } from './hooks/use-live.js';
|
|
20
20
|
export { UseResourceFormOptions, UseResourceFormReturn, blankValues, buildArrayItemDefaults, useResourceForm } from './hooks/use-resource-form.js';
|
|
@@ -22,11 +22,13 @@ export { UseWizardReturn, WizardStep, useWizard } from './hooks/use-wizard.js';
|
|
|
22
22
|
export { DEFAULT_UNDO_DELAY_MS, MutationMode, MutationModeOptions, UndoableWrite, dropPendingWrites, flushPendingWrites, pendingWriteCount } from './hooks/mutation-mode.js';
|
|
23
23
|
export { DEFAULT_UNSAVED_CHANGES_MESSAGE, UseUnsavedChangesGuardOptions, UseUnsavedChangesGuardReturn, useUnsavedChangesGuard } from './hooks/use-unsaved-changes-guard.js';
|
|
24
24
|
export { decodeRecordKey, encodeRecordKey, keyFields } from './schema/index.js';
|
|
25
|
+
export { W as WriteConflict, a as WriteConflictOptions, b as WriteState, w as writeConflict } from './write-state-DVC4Yq9T.js';
|
|
25
26
|
import { Query } from '@tanstack/react-query';
|
|
26
27
|
export { isSafeUrl, normalizeLinkUrl } from './urls.js';
|
|
27
28
|
export { ClassifiedError, ClassifyErrorOptions, ErrorKind, ErrorMessages, ErrorReportContext, ErrorReporter, classifyError, defaultErrorReporter, errorMessages, getErrorReporter, reportError, setErrorReporter } from './errors.js';
|
|
28
29
|
export { titleCase } from './utils.js';
|
|
29
30
|
import 'react';
|
|
31
|
+
import './types-CsKSAKqs.js';
|
|
30
32
|
import './dates.js';
|
|
31
33
|
import './workspaces.js';
|
|
32
34
|
import 'react-hook-form';
|
package/dist/index.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
|
|
2
|
-
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider } from './chunk-7GW3QR63.js';
|
|
3
|
-
export { defineResource } from './chunk-7FVTGKTX.js';
|
|
1
|
+
export { defineResource } from './chunk-YDMKMNDS.js';
|
|
4
2
|
export { decodeRecordKey, encodeRecordKey, keyFields } from './chunk-KV2HW4G4.js';
|
|
5
|
-
|
|
6
|
-
export {
|
|
3
|
+
import './chunk-XCX2TRBL.js';
|
|
4
|
+
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider } from './chunk-ZHC3MDCS.js';
|
|
5
|
+
export { ViewerScope, WorkspaceScope, clearViewerCache, rememberedWorkspaceId, scopeClock, useOptionalViewerScope, useViewer, useViewerScope, useWorkspace } from './chunk-AKF2RAGX.js';
|
|
6
|
+
export { NO_VIEWER } from './chunk-OZYF55E3.js';
|
|
7
|
+
export { blankValues, buildArrayItemDefaults, useResourceForm } from './chunk-3B5O36DU.js';
|
|
8
|
+
export { writeConflict } from './chunk-2WS4LGYU.js';
|
|
9
|
+
export { useResource } from './chunk-OC4OGB2K.js';
|
|
10
|
+
export { DEFAULT_UNSAVED_CHANGES_MESSAGE, useUnsavedChangesGuard } from './chunk-RVWKVD5Q.js';
|
|
7
11
|
export { useWizard } from './chunk-7KOLYF27.js';
|
|
8
12
|
export { WRITE_FAILED, useWrite } from './chunk-52T2EYXH.js';
|
|
9
|
-
|
|
13
|
+
import './chunk-7NUL32W7.js';
|
|
10
14
|
export { useDraft } from './chunk-YQBWXG2G.js';
|
|
11
|
-
export { useLinkOptions } from './chunk-
|
|
12
|
-
export {
|
|
13
|
-
export {
|
|
14
|
-
export {
|
|
15
|
-
export {
|
|
16
|
-
export { useOne } from './chunk-4ZR7472O.js';
|
|
17
|
-
export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, useLiveInvalidation } from './chunk-ZCE3CHPX.js';
|
|
15
|
+
export { useLinkOptions } from './chunk-VJGU6E4U.js';
|
|
16
|
+
export { loadRelationLabel, relationNamingField, useRelationLabel } from './chunk-42QPCDQF.js';
|
|
17
|
+
export { useInfiniteResource } from './chunk-POMTRNAL.js';
|
|
18
|
+
export { useOne } from './chunk-LOJGHR5O.js';
|
|
19
|
+
export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, useLiveInvalidation } from './chunk-XVRIWP7B.js';
|
|
18
20
|
import './chunk-UHOMTFBD.js';
|
|
19
21
|
export { DEFAULT_DRAFT_DELAY_MS, DRAFT_NOT_SAVED, DraftController, isNetworkFailure, stableJson } from './chunk-HBAPYA5K.js';
|
|
20
|
-
|
|
21
|
-
export {
|
|
22
|
-
|
|
22
|
+
export { DEFAULT_UNDO_DELAY_MS, dropPendingWrites, flushPendingWrites, pendingWriteCount } from './chunk-YNXLPOAB.js';
|
|
23
|
+
export { useCapabilities } from './chunk-2VJQVAJD.js';
|
|
24
|
+
import './chunk-AJGVLF37.js';
|
|
23
25
|
export { defineQueryKeys, resourceKeys } from './chunk-7PUFVNPB.js';
|
|
24
|
-
export { DataProviderRoot, GenesisProvider, createMockProvider, useDataProvider, useStorage } from './chunk-
|
|
26
|
+
export { DataProviderRoot, GenesisProvider, createMockProvider, useDataProvider, useStorage } from './chunk-PSFKIG27.js';
|
|
25
27
|
export { createLocalStorageAdapter, createMemoryStorageAdapter, createNoopStorageAdapter } from './chunk-ZYJUEJ4Z.js';
|
|
26
|
-
import './chunk-
|
|
27
|
-
import './chunk-7NUL32W7.js';
|
|
28
|
+
import './chunk-AUVKRXRC.js';
|
|
28
29
|
import './chunk-WXENWPWP.js';
|
|
29
|
-
export { classifyError, defaultErrorReporter, errorMessages, getErrorReporter, reportError, setErrorReporter } from './chunk-
|
|
30
|
-
export { fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, writeOutcomeFromCode } from './chunk-PA6WJE5E.js';
|
|
30
|
+
export { classifyError, defaultErrorReporter, errorMessages, fieldErrorsFromPostgrest, getErrorReporter, readOutcomeFromCode, reportError, setErrorReporter, toDataWriteError, writeOutcomeFromCode } from './chunk-VFT6QKZW.js';
|
|
31
31
|
export { DataReadError, isDataReadError, readFailureMessage } from './chunk-HUNGCTRA.js';
|
|
32
32
|
export { titleCase } from './chunk-RYEXWQFD.js';
|
|
33
33
|
export { DataWriteError, isDataWriteError } from './chunk-LG6TUBVM.js';
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { L as LocalCache, Q as QueryPersistence } from '../types-CsKSAKqs.js';
|
|
2
|
+
export { C as CacheOp, a as CacheScope, S as StoredQuery, b as StoredRow, c as SubscribeOptions, d as cacheScope } from '../types-CsKSAKqs.js';
|
|
3
|
+
import { QueryClient } from '@tanstack/react-query';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A `LocalCache` in memory: for tests, and for a screen that wants the
|
|
7
|
+
* contract without a device store. Nothing survives a reload.
|
|
8
|
+
*
|
|
9
|
+
* @stability Beta
|
|
10
|
+
*/
|
|
11
|
+
declare function memoryLocalCache(): LocalCache;
|
|
12
|
+
|
|
13
|
+
/** Options for {@link indexedDbLocalCache}. */
|
|
14
|
+
interface IndexedDbLocalCacheOptions {
|
|
15
|
+
/** The database name. Default `"genesis-offline"`. */
|
|
16
|
+
name?: string;
|
|
17
|
+
/** The IndexedDB factory. Default `globalThis.indexedDB`. */
|
|
18
|
+
indexedDB?: IDBFactory;
|
|
19
|
+
/**
|
|
20
|
+
* Ask the browser to keep this origin's storage (`navigator.storage.persist()`).
|
|
21
|
+
* Default false: some browsers ask the person, and kept storage outlives a
|
|
22
|
+
* shared machine's session longer. Without it the browser may evict the
|
|
23
|
+
* cache under pressure; it's rebuilt from the server.
|
|
24
|
+
*/
|
|
25
|
+
persist?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* A `LocalCache` in IndexedDB, for the web: plain IndexedDB, no dependency.
|
|
29
|
+
* Rows and queries are separate object stores keyed by scope, so one row is
|
|
30
|
+
* stored once whatever lists hold it, and a write is one transaction. A newer
|
|
31
|
+
* version of the database opened in another tab closes this one, which then
|
|
32
|
+
* reopens on its next use, instead of blocking the upgrade.
|
|
33
|
+
*
|
|
34
|
+
* @stability Beta
|
|
35
|
+
*/
|
|
36
|
+
declare function indexedDbLocalCache(options?: IndexedDbLocalCacheOptions): LocalCache;
|
|
37
|
+
|
|
38
|
+
/** Options for {@link persistOffline}. */
|
|
39
|
+
interface PersistOfflineOptions {
|
|
40
|
+
/** Where reads are kept: `indexedDbLocalCache()` on the web, `sqliteLocalCache({ db })` on the phone. */
|
|
41
|
+
cache: LocalCache;
|
|
42
|
+
/**
|
|
43
|
+
* The resources whose reads are kept on the device: the one opt-in switch.
|
|
44
|
+
* Keeping data on a device is a decision, so nothing else is written. Leave
|
|
45
|
+
* out a resource whose rows shouldn't sit on a phone unencrypted.
|
|
46
|
+
*/
|
|
47
|
+
resources: readonly string[];
|
|
48
|
+
/** Your app's version: a different value discards what was kept. */
|
|
49
|
+
buster: string;
|
|
50
|
+
/** How old a kept read may be when restored. Default 7 days. */
|
|
51
|
+
maxAge?: number;
|
|
52
|
+
/** Save at most this often. Default 500 ms. */
|
|
53
|
+
throttleMs?: number;
|
|
54
|
+
/** The most reads kept per person and workspace; the least recently fetched go first. Default 200. */
|
|
55
|
+
maxReads?: number;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Keeps the reads of the listed resources on the device, per record, and
|
|
59
|
+
* puts them back into the QueryClient on the next start, so lists and records
|
|
60
|
+
* open at once and then refresh as usual. What `GenesisNativeApp`'s and
|
|
61
|
+
* `GenesisProvider`'s `persist` take.
|
|
62
|
+
*
|
|
63
|
+
* persist={persistOffline({ cache: indexedDbLocalCache(), resources: ["tasks", "people"], buster: version })}
|
|
64
|
+
*
|
|
65
|
+
* - Only reads that came back from the provider are kept (never an optimistic
|
|
66
|
+
* change that hasn't been saved), in the bucket of the person and workspace
|
|
67
|
+
* they were read in.
|
|
68
|
+
* - A restored read is marked as fetched when it was, so a screen refetches it
|
|
69
|
+
* once it's stale (the client's `staleTime`), as with any cached read. It
|
|
70
|
+
* never replaces a newer read already in the client.
|
|
71
|
+
* - A newer read replaces a stored row, so a field the server stops returning
|
|
72
|
+
* goes; a record that comes back empty is deleted from the device. Each start
|
|
73
|
+
* deletes reads older than `maxAge` and the rows no kept read refers to.
|
|
74
|
+
* - A device is one person's: restoring someone deletes every other person's
|
|
75
|
+
* reads first, and `restore("")` (nobody signed in) deletes them all, so a
|
|
76
|
+
* session that ended outside the app leaves nothing behind.
|
|
77
|
+
* - A sign-out, a change of person or workspace, or `clear()` stops every save
|
|
78
|
+
* and restore still in flight from landing in the new bucket.
|
|
79
|
+
*
|
|
80
|
+
* @stability Beta
|
|
81
|
+
*/
|
|
82
|
+
declare function persistOffline(options: PersistOfflineOptions): (queryClient: QueryClient) => QueryPersistence;
|
|
83
|
+
|
|
84
|
+
export { type IndexedDbLocalCacheOptions, LocalCache, type PersistOfflineOptions, QueryPersistence, indexedDbLocalCache, memoryLocalCache, persistOffline };
|
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
// src/offline/types.ts
|
|
2
|
+
var userPrefix = (user) => `u:${user}|`;
|
|
3
|
+
function assertScope(scope) {
|
|
4
|
+
if (!/^u:[^|]+\|/.test(scope)) {
|
|
5
|
+
throw new Error(`[genesis offline] "${scope}" isn't a person's cache scope: build it with cacheScope(userId, workspace).`);
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
function cacheScope(userId, workspace = "none") {
|
|
9
|
+
if (!userId) throw new Error("[genesis offline] cacheScope needs the signed-in user's id.");
|
|
10
|
+
return `${userPrefix(userId)}${workspace}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// src/offline/memory.ts
|
|
14
|
+
var rowKey = (resource, id) => `${resource}\0${id}`;
|
|
15
|
+
function apply(bucket, op) {
|
|
16
|
+
if (op.kind === "row") {
|
|
17
|
+
const k = rowKey(op.row.resource, op.row.id);
|
|
18
|
+
const stored = bucket.rows.get(k);
|
|
19
|
+
if (!stored || stored.fetchedAt <= op.row.fetchedAt) bucket.rows.set(k, op.row);
|
|
20
|
+
} else if (op.kind === "query") bucket.queries.set(op.query.key, op.query);
|
|
21
|
+
else if (op.kind === "forget") {
|
|
22
|
+
const stored = bucket.queries.get(op.key);
|
|
23
|
+
if (stored && (op.before === void 0 || stored.fetchedAt < op.before)) bucket.queries.delete(op.key);
|
|
24
|
+
} else if (op.kind === "drop") bucket.rows.delete(rowKey(op.resource, op.id));
|
|
25
|
+
else {
|
|
26
|
+
const keep = new Set(op.keep);
|
|
27
|
+
for (const [k, row] of bucket.rows) if (row.resource === op.resource && !keep.has(row.id) && row.fetchedAt < op.before) bucket.rows.delete(k);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function memoryLocalCache() {
|
|
31
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
32
|
+
const bucket = (scope) => {
|
|
33
|
+
let b = buckets.get(scope);
|
|
34
|
+
if (!b) buckets.set(scope, b = { rows: /* @__PURE__ */ new Map(), queries: /* @__PURE__ */ new Map() });
|
|
35
|
+
return b;
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
async readQueries(scope) {
|
|
39
|
+
assertScope(scope);
|
|
40
|
+
return [...buckets.get(scope)?.queries.values() ?? []];
|
|
41
|
+
},
|
|
42
|
+
async readRows(scope, resource, ids) {
|
|
43
|
+
assertScope(scope);
|
|
44
|
+
const b = buckets.get(scope);
|
|
45
|
+
if (!b) return [];
|
|
46
|
+
return ids.map((id) => b.rows.get(rowKey(resource, id))).filter((r) => !!r);
|
|
47
|
+
},
|
|
48
|
+
async write(scope, ops) {
|
|
49
|
+
assertScope(scope);
|
|
50
|
+
const current = bucket(scope);
|
|
51
|
+
const next = { rows: new Map(current.rows), queries: new Map(current.queries) };
|
|
52
|
+
for (const op of ops) apply(next, op);
|
|
53
|
+
buckets.set(scope, next);
|
|
54
|
+
},
|
|
55
|
+
async clear(target) {
|
|
56
|
+
if (!target) {
|
|
57
|
+
buckets.clear();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if ("scope" in target) {
|
|
61
|
+
buckets.delete(target.scope);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const mine = (scope) => scope.startsWith(userPrefix("user" in target ? target.user : target.except));
|
|
65
|
+
for (const scope of [...buckets.keys()]) if (mine(scope) === "user" in target) buckets.delete(scope);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/offline/indexeddb.ts
|
|
71
|
+
var VERSION = 1;
|
|
72
|
+
var done = (request) => new Promise((resolve, reject) => {
|
|
73
|
+
request.onsuccess = () => resolve(request.result);
|
|
74
|
+
request.onerror = () => reject(request.error);
|
|
75
|
+
});
|
|
76
|
+
var finished = (tx) => new Promise((resolve, reject) => {
|
|
77
|
+
tx.oncomplete = () => resolve();
|
|
78
|
+
tx.onabort = () => reject(tx.error ?? new Error("[genesis offline] IndexedDB transaction aborted"));
|
|
79
|
+
tx.onerror = () => reject(tx.error);
|
|
80
|
+
});
|
|
81
|
+
function indexedDbLocalCache(options = {}) {
|
|
82
|
+
const name = options.name ?? "genesis-offline";
|
|
83
|
+
const factory = options.indexedDB ?? globalThis.indexedDB;
|
|
84
|
+
let opening = null;
|
|
85
|
+
const open = () => {
|
|
86
|
+
if (opening) return opening;
|
|
87
|
+
if (!factory) return Promise.reject(new Error("[genesis offline] IndexedDB isn't available here."));
|
|
88
|
+
if (options.persist === true) {
|
|
89
|
+
const storage = globalThis.navigator?.storage;
|
|
90
|
+
void storage?.persist?.().catch(() => false);
|
|
91
|
+
}
|
|
92
|
+
const request = factory.open(name, VERSION);
|
|
93
|
+
request.onblocked = () => void 0;
|
|
94
|
+
request.onupgradeneeded = () => {
|
|
95
|
+
const db = request.result;
|
|
96
|
+
if (!db.objectStoreNames.contains("rows")) {
|
|
97
|
+
db.createObjectStore("rows", { keyPath: ["scope", "resource", "id"] }).createIndex("scope", "scope");
|
|
98
|
+
}
|
|
99
|
+
if (!db.objectStoreNames.contains("queries")) {
|
|
100
|
+
db.createObjectStore("queries", { keyPath: ["scope", "key"] }).createIndex("scope", "scope");
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
opening = done(request).then((db) => {
|
|
104
|
+
db.onversionchange = () => {
|
|
105
|
+
db.close();
|
|
106
|
+
opening = null;
|
|
107
|
+
};
|
|
108
|
+
return db;
|
|
109
|
+
});
|
|
110
|
+
opening.catch(() => {
|
|
111
|
+
opening = null;
|
|
112
|
+
});
|
|
113
|
+
return opening;
|
|
114
|
+
};
|
|
115
|
+
const scopeRange = (scope) => IDBKeyRange.bound([scope], [scope, []]);
|
|
116
|
+
const personRange = (user) => IDBKeyRange.bound([userPrefix(user)], [`${userPrefix(user)}\uFFFF`]);
|
|
117
|
+
return {
|
|
118
|
+
async readQueries(scope) {
|
|
119
|
+
assertScope(scope);
|
|
120
|
+
const db = await open();
|
|
121
|
+
const records = await done(db.transaction("queries").objectStore("queries").index("scope").getAll(IDBKeyRange.only(scope)));
|
|
122
|
+
return records.map(({ scope: _s, ...query }) => query);
|
|
123
|
+
},
|
|
124
|
+
async readRows(scope, resource, ids) {
|
|
125
|
+
assertScope(scope);
|
|
126
|
+
if (ids.length === 0) return [];
|
|
127
|
+
const db = await open();
|
|
128
|
+
const store = db.transaction("rows").objectStore("rows");
|
|
129
|
+
const found = await Promise.all(ids.map((id) => done(store.get([scope, resource, id]))));
|
|
130
|
+
return found.filter((r) => !!r).map(({ scope: _s, ...row }) => row);
|
|
131
|
+
},
|
|
132
|
+
async write(scope, ops) {
|
|
133
|
+
assertScope(scope);
|
|
134
|
+
if (ops.length === 0) return;
|
|
135
|
+
const db = await open();
|
|
136
|
+
const tx = db.transaction(["rows", "queries"], "readwrite");
|
|
137
|
+
const rows = tx.objectStore("rows");
|
|
138
|
+
const queries = tx.objectStore("queries");
|
|
139
|
+
const newest = /* @__PURE__ */ new Map();
|
|
140
|
+
for (const op of ops) {
|
|
141
|
+
if (op.kind !== "row") continue;
|
|
142
|
+
const k = JSON.stringify([op.row.resource, op.row.id]);
|
|
143
|
+
const seen = newest.get(k);
|
|
144
|
+
if (!seen || seen.fetchedAt <= op.row.fetchedAt) newest.set(k, op.row);
|
|
145
|
+
}
|
|
146
|
+
const olderThan = (store, key, before, then) => {
|
|
147
|
+
const get = store.get(key);
|
|
148
|
+
get.onsuccess = () => {
|
|
149
|
+
const stored = get.result;
|
|
150
|
+
if (stored && stored.fetchedAt < before) then();
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
for (const op of ops) {
|
|
154
|
+
if (op.kind === "row") {
|
|
155
|
+
const row = newest.get(JSON.stringify([op.row.resource, op.row.id]));
|
|
156
|
+
if (row !== op.row) continue;
|
|
157
|
+
const get = rows.get([scope, row.resource, row.id]);
|
|
158
|
+
get.onsuccess = () => {
|
|
159
|
+
const stored = get.result;
|
|
160
|
+
if (!stored || stored.fetchedAt <= row.fetchedAt) rows.put({ ...row, scope });
|
|
161
|
+
};
|
|
162
|
+
} else if (op.kind === "query") queries.put({ ...op.query, scope });
|
|
163
|
+
else if (op.kind === "forget") {
|
|
164
|
+
if (op.before === void 0) queries.delete([scope, op.key]);
|
|
165
|
+
else olderThan(queries, [scope, op.key], op.before, () => queries.delete([scope, op.key]));
|
|
166
|
+
} else if (op.kind === "drop") rows.delete([scope, op.resource, op.id]);
|
|
167
|
+
else {
|
|
168
|
+
const keep = new Set(op.keep);
|
|
169
|
+
const cursor = rows.openCursor(IDBKeyRange.bound([scope, op.resource], [scope, op.resource, []]));
|
|
170
|
+
cursor.onsuccess = () => {
|
|
171
|
+
const c = cursor.result;
|
|
172
|
+
if (!c) return;
|
|
173
|
+
const stored = c.value;
|
|
174
|
+
if (!keep.has(stored.id) && stored.fetchedAt < op.before) c.delete();
|
|
175
|
+
c.continue();
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
await finished(tx);
|
|
180
|
+
},
|
|
181
|
+
async clear(target) {
|
|
182
|
+
const db = await open();
|
|
183
|
+
const tx = db.transaction(["rows", "queries"], "readwrite");
|
|
184
|
+
for (const store of [tx.objectStore("rows"), tx.objectStore("queries")]) {
|
|
185
|
+
if (!target) store.clear();
|
|
186
|
+
else if ("scope" in target) store.delete(scopeRange(target.scope));
|
|
187
|
+
else if ("user" in target) store.delete(personRange(target.user));
|
|
188
|
+
else {
|
|
189
|
+
store.delete(IDBKeyRange.upperBound([userPrefix(target.except)], true));
|
|
190
|
+
store.delete(IDBKeyRange.lowerBound([`${userPrefix(target.except)}\uFFFF`]));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
await finished(tx);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// src/offline/persist.ts
|
|
199
|
+
var DAY = 24 * 60 * 60 * 1e3;
|
|
200
|
+
var META = "__genesis_offline_meta__";
|
|
201
|
+
var KINDS = /* @__PURE__ */ new Set(["list", "detail", "infinite"]);
|
|
202
|
+
var isRef = (v) => !!v && typeof v === "object" && typeof v.$row === "string" && Object.keys(v).length === 1;
|
|
203
|
+
var isRow = (v) => !!v && typeof v === "object" && !Array.isArray(v) && v.id != null;
|
|
204
|
+
var keyText = (key) => JSON.stringify(
|
|
205
|
+
key,
|
|
206
|
+
(_k, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v
|
|
207
|
+
);
|
|
208
|
+
var toScope = (scope) => !scope ? null : scope.startsWith("u:") ? /^u:[^|]+\|/.test(scope) ? scope : null : `${userPrefix(scope)}none`;
|
|
209
|
+
function split(kind, select, data, rows) {
|
|
210
|
+
if (select !== void 0) return kind === "infinite" && !(data && typeof data === "object" && Array.isArray(data.pages)) ? null : data;
|
|
211
|
+
const list = (page) => {
|
|
212
|
+
if (!page || typeof page !== "object" || !Array.isArray(page.data)) return page;
|
|
213
|
+
const p = page;
|
|
214
|
+
return { ...p, data: p.data.map((r) => isRow(r) ? (rows.push(r), { $row: String(r.id) }) : r) };
|
|
215
|
+
};
|
|
216
|
+
if (kind === "list") return list(data);
|
|
217
|
+
if (kind === "infinite") {
|
|
218
|
+
if (!data || typeof data !== "object" || !Array.isArray(data.pages)) return null;
|
|
219
|
+
const d = data;
|
|
220
|
+
return { ...d, pages: d.pages.map(list) };
|
|
221
|
+
}
|
|
222
|
+
if (isRow(data)) {
|
|
223
|
+
rows.push(data);
|
|
224
|
+
return { $row: String(data.id) };
|
|
225
|
+
}
|
|
226
|
+
return data;
|
|
227
|
+
}
|
|
228
|
+
function refsIn(value, out) {
|
|
229
|
+
if (isRef(value)) out.add(value.$row);
|
|
230
|
+
else if (Array.isArray(value)) for (const v of value) refsIn(v, out);
|
|
231
|
+
else if (value && typeof value === "object") for (const v of Object.values(value)) refsIn(v, out);
|
|
232
|
+
}
|
|
233
|
+
function join(value, rows) {
|
|
234
|
+
if (isRef(value)) return rows.get(value.$row);
|
|
235
|
+
if (Array.isArray(value)) {
|
|
236
|
+
const out = value.map((v) => join(v, rows));
|
|
237
|
+
return out.some((v, i) => v === void 0 && value[i] !== void 0) ? void 0 : out;
|
|
238
|
+
}
|
|
239
|
+
if (value && typeof value === "object") {
|
|
240
|
+
const out = {};
|
|
241
|
+
for (const [k, v] of Object.entries(value)) {
|
|
242
|
+
const joined = join(v, rows);
|
|
243
|
+
if (joined === void 0 && v !== void 0) return void 0;
|
|
244
|
+
out[k] = joined;
|
|
245
|
+
}
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
return value;
|
|
249
|
+
}
|
|
250
|
+
function persistOffline(options) {
|
|
251
|
+
const { cache, buster, maxAge = 7 * DAY, throttleMs = 500, maxReads = 200 } = options;
|
|
252
|
+
const kept = new Set(options.resources);
|
|
253
|
+
return (queryClient) => {
|
|
254
|
+
let restores = 0;
|
|
255
|
+
let saves = 0;
|
|
256
|
+
const fetched = /* @__PURE__ */ new WeakMap();
|
|
257
|
+
queryClient.getQueryCache().subscribe((event) => {
|
|
258
|
+
if (event.type !== "updated") return;
|
|
259
|
+
const action = event.action;
|
|
260
|
+
if (action.type !== "success" || action.manual) return;
|
|
261
|
+
fetched.set(event.query, { data: event.query.state.data, fetchedAt: event.query.state.dataUpdatedAt });
|
|
262
|
+
});
|
|
263
|
+
const people = /* @__PURE__ */ new Set();
|
|
264
|
+
const meta = () => ({ kind: "query", query: { key: META, queryKey: [META], resource: META, data: { buster }, fetchedAt: Date.now() } });
|
|
265
|
+
const keptQuery = (query) => {
|
|
266
|
+
const [resource, kind] = query.queryKey;
|
|
267
|
+
return typeof resource === "string" && kept.has(resource) && typeof kind === "string" && KINDS.has(kind);
|
|
268
|
+
};
|
|
269
|
+
const restore = async (raw, signal) => {
|
|
270
|
+
if (raw === "") {
|
|
271
|
+
restores += 1;
|
|
272
|
+
saves += 1;
|
|
273
|
+
people.clear();
|
|
274
|
+
await cache.clear().catch(() => void 0);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const scope = toScope(raw);
|
|
278
|
+
if (!scope) return;
|
|
279
|
+
const mine = ++restores;
|
|
280
|
+
const user = scope.slice(2, scope.indexOf("|"));
|
|
281
|
+
people.add(user);
|
|
282
|
+
const stale = () => mine !== restores || signal?.aborted === true;
|
|
283
|
+
const startedAt = Date.now();
|
|
284
|
+
try {
|
|
285
|
+
await cache.clear({ except: user });
|
|
286
|
+
const stored = await cache.readQueries(scope);
|
|
287
|
+
if (stale()) return;
|
|
288
|
+
const found = stored.find((q) => q.key === META);
|
|
289
|
+
if (!found || found.data?.buster !== buster) {
|
|
290
|
+
const fresh2 = stored.filter((q) => q.key !== META).map((q) => ({ kind: "forget", key: q.key, before: startedAt }));
|
|
291
|
+
for (const resource of /* @__PURE__ */ new Set([...stored.filter((q) => q.key !== META).map((q) => q.resource), ...kept])) {
|
|
292
|
+
fresh2.push({ kind: "prune", resource, keep: [], before: startedAt });
|
|
293
|
+
}
|
|
294
|
+
await cache.write(scope, [...fresh2, meta()]);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const reads = stored.filter((q) => q.key !== META);
|
|
298
|
+
const fresh = reads.filter((q) => Date.now() - q.fetchedAt <= maxAge && kept.has(q.resource)).sort((a, b) => b.fetchedAt - a.fetchedAt).slice(0, maxReads);
|
|
299
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
300
|
+
for (const q of reads) if (!wanted.has(q.resource)) wanted.set(q.resource, /* @__PURE__ */ new Set());
|
|
301
|
+
for (const q of fresh) refsIn(q.data, wanted.get(q.resource));
|
|
302
|
+
const rowsOf = /* @__PURE__ */ new Map();
|
|
303
|
+
for (const [resource, ids] of wanted) {
|
|
304
|
+
if (ids.size === 0) continue;
|
|
305
|
+
const rows = await cache.readRows(scope, resource, [...ids]);
|
|
306
|
+
rowsOf.set(resource, new Map(rows.map((r) => [r.id, r.row])));
|
|
307
|
+
}
|
|
308
|
+
if (stale()) return;
|
|
309
|
+
for (const q of fresh) {
|
|
310
|
+
const data = join(q.data, rowsOf.get(q.resource) ?? /* @__PURE__ */ new Map());
|
|
311
|
+
if (data === void 0) continue;
|
|
312
|
+
const existing = queryClient.getQueryState(q.queryKey);
|
|
313
|
+
if (existing?.data !== void 0 && existing.dataUpdatedAt >= q.fetchedAt) continue;
|
|
314
|
+
queryClient.setQueryData(q.queryKey, data, { updatedAt: q.fetchedAt });
|
|
315
|
+
}
|
|
316
|
+
const sweep = reads.filter((q) => !fresh.includes(q)).map((q) => ({ kind: "forget", key: q.key, before: startedAt }));
|
|
317
|
+
for (const [resource, ids] of wanted) sweep.push({ kind: "prune", resource, keep: [...ids], before: startedAt });
|
|
318
|
+
if (sweep.length) await cache.write(scope, sweep);
|
|
319
|
+
} catch {
|
|
320
|
+
await cache.clear({ scope }).catch(() => void 0);
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
const subscribe = (raw, options2 = {}) => {
|
|
324
|
+
const scope = toScope(raw);
|
|
325
|
+
if (!scope) return () => {
|
|
326
|
+
};
|
|
327
|
+
const mine = ++saves;
|
|
328
|
+
people.add(scope.slice(2, scope.indexOf("|")));
|
|
329
|
+
const pending = /* @__PURE__ */ new Map();
|
|
330
|
+
if (options2.refresh) {
|
|
331
|
+
for (const query of queryClient.getQueryCache().getAll()) {
|
|
332
|
+
if (keptQuery(query) && query.state.fetchStatus === "fetching") void query.cancel({ revert: true });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const before = options2.adopt ? /* @__PURE__ */ new Set() : new Set(queryClient.getQueryCache().getAll().filter((q) => q.state.fetchStatus === "fetching").map((q) => q.queryHash));
|
|
336
|
+
let timer;
|
|
337
|
+
let first = true;
|
|
338
|
+
const flush = () => {
|
|
339
|
+
timer = void 0;
|
|
340
|
+
if (mine !== saves || pending.size === 0) return;
|
|
341
|
+
const ops = first ? [meta()] : [];
|
|
342
|
+
const newest = /* @__PURE__ */ new Map();
|
|
343
|
+
first = false;
|
|
344
|
+
for (const read of pending.values()) {
|
|
345
|
+
if (queryClient.getQueryCache().get(read.query.queryHash) !== read.query) continue;
|
|
346
|
+
const [resource, kind, params, detailSelect] = read.queryKey;
|
|
347
|
+
const select = kind === "detail" ? detailSelect : params?.select;
|
|
348
|
+
const key = keyText(read.queryKey);
|
|
349
|
+
if (kind === "detail" && read.data == null) {
|
|
350
|
+
const id = read.queryKey[2];
|
|
351
|
+
ops.push({ kind: "forget", key });
|
|
352
|
+
if (select === void 0 && id != null) ops.push({ kind: "drop", resource, id: String(id) });
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
const rows = [];
|
|
356
|
+
const data = split(kind, select, read.data, rows);
|
|
357
|
+
if (data === null) continue;
|
|
358
|
+
for (const row of rows) {
|
|
359
|
+
const k = `${resource}\0${String(row.id)}`;
|
|
360
|
+
const seen = newest.get(k);
|
|
361
|
+
if (!seen || seen.fetchedAt <= read.fetchedAt) newest.set(k, { resource, id: String(row.id), row, fetchedAt: read.fetchedAt });
|
|
362
|
+
}
|
|
363
|
+
ops.push({ kind: "query", query: { key, queryKey: read.queryKey, resource, data, fetchedAt: read.fetchedAt } });
|
|
364
|
+
}
|
|
365
|
+
pending.clear();
|
|
366
|
+
for (const row of newest.values()) ops.push({ kind: "row", row });
|
|
367
|
+
if (ops.length) void cache.write(scope, ops).catch(() => void 0);
|
|
368
|
+
};
|
|
369
|
+
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
|
370
|
+
if (event.type !== "updated" || mine !== saves) return;
|
|
371
|
+
const action = event.action;
|
|
372
|
+
if (action.type !== "success" || action.manual) return;
|
|
373
|
+
if (queryClient.getQueryCache().get(event.query.queryHash) !== event.query) return;
|
|
374
|
+
if (before.delete(event.query.queryHash)) return;
|
|
375
|
+
if (!keptQuery(event.query)) return;
|
|
376
|
+
const { data, dataUpdatedAt } = event.query.state;
|
|
377
|
+
pending.set(event.query.queryHash, { query: event.query, queryKey: event.query.queryKey, data, fetchedAt: dataUpdatedAt });
|
|
378
|
+
timer ??= setTimeout(flush, throttleMs);
|
|
379
|
+
});
|
|
380
|
+
if (options2.refresh) {
|
|
381
|
+
const infinite = (query) => keptQuery(query) && query.queryKey[1] === "infinite";
|
|
382
|
+
void queryClient.resetQueries({ predicate: infinite }).catch(() => void 0);
|
|
383
|
+
void queryClient.invalidateQueries({ predicate: (query) => keptQuery(query) && !infinite(query) }).catch(() => void 0);
|
|
384
|
+
}
|
|
385
|
+
if (options2.adopt) {
|
|
386
|
+
for (const query of queryClient.getQueryCache().getAll()) {
|
|
387
|
+
const read = fetched.get(query);
|
|
388
|
+
if (!read || read.data === void 0 || !keptQuery(query)) continue;
|
|
389
|
+
pending.set(query.queryHash, { query, queryKey: query.queryKey, data: read.data, fetchedAt: read.fetchedAt });
|
|
390
|
+
}
|
|
391
|
+
if (pending.size) timer ??= setTimeout(flush, throttleMs);
|
|
392
|
+
}
|
|
393
|
+
return () => {
|
|
394
|
+
unsubscribe();
|
|
395
|
+
if (timer) clearTimeout(timer);
|
|
396
|
+
flush();
|
|
397
|
+
};
|
|
398
|
+
};
|
|
399
|
+
const clear = async () => {
|
|
400
|
+
restores += 1;
|
|
401
|
+
saves += 1;
|
|
402
|
+
const everyone = [...people];
|
|
403
|
+
people.clear();
|
|
404
|
+
if (everyone.length === 0) await cache.clear();
|
|
405
|
+
else for (const user of everyone) await cache.clear({ user });
|
|
406
|
+
};
|
|
407
|
+
return { restore, subscribe, clear };
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export { cacheScope, indexedDbLocalCache, memoryLocalCache, persistOffline };
|
|
412
|
+
//# sourceMappingURL=index.js.map
|
|
413
|
+
//# sourceMappingURL=index.js.map
|