/** * HTTP/tRPC client utilities for the live API tests. * * Uses the same wire protocol as the apps (`httpBatchLink`, no transformer): * POST /api/trpc/.?batch=1 body {"0": } * GET /api/trpc/.?batch=1&input=}> */ import { createTRPCClient, httpBatchLink, TRPCClientError } from '@trpc/client' import type { AppRouter } from '@/src/trpc/router' import { API_BASE_URL, TRPC_URL } from './env' export type ApiClient = ReturnType> /** A typed tRPC client; pass a token to authenticate as that principal. */ export function apiClient(token?: string): ApiClient { return createTRPCClient({ links: [ httpBatchLink({ url: TRPC_URL, headers: () => (token ? { Authorization: `Bearer ${token}` } : {}), }), ], }) } export interface RawTrpcOptions { token?: string /** Override the verb (used by the request-shape edge cases). */ method?: 'GET' | 'POST' headers?: Record /** Use a raw body instead of the encoded input (malformed-JSON cases). */ body?: string } export interface RawTrpcResponse { status: number ok: boolean body: unknown text: string headers: Headers } /** * Low-level tRPC call. Queries default to GET and mutations to POST; pass * `method` to send the wrong verb deliberately. */ export async function rawTrpc( procedure: string, input: unknown, options: RawTrpcOptions = {} ): Promise { const headers: Record = { ...(options.headers ?? {}) } if (options.token) headers.Authorization = `Bearer ${options.token}` if (!headers['content-type'] && !options.body) headers['content-type'] = 'application/json' let method = options.method let url = `${TRPC_URL}/${procedure}?batch=1` let body: string | undefined if (!method) { // Public reads are queries; mutations are POST. The caller may override. method = 'POST' } if (options.body != null) { body = options.body } else if (method === 'GET') { url += `&input=${encodeURIComponent(JSON.stringify({ 0: input }))}` } else { body = JSON.stringify({ 0: input }) } const res = await fetch(url, { method, headers, body }) const text = await res.text() let parsed: unknown = null try { parsed = text ? JSON.parse(text) : null } catch { parsed = null } return { status: res.status, ok: res.ok, body: parsed, text, headers: res.headers } } /** Fetch a REST route (`/api/health`, `/api/v1/...`). */ export async function rest(path: string, init: RequestInit = {}): Promise { const url = path.startsWith('http') ? path : `${API_BASE_URL}${path}` return fetch(url, init) } /** Unique-enough suffix so reruns never collide on names/emails/codes. */ export function uniqueSuffix(): string { return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}` } /** Run a call that must reject and hand back the error (fails if it resolves). */ export async function captureError(fn: () => Promise): Promise { let error: Error | null = null try { await fn() } catch (caught) { error = caught as Error } if (!error) throw new Error('[api-tests] expected the call to reject, but it resolved') return error } export function errorCode(error: unknown): string | undefined { const candidate = error as { data?: { code?: string }; shape?: { data?: { code?: string } } } return candidate?.data?.code ?? candidate?.shape?.data?.code } export function errorHttpStatus(error: unknown): number | undefined { const candidate = error as { data?: { httpStatus?: number }; shape?: { data?: { httpStatus?: number } } } return candidate?.data?.httpStatus ?? candidate?.shape?.data?.httpStatus } export function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error) } /** * Assert that a call rejects with a tRPC code (and optionally a message * fragment). Accepts one code or a list of acceptable codes. */ export async function expectTrpcError( fn: () => Promise, expected: string | string[], messageContains?: string ): Promise { const error = await captureError(fn) const codes = Array.isArray(expected) ? expected : [expected] const code = errorCode(error) if (!code || !codes.includes(code)) { throw new Error( `[api-tests] expected tRPC code ${codes.join('|')} but got ${code ?? ''}: ${errorMessage(error)}` ) } if (messageContains) { const haystack = `${errorMessage(error)} ${JSON.stringify((error as any)?.data ?? '')}` if (!haystack.toLowerCase().includes(messageContains.toLowerCase())) { throw new Error( `[api-tests] expected error message to contain "${messageContains}", got: ${errorMessage(error)}` ) } } return error } /** Query via GET (the verb the backend expects for queries). */ export function rawQuery(procedure: string, input: unknown, options: Omit = {}) { return rawTrpc(procedure, input, { ...options, method: 'GET' }) } /** Mutation via POST. */ export function rawMutation(procedure: string, input: unknown, options: Omit = {}) { return rawTrpc(procedure, input, { ...options, method: 'POST' }) } export function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)) } /** Fail fast when the backend is not running. */ export async function assertServerUp(): Promise { try { const res = await fetch(`${API_BASE_URL}/api/health`, { signal: AbortSignal.timeout(5_000) }) if (res.status >= 500) throw new Error(`health returned ${res.status}`) } catch (error) { throw new Error( `[api-tests] Backend not reachable at ${API_BASE_URL}. Start it with ` + `"cd apps/backend && bun run dev" (wrangler dev, port 8787). ` + `Cause: ${(error as Error).message}` ) } } /** Parse a tRPC batch response and return the first result (or throw). */ export function firstBatchResult(body: unknown): T { const entry = Array.isArray(body) ? body[0] : body const error = (entry as { error?: unknown })?.error if (error) throw new Error(`[api-tests] tRPC error: ${JSON.stringify(error)}`) return (entry as { result?: { data?: T } })?.result?.data as T }