"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectPlatform = detectPlatform;
exports.noLeadingAtSymbol = noLeadingAtSymbol;
exports.parseJson = parseJson;
exports.parseJsonWithFallback = parseJsonWithFallback;
const tslib_1 = require("tslib");
const json5_1 = tslib_1.__importDefault(require("json5"));
const constants_1 = require("../constants");
const logger_1 = require("../logger");
const hostRules = tslib_1.__importStar(require("./host-rules"));
const url_1 = require("./url");
/**
 * Tries to detect the `platform` from a url.
 *
 * @param url the url to detect `platform` from
 * @returns matched `platform` if found, otherwise `null`
 */
function detectPlatform(url) {
    const { hostname } = (0, url_1.parseUrl)(url) ?? {};
    if (hostname === 'dev.azure.com' || hostname?.endsWith('.visualstudio.com')) {
        return 'azure';
    }
    if (hostname === 'bitbucket.org' || hostname === 'bitbucket.com') {
        return 'bitbucket';
    }
    if (hostname?.includes('bitbucket')) {
        return 'bitbucket-server';
    }
    if (hostname &&
        (['gitea.com', 'codeberg.org'].includes(hostname) ||
            hostname.includes('gitea') ||
            hostname.includes('forgejo'))) {
        return 'gitea';
    }
    if (hostname === 'github.com' || hostname?.includes('github')) {
        return 'github';
    }
    if (hostname === 'gitlab.com' || hostname?.includes('gitlab')) {
        return 'gitlab';
    }
    const hostType = hostRules.hostType({ url });
    if (!hostType) {
        return null;
    }
    if (constants_1.BITBUCKET_SERVER_API_USING_HOST_TYPES.includes(hostType)) {
        return 'bitbucket-server';
    }
    if (constants_1.BITBUCKET_API_USING_HOST_TYPES.includes(hostType)) {
        return 'bitbucket';
    }
    if (constants_1.GITEA_API_USING_HOST_TYPES.includes(hostType)) {
        return 'gitea';
    }
    if (constants_1.GITHUB_API_USING_HOST_TYPES.includes(hostType)) {
        return 'github';
    }
    if (constants_1.GITLAB_API_USING_HOST_TYPES.includes(hostType)) {
        return 'gitlab';
    }
    return null;
}
function noLeadingAtSymbol(input) {
    return input.startsWith('@') ? input.slice(1) : input;
}
function parseJson(content, filename) {
    if (!content) {
        return null;
    }
    return filename.endsWith('.json5')
        ? json5_1.default.parse(content)
        : parseJsonWithFallback(content, filename);
}
function parseJsonWithFallback(content, context) {
    let parsedJson;
    try {
        parsedJson = JSON.parse(content);
    }
    catch {
        parsedJson = json5_1.default.parse(content);
        logger_1.logger.warn({ context }, 'File contents are invalid JSON but parse using JSON5. Support for this will be removed in a future release so please change to a support .json5 file name or ensure correct JSON syntax.');
    }
    return parsedJson;
}
//# sourceMappingURL=common.js.map