import axios from 'axios'; const rawBaseUrl = import.meta.env.VITE_API_URL || (import.meta.env.DEV ? 'http://localhost:8000/api/v1' : '/api/v1'); // Intelligent URL Normalization: let sanitizedBaseUrl = rawBaseUrl.trim(); // Ensure absolute URLs have a protocol and /api/v1 suffix if (sanitizedBaseUrl.startsWith('http')) { if (!sanitizedBaseUrl.includes('/api/')) { sanitizedBaseUrl = sanitizedBaseUrl.endsWith('/') ? `${sanitizedBaseUrl}api/v1` : `${sanitizedBaseUrl}/api/v1`; } } // Final trailing slash for clean joins const BASE_URL = sanitizedBaseUrl.endsWith('/') ? sanitizedBaseUrl : `${sanitizedBaseUrl}/`; // Logging for Frontend Debugging console.log(`[API_CLIENT] Initializing...`); console.log(`[API_CLIENT] Raw URL: ${rawBaseUrl}`); console.log(`[API_CLIENT] Sanitized BASE_URL: ${BASE_URL}`); export const api = axios.create({ baseURL: BASE_URL, }); /** * Generates a WebSocket URL based on the current environment and API settings. * Handles HTTP/S protocol switching and domain resolution for production tunnels. */ export const getWsUrl = (path: string) => { // Use the API's base URL as the source of truth for the domain // We use window.location.origin as a fallback for relative BASE_URL paths const apiBase = new URL(BASE_URL, window.location.origin); const protocol = apiBase.protocol === 'https:' ? 'wss:' : 'ws:'; // WebSockets are served from the root of the API server (no /api/v1 prefix) const host = apiBase.host; // Clean forward slash concatenation const cleanPath = path.startsWith('/') ? path : `/${path}`; return `${protocol}//${host}${cleanPath}`; }; let portalType: 'customer' | 'internal' | null = null; /** * Returns a portal-scoped storage key to prevent session collision * when hosting multiple portals on the same domain (e.g. Hugging Face Spaces). */ export const getStorageKey = (key: string) => { return portalType ? `${portalType}_${key}` : key; }; export const setPortalType = (type: 'customer' | 'internal') => { portalType = type; console.log(`[API_CLIENT] Portal Context: ${type}`); }; api.interceptors.request.use((config) => { // Ensure trailing slash on all endpoints to prevent 307 redirects (Mixed Content prevention) if (config.url && !config.url.endsWith('/') && !config.url.includes('?')) { config.url = `${config.url}/`; } const token = localStorage.getItem(getStorageKey('token')); if (token) { config.headers.Authorization = `Bearer ${token}`; } if (portalType) { config.headers['X-Nexus-Portal'] = portalType; } return config; }); api.interceptors.response.use( (response) => response, (error) => { const status = error.response?.status; if (status === 401) { const prevToken = localStorage.getItem(getStorageKey('token')); if (prevToken) { localStorage.removeItem(getStorageKey('token')); localStorage.removeItem(getStorageKey('refresh_token')); localStorage.removeItem(getStorageKey('user')); // Portal-agnostic reload: just refresh the current page // The App.tsx will see the lack of token and show the LoginCard window.location.reload(); } } if (status === 429) { const retryAfter = error.response?.data?.retry_after_seconds || 60; console.warn(`[API_CLIENT] Rate limited. Retry after ${retryAfter}s`); } return Promise.reject(error); } ); export default api;