import { U as A, V as v, W as T } from "./mcp-server-Bxbg2tUi.js";
const y = /* @__PURE__ */ new Set([401, 403]);
function C(e) {
  const t = T(e);
  if (t !== void 0)
    return t;
  if (e !== null && typeof e == "object" && "response" in e)
    return T(e.response);
}
async function _(e, t) {
  const r = A(e, { baseUrl: t });
  try {
    return await v("auth:validate-token", () => r.getUser()), !0;
  } catch (i) {
    const a = C(i);
    if (a !== void 0 && y.has(a))
      return !1;
    throw i;
  }
}
const p = 3e5, w = 12e4, h = 1e4, n = /* @__PURE__ */ new Map();
function k(e, t) {
  return t ? `${e}::${t}` : e;
}
function E() {
  const e = Date.now();
  for (const [t, r] of n)
    e >= r.expiresAt && n.delete(t);
}
function S(e) {
  const t = n.get(e);
  if (t && Date.now() < t.expiresAt)
    return t.valid;
  t && n.delete(e);
}
function U(e, t, r) {
  n.size >= h && E(), n.size >= h && n.clear(), n.set(e, { valid: t, expiresAt: Date.now() + r });
}
function g(e) {
  return e ? `Bearer resource_metadata="${e}"` : "Bearer";
}
function d(e, t) {
  e.status(401).set("WWW-Authenticate", g(t)).json({
    error: "invalid_token",
    error_description: "Todoist API token is invalid or expired"
  });
}
function D(e) {
  const t = e.type === "static" ? p : w, r = e.cacheTtlMs ?? t, { resourceMetadataUrl: i } = e;
  return async (a, s, c) => {
    const u = e.type === "static" ? e.apiKey : e.getApiKey(a);
    if (!u) {
      d(s, i);
      return;
    }
    const f = k(u, e.baseUrl), l = S(f);
    if (l !== void 0) {
      l ? c() : d(s, i);
      return;
    }
    try {
      const o = await _(u, e.baseUrl);
      U(f, o, r), o ? c() : d(s, i);
    } catch (o) {
      console.warn("[Token validation] Transient error, proceeding:", o), c();
    }
  };
}
export {
  D as r,
  _ as v
};
