"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getExtractedConstraints = exports.extractDependency = exports.parseDepName = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const validate_npm_package_name_1 = tslib_1.__importDefault(require("validate-npm-package-name"));
const logger_1 = require("../../../../../logger");
const regex_1 = require("../../../../../util/regex");
const github_tags_1 = require("../../../../datasource/github-tags");
const npm_1 = require("../../../../datasource/npm");
const nodeVersioning = tslib_1.__importStar(require("../../../../versioning/node"));
const npm_2 = require("../../../../versioning/npm");
const RE_REPOSITORY_GITHUB_SSH_FORMAT = (0, regex_1.regEx)(/(?:git@)github.com:([^/]+)\/([^/.]+)(?:\.git)?/);
function parseDepName(depType, key) {
    if (depType !== 'resolutions') {
        return key;
    }
    const [, depName] = (0, regex_1.regEx)(/((?:@[^/]+\/)?[^/@]+)$/).exec(key) ?? [];
    return depName;
}
exports.parseDepName = parseDepName;
function extractDependency(depType, depName, input) {
    const dep = {};
    if (!(0, validate_npm_package_name_1.default)(depName).validForOldPackages) {
        dep.skipReason = 'invalid-name';
        return dep;
    }
    if (typeof input !== 'string') {
        dep.skipReason = 'invalid-value';
        return dep;
    }
    dep.currentValue = input.trim();
    if (depType === 'engines' || depType === 'packageManager') {
        if (depName === 'node') {
            dep.datasource = github_tags_1.GithubTagsDatasource.id;
            dep.packageName = 'nodejs/node';
            dep.versioning = nodeVersioning.id;
        }
        else if (depName === 'yarn') {
            dep.datasource = npm_1.NpmDatasource.id;
            dep.commitMessageTopic = 'Yarn';
            const major = (0, npm_2.isVersion)(dep.currentValue) && npm_2.api.getMajor(dep.currentValue);
            if (major && major > 1) {
                dep.packageName = '@yarnpkg/cli';
            }
        }
        else if (depName === 'npm') {
            dep.datasource = npm_1.NpmDatasource.id;
            dep.commitMessageTopic = 'npm';
        }
        else if (depName === 'pnpm') {
            dep.datasource = npm_1.NpmDatasource.id;
            dep.commitMessageTopic = 'pnpm';
        }
        else if (depName === 'vscode') {
            dep.datasource = github_tags_1.GithubTagsDatasource.id;
            dep.packageName = 'microsoft/vscode';
        }
        else {
            dep.skipReason = 'unknown-engines';
        }
        if (!(0, npm_2.isValid)(dep.currentValue)) {
            dep.skipReason = 'unspecified-version';
        }
        return dep;
    }
    // support for volta
    if (depType === 'volta') {
        if (depName === 'node') {
            dep.datasource = github_tags_1.GithubTagsDatasource.id;
            dep.packageName = 'nodejs/node';
            dep.versioning = nodeVersioning.id;
        }
        else if (depName === 'yarn') {
            dep.datasource = npm_1.NpmDatasource.id;
            dep.commitMessageTopic = 'Yarn';
            const major = (0, npm_2.isVersion)(dep.currentValue) && npm_2.api.getMajor(dep.currentValue);
            if (major && major > 1) {
                dep.packageName = '@yarnpkg/cli';
            }
        }
        else if (depName === 'npm') {
            dep.datasource = npm_1.NpmDatasource.id;
        }
        else if (depName === 'pnpm') {
            dep.datasource = npm_1.NpmDatasource.id;
            dep.commitMessageTopic = 'pnpm';
        }
        else {
            dep.skipReason = 'unknown-volta';
        }
        if (!(0, npm_2.isValid)(dep.currentValue)) {
            dep.skipReason = 'unspecified-version';
        }
        return dep;
    }
    if (dep.currentValue.startsWith('npm:')) {
        dep.npmPackageAlias = true;
        const valSplit = dep.currentValue.replace('npm:', '').split('@');
        if (valSplit.length === 1) {
            dep.packageName = depName;
            dep.currentValue = valSplit[0];
        }
        else if (valSplit.length === 2) {
            dep.packageName = valSplit[0];
            dep.currentValue = valSplit[1];
        }
        else if (valSplit.length === 3) {
            dep.packageName = valSplit[0] + '@' + valSplit[1];
            dep.currentValue = valSplit[2];
        }
        else {
            logger_1.logger.debug(`Invalid npm package alias for dependency: "${depName}":"${dep.currentValue}"`);
        }
    }
    if (dep.currentValue.startsWith('file:')) {
        dep.skipReason = 'file';
        return dep;
    }
    if ((0, npm_2.isValid)(dep.currentValue)) {
        dep.datasource = npm_1.NpmDatasource.id;
        if (dep.currentValue === '') {
            dep.skipReason = 'empty';
        }
        return dep;
    }
    const hashSplit = dep.currentValue.split('#');
    if (hashSplit.length !== 2) {
        dep.skipReason = 'unspecified-version';
        return dep;
    }
    const [depNamePart, depRefPart] = hashSplit;
    let githubOwnerRepo;
    let githubOwner;
    let githubRepo;
    const matchUrlSshFormat = RE_REPOSITORY_GITHUB_SSH_FORMAT.exec(depNamePart);
    if (matchUrlSshFormat === null) {
        githubOwnerRepo = depNamePart
            .replace((0, regex_1.regEx)(/^github:/), '')
            .replace((0, regex_1.regEx)(/^git\+/), '')
            .replace((0, regex_1.regEx)(/^https:\/\/github\.com\//), '')
            .replace((0, regex_1.regEx)(/\.git$/), '');
        const githubRepoSplit = githubOwnerRepo.split('/');
        if (githubRepoSplit.length !== 2) {
            dep.skipReason = 'unspecified-version';
            return dep;
        }
        [githubOwner, githubRepo] = githubRepoSplit;
    }
    else {
        githubOwner = matchUrlSshFormat[1];
        githubRepo = matchUrlSshFormat[2];
        githubOwnerRepo = `${githubOwner}/${githubRepo}`;
    }
    const githubValidRegex = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/i; // TODO #12872 lookahead
    if (!githubValidRegex.test(githubOwner) ||
        !githubValidRegex.test(githubRepo)) {
        dep.skipReason = 'unspecified-version';
        return dep;
    }
    if ((0, npm_2.isVersion)(depRefPart)) {
        dep.currentRawValue = dep.currentValue;
        dep.currentValue = depRefPart;
        dep.datasource = github_tags_1.GithubTagsDatasource.id;
        dep.packageName = githubOwnerRepo;
        dep.pinDigests = false;
    }
    else if ((0, regex_1.regEx)(/^[0-9a-f]{7}$/).test(depRefPart) ||
        (0, regex_1.regEx)(/^[0-9a-f]{40}$/).test(depRefPart)) {
        dep.currentRawValue = dep.currentValue;
        dep.currentValue = null;
        dep.currentDigest = depRefPart;
        dep.datasource = github_tags_1.GithubTagsDatasource.id;
        dep.packageName = githubOwnerRepo;
    }
    else {
        dep.skipReason = 'unversioned-reference';
        return dep;
    }
    dep.sourceUrl = `https://github.com/${githubOwnerRepo}`;
    dep.gitRef = true;
    return dep;
}
exports.extractDependency = extractDependency;
function getExtractedConstraints(deps) {
    const extractedConstraints = {};
    const constraints = ['node', 'yarn', 'npm', 'pnpm', 'vscode'];
    for (const dep of deps) {
        if (!dep.skipReason &&
            (dep.depType === 'engines' || dep.depType === 'packageManager') &&
            dep.depName &&
            constraints.includes(dep.depName) &&
            is_1.default.string(dep.currentValue)) {
            extractedConstraints[dep.depName] = dep.currentValue;
        }
    }
    return extractedConstraints;
}
exports.getExtractedConstraints = getExtractedConstraints;
//# sourceMappingURL=dependency.js.map