"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateElectronDependency = exports.getElectronVersion = exports.getElectronModulePath = exports.PackageNotFoundError = void 0;
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const find_up_1 = __importDefault(require("find-up"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const semver_1 = __importDefault(require("semver"));
const yarn_or_npm_1 = require("./yarn-or-npm");
const d = (0, debug_1.default)('electron-forge:electron-version');
const electronPackageNames = ['electron-nightly', 'electron'];
function findElectronDep(dep) {
    return electronPackageNames.includes(dep);
}
async function findAncestorNodeModulesPath(dir, packageName) {
    d('Looking for a lock file to indicate the root of the repo');
    const lockPath = await (0, find_up_1.default)(['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'], { cwd: dir, type: 'file' });
    if (lockPath) {
        d(`Found lock file: ${lockPath}`);
        const nodeModulesPath = path_1.default.join(path_1.default.dirname(lockPath), 'node_modules', packageName);
        if (await fs_extra_1.default.pathExists(nodeModulesPath)) {
            return nodeModulesPath;
        }
    }
    return Promise.resolve(undefined);
}
async function determineNodeModulesPath(dir, packageName) {
    const nodeModulesPath = path_1.default.join(dir, 'node_modules', packageName);
    if (await fs_extra_1.default.pathExists(nodeModulesPath)) {
        return nodeModulesPath;
    }
    return findAncestorNodeModulesPath(dir, packageName);
}
class PackageNotFoundError extends Error {
    constructor(packageName, dir) {
        super(`Cannot find the package "${packageName}". Perhaps you need to run "${(0, yarn_or_npm_1.safeYarnOrNpm)()} install" in "${dir}"?`);
    }
}
exports.PackageNotFoundError = PackageNotFoundError;
function getElectronModuleName(packageJSON) {
    if (!packageJSON.devDependencies) {
        throw new Error('package.json for app does not have any devDependencies');
    }
    // Why: checked above
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    const packageName = electronPackageNames.find((pkg) => packageJSON.devDependencies[pkg]);
    if (packageName === undefined) {
        throw new Error('Could not find any Electron packages in devDependencies');
    }
    return packageName;
}
async function getElectronPackageJSONPath(dir, packageName) {
    const nodeModulesPath = await determineNodeModulesPath(dir, packageName);
    if (!nodeModulesPath) {
        throw new PackageNotFoundError(packageName, dir);
    }
    const electronPackageJSONPath = path_1.default.join(nodeModulesPath, 'package.json');
    if (await fs_extra_1.default.pathExists(electronPackageJSONPath)) {
        return electronPackageJSONPath;
    }
    return undefined;
}
async function getElectronModulePath(dir, packageJSON) {
    const moduleName = getElectronModuleName(packageJSON);
    const packageJSONPath = await getElectronPackageJSONPath(dir, moduleName);
    if (packageJSONPath) {
        return path_1.default.dirname(packageJSONPath);
    }
    return undefined;
}
exports.getElectronModulePath = getElectronModulePath;
async function getElectronVersion(dir, packageJSON) {
    const packageName = getElectronModuleName(packageJSON);
    // Why: checked in getElectronModuleName
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    let version = packageJSON.devDependencies[packageName];
    if (!semver_1.default.valid(version)) {
        // It's not an exact version, find it in the actual module
        const electronPackageJSONPath = await getElectronPackageJSONPath(dir, packageName);
        if (electronPackageJSONPath) {
            const electronPackageJSON = await fs_extra_1.default.readJson(electronPackageJSONPath);
            version = electronPackageJSON.version;
        }
        else {
            throw new PackageNotFoundError(packageName, dir);
        }
    }
    return version;
}
exports.getElectronVersion = getElectronVersion;
function updateElectronDependency(packageJSON, dev, exact) {
    const alteredDev = [].concat(dev);
    let alteredExact = [].concat(exact);
    // Why: checked in getElectronModuleName
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    if (Object.keys(packageJSON.devDependencies).find(findElectronDep)) {
        alteredExact = alteredExact.filter((dep) => dep !== 'electron');
    }
    else if (packageJSON.dependencies) {
        const electronKey = Object.keys(packageJSON.dependencies).find(findElectronDep);
        if (electronKey) {
            alteredExact = alteredExact.filter((dep) => dep !== 'electron');
            d(`Moving ${electronKey} from dependencies to devDependencies`);
            alteredDev.push(`${electronKey}@${packageJSON.dependencies[electronKey]}`);
            delete packageJSON.dependencies[electronKey];
        }
    }
    return [alteredDev, alteredExact];
}
exports.updateElectronDependency = updateElectronDependency;
//# sourceMappingURL=data:application/json;base64, 