import { toast } from '$lib/stores/toasts.js'; import { getSocketId } from '$lib/stores/socket.js'; export type ApiResult = { ok: boolean; data: T; status: number; }; export async function api( url: string, opts: RequestInit = {} ): Promise> { const headers = new Headers(opts.headers); // Auto-set JSON content type for non-FormData bodies if (opts.body && !(opts.body instanceof FormData) && !headers.has('Content-Type')) { headers.set('Content-Type', 'application/json'); } // Pass socket ID for self-dedup const sid = getSocketId(); if (sid) { headers.set('X-Socket-ID', sid); } try { const res = await fetch(url, { ...opts, headers }); let data: any = null; const contentType = res.headers.get('content-type'); if (contentType?.includes('application/json')) { data = await res.json(); } if (!res.ok) { const msg = data?.error || data?.message || `Request failed (${res.status})`; toast.error(msg); return { ok: false, data, status: res.status }; } return { ok: true, data, status: res.status }; } catch { toast.error('Network error. Please try again.'); return { ok: false, data: null as any, status: 0 }; } }