import { ApiError } from "./apiError.js";
import { u } from "./base.js";
import { isSignedOutResponse, markSignedOut } from "./accessSession.js";
async function readBody(res) {
try {
return await res.text();
} catch (_) {
return "";
}
}
async function request(method, url, opts) {
const res = await fetch(url, { ...opts, redirect: "manual" });
if (isSignedOutResponse(res)) {
markSignedOut();
const err = new ApiError(
method,
url,
401,
"signed out of Cloudflare Access",
await readBody(res),
);
err.signedOut = true;
throw err;
}
return res;
}
async function json(method, url, opts) {
let res;
try {
res = await request(method, url, opts);
} catch (e) {
if (e instanceof ApiError) throw e;
throw new ApiError(method, url, null, e.message);
}
if (!res.ok)
throw new ApiError(
method,
url,
res.status,
res.statusText,
await readBody(res),
);
return res;
}
export async function apiGet(path) {
const url = u(path);
const res = await json("GET", url, {
headers: { Accept: "application/json" },
});
return res.json();
}
export async function apiPutJSON(path, body) {
return request("PUT", u(path), {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
export async function apiPost(path, body) {
const opts = body
? {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}
: { method: "POST" };
return request("POST", u(path), opts);
}
export async function apiSend(path, opts = {}) {
const merged = {
...opts,
headers: { "Content-Type": "application/json", ...(opts.headers || {}) },
};
const method = opts.method || "GET";
const res = await json(method, u(path), merged);
const text = await res.text();
return text ? JSON.parse(text) : null;
}
export async function localGet(path) {
const res = await json("GET", u(path), {
headers: { Accept: "application/json" },
credentials: "same-origin",
});
return res.json();
}
export async function localFetch(path, opts = {}) {
return request((opts.method || "GET").toUpperCase(), u(path), {
credentials: "same-origin",
...opts,
});
}