Open History to see the last commit
1import { parseWithBigInt, stringifyWithBigInt } from '../utils/json'
2β
3// Declare the global placeholders that get replaced by the Vite plugin at transform time
4// Fall back to defaults when not using the Vite plugin or in non-transformed environments
5declare const __TANSTACK_DEVTOOLS_PORT__: number | undefined
6declare const __TANSTACK_DEVTOOLS_HOST__: string | undefined
7declare const __TANSTACK_DEVTOOLS_PROTOCOL__: 'http' | 'https' | undefined
8β
9function getDefaultPort(configPort: number): number {
10 if (typeof __TANSTACK_DEVTOOLS_PORT__ !== 'undefined')
11 return __TANSTACK_DEVTOOLS_PORT__
12 return configPort
13}
14β
15function getDefaultHost(configHost: string): string {
16 if (typeof __TANSTACK_DEVTOOLS_HOST__ !== 'undefined')
17 return __TANSTACK_DEVTOOLS_HOST__
18 return configHost
19}
20β
21function getDefaultProtocol(
22 configProtocol: 'http' | 'https',
23): 'http' | 'https' {
24 if (typeof __TANSTACK_DEVTOOLS_PROTOCOL__ !== 'undefined')
25 return __TANSTACK_DEVTOOLS_PROTOCOL__
26 return configProtocol
27}
28β
29interface TanStackDevtoolsEvent<TEventName extends string, TPayload = any> {
30 type: TEventName
31 payload: TPayload
32 pluginId?: string // Optional pluginId to filter events by plugin
33}
34β
35export interface ClientEventBusConfig {
36 /**
37 * Optional flag to indicate if the devtools server event bus is available to connect to.
38 * This is used to determine if the devtools can connect to the server for real-time event streams.
39 */
40 connectToServerBus?: boolean
41β
42 /**
43 * Optional flag to enable debug mode for the event bus.
44 */
45 debug?: boolean
46β
47 /**
48 * Optional port to connect to the devtools server event bus.
49 * Defaults to 4206.
50 */
51 port?: number
52β
53 /**
54 * Optional host to connect to the devtools server event bus.
55 * Defaults to 'localhost'.
56 */
57 host?: string
58β
59 /**
60 * Optional protocol to use for connecting to the devtools server event bus.
61 * Defaults to 'http'. Set to 'https' when the dev server uses HTTPS.
62 */
63 protocol?: 'http' | 'https'
64}
65β
66export class ClientEventBus {
67 #port: number
68 #host: string
69 #protocol: 'http' | 'https'
70 #socket: WebSocket | null
71 #eventSource: EventSource | null
72 #eventTarget: EventTarget
73 #debug: boolean
74 #connectToServerBus: boolean
75 #broadcastChannel: BroadcastChannel | null
76 // Events emitted while the WebSocket is still establishing its connection.
77 // They are buffered here and flushed once the socket opens so early events
78 // (e.g. the marketplace's `mounted` request) are never silently dropped.
79 #pendingServerEvents: Array<string> = []
80 #dispatcher = (e: Event) => {
81 const event = (e as CustomEvent).detail
82 this.emitToServer(event)
83 this.emitToClients(event)
84 }
85 #connectFunction = () => {
86 this.debugLog(
87 'Connection request made to event-bus, replying back with success',
88 )
89 this.#eventTarget.dispatchEvent(new CustomEvent('tanstack-connect-success'))
90 }
91 constructor({
92 port = 4206,
93 host = 'localhost',
94 protocol = 'http',
95 debug = false,
96 connectToServerBus = false,
97 }: ClientEventBusConfig = {}) {
98 this.#debug = debug
99 this.#broadcastChannel = new BroadcastChannel('tanstack-devtools')
100 this.#eventSource = null
101 this.#port = getDefaultPort(port)
102 this.#host = getDefaultHost(host)
103 this.#protocol = getDefaultProtocol(protocol)
104 this.#socket = null
105 this.#connectToServerBus = connectToServerBus
106 this.#eventTarget = this.getGlobalTarget()
107 this.#broadcastChannel.onmessage = (e) => {
108 this.emitToClients(parseWithBigInt(e.data), true)
109 }
110 this.debugLog('Initializing client event bus')
111 }
112β
113 private emitToClients(
114 event: TanStackDevtoolsEvent<string>,
115 fromBroadcastChannel = false,
116 ) {
117 this.debugLog('Emitting event from client bus', event)
118 const specificEvent = new CustomEvent(event.type, { detail: event })
119 this.debugLog('Emitting event to specific client listeners', event)
120 this.#eventTarget.dispatchEvent(specificEvent)
121 const globalEvent = new CustomEvent('tanstack-devtools-global', {
122 detail: event,
123 })
124 // We only emit the events if they didn't come from the broadcast channel
125 // otherwise it would infinitely send events between
126 if (!fromBroadcastChannel) {
127 this.#broadcastChannel?.postMessage(stringifyWithBigInt(event))
128 }
129 this.debugLog('Emitting event to global client listeners', event)
130 this.#eventTarget.dispatchEvent(globalEvent)
131 }
132β
133 private flushPendingServerEvents() {
134 if (!this.#socket || this.#socket.readyState !== WebSocket.OPEN) {
135 return
136 }
137 const pending = this.#pendingServerEvents
138 this.#pendingServerEvents = []
139 for (const json of pending) {
140 this.debugLog('Flushing queued event to server via WS')
141 this.#socket.send(json)
142 }
143 }
144β
145 private emitToServer(event: TanStackDevtoolsEvent<string, any>) {
146 const json = stringifyWithBigInt(event)
147 // try to emit it to the event bus first
148 if (this.#socket) {
149 if (this.#socket.readyState === WebSocket.OPEN) {
150 this.debugLog('Emitting event to server via WS', event)
151 this.#socket.send(json)
152 } else if (this.#socket.readyState === WebSocket.CONNECTING) {
153 // The socket handshake is still in flight. Buffer the event instead of
154 // dropping it; it will be sent once the connection opens.
155 this.debugLog('WebSocket still connecting, queueing event', event)
156 this.#pendingServerEvents.push(json)
157 }
158 // CLOSING/CLOSED sockets cannot deliver; the event is dropped.
159 return
160 }
161 // try to emit to SSE if WebSocket is not available (this will only happen on the client side)
162 if (this.#eventSource) {
163 this.debugLog('Emitting event to server via SSE', event)
164β
165 fetch(`${this.#protocol}://${this.#host}:${this.#port}/__devtools/send`, {
166 method: 'POST',
167 headers: { 'Content-Type': 'application/json' },
168 body: json,
169 }).catch(() => {})
170 }
171 }
172 start() {
173 this.debugLog('Starting client event bus')
174 if (typeof window === 'undefined') {
175 return
176 }
177 if (this.#connectToServerBus) {
178 this.connect()
179 }
180 this.#eventTarget = window
181 this.#eventTarget.addEventListener(
182 'tanstack-dispatch-event',
183 this.#dispatcher,
184 )
185 this.#eventTarget.addEventListener(
186 'tanstack-connect',
187 this.#connectFunction,
188 )
189 }
190 stop() {
191 this.debugLog('Stopping client event bus')
192 if (typeof window === 'undefined') {
193 return
194 }
195 this.#eventTarget.removeEventListener(
196 'tanstack-dispatch-event',
197 this.#dispatcher,
198 )
199 this.#eventTarget.removeEventListener(
200 'tanstack-connect',
201 this.#connectFunction,
202 )
203 this.#eventSource?.close()
204 this.#socket?.close()
205 this.#socket = null
206 this.#eventSource = null
207 this.#pendingServerEvents = []
208 }
209 private getGlobalTarget() {
210 if (typeof window !== 'undefined') {
211 return window
212 }
213β
214 return new EventTarget()
215 }
216 private debugLog(...messages: Array<any>) {
217 if (this.#debug) {
218 console.log('π΄ [tanstack-devtools:client-bus]', ...messages)
219 }
220 }
221 private connectSSE() {
222 this.debugLog('Connecting to SSE server')
223 this.#eventSource = new EventSource(
224 `${this.#protocol}://${this.#host}:${this.#port}/__devtools/sse`,
225 )
226 this.#eventSource.onmessage = (e) => {
227 this.debugLog('Received message from SSE server', e.data)
228 this.handleEventReceived(e.data)
229 }
230 }
231β
232 private connectWebSocket() {
233 this.debugLog('Connecting to WebSocket server')
234β
235 const wsProtocol = this.#protocol === 'https' ? 'wss' : 'ws'
236 this.#socket = new WebSocket(
237 `${wsProtocol}://${this.#host}:${this.#port}/__devtools/ws`,
238 )
239 this.#socket.onopen = () => {
240 this.debugLog('WebSocket connection opened')
241 this.flushPendingServerEvents()
242 }
243 this.#socket.onmessage = (e) => {
244 this.debugLog('Received message from server', e.data)
245 this.handleEventReceived(e.data)
246 }
247 this.#socket.onclose = () => {
248 this.debugLog('WebSocket connection closed')
249 this.#socket = null
250 // Drop any still-queued events β there is no open socket to deliver them.
251 this.#pendingServerEvents = []
252 }
253 this.#socket.onerror = () => {
254 this.debugLog('WebSocket connection error')
255 }
256 }
257β
258 private connect() {
259 try {
260 this.connectWebSocket()
261 } catch {
262 // Do not try to connect if we're on the server side
263 if (typeof window === 'undefined') return
264 this.connectSSE()
265 }
266 }
267β
268 private handleEventReceived(data: string) {
269 try {
270 const event = parseWithBigInt(data) as TanStackDevtoolsEvent<string, any>
271 this.emitToClients(event)
272 } catch {}
273 }
274}