Skip to content
Source
Sign inSign up
TanStack/devtools
Open History to see the last commit

runtime-bridge.ts

113 lines4.1 KB

1/**
2 * Worker-side bridge for isolated server runtimes (Nitro v3 worker, Cloudflare workerd).
3 *
4 * Injected into the `@tanstack/devtools-event-client` module ONLY in non-client
5 * (server) environments during dev. At module-eval time it gives the isolated
6 * runtime a real `globalThis.__TANSTACK_EVENT_TARGET__` (so the unchanged
7 * `EventClient` uses it instead of a throwaway target) and bridges that target to
8 * the Vite dev process over the framework plugin's existing HMR HotChannel.
9 *
10 * Guards:
11 * - `import.meta.hot` falsy (production / no HMR) -> tree-shaken / no-op.
12 * - global target already set (in-process RunnableDevEnvironment, where
13 * ServerEventBus lives) -> no-op, so existing behavior is unchanged.
14 *
15 * The bridge replicates ServerEventBus's in-process responsibilities so the
16 * EventClient protocol is identical across the wire (see design doc).
17 */
18export function generateRuntimeBridgeCode(): string {
19 return `
20;(function __tsdRuntimeBridge() {
21 if (typeof import.meta === 'undefined' || !import.meta.hot) return;
22 if (!globalThis.__TANSTACK_EVENT_TARGET__) {
23 var target = new EventTarget();
24 globalThis.__TANSTACK_EVENT_TARGET__ = target;
25​
26 // Complete EventClient's connect handshake locally so queued events flush.
27 target.addEventListener('tanstack-connect', function () {
28 target.dispatchEvent(new CustomEvent('tanstack-connect-success'));
29 });
30​
31 // Worker -> Vite dev server.
32 target.addEventListener('tanstack-dispatch-event', function (e) {
33 import.meta.hot.send('tsd:to-server', e.detail);
34 });
35​
36 // Vite dev server -> worker listeners.
37 import.meta.hot.on('tsd:to-client', function (event) {
38 target.dispatchEvent(new CustomEvent(event.type, { detail: event }));
39 target.dispatchEvent(new CustomEvent('tanstack-devtools-global', { detail: event }));
40 });
41 }
42})();
45​
46function isEventClientModule(id: string, code: string): boolean {
47 const isEventClientPath =
48 id.includes('devtools-event-client') || id.includes('event-bus-client')
49 // Only the module that actually defines the class β€” avoids re-export shims
50 // and unrelated files inside the package.
51 return isEventClientPath && code.includes('EventClient')
53​
54export function injectRuntimeBridge(
55 code: string,
56 id: string,
57 environmentName: string | undefined,
58): string | undefined {
59 // Only isolated server environments need the bridge. The client environment
60 // has `window`; the in-process RunnableDevEnvironment is handled by the
61 // runtime global guard inside the injected code.
62 if (!environmentName || environmentName === 'client') return undefined
63 if (!isEventClientModule(id, code)) return undefined
64 return `${code}\n${generateRuntimeBridgeCode()}`
66​
67interface BridgeHotChannel {
68 on?: (event: string, cb: (data: any) => void) => void
69 off?: (event: string, cb: (data: any) => void) => void
70 send?: (event: string, data: any) => void
72interface BridgeServerLike {
73 environments: Record<string, { hot?: BridgeHotChannel | null } | undefined>
75​
76export function wireRuntimeBridgeChannels(
77 server: BridgeServerLike,
78 getTarget: () => EventTarget | null | undefined,
79): () => void {
80 const teardowns: Array<() => void> = []
81​
82 for (const [name, env] of Object.entries(server.environments)) {
83 if (name === 'client') continue
84 const hot = env?.hot
85 if (
86 !hot ||
87 typeof hot.on !== 'function' ||
88 typeof hot.send !== 'function'
89 ) {
90 continue
91 }
92​
93 // Worker -> ServerEventBus (broadcasts to browser + in-process listeners).
94 const onToServer = (event: any) => {
95 getTarget()?.dispatchEvent(
96 new CustomEvent('tanstack-dispatch-event', { detail: event }),
97 )
98 }
99 hot.on('tsd:to-server', onToServer)
100 teardowns.push(() => hot.off?.('tsd:to-server', onToServer))
101​
102 // ServerEventBus output -> worker listeners.
103 const target = getTarget()
104 const forward = (e: Event) =>
105 hot.send!('tsd:to-client', (e as CustomEvent).detail)
106 target?.addEventListener('tanstack-devtools-global', forward)
107 teardowns.push(() =>
108 target?.removeEventListener('tanstack-devtools-global', forward),
109 )
110 }
111​
112 return () => teardowns.forEach((off) => off())