/** * Typed HTTP client for the Gitea REST API. * * Responsibilities: * - Build URLs (base + path + query) without ever putting the token in a URL. * - Attach `Authorization: token ` from an injected secret provider. * - Normalize every failure into {@link ApiError} (status-based kinds, timeouts, * aborts, rate limits) so callers never string-match error messages. * - Support cancellation (AbortSignal) and per-request timeouts. * - Parse pagination metadata (`X-Total-Count` + page/limit heuristic). * * The client is intentionally transport-only: endpoint knowledge lives in * `endpoints.ts`, server-state caching in feature hooks. */ import { ApiError, toApiError } from './errors'; import { apiBaseUrl } from './instance-url'; export type QueryValue = | string | number | boolean | null | undefined | readonly (string | number)[]; export type QueryParams = Record; export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; export interface RequestOptions { method?: HttpMethod; query?: QueryParams; body?: unknown; signal?: AbortSignal; timeoutMs?: number; } export interface PageMetaRaw { total: number | null; } export interface RawResponse { data: T; status: number; total: number | null; /** True when the server indicated more pages (total unknown uses a length heuristic). */ hasMore: boolean; } export type FetchLike = (input: string, init?: RequestInit) => Promise; export interface GiteaClientOptions { /** Instance base URL (no `/api/v1` suffix). */ baseUrl: string; /** Personal access token. Omitted for unauthenticated probes (e.g. /version). */ token?: string; timeoutMs?: number; fetchImpl?: FetchLike; } export function buildQuery(params: QueryParams): string { const search = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (value === undefined || value === null) continue; if (Array.isArray(value)) { if (value.length > 0) search.append(key, value.join(',')); continue; } search.append(key, String(value)); } const qs = search.toString(); return qs ? `?${qs}` : ''; } export class GiteaClient { readonly baseUrl: string; readonly apiRoot: string; private readonly token: string | undefined; private readonly timeoutMs: number; private readonly fetchImpl: FetchLike; constructor(options: GiteaClientOptions) { this.baseUrl = options.baseUrl; this.apiRoot = apiBaseUrl(options.baseUrl); this.token = options.token; this.timeoutMs = options.timeoutMs ?? 15_000; this.fetchImpl = options.fetchImpl ?? (fetch as FetchLike); } /** True when this client carries credentials. */ get isAuthenticated(): boolean { return typeof this.token === 'string' && this.token.length > 0; } async get(path: string, options: Omit = {}): Promise { const raw = await this.raw(path, { ...options, method: 'GET' }); return raw.data; } async post(path: string, body?: unknown, options: RequestOptions = {}): Promise { const raw = await this.raw(path, { ...options, method: 'POST', body }); return raw.data; } async put(path: string, body?: unknown, options: RequestOptions = {}): Promise { const raw = await this.raw(path, { ...options, method: 'PUT', body }); return raw.data; } async patch(path: string, body?: unknown, options: RequestOptions = {}): Promise { const raw = await this.raw(path, { ...options, method: 'PATCH', body }); return raw.data; } async delete(path: string, options: RequestOptions = {}): Promise { const raw = await this.raw(path, { ...options, method: 'DELETE' }); return raw.data; } /** * Fetches a plain-text response (e.g. a pull request `.diff`). * * Shares the timeout/abort/error-normalization contract of {@link raw}, but * deliberately does not parse JSON. A non-2xx response is still mapped to an * {@link ApiError} that never contains the URL or the token. */ async getText(path: string, options: Omit = {}): Promise { const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`; const headers: Record = { Accept: 'text/plain' }; if (this.token) headers.Authorization = `token ${this.token}`; const controller = new AbortController(); let timedOut = false; const timeoutMs = options.timeoutMs ?? this.timeoutMs; const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs); const onCallerAbort = () => controller.abort(); if (options.signal) { if (options.signal.aborted) { clearTimeout(timer); throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); } options.signal.addEventListener('abort', onCallerAbort); } let response: Response; try { response = await this.fetchImpl(url, { method: 'GET', headers, signal: controller.signal }); } catch (error) { if (timedOut) { throw new ApiError({ kind: 'timeout', status: 0, message: 'The server took too long to respond.', }); } if (options.signal?.aborted) { throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); } throw toApiError(error); } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', onCallerAbort); } const text = await response.text(); if (!response.ok) { const kind = ApiError.kindForStatus(response.status); throw new ApiError({ kind, status: response.status, message: messageForStatus(kind, response.status, null), }); } return text; } /** * Uploads a multipart/form-data body (e.g. a release asset) and parses the * JSON response. The multipart boundary is set by the platform, so we never * set `Content-Type` ourselves. Errors are normalized like {@link raw}. */ async postForm( path: string, form: FormData, options: Omit = {}, ): Promise { const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`; const headers: Record = { Accept: 'application/json' }; if (this.token) headers.Authorization = `token ${this.token}`; const controller = new AbortController(); let timedOut = false; const timeoutMs = options.timeoutMs ?? this.timeoutMs ?? 120_000; const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs); const onCallerAbort = () => controller.abort(); if (options.signal) { if (options.signal.aborted) { clearTimeout(timer); throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); } options.signal.addEventListener('abort', onCallerAbort); } let response: Response; try { response = await this.fetchImpl(url, { method: 'POST', headers, body: form as unknown as BodyInit, signal: controller.signal, }); } catch (error) { if (timedOut) { throw new ApiError({ kind: 'timeout', status: 0, message: 'The upload took too long.' }); } if (options.signal?.aborted) { throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); } throw toApiError(error); } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', onCallerAbort); } const text = await response.text(); let parsed: unknown = undefined; if (text.length > 0) { try { parsed = JSON.parse(text); } catch { parsed = undefined; } } if (!response.ok) { const serverMessage = parsed && typeof parsed === 'object' && 'message' in parsed ? String((parsed as { message: unknown }).message) : null; const kind = ApiError.kindForStatus(response.status); throw new ApiError({ kind, status: response.status, serverMessage, message: messageForStatus(kind, response.status, serverMessage), }); } return parsed as T; } /** * Performs a request and returns data plus pagination metadata. * `hasMore` uses `X-Total-Count` when present, otherwise a length heuristic * against the requested page size (Gitea does not consistently emit totals). */ async raw(path: string, options: RequestOptions = {}): Promise> { const method = options.method ?? 'GET'; const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`; const headers: Record = { Accept: 'application/json' }; if (this.token) headers.Authorization = `token ${this.token}`; let body: string | undefined; if (options.body !== undefined) { headers['Content-Type'] = 'application/json'; body = JSON.stringify(options.body); } const controller = new AbortController(); let timedOut = false; const timeoutMs = options.timeoutMs ?? this.timeoutMs; const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs); const onCallerAbort = () => controller.abort(); if (options.signal) { if (options.signal.aborted) { clearTimeout(timer); throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); } options.signal.addEventListener('abort', onCallerAbort); } let response: Response; try { response = await this.fetchImpl(url, { method, headers, body, signal: controller.signal, }); } catch (error) { if (timedOut) { throw new ApiError({ kind: 'timeout', status: 0, message: 'The server took too long to respond.', }); } if (options.signal?.aborted) { throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); } // Transport-level failure (DNS, TLS, offline). toApiError never echoes the URL/token. throw toApiError(error); } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', onCallerAbort); } const totalRaw = response.headers.get('X-Total-Count'); const total = totalRaw !== null && totalRaw !== '' && !Number.isNaN(Number(totalRaw)) ? Number(totalRaw) : null; const text = await response.text(); let parsed: unknown = undefined; if (text.length > 0) { try { parsed = JSON.parse(text); } catch { if (response.ok) { throw new ApiError({ kind: 'invalid-response', status: response.status, message: 'The server returned a response the app could not read.', }); } } } if (!response.ok) { const serverMessage = parsed && typeof parsed === 'object' && 'message' in parsed ? String((parsed as { message: unknown }).message) : text.length > 0 && text.length < 300 ? text : null; const retryAfterHeader = response.headers.get('Retry-After'); const retryAfterSeconds = response.status === 429 && retryAfterHeader && !Number.isNaN(Number(retryAfterHeader)) ? Number(retryAfterHeader) : null; const kind = ApiError.kindForStatus(response.status); throw new ApiError({ kind, status: response.status, serverMessage, retryAfterSeconds, message: messageForStatus(kind, response.status, serverMessage), }); } const requestedLimit = typeof options.query?.limit === 'number' ? options.query.limit : null; const requestedPage = typeof options.query?.page === 'number' ? options.query.page : 1; const items = Array.isArray(parsed) ? (parsed as unknown[]).length : null; const hasMore = requestedLimit === null ? false : total !== null ? requestedPage * requestedLimit < total : items !== null && items >= requestedLimit; return { data: parsed as T, status: response.status, total, hasMore }; } } function messageForStatus(kind: ApiError['kind'], status: number, serverMessage: string | null): string { if (serverMessage) return serverMessage; switch (kind) { case 'unauthorized': return 'This Personal Access Token is no longer valid. It may have expired or been revoked.'; case 'forbidden': return 'You do not have permission to perform this action.'; case 'not-found': return 'Not found on this instance.'; case 'rate-limit': return 'The instance is rate limiting requests. Try again in a moment.'; case 'server': return `The instance returned an error (HTTP ${status}).`; default: return `Request failed (HTTP ${status}).`; } }