// ../preview-next/src/session.ts
import { cookies } from "next/headers.js";
import { cache } from "react";

// ../preview-next/src/constants.ts
var PREVIEW_COOKIE_NAME = "preview_token";
var PREVIEW_COOKIE_MAX_AGE = 60 * 60 * 12;

// ../preview-next/src/jwt.ts
function base64UrlDecodeToString(value) {
  const normalized = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
  if (typeof globalThis.atob === "function") {
    const binary = globalThis.atob(normalized);
    const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
    return new TextDecoder().decode(bytes);
  }
  return Buffer.from(normalized, "base64").toString("utf8");
}
function decodeJwtPayload(token) {
  const parts = token.split(".");
  if (parts.length < 2) return null;
  const payloadPart = parts[1];
  if (!payloadPart) return null;
  try {
    const payload = base64UrlDecodeToString(payloadPart);
    return JSON.parse(payload);
  } catch {
    return null;
  }
}

// ../preview-next/src/session.ts
async function validatePreviewSessionToken(token) {
  if (!token) {
    return {
      status: "absent",
      token: null,
      expiresAt: null,
      canEdit: false,
      authMode: null
    };
  }
  const payload = decodeJwtPayload(token);
  if (!payload || typeof payload.exp !== "number") {
    return {
      status: "invalid",
      token,
      expiresAt: null,
      canEdit: false,
      authMode: null
    };
  }
  const authMode = payload.preview_auth_mode === "onboardingGrant" ? "onboardingGrant" : "userSession";
  const expiresAtMs = payload.exp * 1e3;
  const expiresAt = new Date(expiresAtMs).toISOString();
  const now = Date.now();
  if (expiresAtMs <= now) {
    return {
      status: "expired",
      token,
      expiresAt,
      canEdit: false,
      authMode
    };
  }
  return {
    status: "valid",
    token,
    expiresAt,
    // Legacy preview tokens omit can_edit, so absence still means editable.
    canEdit: payload.can_edit !== false,
    authMode
  };
}
async function readPreviewSession(cookiesStore) {
  const token = cookiesStore.get(PREVIEW_COOKIE_NAME)?.value ?? null;
  return validatePreviewSessionToken(token);
}
var getPreviewSession = cache(async () => {
  const cookieStore = await cookies();
  return readPreviewSession(cookieStore);
});
export {
  getPreviewSession,
  readPreviewSession,
  validatePreviewSessionToken
};
//# sourceMappingURL=session.mjs.map