@blaze-cache/react-query 0.2.3-beta → 0.3.0-beta.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 CHANGED
@@ -44,11 +44,17 @@ up with TanStack's own hashing, so a custom `queryKeyHashFn` is honoured.
44
44
  ## Behaviour
45
45
 
46
46
  * Successful fetches and `setQueryData` are written to the shared cache.
47
- * An **explicit** `removeQueries` or `clear` deletes from it. Ordinary garbage
47
+ * An **explicit** `removeQueries` or `clear` deletes from it — and only when the value
48
+ under the key is a mirror record (carries `dataUpdatedAt`), so a foreign entry parked
49
+ at a colliding key on a shared cache survives the removal. Ordinary garbage
48
50
  collection — a query left unobserved past `gcTime` — deliberately does **not**: that
49
51
  is in-session housekeeping, and the persisted copy is what paints the next session.
50
52
  * Invalidation keeps the data too, so stale-while-revalidate always has something to
51
53
  paint.
54
+ * A refetch rewrites the record with the *existing* entry's tags and TTL when it has
55
+ them: a helper that wrote `tags: ['todos']` under a short TTL keeps both across
56
+ refetches instead of being re-stamped with the sync defaults. No reader on the cache
57
+ (or no existing record) falls back to the defaults, exactly as before.
52
58
  * Renders never touch cache statistics: the pre-fetch lookup prefers `peek` over `get`,
53
59
  so StrictMode's double render cannot move the hit rate or influence eviction.
54
60
  * That holds for events too — `peek` emits nothing, so renders are silent; the writes the
@@ -63,6 +69,136 @@ up with TanStack's own hashing, so a custom `queryKeyHashFn` is honoured.
63
69
  * Error states stay in TanStack — only data crosses into the cache.
64
70
  * TanStack owns freshness *within* a session; Blaze Cache owns it *across* sessions.
65
71
 
