forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB078b459Burak Boduroğlu2 months ago671 commits

client.ts591 lines, 22.7 KiBHistoryRawDownload
1import type { Locale } from "@/i18n/messages";
2
3export class ApiError extends Error {
4 readonly status: number;
5 readonly retryAfter: number | null;
6 /** Set when the school has this route's module switched off (`403 {error, module}`). */
7 readonly module: string | null;
8
9 constructor(status: number, message: string, retryAfter: number | null = null, module: string | null = null) {
10 super(message);
11 this.name = "ApiError";
12 this.status = status;
13 this.retryAfter = retryAfter;
14 this.module = module;
15 }
16}
17
18/** True for a refusal because the school's module is off, not a role or record problem. */
19export function isModuleDisabledError(err: unknown): err is ApiError & { module: string } {
20 return err instanceof ApiError && err.status === 403 && err.module != null;
21}
22
23// A builder can switch a module off mid-session; the backend then answers
24// `403 {error, module}` on every route of it. Listeners (the modules context)
25// hear about it on the first such refusal and refetch the enabled set, so the
26// nav and route gate catch up without a reload.
27const moduleDisabledListeners = new Set<(module: string) => void>();
28
29export function onModuleDisabled(listener: (module: string) => void): () => void {
30 moduleDisabledListeners.add(listener);
31 return () => moduleDisabledListeners.delete(listener);
32}
33
34function disabledModuleOf(status: number, data: unknown): string | null {
35 if (status !== 403 || !data || typeof data !== "object") return null;
36 const module = (data as { module?: unknown }).module;
37 if (typeof module !== "string" || !module) return null;
38 for (const listener of moduleDisabledListeners) listener(module);
39 return module;
40}
41
42type RequestOptions = {
43 method?: "GET" | "POST" | "PATCH" | "DELETE";
44 body?: unknown;
45 signal?: AbortSignal;
46 cache?: RequestCache;
47};
48
49const API_PREFIX = "/api";
50
51// Deadline for a JSON request. Generous enough for the slowest real call
52// (login's Argon2 hash under load), short enough that a hung socket surfaces
53// as an error instead of a permanently disabled button.
54const REQUEST_TIMEOUT_MS = 20_000;
55
56const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = {
57 // Settings lists reject two entries that fold to the same word — İZİN/izin,
58 // ÖDEV/odev. Keyed on the whole normalized string, so both fields are listed.
59 "exam_kinds: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": {
60 en: "Two exam kinds are the same word apart from upper/lower case or Turkish letters. Keep only one of them.",
61 tr: "İki sınav türü, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.",
62 },
63 "attendance_statuses: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": {
64 en: "Two attendance statuses are the same word apart from upper/lower case or Turkish letters. Keep only one of them.",
65 tr: "İki yoklama durumu, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.",
66 },
67 "request failed": {
68 en: "Request failed.",
69 tr: "İşlem tamamlanamadı.",
70 },
71 "unauthorized": {
72 en: "Sign in to continue.",
73 tr: "Devam etmek için giriş yap.",
74 },
75 "forbidden": {
76 en: "You do not have permission for this action.",
77 tr: "Bu işlem için yetkin yok.",
78 },
79 "not found": {
80 en: "The requested record was not found.",
81 tr: "İstenen kayıt bulunamadı.",
82 },
83 "invalid credentials": {
84 en: "Username or password is incorrect.",
85 tr: "Kullanıcı adı veya şifre hatalı.",
86 },
87 "username already exists": {
88 en: "This username is already in use.",
89 tr: "Bu kullanıcı adı zaten kullanılıyor.",
90 },
91 "file too large": {
92 en: "This file is larger than the allowed upload limit.",
93 tr: "Bu dosya izin verilen yükleme sınırından büyük.",
94 },
95 "payload too large": {
96 en: "This upload is too large. Choose a smaller file and try again.",
97 tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.",
98 },
99 "request entity too large": {
100 en: "This upload is too large. Choose a smaller file and try again.",
101 tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.",
102 },
103 "unsupported file type": {
104 en: "This file type is not supported.",
105 tr: "Bu dosya türü desteklenmiyor.",
106 },
107 "unsupported image type": {
108 en: "This image type is not supported. Use PNG, JPEG, WebP, or GIF.",
109 tr: "Bu görsel türü desteklenmiyor. PNG, JPEG, WebP veya GIF kullan.",
110 },
111 "invalid image": {
112 en: "The image could not be read. Choose another image and try again.",
113 tr: "Görsel okunamadı. Başka bir görsel seçip tekrar dene.",
114 },
115 "too many files": {
116 en: "This note already has the maximum number of files.",
117 tr: "Bu notta en fazla dosya sayısına ulaşılmış.",
118 },
119 "note file limit reached": {
120 en: "This note already has the maximum number of files.",
121 tr: "Bu notta en fazla dosya sayısına ulaşılmış.",
122 },
123 "this time overlaps a slot you have already published": {
124 en: "This time overlaps a slot you already published.",
125 tr: "Bu zaman aralığı, daha önce yayınladığın bir müsaitlikle çakışıyor.",
126 },
127 "a repeated slot overlaps one you have already published": {
128 en: "One of the repeated slots overlaps a slot you already published.",
129 tr: "Tekrarlanan müsaitliklerden biri, daha önce yayınladığın bir müsaitlikle çakışıyor.",
130 },
131 "the repeated slots overlap each other": {
132 en: "The repeated slots overlap each other.",
133 tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.",
134 },
135 // Builder surface (web/builder.rs, tenant.rs) — byte-exact.
136 "school slug already taken": {
137 en: "That school code is already taken.",
138 tr: "Bu okul kodu zaten kullanılıyor.",
139 },
140 "that account is not an admin of this school": {
141 en: "That account exists but is not an admin of this school.",
142 tr: "Bu hesap var ama bu okulun yöneticisi değil.",
143 },
144 "school is suspended": {
145 en: "This school is suspended.",
146 tr: "Bu okul askıya alınmış.",
147 },
148 // Booking/decision conflicts from domain/appointment.rs — byte-exact.
149 "the slot is already booked": {
150 en: "Someone else booked this time first.",
151 tr: "Bu saati senden önce başkası aldı.",
152 },
153 "the slot has already started": {
154 en: "This time has already started, so it can no longer be booked.",
155 tr: "Bu saat başladığı için artık randevu alınamaz.",
156 },
157 "you already have an appointment at that time": {
158 en: "You already have an appointment at that time.",
159 tr: "O saatte zaten bir randevun var.",
160 },
161 "the appointment is already settled": {
162 en: "This appointment is already settled.",
163 tr: "Bu randevu zaten sonuçlanmış.",
164 },
165 "the appointment has already started": {
166 en: "This appointment has already started.",
167 tr: "Bu randevu çoktan başladı.",
168 },
169 "that time has already started": {
170 en: "That time has already started. Pick a later one.",
171 tr: "O saat çoktan başladı. Daha ileri bir saat seç.",
172 },
173 "no time has been proposed": {
174 en: "No time has been proposed for this appointment yet.",
175 tr: "Bu randevu için henüz bir saat önerilmedi.",
176 },
177 "the appointment is no longer pending": {
178 en: "This appointment is no longer waiting for an answer.",
179 tr: "Bu randevu artık yanıt bekliyor değil.",
180 },
181 "question: this question did not come from a bank template": {
182 en: "This question was not copied from a bank template, so there is nothing to refresh it from.",
183 tr: "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.",
184 },
185 "request timed out": {
186 en: "The server did not respond in time. Check your connection and try again.",
187 tr: "Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.",
188 },
189 "only the template's owner or an admin can change it": {
190 en: "Only the teacher who created this template (or an admin) can change it.",
191 tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.",
192 },
193 "only the course creator, an assigned teacher, or a manager/admin can author questions": {
194 en: "Only this course's teachers or a manager can add questions to this exam.",
195 tr: "Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.",
196 },
197 "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank": {
198 en: "Only this course's teachers or a manager can save this question to the bank.",
199 tr: "Bu soruyu bankaya yalnızca dersin öğretmenleri veya bir müdür kaydedebilir.",
200 },
201 "cannot change questions after attempts have started": {
202 en: "Students have already started this exam, so its questions can no longer change.",
203 tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.",
204 },
205 "bank questions still reference this subject — re-tag or delete them first": {
206 en: "Question bank templates still use this subject. Re-tag or delete them first.",
207 tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.",
208 },
209 "the term is archived — past years are read-only": {
210 en: "This term is archived. Past years are read-only.",
211 tr: "Bu dönem arşivli. Geçmiş dönemler salt okunur.",
212 },
213 "this course's term is archived — past years are read-only": {
214 en: "This course's term is archived. Past years are read-only.",
215 tr: "Bu dersin dönemi arşivli. Geçmiş dönemler salt okunur.",
216 },
217 "module disabled": {
218 en: "This feature is not enabled for your school.",
219 tr: "Bu özellik okulunuz için etkin değil.",
220 },
221 "course not found": {
222 en: "Course not found.",
223 tr: "Ders bulunamadı.",
224 },
225 "exam not found": {
226 en: "Exam not found.",
227 tr: "Sınav bulunamadı.",
228 },
229 "not enrolled in this exam's course": {
230 en: "You are not enrolled in this exam's course.",
231 tr: "Bu sınavın dersine kayıtlı değilsin.",
232 },
233 "you are not enrolled in this exam's course": {
234 en: "You are not enrolled in this exam's course.",
235 tr: "Bu sınavın dersine kayıtlı değilsin.",
236 },
237 "exam is not scheduled": {
238 en: "This exam is not scheduled for online sitting.",
239 tr: "Bu sınav çevrim içi oturum için zamanlanmamış.",
240 },
241 "attempt not found": {
242 en: "Start the exam before opening the exam room.",
243 tr: "Sınav odasını açmadan önce sınavı başlat.",
244 },
245 "attempt is closed": {
246 en: "This attempt is closed. Answers are read-only.",
247 tr: "Bu oturum kapalı. Cevaplar salt okunur.",
248 },
249 "exam has not started": {
250 en: "This exam has not started yet.",
251 tr: "Bu sınav henüz başlamadı.",
252 },
253 "exam has ended": {
254 en: "This exam has ended.",
255 tr: "Bu sınav sona erdi.",
256 },
257 "no attempts left": {
258 en: "No attempts left for this exam.",
259 tr: "Bu sınav için deneme hakkı kalmadı.",
260 },
261 "answer is required": {
262 en: "Enter an answer before saving.",
263 tr: "Kaydetmeden önce cevap gir.",
264 },
265 "only students can sit exams": {
266 en: "Only students can take exams.",
267 tr: "Sınava yalnızca öğrenciler girebilir.",
268 },
269 "user_id: only students can be enrolled in a course": {
270 en: "Only students can be enrolled in a course.",
271 tr: "Derse yalnızca öğrenciler kaydedilebilir.",
272 },
273 "user_id: only students can be graded": {
274 en: "Only students can be graded.",
275 tr: "Yalnızca öğrencilere not verilebilir.",
276 },
277 "user_id: only students can be marked present in a lesson": {
278 en: "Only students can be marked on a lesson roll call.",
279 tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.",
280 },
281 "event is full": {
282 en: "This event is full.",
283 tr: "Bu etkinlik dolu.",
284 },
285 "registration is closed": {
286 en: "Registration is closed for this event.",
287 tr: "Bu etkinlik için kayıt kapalı.",
288 },
289 "already registered": {
290 en: "This student is already registered.",
291 tr: "Bu öğrenci zaten kayıtlı.",
292 },
293 "already enrolled": {
294 en: "This student is already enrolled.",
295 tr: "Bu öğrenci zaten kayıtlı.",
296 },
297 "active pomodoro session already exists": {
298 en: "You already have a focus session running.",
299 tr: "Zaten devam eden bir odak oturumun var.",
300 },
301 "no active pomodoro session": {
302 en: "There is no active focus session to finish.",
303 tr: "Bitirilecek aktif odak oturumu yok.",
304 },
305};
306
307const FIELD_LABELS: Record<string, Record<Locale, string>> = {
308 content: { en: "Content", tr: "İçerik" },
309 description: { en: "Description", tr: "Açıklama" },
310 password: { en: "Password", tr: "Şifre" },
311 title: { en: "Title", tr: "Başlık" },
312 username: { en: "Username", tr: "Kullanıcı adı" },
313};
314
315export function currentLocale(): Locale {
316 if (typeof window === "undefined") return "en";
317 try {
318 const saved = window.localStorage.getItem("hezarfen.locale");
319 if (saved === "en" || saved === "tr") return saved;
320 return window.navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en";
321 } catch {
322 return "en";
323 }
324}
325
326function normalizeApiMessage(message: string): string {
327 return message
328 .trim()
329 .replace(/[’‘]/g, "'")
330 .replace(/\s+/g, " ")
331 .replace(/[.!?]+$/, "")
332 .toLowerCase();
333}
334
335function sentenceCase(message: string): string {
336 const trimmed = message.trim();
337 if (!trimmed) return trimmed;
338 return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1);
339}
340
341function formatRuntimeErrorMessage(message: string, locale: Locale): string | null {
342 const normalized = normalizeApiMessage(message);
343 if (/^(failed to fetch|load failed|networkerror|network request failed)/.test(normalized)) {
344 return locale === "tr"
345 ? "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene."
346 : "Could not reach the server. Check your connection and try again.";
347 }
348 if (
349 /^(typeerror:\s*)?cannot (read|set) propert(y|ies) of (null|undefined)/.test(normalized) ||
350 /^use\w+ must be used within \w+provider/.test(normalized)
351 ) {
352 return locale === "tr"
353 ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene."
354 : "Something went wrong while loading the page. Reload the page and try again.";
355 }
356 return null;
357}
358
359function formatNumber(value: string, locale: Locale): string {
360 return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value));
361}
362
363function fieldLabel(field: string, locale: Locale): string {
364 const normalized = field.trim().toLowerCase().replace(/[_.-]+/g, " ");
365 const known = FIELD_LABELS[normalized]?.[locale];
366 if (known) return known;
367 return sentenceCase(normalized);
368}
369
370function formatValidationMessage(message: string, locale: Locale): string | null {
371 const lengthMatch = message.match(/^([\w .-]+) must be at most (\d+) characters \(got (\d+)\)$/i);
372 if (!lengthMatch) return null;
373
374 const label = fieldLabel(lengthMatch[1], locale);
375 const max = formatNumber(lengthMatch[2], locale);
376 const got = formatNumber(lengthMatch[3], locale);
377
378 if (locale === "tr") return `${label} en fazla ${max} karakter olmalı. Şu an ${got} karakter.`;
379 return `${label} must be at most ${max} characters. Currently ${got} characters.`;
380}
381
382function errorMessageFromPayload(data: unknown, fallback: string): string {
383 if (!data || typeof data !== "object") return fallback;
384 const record = data as Record<string, unknown>;
385 if (typeof record.error === "string") return record.error;
386 if (typeof record.message === "string") return record.message;
387 const detail = record.detail;
388 if (typeof detail === "string") return detail;
389 if (Array.isArray(detail)) {
390 return detail
391 .map((item) => {
392 if (!item || typeof item !== "object") return "";
393 const row = item as Record<string, unknown>;
394 const loc = Array.isArray(row.loc) ? row.loc.map(String).join(".") : "";
395 const msg = typeof row.msg === "string" ? row.msg : "";
396 return loc && msg ? `${loc}: ${msg}` : msg;
397 })
398 .filter(Boolean)
399 .join("; ") || fallback;
400 }
401 return fallback;
402}
403
404const pendingGets = new Map<string, Promise<unknown>>();
405
406async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
407 const headers: Record<string, string> = {};
408 let body: string | undefined;
409
410 if (options.body !== undefined) {
411 headers["Content-Type"] = "application/json";
412 body = JSON.stringify(options.body);
413 }
414
415 // JSON calls only — uploads (formClient) and downloads (blobClient) stay
416 // untimed. Without this a dead connection leaves callers (exam-room REST
417 // autosave) stuck on "saving…" until the browser gives up.
418 const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
419 // Caller-initiated aborts keep their original AbortError so cancellation
420 // handling upstream is untouched; only our own deadline becomes an ApiError.
421 const asDeadlineError = (err: unknown) =>
422 timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err;
423
424 let res: Response;
425 try {
426 res = await fetch(`${API_PREFIX}${path}`, {
427 method: options.method ?? "GET",
428 headers,
429 body,
430 credentials: "same-origin",
431 signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,
432 cache: options.cache,
433 });
434 } catch (err) {
435 throw asDeadlineError(err);
436 }
437
438 if (res.status === 204) {
439 return undefined as T;
440 }
441
442 // The deadline aborts the body stream too, so headers can arrive in time and
443 // res.text() still blow up mid-download on a multi-MB response.
444 let text: string;
445 try {
446 text = await res.text();
447 } catch (err) {
448 throw asDeadlineError(err);
449 }
450
451 let data: unknown = null;
452 if (text) {
453 try {
454 data = JSON.parse(text);
455 } catch {
456 data = { error: text };
457 }
458 }
459
460 if (!res.ok) {
461 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
462
463 let retryAfter: number | null = null;
464 if (res.status === 429 || res.status === 503) {
465 const raw = res.headers.get("Retry-After");
466 if (raw) {
467 const n = Number(raw);
468 retryAfter = Number.isFinite(n) ? n : null;
469 }
470 }
471
472 throw new ApiError(res.status, message, retryAfter, disabledModuleOf(res.status, data));
473 }
474
475 return data as T;
476}
477
478/**
479 * Coalesce only overlapping, non-cancellable GETs. This is deliberately not a
480 * cache: once settled the entry disappears, so every later resource refetch
481 * still reaches the backend and mutation consistency stays unchanged.
482 */
483export function client<T>(path: string, options: RequestOptions = {}): Promise<T> {
484 const method = options.method ?? "GET";
485 if (method !== "GET" || options.body !== undefined || options.signal || options.cache === "no-store") {
486 return request<T>(path, options);
487 }
488 const key = `${path}\u0000${options.cache ?? "default"}`;
489 const pending = pendingGets.get(key);
490 if (pending) return pending as Promise<T>;
491 const next = request<T>(path, options).finally(() => pendingGets.delete(key));
492 pendingGets.set(key, next);
493 return next;
494}
495
496export async function formClient<T>(path: string, body: FormData, signal?: AbortSignal): Promise<T> {
497 const res = await fetch(`${API_PREFIX}${path}`, {
498 method: "POST",
499 body,
500 credentials: "same-origin",
501 signal,
502 });
503
504 const text = await res.text();
505 let data: unknown = null;
506 if (text) {
507 try {
508 data = JSON.parse(text);
509 } catch {
510 data = { error: text };
511 }
512 }
513
514 if (!res.ok) {
515 const message = errorMessageFromPayload(data, res.statusText || "Request failed");
516 throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data));
517 }
518
519 return data as T;
520}
521
522export async function blobClient(path: string, signal?: AbortSignal): Promise<Blob> {
523 const res = await fetch(`${API_PREFIX}${path}`, {
524 credentials: "same-origin",
525 signal,
526 });
527
528 if (!res.ok) {
529 const text = await res.text();
530 let message = res.statusText || "Request failed";
531 let payload: unknown = null;
532 if (text) {
533 try {
534 payload = JSON.parse(text);
535 message = errorMessageFromPayload(payload, message);
536 } catch {
537 message = text;
538 }
539 }
540 throw new ApiError(res.status, message, null, disabledModuleOf(res.status, payload));
541 }
542
543 return res.blob();
544}
545
546export function formatApiErrorMessage(message: string, locale: Locale = currentLocale()): string {
547 const normalized = normalizeApiMessage(message);
548 const known = API_ERROR_MESSAGES[normalized]?.[locale];
549 if (known) return known;
550 const runtime = formatRuntimeErrorMessage(message, locale);
551 if (runtime) return runtime;
552 const validation = formatValidationMessage(message, locale);
553 if (validation) return validation;
554 // Unmapped backend text is raw English/technical — never surface it to the
555 // user. Fall back to a clean localized line; add a mapping in
556 // API_ERROR_MESSAGES when a specific message deserves its own wording.
557 return locale === "tr"
558 ? "İşlem tamamlanamadı. Lütfen bilgileri kontrol edip tekrar dene."
559 : "Something went wrong. Please check your input and try again.";
560}
561
562export function formatApiError(err: unknown, locale: Locale = currentLocale()): string {
563 if (err instanceof ApiError) {
564 if ((err.status === 429 || err.status === 503) && err.retryAfter != null) {
565 return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`;
566 }
567 // The specific backend message wins over the per-status generic one —
568 // otherwise every 401/403/404/413/5xx entry in the table is dead code.
569 // Ahead of the message table: the backend's text for a switched-off
570 // module may be a generic "forbidden", which reads as a permissions fault.
571 if (err.module != null && err.status === 403) {
572 return locale === "tr" ? "Bu özellik okulunuzda şu an kapalı." : "This feature is currently switched off for your school.";
573 }
574 const known = API_ERROR_MESSAGES[normalizeApiMessage(err.message)]?.[locale];
575 if (known) return known;
576 if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale];
577 if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale];
578 if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale];
579 if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale];
580 if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again.";
581 return formatApiErrorMessage(err.message, locale);
582 }
583 if (err instanceof TypeError) {
584 return formatRuntimeErrorMessage(err.message, locale) ??
585 (locale === "tr"
586 ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene."
587 : "Something went wrong while loading the page. Reload the page and try again.");
588 }
589 if (err instanceof Error) return formatApiErrorMessage(err.message, locale);
590 return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong.";
591}