"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createProxy = void 0;
const http_proxy_middleware_1 = require("http-proxy-middleware");
const DEBUG_MODE = !!process.env.SALES_APP_DEBUG;
const createProxy = ({ account, port, }) => (app) => {
    if (!account) {
        throw new Error('No account configuration passed');
    }
    const adminHost = `https://${account}.myvtex.com`;
    const VTEX_APIS = ['/api', '/_v', '/files', '/iframes'];
    const proxyConfigurations = [
        {
            path: '/api/vtexid',
            changeOrigin: true,
            cookieDomainRewrite: {
                [`${account}.myvtex.com`]: `localhost`,
            },
            cookiePathRewrite: {
                '/api/vtexid/refreshtoken/admin': '/',
            },
            pathRewrite: (path) => {
                if (path.startsWith('/pub/authentication/start')) {
                    return path.replace(/localhost/gi, `${account}.vtexlocal.com.br`);
                }
                return path;
            },
        },
        ...VTEX_APIS.map((path) => ({
            path,
            changeOrigin: true,
        })),
    ];
    proxyConfigurations.forEach((proxyConfig) => {
        const proxyMiddleware = (0, http_proxy_middleware_1.createProxyMiddleware)({
            logger: DEBUG_MODE ? console : undefined,
            target: `${adminHost}${proxyConfig.path}`,
            changeOrigin: proxyConfig.changeOrigin,
            headers: proxyConfig.changeOrigin ? { Origin: adminHost } : {},
            cookieDomainRewrite: proxyConfig.cookieDomainRewrite,
            cookiePathRewrite: proxyConfig.cookiePathRewrite,
            pathRewrite: proxyConfig.pathRewrite,
            on: {
                proxyReq: (clientReq, req, res) => {
                    const isVtexLocalHost = req.headers.host === `${account}.vtexlocal.com.br:${port}`;
                    if (!(clientReq.path.startsWith('/api/vtexid/oauth/finish') &&
                        isVtexLocalHost)) {
                        return;
                    }
                    res.statusCode = 302;
                    res.setHeader('location', `http://localhost:${port}${clientReq.path}`);
                    res.end(() => clientReq.destroy());
                },
                proxyRes: ({ headers }) => {
                    const cookieHeader = headers['set-cookie'];
                    if (Array.isArray(cookieHeader)) {
                        const cookiesToRemove = ['secure', 'samesite=none'];
                        headers['set-cookie'] = cookieHeader.map((headerPart) => {
                            return headerPart
                                .split(';')
                                .filter((value) => !cookiesToRemove.includes(value.trim().toLowerCase()))
                                .join(';');
                        });
                    }
                    const locationHeader = headers.location;
                    if (locationHeader) {
                        const regexLolcal = new RegExp(`${account}.vtexlocal.com.br`, 'gi');
                        headers.location = locationHeader.replace(regexLolcal, 'localhost');
                    }
                },
            },
        });
        app.use(proxyConfig.path, proxyMiddleware);
    });
};
exports.createProxy = createProxy;
//# sourceMappingURL=proxy.js.map