create-fluxstack 1.7.4 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/.dockerignore +82 -0
  2. package/Dockerfile +70 -0
  3. package/app/server/app.ts +20 -5
  4. package/app/server/backend-only.ts +15 -12
  5. package/app/server/index.ts +83 -96
  6. package/app/server/live/FluxStackConfig.ts +5 -5
  7. package/app/server/routes/env-test.ts +59 -0
  8. package/config/app.config.ts +2 -54
  9. package/config/client.config.ts +95 -0
  10. package/config/index.ts +57 -22
  11. package/config/monitoring.config.ts +114 -0
  12. package/config/plugins.config.ts +59 -0
  13. package/config/runtime.config.ts +0 -17
  14. package/config/server.config.ts +50 -30
  15. package/core/build/bundler.ts +17 -16
  16. package/core/build/flux-plugins-generator.ts +29 -18
  17. package/core/build/index.ts +72 -65
  18. package/core/build/live-components-generator.ts +29 -18
  19. package/core/build/optimizer.ts +37 -17
  20. package/core/cli/index.ts +6 -2
  21. package/core/config/env.ts +4 -0
  22. package/core/config/runtime-config.ts +10 -8
  23. package/core/config/schema.ts +24 -2
  24. package/core/framework/server.ts +1 -0
  25. package/core/index.ts +31 -23
  26. package/core/plugins/built-in/monitoring/index.ts +2 -0
  27. package/core/plugins/built-in/static/index.ts +73 -244
  28. package/core/plugins/built-in/swagger/index.ts +2 -0
  29. package/core/plugins/built-in/vite/index.ts +377 -374
  30. package/core/plugins/config.ts +2 -0
  31. package/core/plugins/discovery.ts +2 -0
  32. package/core/plugins/executor.ts +2 -0
  33. package/core/plugins/index.ts +2 -2
  34. package/core/plugins/registry.ts +22 -18
  35. package/core/server/backend-entry.ts +51 -0
  36. package/core/types/plugin.ts +6 -0
  37. package/core/utils/build-logger.ts +324 -0
  38. package/core/utils/config-schema.ts +2 -6
  39. package/core/utils/helpers.ts +14 -9
  40. package/core/utils/regenerate-files.ts +69 -0
  41. package/core/utils/version.ts +1 -1
  42. package/fluxstack.config.ts +138 -252
  43. package/package.json +2 -17
  44. package/vitest.config.ts +8 -26
  45. package/config/build.config.ts +0 -24
