"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_loggers_1 = require("@pnpm/core-loggers");
const types_1 = require("@pnpm/types");
const load_json_file_1 = require("load-json-file");
const path = require("path");
const writePkg = require("write-pkg");
async function save(prefix, packageSpecs) {
    // Read the latest version of package.json to avoid accidental overwriting
    let packageJson;
    const pkgJsonPath = path.join(prefix, 'package.json');
    try {
        packageJson = await load_json_file_1.default(pkgJsonPath);
    }
    catch (err) {
        if (err['code'] !== 'ENOENT')
            throw err; // tslint:disable-line:no-string-literal
        packageJson = {};
    }
    packageSpecs.forEach((packageSpec) => {
        if (packageSpec.saveType) {
            const saveType = packageSpec.saveType;
            packageJson[packageSpec.saveType] = packageJson[packageSpec.saveType] || {};
            packageJson[saveType][packageSpec.name] = packageSpec.pref || findSpec(packageSpec.name, packageJson);
            types_1.DEPENDENCIES_FIELDS.filter((depField) => depField !== packageSpec.saveType).forEach((deptype) => {
                if (packageJson[deptype]) {
                    delete packageJson[deptype][packageSpec.name];
                }
            });
        }
        else {
            const usedDepType = guessDependencyType(packageSpec.name, packageJson) || 'dependencies';
            packageJson[usedDepType] = packageJson[usedDepType] || {};
            packageJson[usedDepType][packageSpec.name] = packageSpec.pref;
        }
    });
    await writePkg(pkgJsonPath, packageJson);
    core_loggers_1.packageJsonLogger.debug({
        prefix,
        updated: packageJson,
    });
    return packageJson;
}
exports.default = save;
function findSpec(depName, pkg) {
    const foundDepType = guessDependencyType(depName, pkg);
    return foundDepType && pkg[foundDepType][depName];
}
function guessDependencyType(depName, pkg) {
    return types_1.DEPENDENCIES_FIELDS
        .find((depField) => Boolean(pkg[depField] && pkg[depField][depName]));
}
exports.guessDependencyType = guessDependencyType;
//# sourceMappingURL=save.js.map