-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathplugin.ts
More file actions
671 lines (620 loc) · 21 KB
/
plugin.ts
File metadata and controls
671 lines (620 loc) · 21 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import { devtoolsEventClient } from '@tanstack/devtools-client'
import { ServerEventBus } from '@tanstack/devtools-event-bus/server'
import { normalizePath } from 'vite'
import chalk from 'chalk'
import {
handleDevToolsViteRequest,
readPackageJson,
stripEnhancedLogPrefix,
} from './utils'
import { DEFAULT_EDITOR_CONFIG, handleOpenSource } from './editor'
import { removeDevtools } from './remove-devtools'
import { addSourceToJsx } from './inject-source'
import { enhanceConsoleLog } from './enhance-logs'
import { detectDevtoolsFile, injectPluginIntoFile } from './inject-plugin'
import {
addPluginToDevtools,
emitOutdatedDeps,
installPackage,
} from './package-manager'
import { generateConsolePipeCode } from './virtual-console'
import type { ServerResponse } from 'node:http'
import type { Plugin } from 'vite'
import type { EditorConfig } from './editor'
import type {
HttpServerLike,
ServerEventBusConfig,
} from '@tanstack/devtools-event-bus/server'
export type ConsoleLevel = 'log' | 'warn' | 'error' | 'info' | 'debug'
export type TanStackDevtoolsViteConfig = {
/**
* Configuration for the editor integration. Defaults to opening in VS code
*/
editor?: EditorConfig
/**
* The configuration options for the server event bus
*/
eventBusConfig?: ServerEventBusConfig & {
/**
* Should the server event bus be enabled or not
* @default true
*/
enabled?: boolean // defaults to true
}
/**
* Configuration for enhanced logging.
*/
enhancedLogs?: {
/**
* Whether to enable enhanced logging.
* @default true
*/
enabled: boolean
}
/**
* Whether to remove devtools from the production build.
* @default true
*/
removeDevtoolsOnBuild?: boolean
/**
* Whether to log information to the console.
* @default true
*/
logging?: boolean
/**
* Configuration for source injection.
*/
injectSource?: {
/**
* Whether to enable source injection via data-tsd-source.
* @default true
*/
enabled: boolean
/**
* List of files or patterns to ignore for source injection.
*/
ignore?: {
files?: Array<string | RegExp>
components?: Array<string | RegExp>
}
}
/**
* Configuration for console piping between client and server.
* When enabled, console logs from the client will appear in the terminal,
* and server logs will appear in the browser console.
*/
consolePiping?: {
/**
* Whether to enable console piping.
* @default true
*/
enabled?: boolean
/**
* Which console methods to pipe.
* @default ['log', 'warn', 'error', 'info', 'debug']
*/
levels?: Array<ConsoleLevel>
}
}
export const defineDevtoolsConfig = (config: TanStackDevtoolsViteConfig) =>
config
export const devtools = (args?: TanStackDevtoolsViteConfig): Array<Plugin> => {
let port = 5173
const logging = args?.logging ?? true
const enhancedLogsConfig = args?.enhancedLogs ?? { enabled: true }
const injectSourceConfig = args?.injectSource ?? { enabled: true }
const removeDevtoolsOnBuild = args?.removeDevtoolsOnBuild ?? true
const serverBusEnabled = args?.eventBusConfig?.enabled ?? true
const consolePipingConfig = args?.consolePiping ?? { enabled: true }
const consolePipingLevels: Array<ConsoleLevel> =
consolePipingConfig.levels ?? ['log', 'warn', 'error', 'info', 'debug']
let devtoolsFileId: string | null = null
let devtoolsPort: number | null = null
let devtoolsHost: string | null = null
let devtoolsProtocol: 'http' | 'https' | null = null
return [
{
enforce: 'pre',
name: '@tanstack/devtools:inject-source',
apply(config) {
return config.mode === 'development' && injectSourceConfig.enabled
},
transform: {
filter: {
id: {
exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
},
},
handler(code, id) {
return addSourceToJsx(code, id, args?.injectSource?.ignore)
},
},
},
{
name: '@tanstack/devtools:config',
enforce: 'pre',
config(_, { command }) {
// we do not apply any config changes for build
if (command !== 'serve') {
return
}
const solidDedupeDeps = [
'solid-js',
'solid-js/web',
'solid-js/store',
'solid-js/html',
'solid-js/h',
]
return {
resolve: {
dedupe: solidDedupeDeps,
},
optimizeDeps: {
include: solidDedupeDeps,
},
}
},
},
{
enforce: 'pre',
name: '@tanstack/devtools:custom-server',
apply(config) {
// Custom server is only needed in development for piping events to the client
return config.mode === 'development'
},
async configureServer(server) {
if (serverBusEnabled) {
const preferredPort = args?.eventBusConfig?.port ?? 4206
const isHttps = !!server.config.server.https
const serverHost =
typeof server.config.server.host === 'string'
? server.config.server.host
: 'localhost'
devtoolsProtocol = isHttps ? 'https' : 'http'
devtoolsHost = serverHost
const bus = new ServerEventBus({
...args?.eventBusConfig,
port: preferredPort,
host: serverHost,
// When HTTPS is enabled, piggyback on Vite's server
// so WebSocket/SSE connections share the same TLS certificate
...(isHttps && server.httpServer
? { httpServer: server.httpServer as HttpServerLike }
: {}),
})
// start() now handles EADDRINUSE and returns the actual port
devtoolsPort = await bus.start()
}
server.middlewares.use((req, _res, next) => {
if (req.socket.localPort && req.socket.localPort !== port) {
port = req.socket.localPort
}
next()
})
if (server.config.server.port) {
port = server.config.server.port
}
server.httpServer?.on('listening', () => {
port = server.config.server.port
})
const editor = args?.editor ?? DEFAULT_EDITOR_CONFIG
const openInEditor: EditorConfig['open'] = async (
path,
lineNum,
columnNum,
) => {
if (!path) {
return
}
await editor.open(path, lineNum, columnNum)
}
const originalConsole = Object.fromEntries(
consolePipingLevels.map((l) => [l, console[l].bind(console)]),
) as Record<ConsoleLevel, typeof console.log>
// SSE clients for broadcasting server logs to browser
const sseClients: Array<{
res: ServerResponse
id: number
}> = []
let sseClientId = 0
const consolePipingEnabled = consolePipingConfig.enabled ?? true
server.middlewares.use((req, res, next) =>
handleDevToolsViteRequest(req, res, next, {
onOpenSource: (parsedData) => {
const { data, routine } = parsedData
if (routine === 'open-source') {
return handleOpenSource({
data: { type: data.type, data },
openInEditor,
})
}
return
},
...(consolePipingEnabled
? {
onConsolePipe: (entries) => {
for (const entry of entries) {
const prefix = chalk.cyan('[Client]')
const logMethod =
originalConsole[entry.level as ConsoleLevel] ||
originalConsole.log
const cleanedArgs = stripEnhancedLogPrefix(
entry.args,
(loc) => chalk.gray(loc),
)
logMethod(prefix, ...cleanedArgs)
}
},
onConsolePipeSSE: (res, req) => {
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
res.setHeader('Access-Control-Allow-Origin', '*')
res.flushHeaders()
const clientId = ++sseClientId
sseClients.push({ res, id: clientId })
req.on('close', () => {
const index = sseClients.findIndex(
(c) => c.id === clientId,
)
if (index !== -1) {
sseClients.splice(index, 1)
}
})
},
onServerConsolePipe: (entries) => {
try {
const data = JSON.stringify({
entries: entries.map((e) => ({
level: e.level,
args: e.args,
source: 'server',
timestamp: e.timestamp || Date.now(),
})),
})
for (const client of sseClients) {
client.res.write(`data: ${data}\n\n`)
}
} catch {}
},
}
: {}),
}),
)
},
},
{
name: '@tanstack/devtools:remove-devtools-on-build',
apply(config, { command }) {
// Check both command and mode to support various hosting providers
// Some providers (Cloudflare, Netlify, Heroku) might not use 'build' command
// but will always set mode to 'production' for production builds
return (
(command !== 'serve' || config.mode === 'production') &&
removeDevtoolsOnBuild
)
},
enforce: 'pre',
transform(code, id) {
const devtoolPackages = [
'@tanstack/react-devtools',
'@tanstack/preact-devtools',
'@tanstack/solid-devtools',
'@tanstack/vue-devtools',
'@tanstack/devtools',
]
if (
id.includes('node_modules') ||
id.includes('?raw') ||
!devtoolPackages.some((pkg) => code.includes(pkg))
)
return
const transform = removeDevtools(code, id)
if (!transform) return
if (logging) {
console.log(
`\n${chalk.greenBright(`[@tanstack/devtools-vite]`)} Removed devtools code from: ${id.replace(normalizePath(process.cwd()), '')}\n`,
)
}
return transform
},
},
{
name: '@tanstack/devtools:event-client-setup',
apply(config, { command }) {
if (
process.env.CI ||
process.env.NODE_ENV !== 'development' ||
command !== 'serve'
)
return false
return config.mode === 'development'
},
async configureServer() {
const packageJson = await readPackageJson()
const outdatedDeps = emitOutdatedDeps().then((deps) => deps)
// Listen for package installation requests
devtoolsEventClient.on('install-devtools', async (event) => {
const result = await installPackage(event.payload.packageName)
devtoolsEventClient.emit('devtools-installed', {
packageName: event.payload.packageName,
success: result.success,
error: result.error,
})
// If installation was successful, automatically add the plugin to devtools
if (result.success) {
const { packageName, pluginName, pluginImport } = event.payload
console.log(
chalk.blueBright(
`[@tanstack/devtools-vite] Auto-adding ${packageName} to devtools...`,
),
)
const injectResult = addPluginToDevtools(
devtoolsFileId,
packageName,
pluginName,
pluginImport,
)
if (injectResult.success) {
// Emit plugin-added event so the UI updates
devtoolsEventClient.emit('plugin-added', {
packageName,
success: true,
})
// Also re-read package.json to update the UI with the newly installed package
const updatedPackageJson = await readPackageJson()
devtoolsEventClient.emit('package-json-read', {
packageJson: updatedPackageJson,
})
}
}
})
// Listen for add plugin to devtools requests
devtoolsEventClient.on('add-plugin-to-devtools', (event) => {
const { packageName, pluginName, pluginImport } = event.payload
console.log(
chalk.blueBright(
`[@tanstack/devtools-vite] Adding ${packageName} to devtools...`,
),
)
const result = addPluginToDevtools(
devtoolsFileId,
packageName,
pluginName,
pluginImport,
)
devtoolsEventClient.emit('plugin-added', {
packageName,
success: result.success,
error: result.error,
})
})
// Handle bump-package-version event
devtoolsEventClient.on('bump-package-version', async (event) => {
const {
packageName,
devtoolsPackage,
pluginName,
minVersion,
pluginImport,
} = event.payload
console.log(
chalk.blueBright(
`[@tanstack/devtools-vite] Bumping ${packageName} to version ${minVersion}...`,
),
)
// Install the package with the minimum version
const packageWithVersion = minVersion
? `${packageName}@^${minVersion}`
: packageName
const result = await installPackage(packageWithVersion)
if (!result.success) {
console.log(
chalk.redBright(
`[@tanstack/devtools-vite] Failed to bump ${packageName}: ${result.error}`,
),
)
devtoolsEventClient.emit('devtools-installed', {
packageName: devtoolsPackage,
success: false,
error: result.error,
})
return
}
console.log(
chalk.greenBright(
`[@tanstack/devtools-vite] Successfully bumped ${packageName} to ${minVersion}!`,
),
)
// Check if we found the devtools file
if (!devtoolsFileId) {
console.log(
chalk.yellowBright(
`[@tanstack/devtools-vite] Devtools file not found. Skipping auto-injection.`,
),
)
devtoolsEventClient.emit('devtools-installed', {
packageName: devtoolsPackage,
success: true,
})
return
}
// Now inject the devtools plugin
console.log(
chalk.blueBright(
`[@tanstack/devtools-vite] Adding ${devtoolsPackage} to devtools...`,
),
)
const injectResult = injectPluginIntoFile(devtoolsFileId, {
packageName: devtoolsPackage,
pluginName,
pluginImport,
})
if (injectResult.success) {
console.log(
chalk.greenBright(
`[@tanstack/devtools-vite] Successfully added ${devtoolsPackage} to devtools!`,
),
)
devtoolsEventClient.emit('plugin-added', {
packageName: devtoolsPackage,
success: true,
})
// Re-read package.json to update the UI
const updatedPackageJson = await readPackageJson()
devtoolsEventClient.emit('package-json-read', {
packageJson: updatedPackageJson,
})
} else {
console.log(
chalk.redBright(
`[@tanstack/devtools-vite] Failed to add ${devtoolsPackage} to devtools: ${injectResult.error}`,
),
)
devtoolsEventClient.emit('plugin-added', {
packageName: devtoolsPackage,
success: false,
error: injectResult.error,
})
}
})
// whenever a client mounts we send all the current info to the subscribers
devtoolsEventClient.on('mounted', async () => {
devtoolsEventClient.emit('outdated-deps-read', {
outdatedDeps: await outdatedDeps,
})
devtoolsEventClient.emit('package-json-read', {
packageJson,
})
})
// Console piping is now handled via HTTP endpoints in the custom-server plugin
},
async handleHotUpdate({ file }) {
if (file.endsWith('package.json')) {
const newPackageJson = await readPackageJson()
devtoolsEventClient.emit('package-json-read', {
packageJson: newPackageJson,
})
emitOutdatedDeps()
}
},
},
// Inject console piping code into entry files (both client and server)
{
name: '@tanstack/devtools:console-pipe-transform',
enforce: 'pre',
apply(config, { command }) {
return (
config.mode === 'development' &&
command === 'serve' &&
(consolePipingConfig.enabled ?? true)
)
},
transform: {
filter: {
id: {
include: /\.(tsx?|jsx?)$/,
exclude: [/node_modules/, /\/dist\//, /\?/],
},
code: {
exclude: /__tsdConsolePipe/, // avoid transforming files that already contain the console pipe code
},
},
handler(code) {
// Check if this is a root entry file (with <html> JSX or client entry points)
// In SSR frameworks, this file runs on BOTH server (SSR) and client (hydration)
// so our runtime check (typeof window === 'undefined') handles both environments
const isRootEntry =
/<html[\s>]/i.test(code) ||
code.includes('StartClient') ||
code.includes('hydrateRoot') ||
code.includes('createRoot') ||
(code.includes('solid-js/web') && code.includes('render('))
if (isRootEntry) {
const viteServerUrl = `http://localhost:${port}`
const inlineCode = generateConsolePipeCode(
consolePipingLevels,
viteServerUrl,
)
return `${inlineCode}\n${code}`
}
return undefined
},
},
},
{
name: '@tanstack/devtools:better-console-logs',
enforce: 'pre',
apply(config) {
return config.mode === 'development' && enhancedLogsConfig.enabled
},
transform: {
filter: {
id: {
exclude: [/node_modules/, /\?raw/, /\/dist\//, /\/build\//],
},
code: {
include: 'console.',
},
},
handler(code, id) {
return enhanceConsoleLog(code, id, port)
},
},
},
{
name: '@tanstack/devtools:inject-plugin',
apply(config, { command }) {
return config.mode === 'development' && command === 'serve'
},
transform(code, id) {
// First pass: find where TanStackDevtools is imported
if (!devtoolsFileId && detectDevtoolsFile(code)) {
// Extract actual file path (remove query params)
const [filePath] = id.split('?')
if (filePath) {
devtoolsFileId = filePath
}
}
return undefined
},
},
{
name: '@tanstack/devtools:connection-injection',
apply(config, { command }) {
return config.mode === 'development' && command === 'serve'
},
transform(code, id) {
// Only transform @tanstack packages that contain the connection placeholders
const hasPlaceholder =
code.includes('__TANSTACK_DEVTOOLS_PORT__') ||
code.includes('__TANSTACK_DEVTOOLS_HOST__') ||
code.includes('__TANSTACK_DEVTOOLS_PROTOCOL__')
if (!hasPlaceholder) return
if (
!id.includes('@tanstack/devtools') &&
!id.includes('@tanstack/event-bus')
)
return
// Replace placeholders with actual values (or fallback defaults)
const portValue = devtoolsPort ?? 4206
const hostValue = devtoolsHost ?? 'localhost'
const protocolValue = devtoolsProtocol ?? 'http'
let result = code
result = result.replace(
/__TANSTACK_DEVTOOLS_PORT__/g,
String(portValue),
)
result = result.replace(
/__TANSTACK_DEVTOOLS_HOST__/g,
JSON.stringify(hostValue),
)
result = result.replace(
/__TANSTACK_DEVTOOLS_PROTOCOL__/g,
JSON.stringify(protocolValue),
)
return result
},
},
]
}