const safeParse = (json) => {
    try {
        return JSON.parse(json ?? "null");
    }
    catch (e) { }
};
export const createCache = (storage) => {
    const jwtStore = new Map();
    const tidStore = new Map();
    const getJwt = (k) => {
        const now = Date.now();
        let { jwt, exp } = jwtStore.get(k) ?? {};
        if (jwt && exp && exp > now) {
            return jwt;
        }
        if (jwt) {
            jwtStore.delete(k);
        }
        ({ jwt, exp } = safeParse(storage?.getItem(k)) ?? {});
        if (jwt && exp && exp > now) {
            jwtStore.set(k, { jwt, exp });
            return jwt;
        }
        if (jwt) {
            storage?.removeItem(k);
        }
        return null;
    };
    const setJwt = (k, jwt, exp) => {
        const now = Date.now();
        if (jwt === "" || exp < now) {
            return;
        }
        jwtStore.set(k, { jwt, exp });
        storage?.setItem(k, JSON.stringify({ jwt, exp }));
        clearTimeout(tidStore.get(k));
        tidStore.set(k, setTimeout(() => removeJwt(k), exp - now));
    };
    const removeJwt = (k) => {
        jwtStore.delete(k);
        clearTimeout(tidStore.get(k));
        tidStore.delete(k);
        storage?.removeItem(k);
    };
    const clear = () => {
        if (storage) {
            Array.from(jwtStore.keys()).forEach((k) => storage?.removeItem(k));
        }
        jwtStore.clear();
        Array.from(tidStore.values()).forEach(clearTimeout);
        tidStore.clear();
    };
    return {
        getJwt,
        setJwt,
        clear,
    };
};
//# sourceMappingURL=createCache.js.map