// api-error.ts — reads a failed fetch `Response` into a `ProblemDetails` // (RFC 9457, `application/problem+json`) object, shape-agnostically. // // Promoted from `dashboard/src/credentials.js`'s original `readErrorBody`, // which returned a flat message string. This returns the structured object // instead so a caller — chiefly `ApiErrorPanel` (./api-error-panel/) — can // render title/status/detail separately and build a useful copy-button // payload, rather than re-parsing a pre-squashed string. // // RFC 9457 is this hive's committed error-body contract for first-party // APIs (mara: "any api of our own responding with error that is not rfc // shaped is a bug to be filed against backend") — every first-party route // emits it as of this writing, so the non-JSON fallback below is NOT // compatibility with an in-flight backend transition (that transition is // finished). It's for bodies we did not author: a caller can be pointed // at something that isn't ours, and an nginx-synthesised 502/504 never // reaches our handlers at all, so it's plain HTML, not problem+json. A // first-party route landing here anyway is a bug to file, not something // this reader should quietly paper over. export interface ProblemDetails { type?: string; title?: string; status?: number; detail?: string; } export async function readApiError(resp: Response): Promise { const status = resp.status; let raw: string; try { raw = (await resp.text()).trim(); } catch { return { status }; } if (raw && (raw[0] === '{' || raw[0] === '[')) { try { const body = JSON.parse(raw) as Record; return { type: typeof body.type === 'string' ? body.type : undefined, title: typeof body.title === 'string' ? body.title : undefined, status: typeof body.status === 'number' ? body.status : status, detail: typeof body.detail === 'string' ? body.detail : typeof body.error === 'string' ? body.error : undefined, }; } catch { // not JSON after all — fall through to the raw-text path below } } return { status, detail: raw || undefined }; } // One-line message for a context that only has room for a single string // (a form's inline result line, a toast) rather than the full panel — // same fallback order `readErrorBody` used: detail (or its `error` alias, // already folded in above) → title → a bare status line. export function problemMessage(p: ProblemDetails): string { return p.detail || p.title || (p.status !== undefined ? `http ${p.status}` : 'request failed'); }