@@ -1,375 +1,378 @@
1
- import type { FluxStack, PluginContext, RequestContext } from "../../types"
2
- import { createServer, type ViteDevServer } from 'vite'
3
-
4
- let viteServer: ViteDevServer | null = null
5
-
6
- export const vitePlugin: Plugin = {
7
- name: "vite",
8
- version: "1.0.0",
9
- description: "Enhanced Vite integration plugin for FluxStack with improved error handling and monitoring",
10
- author: "FluxStack Team",
11
- priority: 800, // Should run early to setup proxying
12
- category: "development",
13
- tags: ["vite", "development", "hot-reload"],
14
- dependencies: [], // No dependencies
15
-
16
- configSchema: {
17
- type: "object",
18
- properties: {
19
- enabled: {
20
- type: "boolean",
21
- description: "Enable Vite integration"
22
- },
23
- port: {
24
- type: "number",
25
- minimum: 1,
26
- maximum: 65535,
27
- description: "Vite development server port"
28
- },
29
- host: {
30
- type: "string",
31
- description: "Vite development server host"
32
- },
33
- checkInterval: {
34
- type: "number",
35
- minimum: 100,
36
- description: "Interval to check if Vite is running (ms)"
37
- },
38
- maxRetries: {
39
- type: "number",
40
- minimum: 1,
41
- description: "Maximum retries to connect to Vite"
42
- },
43
- timeout: {
44
- type: "number",
45
- minimum: 100,
46
- description: "Timeout for Vite requests (ms)"
47
- },
48
- proxyPaths: {
49
- type: "array",
50
- items: { type: "string" },
51
- description: "Paths to proxy to Vite (defaults to all non-API paths)"
52
- },
53
- excludePaths: {
54
- type: "array",
55
- items: { type: "string" },
56
- description: "Paths to exclude from Vite proxying"
57
- }
58
- },
59
- additionalProperties: false
60
- },
61
-
62
- defaultConfig: {
63
- enabled: true,
64
- port: 5173,
65
- host: "localhost",
66
- checkInterval: 2000,
67
- maxRetries: 10,
68
- timeout: 5000,
69
- proxyPaths: [],
70
- excludePaths: []
71
- },
72
-
73
- setup: async (context: PluginContext) => {
74
- const config = getPluginConfig(context)
75
-
76
- if (!config.enabled || !context.config.client) {
77
- context.logger.debug('Vite plugin disabled or no client configuration found')
78
- return
79
- }
80
-
81
- const vitePort = config.port || context.config.client.port || 5173
82
- const viteHost = config.host || "localhost"
83
-
84
- try {
85
- const { startGroup, endGroup, logInGroup } = await import('../../../utils/logger/group-logger')
86
-
87
- startGroup({
88
- title: 'Vite Development Server',
89
- icon: '🎨',
90
- color: 'magenta',
91
- collapsed: true
92
- })
93
-
94
- logInGroup(`Starting on ${viteHost}:${vitePort}`, '📍')
95
-
96
- // Start Vite dev server programmatically
97
- viteServer = await createServer({
98
- configFile: './vite.config.ts',
99
- // Don't override root - let vite.config.ts handle it
100
- server: {
101
- port: vitePort,
102
- host: viteHost,
103
- strictPort: true
104
- },
105
- logLevel: 'warn' // Suppress Vite's verbose logs
106
- })
107
-
108
- await viteServer.listen()
109
-
110
- // Custom URL display instead of viteServer.printUrls()
111
- logInGroup(`Local: http://${viteHost}:${vitePort}/`, '✅')
112
- logInGroup('Hot reload coordination active', '🔄')
113
-
114
- endGroup()
115
- console.log('') // Separator line
116
-
117
- // Store Vite config in context for later use
118
- ; (context as any).viteConfig = {
119
- port: vitePort,
120
- host: viteHost,
121
- ...config,
122
- server: viteServer
123
- }
124
-
125
- // Setup cleanup on process exit
126
- const cleanup = async () => {
127
- if (viteServer) {
128
- context.logger.debug('🛑 Stopping Vite server...')
129
- await viteServer.close()
130
- viteServer = null
131
- }
132
- }
133
-
134
- process.on('SIGINT', cleanup)
135
- process.on('SIGTERM', cleanup)
136
- process.on('exit', cleanup)
137
-
138
- } catch (error) {
139
- context.logger.error('❌ Failed to start Vite server programmatically:', error)
140
- context.logger.debug('⚠️ Falling back to monitoring mode...')
141
-
142
- // Fallback to monitoring if programmatic start fails
143
- ; (context as any).viteConfig = {
144
- port: vitePort,
145
- host: viteHost,
146
- ...config
147
- }
148
- monitorVite(context, viteHost, vitePort, config)
149
- }
150
- },
151
-
152
- onServerStart: async (context: PluginContext) => {
153
- const config = getPluginConfig(context)
154
- const viteConfig = (context as any).viteConfig
155
-
156
- if (config.enabled && viteConfig) {
157
- context.logger.debug(`Vite integration active - monitoring ${viteConfig.host}:${viteConfig.port}`)
158
- }
159
- },
160
-
161
- onBeforeRoute: async (requestContext: RequestContext) => {
162
- // Skip API routes and swagger - let them be handled by backend
163
- if (requestContext.path.startsWith("/api") || requestContext.path.startsWith("/swagger")) {
164
- return
165
- }
166
-
167
- // For Vite internal routes, proxy directly to Vite server
168
- if (requestContext.path.startsWith("/@") || // All Vite internal routes (/@vite/, /@fs/, /@react-refresh, etc.)
169
- requestContext.path.startsWith("/__vite") || // Vite HMR and dev routes
170
- requestContext.path.startsWith("/node_modules") || // Direct node_modules access
171
- requestContext.path.includes("/.vite/") || // Vite cache and deps
172
- requestContext.path.endsWith(".js.map") || // Source maps
173
- requestContext.path.endsWith(".css.map")) { // CSS source maps
174
-
175
- // Use fixed configuration for Vite proxy
176
- const viteHost = "localhost"
177
- const vitePort = 5173
178
-
179
- try {
180
- const url = new URL(requestContext.request.url)
181
- const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
182
-
183
- // Forward request to Vite
184
- const response = await fetch(viteUrl, {
185
- method: requestContext.method,
186
- headers: requestContext.headers,
187
- body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
188
- })
189
-
190
- // Return the Vite response
191
- const body = await response.arrayBuffer()
192
-
193
- requestContext.handled = true
194
- requestContext.response = new Response(body, {
195
- status: response.status,
196
- statusText: response.statusText,
197
- headers: response.headers
198
- })
199
-
200
- } catch (viteError) {
201
- // If Vite fails, let the request continue to normal routing (will become 404)
202
- // Only log if explicitly enabled for debugging
203
- const { serverConfig } = await import('@/config/server.config')
204
- if (serverConfig.enableViteProxyLogs) {
205
- console.warn(`Vite proxy error: ${viteError}`)
206
- }
207
- }
208
- return
209
- }
210
-
211
- // Use fixed configuration for simplicity - Vite should be running on port 5173
212
- const viteHost = "localhost"
213
- const vitePort = 5173
214
-
215
- try {
216
- const url = new URL(requestContext.request.url)
217
- const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
218
-
219
- // Forward request to Vite
220
- const response = await fetch(viteUrl, {
221
- method: requestContext.method,
222
- headers: requestContext.headers,
223
- body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
224
- })
225
-
226
- // If Vite responds successfully, handle the request
227
- if (response.ok || response.status < 500) {
228
- // Return a proper Response object with all headers and status
229
- const body = await response.arrayBuffer()
230
-
231
- requestContext.handled = true
232
- requestContext.response = new Response(body, {
233
- status: response.status,
234
- statusText: response.statusText,
235
- headers: response.headers
236
- })
237
- }
238
-
239
- } catch (viteError) {
240
- // If Vite fails, let the request continue to normal routing (will become 404)
241
- // Only log if explicitly enabled for debugging
242
- const { serverConfig } = await import('@/config/server.config')
243
- if (serverConfig.enableViteProxyLogs) {
244
- console.warn(`Vite proxy error: ${viteError}`)
245
- }
246
- }
247
- }
248
- }
249
-
250
- // Helper function to get plugin config
251
- function getPluginConfig(context: PluginContext) {
252
- const pluginConfig = context.config.plugins.config?.vite || {}
253
- return { ...vitePlugin.defaultConfig, ...pluginConfig }
254
- }
255
-
256
- // Monitor Vite server status with automatic port detection
257
- async function monitorVite(
258
- context: PluginContext,
259
- host: string,
260
- initialPort: number,
261
- config: any
262
- ) {
263
- let retries = 0
264
- let isConnected = false
265
- let actualPort = initialPort
266
- let portDetected = false
267
-
268
- const checkVite = async () => {
269
- try {
270
- // If we haven't found the correct port yet, try to detect it
271
- if (!portDetected) {
272
- const detectedPort = await detectVitePort(host, initialPort)
273
- if (detectedPort !== null) {
274
- actualPort = detectedPort
275
- portDetected = true
276
- // Update the context with the detected port
277
- if ((context as any).viteConfig) {
278
- ; (context as any).viteConfig.port = actualPort
279
- }
280
- }
281
- }
282
-
283
- const isRunning = await checkViteRunning(host, actualPort, config.timeout)
284
-
285
- if (isRunning && !isConnected) {
286
- isConnected = true
287
- retries = 0
288
- if (actualPort !== initialPort) {
289
- context.logger.debug(`✓ Vite server detected on ${host}:${actualPort} (auto-detected from port ${initialPort})`)
290
- } else {
291
- context.logger.debug(`✓ Vite server detected on ${host}:${actualPort}`)
292
- }
293
- context.logger.debug("Hot reload coordination active")
294
- } else if (!isRunning && isConnected) {
295
- isConnected = false
296
- context.logger.warn(`✗ Vite server disconnected from ${host}:${actualPort}`)
297
- // Reset port detection when disconnected
298
- portDetected = false
299
- actualPort = initialPort
300
- } else if (!isRunning) {
301
- retries++
302
- if (retries <= config.maxRetries) {
303
- if (portDetected) {
304
- context.logger.debug(`Waiting for Vite server on ${host}:${actualPort}... (${retries}/${config.maxRetries})`)
305
- } else {
306
- context.logger.debug(`Detecting Vite server port... (${retries}/${config.maxRetries})`)
307
- }
308
- } else if (retries === config.maxRetries + 1) {
309
- context.logger.warn(`Vite server not found after ${config.maxRetries} attempts. Development features may be limited.`)
310
- }
311
- }
312
- } catch (error) {
313
- if (isConnected) {
314
- context.logger.error('Error checking Vite server status', { error })
315
- }
316
- }
317
-
318
- // Continue monitoring
319
- setTimeout(checkVite, config.checkInterval)
320
- }
321
-
322
- // Start monitoring after a brief delay
323
- setTimeout(checkVite, 1000)
324
- }
325
-
326
- // Auto-detect Vite port by trying common ports
327
- async function detectVitePort(host: string, startPort: number): Promise<number | null> {
328
- // Try the initial port first, then common alternatives
329
- const portsToTry = [
330
- startPort,
331
- startPort + 1,
332
- startPort + 2,
333
- startPort + 3,
334
- 5174, // Common Vite alternative
335
- 5175,
336
- 5176,
337
- 3000, // Sometimes Vite might use this
338
- 4173 // Another common alternative
339
- ]
340
-
341
- for (const port of portsToTry) {
342
- try {
343
- const isRunning = await checkViteRunning(host, port, 1000)
344
- if (isRunning) {
345
- return port
346
- }
347
- } catch (error) {
348
- // Continue trying other ports
349
- }
350
- }
351
-
352
- return null
353
- }
354
-
355
- // Check if Vite is running
356
- async function checkViteRunning(host: string, port: number, timeout: number = 1000): Promise<boolean> {
357
- try {
358
- const controller = new AbortController()
359
- const timeoutId = setTimeout(() => controller.abort(), timeout)
360
-
361
- const response = await fetch(`http://${host}:${port}`, {
362
- signal: controller.signal,
363
- method: 'HEAD' // Use HEAD to minimize data transfer
364
- })
365
-
366
- clearTimeout(timeoutId)
367
- return response.status >= 200 && response.status < 500
368
- } catch (error) {
369
- return false
370
- }
371
- }
372
-
373
- // Note: Proxy logic is now handled directly in the onBeforeRoute hook above
374
-
1
+ import type { FluxStack, PluginContext, RequestContext } from "../../types"
2
+ import { createServer, type ViteDevServer } from 'vite'
3
+ import { FLUXSTACK_VERSION } from "../../../utils/version"
4
+
5
+ type Plugin = FluxStack.Plugin
6
+
7
+ let viteServer: ViteDevServer | null = null
8
+
9
+ export const vitePlugin: Plugin = {
10
+ name: "vite",
11
+ version: FLUXSTACK_VERSION,
12
+ description: "Enhanced Vite integration plugin for FluxStack with improved error handling and monitoring",
13
+ author: "FluxStack Team",
14
+ priority: 800, // Should run early to setup proxying
15
+ category: "development",
16
+ tags: ["vite", "development", "hot-reload"],
17
+ dependencies: [], // No dependencies
18
+
19
+ configSchema: {
20
+ type: "object",
21
+ properties: {
22
+ enabled: {
23
+ type: "boolean",
24
+ description: "Enable Vite integration"
25
+ },
26
+ port: {
27
+ type: "number",
28
+ minimum: 1,
29
+ maximum: 65535,
30
+ description: "Vite development server port"
31
+ },
32
+ host: {
33
+ type: "string",
34
+ description: "Vite development server host"
35
+ },
36
+ checkInterval: {
37
+ type: "number",
38
+ minimum: 100,
39
+ description: "Interval to check if Vite is running (ms)"
40
+ },
41
+ maxRetries: {
42
+ type: "number",
43
+ minimum: 1,
44
+ description: "Maximum retries to connect to Vite"
45
+ },
46
+ timeout: {
47
+ type: "number",
48
+ minimum: 100,
49
+ description: "Timeout for Vite requests (ms)"
50
+ },
51
+ proxyPaths: {
52
+ type: "array",
53
+ items: { type: "string" },
54
+ description: "Paths to proxy to Vite (defaults to all non-API paths)"
55
+ },
56
+ excludePaths: {
57
+ type: "array",
58
+ items: { type: "string" },
59
+ description: "Paths to exclude from Vite proxying"
60
+ }
61
+ },
62
+ additionalProperties: false
63
+ },
64
+
65
+ defaultConfig: {
66
+ enabled: true,
67
+ port: 5173,
68
+ host: "localhost",
69
+ checkInterval: 2000,
70
+ maxRetries: 10,
71
+ timeout: 5000,
72
+ proxyPaths: [],
73
+ excludePaths: []
74
+ },
75
+
76
+ setup: async (context: PluginContext) => {
77
+ const config = getPluginConfig(context)
78
+
79
+ if (!config.enabled || !context.config.client) {
80
+ context.logger.debug('Vite plugin disabled or no client configuration found')
81
+ return
82
+ }
83
+
84
+ const vitePort = config.port || context.config.client.port || 5173
85
+ const viteHost = config.host || "localhost"
86
+
87
+ try {
88
+ const { startGroup, endGroup, logInGroup } = await import('../../../utils/logger/group-logger')
89
+
90
+ startGroup({
91
+ title: 'Vite Development Server',
92
+ icon: '🎨',
93
+ color: 'magenta',
94
+ collapsed: true
95
+ })
96
+
97
+ logInGroup(`Starting on ${viteHost}:${vitePort}`, '📍')
98
+
99
+ // Start Vite dev server programmatically
100
+ viteServer = await createServer({
101
+ configFile: './vite.config.ts',
102
+ // Don't override root - let vite.config.ts handle it
103
+ server: {
104
+ port: vitePort,
105
+ host: viteHost,
106
+ strictPort: true
107
+ },
108
+ logLevel: 'warn' // Suppress Vite's verbose logs
109
+ })
110
+
111
+ await viteServer.listen()
112
+
113
+ // Custom URL display instead of viteServer.printUrls()
114
+ logInGroup(`Local: http://${viteHost}:${vitePort}/`, '✅')
115
+ logInGroup('Hot reload coordination active', '🔄')
116
+
117
+ endGroup()
118
+ console.log('') // Separator line
119
+
120
+ // Store Vite config in context for later use
121
+ ; (context as any).viteConfig = {
122
+ port: vitePort,
123
+ host: viteHost,
124
+ ...config,
125
+ server: viteServer
126
+ }
127
+
128
+ // Setup cleanup on process exit
129
+ const cleanup = async () => {
130
+ if (viteServer) {
131
+ context.logger.debug('🛑 Stopping Vite server...')
132
+ await viteServer.close()
133
+ viteServer = null
134
+ }
135
+ }
136
+
137
+ process.on('SIGINT', cleanup)
138
+ process.on('SIGTERM', cleanup)
139
+ process.on('exit', cleanup)
140
+
141
+ } catch (error) {
142
+ context.logger.error('❌ Failed to start Vite server programmatically:', error)
143
+ context.logger.debug('⚠️ Falling back to monitoring mode...')
144
+
145
+ // Fallback to monitoring if programmatic start fails
146
+ ; (context as any).viteConfig = {
147
+ port: vitePort,
148
+ host: viteHost,
149
+ ...config
150
+ }
151
+ monitorVite(context, viteHost, vitePort, config)
152
+ }
153
+ },
154
+
155
+ onServerStart: async (context: PluginContext) => {
156
+ const config = getPluginConfig(context)
157
+ const viteConfig = (context as any).viteConfig
158
+
159
+ if (config.enabled && viteConfig) {
160
+ context.logger.debug(`Vite integration active - monitoring ${viteConfig.host}:${viteConfig.port}`)
161
+ }
162
+ },
163
+
164
+ onBeforeRoute: async (requestContext: RequestContext) => {
165
+ // Skip API routes and swagger - let them be handled by backend
166
+ if (requestContext.path.startsWith("/api") || requestContext.path.startsWith("/swagger")) {
167
+ return
168
+ }
169
+
170
+ // For Vite internal routes, proxy directly to Vite server
171
+ if (requestContext.path.startsWith("/@") || // All Vite internal routes (/@vite/, /@fs/, /@react-refresh, etc.)
172
+ requestContext.path.startsWith("/__vite") || // Vite HMR and dev routes
173
+ requestContext.path.startsWith("/node_modules") || // Direct node_modules access
174
+ requestContext.path.includes("/.vite/") || // Vite cache and deps
175
+ requestContext.path.endsWith(".js.map") || // Source maps
176
+ requestContext.path.endsWith(".css.map")) { // CSS source maps
177
+
178
+ // Use fixed configuration for Vite proxy
179
+ const viteHost = "localhost"
180
+ const vitePort = 5173
181
+
182
+ try {
183
+ const url = new URL(requestContext.request.url)
184
+ const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
185
+
186
+ // Forward request to Vite
187
+ const response = await fetch(viteUrl, {
188
+ method: requestContext.method,
189
+ headers: requestContext.headers,
190
+ body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
191
+ })
192
+
193
+ // Return the Vite response
194
+ const body = await response.arrayBuffer()
195
+
196
+ requestContext.handled = true
197
+ requestContext.response = new Response(body, {
198
+ status: response.status,
199
+ statusText: response.statusText,
200
+ headers: response.headers
201
+ })
202
+
203
+ } catch (viteError) {
204
+ // If Vite fails, let the request continue to normal routing (will become 404)
205
+ // Only log if explicitly enabled for debugging
206
+ const { clientConfig } = await import('@/config/client.config')
207
+ if (clientConfig.vite.enableLogging) {
208
+ console.warn(`Vite proxy error: ${viteError}`)
209
+ }
210
+ }
211
+ return
212
+ }
213
+
214
+ // Use fixed configuration for simplicity - Vite should be running on port 5173
215
+ const viteHost = "localhost"
216
+ const vitePort = 5173
217
+
218
+ try {
219
+ const url = new URL(requestContext.request.url)
220
+ const viteUrl = `http://${viteHost}:${vitePort}${requestContext.path}${url.search}`
221
+
222
+ // Forward request to Vite
223
+ const response = await fetch(viteUrl, {
224
+ method: requestContext.method,
225
+ headers: requestContext.headers,
226
+ body: requestContext.method !== 'GET' && requestContext.method !== 'HEAD' ? requestContext.request.body : undefined
227
+ })
228
+
229
+ // If Vite responds successfully, handle the request
230
+ if (response.ok || response.status < 500) {
231
+ // Return a proper Response object with all headers and status
232
+ const body = await response.arrayBuffer()
233
+
234
+ requestContext.handled = true
235
+ requestContext.response = new Response(body, {
236
+ status: response.status,
237
+ statusText: response.statusText,
238
+ headers: response.headers
239
+ })
240
+ }
241
+
242
+ } catch (viteError) {
243
+ // If Vite fails, let the request continue to normal routing (will become 404)
244
+ // Only log if explicitly enabled for debugging
245
+ const { clientConfig } = await import('@/config/client.config')
246
+ if (clientConfig.vite.enableLogging) {
247
+ console.warn(`Vite proxy error: ${viteError}`)
248
+ }
249
+ }
250
+ }
251
+ }
252
+
253
+ // Helper function to get plugin config
254
+ function getPluginConfig(context: PluginContext) {
255
+ const pluginConfig = context.config.plugins.config?.vite || {}
256
+ return { ...vitePlugin.defaultConfig, ...pluginConfig }
257
+ }
258
+
259
+ // Monitor Vite server status with automatic port detection
260
+ async function monitorVite(
261
+ context: PluginContext,
262
+ host: string,
263
+ initialPort: number,
264
+ config: any
265
+ ) {
266
+ let retries = 0
267
+ let isConnected = false
268
+ let actualPort = initialPort
269
+ let portDetected = false
270
+
271
+ const checkVite = async () => {
272
+ try {
273
+ // If we haven't found the correct port yet, try to detect it
274
+ if (!portDetected) {
275
+ const detectedPort = await detectVitePort(host, initialPort)
276
+ if (detectedPort !== null) {
277
+ actualPort = detectedPort
278
+ portDetected = true
279
+ // Update the context with the detected port
280
+ if ((context as any).viteConfig) {
281
+ ; (context as any).viteConfig.port = actualPort
282
+ }
283
+ }
284
+ }
285
+
286
+ const isRunning = await checkViteRunning(host, actualPort, config.timeout)
287
+
288
+ if (isRunning && !isConnected) {
289
+ isConnected = true
290
+ retries = 0
291
+ if (actualPort !== initialPort) {
292
+ context.logger.debug(`✓ Vite server detected on ${host}:${actualPort} (auto-detected from port ${initialPort})`)
293
+ } else {
294
+ context.logger.debug(`✓ Vite server detected on ${host}:${actualPort}`)
295
+ }
296
+ context.logger.debug("Hot reload coordination active")
297
+ } else if (!isRunning && isConnected) {
298
+ isConnected = false
299
+ context.logger.warn(`✗ Vite server disconnected from ${host}:${actualPort}`)
300
+ // Reset port detection when disconnected
301
+ portDetected = false
302
+ actualPort = initialPort
303
+ } else if (!isRunning) {
304
+ retries++
305
+ if (retries <= config.maxRetries) {
306
+ if (portDetected) {
307
+ context.logger.debug(`Waiting for Vite server on ${host}:${actualPort}... (${retries}/${config.maxRetries})`)
308
+ } else {
309
+ context.logger.debug(`Detecting Vite server port... (${retries}/${config.maxRetries})`)
310
+ }
311
+ } else if (retries === config.maxRetries + 1) {
312
+ context.logger.warn(`Vite server not found after ${config.maxRetries} attempts. Development features may be limited.`)
313
+ }
314
+ }
315
+ } catch (error) {
316
+ if (isConnected) {
317
+ context.logger.error('Error checking Vite server status', { error })
318
+ }
319
+ }
320
+
321
+ // Continue monitoring
322
+ setTimeout(checkVite, config.checkInterval)
323
+ }
324
+
325
+ // Start monitoring after a brief delay
326
+ setTimeout(checkVite, 1000)
327
+ }
328
+
329
+ // Auto-detect Vite port by trying common ports
330
+ async function detectVitePort(host: string, startPort: number): Promise<number | null> {
331
+ // Try the initial port first, then common alternatives
332
+ const portsToTry = [
333
+ startPort,
334
+ startPort + 1,
335
+ startPort + 2,
336
+ startPort + 3,
337
+ 5174, // Common Vite alternative
338
+ 5175,
339
+ 5176,
340
+ 3000, // Sometimes Vite might use this
341
+ 4173 // Another common alternative
342
+ ]
343
+
344
+ for (const port of portsToTry) {
345
+ try {
346
+ const isRunning = await checkViteRunning(host, port, 1000)
347
+ if (isRunning) {
348
+ return port
349
+ }
350
+ } catch (error) {
351
+ // Continue trying other ports
352
+ }
353
+ }
354
+
355
+ return null
356
+ }
357
+
358
+ // Check if Vite is running
359
+ async function checkViteRunning(host: string, port: number, timeout: number = 1000): Promise<boolean> {
360
+ try {
361
+ const controller = new AbortController()
362
+ const timeoutId = setTimeout(() => controller.abort(), timeout)
363
+
364
+ const response = await fetch(`http://${host}:${port}`, {
365
+ signal: controller.signal,
366
+ method: 'HEAD' // Use HEAD to minimize data transfer
367
+ })
368
+
369
+ clearTimeout(timeoutId)
370
+ return response.status >= 200 && response.status < 500
371
+ } catch (error) {
372
+ return false
373
+ }
374
+ }
375
+
376
+ // Note: Proxy logic is now handled directly in the onBeforeRoute hook above
377
+
375
378
  export default vitePlugin