Open History to see the last commit
1import { BroadcastChannel } from 'broadcast-channel'
2import type { BroadcastChannelOptions } from 'broadcast-channel'
3import type { QueryClient, QueryKey } from '@tanstack/query-core'
4β
5/**
6 * Metadata describing a broadcast that failed to be delivered to other tabs.
7 * Passed to {@link BroadcastQueryClientOptions.onBroadcastError} so callers
8 * can correlate failures with the originating query.
9 */
10export interface BroadcastErrorEvent {
11 type: 'updated' | 'removed' | 'added'
12 queryHash: string
13 queryKey: QueryKey
14}
15β
16type BroadcastMessage =
17 | { type: 'updated'; queryHash: string; queryKey: QueryKey; state: unknown }
18 | { type: 'removed'; queryHash: string; queryKey: QueryKey }
19 | { type: 'added'; queryHash: string; queryKey: QueryKey; state: unknown }
20β
21interface BroadcastQueryClientOptions {
22 /** The QueryClient to sync. */
23 queryClient: QueryClient
24 /**
25 * Unique channel name used to communicate between tabs and windows.
26 * @default 'tanstack-query'
27 */
28 broadcastChannel?: string
29 /** Options forwarded to the underlying `BroadcastChannel`. */
30 options?: BroadcastChannelOptions
31 /**
32 * Called when a query event fails to broadcast to other tabs β most
33 * commonly because the query's `state.data`, `state.error`, or `queryKey`
34 * contains a value the structured-clone algorithm cannot serialize
35 * (e.g. `ReadableStream`, `File`, functions, Vue `reactive` proxies).
36 *
37 * Provide this to route failures to an error tracker. If omitted, a
38 * `console.warn` is emitted in development so failures are never silent.
39 *
40 * May return a `Promise`; any rejection is caught internally so it cannot
41 * cause a secondary unhandled rejection.
42 */
43 onBroadcastError?: (
44 error: unknown,
45 event: BroadcastErrorEvent,
46 ) => void | Promise<void>
47}
48β
49export function broadcastQueryClient({
50 queryClient,
51 broadcastChannel = 'tanstack-query',
52 options,
53 onBroadcastError,
54}: BroadcastQueryClientOptions): () => void {
55 let transaction = false
56 const tx = (cb: () => void) => {
57 transaction = true
58 try {
59 cb()
60 } finally {
61 // Guard against `cb` throwing (e.g. `query.setState`/`queryCache.build`
62 // triggering a listener that throws while applying an incoming
63 // cross-tab message). Without this, `transaction` would stay `true`
64 // forever, silently disabling this tab's own broadcasts to other tabs
65 // for the rest of the session.
66 transaction = false
67 }
68 }
69β
70 const channel = new BroadcastChannel(broadcastChannel, {
71 webWorkerSupport: false,
72 ...options,
73 })
74β
75 const queryCache = queryClient.getQueryCache()
76β
77 const safePost = (message: BroadcastMessage): void => {
78 channel.postMessage(message).catch((error: unknown) => {
79 const event: BroadcastErrorEvent = {
80 type: message.type,
81 queryHash: message.queryHash,
82 queryKey: message.queryKey,
83 }
84β
85 if (onBroadcastError) {
86 const warnCallbackError = (callbackError: unknown) => {
87 if (process.env.NODE_ENV !== 'production') {
88 console.warn(
89 `[broadcastQueryClient] onBroadcastError threw while handling "${event.type}" for query ${event.queryHash}.`,
90 callbackError,
91 )
92 }
93 }
94 let result: void | Promise<void>
95 try {
96 result = onBroadcastError(error, event)
97 } catch (callbackError) {
98 warnCallbackError(callbackError)
99 return
100 }
101 result?.catch(warnCallbackError)
102 } else if (process.env.NODE_ENV !== 'production') {
103 console.warn(
104 `[broadcastQueryClient] Failed to broadcast "${event.type}" event for query ${event.queryHash}. ` +
105 'The query value could not be structured-cloned; cross-tab sync for this query was skipped.',
106 error,
107 )
108 }
109 })
110 }
111β
112 const unsubscribe = queryCache.subscribe((queryEvent) => {
113 if (transaction) {
114 return
115 }
116β
117 const {
118 query: { queryHash, queryKey, state, observers },
119 } = queryEvent
120β
121 if (queryEvent.type === 'updated' && queryEvent.action.type === 'success') {
122 safePost({
123 type: 'updated',
124 queryHash,
125 queryKey,
126 state,
127 })
128 }
129β
130 if (queryEvent.type === 'removed' && observers.length > 0) {
131 safePost({
132 type: 'removed',
133 queryHash,
134 queryKey,
135 })
136 }
137β
138 if (queryEvent.type === 'added') {
139 safePost({
140 type: 'added',
141 queryHash,
142 queryKey,
143 state,
144 })
145 }
146 })
147β
148 channel.onmessage = (action) => {
149 if (!action?.type) {
150 return
151 }
152β
153 tx(() => {
154 const { type, queryHash, queryKey, state } = action
155β
156 const query = queryCache.get(queryHash)
157β
158 if (type === 'updated') {
159 if (query) {
160 query.setState(state)
161 return
162 }
163β
164 queryCache.build(
165 queryClient,
166 {
167 queryKey,
168 queryHash,
169 },
170 state,
171 )
172 } else if (type === 'removed') {
173 if (query) {
174 queryCache.remove(query)
175 }
176 } else if (type === 'added') {
177 if (query) {
178 if (query.state.data === undefined) {
179 query.setState(state)
180 }
181 return
182 }
183 queryCache.build(
184 queryClient,
185 {
186 queryKey,
187 queryHash,
188 },
189 state,
190 )
191 }
192 })
193 }
194 return () => {
195 unsubscribe()
196 channel.close()
197 }
198}