Share Yaak's request and response panes (#815)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-11-05 09:23:38 -07:00
1 parent 4ad0533901
commit 08a98d5f82
85 files changed
+5567 -2872

No files matched your search

@@ -0,0 +1,35 @@
import {
type EditorHost,
EditorHostProvider,
MultipartViewer,
type MultipartViewerProps,
TextViewer,
type TextViewerProps,
} from "@yaakapp-internal/ui";
import { type ReactNode, useMemo } from "react";
import { formatText as engineFormatText } from "../lib/body";
/**
* Gives the shared panes the proxy's formatting. Everything else keeps the shared defaults:
* plain editors with no templating, state kept for the session, no dialogs.
*/
export function ProxyEditorHost({
children,
formatText = engineFormatText,
}: {
children: ReactNode;
/** Pretty-prints a body; the engine's formatter unless replaced */
formatText?: TextViewerProps["formatText"];
}) {
// Components made once per formatter, so viewers aren't remounted on every render
const host = useMemo<Partial<EditorHost>>(
() => ({
TextViewer: (props: TextViewerProps) => <TextViewer formatText={formatText} {...props} />,
MultipartViewer: (props: MultipartViewerProps) => (
<MultipartViewer textViewerProps={{ formatText }} {...props} />
),
}),
[formatText],
);
return <EditorHostProvider value={host}>{children}</EditorHostProvider>;
}
+33
View File
@@ -0,0 +1,33 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Yaak Proxy, shared panes harness</title>
<style>
html,
body,
#root {
height: 100%;
margin: 0;
}
</style>
</head>
<body class="text-base">
<!-- Dev only, served by `vp dev`; the build's only entry is index.html -->
<div id="root"></div>
<script>
// Outside the app there's no Tauri; the platform package still looks for its window
window.__TAURI_INTERNALS__ = {
metadata: {
currentWindow: { label: "harness" },
currentWebview: { label: "harness", windowLabel: "harness" },
},
invoke: () => Promise.reject(new Error("Not running in the app")),
transformCallback: () => 0,
};
</script>
<script type="module" src="/font-size.ts"></script>
<script type="module" src="/harness/main.tsx"></script>
</body>
</html>
@@ -0,0 +1,113 @@
import {
HttpRequestPaneView,
HttpResponsePaneView,
type HttpBodyResult,
type ResponseViewMode,
} from "@yaakapp-internal/ui";
import { useMemo, useState } from "react";
import { ProxyEditorHost } from "../components/ProxyEditorHost";
import { findHeader } from "../lib/body";
import {
type FlowBodyData,
flowBodyFromRpc,
flowBodyLoader,
flowRequestToView,
flowResponseToView,
} from "../lib/flowViews";
import { type FlowFixture, fixtures } from "./fixtures";
/**
* Dev only: renders captured flows through the shared request and response panes, read-only,
* side by side, the way the proxy's detail view will. Open `/harness.html?flow=0&theme=dark`.
*/
export function FlowPanesHarness() {
const params = new URLSearchParams(location.search);
const [index, setIndex] = useState(Number(params.get("flow") ?? 0));
const fixture = fixtures[index] ?? fixtures[0];
if (fixture == null) return null;
return (
<ProxyEditorHost formatText={formatLocally}>
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] gap-2 p-2 bg-surface">
<div className="flex gap-2 text-sm">
{fixtures.map((f, i) => (
<button
key={f.flow.id}
type="button"
className={i === index ? "text-text" : "text-text-subtle"}
onClick={() => setIndex(i)}
>
{f.label}
</button>
))}
</div>
<FlowPanes key={fixture.flow.id} fixture={fixture} />
</div>
</ProxyEditorHost>
);
}
function FlowPanes({ fixture }: { fixture: FlowFixture }) {
const { flow } = fixture;
const [viewMode, setViewMode] = useState<ResponseViewMode>("pretty");
const requestBody = useMemo(() => flowBodyFromRpc(fixture.requestBody), [fixture]);
const responseBody = useMemo(() => flowBodyFromRpc(fixture.responseBody), [fixture]);
const request = useMemo(() => flowRequestToView(flow, requestBody), [flow, requestBody]);
const response = useMemo(() => flowResponseToView(flow, responseBody), [flow, responseBody]);
const requestLoader = useMemo(
() =>
flowBodyLoader({
useBody: () => loaded(requestBody),
contentType: findHeader(flow.requestHeaders, "content-type"),
}),
[requestBody, flow],
);
const responseLoader = useMemo(
() =>
flowBodyLoader({
useBody: () => loaded(responseBody),
contentType: findHeader(flow.responseHeaders, "content-type"),
}),
[responseBody, flow],
);
return (
<div className="grid grid-cols-2 gap-2 min-h-0">
<div className="min-h-0 px-2">
<HttpRequestPaneView
request={request}
fullHeight
forceUpdateKey={flow.updatedAt}
tabsStorageKey="flow_request_tabs"
bodyLoader={requestLoader}
/>
</div>
<HttpResponsePaneView
response={response}
body={responseLoader}
requestBody={requestLoader}
emptyState={<div className="p-3 text-text-subtle">Waiting for a response</div>}
viewMode={viewMode}
onViewModeChange={setViewMode}
tabsStorageKey="flow_response_tabs"
activeTabKey={flow.id}
onCopyAsCurl={() => undefined}
/>
</div>
);
}
function loaded(data: FlowBodyData): HttpBodyResult<FlowBodyData | null> {
return { data, isLoading: false, error: null };
}
/** The engine formats JSON over RPC, which a page outside the app can't reach */
async function formatLocally(text: string, language: unknown): Promise<string> {
if (language !== "json") return text;
try {
return JSON.stringify(JSON.parse(text), null, 2);
} catch {
return text;
}
}
+141
View File
@@ -0,0 +1,141 @@
import type { Flow, GetFlowBodyResponse } from "@yaakapp-internal/proxy-lib";
/** A flow fixture with its two bodies, as the engine's `get_flow_body` RPC returns them */
export interface FlowFixture {
label: string;
flow: Flow;
requestBody: GetFlowBodyResponse;
responseBody: GetFlowBodyResponse;
}
function body(data: string | Uint8Array): GetFlowBodyResponse {
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return { data: btoa(binary), truncated: false, storedSize: bytes.length };
}
const base: Flow = {
id: "fl_harness",
createdAt: "2026-11-04T22:10:00",
updatedAt: "2026-11-04T22:10:01",
startedAt: "2026-11-04T22:10:00.000",
method: "GET",
url: "https://api.example.com/",
clientHttpVersion: "HTTP/2",
upstreamHttpVersion: "HTTP/2",
remoteAddr: "93.184.216.34:443",
status: 200,
contentType: null,
requestHeaders: [],
responseHeaders: [],
requestSize: 0,
responseSize: 0,
requestTruncated: false,
responseTruncated: false,
elapsedHeadersMs: 84,
elapsedMs: 112,
error: null,
cancelled: false,
savedRequestId: null,
clientPid: 4211,
clientName: "curl",
clientBundleId: null,
clientPath: "/usr/bin/curl",
};
const jsonRequest = JSON.stringify({ amount: 4200, currency: "usd", capture: true });
const jsonResponse = JSON.stringify({
id: "pi_3Q8x",
object: "payment_intent",
amount: 4200,
currency: "usd",
status: "succeeded",
charges: { data: [{ id: "ch_1", paid: true }] },
});
const formRequest = "grant_type=client_credentials&client_id=yaak-proxy&scope=read+write";
const htmlResponse =
"<!doctype html><html><body style='font-family:sans-serif'><h1>Signed in</h1><p>You can close this window.</p></body></html>";
// A 24x24 PNG gradient
const png = Uint8Array.from(
atob(
"iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAIAAABvFaqvAAADnUlEQVR4nA3MEQJEIQBAwc95nOdxHj2J8zjP4zyP8zjP47wD7M4B5vv4BJ/kU3yaz/BZPsfn+QJf5Et8ma/wVb7G1/kG3+RbfJvv8F2+x/d9CIGQCIXQCIOwCIfwiICIiITIiIKoiIboiIGYiIXYiIO4iIf4R1IgJVIhNdIgLdIhPTIgIzIhM7IgK7IhO3IgJ3IhN/IgL/Ih/5ESKIlSKI0yKItyKI8KqIhKqIwqqIpqqI4aqIlaqI06qIt6qH+kBVqiFVqjDdqiHdqjAzqiEzqjC7qiG7qjB3qiF3qjD/qiH/ofGYGRGIXRGIOxGIfxmICJmITJmIKpmIbpmIGZmIXZmIO5mIf5R1ZgJVZhNdZgLdZhPTZgIzZhM7ZgK7ZhO3ZgJ3ZhN/ZgL/Zh/5ETOIlTOI0zOItzOI8LuIhLuIwruIpruI4buIlbuI07uIt7uH/kBV7iFV7jDd7iHd7jAz7iEz7jC77iG77jB37iF37jD/7iH/4fBUGQBEXQBEOwBEfwhECIhETIhEKohEbohEGYhEXYhEO4hEf4R1EQJVERNdEQLdERPTEQIzERM7EQK7ERO3EQJ3ERN/EQL/ER/1ESJElSJE0yJEtyJE8KpEhKpEwqpEpqpE4apElapE06pEt6pH+UBVmSFVmTDdmSHdmTAzmSEzmTC7mSG7mTB3mSF3mTD/mSH/kfFUGRFEXRFEOxFEfxlECJlETJlEKplEbplEGZlEXZlEO5lEf5R1VQJVVRNdVQLdVRPTVQIzVRM7VQK7VRO3VQJ3VRN/VQL/VR/1ETNElTNE0zNEtzNE8LtEhLtEwrtEprtE4btElbtE07tEt7tH/UBV3SFV3TDd3SHd3TAz3SEz3TC73SG73TB33SF33TD/3SH/0fDcGQDMXQDMOwDMfwjMCIjMTIjMKojMbojMGYjMXYjMO4jMf4R1MwJVMxNdMwLdMxPTMwIzMxM7MwK7MxO3MwJ3MxN/MwL/Mx/9ESLMlSLM0yLMtyLM8KrMhKrMwqrMpqrM4arMlarM06rMt6rH+0BVuyFVuzDduyHduzAzuyEzuzC7uyG7uzB3uyF3uzD/uyH/sfHcGRHMXRHMOxHMfxnMCJnMTJnMKpnMbpnMGZnMXZnMO5nMf5R1dwJVdxNddwLddxPTdwIzdxM7dwK7dxO3dwJ3dxN/dwL/dx/9ETPMlTPM0zPMtzPM8LvMhLvMwrvMprvM4bvMlbvM07vMt7vB8/gdf/dWsIbgAAAABJRU5ErkJggg==",
),
(c) => c.charCodeAt(0),
);
export const fixtures: FlowFixture[] = [
{
label: "JSON POST",
flow: {
...base,
id: "fl_json",
method: "POST",
url: "https://api.stripe.com/v1/payment_intents?expand=charges&limit=1",
contentType: "application/json",
requestHeaders: [
{ name: "Content-Type", value: "application/json" },
{ name: "Authorization", value: "Bearer sk_test_51Hx" },
{ name: "Cookie", value: "session=abc123; theme=dark" },
{ name: "User-Agent", value: "curl/8.7.1" },
],
responseHeaders: [
{ name: "Content-Type", value: "application/json; charset=utf-8" },
{ name: "Set-Cookie", value: "session=def456; Path=/; HttpOnly; Secure" },
{ name: "Request-Id", value: "req_9Z" },
],
requestSize: jsonRequest.length,
responseSize: jsonResponse.length,
},
requestBody: body(jsonRequest),
responseBody: body(jsonResponse),
},
{
label: "Form POST, HTML response",
flow: {
...base,
id: "fl_form",
method: "POST",
url: "https://auth.example.com/oauth/token",
contentType: "text/html",
requestHeaders: [
{ name: "Content-Type", value: "application/x-www-form-urlencoded" },
{ name: "Authorization", value: "Basic eWFhazpwcm94eQ==" },
],
responseHeaders: [{ name: "Content-Type", value: "text/html; charset=utf-8" }],
requestSize: formRequest.length,
responseSize: htmlResponse.length,
},
requestBody: body(formRequest),
responseBody: body(htmlResponse),
},
{
label: "Image GET",
flow: {
...base,
id: "fl_image",
url: "https://cdn.example.com/avatars/42.png?size=2",
contentType: "image/png",
requestHeaders: [{ name: "Accept", value: "image/*" }],
responseHeaders: [{ name: "Content-Type", value: "image/png" }],
responseSize: png.length,
},
requestBody: body(""),
responseBody: body(png),
},
{
label: "Failed",
flow: {
...base,
id: "fl_failed",
url: "https://unreachable.example.com/health",
status: null,
elapsedHeadersMs: null,
elapsedMs: null,
error: "dns error: failed to lookup address information: nodename nor servname provided",
requestHeaders: [{ name: "Accept", value: "*/*" }],
},
requestBody: body(""),
responseBody: body(""),
},
];
+20
View File
@@ -0,0 +1,20 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { applyThemeToDocument, defaultDarkTheme, defaultLightTheme } from "@yaakapp-internal/theme";
import { createStore, Provider } from "jotai";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { FlowPanesHarness } from "./FlowPanesHarness";
import "../main.css";
const dark = new URLSearchParams(location.search).get("theme") !== "light";
applyThemeToDocument(dark ? defaultDarkTheme : defaultLightTheme);
createRoot(document.getElementById("root") as HTMLElement).render(
<StrictMode>
<QueryClientProvider client={new QueryClient()}>
<Provider store={createStore()}>
<FlowPanesHarness />
</Provider>
</QueryClientProvider>
</StrictMode>,
);
+222
View File
@@ -0,0 +1,222 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import {
BODY_TYPE_BINARY,
BODY_TYPE_FORM_MULTIPART,
BODY_TYPE_FORM_URLENCODED,
BODY_TYPE_JSON,
BODY_TYPE_OTHER,
} from "@yaakapp-internal/ui/httpTypes";
import { describe, expect, test } from "vite-plus/test";
import {
authFromHeaders,
type FlowBodyData,
flowBodyFromRpc,
flowRequestToView,
flowResponseToView,
queryToPairs,
utcTimestamp,
} from "./flowViews";
const flow: Flow = {
id: "fl_1",
createdAt: "2026-11-04T22:10:00Z",
updatedAt: "2026-11-04T22:10:01Z",
startedAt: "2026-11-04T22:10:00Z",
method: "POST",
url: "https://api.example.com/v1/items?limit=1&q=a+b#top",
clientHttpVersion: "HTTP/1.1",
upstreamHttpVersion: "HTTP/2",
remoteAddr: "1.2.3.4:443",
status: 201,
contentType: "application/json",
requestHeaders: [
{ name: "Content-Type", value: "application/json" },
{ name: "Cookie", value: "a=1" },
],
responseHeaders: [
{ name: "Content-Type", value: "application/json" },
{ name: "Set-Cookie", value: "b=2; Path=/" },
],
requestSize: 7,
responseSize: 12,
requestTruncated: false,
responseTruncated: false,
elapsedHeadersMs: 40,
elapsedMs: 55,
error: null,
cancelled: false,
savedRequestId: null,
clientPid: null,
clientName: null,
clientBundleId: null,
clientPath: null,
};
function bytes(text: string): FlowBodyData {
return { bytes: new TextEncoder().encode(text), truncated: false, storedSize: text.length };
}
function withContentType(contentType: string): Flow {
return { ...flow, requestHeaders: [{ name: "Content-Type", value: contentType }] };
}
describe("flowRequestToView", () => {
test("maps the request line, headers and query", () => {
const view = flowRequestToView(flow, bytes('{"a":1}'));
expect(view.method).toBe("POST");
expect(view.url).toBe(flow.url);
expect(view.headers.map((h) => h.name)).toEqual(["Content-Type", "Cookie"]);
expect(view.urlParameters.map(({ name, value }) => ({ name, value }))).toEqual([
{ name: "limit", value: "1" },
{ name: "q", value: "a b" },
]);
expect(view.contentType).toBe("application/json");
});
test("reads a JSON body as JSON, sent as written", () => {
const view = flowRequestToView(flow, bytes('{"a":1}'));
expect(view.bodyType).toBe(BODY_TYPE_JSON);
expect(view.body).toEqual({ text: '{"a":1}', sendJsonComments: true });
});
test("reads a url-encoded body as form fields", () => {
const view = flowRequestToView(
withContentType("application/x-www-form-urlencoded; charset=utf-8"),
bytes("a=1&b=two+words&c=%26"),
);
expect(view.bodyType).toBe(BODY_TYPE_FORM_URLENCODED);
expect(view.body.form?.map(({ name, value }) => [name, value])).toEqual([
["a", "1"],
["b", "two words"],
["c", "&"],
]);
});
test("leaves multipart and binary bodies to the viewers", () => {
expect(
flowRequestToView(withContentType("multipart/form-data; boundary=x"), bytes("--x--"))
.bodyType,
).toBe(BODY_TYPE_FORM_MULTIPART);
const binary: FlowBodyData = {
bytes: new Uint8Array([0xff, 0xfe, 0x00]),
truncated: false,
storedSize: 3,
};
expect(flowRequestToView(withContentType("application/octet-stream"), binary).bodyType).toBe(
BODY_TYPE_BINARY,
);
});
test("reads other text as text, and no body as none", () => {
expect(flowRequestToView(withContentType("text/plain"), bytes("hi")).bodyType).toBe(
BODY_TYPE_OTHER,
);
expect(flowRequestToView(flow, bytes("")).bodyType).toBeNull();
expect(flowRequestToView(flow, null).bodyType).toBeNull();
});
test("shows authentication from the Authorization header", () => {
expect(authFromHeaders([{ name: "authorization", value: "Bearer abc" }])).toEqual({
label: "Bearer",
values: [{ name: "Authorization", value: "Bearer abc" }],
});
expect(authFromHeaders([{ name: "Authorization", value: "Custom x" }])?.label).toBe("Auth");
expect(authFromHeaders([])).toBeNull();
});
});
describe("flowResponseToView", () => {
test("maps status, timing, sizes and cookies", () => {
const view = flowResponseToView(flow);
expect(view).toMatchObject({
id: "fl_1",
ownerId: "fl_1",
state: "closed",
status: 201,
statusReason: "Created",
contentType: "application/json",
contentLength: 12,
requestContentLength: 7,
startedAt: "2026-11-04T22:10:00Z",
elapsedMs: 55,
elapsedHeadersMs: 40,
version: "HTTP/2",
remoteAddr: "1.2.3.4:443",
cookieHeaders: { sent: ["a=1"], received: ["b=2; Path=/"] },
});
});
test("shows a gzip response's decoded size, with its wire size as compressed", () => {
const gzipped: Flow = {
...flow,
responseHeaders: [...flow.responseHeaders, { name: "Content-Encoding", value: "gzip" }],
responseSize: 40,
};
const decoded: FlowBodyData = {
bytes: new Uint8Array(120),
truncated: false,
storedSize: 40,
};
expect(flowResponseToView(gzipped, decoded)).toMatchObject({
contentLength: 120,
contentLengthCompressed: 40,
});
// Before the body loads, the wire size stands in, still marked compressed
expect(flowResponseToView(gzipped)).toMatchObject({
contentLength: 40,
contentLengthCompressed: 40,
});
});
test("keeps the wire size for an unencoded body cut at the capture limit", () => {
const cut: FlowBodyData = { bytes: new Uint8Array(5), truncated: true, storedSize: 5 };
expect(flowResponseToView(flow, cut)).toMatchObject({
contentLength: 12,
contentLengthCompressed: null,
});
expect(flowResponseToView(flow, bytes("hello world!"))).toMatchObject({
contentLength: 12,
contentLengthCompressed: null,
});
});
test("reads the engine's zone-less timestamps as UTC", () => {
expect(flowResponseToView({ ...flow, startedAt: "2026-11-04T22:10:00.123" })?.startedAt).toBe(
"2026-11-04T22:10:00.123Z",
);
expect(utcTimestamp("2026-11-04T22:10:00+02:00")).toBe("2026-11-04T22:10:00+02:00");
});
test("is still connected while the body streams", () => {
expect(flowResponseToView({ ...flow, elapsedMs: null })?.state).toBe("connected");
});
test("has no response while waiting on one", () => {
expect(flowResponseToView({ ...flow, status: null, elapsedMs: null })).toBeNull();
});
test("carries a failure as the response's error", () => {
const view = flowResponseToView({ ...flow, status: null, elapsedMs: null, error: "refused" });
expect(view).toMatchObject({ state: "closed", status: 0, error: "refused" });
});
test("says when the client gave up before a response", () => {
const view = flowResponseToView({ ...flow, status: null, elapsedMs: null, cancelled: true });
expect(view?.error).toBe("Cancelled by the client");
});
});
describe("flowBodyFromRpc", () => {
test("decodes the RPC's base64", () => {
const body = flowBodyFromRpc({ data: btoa("hello"), truncated: true, storedSize: 5 });
expect(new TextDecoder().decode(body.bytes)).toBe("hello");
expect(body.truncated).toBe(true);
});
});
describe("queryToPairs", () => {
test("ignores the fragment and keeps repeats", () => {
expect(queryToPairs("https://x.test/?a=1&a=2#b=3").map((p) => p.value)).toEqual(["1", "2"]);
expect(queryToPairs("https://x.test/")).toEqual([]);
});
});
+235
View File
@@ -0,0 +1,235 @@
import type { Flow, GetFlowBodyResponse, ProxyHeader } from "@yaakapp-internal/proxy-lib";
import {
BODY_TYPE_BINARY,
BODY_TYPE_FORM_MULTIPART,
BODY_TYPE_FORM_URLENCODED,
BODY_TYPE_JSON,
BODY_TYPE_OTHER,
BODY_TYPE_XML,
type HttpAuthView,
type HttpBodyLoader,
type HttpBodyResult,
type HttpPairView,
type HttpRequestBodyView,
type HttpRequestView,
type HttpResponseView,
} from "@yaakapp-internal/ui/httpTypes";
import { useEffect, useState } from "react";
import { base64ToBytes, bytesToText, findHeader, mimeEssence } from "./body";
import { statusReason } from "./statusReason";
/** A captured body as the engine's body RPC returns it, decoded */
export interface FlowBodyData {
bytes: Uint8Array<ArrayBuffer>;
truncated: boolean;
storedSize: number;
}
export function flowBodyFromRpc(res: GetFlowBodyResponse): FlowBodyData {
return { bytes: base64ToBytes(res.data), truncated: res.truncated, storedSize: res.storedSize };
}
/** A captured request as the shared request pane shows it, read-only */
export function flowRequestToView(flow: Flow, body: FlowBodyData | null): HttpRequestView {
const contentType = findHeader(flow.requestHeaders, "content-type");
const text = body == null ? null : bytesToText(body.bytes, body.truncated);
const { bodyType, body: bodyView } = requestBodyView(contentType, body, text);
return {
id: flow.id,
method: flow.method,
url: flow.url,
headers: headersToPairs(flow.requestHeaders),
urlParameters: queryToPairs(flow.url),
bodyType,
body: bodyView,
contentType,
auth: authFromHeaders(flow.requestHeaders),
};
}
/** The body type a captured body reads as, in the shape that body type's editor shows */
function requestBodyView(
contentType: string | null,
body: FlowBodyData | null,
text: string | null,
): { bodyType: string | null; body: HttpRequestBodyView } {
if (body == null || body.bytes.length === 0) return { bodyType: null, body: {} };
const mime = mimeEssence(contentType) ?? "";
if (mime.startsWith("multipart/")) return { bodyType: BODY_TYPE_FORM_MULTIPART, body: {} };
if (text == null) return { bodyType: BODY_TYPE_BINARY, body: {} };
if (mime === BODY_TYPE_FORM_URLENCODED) {
return { bodyType: BODY_TYPE_FORM_URLENCODED, body: { form: formToPairs(text) } };
}
if (mime === "application/json" || mime.endsWith("+json")) {
// Captured as sent, so nothing was cleaned up before it went out
return { bodyType: BODY_TYPE_JSON, body: { text, sendJsonComments: true } };
}
if (mime === "text/xml" || mime === "application/xml" || mime.endsWith("+xml")) {
return { bodyType: BODY_TYPE_XML, body: { text } };
}
return { bodyType: BODY_TYPE_OTHER, body: { text } };
}
/**
* A captured response as the shared response pane shows it, or null when the request never
* got one and didn't fail either (it's still waiting). `body` is the response body from the
* engine, decoded; its size is the one the pane shows, and the wire size counts as compressed
* when the response had a Content-Encoding. Until it loads, the wire size stands in.
*/
export function flowResponseToView(
flow: Flow,
body: FlowBodyData | null = null,
): HttpResponseView | null {
const ended = flow.elapsedMs != null || flow.error != null || flow.cancelled;
if (flow.status == null && !ended) return null;
const encoding = findHeader(flow.responseHeaders, "content-encoding")?.trim().toLowerCase();
const encoded = encoding != null && encoding !== "" && encoding !== "identity";
return {
id: flow.id,
ownerId: flow.id,
state: ended ? "closed" : "connected",
status: flow.status ?? 0,
statusReason: flow.status == null ? null : statusReason(flow.status),
url: flow.url,
headers: headersToPairs(flow.responseHeaders),
requestHeaders: headersToPairs(flow.requestHeaders),
contentType: findHeader(flow.responseHeaders, "content-type"),
// A body cut at the capture limit is short; unencoded, the wire size is the exact one
contentLength:
body == null || (body.truncated && !encoded) ? flow.responseSize : body.bytes.length,
contentLengthCompressed: encoded ? flow.responseSize : null,
requestContentLength: flow.requestSize,
startedAt: utcTimestamp(flow.startedAt),
elapsedMs: flow.elapsedMs ?? 0,
elapsedHeadersMs: flow.elapsedHeadersMs ?? 0,
elapsedDnsMs: 0,
error: flow.error ?? (flow.cancelled && flow.status == null ? "Cancelled by the client" : null),
remoteAddr: flow.remoteAddr,
version: flow.upstreamHttpVersion ?? flow.clientHttpVersion,
cookieHeaders: {
sent: headerValues(flow.requestHeaders, "cookie"),
received: headerValues(flow.responseHeaders, "set-cookie"),
},
};
}
/**
* Reads a captured body the ways the shared viewers ask for it. `useBody` is the hook that
* loads it, the engine's body RPC in the app or a fixture in tests.
*/
export function flowBodyLoader({
useBody,
contentType,
filterText,
}: {
useBody: () => HttpBodyResult<FlowBodyData | null>;
contentType: string | null;
filterText?: (expression: string) => Promise<string | null>;
}): HttpBodyLoader {
return {
useText: () => {
const body = useBody();
return { ...body, data: mapData(body, (b) => bytesToText(b.bytes, b.truncated)) };
},
useBytes: () => {
const body = useBody();
return { ...body, data: mapData(body, (b) => b.bytes) };
},
useUrl: (enabled: boolean) => {
const body = useBody();
const bytes = enabled ? (body.data?.bytes ?? null) : null;
const url = useObjectUrl(bytes, contentType);
// The URL follows the bytes by a render
const waiting = bytes != null && bytes.length > 0 && url == null;
return { ...body, isLoading: !enabled || body.isLoading || waiting, data: url };
},
filterText,
};
}
function mapData<T>(
body: HttpBodyResult<FlowBodyData | null>,
fn: (b: FlowBodyData) => T,
): T | null | undefined {
if (body.data === undefined) return undefined;
if (body.data == null || body.data.bytes.length === 0) return null;
return fn(body.data);
}
/** A URL for bytes held in memory, revoked when they change */
function useObjectUrl(bytes: Uint8Array<ArrayBuffer> | null, contentType: string | null) {
const [url, setUrl] = useState<string | null>(null);
// Made and revoked by the same effect, so a remount can't revoke a URL still in use
useEffect(() => {
if (bytes == null || bytes.length === 0) {
setUrl(null);
return;
}
const next = URL.createObjectURL(new Blob([bytes], { type: mimeEssence(contentType) ?? "" }));
setUrl(next);
return () => URL.revokeObjectURL(next);
}, [bytes, contentType]);
return url;
}
/** The engine stores UTC without a zone; JavaScript would read that as local time */
export function utcTimestamp(timestamp: string): string {
return /(Z|[+-]\d\d:?\d\d)$/i.test(timestamp) ? timestamp : `${timestamp}Z`;
}
function headersToPairs(headers: ProxyHeader[]): HttpPairView[] {
return headers.map((h, i) => ({ id: `${i}`, name: h.name, value: h.value, enabled: true }));
}
function headerValues(headers: ProxyHeader[], name: string): string[] {
return headers.filter((h) => h.name.toLowerCase() === name).map((h) => h.value);
}
/** A URL's query string as parameters, in order, repeats kept */
export function queryToPairs(url: string): HttpPairView[] {
const query = url.split("#")[0]?.split("?").slice(1).join("?") ?? "";
return formToPairs(query);
}
/** `a=1&b=2` as pairs, decoded the way a form or query string is */
export function formToPairs(text: string): HttpPairView[] {
if (text === "") return [];
return text.split("&").map((part, i) => {
const [name = "", ...rest] = part.split("=");
return {
id: `${i}`,
name: decodeFormPart(name),
value: decodeFormPart(rest.join("=")),
enabled: true,
};
});
}
function decodeFormPart(s: string): string {
try {
return decodeURIComponent(s.replaceAll("+", " "));
} catch {
return s;
}
}
/** What the request authenticated with, named by its scheme, for display */
export function authFromHeaders(headers: ProxyHeader[]): HttpAuthView | null {
const value = findHeader(headers, "authorization");
if (value == null) return null;
const scheme = value.split(" ")[0]?.toLowerCase() ?? "";
return { label: AUTH_SCHEMES[scheme] ?? "Auth", values: [{ name: "Authorization", value }] };
}
const AUTH_SCHEMES: Record<string, string> = {
basic: "Basic",
bearer: "Bearer",
digest: "Digest",
ntlm: "NTLM",
negotiate: "Negotiate",
"aws4-hmac-sha256": "AWS",
};