import { b as private_env } from './shared-server-DaWdgxVh.js';
import { v as validateAuth } from './auth-DuunT7Cg.js';
import { j as json } from './index-CoD1IJuy.js';
import 'crypto';

const ALLOWED_CLIENT_HEADERS = {
  anthropic: /* @__PURE__ */ new Set(["anthropic-beta", "anthropic-version"]),
  "google-ai": /* @__PURE__ */ new Set([]),
  litellm: /* @__PURE__ */ new Set([]),
  mistral: /* @__PURE__ */ new Set([]),
  openai: /* @__PURE__ */ new Set(["openai-organization", "openai-project"])
};
const POST = async ({ request }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  let payload;
  try {
    payload = await request.json();
  } catch {
    return json({ error: "Invalid JSON body" }, { status: 400 });
  }
  if (!payload || typeof payload !== "object" || typeof payload.provider !== "string" || typeof payload.url !== "string" || !payload.headers || typeof payload.headers !== "object") {
    return json({ error: "Invalid proxy payload" }, { status: 400 });
  }
  const {
    body,
    headers: reqHeaders,
    provider,
    url
  } = payload;
  const ALLOWED_PREFIXES = {
    anthropic: "https://api.anthropic.com/",
    "google-ai": "https://generativelanguage.googleapis.com/",
    mistral: "https://api.mistral.ai/",
    openai: "https://api.openai.com/"
  };
  if (provider === "litellm") {
    const rawBase = private_env.LITELLM_BASE_URL?.trim();
    if (!rawBase) {
      return json({ error: "LiteLLM is not configured on this server" }, { status: 403 });
    }
    const litellmPrefix = `${rawBase.replace(/\/+$/, "")}/`;
    if (!url.startsWith(litellmPrefix)) {
      return json({ error: `Provider "${provider}" or URL not allowed` }, { status: 403 });
    }
  } else {
    const allowedPrefix = ALLOWED_PREFIXES[provider];
    if (!allowedPrefix || !url.startsWith(allowedPrefix)) {
      return json({ error: `Provider "${provider}" or URL not allowed` }, { status: 403 });
    }
  }
  const apiKeyEnv = {
    anthropic: private_env.ANTHROPIC_API_KEY ?? "",
    "google-ai": private_env.GOOGLE_AI_API_KEY ?? "",
    litellm: private_env.LITELLM_API_KEY ?? "",
    mistral: private_env.MISTRAL_API_KEY ?? "",
    openai: private_env.OPENAI_API_KEY ?? ""
  };
  const allowedForProvider = ALLOWED_CLIENT_HEADERS[provider] ?? /* @__PURE__ */ new Set();
  const normalizedReqHeaders = {};
  for (const [k, v] of Object.entries(reqHeaders)) {
    const key = k.toLowerCase();
    if (allowedForProvider.has(key)) {
      normalizedReqHeaders[key] = v;
    }
  }
  const forwardHeaders = {
    "Content-Type": "application/json",
    ...normalizedReqHeaders
  };
  if (provider === "anthropic") {
    if (apiKeyEnv.anthropic) {
      forwardHeaders["x-api-key"] = apiKeyEnv.anthropic;
    }
    forwardHeaders["anthropic-version"] = forwardHeaders["anthropic-version"] ?? "2023-06-01";
  } else if (provider === "google-ai") {
    if (apiKeyEnv["google-ai"]) {
      forwardHeaders["x-goog-api-key"] = apiKeyEnv["google-ai"];
    }
  } else if (provider === "openai") {
    if (apiKeyEnv.openai) {
      forwardHeaders.Authorization = `Bearer ${apiKeyEnv.openai}`;
    }
  } else if (provider === "mistral") {
    if (apiKeyEnv.mistral) {
      forwardHeaders.Authorization = `Bearer ${apiKeyEnv.mistral}`;
    }
  } else if (provider === "litellm") {
    if (apiKeyEnv.litellm) {
      forwardHeaders.Authorization = `Bearer ${apiKeyEnv.litellm}`;
    }
  }
  const controller = new AbortController();
  const timeout = setTimeout(() => {
    controller.abort();
  }, 3e4);
  let resp;
  try {
    resp = await fetch(url, {
      body: JSON.stringify(body),
      headers: forwardHeaders,
      method: "POST",
      signal: controller.signal
    });
  } catch (err) {
    clearTimeout(timeout);
    const message = err instanceof Error ? err.message : "Upstream request failed";
    return json({ error: message }, { status: 502 });
  }
  clearTimeout(timeout);
  let data;
  try {
    data = await resp.json();
  } catch {
    return json({ error: "Upstream returned non-JSON response" }, { status: 502 });
  }
  return json(data, { status: resp.status });
};

export { POST };
//# sourceMappingURL=_server.ts-BCljU9Sg.js.map
