Files
dmenu-admin/menuPreviewProxy.ts
T
hamid zarghami 6324cabb32
deploy to danak / build_and_deploy (push) Has been cancelled
fix build
2026-06-28 09:11:12 +03:30

76 lines
2.4 KiB
TypeScript

import type { IncomingMessage, ServerResponse } from "node:http";
import type { IncomingMessage as ProxyIncomingMessage } from "node:http";
import type { ProxyOptions } from "vite";
import { MENU_SITE_ORIGIN, isMenuSlugProxyPath, stripMenuPreviewCacheParam, toMenuSitePath } from "./src/config/menuPreview";
const stripFrameHeaders = (_proxyRes: ProxyIncomingMessage, _req: IncomingMessage, res: ServerResponse) => {
res.removeHeader("x-frame-options");
res.removeHeader("content-security-policy");
};
const stripPreviewPageHeaders = (_proxyRes: ProxyIncomingMessage, _req: IncomingMessage, res: ServerResponse) => {
stripFrameHeaders(_proxyRes, _req, res);
res.removeHeader("cache-control");
res.removeHeader("etag");
res.removeHeader("last-modified");
res.setHeader("cache-control", "no-store, no-cache, must-revalidate");
res.setHeader("pragma", "no-cache");
res.setHeader("expires", "0");
};
const menuAssetProxy = (): ProxyOptions => ({
target: MENU_SITE_ORIGIN,
changeOrigin: true,
secure: true,
configure: (proxy) => {
proxy.on("proxyRes", stripFrameHeaders);
},
});
export const createMenuPreviewProxy = (): Record<string, ProxyOptions> => ({
"/assets/fonts": menuAssetProxy(),
"/assets/images": menuAssetProxy(),
"/_next": menuAssetProxy(),
"/icons": menuAssetProxy(),
});
export const shouldProxyMenuSlugRequest = (url: string | undefined) => {
if (!url) return false;
const pathname = url.split("?")[0] ?? "";
if (pathname.startsWith("/@") || pathname.startsWith("/src/") || pathname.startsWith("/node_modules/")) {
return false;
}
if (
pathname.startsWith("/assets/fonts/") ||
pathname.startsWith("/assets/images/") ||
pathname.startsWith("/_next/") ||
pathname.startsWith("/icons/")
) {
return false;
}
if (pathname.startsWith("/assets/")) {
return false;
}
return isMenuSlugProxyPath(pathname);
};
export const getMenuSiteTargetUrl = (url: string) => {
const [pathname, search = ""] = url.split("?");
const menuPath = toMenuSitePath(pathname ?? "");
if (!menuPath) return null;
return `${MENU_SITE_ORIGIN}${menuPath}${stripMenuPreviewCacheParam(search)}`;
};
export const createMenuSlugProxyAgent = (): { configure: NonNullable<ProxyOptions["configure"]> } => ({
configure: (proxy) => {
proxy.on("proxyReq", (proxyReq) => {
proxyReq.removeHeader("origin");
});
proxy.on("proxyRes", stripPreviewPageHeaders);
},
});