Open History to see the last commit
1import type { AllDevtoolsEvents, TanStackDevtoolsEvent } from './types'
2β
3declare global {
4 var __TANSTACK_EVENT_TARGET__: EventTarget | null
5}
6β
7export class EventClient<TEventMap extends Record<string, any>> {
8 #enabled = true
9 #pluginId: string
10 #eventTarget: () => EventTarget
11 #debug: boolean
12 #queuedEvents: Array<TanStackDevtoolsEvent<string, any>>
13 #connected: boolean
14 #connectIntervalId: number | null
15 #connectEveryMs: number
16 #retryCount = 0
17 #maxRetries = 5
18 #connecting = false
19 #failedToConnect = false
20 #internalEventTarget: EventTarget | null = null
21β
22 #onConnected = () => {
23 this.debugLog('Connected to event bus')
24 this.#connected = true
25 this.#connecting = false
26 this.debugLog('Emitting queued events', this.#queuedEvents)
27 this.#queuedEvents.forEach((event) => this.emitEventToBus(event))
28 this.#queuedEvents = []
29 this.stopConnectLoop()
30 this.#eventTarget().removeEventListener(
31 'tanstack-connect-success',
32 this.#onConnected,
33 )
34 }
35 // fired off right away and then at intervals
36 #retryConnection = () => {
37 if (this.#retryCount < this.#maxRetries) {
38 this.#retryCount++
39 this.dispatchCustomEvent('tanstack-connect', {})
40β
41 return
42 }
43 this.#eventTarget().removeEventListener(
44 'tanstack-connect',
45 this.#retryConnection,
46 )
47 this.#failedToConnect = true
48 this.debugLog('Max retries reached, giving up on connection')
49 this.stopConnectLoop()
50 }
51β
52 // This is run to register connection handlers on first emit attempt
53 #connectFunction = () => {
54 if (this.#connecting) return
55 this.#connecting = true
56 this.#eventTarget().addEventListener(
57 'tanstack-connect-success',
58 this.#onConnected,
59 )
60 this.#retryConnection()
61 }
62β
63 constructor({
64 pluginId,
65 debug = false,
66 enabled = true,
67 reconnectEveryMs = 300,
68 }: {
69 pluginId: string
70 debug?: boolean
71 reconnectEveryMs?: number
72 enabled?: boolean
73 }) {
74 this.#pluginId = pluginId
75 this.#enabled = enabled
76 this.#eventTarget = this.getGlobalTarget
77 this.#debug = debug
78 this.debugLog(' Initializing event subscription for plugin', this.#pluginId)
79 this.#queuedEvents = []
80 this.#connected = false
81 this.#failedToConnect = false
82 this.#connectIntervalId = null
83 this.#connectEveryMs = reconnectEveryMs
84 }
85β
86 private startConnectLoop() {
87 // if connected, trying to connect, or the internalId is already set, do nothing
88 if (this.#connectIntervalId !== null || this.#connected) return
89 this.debugLog(`Starting connect loop (every ${this.#connectEveryMs}ms)`)
90β
91 this.#connectIntervalId = setInterval(
92 this.#retryConnection,
93 this.#connectEveryMs,
94 ) as unknown as number
95 }
96β
97 private stopConnectLoop() {
98 this.#connecting = false
99β
100 if (this.#connectIntervalId === null) {
101 return
102 }
103 clearInterval(this.#connectIntervalId)
104 this.#connectIntervalId = null
105 this.#queuedEvents = []
106 this.debugLog('Stopped connect loop')
107 }
108β
109 private debugLog(...args: Array<any>) {
110 if (this.#debug) {
111 console.log(`π΄ [tanstack-devtools:${this.#pluginId}-plugin]`, ...args)
112 }
113 }
114 private getGlobalTarget() {
115 // server one is the global event target
116 if (
117 typeof globalThis !== 'undefined' &&
118 globalThis.__TANSTACK_EVENT_TARGET__
119 ) {
120 this.debugLog('Using global event target')
121 return globalThis.__TANSTACK_EVENT_TARGET__
122 }
123 // CLient event target is the browser window object
124 if (
125 typeof window !== 'undefined' &&
126 typeof window.addEventListener !== 'undefined'
127 ) {
128 this.debugLog('Using window as event target')
129β
130 return window
131 }
132 // Protect against non-web environments like react-native
133 const eventTarget =
134 typeof EventTarget !== 'undefined' ? new EventTarget() : undefined
135β
136 // For non-web environments like react-native
137 if (
138 typeof eventTarget === 'undefined' ||
139 typeof eventTarget.addEventListener === 'undefined'
140 ) {
141 this.debugLog(
142 'No event mechanism available, running in non-web environment',
143 )
144 return {
145 addEventListener: () => {},
146 removeEventListener: () => {},
147 dispatchEvent: () => false,
148 }
149 }
150β
151 this.debugLog('Using new EventTarget as fallback')
152 return eventTarget
153 }
154β
155 getPluginId() {
156 return this.#pluginId
157 }
158β
159 private dispatchCustomEventShim(eventName: string, detail: any) {
160 try {
161 const event = new Event(eventName, {
162 detail: detail,
163 } as any)
164 this.#eventTarget().dispatchEvent(event)
165 } catch (e) {
166 this.debugLog('Failed to dispatch shim event')
167 }
168 }
169β
170 private dispatchCustomEvent(eventName: string, detail?: any) {
171 try {
172 this.#eventTarget().dispatchEvent(new CustomEvent(eventName, { detail }))
173 } catch (e) {
174 this.dispatchCustomEventShim(eventName, detail)
175 }
176 }
177β
178 private emitEventToBus(event: TanStackDevtoolsEvent<string, any>) {
179 this.debugLog('Emitting event to client bus', event)
180 this.dispatchCustomEvent('tanstack-dispatch-event', event)
181 }
182β
183 createEventPayload<TEvent extends keyof TEventMap & string>(
184 eventSuffix: TEvent,
185 payload: TEventMap[TEvent],
186 ) {
187 return {
188 type: `${this.#pluginId}:${eventSuffix}`,
189 payload,
190 pluginId: this.#pluginId,
191 }
192 }
193 emit<TEvent extends keyof TEventMap & string>(
194 eventSuffix: TEvent,
195 payload: TEventMap[TEvent],
196 ) {
197 if (!this.#enabled) {
198 this.debugLog(
199 'Event bus client is disabled, not emitting event',
200 eventSuffix,
201 payload,
202 )
203 return
204 }
205 if (this.#internalEventTarget) {
206 this.debugLog(
207 'Emitting event to internal event target',
208 eventSuffix,
209 payload,
210 )
211 this.#internalEventTarget.dispatchEvent(
212 new CustomEvent(`${this.#pluginId}:${eventSuffix}`, {
213 detail: this.createEventPayload(eventSuffix, payload),
214 }),
215 )
216 }
217β
218 if (this.#failedToConnect) {
219 this.debugLog('Previously failed to connect, not emitting to bus')
220 return
221 }
222 // wait to connect to the bus
223 if (!this.#connected) {
224 this.debugLog('Bus not available, will be pushed as soon as connected')
225 this.#queuedEvents.push(this.createEventPayload(eventSuffix, payload))
226 // start connection to event bus
227 if (typeof CustomEvent !== 'undefined' && !this.#connecting) {
228 this.#connectFunction()
229 this.startConnectLoop()
230 }
231 return
232 }
233 // emit right now
234 return this.emitEventToBus(this.createEventPayload(eventSuffix, payload))
235 }
236β
237 on<TEvent extends keyof TEventMap & string>(
238 eventSuffix: TEvent,
239 cb: (event: TanStackDevtoolsEvent<TEvent, TEventMap[TEvent]>) => void,
240 options?: {
241 withEventTarget?: boolean
242 },
243 ) {
244 const withEventTarget = options?.withEventTarget ?? false
245 const eventName = `${this.#pluginId}:${eventSuffix}` as const
246 if (withEventTarget) {
247 if (!this.#internalEventTarget) {
248 this.#internalEventTarget = new EventTarget()
249 }
250 this.#internalEventTarget.addEventListener(eventName, (e) => {
251 cb((e as CustomEvent).detail)
252 })
253 }
254 if (!this.#enabled) {
255 this.debugLog(
256 'Event bus client is disabled, not registering event',
257 eventName,
258 )
259 return () => {}
260 }
261 const handler = (e: Event) => {
262 this.debugLog('Received event from bus', (e as CustomEvent).detail)
263 cb((e as CustomEvent).detail)
264 }
265 this.#eventTarget().addEventListener(eventName, handler)
266 this.debugLog('Registered event to bus', eventName)
267 return () => {
268 if (withEventTarget) {
269 this.#internalEventTarget?.removeEventListener(eventName, handler)
270 }
271 this.#eventTarget().removeEventListener(eventName, handler)
272 }
273 }
274β
275 onAll(cb: (event: TanStackDevtoolsEvent<string, any>) => void) {
276 if (!this.#enabled) {
277 this.debugLog('Event bus client is disabled, not registering event')
278 return () => {}
279 }
280β
281 const handler = (e: Event) => {
282 const event = (e as CustomEvent).detail
283β
284 cb(event)
285 }
286 this.#eventTarget().addEventListener('tanstack-devtools-global', handler)
287 return () =>
288 this.#eventTarget().removeEventListener(
289 'tanstack-devtools-global',
290 handler,
291 )
292 }
293 onAllPluginEvents(cb: (event: AllDevtoolsEvents<TEventMap>) => void) {
294 if (!this.#enabled) {
295 this.debugLog('Event bus client is disabled, not registering event')
296 return () => {}
297 }
298 const handler = (e: Event) => {
299 const event = (e as CustomEvent).detail
300 if (this.#pluginId && event.pluginId !== this.#pluginId) {
301 return
302 }
303 cb(event)
304 }
305 this.#eventTarget().addEventListener('tanstack-devtools-global', handler)
306 return () =>
307 this.#eventTarget().removeEventListener(
308 'tanstack-devtools-global',
309 handler,
310 )
311 }
312}