import type { ApiProblem } from "../types"; import { API_ORIGIN } from "../../lib/runtime-config"; import { AUTH_CLEARED_EVENT, AUTH_INVALIDATED_EVENT, safeApiMessage } from "../../lib/api"; export const apiOrigin = API_ORIGIN; let csrfToken: string | null = null; const getCache = new Map }>(); const getCacheTtlMs = 30_000; if (typeof window !== "undefined") { for (const event of [AUTH_CLEARED_EVENT, AUTH_INVALIDATED_EVENT]) window.addEventListener(event, () => { csrfToken = null; getCache.clear(); }); } export class ApiError extends Error { constructor(public status: number, public problem: ApiProblem) { super(adminApiMessage(status, problem)); } } const fieldLabels: Record = { projectNumber: "شماره پروژه", title: "عنوان", startDate: "تاریخ شروع", endDate: "تاریخ پایان", rating: "امتیاز", strategicThemeId: "مضمون راهبردی", innovationValueId: "ارزش فناوری و نوآوری", fiscalYear: "سال مالی", quarters: "اطلاعات فصل‌ها", projectId: "پروژه مرتبط", ideaId: "ایده مرتبط", fullName: "نام کامل", collaborationStartDate: "تاریخ شروع همکاری", innovatorFullName: "نام ایده‌پرداز", ideaStatus: "وضعیت ایده", incomeAfter: "درآمد بعد", articles: "مقاله‌ها", patents: "اختراع‌ها", article: "مقاله", patent: "اختراع", directLink: "لینک مستقیم", reportType: "نوع گزارش", language: "زبان", bookType: "نوع کتاب", activityType: "نوع فعالیت", eventType: "نوع رویداد", role: "نقش", participationType: "نوع مشارکت", presenceType: "نوع حضور", pageCount: "تعداد صفحات", personnelNumber: "شماره پرسنلی", ideaOriginality: "اصالت ایده", file: "فایل", rowVersion: "نسخه رکورد", userName: "نام کاربری", displayName: "نام نمایشی", password: "رمز عبور", newPassword: "رمز عبور جدید", approvedBudget: "بودجه مصوب", budgetSpent: "بودجه مصرف‌شده", innovationDetails: "جزئیات نوآوری", greenDetails: "جزئیات نوآوری سبز", technologyParameters: "پارامترهای فناوری", exports: "اطلاعات صادرات", counts: "تعدادها", amounts: "مبالغ", }; export function adminFieldErrors(problem: ApiProblem): Record { if (Array.isArray(problem.errors)) return Object.fromEntries(problem.errors.map(x => [x.fieldCode, x.message])); if (problem.errors && typeof problem.errors === "object") return Object.fromEntries(Object.entries(problem.errors).map(([key, values]) => [key, values[0] ?? "مقدار معتبر نیست."])); return {}; } function adminApiMessage(status: number, problem: ApiProblem): string { const safe = safeApiMessage(status, problem.code, problem.traceId); if (status >= 500 || status === 401 || status === 403 || problem.code === "invalid_csrf") return safe; const errors = adminFieldErrors(problem); const first = Object.entries(errors)[0]; if (first) { const [field, detail] = first; const label = fieldLabels[field] ?? fieldLabels[field.split(".").at(-1) ?? ""]; return label ? `${label}: ${detail}` : detail; } return status === 422 && typeof problem.title === "string" && problem.title.length <= 300 ? problem.title : safe; } 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.dispatchEvent(new Event(AUTH_INVALIDATED_EVENT)); if (window.location.pathname !== "/admin/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; }