"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.latest = void 0;
const fast_memoize_1 = __importDefault(require("fast-memoize"));
const promises_1 = __importDefault(require("fs/promises"));
const make_fetch_happen_1 = __importDefault(require("make-fetch-happen"));
const programError_1 = __importDefault(require("../lib/programError"));
/** Returns true if a string is a url. */
const isUrl = (s) => (s && s.startsWith('http://')) || s.startsWith('https://');
/**
 * Returns a registry object given a valid file path or url.
 *
 * @param path
 * @returns a registry object
 */
const readStaticRegistry = async (options) => {
    const path = options.registry;
    let content;
    // url
    if (isUrl(path)) {
        const body = await (0, make_fetch_happen_1.default)(path);
        content = await body.text();
    }
    // local path
    else {
        try {
            content = await promises_1.default.readFile(path, 'utf8');
        }
        catch (err) {
            (0, programError_1.default)(options, `\nThe specified static registry file does not exist: ${options.registry}`);
        }
    }
    return JSON.parse(content);
};
const registryMemoized = (0, fast_memoize_1.default)(readStaticRegistry);
/**
 * Fetches the version in static registry.
 *
 * @param packageName
 * @param currentVersion
 * @param options
 * @returns A promise that fulfills to string value or null
 */
const latest = async (packageName, currentVersion, options) => {
    const registry = await registryMemoized(options || {});
    return { version: registry[packageName] || null };
};
exports.latest = latest;
//# sourceMappingURL=staticRegistry.js.map