"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildDefinePlugin = void 0;
const magic_string_1 = __importDefault(require("magic-string"));
const css_1 = require("./css");
/**
 * Build only.
 * Server define is injected as runtime variables by clientInjection plugin
 * to avoid transform cost during dev.
 */
function buildDefinePlugin(config) {
    const userDefine = {};
    for (const key in config.define) {
        userDefine[key] = JSON.stringify(config.define[key]);
    }
    const individualEnvKeys = {};
    for (const key in config.env) {
        individualEnvKeys[`import.meta.env.${key}`] = JSON.stringify(config.env[key]);
    }
    const replacements = {
        ...userDefine,
        ...individualEnvKeys,
        'import.meta.env.': `({}).`,
        'import.meta.env': JSON.stringify(config.env),
        'process.env.NODE_ENV': JSON.stringify(config.mode),
        'process.env.': `({}).`,
        'process.env': JSON.stringify({ NODE_ENV: config.mode }),
        'import.meta.hot': `false`
    };
    const pattern = new RegExp('\\b(' +
        Object.keys(replacements)
            .map((str) => {
            return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
        })
            .join('|') +
        ')\\b', 'g');
    return {
        name: 'vite:define',
        transform(code, id) {
            if (
            // exclude css and static assets for performance
            css_1.isCSSRequest(id) ||
                config.assetsInclude(id)) {
                return;
            }
            const s = new magic_string_1.default(code);
            let hasReplaced = false;
            let match;
            while ((match = pattern.exec(code))) {
                hasReplaced = true;
                const start = match.index;
                const end = start + match[0].length;
                const replacement = '' + replacements[match[1]];
                s.overwrite(start, end, replacement);
            }
            if (!hasReplaced) {
                return null;
            }
            const result = { code: s.toString() };
            if (config.build.sourcemap) {
                result.map = s.generateMap({ hires: true });
            }
            return result;
        }
    };
}
exports.buildDefinePlugin = buildDefinePlugin;
//# sourceMappingURL=define.js.map