* Get server origin for URLs
(server: ViteDevServer)
| 5486 | * Get server origin for URLs |
| 5487 | */ |
| 5488 | function getServerOrigin(server: ViteDevServer): string { |
| 5489 | const urls: any = (server as any).resolvedUrls; |
| 5490 | // Prefer a real LAN/network URL when available so emulators/devices can reach the host directly. |
| 5491 | if (urls?.network?.length) { |
| 5492 | try { |
| 5493 | const u = new URL(String(urls.network[0])); |
| 5494 | const origin = `${u.protocol}//${u.host}`; |
| 5495 | if (!/^https?:\/\/[\w\-.:\[\]]+$/.test(origin)) { |
| 5496 | console.warn('[hmr][origin] invariant failed for resolvedUrls.network:', urls.network[0], '→', origin); |
| 5497 | } |
| 5498 | return origin; |
| 5499 | } catch { |
| 5500 | // Fallthrough to local below if network parse fails |
| 5501 | } |
| 5502 | } |
| 5503 | if (urls?.local?.length) { |
| 5504 | try { |
| 5505 | const u = new URL(String(urls.local[0])); |
| 5506 | const origin = `${u.protocol}//${u.host}`; |
| 5507 | if (!/^https?:\/\/[\w\-.:\[\]]+$/.test(origin)) { |
| 5508 | console.warn('[hmr][origin] invariant failed for resolvedUrls.local:', urls.local[0], '→', origin); |
| 5509 | } |
| 5510 | return origin; |
| 5511 | } catch { |
| 5512 | // Fallthrough to manual construction |
| 5513 | } |
| 5514 | } |
| 5515 | |
| 5516 | const isHttps = !!server.config.server?.https; |
| 5517 | const httpServer = server.httpServer as any; |
| 5518 | const addr = httpServer?.address?.(); |
| 5519 | const port = Number(server.config.server?.port || addr?.port || 5173); |
| 5520 | const hostCfg = server.config.server?.host; |
| 5521 | const host = typeof hostCfg === 'string' && hostCfg !== '0.0.0.0' ? hostCfg : '127.0.0.1'; |
| 5522 | |
| 5523 | const origin = `${isHttps ? 'https' : 'http'}://${host}:${port}`; |
| 5524 | if (!/^https?:\/\/[\w\-.:\[\]]+$/.test(origin)) { |
| 5525 | console.warn('[hmr][origin] invariant failed for constructed origin:', origin); |
| 5526 | } |
| 5527 | return origin; |
| 5528 | } |
| 5529 | |
| 5530 | // Test-only export: allow unit tests to run the sanitizer on snippets without booting a server |
| 5531 | // Safe in production builds; this is a named export that tests can import explicitly. |
no test coverage detected