version 1
Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s

This commit is contained in:
Ivan Rezchikov
2026-09-18 00:45:51 +03:00
commit 628dd6384b
149 changed files with 11478 additions and 0 deletions
+223
View File
@@ -0,0 +1,223 @@
import type {
CollectionResult,
CollocationsResult,
DictionaryResult,
ExamplesResult,
Language,
TranslationResult,
UsageResult,
} from "@/types/api";
export type ApiErrorKind = "network" | "auth" | "quota" | "not-found" | "server";
export interface ApiError {
kind: ApiErrorKind;
}
export type ErrorWithKind = Error & ApiError;
export interface RawCollection {
id: string;
name: string;
lang: Language;
user_id: string;
words: string[];
type: "auto" | "user";
created_at: string;
updated_at: string;
}
export function apiError(kind: ApiErrorKind): ErrorWithKind {
const err = new Error(kind) as ErrorWithKind;
err.kind = kind;
return err;
}
export function isApiError(err: unknown): err is ErrorWithKind {
return (
err instanceof Error &&
"kind" in err &&
typeof (err as ErrorWithKind).kind === "string"
);
}
export function normalizeCollection(raw: RawCollection): CollectionResult {
return {
id: raw.id,
name: raw.name,
lang: raw.lang,
userId: raw.user_id,
words: raw.words,
type: raw.type,
created_at: raw.created_at,
updated_at: raw.updated_at,
};
}
export async function parseBody<T>(response: Response): Promise<T> {
const text = await response.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
}
export function errorKind(status: number): ApiErrorKind {
if (status === 401) return "auth";
if (status === 429) return "quota";
if (status === 404) return "not-found";
return "server";
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response;
try {
response = await fetch(path, init);
} catch (err) {
if (err instanceof Error && err.name === "AbortError") throw err;
throw apiError("network");
}
if (!response.ok) throw apiError(errorKind(response.status));
return parseBody<T>(response);
}
const jsonHeaders = { "Content-Type": "application/json" };
export function translateText(
{ text, from, to }: { text: string; from: Language; to: Language },
signal?: AbortSignal
): Promise<TranslationResult> {
return request<TranslationResult>("/api/translate", {
method: "POST",
headers: jsonHeaders,
body: JSON.stringify({ text, from, to }),
signal,
});
}
export function lookupDictionary(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<DictionaryResult> {
return request<DictionaryResult>(
`/api/dictionary/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
}
export function getCollocations(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<CollocationsResult> {
return request<CollocationsResult>(
`/api/collocations/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
}
export function getExamples(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<ExamplesResult> {
return request<ExamplesResult>(
`/api/examples/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
}
export async function getCollections(
signal?: AbortSignal
): Promise<CollectionResult[]> {
try {
const raw = await request<RawCollection[]>("/api/collections", { signal });
return raw.map(normalizeCollection);
} catch (err) {
if (isApiError(err) && err.kind === "not-found") return [];
throw err;
}
}
export async function createCollection(
name: string,
lang: Language,
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>("/api/collections", {
signal,
method: "POST",
headers: jsonHeaders,
body: JSON.stringify({ name, lang }),
});
return normalizeCollection(raw);
}
export async function getCollectionsByWord(
lang: Language,
word: string,
signal?: AbortSignal
): Promise<CollectionResult[]> {
try {
const raw = await request<RawCollection[]>(
`/api/collections/search/${lang}/${encodeURIComponent(word)}`,
{ signal }
);
return raw.map(normalizeCollection);
} catch (err) {
if (isApiError(err) && err.kind === "not-found") return [];
throw err;
}
}
export function deleteCollection(id: string, signal?: AbortSignal) {
return request<void>(`/api/collections/${id}`, {
signal,
method: "DELETE",
});
}
export async function updateCollection(
id: string,
name: string,
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>(`/api/collections/${id}`, {
signal,
method: "PATCH",
headers: jsonHeaders,
body: JSON.stringify({ name }),
});
return normalizeCollection(raw);
}
export async function addWordsToCollection(
id: string,
words: string[],
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>(`/api/collections/${id}/words`, {
signal,
method: "POST",
headers: jsonHeaders,
body: JSON.stringify({ words }),
});
return normalizeCollection(raw);
}
export async function deleteWordFromCollection(
id: string,
word: string,
signal?: AbortSignal
): Promise<CollectionResult> {
const raw = await request<RawCollection>(
`/api/collections/${id}/words?word=${encodeURIComponent(word)}`,
{ signal, method: "DELETE" }
);
return normalizeCollection(raw);
}
export function getUsage(signal?: AbortSignal): Promise<UsageResult> {
return request<UsageResult>("/api/usage", { signal });
}
+20
View File
@@ -0,0 +1,20 @@
import { cookies } from "next/headers";
const BACKEND_URL = process.env.BACKEND_URL!;
interface BackendInit extends RequestInit {
next?: { revalidate?: number | false; tags?: string[] };
}
export async function backendFetch(
path: string,
init: BackendInit = {}
): Promise<Response> {
const { next, ...restInit } = init;
const headers = new Headers(restInit.headers);
const token = (await cookies()).get("session")?.value;
if (token) headers.set("Authorization", `Bearer ${token}`);
return fetch(`${BACKEND_URL}${path}`, { ...restInit, headers, next });
}
+66
View File
@@ -0,0 +1,66 @@
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const MONTH = 30 * DAY;
export type RelativeTimeKey =
| "now"
| "minutes"
| "hours"
| "yesterday"
| "days"
| "month"
| "months"
| "year"
| "moreThanYear";
export type RelativeTimeTranslator = (
key: RelativeTimeKey,
values?: { count?: number }
) => string;
/**
* Formats an ISO date as a localized relative time using the following
* thresholds:
*
* - < 1 minute -> "Now"
* - < 1 hour -> "X minutes ago"
* - < 24 hours -> "X hours ago"
* - 1 day -> "Yesterday"
* - < 30 days -> "X days ago"
* - 1 month -> "A month ago"
* - < 12 months -> "X months ago"
* - 12-23 months -> "A year ago"
* - >= 24 months -> "More than a year ago"
*/
export function formatDate(
dateString: string,
t: RelativeTimeTranslator,
now: Date = new Date()
): string {
const date = new Date(dateString);
if (Number.isNaN(date.getTime())) return dateString;
const diffMs = now.getTime() - date.getTime();
// Future dates (or the very same moment) are shown as "now".
if (diffMs < MINUTE) return t("now");
const minutes = Math.floor(diffMs / MINUTE);
if (minutes < 60) return t("minutes", { count: minutes });
const hours = Math.floor(diffMs / HOUR);
if (hours < 24) return t("hours", { count: hours });
const days = Math.floor(diffMs / DAY);
if (days === 1) return t("yesterday");
if (days < 30) return t("days", { count: days });
const months = Math.floor(diffMs / MONTH);
if (months === 1) return t("month");
if (months < 12) return t("months", { count: months });
const years = Math.floor(months / 12);
if (years === 1) return t("year");
return t("moreThanYear");
}
+10
View File
@@ -0,0 +1,10 @@
import type { UiLanguage } from "@/types/language";
export const LANGUAGES: readonly UiLanguage[] = [
{ id: "en", autonym: "English", flag: "/uk.svg" },
{ id: "it", autonym: "Italiano", flag: "/it.svg" },
{ id: "ru", autonym: "Русский", flag: "/ru.svg" },
];
export const DEFAULT_SOURCE_LANG = LANGUAGES[0];
export const DEFAULT_TARGET_LANG = LANGUAGES[1];
+13
View File
@@ -0,0 +1,13 @@
import { randomBytes, createHash } from "crypto";
export function generateCodeVerifier(): string {
return randomBytes(32).toString("base64url");
}
export function generateCodeChallenge(verifier: string): string {
return createHash("sha256").update(verifier).digest("base64url");
}
export function generateState(): string {
return randomBytes(16).toString("base64url");
}
+47
View File
@@ -0,0 +1,47 @@
import { backendFetch } from "./backend";
import {
apiError,
errorKind,
isApiError,
normalizeCollection,
parseBody,
type RawCollection,
} from "./api";
import type { CollectionResult, DictionaryResult, Language } from "@/types/api";
async function serverRequest<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response;
try {
response = await backendFetch(path, init);
} catch {
throw apiError("network");
}
if (!response.ok) throw apiError(errorKind(response.status));
return parseBody<T>(response);
}
export async function getCollections(): Promise<CollectionResult[]> {
try {
const raw = await serverRequest<RawCollection[]>("/api/collections");
return raw.map(normalizeCollection);
} catch (err) {
if (isApiError(err) && err.kind === "not-found") return [];
throw err;
}
}
export async function getCollection(id: string): Promise<CollectionResult> {
const raw = await serverRequest<RawCollection>(`/api/collections/${encodeURIComponent(id)}`);
return normalizeCollection(raw);
}
export function lookupDictionary(
lang: Language,
word: string
): Promise<DictionaryResult> {
return serverRequest<DictionaryResult>(
`/api/dictionary/${lang}/${encodeURIComponent(word)}`
);
}
+12
View File
@@ -0,0 +1,12 @@
import type { User } from "@/types/api";
import { backendFetch } from "./backend";
export async function getUser(): Promise<User | null> {
try {
const response = await backendFetch(`/api/auth/me`);
if (!response.ok) return null;
return (await response.json()) as User;
} catch {
return null;
}
}
+19
View File
@@ -0,0 +1,19 @@
"use client";
import { useTranslations } from "next-intl";
import { isApiError, type ApiErrorKind } from "@/lib/api";
export function useApiErrorMessage(kind?: ApiErrorKind | null): string | null {
const t = useTranslations("ApiErrors");
if (!kind) return null;
return t(kind);
}
export function resolveApiErrorMessage(
err: unknown,
t: (key: ApiErrorKind) => string,
fallback: string
): string {
if (isApiError(err)) return t(err.kind);
return fallback;
}
+17
View File
@@ -0,0 +1,17 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatTimestamp(iso?: string, locale?: string) {
if (!iso) return null
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return null
return date.toLocaleString(locale, { dateStyle: "medium", timeStyle: "short" })
}
export function formatNumber(value: number, locale?: string) {
return value.toLocaleString(locale)
}