export interface ApiEnvelope { code: number message: string data?: T | null error?: string | null error_code?: string | null request_id?: string } export class ApiFailure extends Error { readonly code: number readonly errorCode?: string | null readonly requestId?: string | null constructor(message: string, code: number, errorCode?: string | null, requestId?: string | null) { super(message) this.name = 'ApiFailure' this.code = code this.errorCode = errorCode this.requestId = requestId } } export async function unwrapApi( method: PromiseLike< | ApiEnvelope | { code: number message: string data?: unknown error?: string | null error_code?: string | null request_id?: string } >, ): Promise { const res = (await method) as ApiEnvelope if (res.code !== 200) { throw new ApiFailure(res.error || res.message || 'request failed', res.code, res.error_code, res.request_id) } return res.data as T }