// Borrou Partner API: a minimal client for Node 20+ (built-in fetch). v0.1 DRAFT. // // - OAuth 2.0 client credentials, the access token cached until a minute before it expires. // - Every POST and DELETE carries an Idempotency-Key. One key per request: every retry of that // request sends the same key, and a new request gets a new one. // - Retries on no answer (a timeout or a dropped connection), 429 and 5xx, honouring Retry-After; // a 409 only when Borrou sends Retry-After with it (see the note on retryable()). // - Cursor pagination as an async iterator. import { randomUUID } from "node:crypto"; export interface BorrouClientOptions { /** https://api.borrou.capital for the sandbox. */ baseUrl: string; clientId: string; clientSecret: string; /** Attempts per request, the first included. */ maxAttempts?: number; /** The longest Retry-After the client waits for; a longer one is returned to the caller as an error. */ maxRetryAfterSeconds?: number; timeoutMs?: number; fetch?: typeof fetch; sleep?: (ms: number) => Promise; } export interface BorrouResponse { status: number; body: T; requestId: string | null; /** True when Borrou answered with the stored response of an earlier request with this key. */ replayed: boolean; } export class BorrouApiError extends Error { constructor( readonly status: number, /** Stable: branch on it (docs/api/ERRORS.md). The message is for people and may change. */ readonly code: string, message: string, /** Quote it to TFG when asking about a request. */ readonly requestId: string | null, readonly retryAfterSeconds: number | null, readonly body: unknown, ) { super(`${status} ${code}: ${message}`); this.name = "BorrouApiError"; } } type Query = Record; interface Page { data: T[]; has_more: boolean; /** A string for the lists; for the events feed, a position (a number). */ next_cursor: string | number | null; } const TOKEN_RENEWAL_MARGIN_MS = 60_000; export class BorrouClient { private readonly baseUrl: string; private readonly maxAttempts: number; private readonly maxRetryAfterSeconds: number; private readonly timeoutMs: number; private readonly fetchImpl: typeof fetch; private readonly sleep: (ms: number) => Promise; private token: { value: string; expiresAt: number } | null = null; private tokenInFlight: Promise | null = null; constructor(private readonly options: BorrouClientOptions) { this.baseUrl = options.baseUrl.replace(/\/+$/, ""); this.maxAttempts = options.maxAttempts ?? 5; this.maxRetryAfterSeconds = options.maxRetryAfterSeconds ?? 60; this.timeoutMs = options.timeoutMs ?? 30_000; this.fetchImpl = options.fetch ?? fetch; this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); } /** The cached access token, renewed a minute before it expires; one renewal at a time. */ async accessToken(): Promise { if (this.token && Date.now() < this.token.expiresAt - TOKEN_RENEWAL_MARGIN_MS) return this.token.value; this.tokenInFlight ??= this.requestToken().finally(() => { this.tokenInFlight = null; }); return this.tokenInFlight; } private async requestToken(): Promise { // RFC 6749 ยง2.3.1: the id and the secret form-encoded, then base64 in HTTP Basic. const basic = Buffer.from(`${encodeURIComponent(this.options.clientId)}:${encodeURIComponent(this.options.clientSecret)}`).toString("base64"); const { body } = await this.send<{ access_token: string; expires_in: number }>("POST", "/v1/oauth/token", { headers: { Authorization: `Basic ${basic}`, "Content-Type": "application/x-www-form-urlencoded" }, rawBody: "grant_type=client_credentials", }); this.token = { value: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 }; return this.token.value; } async get(path: string, query?: Query): Promise> { return this.request("GET", path, { query }); } /** An idempotent write. Pass `idempotencyKey` only to retry a request your own process lost track of. */ async post(path: string, body?: unknown, idempotencyKey?: string): Promise> { return this.request("POST", path, { body, idempotencyKey }); } async delete(path: string, idempotencyKey?: string): Promise> { return this.request("DELETE", path, { idempotencyKey }); } async request( method: "GET" | "POST" | "DELETE", path: string, options: { query?: Query; body?: unknown; idempotencyKey?: string } = {}, ): Promise> { // One key for every attempt of this request, never shared with another request. const idempotencyKey = method === "GET" ? undefined : (options.idempotencyKey ?? randomUUID()); let renewedToken = false; for (;;) { try { return await this.send(method, withQuery(path, options.query), { headers: { Authorization: `Bearer ${await this.accessToken()}`, ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}), ...(options.body !== undefined ? { "Content-Type": "application/json" } : {}), }, rawBody: options.body !== undefined ? JSON.stringify(options.body) : undefined, }); } catch (err) { // A token cut off by a credential rotation is refused before anything runs: renew it once. if (err instanceof BorrouApiError && err.status === 401 && err.code === "invalid_token" && !renewedToken) { this.token = null; renewedToken = true; continue; } throw err; } } } /** * Every item of a cursor-paginated list, page after page. Lists take `starting_after` (applications, * clients, loans); the events feed takes `after`, a position. */ async *paginate(path: string, query: Query = {}, cursorParam: "starting_after" | "after" = "starting_after"): AsyncGenerator { let cursor: string | number | null = null; do { const pageQuery: Query = cursor === null ? query : { ...query, [cursorParam]: cursor }; const { body } = await this.get>(path, pageQuery); yield* body.data; cursor = body.has_more ? body.next_cursor : null; } while (cursor !== null); } private async send(method: string, path: string, init: { headers: Record; rawBody?: string }): Promise> { for (let attempt = 1; ; attempt += 1) { let res: Response; try { res = await this.fetchImpl(`${this.baseUrl}${path}`, { method, headers: { Accept: "application/json", ...init.headers }, body: init.rawBody, signal: AbortSignal.timeout(this.timeoutMs), }); } catch (err) { // No answer: the write may or may not have happened, which is what the key is for. if (attempt >= this.maxAttempts) throw err; await this.sleep(backoffMs(attempt)); continue; } const body = (await res.json().catch(() => null)) as T & { error?: { code?: string; message?: string; request_id?: string } }; const requestId = res.headers.get("X-Request-Id"); if (res.ok) return { status: res.status, body, requestId, replayed: res.headers.get("Idempotent-Replayed") === "true" }; const retryAfter = retryAfterSeconds(res.headers.get("Retry-After")); const error = new BorrouApiError( res.status, body?.error?.code ?? "unknown", body?.error?.message ?? res.statusText, body?.error?.request_id ?? requestId, retryAfter, body, ); const waitTooLong = retryAfter !== null && retryAfter > this.maxRetryAfterSeconds; if (attempt >= this.maxAttempts || waitTooLong || !retryable(res.status, retryAfter)) throw error; await this.sleep(retryAfter !== null ? retryAfter * 1000 : backoffMs(attempt)); } } } /** * 429 and 5xx are worth another attempt with the same key: a 5xx saved nothing, and 503 * price_unavailable or provider_unavailable carry Retry-After. A 409 is a conflict with the state of * the loan or the application (ERRORS.md): retrying it unchanged gets the same answer, and a stored * one is replayed as it was. Borrou never answers 409 to a concurrent retry with the same key: that * request waits and replays the first one's answer. So a 409 is retried only when Borrou says when. */ export function retryable(status: number, retryAfter: number | null): boolean { if (status === 429 || status >= 500) return true; return status === 409 && retryAfter !== null; } /** Exponential backoff with full jitter: up to 0.5 s, 1 s, 2 s, ... capped at 30 s. */ export function backoffMs(attempt: number): number { return Math.random() * Math.min(30_000, 500 * 2 ** (attempt - 1)); } /** Retry-After as seconds, or as an HTTP date; null when absent or unreadable. */ export function retryAfterSeconds(value: string | null): number | null { if (!value) return null; if (/^\d+$/.test(value.trim())) return Number(value.trim()); const at = Date.parse(value); return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000)); } function withQuery(path: string, query?: Query): string { if (!query) return path; const params = new URLSearchParams(); for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value)); const text = params.toString(); return text ? `${path}?${text}` : path; }