"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.PnpmfileConfiguration = void 0;
const path = __importStar(require("node:path"));
const semver = __importStar(require("semver"));
const node_core_library_1 = require("@rushstack/node-core-library");
const pnpmfile = __importStar(require("./PnpmfileShim"));
const PathConstants_1 = require("../../utilities/PathConstants");
/**
 * Loads PNPM's pnpmfile.js configuration, and invokes it to preprocess package.json files,
 * optionally utilizing a pnpmfile shim to inject preferred versions.
 */
class PnpmfileConfiguration {
    constructor(context) {
        pnpmfile.reset();
        this._context = context;
    }
    static async initializeAsync(rushConfiguration, subspace, variant) {
        if (rushConfiguration.packageManager !== 'pnpm') {
            throw new Error(`PnpmfileConfiguration cannot be used with package manager "${rushConfiguration.packageManager}"`);
        }
        // Set the context to swallow log output and store our settings
        const context = {
            log: (message) => { },
            pnpmfileShimSettings: await PnpmfileConfiguration._getPnpmfileShimSettingsAsync(rushConfiguration, subspace, variant)
        };
        return new PnpmfileConfiguration(context);
    }
    static async writeCommonTempPnpmfileShimAsync(rushConfiguration, targetDir, subspace, variant) {
        if (rushConfiguration.packageManager !== 'pnpm') {
            throw new Error(`PnpmfileConfiguration cannot be used with package manager "${rushConfiguration.packageManager}"`);
        }
        const pnpmfilePath = path.join(targetDir, rushConfiguration.packageManagerWrapper.pnpmfileFilename);
        // Write the shim itself
        await node_core_library_1.FileSystem.copyFileAsync({
            sourcePath: `${PathConstants_1.scriptsFolderPath}/${PathConstants_1.pnpmfileShimFilename}`,
            destinationPath: pnpmfilePath
        });
        const pnpmfileShimSettings = await PnpmfileConfiguration._getPnpmfileShimSettingsAsync(rushConfiguration, subspace, variant);
        // Write the settings file used by the shim
        await node_core_library_1.JsonFile.saveAsync(pnpmfileShimSettings, path.join(targetDir, 'pnpmfileSettings.json'), {
            ensureFolderExists: true
        });
    }
    static async _getPnpmfileShimSettingsAsync(rushConfiguration, subspace, variant) {
        let allPreferredVersions = {};
        let allowedAlternativeVersions = {};
        const workspaceVersions = {};
        // Only workspaces shims in the common versions using pnpmfile
        if (rushConfiguration.packageManagerOptions.useWorkspaces) {
            const commonVersionsConfiguration = subspace.getCommonVersions(variant);
            const preferredVersions = new Map();
            node_core_library_1.MapExtensions.mergeFromMap(preferredVersions, rushConfiguration.getImplicitlyPreferredVersions(subspace, variant));
            for (const [name, version] of commonVersionsConfiguration.getAllPreferredVersions()) {
                // Use the most restrictive version range available
                if (!preferredVersions.has(name) || semver.subset(version, preferredVersions.get(name))) {
                    preferredVersions.set(name, version);
                }
            }
            allPreferredVersions = node_core_library_1.MapExtensions.toObject(preferredVersions);
            allowedAlternativeVersions = node_core_library_1.MapExtensions.toObject(commonVersionsConfiguration.allowedAlternativeVersions);
            for (const project of rushConfiguration.projects) {
                workspaceVersions[project.packageName] = project.packageJson.version;
            }
        }
        const settings = {
            allPreferredVersions,
            allowedAlternativeVersions,
            workspaceVersions,
            semverPath: node_core_library_1.Import.resolveModule({ modulePath: 'semver', baseFolderPath: __dirname })
        };
        // Use the provided path if available. Otherwise, use the default path.
        const userPnpmfilePath = subspace.getPnpmfilePath(variant);
        if (userPnpmfilePath && node_core_library_1.FileSystem.exists(userPnpmfilePath)) {
            settings.userPnpmfilePath = userPnpmfilePath;
        }
        return settings;
    }
    /**
     * Transform a package.json file using the pnpmfile.js hook.
     * @returns the transformed object, or the original input if pnpmfile.js was not found.
     */
    transform(packageJson) {
        var _a;
        if (!((_a = pnpmfile.hooks) === null || _a === void 0 ? void 0 : _a.readPackage) || !this._context) {
            return packageJson;
        }
        else {
            return pnpmfile.hooks.readPackage(packageJson, this._context);
        }
    }
}
exports.PnpmfileConfiguration = PnpmfileConfiguration;
//# sourceMappingURL=PnpmfileConfiguration.js.map