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

index.test.ts

484 lines15.1 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { devtools } from '../src/plugin'
3import type { Plugin } from 'vite'
4import type * as Utils from '../src/utils'
5​
6let capturedOnConsolePipe: ((entries: Array<any>) => void) | undefined
7​
8vi.mock('../src/utils', async (importOriginal) => {
9 const actual = await importOriginal<typeof Utils>()
10 return {
11 ...actual,
12 handleDevToolsViteRequest: vi.fn(
13 (_req: any, _res: any, _next: any, handlers: any) => {
14 if (typeof handlers === 'object' && handlers?.onConsolePipe) {
15 capturedOnConsolePipe = handlers.onConsolePipe
16 }
17 },
18 ),
19 }
20})
21​
22// Helper to find a plugin by name from the array returned by devtools()
23function findPlugin(plugins: Array<Plugin>, name: string): Plugin | undefined {
24 return plugins.find((p) => p.name === name)
26​
27// Helper to create a mock Vite server
28function createMockServer(
29 options: {
30 https?: boolean | object
31 host?: string | boolean
32 port?: number
33 httpServer?: any
34 } = {},
35) {
36 return {
37 config: {
38 server: {
39 https: options.https ?? false,
40 host: options.host ?? 'localhost',
41 port: options.port ?? 5173,
42 },
43 mode: 'development',
44 },
45 httpServer: options.httpServer ?? {
46 on: vi.fn(),
47 address: vi.fn().mockReturnValue({ port: 5173 }),
48 },
49 middlewares: {
50 use: vi.fn(),
51 },
52 }
54​
55describe('devtools plugin', () => {
56 describe('connection-injection plugin', () => {
57 let connectionPlugin: Plugin
58​
59 beforeEach(() => {
60 const plugins = devtools({
61 eventBusConfig: { enabled: false }, // Disable server bus for unit test
62 })
63 const found = findPlugin(
64 plugins,
65 '@tanstack/devtools:connection-injection',
66 )
67 if (!found) {
68 throw new Error('connection-injection plugin not found')
69 }
70 connectionPlugin = found
71 })
72​
73 it('should exist in the plugins array', () => {
74 const plugins = devtools()
75 const plugin = findPlugin(
76 plugins,
77 '@tanstack/devtools:connection-injection',
78 )
79 expect(plugin).toBeDefined()
80 })
81​
82 it('should only apply in development mode with serve command', () => {
83 const apply = connectionPlugin.apply as (config: any, env: any) => boolean
84 expect(apply({ mode: 'development' }, { command: 'serve' })).toBe(true)
85 expect(apply({ mode: 'production' }, { command: 'serve' })).toBe(false)
86 expect(apply({ mode: 'development' }, { command: 'build' })).toBe(false)
87 })
88​
89 it('should replace __TANSTACK_DEVTOOLS_PORT__ in matching modules', () => {
90 const transform = connectionPlugin.transform as (
91 code: string,
92 id: string,
93 ) => string | undefined
94 const code = 'const port = __TANSTACK_DEVTOOLS_PORT__'
95 const result = transform(
96 code,
97 'node_modules/@tanstack/event-bus/dist/client.js',
98 )
99 expect(result).toBeDefined()
100 expect(result).not.toContain('__TANSTACK_DEVTOOLS_PORT__')
101 // Default port when bus is not started
102 expect(result).toContain('4206')
103 })
104​
105 it('should replace __TANSTACK_DEVTOOLS_HOST__ in matching modules', () => {
106 const transform = connectionPlugin.transform as (
107 code: string,
108 id: string,
109 ) => string | undefined
110 const code = 'const host = __TANSTACK_DEVTOOLS_HOST__'
111 const result = transform(
112 code,
113 'node_modules/@tanstack/devtools/dist/client.js',
114 )
115 expect(result).toBeDefined()
116 expect(result).not.toContain('__TANSTACK_DEVTOOLS_HOST__')
117 // Default host
118 expect(result).toContain('"localhost"')
119 })
120​
121 it('should replace __TANSTACK_DEVTOOLS_PROTOCOL__ in matching modules', () => {
122 const transform = connectionPlugin.transform as (
123 code: string,
124 id: string,
125 ) => string | undefined
126 const code = 'const protocol = __TANSTACK_DEVTOOLS_PROTOCOL__'
127 const result = transform(
128 code,
129 'node_modules/@tanstack/event-bus/dist/client.js',
130 )
131 expect(result).toBeDefined()
132 expect(result).not.toContain('__TANSTACK_DEVTOOLS_PROTOCOL__')
133 // Default protocol
134 expect(result).toContain('"http"')
135 })
136​
137 it('should replace all three placeholders in the same code', () => {
138 const transform = connectionPlugin.transform as (
139 code: string,
140 id: string,
141 ) => string | undefined
142 const code = [
143 'const port = __TANSTACK_DEVTOOLS_PORT__;',
144 'const host = __TANSTACK_DEVTOOLS_HOST__;',
145 'const protocol = __TANSTACK_DEVTOOLS_PROTOCOL__;',
146 ].join('\n')
147 const result = transform(
148 code,
149 'node_modules/@tanstack/event-bus/dist/client.js',
150 )
151 expect(result).toBeDefined()
152 expect(result).toContain('4206')
153 expect(result).toContain('"localhost"')
154 expect(result).toContain('"http"')
155 })
156​
157 it('should return undefined for code without any placeholders', () => {
158 const transform = connectionPlugin.transform as (
159 code: string,
160 id: string,
161 ) => string | undefined
162 const result = transform(
163 'const x = 42',
164 'node_modules/@tanstack/event-bus/dist/client.js',
165 )
166 expect(result).toBeUndefined()
167 })
168​
169 it('should return undefined for non-tanstack module IDs', () => {
170 const transform = connectionPlugin.transform as (
171 code: string,
172 id: string,
173 ) => string | undefined
174 const result = transform(
175 'const port = __TANSTACK_DEVTOOLS_PORT__',
176 'node_modules/some-other-package/index.js',
177 )
178 expect(result).toBeUndefined()
179 })
180 })
181​
182 describe('configureServer - HTTPS detection', () => {
183 it('should set protocol to https when server.https is truthy', async () => {
184 const plugins = devtools({
185 eventBusConfig: { enabled: true, port: 0 },
186 })
187 const customServerPlugin = findPlugin(
188 plugins,
189 '@tanstack/devtools:custom-server',
190 )
191 const connectionPlugin = findPlugin(
192 plugins,
193 '@tanstack/devtools:connection-injection',
194 )
195​
196 expect(customServerPlugin).toBeDefined()
197 expect(connectionPlugin).toBeDefined()
198​
199 const mockHttpServer = {
200 on: vi.fn(),
201 address: vi.fn().mockReturnValue({ port: 5173 }),
202 listenerCount: vi.fn().mockReturnValue(0),
203 }
204​
205 const server = createMockServer({
206 https: { key: 'fake-key', cert: 'fake-cert' },
207 host: 'localhost',
208 port: 5173,
209 httpServer: mockHttpServer,
210 })
211​
212 // Call configureServer to trigger HTTPS detection
213 const configureServer = customServerPlugin!.configureServer as (
214 server: any,
215 ) => Promise<void>
216 await configureServer(server)
217​
218 // Now test the transform to verify protocol was set to 'https'
219 const transform = connectionPlugin!.transform as (
220 code: string,
221 id: string,
222 ) => string | undefined
223 const result = transform(
224 'const protocol = __TANSTACK_DEVTOOLS_PROTOCOL__',
225 'node_modules/@tanstack/event-bus/dist/client.js',
226 )
227 expect(result).toContain('"https"')
228 })
229​
230 it('should set protocol to http when server.https is falsy', async () => {
231 const plugins = devtools({
232 eventBusConfig: { enabled: true, port: 0 },
233 })
234 const customServerPlugin = findPlugin(
235 plugins,
236 '@tanstack/devtools:custom-server',
237 )
238 const connectionPlugin = findPlugin(
239 plugins,
240 '@tanstack/devtools:connection-injection',
241 )
242​
243 const server = createMockServer({
244 https: false,
245 port: 5173,
246 })
247​
248 const configureServer = customServerPlugin!.configureServer as (
249 server: any,
250 ) => Promise<void>
251 await configureServer(server)
252​
253 const transform = connectionPlugin!.transform as (
254 code: string,
255 id: string,
256 ) => string | undefined
257 const result = transform(
258 'const protocol = __TANSTACK_DEVTOOLS_PROTOCOL__',
259 'node_modules/@tanstack/event-bus/dist/client.js',
260 )
261 expect(result).toContain('"http"')
262 })
263​
264 it('should use server host config for host placeholder', async () => {
265 const plugins = devtools({
266 eventBusConfig: { enabled: true, port: 0 },
267 })
268 const customServerPlugin = findPlugin(
269 plugins,
270 '@tanstack/devtools:custom-server',
271 )
272 const connectionPlugin = findPlugin(
273 plugins,
274 '@tanstack/devtools:connection-injection',
275 )
276​
277 const server = createMockServer({
278 host: 'my-custom-host.local',
279 port: 5173,
280 })
281​
282 const configureServer = customServerPlugin!.configureServer as (
283 server: any,
284 ) => Promise<void>
285 await configureServer(server)
286​
287 const transform = connectionPlugin!.transform as (
288 code: string,
289 id: string,
290 ) => string | undefined
291 const result = transform(
292 'const host = __TANSTACK_DEVTOOLS_HOST__',
293 'node_modules/@tanstack/event-bus/dist/client.js',
294 )
295 expect(result).toContain('"my-custom-host.local"')
296 })
297​
298 it('should default host to localhost when server.host is boolean true', async () => {
299 const plugins = devtools({
300 eventBusConfig: { enabled: true, port: 0 },
301 })
302 const customServerPlugin = findPlugin(
303 plugins,
304 '@tanstack/devtools:custom-server',
305 )
306 const connectionPlugin = findPlugin(
307 plugins,
308 '@tanstack/devtools:connection-injection',
309 )
310​
311 const server = createMockServer({
312 host: true, // Vite uses `true` to mean "expose on all interfaces"
313 port: 5173,
314 })
315​
316 const configureServer = customServerPlugin!.configureServer as (
317 server: any,
318 ) => Promise<void>
319 await configureServer(server)
320​
321 const transform = connectionPlugin!.transform as (
322 code: string,
323 id: string,
324 ) => string | undefined
325 const result = transform(
326 'const host = __TANSTACK_DEVTOOLS_HOST__',
327 'node_modules/@tanstack/event-bus/dist/client.js',
328 )
329 expect(result).toContain('"localhost"')
330 })
331 })
332​
333 describe('configureServer - onConsolePipe uses pre-wrap console methods', () => {
334 let originalLog: typeof console.log
335 let beforeWrapSpy: ReturnType<typeof vi.fn>
336 let afterWrapSpy: ReturnType<typeof vi.fn>
337​
338 beforeEach(async () => {
339 capturedOnConsolePipe = undefined
340 originalLog = console.log
341 beforeWrapSpy = vi.fn()
342 afterWrapSpy = vi.fn()
343​
344 console.log = beforeWrapSpy
345​
346 const plugins = devtools({ eventBusConfig: { enabled: false } })
347 const customServerPlugin = findPlugin(
348 plugins,
349 '@tanstack/devtools:custom-server',
350 )!
351​
352 const server = {
353 ...createMockServer(),
354 middlewares: {
355 use: vi.fn((handler: any) => {
356 handler({ url: '/not-a-tsd-route', socket: {} }, {}, vi.fn())
357 }),
358 },
359 }
360​
361 const configureServer = customServerPlugin.configureServer as (
362 server: any,
363 ) => Promise<void>
364 await configureServer(server)
365​
366 console.log = afterWrapSpy
367 })
368​
369 afterEach(() => {
370 console.log = originalLog
371 capturedOnConsolePipe = undefined
372 })
373​
374 it('uses the captured original method directly for a known level', () => {
375 expect(capturedOnConsolePipe).toBeDefined()
376 beforeWrapSpy.mockClear()
377 afterWrapSpy.mockClear()
378​
379 capturedOnConsolePipe!([
380 { level: 'log', args: ['test message'], timestamp: Date.now() },
381 ])
382​
383 expect(beforeWrapSpy).toHaveBeenCalledTimes(1)
384 expect(afterWrapSpy).not.toHaveBeenCalled()
385 })
386 it('falls back to captured originalConsole.log for an unknown level, not the live console.log', () => {
387 expect(capturedOnConsolePipe).toBeDefined()
388 beforeWrapSpy.mockClear()
389 afterWrapSpy.mockClear()
390​
391 // 'trace' is not in consolePipingLevels so originalConsole['trace'] is
392 // undefined and the fallback branch is taken.
393 capturedOnConsolePipe!([
394 { level: 'trace', args: ['test message'], timestamp: Date.now() },
395 ])
396​
397 expect(beforeWrapSpy).toHaveBeenCalledTimes(1)
398 expect(afterWrapSpy).not.toHaveBeenCalled()
399 })
400 })
401​
402 describe('plugin array', () => {
403 it('should return an array of plugins', () => {
404 const plugins = devtools()
405 expect(Array.isArray(plugins)).toBe(true)
406 expect(plugins.length).toBeGreaterThan(0)
407 })
408​
409 it('should not contain old port-injection plugin name', () => {
410 const plugins = devtools()
411 const oldPlugin = findPlugin(plugins, '@tanstack/devtools:port-injection')
412 expect(oldPlugin).toBeUndefined()
413 })
414​
415 it('should contain connection-injection plugin', () => {
416 const plugins = devtools()
417 const plugin = findPlugin(
418 plugins,
419 '@tanstack/devtools:connection-injection',
420 )
421 expect(plugin).toBeDefined()
422 })
423​
424 it('runs better-console-logs before console-pipe-transform', () => {
425 // Both plugins are enforce: 'pre' and run in array order. console-pipe
426 // prepends a multi-line IIFE to root entry files; if better-console-logs
427 // ran after, its AST line numbers would be shifted past the end of the
428 // user's file and "Go to Source" links would miss the actual source.
429 const plugins = devtools()
430 const names = plugins.map((p) => p.name)
431 const betterLogsIdx = names.indexOf(
432 '@tanstack/devtools:better-console-logs',
433 )
434 const pipeIdx = names.indexOf('@tanstack/devtools:console-pipe-transform')
435 expect(betterLogsIdx).toBeGreaterThanOrEqual(0)
436 expect(pipeIdx).toBeGreaterThanOrEqual(0)
437 expect(betterLogsIdx).toBeLessThan(pipeIdx)
438 })
439 })
440​
441 describe('runtime-bridge plugin', () => {
442 it('devtools() includes the runtime-bridge plugin', () => {
443 const plugins = devtools()
444 const names = plugins.map((p) => p.name)
445 expect(names).toContain('@tanstack/devtools:runtime-bridge')
446 })
447​
448 it('runtime-bridge transform injects in a server environment', () => {
449 const plugin = devtools().find(
450 (p) => p.name === '@tanstack/devtools:runtime-bridge',
451 )!
452 // emulate Vite's per-environment plugin context
453 const ctx = { environment: { name: 'ssr' } }
454 const handler =
455 typeof plugin.transform === 'function'
456 ? plugin.transform
457 : (plugin.transform as any).handler
458 const out = handler.call(
459 ctx,
460 'class EventClient {}',
461 '/x/node_modules/@tanstack/devtools-event-client/dist/esm/index.js',
462 )
463 expect(out).toBeDefined()
464 expect(String(out)).toContain('__tsdRuntimeBridge')
465 })
466​
467 it('runtime-bridge transform skips the client environment', () => {
468 const plugin = devtools().find(
469 (p) => p.name === '@tanstack/devtools:runtime-bridge',
470 )!
471 const ctx = { environment: { name: 'client' } }
472 const handler =
473 typeof plugin.transform === 'function'
474 ? plugin.transform
475 : (plugin.transform as any).handler
476 const out = handler.call(
477 ctx,
478 'class EventClient {}',
479 '/x/node_modules/@tanstack/devtools-event-client/dist/esm/index.js',
480 )
481 expect(out).toBeUndefined()
482 })
483 })
484})