Open History to see the last commit
1import {
2 DEFAULT_EDITOR_CONFIG,
3 TANSTACK_DEVTOOLS_PACKAGES,
4 addPluginToDevtools,
5 addSourceToJsx,
6 detectDevtoolsFile,
7 emitOutdatedDeps,
8 enhanceConsoleLog,
9 generateConsolePipeCode,
10 handleDevToolsRequest,
11 handleOpenSource,
12 injectPluginIntoFile,
13 injectRuntimeBridge,
14 installPackage,
15 normalizePath,
16 readPackageJson,
17 removeDevtools,
18 stripEnhancedLogPrefix,
19 wireRuntimeBridgeChannels,
20} from '@tanstack/devtools-bundler-core'
21import { devtoolsEventClient } from '@tanstack/devtools-client'
22import { ServerEventBus } from '@tanstack/devtools-event-bus/server'
23import chalk from 'chalk'
24import type { ServerResponse } from 'node:http'
25import type {
26 ConsoleLevel,
27 EditorConfig,
28 TanStackDevtoolsConfig,
29} from '@tanstack/devtools-bundler-core'
30import type { HttpServerLike } from '@tanstack/devtools-event-bus/server'
31import type { Plugin } from 'vite'
32β
33export type { ConsoleLevel } from '@tanstack/devtools-bundler-core'
34export type TanStackDevtoolsViteConfig = TanStackDevtoolsConfig
35β
36export const defineDevtoolsConfig = (config: TanStackDevtoolsViteConfig) =>
37 config
38β
39export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
40 let port = 5173
41 const logging = args?.logging ?? true
42 const enhancedLogsConfig = args?.enhancedLogs ?? { enabled: true }
43 const injectSourceConfig = args?.injectSource ?? { enabled: true }
44 const removeDevtoolsOnBuild = args?.removeDevtoolsOnBuild ?? true
45 const serverBusEnabled = args?.eventBusConfig?.enabled ?? true
46 const consolePipingConfig = args?.consolePiping ?? { enabled: true }
47 const consolePipingLevels: Array<ConsoleLevel> =
48 consolePipingConfig.levels ?? ['log', 'warn', 'error', 'info', 'debug']
49β
50 let devtoolsFileId: string | null = null
51 let devtoolsPort: number | null = null
52 let devtoolsHost: string | null = null
53 let devtoolsProtocol: 'http' | 'https' | null = null
54β
55 return [
56 {
57 enforce: 'pre',
58 name: '@tanstack/devtools:inject-source',
59 apply(config) {
60 return config.mode === 'development' && injectSourceConfig.enabled
61 },
62 transform: {
63 // Run before the transforms of plugins without `order: 'pre'`, also when
64 // devtools() is not first in the plugins array. A plugin that changes
65 // the code of one environment only would shift the lines and make the
66 // SSR and client locations differ, which breaks hydration. An earlier
67 // plugin whose transform also has `order: 'pre'` still runs first.
68 order: 'pre',
69 filter: {
70 id: {
71 exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
72 },
73 },
74 handler(code, id) {
75 return addSourceToJsx(code, id, args?.injectSource?.ignore)
76 },
77 },
78 },
79 {
80 name: '@tanstack/devtools:config',
81 enforce: 'pre',
82 config(_, { command }) {
83 // we do not apply any config changes for build
84 if (command !== 'serve') {
85 return
86 }
87β
88 /* const solidDedupeDeps = [
89 'solid-js',
90 'solid-js/web',
91 'solid-js/store',
92 'solid-js/html',
93 'solid-js/h',
94 ]
95β
96 return {
97 resolve: {
98 dedupe: solidDedupeDeps,
99 },
100 optimizeDeps: {
101 include: solidDedupeDeps,
102 },
103 } */
104 },
105 },
106 {
107 enforce: 'pre',
108 name: '@tanstack/devtools:custom-server',
109 apply(config) {
110 // Custom server is only needed in development for piping events to the client
111 return config.mode === 'development'
112 },
113 async configureServer(server) {
114 if (serverBusEnabled) {
115 const preferredPort = args?.eventBusConfig?.port ?? 4206
116 const isHttps = !!server.config.server.https
117 const serverHost =
118 typeof server.config.server.host === 'string'
119 ? server.config.server.host
120 : 'localhost'
121β
122 devtoolsProtocol = isHttps ? 'https' : 'http'
123 devtoolsHost = serverHost
124β
125 const bus = new ServerEventBus({
126 ...args?.eventBusConfig,
127 port: preferredPort,
128 host: serverHost,
129 // When HTTPS is enabled, piggyback on Vite's server
130 // so WebSocket/SSE connections share the same TLS certificate
131 ...(isHttps && server.httpServer
132 ? { httpServer: server.httpServer as HttpServerLike }
133 : {}),
134 })
135 // start() now handles EADDRINUSE and returns the actual port
136 devtoolsPort = await bus.start()
137 if ((server as any).environments) {
138 const teardownBridge = wireRuntimeBridgeChannels(
139 server as unknown as Parameters<
140 typeof wireRuntimeBridgeChannels
141 >[0],
142 () => globalThis.__TANSTACK_EVENT_TARGET__,
143 )
144 server.httpServer?.on('close', teardownBridge)
145 }
146 }
147β
148 server.middlewares.use((req, _res, next) => {
149 if (req.socket.localPort && req.socket.localPort !== port) {
150 port = req.socket.localPort
151 }
152 next()
153 })
154 if (server.config.server.port) {
155 port = server.config.server.port
156 }
157β
158 server.httpServer?.on('listening', () => {
159 port = server.config.server.port
160 })
161β
162 const editor = args?.editor ?? DEFAULT_EDITOR_CONFIG
163 const openInEditor: EditorConfig['open'] = async (
164 path,
165 lineNum,
166 columnNum,
167 ) => {
168 if (!path) {
169 return
170 }
171 await editor.open(path, lineNum, columnNum)
172 }
173β
174 const originalConsole = Object.fromEntries(
175 consolePipingLevels.map((l) => [l, console[l].bind(console)]),
176 ) as Partial<Record<ConsoleLevel, typeof console.log>>
177β
178 // SSE clients for broadcasting server logs to browser
179 const sseClients: Array<{
180 res: ServerResponse
181 id: number
182 }> = []
183 let sseClientId = 0
184 const consolePipingEnabled = consolePipingConfig.enabled ?? true
185β
186 server.middlewares.use((req, res, next) =>
187 handleDevToolsRequest(req, res, next, {
188 onOpenSource: (parsedData) => {
189 const { data, routine } = parsedData
190 if (routine === 'open-source') {
191 return handleOpenSource({
192 data: { type: data.type, data },
193 openInEditor,
194 })
195 }
196 return
197 },
198 ...(consolePipingEnabled
199 ? {
200 onConsolePipe: (entries) => {
201 for (const entry of entries) {
202 const prefix = chalk.cyan('[Client]')
203 const logMethod =
204 originalConsole[entry.level as ConsoleLevel] ??
205 // log exists in consolePipingLevels
206 originalConsole.log!
207β
208 const cleanedArgs = stripEnhancedLogPrefix(
209 entry.args,
210 (loc) => chalk.gray(loc),
211 )
212 logMethod(prefix, ...cleanedArgs)
213 }
214 },
215 onConsolePipeSSE: (res, req) => {
216 res.setHeader('Content-Type', 'text/event-stream')
217 res.setHeader('Cache-Control', 'no-cache')
218 res.setHeader('Connection', 'keep-alive')
219 res.setHeader('Access-Control-Allow-Origin', '*')
220 res.flushHeaders()
221β
222 const clientId = ++sseClientId
223 sseClients.push({ res, id: clientId })
224β
225 req.on('close', () => {
226 const index = sseClients.findIndex(
227 (c) => c.id === clientId,
228 )
229 if (index !== -1) {
230 sseClients.splice(index, 1)
231 }
232 })
233 },
234 onServerConsolePipe: (entries) => {
235 try {
236 const data = JSON.stringify({
237 entries: entries.map((e) => ({
238 level: e.level,
239 args: e.args,
240 source: 'server',
241 timestamp: e.timestamp || Date.now(),
242 })),
243 })
244β
245 for (const client of sseClients) {
246 client.res.write(`data: ${data}\n\n`)
247 }
248 } catch {}
249 },
250 }
251 : {}),
252 }),
253 )
254 },
255 },
256 {
257 name: '@tanstack/devtools:remove-devtools-on-build',
258 apply(config, { command }) {
259 // Check both command and mode to support various hosting providers
260 // Some providers (Cloudflare, Netlify, Heroku) might not use 'build' command
261 // but will always set mode to 'production' for production builds
262 return (
263 (command !== 'serve' || config.mode === 'production') &&
264 removeDevtoolsOnBuild
265 )
266 },
267 enforce: 'pre',
268 transform(code, id) {
269 if (
270 id.includes('node_modules') ||
271 id.includes('?raw') ||
272 !TANSTACK_DEVTOOLS_PACKAGES.some((pkg) => code.includes(pkg))
273 )
274 return
275 const transform = removeDevtools(code, id)
276 if (!transform) return
277 if (logging) {
278 console.log(
279 `\n${chalk.greenBright(`[@tanstack/devtools-vite]`)} Removed devtools code from: ${id.replace(normalizePath(process.cwd()), '')}\n`,
280 )
281 }
282 return transform
283 },
284 },
285 {
286 name: '@tanstack/devtools:event-client-setup',
287 apply(config, { command }) {
288 if (
289 process.env.CI ||
290 process.env.NODE_ENV !== 'development' ||
291 command !== 'serve'
292 )
293 return false
294 return config.mode === 'development'
295 },
296 async configureServer() {
297 const packageJson = await readPackageJson()
298 const outdatedDeps = emitOutdatedDeps().then((deps) => deps)
299β
300 // Listen for package installation requests
301 devtoolsEventClient.on('install-devtools', async (event) => {
302 const result = await installPackage(event.payload.packageName)
303 devtoolsEventClient.emit('devtools-installed', {
304 packageName: event.payload.packageName,
305 success: result.success,
306 error: result.error,
307 })
308β
309 // If installation was successful, automatically add the plugin to devtools
310 if (result.success) {
311 const { packageName, pluginName, pluginImport } = event.payload
312β
313 console.log(
314 chalk.blueBright(
315 `[@tanstack/devtools-vite] Auto-adding ${packageName} to devtools...`,
316 ),
317 )
318β
319 const injectResult = addPluginToDevtools(
320 devtoolsFileId,
321 packageName,
322 pluginName,
323 pluginImport,
324 )
325β
326 if (injectResult.success) {
327 // Emit plugin-added event so the UI updates
328 devtoolsEventClient.emit('plugin-added', {
329 packageName,
330 success: true,
331 })
332β
333 // Also re-read package.json to update the UI with the newly installed package
334 const updatedPackageJson = await readPackageJson()
335 devtoolsEventClient.emit('package-json-read', {
336 packageJson: updatedPackageJson,
337 })
338 }
339 }
340 })
341β
342 // Listen for add plugin to devtools requests
343 devtoolsEventClient.on('add-plugin-to-devtools', (event) => {
344 const { packageName, pluginName, pluginImport } = event.payload
345β
346 console.log(
347 chalk.blueBright(
348 `[@tanstack/devtools-vite] Adding ${packageName} to devtools...`,
349 ),
350 )
351β
352 const result = addPluginToDevtools(
353 devtoolsFileId,
354 packageName,
355 pluginName,
356 pluginImport,
357 )
358β
359 devtoolsEventClient.emit('plugin-added', {
360 packageName,
361 success: result.success,
362 error: result.error,
363 })
364 })
365β
366 // Handle bump-package-version event
367 devtoolsEventClient.on('bump-package-version', async (event) => {
368 const {
369 packageName,
370 devtoolsPackage,
371 pluginName,
372 minVersion,
373 pluginImport,
374 } = event.payload
375β
376 console.log(
377 chalk.blueBright(
378 `[@tanstack/devtools-vite] Bumping ${packageName} to version ${minVersion}...`,
379 ),
380 )
381β
382 // Install the package with the minimum version
383 const packageWithVersion = minVersion
384 ? `${packageName}@^${minVersion}`
385 : packageName
386β
387 const result = await installPackage(packageWithVersion)
388β
389 if (!result.success) {
390 console.log(
391 chalk.redBright(
392 `[@tanstack/devtools-vite] Failed to bump ${packageName}: ${result.error}`,
393 ),
394 )
395 devtoolsEventClient.emit('devtools-installed', {
396 packageName: devtoolsPackage,
397 success: false,
398 error: result.error,
399 })
400 return
401 }
402β
403 console.log(
404 chalk.greenBright(
405 `[@tanstack/devtools-vite] Successfully bumped ${packageName} to ${minVersion}!`,
406 ),
407 )
408β
409 // Check if we found the devtools file
410 if (!devtoolsFileId) {
411 console.log(
412 chalk.yellowBright(
413 `[@tanstack/devtools-vite] Devtools file not found. Skipping auto-injection.`,
414 ),
415 )
416 devtoolsEventClient.emit('devtools-installed', {
417 packageName: devtoolsPackage,
418 success: true,
419 })
420 return
421 }
422β
423 // Now inject the devtools plugin
424 console.log(
425 chalk.blueBright(
426 `[@tanstack/devtools-vite] Adding ${devtoolsPackage} to devtools...`,
427 ),
428 )
429β
430 const injectResult = injectPluginIntoFile(devtoolsFileId, {
431 packageName: devtoolsPackage,
432 pluginName,
433 pluginImport,
434 })
435β
436 if (injectResult.success) {
437 console.log(
438 chalk.greenBright(
439 `[@tanstack/devtools-vite] Successfully added ${devtoolsPackage} to devtools!`,
440 ),
441 )
442β
443 devtoolsEventClient.emit('plugin-added', {
444 packageName: devtoolsPackage,
445 success: true,
446 })
447β
448 // Re-read package.json to update the UI
449 const updatedPackageJson = await readPackageJson()
450 devtoolsEventClient.emit('package-json-read', {
451 packageJson: updatedPackageJson,
452 })
453 } else {
454 console.log(
455 chalk.redBright(
456 `[@tanstack/devtools-vite] Failed to add ${devtoolsPackage} to devtools: ${injectResult.error}`,
457 ),
458 )
459β
460 devtoolsEventClient.emit('plugin-added', {
461 packageName: devtoolsPackage,
462 success: false,
463 error: injectResult.error,
464 })
465 }
466 })
467β
468 // whenever a client mounts we send all the current info to the subscribers
469 devtoolsEventClient.on('mounted', async () => {
470 devtoolsEventClient.emit('outdated-deps-read', {
471 outdatedDeps: await outdatedDeps,
472 })
473 devtoolsEventClient.emit('package-json-read', {
474 packageJson,
475 })
476 })
477β
478 // Console piping is now handled via HTTP endpoints in the custom-server plugin
479 },
480 async handleHotUpdate({ file }) {
481 if (file.endsWith('package.json')) {
482 const newPackageJson = await readPackageJson()
483 devtoolsEventClient.emit('package-json-read', {
484 packageJson: newPackageJson,
485 })
486 emitOutdatedDeps()
487 }
488 },
489 },
490 // Enhanced logs must run BEFORE console-pipe-transform: the latter
491 // prepends a multi-line IIFE to root entry files, which would shift
492 // every line number computed by the oxc-parser AST and produce
493 // "Go to Source" links pointing past the end of the user's file.
494 {
495 name: '@tanstack/devtools:better-console-logs',
496 enforce: 'pre',
497 apply(config) {
498 return config.mode === 'development' && enhancedLogsConfig.enabled
499 },
500 transform: {
501 filter: {
502 id: {
503 exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
504 },
505 code: {
506 include: 'console.',
507 },
508 },
509 handler(code, id) {
510 return enhanceConsoleLog(code, id, port)
511 },
512 },
513 },
514 // Inject console piping code into entry files (both client and server)
515 {
516 name: '@tanstack/devtools:console-pipe-transform',
517 enforce: 'pre',
518 apply(config, { command }) {
519 return (
520 config.mode === 'development' &&
521 command === 'serve' &&
522 (consolePipingConfig.enabled ?? true)
523 )
524 },
525 transform: {
526 filter: {
527 id: {
528 include: /\.(tsx?|jsx?)$/,
529 exclude: [/node_modules/, /\/dist\//, /\?/],
530 },
531 code: {
532 exclude: /__tsdConsolePipe/, // avoid transforming files that already contain the console pipe code
533 },
534 },
535 handler(code) {
536 // Check if this is a root entry file (with <html> JSX or client entry points)
537 // In SSR frameworks, this file runs on BOTH server (SSR) and client (hydration)
538 // so our runtime check (typeof window === 'undefined') handles both environments
539 const isRootEntry =
540 /<html[\s>]/i.test(code) ||
541 code.includes('StartClient') ||
542 code.includes('hydrateRoot') ||
543 code.includes('createRoot') ||
544 // Solid 1 renders from `solid-js/web`, Solid 2 from `@solidjs/web`.
545 ((code.includes('solid-js/web') || code.includes('@solidjs/web')) &&
546 code.includes('render('))
547β
548 if (isRootEntry) {
549 const viteServerUrl = `http://localhost:${port}`
550 const inlineCode = generateConsolePipeCode(
551 consolePipingLevels,
552 viteServerUrl,
553 )
554β
555 return `${inlineCode}\n${code}`
556 }
557β
558 return undefined
559 },
560 },
561 },
562 {
563 name: '@tanstack/devtools:inject-plugin',
564 apply(config, { command }) {
565 return config.mode === 'development' && command === 'serve'
566 },
567 transform(code, id) {
568 // First pass: find where TanStackDevtools is imported
569 if (!devtoolsFileId && detectDevtoolsFile(code)) {
570 // Extract actual file path (remove query params)
571 const [filePath] = id.split('?')
572 if (filePath) {
573 devtoolsFileId = filePath
574 }
575 }
576β
577 return undefined
578 },
579 },
580 {
581 name: '@tanstack/devtools:connection-injection',
582 apply(config, { command }) {
583 return config.mode === 'development' && command === 'serve'
584 },
585 transform(code, id) {
586 // Only transform @tanstack packages that contain the connection placeholders
587 const hasPlaceholder =
588 code.includes('__TANSTACK_DEVTOOLS_PORT__') ||
589 code.includes('__TANSTACK_DEVTOOLS_HOST__') ||
590 code.includes('__TANSTACK_DEVTOOLS_PROTOCOL__')
591 if (!hasPlaceholder) return
592 // Vite pre-bundles npm installs into chunks under `.vite/deps*`, whose
593 // ids no longer name the package.
594 if (
595 !id.includes('@tanstack/devtools') &&
596 !id.includes('@tanstack/event-bus') &&
597 !id.includes('/.vite/deps')
598 )
599 return
600β
601 // Replace placeholders with actual values (or fallback defaults)
602 const portValue = devtoolsPort ?? 4206
603 const hostValue = devtoolsHost ?? 'localhost'
604 const protocolValue = devtoolsProtocol ?? 'http'
605β
606 let result = code
607 result = result.replace(
608 /__TANSTACK_DEVTOOLS_PORT__/g,
609 String(portValue),
610 )
611 result = result.replace(
612 /__TANSTACK_DEVTOOLS_HOST__/g,
613 JSON.stringify(hostValue),
614 )
615 result = result.replace(
616 /__TANSTACK_DEVTOOLS_PROTOCOL__/g,
617 JSON.stringify(protocolValue),
618 )
619 return result
620 },
621 },
622 {
623 name: '@tanstack/devtools:runtime-bridge',
624 apply(config, { command }) {
625 return config.mode === 'development' && command === 'serve'
626 },
627 transform(code, id) {
628 if (id.includes('?')) return
629 return injectRuntimeBridge(
630 code,
631 id,
632 (this as any).environment?.name as string | undefined,
633 )
634 },
635 },
636 ]
637}