"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpTarget = exports.httpRules = exports.parseArchiveUrl = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const zod_1 = require("zod");
const regex_1 = require("../../../../util/regex");
const url_1 = require("../../../../util/url");
const github_releases_1 = require("../../../datasource/github-releases");
const github_tags_1 = require("../../../datasource/github-tags");
function parseArchiveUrl(urlString) {
    if (!urlString) {
        return null;
    }
    const url = (0, url_1.parseUrl)(urlString);
    if (!url || url.host !== 'github.com' || !url.pathname) {
        return null;
    }
    const path = url.pathname.split('/').slice(1);
    const repo = path[0] + '/' + path[1];
    let datasource = '';
    let currentValue = null;
    if (path[2] === 'releases' && path[3] === 'download') {
        datasource = github_releases_1.GithubReleasesDatasource.id;
        currentValue = path[4];
    }
    else if (path[2] === 'archive' &&
        path[3] === 'refs' &&
        path[4] === 'tags') {
        datasource = github_tags_1.GithubTagsDatasource.id;
        currentValue = path[5];
    }
    else if (path[2] === 'archive') {
        datasource = github_tags_1.GithubTagsDatasource.id;
        currentValue = path[3];
    }
    if (currentValue) {
        // Strip archive extension to get hash or tag.
        // Tolerates formats produced by Git(Hub|Lab) and allowed by http_archive
        // Note: Order matters in suffix list to strip, e.g. .tar.gz.
        for (const extension of ['.gz', '.bz2', '.xz', '.tar', '.tgz', '.zip']) {
            if (currentValue.endsWith(extension)) {
                currentValue = currentValue.slice(0, -extension.length);
            }
        }
        return { datasource, repo, currentValue };
    }
    return null;
}
exports.parseArchiveUrl = parseArchiveUrl;
exports.httpRules = ['http_archive', 'http_file'];
exports.HttpTarget = zod_1.z
    .object({
    rule: zod_1.z.enum(exports.httpRules),
    name: zod_1.z.string(),
    url: zod_1.z.string().optional(),
    urls: zod_1.z.array(zod_1.z.string()).optional(),
    sha256: zod_1.z.string(),
})
    .refine(({ url, urls }) => !!url || !!urls)
    .transform(({ rule, name, url, urls = [] }) => {
    const parsedUrl = [url, ...urls].map(parseArchiveUrl).find(is_1.default.truthy);
    if (!parsedUrl) {
        return null;
    }
    const dep = {
        datasource: parsedUrl.datasource,
        depType: rule,
        depName: name,
        packageName: parsedUrl.repo,
    };
    if ((0, regex_1.regEx)(/^[a-f0-9]{40}$/i).test(parsedUrl.currentValue)) {
        dep.currentDigest = parsedUrl.currentValue;
    }
    else {
        dep.currentValue = parsedUrl.currentValue;
    }
    return dep;
});
//# sourceMappingURL=http.js.map