Files
pansy/web/src/lib/api.ts
T
steveandClaude Opus 4.8 0f3dedab73 Address Gadfly review findings on Phase 0
Applied the fixes warranted by the adversarial review of PR #21 (all
findings graded in the gadfly store):

Store (highest impact):
- buildDSN always merges busy_timeout/journal_mode/foreign_keys pragmas
  into the DSN, even for file: URIs or paths with a query string — the
  prior passthrough silently disabled FK enforcement for those PANSY_DB
  values. Also escape '#' in the path and tighten in-memory detection to
  an exact ':memory:' token or mode=memory param (no substring misfire).
- migrate.go: detect duplicate migration versions with a clear error;
  wrap appliedVersions' rows.Err() with the store: prefix.

API:
- SetTrustedProxies failure now falls back to trust-none instead of
  leaving gin's trust-everyone default (X-Forwarded-For spoofing).
- SPA: 404 embedded directories (was a directory listing), 404 bare /api,
  add X-Content-Type-Options: nosniff, cache index.html bytes once at
  startup, single fs.Stat existence check, shared writeAPIError helper.
- Move gin.SetMode out of package init() into New().

Config: validate PANSY_PORT range (fall back to 8080 with a warning).

Web:
- api.ts: serialize the request body before the fetch try so a
  JSON.stringify failure isn't misreported as a network error.
- AppShell: move state-specific/conflicting utilities into
  active/inactiveProps so concatenated Tailwind classes don't collide.

Tests: added store DSN-pragma/memory-detection cases and SPA
directory-404 case. go build/vet/test clean (CGO off); web tsc + build
clean; re-verified in a browser (SPA, deep links, /assets 404, nav).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
2026-07-18 15:19:30 -04:00

126 lines
4.2 KiB
TypeScript

// Typed fetch wrapper for the pansy JSON API under /api/v1.
//
// Every non-2xx response throws an ApiError carrying the HTTP status and the
// parsed response body. That contract matters beyond this issue: the optimistic
// editor (per DESIGN.md § Sync) sends each PATCH/DELETE with a row `version` and,
// on a 409, reads the *current* row back out of `ApiError.body` to reconcile.
const BASE = '/api/v1'
/** Error thrown for any non-2xx response (or a network failure, status 0). */
export class ApiError extends Error {
readonly status: number
/** Parsed response body (JSON object, string, or null). On a 409 this is the current server row. */
readonly body: unknown
constructor(message: string, status: number, body: unknown) {
super(message)
this.name = 'ApiError'
this.status = status
this.body = body
}
/** A version conflict (DESIGN.md § Sync); `body` holds the current server row. */
get isConflict(): boolean {
return this.status === 409
}
/** No authenticated session; callers typically redirect to /login. */
get isUnauthorized(): boolean {
return this.status === 401
}
}
type ParamValue = string | number | boolean | undefined | null
export type Params = Record<string, ParamValue>
export interface RequestOptions {
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
/** JSON request body; serialized and sent with a JSON content-type. */
body?: unknown
/** Query-string parameters; undefined/null/'' entries are omitted. */
params?: Params
signal?: AbortSignal
}
function buildUrl(path: string, params?: Params): string {
const url = BASE + path
if (!params) return url
const qs = new URLSearchParams()
for (const [k, v] of Object.entries(params)) {
if (v === undefined || v === null || v === '') continue
qs.set(k, String(v))
}
const s = qs.toString()
return s ? `${url}?${s}` : url
}
async function parseBody(res: Response): Promise<unknown> {
if (res.status === 204) return null
const text = await res.text()
if (!text) return null
const contentType = res.headers.get('content-type') ?? ''
if (contentType.includes('application/json')) {
try {
return JSON.parse(text)
} catch {
return text
}
}
return text
}
function messageFrom(body: unknown, status: number): string {
if (body && typeof body === 'object') {
const err = (body as { error?: { message?: string } }).error
if (err?.message) return err.message
const msg = (body as { message?: string }).message
if (msg) return msg
}
return `Request failed (${status})`
}
/** Perform a request against /api/v1 and return the parsed JSON body as T. */
export async function apiFetch<T>(path: string, opts: RequestOptions = {}): Promise<T> {
const { method = 'GET', body, params, signal } = opts
// Serialize before the try so a JSON.stringify failure (e.g. a circular value)
// surfaces as itself, not as a misleading "cannot reach the server" error.
const requestBody = body !== undefined ? JSON.stringify(body) : undefined
let res: Response
try {
res = await fetch(buildUrl(path, params), {
method,
signal,
credentials: 'same-origin', // send the HttpOnly session cookie
headers: {
accept: 'application/json',
...(body !== undefined ? { 'content-type': 'application/json' } : {}),
},
body: requestBody,
})
} catch (err) {
if ((err as Error)?.name === 'AbortError') throw err
throw new ApiError('Cannot reach the pansy server.', 0, null)
}
const payload = await parseBody(res)
if (!res.ok) {
throw new ApiError(messageFrom(payload, res.status), res.status, payload)
}
return payload as T
}
/** Convenience verbs over apiFetch. */
export const api = {
get: <T>(path: string, opts?: Omit<RequestOptions, 'method' | 'body'>) =>
apiFetch<T>(path, { ...opts, method: 'GET' }),
post: <T>(path: string, body?: unknown, opts?: Omit<RequestOptions, 'method' | 'body'>) =>
apiFetch<T>(path, { ...opts, method: 'POST', body }),
patch: <T>(path: string, body?: unknown, opts?: Omit<RequestOptions, 'method' | 'body'>) =>
apiFetch<T>(path, { ...opts, method: 'PATCH', body }),
delete: <T>(path: string, opts?: Omit<RequestOptions, 'method' | 'body'>) =>
apiFetch<T>(path, { ...opts, method: 'DELETE' }),
}