"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DartVersionDatasource = exports.stableVersionRegex = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const regex_1 = require("../../../util/regex");
const datasource_1 = require("../datasource");
exports.stableVersionRegex = (0, regex_1.regEx)(/^\d+\.\d+\.\d+$/);
class DartVersionDatasource extends datasource_1.Datasource {
    constructor() {
        super(DartVersionDatasource.id);
        this.customRegistrySupport = false;
        this.defaultRegistryUrls = ['https://storage.googleapis.com'];
        this.caching = true;
        this.channels = ['stable', 'beta', 'dev'];
    }
    async getReleases({ registryUrl, }) {
        // istanbul ignore if
        if (!registryUrl) {
            return null;
        }
        const result = {
            homepage: 'https://dart.dev/',
            sourceUrl: 'https://github.com/dart-lang/sdk',
            registryUrl,
            releases: [],
        };
        try {
            for (const channel of this.channels) {
                const resp = (await this.http.getJson(`${registryUrl}/storage/v1/b/dart-archive/o?delimiter=%2F&prefix=channels%2F${channel}%2Frelease%2F&alt=json`)).body;
                const releases = this.getReleasesFromResponse(channel, resp.prefixes);
                result.releases.push(...releases);
            }
        }
        catch (err) {
            this.handleGenericErrors(err);
        }
        return result.releases.length ? result : null;
    }
    getReleasesFromResponse(channel, prefixes) {
        return prefixes
            .map((prefix) => this.getVersionFromPrefix(prefix))
            .filter(is_1.default.string)
            .filter((version) => {
            if (version === 'latest' ||
                // The API response contains a stable version being released as a non-stable
                // release. So we filter out these releases here.
                (channel !== 'stable' && exports.stableVersionRegex.test(version))) {
                return false;
            }
            return true;
        })
            .map((version) => ({ version, isStable: channel === 'stable' }));
    }
    // Prefix should have a format of "channels/stable/release/2.9.3/"
    getVersionFromPrefix(prefix) {
        const parts = prefix.split('/');
        return parts[parts.length - 2];
    }
}
exports.DartVersionDatasource = DartVersionDatasource;
DartVersionDatasource.id = 'dart-version';
//# sourceMappingURL=index.js.map