/** * Vite configuration for the DMS frontend application. */ import { defineConfig, loadEnv } from 'vite'; /** * Parses a comma-separated environment value into normalized entries. * * @param rawValue Raw comma-separated value. * @returns List of non-empty normalized entries. */ function parseCsvList(rawValue: string | undefined): string[] { if (!rawValue) { return []; } return rawValue .split(',') .map((entry) => entry.trim()) .filter((entry) => entry.length > 0); } /** * Extracts hostnames from CORS origin values. * * @param rawValue JSON array string or comma-separated origin list. * @returns Hostnames parsed from valid origins. */ function parseCorsOriginHosts(rawValue: string | undefined): string[] { if (!rawValue) { return []; } let origins: string[] = []; try { const parsedOrigins = JSON.parse(rawValue); if (Array.isArray(parsedOrigins)) { origins = parsedOrigins.filter((entry): entry is string => typeof entry === 'string'); } else if (typeof parsedOrigins === 'string') { origins = [parsedOrigins]; } } catch { origins = parseCsvList(rawValue); } return origins.flatMap((origin) => { try { const parsedUrl = new URL(origin); return parsedUrl.hostname ? [parsedUrl.hostname] : []; } catch { return []; } }); } /** * Builds the Vite allowed host list from environment-driven inputs. * * @param env Environment variable key-value map. * @returns De-duplicated hostnames, or undefined to keep Vite defaults. */ function buildAllowedHosts(env: Record): string[] | undefined { const explicitHosts = parseCsvList(env.VITE_ALLOWED_HOSTS); const corsOriginHosts = parseCorsOriginHosts(env.CORS_ORIGINS); const mergedHosts = Array.from(new Set([...explicitHosts, ...corsOriginHosts])); return mergedHosts.length > 0 ? mergedHosts : undefined; } /** * Exports frontend build and dev-server settings. */ export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), ''); const allowedHosts = buildAllowedHosts(env); return { server: { host: '0.0.0.0', port: 5173, ...(allowedHosts ? { allowedHosts } : {}), }, }; });