-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathclient.ts
More file actions
181 lines (167 loc) · 5.11 KB
/
client.ts
File metadata and controls
181 lines (167 loc) · 5.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
interface TanStackDevtoolsEvent<TEventName extends string, TPayload = any> {
type: TEventName
payload: TPayload
pluginId?: string // Optional pluginId to filter events by plugin
}
export interface ClientEventBusConfig {
/**
* Optional flag to indicate if the devtools server event bus is available to connect to.
* This is used to determine if the devtools can connect to the server for real-time event streams.
*/
connectToServerBus?: boolean
/**
* Optional flag to enable debug mode for the event bus.
*/
debug?: boolean
/**
* Optional port to connect to the devtools server event bus.
* Defaults to 42069.
*/
port?: number
}
export class ClientEventBus {
#port: number
#socket: WebSocket | null
#eventSource: EventSource | null
#eventTarget: EventTarget
#debug: boolean
#connectToServerBus: boolean
#dispatcher = (e: Event) => {
const event = (e as CustomEvent).detail
this.emitToServer(event)
this.emitToClients(event)
}
#connectFunction = () => {
this.debugLog(
'Connection request made to event-bus, replying back with success',
)
this.#eventTarget.dispatchEvent(new CustomEvent('tanstack-connect-success'))
}
constructor({
port = 42069,
debug = false,
connectToServerBus = false,
}: ClientEventBusConfig = {}) {
this.#debug = debug
this.#eventSource = null
this.#port = port
this.#socket = null
this.#connectToServerBus = connectToServerBus
this.#eventTarget = this.getGlobalTarget()
this.debugLog('Initializing client event bus')
}
private emitToClients(event: TanStackDevtoolsEvent<string>) {
this.debugLog('Emitting event from client bus', event)
const specificEvent = new CustomEvent(event.type, { detail: event })
this.debugLog('Emitting event to specific client listeners', event)
this.#eventTarget.dispatchEvent(specificEvent)
const globalEvent = new CustomEvent('tanstack-devtools-global', {
detail: event,
})
this.debugLog('Emitting event to global client listeners', event)
this.#eventTarget.dispatchEvent(globalEvent)
}
private emitToServer(event: TanStackDevtoolsEvent<string, any>) {
const json = JSON.stringify(event)
// try to emit it to the event bus first
if (this.#socket && this.#socket.readyState === WebSocket.OPEN) {
this.debugLog('Emitting event to server via WS', event)
this.#socket.send(json)
// try to emit to SSE if WebSocket is not available (this will only happen on the client side)
} else if (this.#eventSource) {
this.debugLog('Emitting event to server via SSE', event)
fetch(`http://localhost:${this.#port}/__devtools/send`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: json,
}).catch(() => {})
}
}
start() {
this.debugLog('Starting client event bus')
if (typeof window === 'undefined') {
return
}
if (this.#connectToServerBus) {
this.connect()
}
this.#eventTarget = window
this.#eventTarget.addEventListener(
'tanstack-dispatch-event',
this.#dispatcher,
)
this.#eventTarget.addEventListener(
'tanstack-connect',
this.#connectFunction,
)
}
stop() {
this.debugLog('Stopping client event bus')
if (typeof window === 'undefined') {
return
}
this.#eventTarget.removeEventListener(
'tanstack-dispatch-event',
this.#dispatcher,
)
this.#eventTarget.removeEventListener(
'tanstack-connect',
this.#connectFunction,
)
this.#eventSource?.close()
this.#socket?.close()
this.#socket = null
this.#eventSource = null
}
private getGlobalTarget() {
if (typeof window !== 'undefined') {
return window
}
return new EventTarget()
}
private debugLog(...messages: Array<any>) {
if (this.#debug) {
console.log('🌴 [tanstack-devtools:client-bus]', ...messages)
}
}
private connectSSE() {
this.debugLog('Connecting to SSE server')
this.#eventSource = new EventSource(
`http://localhost:${this.#port}/__devtools/sse`,
)
this.#eventSource.onmessage = (e) => {
this.debugLog('Received message from SSE server', e.data)
this.handleEventReceived(e.data)
}
}
private connectWebSocket() {
this.debugLog('Connecting to WebSocket server')
this.#socket = new WebSocket(`ws://localhost:${this.#port}/__devtools/ws`)
this.#socket.onmessage = (e) => {
this.debugLog('Received message from server', e.data)
this.handleEventReceived(e.data)
}
this.#socket.onclose = () => {
this.debugLog('WebSocket connection closed')
this.#socket = null
}
this.#socket.onerror = () => {
this.debugLog('WebSocket connection error')
}
}
private connect() {
try {
this.connectWebSocket()
} catch {
// Do not try to connect if we're on the server side
if (typeof window === 'undefined') return
this.connectSSE()
}
}
private handleEventReceived(data: string) {
try {
const event = JSON.parse(data) as TanStackDevtoolsEvent<string, any>
this.emitToClients(event)
} catch {}
}
}