"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildDefaultCorsOptions = buildDefaultCorsOptions;
const common_1 = require("@nestjs/common");
const logger = new common_1.Logger('CorsHelper');
function buildDefaultCorsOptions() {
    const rawOrigins = process.env.SECURITY_CORS_ORIGINS ?? '*';
    logger.log(`CORS allowed origins: ${rawOrigins}`);
    const allowed = rawOrigins.split(',').map(s => s.trim()).filter(Boolean);
    const escapeRx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const patternToRegex = (pattern) => {
        const hasScheme = /^https?:\/\//i.test(pattern);
        const schemePart = hasScheme ? '' : 'https?:\\/\\/';
        if (pattern === '*' || pattern === '.*')
            return /^.*$/i;
        const escaped = escapeRx(pattern)
            .replace(/^https?:\/\//i, '')
            .replace(/\*/g, '[^.]+');
        return new RegExp(`^${schemePart}${escaped}(?::\\d+)?$`, 'i');
    };
    const matchers = allowed.map(patternToRegex);
    logger.log(`CORS regexes: ${matchers.map(r => r.toString()).join(', ')}`);
    return {
        origin: (origin, cb) => {
            if (!origin) {
                logger.debug('CORS origin callback skipped regex evaluation because origin was empty');
                return cb(null, true);
            }
            const matchingRegex = matchers.find(rx => rx.test(origin));
            if (matchingRegex) {
                logger.debug(`CORS origin matched: origin=${origin}; regex=${matchingRegex.toString()}`);
                return cb(null, true);
            }
            logger.debug(`CORS origin did not match any regex: origin=${origin}; regexes=${matchers.map(r => r.toString()).join(', ')}`);
            return cb(new Error(`Origin ${origin} not allowed by CORS. Allowed origins: ${allowed.join(', ')}`), false);
        },
        methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
        allowedHeaders: ['Content-Type', 'Authorization', 'solidx-api-key'],
        credentials: true,
    };
}
//# sourceMappingURL=cors.helper.js.map