From 61af9463cd2a94fdf951511653a13a320c5890b8 Mon Sep 17 00:00:00 2001 From: Hydra Date: Thu, 12 Nov 2026 21:16:50 +0200 Subject: [PATCH 01/36] fix(dashboard): keep destination selection consistent for one server --- .../migration/PlatformImportServices.tsx | 1 - .../servers/managed-server.test.tsx | 95 ++++++++++++++++++- .../src/components/shared/ServerSelector.tsx | 32 +++---- docs/dashboard-design.md | 3 + 4 files changed, 108 insertions(+), 23 deletions(-) diff --git a/apps/dashboard/src/components/migration/PlatformImportServices.tsx b/apps/dashboard/src/components/migration/PlatformImportServices.tsx index 404c14aca..d119a426d 100644 --- a/apps/dashboard/src/components/migration/PlatformImportServices.tsx +++ b/apps/dashboard/src/components/migration/PlatformImportServices.tsx @@ -136,7 +136,6 @@ export function PlatformImportServices({ onSelect={(server) => onTarget(server?.id ?? "", server?.name ?? "")} onReadyChange={onTargetReady} disabled={busy} - label="Plan or server" useSavedDefault={false} />
diff --git a/apps/dashboard/src/components/servers/managed-server.test.tsx b/apps/dashboard/src/components/servers/managed-server.test.tsx index 0263e9ef8..f9e113a54 100644 --- a/apps/dashboard/src/components/servers/managed-server.test.tsx +++ b/apps/dashboard/src/components/servers/managed-server.test.tsx @@ -8,6 +8,7 @@ import { baseDictionary } from "@/i18n"; import { PlatformProvider } from "@/context/PlatformContext"; import { AppDestinationPicker, type AppDestination } from "@/components/deploy/AppDestinationPicker"; import ServerSelector from "@/components/shared/ServerSelector"; +import { PlatformImportServices } from "@/components/migration/PlatformImportServices"; import { BillingLink, BillingWorkspaceProvider, workspaceBillingHref } from "@/components/billing/BillingWorkspaceContext"; import { ApiError } from "@/lib/api/client"; import { ServerUsage } from "./ServerUsage"; @@ -82,15 +83,105 @@ afterEach(async () => { vi.unstubAllGlobals(); }); -it("selects the only server without provisioning anything on render", async () => { +it("keeps the only selected server in the shared picker with Add server inside its menu", async () => { const change = vi.fn(); await render(); expect(change).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ id: server.id })); expect(host.textContent).toContain("Production"); - expect(host.querySelector('[role="combobox"]')).toBeNull(); + const trigger = host.querySelector('button[aria-haspopup="listbox"]'); + expect(trigger).not.toBeNull(); + expect(document.body.textContent).not.toContain(copy.newProjectServer); expect(h.ensure).not.toHaveBeenCalled(); expect(h.add).not.toHaveBeenCalled(); + await act(async () => trigger!.click()); + expect(document.querySelector('[role="listbox"]')?.textContent).toContain("Production"); + const add = [...document.querySelectorAll("button")].find( + (node) => node.textContent?.trim() === copy.newProjectServer, + ); + expect(add).toBeDefined(); + await act(async () => add!.click()); + expect(h.add).toHaveBeenCalledOnce(); + expect(document.querySelector('[role="listbox"]')).toBeNull(); + expect(change).toHaveBeenCalledTimes(1); + expect(h.ensure).not.toHaveBeenCalled(); }); + +it.each(["railway", "vercel"] as const)( + "changes the %s import destination through the real shared picker", + async (provider) => { + const connected: ServerDetail = { + ...server, + id: "connected-server", + name: "SSH destination", + managed: undefined, + connection: "ssh", + sshHost: "192.0.2.10", + sshUser: "deploy", + sshPort: 22, + }; + h.list.mockResolvedValue({ servers: [connected, server] }); + const target = vi.fn(), + review = vi.fn(); + function Import() { + const [id, setId] = useState(connected.id); + const [ready, setReady] = useState(false); + return ( + {}} + onChoose={() => {}} + onTargetReady={setReady} + onTarget={(next, name) => { + setId(next); + target(next, name); + }} + onReview={() => review(id)} + /> + ); + } + await render(); + expect(button("Check import").disabled).toBe(false); + const trigger = host.querySelector('button[aria-haspopup="listbox"]')!; + expect(trigger.textContent).toContain(connected.name); + await act(async () => trigger.click()); + const destination = [...document.querySelectorAll('[role="option"]')].find( + (node) => node.textContent?.includes(server.name ?? server.id), + ); + expect(destination).toBeDefined(); + await act(async () => destination!.click()); + expect(target).toHaveBeenCalledExactlyOnceWith(server.id, server.name); + expect(trigger.textContent).toContain(server.name); + expect(document.querySelector('[role="listbox"]')).toBeNull(); + await act(async () => button("Check import").click()); + expect(review).toHaveBeenCalledExactlyOnceWith(server.id); + expect(h.add).not.toHaveBeenCalled(); + expect(h.ensure).not.toHaveBeenCalled(); + }, +); it.each([true, false])("uses an acquired server for catalog apps (self-hosted: %s)", async selfHosted => { const changed = vi.fn(), ready = vi.fn(); function Picker() { diff --git a/apps/dashboard/src/components/shared/ServerSelector.tsx b/apps/dashboard/src/components/shared/ServerSelector.tsx index 5fb3cae6e..45d39a82f 100644 --- a/apps/dashboard/src/components/shared/ServerSelector.tsx +++ b/apps/dashboard/src/components/shared/ServerSelector.tsx @@ -8,7 +8,7 @@ import { useI18n } from "@/components/i18n-provider"; import { systemApi, type ServerInfo } from "@/lib/api/system"; import { useServerDestinations } from "@/hooks/useServerDestinations"; import { useAddServerModal } from "@/components/servers/add-server-modal"; -import { ServerPicker, ServerRowContent } from "@/components/shared/ServerPicker"; +import { ServerPicker } from "@/components/shared/ServerPicker"; import { Button } from "@/components/ui/button"; import { usePlatform } from "@/context/PlatformContext"; import { settingsApi } from "@/lib/api/settings"; @@ -297,24 +297,16 @@ export function ServerSelectorView({ ) : automaticCloud ? ( ) : rows.length > 0 ? ( - <> - {rows.length === 1 && effective === rows[0]!.id ? ( -
- -
- ) : ( - select(server.id)} - onAddServer={canAddServer && !disabled && !disabledReason ? addServer : undefined} - addServerLabel={addLabel} - /> - )} - + select(server.id)} + onAddServer={canAddServer && !disabled && !disabledReason ? addServer : undefined} + addServerLabel={addLabel} + /> ) : (

@@ -342,7 +334,7 @@ export function ServerSelectorView({ {restrictedSource ? t.migration.sources.hint : forDeployment && !automaticCloud ? managedCopy.existingServerHint : managedCopy.subscriptionHint}

)} - {canAddServer && (automaticCloud || rows.length === 1) && ( + {canAddServer && automaticCloud && (
) : null} + {responseRoutes} ); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx index e10f0b21b..845559b21 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx @@ -69,7 +69,7 @@ export function RouteRules() { setLoading(true); try { const res = await projectsApi.listRouteRules(projectData.id); - const list = res?.rules ?? []; + const list = (res?.rules ?? []).filter(rule => !rule.spec.response); setRules(list); if (!autoOpened.current && list.length > 0) { setOpen(true); diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx index 8045f5187..e23c9279f 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/domain-routing-retry.test.tsx @@ -41,6 +41,7 @@ vi.mock("@/lib/api", async (original) => { ...actual.projectsApi, getEdgeStatus: mocks.edgeStatus, listRouteProtection: async () => ({ data: [] }), + listRouteRules: async () => ({ rules: [] }), }, domainsApi: { ...actual.domainsApi, list: mocks.listDomains, verifySsl: mocks.verifySsl }, deployApi: { diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx index 28825b05d..b776ee564 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/services/service-domains.test.tsx @@ -32,7 +32,7 @@ vi.mock("@/lib/api", async (original) => { return { ...actual, servicesApi: { ...actual.servicesApi, get: mocks.get, update: mocks.update }, - projectsApi: { ...actual.projectsApi, update: mocks.updateProject, connectDomain: mocks.connect, getEdgeStatus: async () => ({ ready: true }), listRouteProtection: async () => ({ data: [] }) }, + projectsApi: { ...actual.projectsApi, update: mocks.updateProject, connectDomain: mocks.connect, getEdgeStatus: async () => ({ ready: true }), listRouteProtection: async () => ({ data: [] }), listRouteRules: async () => ({ rules: [] }) }, deployApi: { ...actual.deployApi, checkPorts: async () => ({ data: [] }), checkOutput: async () => ({ data: [] }) }, domainsApi: { ...actual.domainsApi, remove: mocks.remove, verify: mocks.verify, records: mocks.records, list: mocks.listDomains, dnsChallenge: mocks.dnsChallenge, startDnsChallenge: mocks.startDnsChallenge, dnsPlan: mocks.dnsPlan, diff --git a/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx b/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx new file mode 100644 index 000000000..e9b7f1f68 --- /dev/null +++ b/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx @@ -0,0 +1,193 @@ +// @vitest-environment happy-dom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { normalizeEdgeResponse } from "@repo/core"; +import { DomainResponseRoutes } from "./DomainResponseRoutes"; + +const api = vi.hoisted(() => ({ + listRouteRules: vi.fn(), + createRouteRule: vi.fn(), + updateRouteRule: vi.fn(), + deleteRouteRule: vi.fn(), +})); +vi.mock("@/lib/api", () => ({ + projectsApi: api, + getApiErrorMessage: (error: unknown, fallback: string) => + error instanceof Error ? error.message : fallback, +})); +let root: Root; +let container: HTMLDivElement; +const rule = (overrides = {}) => ({ + id: "response-a", + projectId: "project", + domainId: "domain-a", + pathPrefix: "/x", + enabled: true, + spec: { + response: normalizeEdgeResponse({ body: "original", headers: { "cache-control": "no-store" } }), + }, + ...overrides, +}); +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + api.listRouteRules.mockResolvedValue({ rules: [] }); + api.createRouteRule.mockImplementation(async (_project, input) => ({ + rule: rule({ ...input, edgeApplied: true }), + })); + api.updateRouteRule.mockImplementation(async (_project, _id, input) => ({ + rule: rule({ ...input, edgeApplied: true }), + })); + api.deleteRouteRule.mockResolvedValue({ success: true, edgeApplied: true }); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); +}); +async function render() { + await act(async () => + root.render( + , + ), + ); +} +async function click(label: string) { + const button = [...document.querySelectorAll("button")].find( + (element) => + element.getAttribute("aria-label") === label || element.textContent?.trim() === label, + ); + expect(button, label).toBeTruthy(); + await act(async () => button!.click()); +} +async function input(selector: string, value: string) { + const element = document.querySelector(selector)!; + expect(element, selector).toBeTruthy(); + await act(async () => { + Object.getOwnPropertyDescriptor( + element.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype, + "value", + )!.set!.call(element, value); + element.dispatchEvent(new Event("input", { bubbles: true })); + }); +} +async function submit() { + await act(async () => { + document + .querySelector("form")! + .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })); + }); +} + +it("creates a response for this domain, keeps preview HTML inert, and reports edge acknowledgement", async () => { + await render(); + await click("Add route"); + await input('input[placeholder="/health"]', "/status"); + await input("textarea", ""); + await click("Add header"); + await input('input[aria-label="Header name 1"]', "Cache-Control"); + await input('input[aria-label="Header value 1"]', "no-store"); + await click("Response preview"); + expect(document.querySelector("pre")?.textContent).toContain("", + headers: { "cache-control": "no-store" }, + match: "exact", + }), + }, + }), + ); + expect(document.body.textContent).toContain("Saved and applied to the edge."); + expect(document.querySelector('[role="dialog"]')).toBeNull(); +}); + +it("retains a failed draft, avoids double submit and distinguishes saved from applied", async () => { + await render(); + await click("Add route"); + await input('input[placeholder="/health"]', "/x"); + await input("textarea", "keep this content"); + let reject!: (error: Error) => void; + api.createRouteRule.mockImplementationOnce( + () => + new Promise((_, fail) => { + reject = fail; + }), + ); + await submit(); + await submit(); + expect(api.createRouteRule).toHaveBeenCalledTimes(1); + await act(async () => reject(new Error("offline"))); + expect(document.querySelector("textarea")?.value).toBe("keep this content"); + expect(document.body.textContent).toContain("offline"); + api.createRouteRule.mockResolvedValue({ rule: rule({ edgeApplied: false }) }); + await submit(); + expect(document.body.textContent).toContain("Edge application is pending"); + expect(document.body.textContent).not.toContain("Saved and applied"); +}); + +it("rejects duplicate or injected headers before sending a mutation", async () => { + await render(); + await click("Add route"); + await input('input[placeholder="/health"]', "/headers"); + for (const [index, name] of ["X-Test", "x-test"].entries()) { + await click("Add header"); + await input(`input[aria-label="Header name ${index + 1}"]`, name); + } + await submit(); + expect(api.createRouteRule).not.toHaveBeenCalled(); + expect(document.body.textContent).toContain("must be unique"); +}); + +it("edits only the selected domain response and preserves its disabled state", async () => { + api.listRouteRules.mockResolvedValue({ + rules: [ + rule({ enabled: false }), + rule({ id: "other", domainId: "domain-b", pathPrefix: "/other-domain" }), + rule({ id: "policy", spec: { rateLimit: { rps: 5, burst: 0 } } }), + ], + }); + await render(); + expect(container.textContent).not.toContain("/other-domain"); + await click("Edit route /x"); + expect(document.querySelector("textarea")?.value).toBe("original"); + await input("textarea", "changed"); + await submit(); + const patch = api.updateRouteRule.mock.calls[0]![2]; + expect(patch).not.toHaveProperty("enabled"); + expect(patch.spec.response).toMatchObject({ + body: "changed", + headers: { "cache-control": "no-store" }, + }); + expect(api.createRouteRule).not.toHaveBeenCalled(); +}); + +it("keeps failed loading distinct from an empty list and requires confirmation to remove", async () => { + api.listRouteRules.mockRejectedValueOnce(new Error("Cannot reach API")); + await render(); + expect(container.textContent).toContain("Cannot reach API"); + expect( + [...container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Add route"), + )?.disabled, + ).toBe(true); + api.listRouteRules.mockResolvedValue({ rules: [rule()] }); + await click("Retry"); + await click("Remove /x"); + expect(api.deleteRouteRule).not.toHaveBeenCalled(); + await click("Remove"); + expect(api.deleteRouteRule).toHaveBeenCalledWith("project", "response-a"); + expect(container.textContent).not.toContain("/x"); +}); diff --git a/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx b/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx new file mode 100644 index 000000000..cb59ad690 --- /dev/null +++ b/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx @@ -0,0 +1,625 @@ +"use client"; + +import { useCallback, useEffect, useId, useRef, useState } from "react"; +import { Icon } from "@repo/ui/icons"; +import { normalizeEdgeResponse, normalizeResponsePath, EDGE_RESPONSE_MAX_BYTES } from "@repo/core"; +import { useI18n } from "@/components/i18n-provider"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Textarea } from "@/components/ui/textarea"; +import { CustomSelect } from "@/components/ui/CustomSelect"; +import { Modal } from "@/components/ui/Modal"; +import { useDialogFocus } from "@/hooks/useDialogFocus"; +import { projectsApi, getApiErrorMessage, type RouteRuleRow } from "@/lib/api"; + +type Draft = { + id?: string; + path: string; + match: "exact" | "prefix"; + status: string; + contentType: string; + body: string; + methods: string; + headers: Array<{ name: string; value: string }>; +}; +const blank = (): Draft => ({ + path: "", + match: "exact", + status: "200", + contentType: "text/plain; charset=utf-8", + body: "", + methods: "GET, HEAD", + headers: [], +}); +const fromRule = (rule: RouteRuleRow): Draft => ({ + id: rule.id, + path: rule.pathPrefix || "/", + match: rule.spec.response!.match, + status: String(rule.spec.response!.status), + contentType: rule.spec.response!.contentType, + body: rule.spec.response!.body, + methods: rule.spec.response!.methods.join(", "), + headers: Object.entries(rule.spec.response!.headers).map(([name, value]) => ({ name, value })), +}); + +/** The same domain editor is used by single-app, service and project route cards. */ +export function DomainResponseRoutes({ + projectId, + domainId, + hostname, +}: { + projectId: string; + domainId: string; + hostname: string; +}) { + const { t, locale } = useI18n(); + const w = t.projectSettings.responseRoutes; + const labelId = useId(); + const [rules, setRules] = useState([]); + const [loading, setLoading] = useState(true); + const [loadError, setLoadError] = useState(""); + const [error, setError] = useState(""); + const [notice, setNotice] = useState(""); + const [draft, setDraft] = useState(null); + const [open, setOpen] = useState(false); + const [preview, setPreview] = useState(false); + const [busy, setBusy] = useState(false); + const [removeId, setRemoveId] = useState(null); + const mutation = useRef(false); + const alive = useRef(true); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + }; + }, []); + const close = () => { + if (!mutation.current) setOpen(false); + }; + const { dialog, onKeyDown } = useDialogFocus(close, open); + const load = useCallback(async () => { + setLoading(true); + setLoadError(""); + try { + const result = await projectsApi.listRouteRules(projectId); + if (alive.current) + setRules(result.rules.filter((rule) => rule.domainId === domainId && rule.spec.response)); + } catch (cause) { + if (alive.current) setLoadError(getApiErrorMessage(cause, w.loadFailed)); + } finally { + if (alive.current) setLoading(false); + } + }, [projectId, domainId, w.loadFailed]); + useEffect(() => { + void load(); + }, [load]); + + const update = (patch: Partial) => + setDraft((current) => current && { ...current, ...patch }); + const edit = (rule?: RouteRuleRow) => { + setDraft((current) => + current && current.id === rule?.id ? current : rule ? fromRule(rule) : blank(), + ); + setError(""); + setPreview(false); + setOpen(true); + }; + const run = async (operation: () => Promise) => { + if (mutation.current) return; + mutation.current = true; + setBusy(true); + setError(""); + setNotice(""); + try { + await operation(); + } catch (cause) { + if (alive.current) setError(getApiErrorMessage(cause, w.saveFailed)); + } finally { + mutation.current = false; + if (alive.current) setBusy(false); + } + }; + const save = () => + run(async () => { + if (!draft) return; + const path = normalizeResponsePath(draft.path); + const headers: Record = {}; + for (const row of draft.headers) { + if (!row.name && !row.value) continue; + const name = row.name.trim().toLowerCase(); + if (Object.hasOwn(headers, name)) throw new Error(w.duplicateHeader); + Object.defineProperty(headers, name, { value: row.value, enumerable: true }); + } + const response = normalizeEdgeResponse({ + match: draft.match, + status: Number(draft.status), + contentType: draft.contentType.trim(), + body: draft.body, + headers, + methods: draft.methods + .split(/[\s,]+/) + .filter(Boolean) + .map((value) => value.toUpperCase()), + }); + const input = { domainId, pathPrefix: path, spec: { response } }; + const result = draft.id + ? await projectsApi.updateRouteRule(projectId, draft.id, input) + : await projectsApi.createRouteRule(projectId, { ...input, enabled: true }); + if (!alive.current) return; + setRules((current) => [...current.filter((rule) => rule.id !== result.rule.id), result.rule]); + setDraft(null); + setOpen(false); + setNotice(result.rule.edgeApplied === true ? w.saved : w.pending); + }); + const toggle = (rule: RouteRuleRow) => + run(async () => { + const result = await projectsApi.updateRouteRule(projectId, rule.id, { + enabled: !rule.enabled, + }); + if (alive.current) { + setRules((current) => current.map((row) => (row.id === rule.id ? result.rule : row))); + setNotice(result.rule.edgeApplied === true ? w.saved : w.pending); + } + }); + const remove = (rule: RouteRuleRow) => + run(async () => { + const result = await projectsApi.deleteRouteRule(projectId, rule.id); + if (!alive.current) return; + setRules((current) => current.filter((row) => row.id !== rule.id)); + setRemoveId(null); + setNotice(result.edgeApplied === true ? w.saved : w.pending); + if (draft?.id === rule.id) setDraft(null); + }); + const contentTypes = [ + { value: "text/plain; charset=utf-8", label: w.plainText }, + { value: "application/json", label: "JSON" }, + { value: "text/html; charset=utf-8", label: "HTML" }, + { value: "application/xml", label: "XML" }, + ]; + const format = + draft && contentTypes.some((type) => type.value === draft.contentType) + ? draft.contentType + : "custom"; + const contentBytes = new TextEncoder().encode(draft?.body ?? "").length; + const fieldClass = "bg-muted/60 ring-1 ring-inset ring-border/50 focus:bg-muted/80"; + const bodyless = draft && [204, 205, 304].includes(Number(draft.status)); + + return ( +
+
+

{w.title}

+ +
+

{w.description}

+ {loading && ( +
+ )} + {loadError && ( +
+

+ {loadError} +

+ +
+ )} + {!open && error && ( +

+ {error} +

+ )} + {notice && ( +

+ {notice} +

+ )} +
+ {rules.map((rule) => { + const path = rule.pathPrefix || "/"; + const response = rule.spec.response!; + return ( +
+
+ + + +
+ {removeId === rule.id && ( +
+

{w.removeHint}

+ + +
+ )} +
+ ); + })} +
+ +
+
{ + event.preventDefault(); + void save(); + }} + className="flex min-h-0 flex-1 flex-col" + > +
+
+ +
+
+

+ {draft?.id ? w.edit : w.add} +

+

+ {hostname} +

+
+ + {w.staticResponse} + + +
+ {draft && ( +
+
+
+
+
+ +
+ {w.match} + update({ match })} + /> +
+
+

+ {draft.match === "exact" ? w.exactHint : w.prefixHint} +

+
+
+ +
+ {w.contentType} + + update({ contentType: value === "custom" ? "" : value }) + } + /> +
+
+ {format === "custom" && ( + + )} +
+
+
+ {[ + { value: false, label: w.body, icon: "code" as const }, + { value: true, label: w.preview, icon: "eye" as const }, + ].map((view) => ( + + ))} +
+ {preview ? ( +
{`HTTP/1.1 ${draft.status}\nContent-Type: ${draft.contentType}\n${draft.headers
+                            .filter((row) => row.name)
+                            .map((row) => `${row.name}: ${row.value}\n`)
+                            .join("")}\n${draft.body}`}
+ ) : ( +