72
+ ## API
73
+
74
+ The integration is one cache + a set of hooks, helpers and hydration functions. All of
75
+ them take `(cache, client?, options?)` — the cache first, then the `QueryClient` (from
76
+ context when omitted by a hook), then the options.
77
+
78
+ | Export | What it does |
79
+ | --- | --- |
80
+ | `createBlazeQueryClient` / `syncBlazeQueryCache` | Mirror TanStack cache writes into the Blaze Cache (see [Behaviour](#behaviour)). |
81
+ | `useBlazeQuery` | `useQuery` seeded from the mirror. |
82
+ | `useBlazeInfiniteQuery` | `useInfiniteQuery` seeded with the whole `InfiniteData` (all pages) as `initialData` — only for `InfiniteData`-shaped records; a plain record under the key is left unseeded. |
83
+ | `useBlazeQueries` | `useQueries` over several keys, each seeded independently. |
84
+ | `useBlazeMutation` | `useMutation` that invalidates queries after success. |
85
+ | `prefetchBlazeQuery` | Imperatively seed + prefetch, mirroring the fetched result. |
86
+ | `setBlazeQueryData` | Write data through to the mirror (TanStack first, then Blaze). |
87
+ | `invalidateBlazeQueries` | Invalidate in TanStack **and** purge the mirror. |
88
+ | `removeBlazeQueries` | Remove from TanStack **and** purge the mirror. |
89
+ | `dehydrateBlazeQueryClient` / `hydrateBlazeQueryClient` | Serialize / restore the mirror as a TanStack `DehydratedState`. |
90
+
91
+ ## Example usage
92
+
93
+ ### `useBlazeQuery` — instant first paint
94
+
95
+ ```tsx
96
+ import { useBlazeQuery } from '@blaze-cache/react-query';
97
+
98
+ function Todos({ userId }: { userId: string }) {
99
+ const todos = useBlazeQuery(cache, {
100
+ queryKey: ['todos', userId],
101
+ queryFn: () => api.get('/todos', { userId }).then((r) => r.data),
102
+ });
103
+ // renders cached data immediately; refetches stale data in the background
104
+ }
105
+ ```
106
+
107
+ ### `useBlazeInfiniteQuery` — instant first paint for infinite lists
108
+
109
+ ```tsx
110
+ const feed = useBlazeInfiniteQuery(cache, {
111
+ queryKey: ['feed', userId],
112
+ queryFn: ({ pageParam }) => api.get('/feed', { userId, pageParam }),
113
+ initialPageParam: 0,
114
+ getNextPageParam: (lastPage) => lastPage.nextCursor,
115
+ });
116
+ // feed.data?.pages — every page cached before the reload, immediately
117
+ ```
118
+
119
+ The whole `InfiniteData` payload (pages + page params) is mirrored as one entry and seeded
120
+ back as `initialData`, with the original `dataUpdatedAt`, so the first paint after a reload
121
+ shows all previously loaded pages while TanStack still refetches. Only a record that
122
+ really holds `InfiniteData` (`pages` and `pageParams` arrays) seeds: a plain value under
123
+ the key — a `setBlazeQueryData` write, or a query that changed shape — is left alone and
124
+ the query fetches normally instead of crashing on `data.pages.map`.
125
+
126
+ ### `useBlazeQueries` — parallel instant first paint
127
+
128
+ ```tsx
129
+ const [profile, settings, notifications] = useBlazeQueries(cache, {
130
+ queries: [
131
+ { queryKey: ['profile', userId], queryFn: () => api.profile(userId) },
132
+ { queryKey: ['settings'], queryFn: () => api.settings },
133
+ { queryKey: ['notifications', userId], queryFn: () => api.notifications(userId) },
134
+ ],
135
+ });
136
+ ```
137
+
138
+ ### `useBlazeMutation` — keep the mirror in sync after writes
139
+
140
+ ```tsx
141
+ const addTodo = useBlazeMutation(cache, {
142
+ mutationFn: (text: string) => api.post('/todos', { userId, text }),
143
+ invalidate: { queryKey: ['todos', userId] }, // or { tags: ['todos', `user:${userId}`] }
144
+ onSuccess: (data) => toast('Todo added'),
145
+ });
146
+ ```
147
+
148
+ On success the mutation invalidates the given queries — TanStack marks them stale (active
149
+ ones refetch) and the matching persisted records are purged, so a reload cannot paint
150
+ pre-write data. Your own `onSuccess` still runs first, and invalidation is skipped if it
151
+ throws.
152
+
153
+ ### `prefetchBlazeQuery` — warm the mirror before navigation
154
+
155
+ ```ts
156
+ await prefetchBlazeQuery(cache, queryClient, {
157
+ queryKey: ['todos', userId],
158
+ queryFn: () => api.get('/todos', { userId }).then((r) => r.data),
159
+ staleTime: 5 * 60_000, // serve within the window from the mirror
160
+ });
161
+ ```
162
+
163
+ ### `setBlazeQueryData` — write through to the mirror
164
+
165
+ ```ts
166
+ setBlazeQueryData(cache, queryClient, ['settings', userId], settings, {
167
+ tags: ['settings', `user:${userId}`],
168
+ });
169
+ ```
170
+
171
+ ### `invalidateBlazeQueries` / `removeBlazeQueries` — purge persisted data on writes
172
+
173
+ ```ts
174
+ // After a mutation that changes a list:
175
+ await invalidateBlazeQueries(cache, queryClient, { queryKey: ['todos', userId] });
176
+ // …or by tag, which also covers queries from earlier sessions:
177
+ invalidateBlazeQueries(cache, queryClient, { tags: ['todos', `user:${userId}`] });
178
+
179
+ removeBlazeQueries(cache, queryClient, { tags: ['todos', `user:${userId}`] }); // after logout
180
+ removeBlazeQueries(cache, queryClient); // every mirror record — and only those
181
+ ```
182
+
183
+ Purges are scoped to **mirror records** (the `dataUpdatedAt` shape TanStack writes), so on
184
+ a cache shared with `@blaze-cache/axios`, `@blaze-cache/fetch` or `@blaze-cache/swr` they
185
+ leave other integrations' entries alone — including unfiltered calls and tag purges, even
186
+ when a caller domain tag (`'todos'`) is one the other integrations also use. The selection
187
+ enumerates `entries()`, so the concrete `BlazeCache` (or anything with `entries`) is
188
+ required for tag and non-exact-key filters.
189
+
190
+ ### `dehydrateBlazeQueryClient` / `hydrateBlazeQueryClient` — server-side persistence
191
+
192
+ ```ts
193
+ // Server: serialize whatever the mirror holds for this request.
194
+ const dehydratedState = dehydrateBlazeQueryClient(cache);
195
+
196
+ // Client: restore into the (synced) client, then keep it persisted again.
197
+ hydrateBlazeQueryClient(cache, queryClient, dehydratedState, {
198
+ tags: ['ssr', `user:${userId}`],
199
+ });
200
+ ```
201
+
66
202
  ## Documentation
67
203
 
68
204
  Setup and the full integration reference live in the
@@ -73,6 +209,8 @@ Setup and the full integration reference live in the
73
209
  * [`@blaze-cache/core`](https://www.npmjs.com/package/@blaze-cache/core) — the cache itself
74
210
  * [`@blaze-cache/axios`](https://www.npmjs.com/package/@blaze-cache/axios) — HTTP adapter
75
211
  * [`@blaze-cache/fetch`](https://www.npmjs.com/package/@blaze-cache/fetch) — drop-in `fetch()` replacement
212
+ * [`@blaze-cache/ky`](https://www.npmjs.com/package/@blaze-cache/ky) — ky hooks (v1 and v2)
213
+ * [`@blaze-cache/swr`](https://www.npmjs.com/package/@blaze-cache/swr) — SWR middleware + hook
76
214
 
77
215
  ## License
78
216
 
@@ -0,0 +1,74 @@
1
+ import type { DehydratedState, HydrateOptions, QueryClient } from '@tanstack/react-query';
2
+ import type { BlazeMirrorOptions, BlazeQueryCacheLike, BlazeQueryRecord } from './types.js';
3
+ /** Options for {@link dehydrateBlazeQueryClient}. */
4
+ export interface DehydrateBlazeOptions {
5
+ /**
6
+ * Transforms each record's `data` before it lands in the snapshot — the same escape
7
+ * hatch as TanStack's `DehydrateOptions.serializeData`, for data that is not
8
+ * JSON-serializable as-is (Dates, Map, class instances).
9
+ */
10
+ serializeData?: (data: unknown) => unknown;
11
+ /**
12
+ * Include only records this predicate accepts — filter by key, tag (via
13
+ * `cache.entries()`), age (`dataUpdatedAt`), anything readable from the record.
14
+ *
15
+ * ```ts
16
+ * dehydrateBlazeQueryClient(cache, {
17
+ * predicate: (record) => record.dataUpdatedAt > Date.now() - 60_000,
18
+ * });
19
+ * ```
20
+ */
21
+ predicate?: (record: BlazeQueryRecord, queryHash: string) => boolean;
22
+ }
23
+ /** Options for {@link hydrateBlazeQueryClient}. */
24
+ export interface HydrateBlazeOptions extends BlazeMirrorOptions {
25
+ /** Forwarded to TanStack's `hydrate` — per-query defaults, `deserializeData`, … */
26
+ defaultOptions?: HydrateOptions['defaultOptions'];
27
+ }
28
+ /**
29
+ * Builds a TanStack `DehydratedState` from the persisted Blaze mirror alone — no
30
+ * `QueryClient` involved.
31
+ *
32
+ * Every live record that carries a `queryKey` becomes a `DehydratedQuery` filed under its
33
+ * mirror key (which *is* the query hash), with `dataUpdatedAt` preserved so the restored
34
+ * session's staleness arithmetic matches the original one. Embed the result in server
35
+ * markup and call {@link hydrateBlazeQueryClient} on the client for a first paint with
36
+ * zero network and zero re-read of IndexedDB.
37
+ *
38
+ * ```ts
39
+ * const state = dehydrateBlazeQueryClient(cache);
40
+ * // … in the server response:
41
+ * `<script>window.__HYDRATED__ = ${JSON.stringify(state)}</script>`;
42
+ * ```
43
+ *
44
+ * Rejections follow the package's rule of never under-delivering silently: records written
45
+ * before `queryKey` existed cannot be rebuilt and are skipped (they still seed the hooks
46
+ * directly), and a cache without `entries()` throws rather than returning a hollow
47
+ * snapshot.
48
+ *
49
+ * Infinite queries round trip too: the record's `queryType` is carried through, so
50
+ * `hydrate` rebuilds them as infinite queries with all their pages intact.
51
+ */
52
+ export declare function dehydrateBlazeQueryClient(cache: BlazeQueryCacheLike, options?: DehydrateBlazeOptions): DehydratedState;
53
+ /**
54
+ * Restores a `DehydratedState` into a `QueryClient` **and** persists it in the Blaze
55
+ * Cache — the counterpart to {@link dehydrateBlazeQueryClient}, and the durable half of
56
+ * TanStack's plain `hydrate`.
57
+ *
58
+ * TanStack's hydration is in-session only: its result lives in the query cache and dies
59
+ * with the tab. This writes each restored query back into the mirror as well (self-
60
+ * describing `queryKey`/`queryType`, original `dataUpdatedAt`, per-call `ttlMs`/`tags`),
61
+ * so the state you just hydrated is what the *next* session paints from — which is
62
+ * exactly the server-payload flow: hydrate on arrival, persist for the reload after.
63
+ *
64
+ * The mirror write reads each query back from TanStack **after** hydration, so whatever
65
+ * `deserializeData` produced and TanStack's "keep the newer data" rule are what gets
66
+ * persisted — TanStack remains the source of truth for the values.
67
+ *
68
+ * ```ts
69
+ * const state = JSON.parse(window.__HYDRATED__) as DehydratedState;
70
+ * hydrateBlazeQueryClient(cache, client, state, { tags: ['ssr', 'user:42'] });
71
+ * ```
72
+ */
73
+ export declare function hydrateBlazeQueryClient(cache: BlazeQueryCacheLike, client: QueryClient, dehydratedState: Partial<DehydratedState>, options?: HydrateBlazeOptions): void;
74
+ //# sourceMappingURL=hydration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration.d.ts","sourceRoot":"","sources":["../src/hydration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAI1F,OAAO,KAAK,EACV,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAKpB,qDAAqD;AACrD,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC;IAC3C;;;;;;;;;OASG;IACH,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;CACtE;AAED,mDAAmD;AACnD,MAAM,WAAW,mBAAoB,SAAQ,kBAAkB;IAC7D,mFAAmF;IACnF,cAAc,CAAC,EAAE,cAAc,CAAC,gBAAgB,CAAC,CAAC;CACnD;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,mBAAmB,EAC1B,OAAO,GAAE,qBAA0B,GAClC,eAAe,CA6CjB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,mBAAmB,EAC1B,MAAM,EAAE,WAAW,EACnB,eAAe,EAAE,OAAO,CAAC,eAAe,CAAC,EACzC,OAAO,CAAC,EAAE,mBAAmB,GAC5B,IAAI,CAuBN"}
@@ -0,0 +1,107 @@
1
+ import { hydrate } from '@tanstack/react-query';
2
+ import { isMirrorRecord } from './record.js';
3
+ import { DEFAULT_TAGS, DEFAULT_TTL_MS } from './sync.js';
4
+ /**
5
+ * Builds a TanStack `DehydratedState` from the persisted Blaze mirror alone — no
6
+ * `QueryClient` involved.
7
+ *
8
+ * Every live record that carries a `queryKey` becomes a `DehydratedQuery` filed under its
9
+ * mirror key (which *is* the query hash), with `dataUpdatedAt` preserved so the restored
10
+ * session's staleness arithmetic matches the original one. Embed the result in server
11
+ * markup and call {@link hydrateBlazeQueryClient} on the client for a first paint with
12
+ * zero network and zero re-read of IndexedDB.
13
+ *
14
+ * ```ts
15
+ * const state = dehydrateBlazeQueryClient(cache);
16
+ * // … in the server response:
17
+ * `<script>window.__HYDRATED__ = ${JSON.stringify(state)}</script>`;
18
+ * ```
19
+ *
20
+ * Rejections follow the package's rule of never under-delivering silently: records written
21
+ * before `queryKey` existed cannot be rebuilt and are skipped (they still seed the hooks
22
+ * directly), and a cache without `entries()` throws rather than returning a hollow
23
+ * snapshot.
24
+ *
25
+ * Infinite queries round trip too: the record's `queryType` is carried through, so
26
+ * `hydrate` rebuilds them as infinite queries with all their pages intact.
27
+ */
28
+ export function dehydrateBlazeQueryClient(cache, options = {}) {
29
+ if (!cache.entries) {
30
+ throw new Error('[blaze-cache/react-query] Dehydrating the mirror must enumerate every persisted ' +
31
+ 'entry, but the cache does not implement `entries()`. Refusing to return an ' +
32
+ 'empty snapshot.');
33
+ }
34
+ const queries = [];
35
+ for (const entry of cache.entries()) {
36
+ // Shape gate first: a cache shared with another integration can hold foreign values,
37
+ // and only a mirror record carries the `data`/`dataUpdatedAt` pair a dehydrated query
38
+ // needs — an axios body would dehydrate as data dated `undefined`. Pre-`queryKey`
39
+ // records still skip, as before: they cannot be rebuilt into a TanStack query.
40
+ if (!isMirrorRecord(entry.value))
41
+ continue;
42
+ const record = entry.value;
43
+ if (record.queryKey === undefined)
44
+ continue;
45
+ if (options.predicate && !options.predicate(record, entry.key))
46
+ continue;
47
+ queries.push({
48
+ queryHash: entry.key,
49
+ queryKey: record.queryKey,
50
+ // Freshness comes from `dataUpdatedAt`; `dehydratedAt` is simply "now", as in
51
+ // TanStack's own `dehydrateQuery`.
52
+ dehydratedAt: Date.now(),
53
+ ...(record.queryType ? { queryType: record.queryType } : null),
54
+ state: {
55
+ data: options.serializeData ? options.serializeData(record.data) : record.data,
56
+ dataUpdateCount: 1,
57
+ dataUpdatedAt: record.dataUpdatedAt,
58
+ error: null,
59
+ errorUpdateCount: 0,
60
+ errorUpdatedAt: 0,
61
+ fetchFailureCount: 0,
62
+ fetchFailureReason: null,
63
+ fetchMeta: null,
64
+ isInvalidated: false,
65
+ status: 'success',
66
+ fetchStatus: 'idle',
67
+ },
68
+ });
69
+ }
70
+ return { mutations: [], queries };
71
+ }
72
+ /**
73
+ * Restores a `DehydratedState` into a `QueryClient` **and** persists it in the Blaze
74
+ * Cache — the counterpart to {@link dehydrateBlazeQueryClient}, and the durable half of
75
+ * TanStack's plain `hydrate`.
76
+ *
77
+ * TanStack's hydration is in-session only: its result lives in the query cache and dies
78
+ * with the tab. This writes each restored query back into the mirror as well (self-
79
+ * describing `queryKey`/`queryType`, original `dataUpdatedAt`, per-call `ttlMs`/`tags`),
80
+ * so the state you just hydrated is what the *next* session paints from — which is
81
+ * exactly the server-payload flow: hydrate on arrival, persist for the reload after.
82
+ *
83
+ * The mirror write reads each query back from TanStack **after** hydration, so whatever
84
+ * `deserializeData` produced and TanStack's "keep the newer data" rule are what gets
85
+ * persisted — TanStack remains the source of truth for the values.
86
+ *
87
+ * ```ts
88
+ * const state = JSON.parse(window.__HYDRATED__) as DehydratedState;
89
+ * hydrateBlazeQueryClient(cache, client, state, { tags: ['ssr', 'user:42'] });
90
+ * ```
91
+ */
92
+ export function hydrateBlazeQueryClient(cache, client, dehydratedState, options) {
93
+ hydrate(client, dehydratedState, options?.defaultOptions ? { defaultOptions: options.defaultOptions } : undefined);
94
+ for (const dehydrated of dehydratedState.queries ?? []) {
95
+ const query = client.getQueryCache().get(dehydrated.queryHash);
96
+ const data = query?.state.data;
97
+ if (!query || data === undefined)
98
+ continue; // nothing landed — nothing to persist
99
+ cache.set(dehydrated.queryHash, {
100
+ data,
101
+ dataUpdatedAt: query.state.dataUpdatedAt,
102
+ queryKey: dehydrated.queryKey,
103
+ ...(query.queryType === 'infinite' ? { queryType: 'infinite' } : null),
104
+ }, { ttlMs: options?.ttlMs ?? DEFAULT_TTL_MS, tags: options?.tags ?? DEFAULT_TAGS });
105
+ }
106
+ }
107
+ //# sourceMappingURL=hydration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration.js","sourceRoot":"","sources":["../src/hydration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAGhD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAqCzD;;;;;;;;;;;;;;;;;;;;;;;GAuBG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YAAY,EAAE,CACjF,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -0,0 +1,101 @@
1
+ import type { DefaultError, FetchQueryOptions, QueryClient, QueryKey } from '@tanstack/react-query';
2
+ import type { BlazeMirrorOptions, BlazeQueryCacheLike, BlazeQueryFilters } from './types.js';
3
+ /**
4
+ * The options {@link prefetchBlazeQuery} accepts: TanStack's own `FetchQueryOptions` plus
5
+ * how the fetched result should be stamped into the Blaze Cache.
6
+ */
7
+ export interface BlazeFetchQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey> {
8
+ /** TTL for the mirror entry. Defaults to the same 24 h the sync layer uses. */
9
+ ttlMs?: number;
10
+ /** Tags for the mirror entry. Defaults to `['react-query']`. */
11
+ tags?: readonly string[];
12
+ }
13
+ /**
14
+ * `prefetchQuery` that starts from the Blaze Cache.
15
+ *
16
+ * Mirrors {@link useBlazeQuery} imperatively: the persisted record is seeded as
17
+ * `initialData` with its original `dataUpdatedAt` before prefetching, so a `staleTime`
18
+ * window can be satisfied from disk without touching the network at all. When a fetch
19
+ * does run, its result is written back to the mirror under the same record (tags, TTL and
20
+ * self-describing `queryKey` included) — even on a client with no sync layer attached.
21
+ *
22
+ * Errors are swallowed exactly like TanStack's `prefetchQuery`.
23
+ *
24
+ * ```ts
25
+ * await prefetchBlazeQuery(cache, client, {
26
+ * queryKey: ['todos', userId],
27
+ * queryFn: () => fetchTodos(userId),
28
+ * staleTime: 5 * 60_000,
29
+ * tags: ['todos', `user:${userId}`],
30
+ * });
31
+ * ```
32
+ */
33
+ export declare function prefetchBlazeQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(cache: BlazeQueryCacheLike, client: QueryClient, options: BlazeFetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
34
+ /**
35
+ * `setQueryData` that also writes the Blaze Cache mirror.
36
+ *
37
+ * The TanStack write goes through first (so its exact `dataUpdatedAt` — and structural
38
+ * sharing, which may keep the previous object — is what both caches record), then the
39
+ * mirror is written synchronously under the resolved query hash, tagged per `options`.
40
+ * With a sync layer attached, its batched write sees this identical record and leaves the
41
+ * helper's `ttlMs`/`tags` in place.
42
+ *
43
+ * `data` is a plain value, not an updater — pass a function to TanStack's own
44
+ * `client.setQueryData` when you need to read the previous value first. `undefined` is
45
+ * ignored on both sides, exactly as TanStack ignores it.
46
+ *
47
+ * ```ts
48
+ * setBlazeQueryData(cache, client, ['settings', userId], settings, {
49
+ * tags: ['settings', `user:${userId}`],
50
+ * });
51
+ * ```
52
+ *
53
+ * @returns The stored data, or `undefined` when `data` was `undefined`.
54
+ */
55
+ export declare function setBlazeQueryData<TData = unknown, TQueryKey extends QueryKey = QueryKey>(cache: BlazeQueryCacheLike, client: QueryClient, queryKey: TQueryKey, data: TData, options?: BlazeMirrorOptions): TData | undefined;
56
+ /**
57
+ * `invalidateQueries` for both caches at once: TanStack marks the matching queries stale
58
+ * (active ones refetch, as usual), and the matching **persisted** records are purged so a
59
+ * reload cannot paint pre-invalidation data.
60
+ *
61
+ * Keeping the mirror entry instead would defeat the call — `dataUpdatedAt` is TanStack's
62
+ * staleness clock, and a persisted record would come back as `initialData` on the next
63
+ * session regardless of when it was invalidated. In-session behaviour is untouched:
64
+ * the refetched results re-mirror themselves through the sync layer, stale-while-revalidate
65
+ * included. This mirrors the sync layer's own contract that *explicit* purges remove
66
+ * mirror entries (see {@link syncBlazeQueryCache}).
67
+ *
68
+ * Filters work on both sides; see {@link BlazeQueryFilters} for how `tags`, keys and
69
+ * query-state selectors combine. Purging by tag or by non-exact key needs
70
+ * `cache.entries` — both **throw** when it is absent rather than under-delivering.
71
+ * (Tag purges deliberately enumerate rather than call `cache.invalidateTags`: the core's
72
+ * tag index is one global namespace, so that call would reach other integrations' entries
73
+ * on a shared cache. Enumeration keeps the purge on mirror records — see
74
+ * {@link isMirrorRecord}.)
75
+ *
76
+ * ```ts
77
+ * await invalidateBlazeQueries(cache, client, { queryKey: ['todos', userId] });
78
+ * await invalidateBlazeQueries(cache, client, { tags: [`user:${userId}`] });
79
+ * ```
80
+ *
81
+ * @returns Resolves like TanStack's `invalidateQueries` — once the triggered refetches settle.
82
+ */
83
+ export declare function invalidateBlazeQueries(cache: BlazeQueryCacheLike, client: QueryClient, filters?: BlazeQueryFilters): Promise<void>;
84
+ /**
85
+ * `removeQueries` for both caches at once: TanStack drops the matching queries outright,
86
+ * and the matching persisted records are purged — the explicit-purge half of the sync
87
+ * layer's contract (see {@link syncBlazeQueryCache}).
88
+ *
89
+ * The same mirror-side rules and rejections as {@link invalidateBlazeQueries} apply; the
90
+ * difference between the two helpers is what happens on TanStack's side (dropped vs.
91
+ * marked stale), not what happens in the mirror.
92
+ *
93
+ * ```ts
94
+ * // After a logout — including queries from earlier sessions TanStack never loaded:
95
+ * removeBlazeQueries(cache, client, { tags: [`user:${userId}`] });
96
+ * // Every mirror record — and only those, so foreign entries on a shared cache stay:
97
+ * removeBlazeQueries(cache, client);
98
+ * ```
99
+ */
100
+ export declare function removeBlazeQueries(cache: BlazeQueryCacheLike, client: QueryClient, filters?: BlazeQueryFilters): void;
101
+ //# sourceMappingURL=imperative.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imperative.d.ts","sourceRoot":"","sources":["../src/imperative.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EACZ,iBAAiB,EACjB,WAAW,EAEX,QAAQ,EAET,MAAM,uBAAuB,CAAC;AAM/B,OAAO,KAAK,EAEV,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,MAAM,WAAW,sBAAsB,CACrC,YAAY,GAAG,OAAO,EACtB,MAAM,GAAG,YAAY,EACrB,KAAK,GAAG,YAAY,EACpB,SAAS,SAAS,QAAQ,GAAG,QAAQ,CACrC,SAAQ,iBAAiB,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