@scalar/api-client
Version:
the open source API testing client
123 lines (122 loc) • 3.04 kB
JavaScript
import { httpStatusCodes as S } from "@scalar/helpers/http/http-status-codes";
import { executeHook as f } from "@scalar/oas-utils/helpers";
import { normalizeError as b, ERRORS as q } from "../../../../libs/errors.js";
import { normalizeHeaders as x } from "../../../../libs/normalize-headers.js";
import { decodeBuffer as D } from "./decode-buffer.js";
import { getCookieHeaderKeys as T } from "./get-cookie-header-keys.js";
const E = [204, 205, 304], v = async ({
isUsingProxy: t,
operation: n,
request: p,
plugins: r
}) => {
try {
const { request: s } = await f({ request: p }, "beforeRequest", r), l = Date.now(), e = await fetch(s.clone()), a = Date.now(), c = a - l, d = e.headers.get("content-type"), o = x(e.headers, t), u = new URL(e.url), m = u.pathname + u.search, i = e.statusText || S[e.status]?.name || "", h = s.method, R = E.includes(e.status);
return d?.startsWith("text/event-stream") && e.body ? H({
response: e,
modifiedRequest: s,
operation: n,
plugins: r,
endTime: a,
duration: c,
responseHeaders: o,
statusText: i,
method: h,
fullPath: m
}) : g({
response: e,
modifiedRequest: s,
operation: n,
plugins: r,
endTime: a,
duration: c,
responseHeaders: o,
statusText: i,
method: h,
fullPath: m,
contentType: d,
shouldSkipBody: R
});
} catch (s) {
return [b(s, q.REQUEST_FAILED), null];
}
}, H = async ({
response: t,
modifiedRequest: n,
operation: p,
plugins: r,
endTime: s,
duration: l,
responseHeaders: e,
statusText: a,
method: c,
fullPath: d
}) => {
const o = new Response(null, {
status: t.status,
statusText: a,
headers: t.headers
});
await f({ response: o, request: n, operation: p }, "responseReceived", r);
const u = T(o.headers);
return [
null,
{
timestamp: s,
request: n,
response: {
...o,
headers: e,
cookieHeaderKeys: u,
reader: t.body.getReader(),
duration: l,
method: c,
path: d
},
originalResponse: o.clone()
}
];
}, g = async ({
response: t,
modifiedRequest: n,
operation: p,
plugins: r,
endTime: s,
duration: l,
responseHeaders: e,
statusText: a,
method: c,
fullPath: d,
contentType: o,
shouldSkipBody: u
}) => {
const i = await t.clone().arrayBuffer(), R = D(i, o ?? "text/plain;charset=UTF-8"), y = new Response(u ? null : i, {
status: t.status,
statusText: a,
headers: t.headers
});
await f({ response: y, request: n, operation: p }, "responseReceived", r);
const w = T(y.headers);
return [
null,
{
timestamp: s,
request: n,
response: {
...y,
headers: e,
cookieHeaderKeys: w,
data: R,
size: i.byteLength,
duration: l,
method: c,
status: t.status,
path: d
},
originalResponse: t.clone()
}
];
};
export {
v as sendRequest
};