UNPKG

vite-dynamic-proxy

Version:

A Vite plugin that enables dynamic proxy configuration at runtime, allowing flexible and configurable proxy settings for development servers

85 lines (83 loc) 2.92 kB
// src/index.ts function dynamicProxyPlugin(options) { if (!options.defaultTarget) { throw new Error("vite-dynamic-proxy: defaultTarget is required"); } if (!options.path) { throw new Error("vite-dynamic-proxy: path is required"); } const defaultTarget = options.defaultTarget; const paths = Array.isArray(options.path) ? options.path : [options.path]; const changeOrigin = options.changeOrigin ?? true; paths.forEach((path) => { if (!/^(\^)?\/[\w\-/]*$/.test(path)) { throw new Error( `vite-dynamic-proxy: path "${path}" must be a valid path (e.g., "/api") or start with ^ (e.g., "^/api")` ); } }); console.log("\nvite-dynamic-proxy plugin configuration:"); console.log("- defaultTarget:", defaultTarget); console.log("- paths:", paths); console.log("- changeOrigin:", changeOrigin, "\n"); let lastDebugTarget; return { name: "vite-dynamic-proxy", configureServer(server) { const proxyConfig = {}; paths.forEach((path) => { proxyConfig[path] = { target: defaultTarget, changeOrigin }; }); server.config.server.proxy = proxyConfig; server.middlewares.use( (req, res, next) => { if (!req.url) { next(); return; } const url = new URL(req.url, `http://${req.headers.host}`); const matchingPath = paths.find((path) => { return path.startsWith("^") ? new RegExp(path).test(url.pathname) : url.pathname.startsWith(path); }); if (matchingPath) { const referer = req.headers.referer; if (referer) { const refererUrl = new URL(referer); const debug = refererUrl.searchParams.get("debug"); if (debug) { let debugTarget; if (debug.startsWith("https://")) { debugTarget = debug; } else if (debug.startsWith("http://")) { debugTarget = debug; } else { debugTarget = `http://${debug}`; } if (debugTarget !== lastDebugTarget) { console.log("vite-dynamic-proxy: Proxying to:", debugTarget); lastDebugTarget = debugTarget; } if (server.config.server && server.config.server.proxy) { const proxy = server.config.server.proxy; paths.forEach((path) => { if (proxy[path]) { proxy[path].target = debugTarget; if (debugTarget.startsWith("https://")) { proxy[path].secure = false; } } }); } } } } next(); } ); } }; } export { dynamicProxyPlugin };