"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.webWorkerPlugin = void 0;
const url_1 = require("url");
const querystring_1 = __importDefault(require("querystring"));
const asset_1 = require("./asset");
const utils_1 = require("../utils");
function isWorkerRequest(id) {
    const { search } = url_1.parse(id);
    if (!search) {
        return false;
    }
    const query = querystring_1.default.parse(search.slice(1));
    return query.worker != null ? query : false;
}
function webWorkerPlugin(config) {
    const isBuild = config.command === 'build';
    return {
        name: 'vite:worker',
        load(id) {
            if (isBuild && isWorkerRequest(id)) {
                return '';
            }
        },
        async transform(_, id) {
            const query = isWorkerRequest(id);
            if (!query) {
                return;
            }
            let url;
            if (config.command === 'serve') {
                url = await asset_1.fileToUrl(utils_1.cleanUrl(id), config, this);
            }
            else {
                if (query.inline != null) {
                    // bundle the file as entry to support imports and inline as base64
                    // data url
                    const rollup = require('rollup');
                    const bundle = await rollup.rollup({
                        input: utils_1.cleanUrl(id),
                        plugins: config.plugins
                    });
                    try {
                        const { output } = await bundle.generate({
                            format: 'es',
                            sourcemap: config.build.sourcemap
                        });
                        url = `data:application/javascript;base64,${Buffer.from(output[0].code).toString('base64')}`;
                    }
                    finally {
                        bundle.close();
                    }
                }
                else {
                    // emit as separate chunk
                    url = `__VITE_ASSET__${this.emitFile({
                        type: 'chunk',
                        id: utils_1.cleanUrl(id)
                    })}`;
                }
            }
            return `export default function WorkerWrapper() {
        return new Worker(${JSON.stringify(url)}, { type: 'module' })
      }`;
        }
    };
}
exports.webWorkerPlugin = webWorkerPlugin;
//# sourceMappingURL=worker.js.map