"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.kaminoCdn = exports.KaminoCdnClient = void 0;
const constants_1 = require("../utils/constants");
const DEFAULT_CDN_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
/**
 * Client for fetching and caching Kamino CDN resources.
 * Lazily loads data on first access. Concurrent calls share a single in-flight request.
 * Cached data expires after a configurable TTL (default 5 minutes).
 */
class KaminoCdnClient {
    data;
    loadedAt = 0;
    loadPromise;
    cluster;
    ttlMs;
    constructor(options = {}) {
        this.cluster = options.cluster ?? 'mainnet-beta';
        this.ttlMs = options.ttlMs ?? DEFAULT_CDN_CACHE_TTL_MS;
    }
    /** Returns the full CDN data for the configured cluster, lazily fetching if needed */
    async getData() {
        await this.ensureLoaded();
        return this.data;
    }
    /** Clears the cached data, forcing a fresh fetch on next access */
    clear() {
        this.data = undefined;
        this.loadedAt = 0;
        this.loadPromise = undefined;
    }
    async ensureLoaded() {
        if (this.data && Date.now() - this.loadedAt < this.ttlMs)
            return;
        if (this.loadPromise) {
            await this.loadPromise;
            return;
        }
        this.loadPromise = (async () => {
            try {
                const url = `${constants_1.CDN_ENDPOINT}/resources.json`;
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const text = await response.text();
                const parsed = JSON.parse(text);
                this.data = parsed[this.cluster];
                this.loadedAt = Date.now();
            }
            catch {
                // leave data as undefined, allow retry on next call
            }
            finally {
                this.loadPromise = undefined;
            }
        })();
        await this.loadPromise;
    }
}
exports.KaminoCdnClient = KaminoCdnClient;
/** Default shared client instance for mainnet-beta */
exports.kaminoCdn = new KaminoCdnClient();
//# sourceMappingURL=cdnClient.js.map