"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyBuilderResolvePlugin = void 0;
const config_1 = require("../config");
const lodash_1 = __importDefault(require("@modern-js/utils/lodash"));
function applyBuilderResolvePlugin(api) {
    api.modifyBundlerChain(async (chain, { target, CHAIN_ID }) => {
        const config = api.getNormalizedConfig();
        const isTsProject = Boolean(api.context.tsconfigPath);
        applyExtensions({
            chain,
            config,
            target,
            isTsProject,
        });
        await applyAlias({
            chain,
            config,
            rootPath: api.context.rootPath,
        });
        applyMainFields({
            chain,
            config,
            target,
        });
        applyFullySpecified({ chain, config, CHAIN_ID });
    });
}
exports.applyBuilderResolvePlugin = applyBuilderResolvePlugin;
// compatible with legacy packages with type="module"
// https://github.com/webpack/webpack/issues/11467
function applyFullySpecified({ chain, CHAIN_ID, }) {
    chain.module
        .rule(CHAIN_ID.RULE.MJS)
        .test(/\.m?js/)
        .resolve.set('fullySpecified', false);
}
function applyExtensions({ chain, config, target, isTsProject, }) {
    const extensions = (0, config_1.getExtensions)({
        target,
        isTsProject,
        resolveExtensionPrefix: config.source.resolveExtensionPrefix,
    });
    chain.resolve.extensions.merge(extensions);
}
async function applyAlias({ chain, config, rootPath, }) {
    const { alias } = config.source;
    if (!alias) {
        return;
    }
    const { applyOptionsChain, ensureAbsolutePath } = await Promise.resolve().then(() => __importStar(require('@modern-js/utils')));
    const mergedAlias = applyOptionsChain({}, alias);
    /**
     * Format alias value:
     * - Relative paths need to be turned into absolute paths.
     * - Absolute paths or a package name are not processed.
     */
    Object.keys(mergedAlias).forEach(name => {
        const values = lodash_1.default.castArray(mergedAlias[name]);
        const formattedValues = values.map(value => {
            if (typeof value === 'string' && value.startsWith('.')) {
                return ensureAbsolutePath(rootPath, value);
            }
            return value;
        });
        chain.resolve.alias.set(name, formattedValues.length === 1 ? formattedValues[0] : formattedValues);
    });
}
function applyMainFields({ chain, config, target, }) {
    const { resolveMainFields } = config.source;
    if (!resolveMainFields) {
        return;
    }
    const mainFields = Array.isArray(resolveMainFields)
        ? resolveMainFields
        : resolveMainFields[target];
    if (mainFields) {
        mainFields
            .reduce((result, fields) => {
            if (Array.isArray(fields)) {
                result.push(...fields);
            }
            else {
                result.push(fields);
            }
            return result;
        }, [])
            .forEach(field => {
            chain.resolve.mainFields.add(field);
        });
    }
}
