"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bundleSource = bundleSource;
const linguiEsbuildPlugin_1 = require("./linguiEsbuildPlugin");
const buildIncludeDepsFilter_1 = require("./buildIncludeDepsFilter");
function createExtRegExp(extensions) {
    return new RegExp("\\.(?:" + extensions.join("|") + ")(?:\\?.*)?$");
}
async function bundleSource(linguiConfig, entryPoints, outDir, rootDir) {
    const esbuild = await import("esbuild");
    const config = linguiConfig.experimental.extractor;
    const excludeExtensions = config.excludeExtensions || [
        "ico",
        "pot",
        "xliff",
        "woff2",
        "woff",
        "eot",
        "gif",
        "otf",
        "ttf",
        "mp4",
        "svg",
        "png",
        "css",
        "sass",
        "scss",
        "less",
        "jpg",
    ];
    const esbuildOptions = {
        entryPoints: entryPoints,
        outExtension: { ".js": ".jsx" },
        jsx: "preserve",
        bundle: true,
        platform: "node",
        target: ["esnext"],
        format: "esm",
        splitting: false,
        treeShaking: true,
        outdir: outDir,
        sourcemap: "inline",
        sourceRoot: outDir,
        sourcesContent: false,
        metafile: true,
        plugins: [
            (0, linguiEsbuildPlugin_1.pluginLinguiMacro)({ linguiConfig }),
            {
                name: "externalize-deps",
                setup(build) {
                    const shouldInclude = (0, buildIncludeDepsFilter_1.buildIncludeDepsFilter)(config.includeDeps || []);
                    // considers all import paths that "look like" package imports in the original source code to be package imports.
                    // Specifically import paths that don't start with a path segment of / or . or .. are considered to be package imports.
                    // The only two exceptions to this rule are subpath imports (which start with a # character) and deps specified in the `includeDeps`
                    build.onResolve({ filter: /^[^.#/].*/ }, async (args) => {
                        if (shouldInclude(args.path)) {
                            return { external: false };
                        }
                        return {
                            external: true,
                        };
                    });
                },
            },
            {
                name: "externalize-files",
                setup(build) {
                    build.onResolve({ filter: createExtRegExp(excludeExtensions) }, () => ({
                        external: true,
                    }));
                },
            },
        ],
    };
    return await esbuild.build(config.resolveEsbuildOptions
        ? config.resolveEsbuildOptions(esbuildOptions)
        : esbuildOptions);
}
