← back to Yolo Agent
ledger-app/src/lib/xfetch.ts
32 lines
// XMLHttpRequest wrapper — required because the page may load via credential-embedded URL
// fetch() strips credentials from cross-origin requests, XHR preserves them
export interface XFetchResponse {
ok: boolean;
status: number;
json: () => Promise<any>;
text: () => Promise<string>;
}
export function xfetch(
url: string,
opts?: { method?: string; body?: any }
): Promise<XFetchResponse> {
return new Promise((resolve, reject) => {
const x = new XMLHttpRequest();
x.open(opts?.method || 'GET', url, true);
x.withCredentials = true;
if (opts?.body) x.setRequestHeader('Content-Type', 'application/json');
x.onload = () => {
resolve({
ok: x.status >= 200 && x.status < 300,
status: x.status,
json: () => Promise.resolve(JSON.parse(x.responseText)),
text: () => Promise.resolve(x.responseText),
});
};
x.onerror = () => reject(new Error('XHR failed'));
x.send(opts?.body ? JSON.stringify(opts.body) : null);
});
}