import { fetchJwt } from "./fetchJwt.js";
import { parseJwt } from "./parseJwt.js";
const ms = (exp) => exp * 1_000;
const nullAuth = () => ({ jwt: null, token: null });
export const makeAuth = (cache, key) => async (input, { useCache = true, parseToken = true, ...init } = {}) => {
    let jwtSource = "cache";
    const k = await key(input, init);
    // cached jwt only lasts until jwt expires
    let jwt = useCache && cache.getJwt(k);
    if (jwt && !parseToken) {
        return { jwt, token: null };
    }
    if (!jwt) {
        // cache miss, fetch from network
        jwt = await fetchJwt(input, init);
        jwtSource = "network";
    }
    if (!jwt) {
        return nullAuth();
    }
    const token = parseJwt(jwt);
    if (!token) {
        return { jwt: null, token: null };
    }
    if (useCache && jwtSource === "network" && !token.isExpired) {
        const { exp } = token.payload;
        cache.setJwt(k, jwt, ms(exp));
    }
    return { jwt, token };
};
//# sourceMappingURL=makeAuth.js.map