import type { ApiProblem } from "../types"; import { API_ORIGIN } from "../../lib/runtime-config"; export const apiOrigin = API_ORIGIN; let csrfToken: string | null = null; const getCache = new Map }>(); const getCacheTtlMs = 30_000; export class ApiError extends Error { constructor(public status: number, public problem: ApiProblem) { super(problem.title ?? "خطا در ارتباط با سرور"); } } async function getCsrfToken() { if (csrfToken) return csrfToken; const response = await fetch(`${apiOrigin}/api/v1/auth/csrf`, { credentials: "include" }); if (!response.ok) throw new Error("دریافت توکن امنیتی ناموفق بود."); csrfToken = (await response.json() as { requestToken: string }).requestToken; return csrfToken; } export async function api(path: string, init: RequestInit = {}): Promise { const method = (init.method ?? "GET").toUpperCase(); if (method === "GET") { const cached = getCache.get(path); if (cached && cached.expires > Date.now()) return cached.value as Promise; if (cached) getCache.delete(path); const value = request(path, init, method).catch(reason => { getCache.delete(path); throw reason; }); getCache.set(path, { expires: Date.now() + getCacheTtlMs, value }); return value; } getCache.clear(); return request(path, init, method); } async function request(path: string, init: RequestInit, method: string): Promise { const headers = new Headers(init.headers); headers.set("Accept", "application/json"); if (init.body && !(init.body instanceof FormData)) headers.set("Content-Type", "application/json"); if (!["GET", "HEAD", "OPTIONS"].includes(method)) headers.set("X-CSRF-TOKEN", await getCsrfToken()); const response = await fetch(`${apiOrigin}${path}`, { ...init, headers, credentials: "include" }); if (response.status === 401) { csrfToken = null; getCache.clear(); if (!path.endsWith("/login")) window.location.assign("/admin/login"); } if (!response.ok) { let problem: ApiProblem = { title: `خطای ${response.status}` }; try { problem = await response.json() as ApiProblem; } catch { /* non-json response */ } throw new ApiError(response.status, problem); } if (path.endsWith("/auth/login")) { csrfToken = null; getCache.clear(); } if (response.status === 204) return undefined as T; return response.json() as Promise; }