"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/preview-next/before-render.tsx
var before_render_exports = {};
__export(before_render_exports, {
  createPreviewModeBeforeRender: () => createPreviewModeBeforeRender
});
module.exports = __toCommonJS(before_render_exports);

// ../preview-next/src/session.ts
var import_headers = require("next/headers.js");
var import_react = require("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 = (0, import_react.cache)(async () => {
  const cookieStore = await (0, import_headers.cookies)();
  return readPreviewSession(cookieStore);
});

// src/preview-next/before-render.tsx
var import_jsx_runtime = require("react/jsx-runtime");
function createPreviewModeBeforeRender(options) {
  const {
    getClient,
    siteId,
    siteSlug,
    PreviewModeClient,
    enabled,
    requirePageContent = true
  } = options;
  return async (context) => {
    const { content, preview, useThemeScope } = context;
    if (!preview) return null;
    const isEnabled = enabled === void 0 ? process.env.RIVERBANK_PREVIEW_MODE === "true" : typeof enabled === "function" ? enabled() : enabled;
    if (!isEnabled) return null;
    const session = await getPreviewSession();
    if (!session.canEdit || !session.token) return null;
    if (requirePageContent && content.type !== "page") return null;
    const apiBaseUrl = getClient().getBaseUrl();
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      PreviewModeClient,
      {
        apiBaseUrl,
        siteId,
        siteSlug,
        previewSession: {
          canEdit: session.canEdit,
          // SDK preview hosts do not currently resolve can_manage_site, so keep apply-site-style disabled.
          canManage: false,
          authMode: session.authMode,
          expiresAt: session.expiresAt
        },
        previewToken: session.token,
        useThemeScope,
        content
      }
    );
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createPreviewModeBeforeRender
});
//# sourceMappingURL=before-render.js.map