import axios, { AxiosInstance } from "axios"; import { B44Error, logError } from "./error"; /** * Create an HTTP client with the specified configuration * @param config Client configuration * @returns Configured Axios instance */ export function createHttpClient(config: { baseURL: string; headers?: Record; token?: string; requiresAuth?: boolean; appId: string | number; serverUrl: string; }): AxiosInstance { const { baseURL, headers = {}, token, requiresAuth = false, appId, serverUrl, } = config; // Create Axios instance with default headers const client = axios.create({ baseURL, headers: { "Content-Type": "application/json", Accept: "application/json", ...headers, }, }); // Set authorization header if token is provided if (token) { client.defaults.headers.common["Authorization"] = `Bearer ${token}`; } // Request interceptor to add origin URL client.interceptors.request.use((config) => { if (typeof window !== "undefined") { config.headers.set("X-Origin-URL", window.location.href); } return config; }); // Response interceptor to handle errors client.interceptors.response.use( // Success handler - extract data from response (response) => response.data, // Error handler - convert to B44Error (error) => { // Extract error message from response or use default const message = error.response?.data?.message || error.response?.data?.detail || error.message; // Create B44Error with additional information const b44Error = new B44Error( message, error.response?.status, error.response?.data?.code, error.response?.data, error ); // Log error in development mode if (process.env.NODE_ENV !== "production") { logError("[B44 SDK Error]", b44Error); } // Handle authentication errors console.log( requiresAuth, error.response?.status, typeof window !== "undefined" ); if ( requiresAuth && error.response?.status === 403 && typeof window !== "undefined" ) { console.log("Authentication required. Redirecting to login..."); // Redirect to login page after a short delay setTimeout(() => { redirectToLogin(serverUrl, appId); }, 100); } return Promise.reject(b44Error); } ); return client; } /** * Redirect to the login page * @param serverUrl Base server URL * @param appId Application ID */ function redirectToLogin(serverUrl: string, appId: string | number): void { if (typeof window === "undefined") { return; } const loginUrl = `${serverUrl}/login?from_url=${encodeURIComponent(window.location.href)}&app_id=${appId}`; window.location.href = loginUrl; }