import { env } from '$env/dynamic/public'; export const API_URL = env.PUBLIC_API_URL || 'http://localhost:8000'; // Helper to get token from localStorage export function getToken(): string | null { return localStorage.getItem('token'); } // Helper to add Authorization header if token exists export function authHeaders(headers: Record = {}): Record { const token = getToken(); return token ? { ...headers, Authorization: `Bearer ${token}` } : headers; } /** * Login and Register API */ export interface AuthResponse { access_token: string; token_type: string; } export async function login(username: string, password: string): Promise { const form = new FormData(); form.append('username', username); form.append('password', password); const response = await fetch(`${API_URL}/login`, { method: 'POST', body: form }); if (!response.ok) { const data = await response.json(); throw new Error(data.detail || 'Login failed'); } return response.json(); } export async function register(username: string, password: string): Promise { const response = await fetch(`${API_URL}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); if (!response.ok) { const data = await response.json(); throw new Error(data.detail || 'Registration failed'); } return response.json(); } /** * Type definitions for Subscriptions and Notifications */ export interface Subscription { id: number; topic: string; created_at: string; has_unread: boolean; } export interface Notification { id: number; subscription_id: number; title: string; message: string; priority: number; created_at: string; viewed: boolean; } /** * Type definitions for Settings */ export interface Settings { id: number; requirements: string; environment: string; user: string; ntfy_url?: string; } export async function checkHealth(): Promise<'healthy' | 'unhealthy'> { try { const response = await fetch(`${API_URL}/health`); if (response.ok) { return 'healthy'; } else { return 'unhealthy'; } } catch { return 'unhealthy'; } } /** * Type definitions for Script and Log */ export interface Log { id: number; script_id: number; message: string; error_message: string; error_code: number; created_at?: string; } export interface Script { id: number; name: string; script_content?: string; created_at?: string; enabled: boolean; } // Fetch all scripts export async function fetchScripts(): Promise { const response = await fetch(`${API_URL}/script`, { headers: authHeaders() }); if (!response.ok) { throw new Error('Failed to fetch scripts ' + response.statusText); } return response.json(); } // Add a new script export async function addScript( script: Omit ): Promise