-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathplugin.ts
More file actions
221 lines (205 loc) · 6.07 KB
/
plugin.ts
File metadata and controls
221 lines (205 loc) · 6.07 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
interface TanStackDevtoolsEvent<TEventName extends string, TPayload = any> {
type: TEventName
payload: TPayload
pluginId?: string // Optional pluginId to filter events by plugin
}
declare global {
// eslint-disable-next-line no-var
var __TANSTACK_EVENT_TARGET__: EventTarget | null
}
type AllDevtoolsEvents<TEventMap extends Record<string, any>> = {
[Key in keyof TEventMap]: TanStackDevtoolsEvent<Key & string, TEventMap[Key]>
}[keyof TEventMap]
export class EventClient<
TEventMap extends Record<string, any>,
TPluginId extends string = TEventMap extends Record<infer P, any>
? P extends `${infer Id}:${string}`
? Id
: never
: never,
> {
#pluginId: TPluginId
#eventTarget: () => EventTarget
#debug: boolean
#queuedEvents: Array<TanStackDevtoolsEvent<string, any>>
#connected: boolean
#connectIntervalId: number | null
#connectEveryMs: number
#retryCount = 0
#maxRetries = 5
#onConnected = () => {
this.debugLog('Connected to event bus')
this.#connected = true
this.debugLog('Emitting queued events', this.#queuedEvents)
this.#queuedEvents.forEach((event) => this.emitEventToBus(event))
this.#queuedEvents = []
this.stopConnectLoop()
this.#eventTarget().removeEventListener(
'tanstack-connect-success',
this.#onConnected,
)
}
#connectFunction = () => {
if (this.#retryCount < this.#maxRetries) {
this.#retryCount++
this.#eventTarget().dispatchEvent(new CustomEvent('tanstack-connect'))
return
}
this.#eventTarget().removeEventListener(
'tanstack-connect',
this.#connectFunction,
)
this.debugLog('Max retries reached, giving up on connection')
this.stopConnectLoop()
}
constructor({
pluginId,
debug = false,
}: {
pluginId: TPluginId
debug?: boolean
}) {
this.#pluginId = pluginId
this.#eventTarget = this.getGlobalTarget
this.#debug = debug
this.debugLog(' Initializing event subscription for plugin', this.#pluginId)
this.#queuedEvents = []
this.#connected = false
this.#connectIntervalId = null
this.#connectEveryMs = 500
this.#eventTarget().addEventListener(
'tanstack-connect-success',
this.#onConnected,
)
this.#connectFunction()
this.startConnectLoop()
}
private startConnectLoop() {
if (this.#connectIntervalId !== null || this.#connected) return
this.debugLog(`Starting connect loop (every ${this.#connectEveryMs}ms)`)
this.#connectIntervalId = setInterval(
this.#connectFunction,
this.#connectEveryMs,
) as unknown as number
}
private stopConnectLoop() {
if (this.#connectIntervalId === null) {
return
}
clearInterval(this.#connectIntervalId)
this.#connectIntervalId = null
this.debugLog('Stopped connect loop')
}
private debugLog(...args: Array<any>) {
if (this.#debug) {
console.log(`🌴 [tanstack-devtools:${this.#pluginId}-plugin]`, ...args)
}
}
private getGlobalTarget() {
// server one is the global event target
if (
typeof globalThis !== 'undefined' &&
globalThis.__TANSTACK_EVENT_TARGET__
) {
this.debugLog('Using global event target')
return globalThis.__TANSTACK_EVENT_TARGET__
}
// CLient event target is the window object
if (typeof window !== 'undefined') {
this.debugLog('Using window as event target')
return window
}
this.debugLog('Using new EventTarget as fallback')
return new EventTarget()
}
getPluginId() {
return this.#pluginId
}
private emitEventToBus(event: TanStackDevtoolsEvent<string, any>) {
this.debugLog('Emitting event to client bus', event)
this.#eventTarget().dispatchEvent(
new CustomEvent('tanstack-dispatch-event', { detail: event }),
)
}
emit<
TSuffix extends Extract<
keyof TEventMap,
`${TPluginId & string}:${string}`
> extends `${TPluginId & string}:${infer S}`
? S
: never,
>(
eventSuffix: TSuffix,
payload: TEventMap[`${TPluginId & string}:${TSuffix}`],
) {
// wait to connect to the bus
if (!this.#connected) {
this.debugLog('Bus not available, will be pushed as soon as connected')
return this.#queuedEvents.push({
type: `${this.#pluginId}:${eventSuffix}`,
payload,
pluginId: this.#pluginId,
})
}
// emit right now
return this.emitEventToBus({
type: `${this.#pluginId}:${eventSuffix}`,
payload,
pluginId: this.#pluginId,
})
}
on<
TSuffix extends Extract<
keyof TEventMap,
`${TPluginId & string}:${string}`
> extends `${TPluginId & string}:${infer S}`
? S
: never,
>(
eventSuffix: TSuffix,
cb: (
event: TanStackDevtoolsEvent<
`${TPluginId & string}:${TSuffix}`,
TEventMap[`${TPluginId & string}:${TSuffix}`]
>,
) => void,
) {
const eventName = `${this.#pluginId}:${eventSuffix}` as const
const handler = (e: Event) => {
this.debugLog('Received event from bus', (e as CustomEvent).detail)
cb((e as CustomEvent).detail)
}
this.#eventTarget().addEventListener(eventName, handler)
this.debugLog('Registered event to bus', eventName)
return () => {
this.#eventTarget().removeEventListener(eventName, handler)
}
}
onAll(cb: (event: TanStackDevtoolsEvent<string, any>) => void) {
const handler = (e: Event) => {
const event = (e as CustomEvent).detail
cb(event)
}
this.#eventTarget().addEventListener('tanstack-devtools-global', handler)
return () =>
this.#eventTarget().removeEventListener(
'tanstack-devtools-global',
handler,
)
}
onAllPluginEvents(cb: (event: AllDevtoolsEvents<TEventMap>) => void) {
const handler = (e: Event) => {
const event = (e as CustomEvent).detail
if (this.#pluginId && event.pluginId !== this.#pluginId) {
return
}
cb(event)
}
this.#eventTarget().addEventListener('tanstack-devtools-global', handler)
return () =>
this.#eventTarget().removeEventListener(
'tanstack-devtools-global',
handler,
)
}
}