mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 07:00:26 +08:00
55 lines
2.0 KiB
TypeScript
55 lines
2.0 KiB
TypeScript
// API configuration and utility functions
|
|
|
|
// Get API base URL from environment variable.
|
|
// The launcher injects NEXT_PUBLIC_API_BASE from the canonical project-root `.env`.
|
|
export const API_BASE_URL =
|
|
process.env.NEXT_PUBLIC_API_BASE ||
|
|
(() => {
|
|
if (typeof window !== "undefined") {
|
|
console.error("NEXT_PUBLIC_API_BASE is not set.");
|
|
console.error(
|
|
"Please configure NEXT_PUBLIC_API_BASE in your environment and restart the application.",
|
|
);
|
|
console.error("Run python scripts/start_tour.py to rebuild your local setup if needed.");
|
|
}
|
|
throw new Error(
|
|
"NEXT_PUBLIC_API_BASE is not configured. Please set it in your environment and restart.",
|
|
);
|
|
})();
|
|
|
|
/**
|
|
* Construct a full API URL from a path
|
|
* @param path - API path (e.g., '/api/v1/knowledge/list')
|
|
* @returns Full URL (e.g., 'http://localhost:8001/api/v1/knowledge/list')
|
|
*/
|
|
export function apiUrl(path: string): string {
|
|
// Remove leading slash if present to avoid double slashes
|
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
|
|
// Remove trailing slash from base URL if present
|
|
const base = API_BASE_URL.endsWith("/")
|
|
? API_BASE_URL.slice(0, -1)
|
|
: API_BASE_URL;
|
|
|
|
return `${base}${normalizedPath}`;
|
|
}
|
|
|
|
/**
|
|
* Construct a WebSocket URL from a path
|
|
* @param path - WebSocket path (e.g., '/api/v1/solve')
|
|
* @returns WebSocket URL (e.g., 'ws://localhost:8001/api/v1/ws')
|
|
*/
|
|
export function wsUrl(path: string): string {
|
|
// Security Hardening: Convert http to ws and https to wss.
|
|
// In production environments (where API_BASE_URL starts with https), this ensures secure websockets.
|
|
const base = API_BASE_URL.replace(/^http:/, "ws:").replace(/^https:/, "wss:");
|
|
|
|
// Remove leading slash if present to avoid double slashes
|
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
|
|
// Remove trailing slash from base URL if present
|
|
const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
|
|
|
|
return `${normalizedBase}${normalizedPath}`;
|
|
}
|