EnergyVenom's picture
Patchwise Agent Studio: Oracle AI Agent Studio cycles
af1bee9 verified
Raw History Blame Contribute Delete
4.48 kB
// Typed REST client: openapi-fetch over the generated FastAPI schema (src/api/schema.d.ts, `npm run gen:api`).
// Same-origin cookie session; every unsafe request carries the CSRF token (double-submit cookie `fpt_csrf`).
import createClient, { type Middleware } from 'openapi-fetch';
import type { components, paths } from './schema';
import { explainError } from './errors';
export type Schemas = components['schemas'];
export class ApiError extends Error {
status: number;
code: string;
requestId?: string | null;
body: unknown;
constructor(status: number, code: string, detail: string, body?: unknown, requestId?: string | null) {
super(detail);
this.status = status;
this.code = code;
this.body = body;
this.requestId = requestId;
}
}
const UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
export function readCookie(name: string, cookieString: string = typeof document !== 'undefined' ? document.cookie : ''): string | null {
for (const part of cookieString.split(';')) {
const [k, ...v] = part.trim().split('=');
if (k === name) return decodeURIComponent(v.join('='));
}
return null;
}
let csrfOverride: string | null = null;
export function setCsrfToken(t: string | null) {
csrfOverride = t;
}
export function csrfToken(): string | null {
return readCookie('fpt_csrf') ?? csrfOverride;
}
export const csrfMiddleware: Middleware = {
onRequest({ request }) {
if (UNSAFE.has(request.method.toUpperCase())) {
const t = csrfToken();
if (t) request.headers.set('X-CSRF-Token', t);
}
return request;
},
};
export function createApi(baseUrl = '', fetchImpl?: typeof fetch) {
// Resolve fetch lazily (not at import time) so the browser's fetch, or a test double, is always the current one.
const c = createClient<paths>({ baseUrl, credentials: 'same-origin', fetch: (req: Request) => (fetchImpl ?? globalThis.fetch)(req) });
c.use(csrfMiddleware);
return c;
}
export const api = createApi(typeof window !== 'undefined' ? window.location.origin : '');
type Result<T> = { data?: T; error?: unknown; response: Response };
/** Unwrap an openapi-fetch result into data or a typed ApiError (backend error model: {detail, code, request_id}). */
export async function unwrap<T>(p: Promise<Result<T>>): Promise<T> {
const { data, error, response } = await p;
if (response.ok) return (data ?? (undefined as T)) as T;
const e = (error ?? {}) as { detail?: unknown; code?: string; request_id?: string };
const detail = typeof e.detail === 'string' ? e.detail : `HTTP ${response.status}`;
throw new ApiError(response.status, e.code ?? 'HTTP_ERROR', detail, error, e.request_id ?? response.headers.get('x-request-id'));
}
/** For endpoints whose payload is a dynamic dict (graph state views): typed by src/api/types.ts. */
export async function getJson<T>(url: string): Promise<T> {
const r = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } });
if (r.status === 204) return null as T;
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new ApiError(r.status, body.code ?? 'HTTP_ERROR', body.detail ?? `HTTP ${r.status}`, body, body.request_id);
return body as T;
}
/** An unsafe JSON request (with the CSRF header) for endpoints not yet in the generated schema. Errors become ApiError. */
export async function sendJson<T>(method: 'POST' | 'PUT' | 'PATCH' | 'DELETE', url: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = { Accept: 'application/json', 'Content-Type': 'application/json' };
const t = csrfToken();
if (t) headers['X-CSRF-Token'] = t;
const r = await fetch(url, { method, credentials: 'same-origin', headers, body: body === undefined ? undefined : JSON.stringify(body) });
if (r.status === 204) return null as T;
const out = await r.json().catch(() => ({}));
if (!r.ok) throw new ApiError(r.status, out.code ?? 'HTTP_ERROR', typeof out.detail === 'string' ? out.detail : `HTTP ${r.status}`, out, out.request_id ?? r.headers.get('x-request-id'));
return out as T;
}
/** The error in plain words (what happened, and what to do), never the raw code or request id. */
export function errorMessage(e: unknown): string {
const i = explainError(e);
return [i.message, i.fields?.map((f) => `${f.field}: ${f.message}`).join('; '), i.hint].filter(Boolean).join(' ');
}