import type { ClientRequest } from "http"; import type { ProxyOptions } from "vite"; import type { Credential } from "../servicenow/types"; export const DEFAULT_PROXY_PATHS = [ "/api", "/amb", "/scripts/", "/images/@servicenow/", "/uxasset/externals", "/$uxappimmutables.do", "/uxta", ]; export async function createViteProxy( credential: Credential | undefined, proxyPaths: string[] = DEFAULT_PROXY_PATHS, ): Promise> { const proxy: Record = {}; if ( !credential || typeof credential.getUrl !== "function" || typeof credential.getHeaders !== "function" ) { return proxy; } const authHeaders = await credential.getHeaders(); const proxyTarget = credential.getUrl().href.replace(/\/$/, ""); for (const proxyPath of proxyPaths) { proxy[proxyPath] = { target: proxyTarget, changeOrigin: true, // `changeOrigin` only rewrites the HTTP Host header ...(proxyPath === "/amb" ? { ws: true, rewriteWsOrigin: true } : {}), configure: (proxyServer) => { const setAuthHeaders = (proxyReq: ClientRequest) => { for (const [key, value] of Object.entries(authHeaders)) { proxyReq.setHeader(key, value); } }; proxyServer.on("proxyReq", setAuthHeaders); proxyServer.on("proxyReqWs", setAuthHeaders); }, }; } return proxy; }