import { IRequest } from 'itty-router'; /** * CORS headers to allow any domain to call our service */ const CORS_HEADERS = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-openai-api-key, x-claude-api-key, x-anthropic-api-key, x-google-api-key, x-google-ai-api-key, x-groq-api-key, x-mistral-api-key, x-openrouter-api-key, x-cohere-api-key, x-ai21-api-key, x-xai-api-key, x-deepseek-api-key, x-cloudflare-api-key, x-cloudflare-account-id, x-stability-api-key, x-falai-api-key', 'Access-Control-Max-Age': '86400', // 24 hours }; /** * CORS middleware that adds CORS headers to all responses */ export function corsMiddleware(req: IRequest) { // Handle OPTIONS preflight request if (req.method === 'OPTIONS') { return new Response(null, { status: 204, headers: CORS_HEADERS }); } // Continue to next handler return undefined; } /** * Wrap a response with CORS headers */ export function withCors(response: Response): Response { const newHeaders = new Headers(response.headers); // Add CORS headers for (const [key, value] of Object.entries(CORS_HEADERS)) { newHeaders.set(key, value); } return new Response(response.body, { status: response.status, statusText: response.statusText, headers: newHeaders }); } /** * Create a JSON response with CORS headers */ export function jsonWithCors(data: any, init?: ResponseInit): Response { const headers = new Headers(init?.headers || {}); headers.set('Content-Type', 'application/json'); // Add CORS headers for (const [key, value] of Object.entries(CORS_HEADERS)) { headers.set(key, value); } return new Response(JSON.stringify(data), { ...init, headers }); }