File size: 1,612 Bytes
1a12d36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * Centralized API utilities.
 *
 * In production: HttpOnly cookie (hf_access_token) is sent automatically.
 * In development: auth is bypassed on the backend.
 * 
 * NOTE: This version supports separate frontend/backend hosting.
 * Configure the backend URL via VITE_BACKEND_URL environment variable.
 */

import { API_CONFIG } from '@/config/api';
import { triggerLogin } from '@/hooks/useAuth';

/** Wrapper around fetch with credentials and common headers. */
export async function apiFetch(
  path: string,
  options: RequestInit = {}
): Promise<Response> {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(options.headers as Record<string, string>),
  };

  // Build full URL using the configured backend URL
  const url = API_CONFIG.getApiUrl(path);

  const response = await fetch(url, {
    ...options,
    headers,
    credentials: 'include', // Send cookies with every request
  });

  // Handle 401 — redirect to login
  if (response.status === 401) {
    try {
      const authStatus = await fetch(API_CONFIG.getApiUrl('/auth/status'), { 
        credentials: 'include' 
      });
      const data = await authStatus.json();
      if (data.auth_enabled) {
        triggerLogin();
        throw new Error('Authentication required — redirecting to login.');
      }
    } catch (e) {
      if (e instanceof Error && e.message.includes('redirecting')) throw e;
    }
  }

  return response;
}

/** Build the WebSocket URL for a session. */
export function getWebSocketUrl(sessionId: string): string {
  return API_CONFIG.getWebSocketUrl(sessionId);
}