"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomDatasource = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const jsonata_1 = tslib_1.__importDefault(require("jsonata"));
const logger_1 = require("../../../logger");
const regex_1 = require("../../../util/regex");
const datasource_1 = require("../datasource");
const schema_1 = require("./schema");
const utils_1 = require("./utils");
class CustomDatasource extends datasource_1.Datasource {
    static id = 'custom';
    customRegistrySupport = true;
    constructor() {
        super(CustomDatasource.id);
    }
    async getReleases(getReleasesConfig) {
        const customDatasourceName = getReleasesConfig.datasource?.replace('custom.', '');
        if (!is_1.default.nonEmptyString(customDatasourceName)) {
            logger_1.logger.debug(`No datasource has been supplied while looking up ${getReleasesConfig.packageName}`);
            return null;
        }
        const config = (0, utils_1.massageCustomDatasourceConfig)(customDatasourceName, getReleasesConfig);
        if (is_1.default.nullOrUndefined(config)) {
            return null;
        }
        const { defaultRegistryUrlTemplate, transformTemplates, format } = config;
        // TODO add here other format options than JSON and "plain"
        let response;
        try {
            if (format === 'plain') {
                response = await this.fetchPlainFormat(defaultRegistryUrlTemplate);
            }
            else {
                response = (await this.http.getJson(defaultRegistryUrlTemplate)).body;
            }
        }
        catch (e) {
            this.handleHttpErrors(e);
            return null;
        }
        let data = response;
        for (const transformTemplate of transformTemplates) {
            const expression = (0, jsonata_1.default)(transformTemplate);
            data = await expression.evaluate(data);
        }
        try {
            const parsed = schema_1.ReleaseResultZodSchema.parse(data);
            return structuredClone(parsed);
        }
        catch (err) {
            logger_1.logger.debug({ err }, `Response has failed validation`);
            logger_1.logger.trace({ data }, 'Response that has failed validation');
            return null;
        }
    }
    async fetchPlainFormat(url) {
        const response = await this.http.get(url, {
            headers: {
                Accept: 'text/plain',
            },
        });
        const contentType = response.headers['content-type'];
        if (!contentType?.startsWith('text/')) {
            return null;
        }
        const versions = response.body.split(regex_1.newlineRegex).map((version) => {
            return {
                version: version.trim(),
            };
        });
        return {
            releases: versions,
        };
    }
}
exports.CustomDatasource = CustomDatasource;
//# sourceMappingURL=index.js.map