|
| 1 | +/** |
| 2 | + * Vite `base: './'` is used for Home Assistant Ingress (and other subpath hosts) so asset URLs are |
| 3 | + * relative to the page. Helpers here resolve same-origin links that would break if built with `base: '/'`. |
| 4 | + */ |
| 5 | + |
| 6 | +export function isIngressRelativeBase(): boolean { |
| 7 | + const b = import.meta.env.BASE_URL; |
| 8 | + return b === './' || b.startsWith('./'); |
| 9 | +} |
| 10 | + |
| 11 | +/** Directory URL (with trailing slash) for resolving static files and API roots in the browser. */ |
| 12 | +export function getResolvedPublicBase(): string { |
| 13 | + const base = import.meta.env.BASE_URL; |
| 14 | + if (import.meta.env.DEV) { |
| 15 | + return `${window.location.origin}/`; |
| 16 | + } |
| 17 | + if (base === '/' || base === '') { |
| 18 | + return `${window.location.origin}/`; |
| 19 | + } |
| 20 | + if (isIngressRelativeBase()) { |
| 21 | + try { |
| 22 | + const resolved = new URL(base, window.location.href).href; |
| 23 | + return resolved.endsWith('/') ? resolved : `${resolved}/`; |
| 24 | + } catch { |
| 25 | + return `${window.location.origin}/`; |
| 26 | + } |
| 27 | + } |
| 28 | + const path = base.endsWith('/') ? base : `${base}/`; |
| 29 | + return `${window.location.origin}${path}`; |
| 30 | +} |
| 31 | + |
| 32 | +export function publicAssetUrl(relativePath: string): string { |
| 33 | + const rel = relativePath.replace(/^\//, ''); |
| 34 | + return new URL(rel, getResolvedPublicBase()).href; |
| 35 | +} |
| 36 | + |
| 37 | +/** Socket.IO `path` option: must include HA Ingress prefix when the UI is not at domain root. */ |
| 38 | +export function getSocketIoPath(): string { |
| 39 | + if (import.meta.env.DEV) return '/socket.io'; |
| 40 | + const base = import.meta.env.BASE_URL; |
| 41 | + if (base === '/' || base === '') return '/socket.io'; |
| 42 | + if (isIngressRelativeBase()) { |
| 43 | + const p = window.location.pathname.replace(/\/+$/, ''); |
| 44 | + return p ? `${p}/socket.io` : '/socket.io'; |
| 45 | + } |
| 46 | + const normalized = base.endsWith('/') ? base.slice(0, -1) : base; |
| 47 | + return `${normalized}/socket.io`; |
| 48 | +} |
0 commit comments