Simplify publish diagnostics and preserve failure reports

This commit is contained in:
Oleg Isonen committed 2026-11-14 11:28:59 +00:00
1 parent ba0212cfb7
commit 2d021f406e
16 files changed
+2947 -1835

No files matched your search

@@ -0,0 +1,86 @@
import type { PublishValidationFinding } from "./diagnostics";
import type { PublishLog } from "./use-publish-logs";
import { publishLogStatus } from "./constants";
export const getDiagnosticsReport = ({
findings,
items,
canViewPublishLogs,
includeLatestPublishFindings = true,
}: {
findings: PublishValidationFinding[];
items: PublishLog[];
canViewPublishLogs: boolean;
includeLatestPublishFindings?: boolean;
}) => {
const latestPublish = includeLatestPublishFindings ? items[0] : undefined;
const reportFindings = [
...findings,
...(latestPublish?.findings ?? []),
...(latestPublish?.target === "static" && latestPublish.status === "failed"
? [
{
severity: "error" as const,
source: "publish" as const,
buildId: latestPublish.buildId,
title: publishLogStatus.failed.text,
reportText: publishLogStatus.failed.text,
},
]
: []),
...(canViewPublishLogs
? (latestPublish?.issues?.map<PublishValidationFinding>((issue) => ({
severity: issue.severity,
source: "build" as const,
title: issue.message,
reportText: `${issue.severity.toUpperCase()}: ${issue.message}`,
})) ?? [])
: []),
].filter(
(finding, index, all) =>
all.findIndex(
(other) =>
other.source === finding.source &&
other.buildId === finding.buildId &&
other.reportText === finding.reportText
) === index
);
const findingTabs = [
{
value: "warnings" as const,
label: "Warnings",
findings: reportFindings.filter(({ severity }) => severity === "warning"),
},
{
value: "errors" as const,
label: "Errors",
findings: reportFindings.filter(({ severity }) => severity === "error"),
},
];
const populatedTabs = findingTabs.filter(
({ findings }) => findings.length > 0
);
const orderedItems = [...items].reverse();
const reportText = reportFindings
.map(({ reportText }) => reportText)
.join("\n\n");
const publishText = orderedItems
.filter(
(item) => item.logState === "available" && item.logText !== undefined
)
.map((item) =>
[
...(item.domains.length > 0 ? item.domains : ["Static export"]),
item.logText,
].join("\n")
)
.join("\n\n");
return {
findings: reportFindings,
tabs: populatedTabs,
publishes: orderedItems,
reportText,
publishText,
issuesOmitted: latestPublish?.issuesOmitted,
};
};
@@ -68,6 +68,45 @@ const openDetails = (element: HTMLElement) => {
act(() => button?.click());
};
test("keeps audit and build findings in severity tabs, not in publish logs", async () => {
render(
[],
true,
[
{
buildId: "build-separated",
target: "site",
domains: ["example.com"],
status: "failed",
findings: [createFinding("warning", 42)],
issues: [{ severity: "error", message: "build-issue-42" }],
logState: "available",
logText: "runner-output-42",
},
],
undefined,
true
);
const tabs = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
);
expect(tabs).toHaveLength(3);
const publishTab = tabs.find((tab) => tab.textContent === "Publish")!;
await act(async () => userEvent.click(publishTab));
const active = document.body.querySelector(
'[role="tabpanel"][data-state="active"]'
)!;
expect(active.textContent).toContain("runner-output-42");
expect(active.textContent).not.toContain("warning-42");
expect(active.textContent).not.toContain("build-issue-42");
const warningsTab = tabs.find((tab) => tab.textContent === "Warnings")!;
await act(async () => userEvent.click(warningsTab));
expect(document.body.textContent).toContain("warning-42");
const errorsTab = tabs.find((tab) => tab.textContent === "Errors")!;
await act(async () => userEvent.click(errorsTab));
expect(document.body.textContent).toContain("build-issue-42");
});
test.each(["findings", "details", "publish"] as const)(
"scrolls overflowing %s with the native scroll container",
async (view) => {
@@ -455,6 +494,14 @@ test("collapses each complete publish and copies its full log from the header",
await act(async () => userEvent.click(copyButtons[0]!));
expect(writeText).toHaveBeenCalledWith("Complete second publish log");
expect(triggers[0]?.getAttribute("aria-expanded")).toBe("true");
const keyboardCopy = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Copy log"]'
)!;
expect(keyboardCopy.parentElement?.closest("button")).toBeNull();
act(() => keyboardCopy.focus());
await act(async () => userEvent.keyboard("{Enter}"));
expect(writeText).toHaveBeenCalledTimes(2);
expect(triggers[0]?.getAttribute("aria-expanded")).toBe("true");
});
test("can maximize Diagnostics and aligns publish content with its title", async () => {
@@ -513,6 +560,7 @@ test("publish failure is plain text and links to the Publish tab", async () => {
severity: "error",
source: "publish",
title: "Build failed before deployment",
buildId: "build-1",
summary: "Build failed before deployment",
reportText: "Build failed before deployment",
},
@@ -561,6 +609,7 @@ test("Free publish failures link to a Publish upgrade banner without exposing lo
severity: "error",
source: "publish",
title: "Publish failed",
buildId: "build-1",
reportText: "Publish failed",
},
],
@@ -665,6 +714,45 @@ test("pre-dispatch failure has no link to an absent Publish tab", () => {
).toBe(false);
});
test.each([true, false])(
"pre-dispatch failure does not link an older publish (paid: %s)",
(paid) => {
render(
[
{
severity: "error",
source: "publish",
title: "new-request-rejection",
reportText: "new-request-rejection",
},
],
paid,
[
{
buildId: "old-build",
target: "site",
domains: ["example.com"],
status: "success",
findings: [],
logState: "available",
logText: "old-output",
},
],
undefined,
true
);
expect(
document.body.querySelector('[role="tab"][aria-selected="true"]')
?.textContent
).toBe("Errors");
expect(
Array.from(document.body.querySelectorAll("button")).some(
(button) => button.textContent === "show logs"
)
).toBe(false);
}
);
test("Free audit summaries do not expose long cached details", () => {
const longSummary = `Short reason ${"private context ".repeat(30)}`;
const element = render(
@@ -1,3 +1,4 @@
import { getDiagnosticsReport } from "./diagnostics-utils";
import { Fragment, useEffect, useState, type ReactNode } from "react";
import {
Button,
@@ -38,6 +39,7 @@ export type PublishValidationFinding = {
link?: ReactNode;
relatedInstanceId?: string;
reportText: string;
buildId?: string;
};
const shortFinding = (finding: PublishValidationFinding) =>
@@ -96,11 +98,15 @@ const FindingList = ({
canViewPublishLogs,
onSelect,
onOpenPublish,
issuesOmitted = 0,
publishBuildIds,
}: {
findings: PublishValidationFinding[];
canViewPublishLogs: boolean;
onSelect: (finding: PublishValidationFinding) => void;
onOpenPublish?: () => void;
issuesOmitted?: number;
publishBuildIds: string[];
}) => (
<ScrollAreaNative css={{ height: "100%" }}>
<PanelContent as={Flex} direction="column" gap={3}>
@@ -115,22 +121,24 @@ const FindingList = ({
{finding.source === "publish" ? (
<Text variant="labels" userSelect="text">
{canViewPublishLogs ? finding.title : shortFinding(finding)}
{onOpenPublish !== undefined && (
<>
{" "}
<Link
as="button"
type="button"
variant="inherit"
color="inherit"
underline="always"
css={{ border: 0, padding: 0, background: "none" }}
onClick={onOpenPublish}
>
show logs
</Link>
</>
)}
{onOpenPublish !== undefined &&
finding.buildId !== undefined &&
publishBuildIds.includes(finding.buildId) && (
<>
{" "}
<Link
as="button"
type="button"
variant="inherit"
color="inherit"
underline="always"
css={{ border: 0, padding: 0, background: "none" }}
onClick={onOpenPublish}
>
show logs
</Link>
</>
)}
</Text>
) : canViewPublishLogs ? (
<Button
@@ -149,10 +157,205 @@ const FindingList = ({
{index < findings.length - 1 && <Separator />}
</Fragment>
))}
{canViewPublishLogs && issuesOmitted > 0 && (
<Text color="subtle">{issuesOmitted} more issues not shown.</Text>
)}
</PanelContent>
</ScrollAreaNative>
);
const FindingDetails = ({
finding,
onBack,
onNavigate,
}: {
finding: PublishValidationFinding;
onBack: () => void;
onNavigate: () => void;
}) => (
<PanelContent
as={Flex}
direction="column"
gap={3}
css={{ minHeight: 0, flex: 1 }}
>
<Button type="button" color="neutral" onClick={onBack}>
Back
</Button>
<Text variant="titles" userSelect="text">
{finding.title}
</Text>
{finding.details !== undefined && (
<ScrollAreaNative css={{ minHeight: 0, flex: 1 }}>
<Text css={{ userSelect: "text" }}>{finding.details}</Text>
</ScrollAreaNative>
)}
<div
onClick={(event) => {
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
onNavigate();
}}
>
{finding.link}
</div>
</PanelContent>
);
const PublishHistoryEntry = ({
item,
defaultOpen,
canViewPublishLogs,
}: {
item: PublishLog;
defaultOpen: boolean;
canViewPublishLogs: boolean;
}) => {
const duration = getPublishDuration(item);
return (
<Collapsible.Root asChild defaultOpen={defaultOpen}>
<Flex direction="column" gap={2}>
<Collapsible.Trigger asChild>
<SectionTitle
aria-labelledby={`publish-title-${item.buildId}`}
suffixPlaceholder={<CopyIcon aria-hidden />}
suffix={
canViewPublishLogs &&
item.logState === "available" &&
item.logText !== undefined && (
<CopyToClipboard text={item.logText} copyText="Copy log">
<IconButton
type="button"
aria-label="Copy log"
onPointerDown={(event) => event.stopPropagation()}
>
<CopyIcon aria-hidden />
</IconButton>
</CopyToClipboard>
)
}
>
<Text
as="span"
id={`publish-title-${item.buildId}`}
variant="titles"
truncate
css={{ flex: "0 1 auto", minWidth: 0 }}
>
{item.domains.length > 0
? item.domains.join(", ")
: "Static export"}
</Text>
</SectionTitle>
</Collapsible.Trigger>
<Collapsible.Content asChild>
<Flex
direction="column"
gap={2}
css={{
paddingInline: theme.panel.paddingInline,
}}
>
<Text color="subtle">{publishLogStatus[item.status].text}</Text>
{canViewPublishLogs && item.startedAt !== undefined && (
<Text>Started: {new Date(item.startedAt).toLocaleString()}</Text>
)}
{canViewPublishLogs && duration !== undefined && (
<Text>Duration: {duration}s</Text>
)}
{canViewPublishLogs &&
item.status === "failed" &&
(item.failedStage !== undefined || item.code !== undefined) && (
<Text color="destructive">
{[item.failedStage, item.code?.replaceAll("_", " ")]
.filter(Boolean)
.join(" · ")}
</Text>
)}
{canViewPublishLogs &&
item.status !== "pending" &&
(item.logState === "available" ? (
<Text
as="pre"
variant="mono"
userSelect="text"
css={{
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
}}
>
{item.logText}
</Text>
) : (
<Text color="subtle">
{item.logHandle === undefined ||
item.logState === "unavailable"
? "Publish logs are unavailable."
: "Loading logs…"}
</Text>
))}
</Flex>
</Collapsible.Content>
<Separator />
</Flex>
</Collapsible.Root>
);
};
const PublishHistory = ({
items,
canViewPublishLogs,
onLoadLog,
}: {
items: PublishLog[];
canViewPublishLogs: boolean;
onLoadLog?: (item: PublishLog) => void;
}) => {
useEffect(() => {
if (!canViewPublishLogs) {
return;
}
for (const item of items) {
if (
item.status !== "pending" &&
item.logHandle !== undefined &&
item.logState === undefined
) {
onLoadLog?.(item);
}
}
}, [canViewPublishLogs, items, onLoadLog]);
return (
<ScrollAreaNative css={{ height: "100%" }}>
<PanelContent as={Flex} direction="column" gap={3}>
{!canViewPublishLogs && (
<PanelBanner variant="info" role="note">
<Text>Upgrade to Pro to view publish logs.</Text>
</PanelBanner>
)}
{items.length === 0 && (
<Text color="subtle">No publishes in this session.</Text>
)}
{items.map((item, index) => (
<PublishHistoryEntry
key={item.buildId}
item={item}
defaultOpen={index === items.length - 1}
canViewPublishLogs={canViewPublishLogs}
/>
))}
</PanelContent>
</ScrollAreaNative>
);
};
export const PublishDiagnosticsDialog = ({
findings,
open,
@@ -161,6 +364,7 @@ export const PublishDiagnosticsDialog = ({
initialTab,
items = [],
canViewPublishLogs = true,
includeLatestPublishFindings = true,
onLoadLog,
}: {
findings: PublishValidationFinding[];
@@ -170,6 +374,7 @@ export const PublishDiagnosticsDialog = ({
initialTab?: "warnings" | "errors" | "publish";
items?: PublishLog[];
canViewPublishLogs?: boolean;
includeLatestPublishFindings?: boolean;
onLoadLog?: (item: PublishLog) => void;
}) => {
const [internalOpen, setInternalOpen] = useState(false);
@@ -177,33 +382,29 @@ export const PublishDiagnosticsDialog = ({
useState<PublishValidationFinding>();
const isOpen = open ?? internalOpen;
const setIsOpen = onOpenChange ?? setInternalOpen;
const errors = findings.filter(({ severity }) => severity === "error");
const warnings = findings.filter(({ severity }) => severity === "warning");
const defaultTab = initialTab ?? (errors.length > 0 ? "errors" : "warnings");
const {
findings: reportFindings,
tabs,
publishes: orderedItems,
reportText,
publishText,
issuesOmitted,
} = getDiagnosticsReport({
findings,
items,
canViewPublishLogs,
includeLatestPublishFindings,
});
const defaultTab = initialTab ?? tabs.at(-1)?.value ?? "publish";
const [tab, setTab] = useState(defaultTab);
const orderedItems = [...items].reverse();
const activeTab =
(tab === "warnings" && warnings.length > 0) ||
(tab === "errors" && errors.length > 0) ||
(tab === "publish" && items.length > 0)
(tab === "publish" && items.length > 0) ||
tabs.some(({ value }) => value === tab)
? tab
: errors.length > 0
? "errors"
: warnings.length > 0
? "warnings"
: "publish";
const reportText = findings.map(({ reportText }) => reportText).join("\n\n");
const publishText = orderedItems
.filter(
(item) => item.logState === "available" && item.logText !== undefined
)
.map((item) =>
[
...(item.domains.length > 0 ? item.domains : ["Static export"]),
item.logText,
].join("\n")
)
.join("\n\n");
: (tabs.at(-1)?.value ?? "publish");
const copyText = activeTab === "publish" ? publishText : reportText;
useEffect(() => {
@@ -217,22 +418,7 @@ export const PublishDiagnosticsDialog = ({
}
}, [canViewPublishLogs]);
useEffect(() => {
if (isOpen === false || activeTab !== "publish" || !canViewPublishLogs) {
return;
}
for (const item of items) {
if (
item.status !== "pending" &&
item.logHandle !== undefined &&
item.logState === undefined
) {
onLoadLog?.(item);
}
}
}, [activeTab, canViewPublishLogs, isOpen, items, onLoadLog]);
if (open === undefined && findings.length === 0) {
if (open === undefined && reportFindings.length === 0 && items.length === 0) {
return null;
}
@@ -240,7 +426,7 @@ export const PublishDiagnosticsDialog = ({
<>
{open === undefined && (
<PublishValidationBanner
findings={findings}
findings={reportFindings}
onOpen={() => setIsOpen(true)}
/>
)}
@@ -274,46 +460,11 @@ export const PublishDiagnosticsDialog = ({
Diagnostics
</DialogTitle>
{selectedFinding !== undefined && canViewPublishLogs ? (
<PanelContent
as={Flex}
direction="column"
gap={3}
css={{ minHeight: 0, flex: 1 }}
>
<Button
type="button"
color="neutral"
onClick={() => setSelectedFinding(undefined)}
>
Back
</Button>
<Text variant="titles" userSelect="text">
{selectedFinding.title}
</Text>
{selectedFinding.details !== undefined && (
<ScrollAreaNative css={{ minHeight: 0, flex: 1 }}>
<Text css={{ userSelect: "text" }}>
{selectedFinding.details}
</Text>
</ScrollAreaNative>
)}
<div
onClick={(event) => {
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
setIsOpen(false);
}}
>
{selectedFinding.link}
</div>
</PanelContent>
<FindingDetails
finding={selectedFinding}
onBack={() => setSelectedFinding(undefined)}
onNavigate={() => setIsOpen(false)}
/>
) : (
<PanelTabs
value={activeTab}
@@ -321,208 +472,42 @@ export const PublishDiagnosticsDialog = ({
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
>
<PanelTabsList aria-label="Publish check severity">
{warnings.length > 0 && (
<PanelTabsTrigger value="warnings">Warnings</PanelTabsTrigger>
)}
{errors.length > 0 && (
<PanelTabsTrigger value="errors">Errors</PanelTabsTrigger>
)}
{tabs.map(({ value, label }) => (
<PanelTabsTrigger key={value} value={value}>
{label}
</PanelTabsTrigger>
))}
{items.length > 0 && (
<PanelTabsTrigger value="publish">Publish</PanelTabsTrigger>
)}
</PanelTabsList>
<PanelTabsContent
value="warnings"
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
>
<FindingList
findings={warnings}
canViewPublishLogs={canViewPublishLogs}
onSelect={setSelectedFinding}
onOpenPublish={
items.length > 0 ? () => setTab("publish") : undefined
}
/>
</PanelTabsContent>
<PanelTabsContent
value="errors"
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
>
<FindingList
findings={errors}
canViewPublishLogs={canViewPublishLogs}
onSelect={setSelectedFinding}
onOpenPublish={
items.length > 0 ? () => setTab("publish") : undefined
}
/>
</PanelTabsContent>
{tabs.map(({ value, findings }) => (
<PanelTabsContent
key={value}
value={value}
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
>
<FindingList
findings={findings}
canViewPublishLogs={canViewPublishLogs}
issuesOmitted={issuesOmitted}
publishBuildIds={items.map(({ buildId }) => buildId)}
onSelect={setSelectedFinding}
onOpenPublish={
items.length > 0 ? () => setTab("publish") : undefined
}
/>
</PanelTabsContent>
))}
<PanelTabsContent
value="publish"
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
>
<ScrollAreaNative css={{ height: "100%" }}>
<PanelContent as={Flex} direction="column" gap={3}>
{!canViewPublishLogs && (
<PanelBanner variant="info" role="note">
<Text>Upgrade to Pro to view publish logs.</Text>
</PanelBanner>
)}
{items.length === 0 && (
<Text color="subtle">No publishes in this session.</Text>
)}
{orderedItems.map((item, index) => {
const duration = getPublishDuration(item);
return (
<Collapsible.Root
key={item.buildId}
asChild
defaultOpen={index === orderedItems.length - 1}
>
<Flex direction="column" gap={2}>
<Collapsible.Trigger asChild>
<SectionTitle
aria-labelledby={`publish-title-${item.buildId}`}
suffixPlaceholder={<CopyIcon aria-hidden />}
suffix={
canViewPublishLogs &&
item.logState === "available" &&
item.logText !== undefined && (
<CopyToClipboard
text={item.logText}
copyText="Copy log"
>
<IconButton
type="button"
aria-label="Copy log"
onPointerDown={(event) =>
event.stopPropagation()
}
>
<CopyIcon aria-hidden />
</IconButton>
</CopyToClipboard>
)
}
>
<Text
as="span"
id={`publish-title-${item.buildId}`}
variant="titles"
truncate
css={{ flex: "0 1 auto", minWidth: 0 }}
>
{item.domains.length > 0
? item.domains.join(", ")
: "Static export"}
</Text>
</SectionTitle>
</Collapsible.Trigger>
<Collapsible.Content asChild>
<Flex
direction="column"
gap={2}
css={{
paddingInline: theme.panel.paddingInline,
}}
>
<Text color="subtle">
{publishLogStatus[item.status].text}
</Text>
{canViewPublishLogs &&
item.startedAt !== undefined && (
<Text>
Started:{" "}
{new Date(
item.startedAt
).toLocaleString()}
</Text>
)}
{canViewPublishLogs &&
duration !== undefined && (
<Text>Duration: {duration}s</Text>
)}
{canViewPublishLogs &&
item.status === "failed" &&
(item.failedStage !== undefined ||
item.code !== undefined) && (
<Text color="destructive">
{[
item.failedStage,
item.code?.replaceAll("_", " "),
]
.filter(Boolean)
.join(" · ")}
</Text>
)}
{canViewPublishLogs &&
item.status !== "pending" &&
(item.logState === "available" ? (
<Text
as="pre"
variant="mono"
userSelect="text"
css={{
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
}}
>
{item.logText}
</Text>
) : (
<Text color="subtle">
{item.logHandle === undefined ||
item.logState === "unavailable"
? "Publish logs are unavailable."
: "Loading logs…"}
</Text>
))}
{item.findings.length > 0 && (
<Flex direction="column" gap={1}>
<Text variant="labels">Audit</Text>
{item.findings.map((finding, index) => (
<Text key={index}>
{canViewPublishLogs
? (finding.summary ?? finding.title)
: shortFinding(finding)}
</Text>
))}
</Flex>
)}
{canViewPublishLogs &&
item.issues !== undefined &&
item.issues.length > 0 && (
<Text variant="labels">Build</Text>
)}
{canViewPublishLogs &&
item.issues?.map((issue, index) => (
<Text
key={index}
color={
issue.severity === "error"
? "destructive"
: "subtle"
}
>
{issue.message}
</Text>
))}
{canViewPublishLogs &&
(item.issuesOmitted ?? 0) > 0 && (
<Text color="subtle">
{item.issuesOmitted} more issues not
shown.
</Text>
)}
</Flex>
</Collapsible.Content>
<Separator />
</Flex>
</Collapsible.Root>
);
})}
</PanelContent>
</ScrollAreaNative>
<PublishHistory
items={orderedItems}
canViewPublishLogs={canViewPublishLogs}
onLoadLog={onLoadLog}
/>
</PanelTabsContent>
</PanelTabs>
)}
@@ -0,0 +1,39 @@
import type { ReactNode } from "react";
import { IconButton, Tooltip } from "@webstudio-is/design-system";
import type { AlertIcon } from "@webstudio-is/icons";
import { publishLogStatus } from "./constants";
import type { PublishLog } from "./use-publish-logs";
export const DomainPublishStatus = ({
domain,
buildId,
latestLog,
fallback,
onOpenReport,
}: {
domain: string;
buildId?: string;
latestLog?: Pick<PublishLog, "buildId" | "status">;
fallback: { Icon: typeof AlertIcon; color: string; text: ReactNode };
onOpenReport?: () => void;
}) => {
const currentLog = latestLog?.buildId === buildId ? latestLog : undefined;
const { Icon, color, text } =
currentLog === undefined ? fallback : publishLogStatus[currentLog.status];
return (
<Tooltip content={text}>
<IconButton
type="button"
aria-label={`Publish log: ${domain}`}
css={{ color }}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
onOpenReport?.();
}}
>
<Icon />
</IconButton>
</Tooltip>
);
};
@@ -1,8 +1,10 @@
import { act } from "react-dom/test-utils";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, expect, test } from "vitest";
import { afterEach, expect, test, vi } from "vitest";
import { TooltipProvider } from "@webstudio-is/design-system";
import { __testing__, PENDING_TIMEOUT, type Domain } from "./domains";
import { __testing__, type Domain } from "./domains";
import { PENDING_TIMEOUT } from "./publish-status";
import type { PublishLog } from "./use-publish-logs";
const { StatusIcon } = __testing__;
let root: Root | undefined;
@@ -21,8 +23,19 @@ afterEach(() => {
const renderStatus = (
publishStatus: "PENDING" | "PUBLISHED" | "FAILED" | undefined,
age = 0,
isLoading = false
{
age = 0,
isLoading = false,
latestLog,
onOpenReport,
onSectionClick,
}: {
age?: number;
isLoading?: boolean;
latestLog?: PublishLog;
onOpenReport?: (domain: string) => void;
onSectionClick?: () => void;
} = {}
) => {
if (container === undefined) {
container = document.createElement("div");
@@ -34,21 +47,30 @@ const renderStatus = (
root = createRoot(container);
}
const projectDomain = {
domain: "example.com",
status: "ACTIVE",
verified: true,
latestBuildVirtual:
publishStatus === undefined
? null
: {
buildId: "current-build",
publishStatus,
createdAt: new Date(Date.now() - age).toISOString(),
},
} as Domain;
act(() =>
root?.render(
<TooltipProvider>
<StatusIcon projectDomain={projectDomain} isLoading={isLoading} />
</TooltipProvider>
<div onClick={onSectionClick}>
<TooltipProvider>
<StatusIcon
projectDomain={projectDomain}
isLoading={isLoading}
latestLog={latestLog}
onOpenReport={onOpenReport}
/>
</TooltipProvider>
</div>
)
);
const icon = container.querySelector("svg");
@@ -69,8 +91,10 @@ test.each([
test("keeps status loading neutral and expired publishing red", () => {
expect(renderStatus("PENDING")).toBe("rgb(200, 160, 0)");
expect(renderStatus("PENDING", 0, true)).toBe("rgb(100, 100, 100)");
expect(renderStatus("PENDING", PENDING_TIMEOUT + 1000)).toBe(
expect(renderStatus("PENDING", { isLoading: true })).toBe(
"rgb(100, 100, 100)"
);
expect(renderStatus("PENDING", { age: PENDING_TIMEOUT + 1000 })).toBe(
"rgb(200, 0, 0)"
);
});
@@ -78,3 +102,54 @@ test("keeps status loading neutral and expired publishing red", () => {
test("does not show success for a domain that has never been published", () => {
expect(renderStatus(undefined)).toBe("rgb(100, 100, 100)");
});
test.each([
["pending", "rgb(200, 160, 0)"],
["failed", "rgb(200, 0, 0)"],
["success", "rgb(0, 160, 0)"],
] as const)(
"uses the matching %s session log instead of the persisted status",
(status, color) => {
expect(
renderStatus(status === "failed" ? "PUBLISHED" : "PENDING", {
age: PENDING_TIMEOUT + 1000,
latestLog: {
buildId: "current-build",
target: "site",
domains: ["example.com"],
findings: [],
status,
},
})
).toBe(color);
}
);
test("ignores a log for a different domain build", () => {
expect(
renderStatus("PUBLISHED", {
latestLog: {
buildId: "old-build",
target: "site",
domains: ["example.com"],
findings: [],
status: "failed",
},
})
).toBe("rgb(0, 160, 0)");
});
test("opening a domain report does not toggle the surrounding section", () => {
const onOpenReport = vi.fn();
const onSectionClick = vi.fn();
renderStatus("PUBLISHED", { onOpenReport, onSectionClick });
const event = new MouseEvent("click", { bubbles: true, cancelable: true });
act(() =>
container!
.querySelector('button[aria-label="Publish log: example.com"]')
?.dispatchEvent(event)
);
expect(onOpenReport).toHaveBeenCalledExactlyOnceWith("example.com");
expect(onSectionClick).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
});
@@ -18,11 +18,9 @@ import {
import type { Project } from "@webstudio-is/project";
import {
AlertIcon,
CheckCircleIcon,
CopyIcon,
HelpIcon,
InfoCircleIcon,
SpinnerIcon,
} from "@webstudio-is/icons";
import { CollapsibleDomainSection } from "./collapsible-domain-section";
import {
@@ -42,11 +40,11 @@ import { extractCname } from "./cname";
import { useEffectEvent } from "~/shared/hook-utils/effect-event";
import { DomainCheckbox } from "./domain-checkbox";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { RelativeTime } from "~/builder/shared/relative-time";
import { getPublishStatusAndText } from "./publish-status";
import { $currentSystem } from "~/shared/system";
import { getPublishUrl } from "./publish-url";
import type { PublishLog } from "./use-publish-logs";
import { publishLogStatus } from "./constants";
import { DomainPublishStatus } from "./domain-publish-status";
export type Domain = Project["domainsVirtual"][number];
@@ -63,54 +61,6 @@ export const getStatus = (projectDomain: Domain) =>
? (`VERIFIED_${projectDomain.status}` as const)
: `UNVERIFIED`;
export const PENDING_TIMEOUT =
process.env.NODE_ENV === "production" ? 60 * 3 * 1000 : 35000;
export const getPublishStatusAndText = ({
createdAt,
publishStatus,
}: Pick<
NonNullable<Domain["latestBuildVirtual"]>,
"createdAt" | "publishStatus"
>) => {
let status = publishStatus;
const delta = Date.now() - new Date(createdAt).getTime();
// Assume build failed after 3 minutes
if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) {
status = "FAILED";
}
const textStart =
status === "PUBLISHED"
? "Published"
: status === "FAILED"
? "Publish failed"
: "Publishing started";
const statusText = (
<>
{textStart} <RelativeTime time={new Date(createdAt)} />
</>
);
const color =
status === "PUBLISHED"
? cssVar("--foreground-positive")
: status === "FAILED"
? cssVar("--foreground-negative")
: cssVar("--foreground-warning");
const Icon =
status === "PUBLISHED"
? CheckCircleIcon
: status === "FAILED"
? AlertIcon
: SpinnerIcon;
return { statusText, status, color, Icon };
};
const getStatusText = (props: {
projectDomain: Domain;
isLoading: boolean;
@@ -172,28 +122,14 @@ const StatusIcon = (props: {
onOpenReport?: (domain: string) => void;
}) => {
const fallback = getStatusText(props);
const latestLog =
props.latestLog?.buildId === props.projectDomain.latestBuildVirtual?.buildId
? props.latestLog
: undefined;
const { Icon, color, text } =
latestLog === undefined ? fallback : publishLogStatus[latestLog.status];
return (
<Tooltip content={text}>
<IconButton
type="button"
aria-label={`Publish log: ${props.projectDomain.domain}`}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
props.onOpenReport?.(props.projectDomain.domain);
}}
css={{ color }}
>
<Icon />
</IconButton>
</Tooltip>
<DomainPublishStatus
domain={props.projectDomain.domain}
buildId={props.projectDomain.latestBuildVirtual?.buildId}
latestLog={props.latestLog}
fallback={fallback}
onOpenReport={() => props.onOpenReport?.(props.projectDomain.domain)}
/>
);
};
const DomainItem = ({
@@ -9,7 +9,7 @@ import {
test,
vi,
} from "vitest";
import { TooltipProvider } from "@webstudio-is/design-system";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
@@ -27,6 +27,8 @@ let nanoStates: typeof import("~/shared/nano-states");
let builderStates: typeof import("~/builder/shared/nano-states");
const requests: Array<{ path: string; input: unknown }> = [];
let publishResponse: unknown = { success: false, error: "Publish blocked" };
let jobStatus: "failed" | "success" = "failed";
let didPublish = false;
beforeAll(async () => {
Object.defineProperty(Element.prototype, "scrollIntoView", {
@@ -42,19 +44,65 @@ beforeAll(async () => {
requestInit?.body === undefined
? JSON.parse(url.searchParams.get("input") ?? "{}")
: JSON.parse(String(requestInit.body));
requests.push({ path: url.pathname, input });
let data: unknown;
switch (url.pathname) {
case "/trpc/domain.publish":
data = publishResponse;
break;
case "/trpc/api.publish.getJob":
data = { status: "failed", code: "BUILD_FAILED" };
break;
default:
throw new Error(`Unexpected request: ${url.pathname}`);
}
return new Response(JSON.stringify([{ result: { data } }]), {
const results = url.pathname
.slice("/trpc/".length)
.split(",")
.map((route, index) => {
const path = `/trpc/${route}`;
requests.push({ path, input: { "0": input[String(index)] } });
let data: unknown;
switch (path) {
case "/trpc/domain.publish":
if (publishResponse instanceof Error) {
throw publishResponse;
}
data = publishResponse;
didPublish = (publishResponse as { success: boolean }).success;
break;
case "/trpc/api.publish.getJob":
data = { status: jobStatus, code: "BUILD_FAILED" };
break;
case "/trpc/domain.project":
data = {
success: true,
project: {
id: "project-1",
domain: "example",
domainsVirtual: [],
latestBuildVirtual: didPublish
? {
domain: "example",
buildId: "build-1",
createdAt: new Date().toISOString(),
publishStatus:
jobStatus === "success" ? "PUBLISHED" : "FAILED",
}
: null,
},
};
break;
case "/trpc/domain.countTotalDomains":
data = { success: true, data: 0 };
break;
case "/trpc/project.userPublishCount":
data = { success: true, data: 0, limit: 100 };
break;
default:
return {
error: {
message: `Unexpected request: ${path}`,
code: -32603,
data: {
code: "INTERNAL_SERVER_ERROR",
httpStatus: 500,
path: route,
},
},
};
}
return { result: { data } };
});
return new Response(JSON.stringify(results), {
headers: { "Content-Type": "application/json" },
});
}
@@ -71,6 +119,85 @@ beforeEach(() => {
reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
publishResponse = { success: false, error: "Publish blocked" };
requests.length = 0;
jobStatus = "failed";
didPublish = false;
});
test("a successful site runner finishes the current publish and retains its report", async () => {
jobStatus = "success";
publishResponse = {
success: true,
buildId: "build-1",
logHandle: "log-handle",
findings: [],
};
stores.$project.set({
id: "project-1",
domain: "example",
domainsVirtual: [],
latestStaticBuild: null,
} as unknown as Project);
nanoStates.$authTokenPermissions.set({
canClone: true,
canCopy: true,
canPublish: true,
});
builderStates.$publishDialog.set("publish");
resetStores = () => {
stores.$project.set(undefined);
builderStates.$publishDialog.set("none");
};
const container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
await act(async () =>
root?.render(
<TooltipProvider>
<publishModule.PublishButton projectId="project-1" />
</TooltipProvider>
)
);
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
)!;
if (domain.checked === false) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
const publish = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
)
.filter((button) => button.textContent === "Publish")
.at(-1)!;
await act(async () => publish.click());
await act(async () =>
vi.waitFor(() =>
expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("build-1")
)
);
expect(requests.map(({ path }) => path)).toContain(
"/trpc/api.publish.getJob"
);
expect(publish.disabled).toBe(false);
const report = document.body.querySelector<HTMLButtonElement>(
'button[aria-label^="Publish log:"]'
)!;
await act(async () => report.click());
expect(
document.body.querySelector('[role="tab"][aria-selected="true"]')
?.textContent
).toBe("Publish");
expect(
document.body.querySelector(
'[role="tabpanel"][data-state="active"] button[aria-expanded]'
)
).not.toBeNull();
// The status label is the public result of a completed publish.
expect(
document.body.querySelector('[role="tabpanel"][data-state="active"]')
?.textContent
).toContain("Published");
});
afterEach(() => {
@@ -81,6 +208,7 @@ afterEach(() => {
root = undefined;
resetStores = undefined;
document.body.innerHTML = "";
vi.restoreAllMocks();
});
afterAll(() => {
@@ -221,15 +349,23 @@ test("keeps Diagnostics visible but disabled before there is anything to show",
).find((item) => item.textContent?.trim() === "Diagnostics");
expect(diagnostics).toBeDefined();
expect(diagnostics?.getAttribute("data-disabled")).not.toBeNull();
expect(
requests.filter(({ path }) => path === "/trpc/project.userPublishCount")
).toHaveLength(1);
});
test.each([
["Validate", "Errors", false],
["Publish", "Errors", false],
["Publish", "Publish", true],
["Validate", "Errors", false, false],
["Publish", "Errors", false, false],
["Publish", "Publish", true, false],
["Publish", "Errors", false, true],
] as const)(
"%s keeps the result in the popover until See issues opens %s",
async (action, expectedTab, accepted) => {
async (action, expectedTab, accepted, transport) => {
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
if (transport) {
publishResponse = new Error("transport-failure");
}
if (accepted) {
publishResponse = {
success: true,
@@ -306,6 +442,9 @@ test.each([
}
expect(builderStates.$publishDialog.get()).toBe("publish");
if (action === "Validate" || transport) {
expect(errorToast).not.toHaveBeenCalled();
}
if (accepted) {
expect(requests.map(({ path }) => path)).toContain(
"/trpc/api.publish.getJob"
@@ -315,6 +454,12 @@ test.each([
const seeIssues = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
).find((button) => button.textContent?.trim() === "See issues");
if (transport) {
// The transport error payload must remain visible in the popover banner.
expect(seeIssues?.parentElement?.textContent).toContain(
"transport-failure"
);
}
await act(async () => seeIssues?.click());
expect(builderStates.$publishDialog.get()).toBe("none");
expect(document.body.querySelector('[role="tablist"]')).not.toBeNull();
@@ -6,7 +6,7 @@ import { TooltipProvider, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import { $publishDialog } from "~/builder/shared/nano-states";
import { $project } from "~/shared/sync/data-stores";
import { __testing__ } from "./publish";
import { __testing__ } from "./use-publish-progress";
import { DomainCheckbox, domainToPublishName } from "./domain-checkbox";
import { PublishDiagnosticsDialog } from "./diagnostics";
@@ -563,7 +563,7 @@ test("an old poll cannot update a newly mounted copy of the same project", async
expect($project.get()).toBe(reopenedProject);
});
test("publish failure shows a toast while the Publish panel is open", () => {
test("publish failure updates the banner without a duplicate toast while Publish is open", () => {
const successToast = vi.spyOn(toast, "success").mockImplementation(() => "");
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
const setPublishError = vi.fn();
@@ -585,7 +585,7 @@ test("publish failure shows a toast while the Publish panel is open", () => {
});
expect(successToast).not.toHaveBeenCalled();
expect(errorToast).toHaveBeenCalledOnce();
expect(errorToast).not.toHaveBeenCalled();
expect(setPublishError).toHaveBeenCalledOnce();
});
@@ -648,10 +648,10 @@ test("publish completion shows a toast after the dialog closes", () => {
expect(successToast).toHaveBeenCalledOnce();
expect(errorToast).toHaveBeenCalledOnce();
expect(setPublishError).toHaveBeenCalledWith(failedStatusText);
expect(setPublishError).toHaveBeenCalledWith(failedStatusText, undefined);
});
test("a rejected publish request shows a toast while the dialog is open", async () => {
test("a rejected publish request updates the banner without a duplicate toast", async () => {
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
$publishDialog.set("publish");
$project.set({ id: "project" } as Project);
@@ -683,7 +683,7 @@ test("a rejected publish request shows a toast while the dialog is open", async
expect(container.querySelector("output")?.textContent).toBe(
"Network unavailable"
);
expect(errorToast).toHaveBeenCalledOnce();
expect(errorToast).not.toHaveBeenCalled();
});
test("starting validation clears a previous request failure", async () => {
@@ -756,7 +756,7 @@ test("a rejected publish request shows a toast after the dialog closes", async (
);
});
test("a rejected publish request shows a toast after the panel reopens", async () => {
test("a rejected publish request does not duplicate its banner after the panel reopens", async () => {
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
$publishDialog.set("publish");
$project.set({ id: "project" } as Project);
@@ -806,7 +806,7 @@ test("a rejected publish request shows a toast after the panel reopens", async (
expect(container.querySelector("output")?.textContent).toBe(
"Network unavailable"
);
expect(errorToast).toHaveBeenCalledOnce();
expect(errorToast).not.toHaveBeenCalled();
});
test("a publish failure remains available after the panel remounts", () => {
@@ -848,7 +848,7 @@ test("a publish failure remains available after the panel remounts", () => {
act(() => finish.click());
expect(container.querySelector("output")?.textContent).toBe("Build failed");
expect(errorToast).toHaveBeenCalledOnce();
expect(errorToast).not.toHaveBeenCalled();
});
test("a successful status refresh clears a persisted publish failure", () => {
@@ -1121,7 +1121,7 @@ test("publish diagnostics remain visible after the panel remounts", () => {
<button onClick={() => setIsOpen(true)}>Reopen</button>
<button
onClick={() =>
progress.setPublishFindings([
progress.beginPublishDiagnostics().setFindings([
{
severity: "warning",
title: "Check",
@@ -1346,3 +1346,41 @@ test("a rejected request after project navigation does not show a stale toast",
await act(async () => rejectPublish(new Error("Network unavailable")));
expect(errorToast).not.toHaveBeenCalled();
});
test.each(["site", "static"] as const)(
"keeps %s findings when diagnostics for the other target start",
(firstTarget) => {
const secondTarget = firstTarget === "site" ? "static" : "site";
let progress: ReturnType<typeof usePublishProgress>;
const Harness = () => {
progress = usePublishProgress("project");
return null;
};
$project.set({ id: "project" } as Project);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(<Harness />));
act(() => {
progress
.beginPublishDiagnostics([], firstTarget)
.setFindings([
{ severity: "warning", title: firstTarget, reportText: firstTarget },
]);
});
act(() => {
progress.beginPublishDiagnostics([], secondTarget).setFindings([
{
severity: "warning",
title: secondTarget,
reportText: secondTarget,
},
]);
});
expect(
progress!.publishDiagnostics[firstTarget].findings.map(
({ reportText }) => reportText
)
).toEqual([firstTarget]);
}
);
@@ -1,5 +1,6 @@
import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
import { userEvent } from "@vitest/browser/context";
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
@@ -7,9 +8,18 @@ import type { Project } from "@webstudio-is/project";
let root: Root | undefined;
let container: HTMLDivElement | undefined;
let publishModule: typeof import("./publish");
let logsModule: typeof import("./use-publish-logs");
let flowModule: typeof import("./use-publish-flow");
let diagnosticsModule: typeof import("./diagnostics");
const acceptedResponse = {
success: true,
buildId: "static-1",
logHandle: "handle-1",
findings: [],
name: "site.zip",
};
let staticResponse: unknown = acceptedResponse;
let projectStore: (typeof import("~/shared/sync/data-stores"))["$project"];
let getJobStatus: "pending" | "success" = "pending";
let getJobStatus: "pending" | "success" | "failed" = "pending";
let publishRequests = 0;
let jobRequests = 0;
let projectRequests = 0;
@@ -33,13 +43,7 @@ beforeAll(async () => {
}
if (path === "/trpc/domain.publish") {
publishRequests += 1;
return respond({
success: true,
buildId: "static-1",
logHandle: "handle-1",
findings: [],
name: "site.zip",
});
return respond(staticResponse);
}
if (path === "/trpc/api.publish.getJob") {
jobRequests += 1;
@@ -62,7 +66,8 @@ beforeAll(async () => {
throw new Error(`Unexpected request: ${path}`);
});
publishModule = await import("./publish");
logsModule = await import("./use-publish-logs");
flowModule = await import("./use-publish-flow");
diagnosticsModule = await import("./diagnostics");
projectStore = (await import("~/shared/sync/data-stores")).$project;
const { updateCsrfToken } = await import("~/shared/csrf.client");
updateCsrfToken("test-token");
@@ -75,6 +80,7 @@ afterEach(() => {
container = undefined;
projectStore.set(undefined);
getJobStatus = "pending";
staticResponse = acceptedResponse;
publishRequests = 0;
jobRequests = 0;
projectRequests = 0;
@@ -92,22 +98,32 @@ const Harness = ({
open: boolean;
projectId?: string;
}) => {
const progress = publishModule.__testing__.usePublishProgress(projectId);
const logs = logsModule.usePublishLogs(projectId, false);
const flow = flowModule.usePublishFlow(projectId, false, "none");
return (
<TooltipProvider>
<output>{progress.isPublishing ? "pending" : "idle"}</output>
<output>{flow.isPublishing ? "pending" : "idle"}</output>
<output data-log-status>{flow.logs[0]?.status}</output>
<output data-static-error>{flow.staticError?.severity}</output>
{open && (
<publishModule.__testing__.PublishStatic
projectId={projectId}
templates={["ssg"]}
publishLogs={logs}
progress={progress}
onOpenReport={() => {}}
onFindings={() => {}}
flow={flow}
onDownload={downloads}
/>
)}
<diagnosticsModule.PublishDiagnosticsDialog
findings={flow.reportFindings}
includeLatestPublishFindings={flow.includeLatestPublishFindings}
items={flow.reportItems}
open={flow.selectedReport !== undefined}
onOpenChange={(open) => {
if (!open) {
flow.closeReport();
}
}}
initialTab={flow.selectedReport?.tab}
canViewPublishLogs={false}
/>
</TooltipProvider>
);
};
@@ -139,8 +155,12 @@ test("reopening an active static publish keeps one status owner and one download
getJobStatus = "success";
await act(async () => vi.advanceTimersByTimeAsync(15_000));
expect(downloads).toHaveBeenCalledExactlyOnceWith("site.zip");
expect(container?.querySelector("[data-log-status]")?.textContent).toBe(
"success"
);
expect(publishRequests).toBe(1);
expect(jobRequests).toBe(2);
expect(container?.querySelector("[data-static-error]")?.textContent).toBe("");
});
test("project navigation suppresses an old static download and error toast", async () => {
@@ -172,3 +192,97 @@ test("project navigation suppresses an old static download and error toast", asy
expect(downloads).not.toHaveBeenCalled();
expect(errorToast).not.toHaveBeenCalled();
});
test("a failed static runner clears progress without starting a download", async () => {
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
getJobStatus = "failed";
projectStore.set({ id: "project-a", latestStaticBuild: null } as Project);
render(true);
const button = Array.from(container!.querySelectorAll("button")).find(
(candidate) => candidate.textContent === "Build and download static site"
);
await act(async () => button?.click());
await act(async () => vi.waitFor(() => expect(jobRequests).toBe(1)));
expect(downloads).not.toHaveBeenCalled();
expect(errorToast).toHaveBeenCalledOnce();
expect(container?.querySelector("[data-log-status]")?.textContent).toBe(
"failed"
);
expect(container?.querySelector("output")?.textContent).toBe("idle");
await act(async () =>
userEvent.click(
container!.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
)!
)
);
const errors = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
).find((tab) => tab.textContent === "Errors");
expect(errors).toBeDefined();
await act(async () => userEvent.click(errors!));
const showLogs = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
).find((button) => button.textContent === "show logs");
expect(showLogs).toBeDefined();
await act(async () => userEvent.click(showLogs!));
expect(
document.body.querySelector('[role="tab"][aria-selected="true"]')
?.textContent
).toBe("Publish");
expect(
document.body.querySelector(
'[role="tabpanel"][data-state="active"] [role="note"]'
)
).not.toBeNull();
});
test("the static status reopens an audit rejection instead of an older successful publish", async () => {
getJobStatus = "success";
projectStore.set({ id: "project-a", latestStaticBuild: null } as Project);
render(true);
const publish = Array.from(
container!.querySelectorAll<HTMLButtonElement>("button")
).find((button) => button.textContent === "Build and download static site")!;
await act(async () => publish.click());
await vi.waitFor(async () => {
await act(async () => {});
expect(container?.querySelector("[data-log-status]")?.textContent).toBe(
"success"
);
expect(container?.querySelector("output")?.textContent).toBe("idle");
});
staticResponse = {
success: false,
auditFindings: [{ severity: "error", message: "audit-rejection" }],
};
await act(async () =>
Array.from(container!.querySelectorAll<HTMLButtonElement>("button"))
.find((button) => button.textContent === "Build and download static site")
?.click()
);
const activeTab = () =>
document.body.querySelector('[role="tab"][aria-selected="true"]')
?.textContent;
await vi.waitFor(async () => {
await act(async () => {});
expect(activeTab()).toBe("Errors");
});
await act(async () =>
document.body
.querySelector<HTMLButtonElement>('button[aria-label="Close"]')
?.click()
);
await vi.waitFor(async () => {
await act(async () => {});
expect(document.body.querySelector('[role="dialog"]')).toBeNull();
});
await act(async () =>
container!
.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
)
?.click()
);
expect(activeTab()).toBe("Errors");
});
@@ -1,6 +1,6 @@
import { expect, test, vi } from "vitest";
import type { Project } from "@webstudio-is/project";
import { __testing__ } from "./publish";
import { __testing__ } from "./use-publish-progress";
const { waitForPublishStatus } = __testing__;
@@ -0,0 +1,84 @@
import type { Project } from "@webstudio-is/project";
import { cssVar } from "@webstudio-is/design-system";
import { CheckCircleIcon, AlertIcon, SpinnerIcon } from "@webstudio-is/icons";
import { RelativeTime } from "~/builder/shared/relative-time";
export const PENDING_TIMEOUT =
process.env.NODE_ENV === "production" ? 60 * 3 * 1000 : 35000;
export const getPublishStatusAndText = ({
createdAt,
publishStatus,
}: Pick<
NonNullable<Project["domainsVirtual"][number]["latestBuildVirtual"]>,
"createdAt" | "publishStatus"
>) => {
let status = publishStatus;
const delta = Date.now() - new Date(createdAt).getTime();
// Assume build failed after 3 minutes
if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) {
status = "FAILED";
}
const textStart =
status === "PUBLISHED"
? "Published"
: status === "FAILED"
? "Publish failed"
: "Publishing started";
const statusText = (
<>
{textStart} <RelativeTime time={new Date(createdAt)} />
</>
);
const color =
status === "PUBLISHED"
? cssVar("--foreground-positive")
: status === "FAILED"
? cssVar("--foreground-negative")
: cssVar("--foreground-warning");
const Icon =
status === "PUBLISHED"
? CheckCircleIcon
: status === "FAILED"
? AlertIcon
: SpinnerIcon;
return { statusText, status, color, Icon };
};
export const getStaticPublishStatusAndText = ({
updatedAt,
publishStatus,
}: {
updatedAt: string;
publishStatus: "PENDING" | "FAILED" | "PUBLISHED";
}) => {
let status = publishStatus;
const delta = Date.now() - new Date(updatedAt).getTime();
// Assume build failed after 3 minutes
if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) {
status = "FAILED";
}
const textStart =
status === "PUBLISHED"
? "Downloaded"
: status === "FAILED"
? "Download failed"
: "Download started";
const statusText = (
<>
{textStart} <RelativeTime time={new Date(updatedAt)} />
</>
);
return { statusText, status };
};
@@ -0,0 +1,261 @@
import { type ReactNode } from "react";
import { Link, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import {
findPageAndSelectorByInstanceId,
formatPrePublishAuditFinding,
runPrePublishAudit,
} from "@webstudio-is/project-build/runtime";
import {
$registeredComponentMetas,
$selectedPageId,
selectInstance,
} from "~/shared/nano-states";
import {
$assetFolders,
$assets,
$pages,
$instances,
$props,
$dataSources,
$resources,
} from "~/shared/sync/data-stores";
import { $publishDialog } from "~/builder/shared/nano-states";
import { getInstanceLink } from "~/shared/instance-utils/link";
import { flushExternalContentProject } from "~/shared/external-content-roots";
import { nativeClient } from "~/shared/trpc/trpc-client";
import { getContentDatabasePublishFindings } from "./content-database-publish-warning";
import { getPublishValidationErrorMessage } from "./publish-error";
import type { PublishValidationFinding } from "./diagnostics";
const getPrePublishInstanceTarget = (
instanceId: string,
pageId?: string,
instanceSelector?: string[]
) => {
const pages = $pages.get();
const instances = $instances.get();
if (pages === undefined || instances.has(instanceId) === false) {
return;
}
const target =
pageId === undefined || instanceSelector === undefined
? findPageAndSelectorByInstanceId(pages, instances, instanceId)
: { pageId, instanceSelector };
const href = getInstanceLink(target.instanceSelector);
if (href === undefined) {
return;
}
return { ...target, href };
};
const PrePublishInstanceLink = ({
instanceId,
pageId,
instanceSelector,
children,
}: {
instanceId: string;
pageId?: string;
instanceSelector?: string[];
children: ReactNode;
}) => {
const target = getPrePublishInstanceTarget(
instanceId,
pageId,
instanceSelector
);
if (target === undefined) {
return null;
}
return (
<Link
href={target.href}
onClick={(event) => {
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
event.preventDefault();
$selectedPageId.set(target.pageId);
selectInstance(target.instanceSelector);
$publishDialog.set("none");
}}
>
{children}
</Link>
);
};
const getPrePublishAuditFindings = (): PublishValidationFinding[] => {
const findings = runPrePublishAudit({
pages: $pages.get(),
instances: $instances.get(),
props: $props.get(),
dataSources: $dataSources.get(),
resources: $resources.get(),
assets: $assets.get(),
metas: $registeredComponentMetas.get(),
});
return findings.flatMap((finding) => {
if (finding.severity !== "error" && finding.severity !== "warning") {
return [];
}
const context = Object.entries(finding.location)
.filter(
([key, value]) => key !== "instanceSelector" && value !== undefined
)
.map(([key, value]) => `${key}: ${value}`);
const reportText = [
`${finding.severity.toUpperCase()}: ${formatPrePublishAuditFinding(
finding
)}`,
`Rule: ${finding.ruleId}`,
...context,
].join("\n");
return [
{
severity: finding.severity,
title: formatPrePublishAuditFinding(finding),
summary: formatPrePublishAuditFinding(finding).slice(0, 160),
link:
finding.location.instanceId === undefined ? undefined : (
<PrePublishInstanceLink
instanceId={finding.location.instanceId}
pageId={finding.location.pageId}
instanceSelector={finding.location.instanceSelector}
>
Show element
</PrePublishInstanceLink>
),
details: context.length === 0 ? undefined : context.join(" · "),
reportText,
},
];
});
};
export const runPublishDiagnostics = async (
projectId: Project["id"],
domains?: string[]
) => {
const cssBuildWarningText =
"Some project styles cannot be processed for publishing. Publishing can continue using base and font styles.";
const auditFindings = getPrePublishAuditFindings();
const validation =
domains === undefined
? undefined
: await nativeClient.api.publish.validate.query({
projectId,
target: "staging",
domains,
});
const diagnostics =
validation?.diagnostics ??
(await nativeClient.build.contentDatabasePublishDiagnostics.query({
projectId,
}));
const contentFindings = getContentDatabasePublishFindings(diagnostics).map(
(finding) => ({
...finding,
link:
finding.relatedInstanceId === undefined ? undefined : (
<PrePublishInstanceLink instanceId={finding.relatedInstanceId}>
Open Content Block
</PrePublishInstanceLink>
),
})
);
const cssWarning =
validation?.cssValid === false
? [
{
severity: "warning" as const,
title: cssBuildWarningText,
reportText: cssBuildWarningText,
},
]
: [];
const findings = [...auditFindings, ...contentFindings, ...cssWarning];
return {
passed: findings.every(({ severity }) => severity !== "error"),
findings,
};
};
export const runPublishValidation = async (
projectId: Project["id"],
domains: string[]
) => {
await flushExternalContentProject({ projectId });
return runPublishDiagnostics(projectId, domains);
};
export const reportPublishValidationFailure = (
error: unknown,
setFindings: (findings: PublishValidationFinding[]) => void,
{
publishingContinues = false,
showToast = true,
}: { publishingContinues?: boolean; showToast?: boolean } = {}
) => {
const diagnosticMessage = getPublishValidationErrorMessage(error, {
assets: $assets.get(),
assetFolders: $assetFolders.get(),
});
const message = publishingContinues
? `${diagnosticMessage}\n\nThe publish request was sent without waiting for these diagnostics.`
: diagnosticMessage;
if (showToast) {
toast.error(message.slice(0, 200));
}
const mcpUrl = "https://wstd.us/mcp";
const mcpUrlIndex = message.indexOf(mcpUrl);
const details =
mcpUrlIndex === -1 ? (
message
) : (
<>
{message.slice(0, mcpUrlIndex)}
<Link href={mcpUrl} target="_blank" rel="noreferrer">
Webstudio MCP
</Link>
{message.slice(mcpUrlIndex + mcpUrl.length)}
</>
);
setFindings([
{
severity: "error",
title: publishingContinues
? "Publish checks couldn’t complete"
: "Unable to complete publish validation",
summary: message.slice(0, 160),
details,
reportText: `ERROR: Unable to complete publish validation\n${message}`,
},
]);
};
export const getServerPublishFindings = (
findings: readonly {
severity: "error" | "warning" | "info";
message: string;
}[]
): PublishValidationFinding[] =>
findings.flatMap((finding) =>
finding.severity === "info"
? []
: [
{
severity: finding.severity,
title: finding.message,
summary: finding.message,
reportText: `${finding.severity.toUpperCase()}: ${finding.message}`,
},
]
);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,463 @@
import { act } from "react-dom/test-utils";
import { createRoot, type Root } from "react-dom/client";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
expect,
test,
vi,
} from "vitest";
import { toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
const deferred = <T,>() => {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
};
const respond = (data: unknown) =>
new Response(JSON.stringify([{ result: { data } }]), {
headers: { "Content-Type": "application/json" },
});
let checks = deferred<Response>();
let dispatch = deferred<Response>();
let checkRequests = 0;
let checksRead = 0;
let publishRequests = 0;
let flowModule: typeof import("./use-publish-flow");
let stores: typeof import("~/shared/sync/data-stores");
let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog;
let flow: ReturnType<typeof import("./use-publish-flow").usePublishFlow>;
let root: Root;
let container: HTMLDivElement;
let getDiagnosticsReport: typeof import("./diagnostics-utils").getDiagnosticsReport;
const Harness = ({ paid = false }: { paid?: boolean }) => {
flow = flowModule.usePublishFlow("project", paid, "none");
return null;
};
beforeAll(async () => {
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
vi.resetModules();
vi.stubGlobal("fetch", async (requestInfo: RequestInfo | URL) => {
const path = new URL(String(requestInfo), "http://localhost").pathname;
if (path === "/trpc/domain.publish") {
publishRequests += 1;
return dispatch.promise;
}
if (path === "/trpc/api.publish.getJob") {
return respond({ status: "failed", code: "BUILD_FAILED" });
}
if (path === "/trpc/api.publish.getLog") {
return respond({
availability: "available",
log: {
encoding: "base64url",
chunk: btoa("old-runner-output"),
complete: true,
issues: [{ severity: "error", message: "old-build-issue" }],
issuesOmitted: 2,
},
});
}
if (
path === "/trpc/api.publish.validate" ||
path === "/trpc/build.contentDatabasePublishDiagnostics"
) {
checkRequests += 1;
try {
const response = (await checks.promise).clone();
const json = response.json.bind(response);
response.json = async () => {
const result = await json();
checksRead += 1;
return result;
};
return response;
} catch (error) {
checksRead += 1;
throw error;
}
}
throw new Error(`Unexpected request: ${path}`);
});
flowModule = await import("./use-publish-flow");
getDiagnosticsReport = (await import("./diagnostics-utils"))
.getDiagnosticsReport;
stores = await import("~/shared/sync/data-stores");
publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog;
(await import("~/shared/csrf.client")).updateCsrfToken("test-token");
});
beforeEach(() => {
checks = deferred<Response>();
dispatch = deferred<Response>();
checkRequests = 0;
checksRead = 0;
publishRequests = 0;
vi.spyOn(toast, "error").mockImplementation(() => "");
stores.$project.set({ id: "project" } as Project);
publishDialog.set("none");
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root.render(<Harness />));
});
afterEach(async () => {
act(() => root.unmount());
checks.resolve(respond({ mdxErrors: [], mdxOmissions: [] }));
dispatch.resolve(respond({ success: false, error: "cleanup" }));
await act(async () =>
vi.waitFor(() => expect(checksRead).toBe(checkRequests))
);
container.remove();
stores.$project.set(undefined);
publishDialog.set("none");
vi.restoreAllMocks();
});
afterAll(() => vi.unstubAllGlobals());
const start = (target: "site" | "static", domains = ["example.com"]) =>
act(() => {
if (target === "site") {
flow.openSiteReport(undefined, "errors");
flow.publish({
target,
domains,
timesLeft: 10,
maxDailyPublishesPerUser: 20,
});
} else {
flow.openStaticReport("errors");
flow.publish({ target, templates: ["ssg"] });
}
});
const waitForUpdate = (check: () => void) =>
vi.waitFor(async () => {
await act(async () => {});
check();
});
const completeChecks = async (fail = false) =>
act(async () => {
if (fail) {
checks.reject(new Error("check-failure"));
} else {
checks.resolve(
respond({
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: false,
mdxErrors: [],
mdxOmissions: [
{
filename: "check.mdx",
templateName: "missing",
blockInstanceId: "block",
assetId: "asset",
},
],
})
);
}
await checks.promise.catch(() => {});
await vi.waitFor(() => expect(checksRead).toBe(checkRequests));
});
test.each([
["site", "checks-first", false],
["site", "checks-first", true],
["site", "server-first", false],
["site", "server-first", true],
["static", "checks-first", false],
["static", "checks-first", true],
["static", "server-first", false],
["static", "server-first", true],
] as const)(
"%s audit rejection wins with %s (failed checks: %s)",
async (target, order, failChecks) => {
start(target);
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1]))
);
let completed: string[] = [];
if (order === "checks-first") {
await completeChecks(failChecks);
await waitForUpdate(() =>
expect(flow.reportFindings.length).toBeGreaterThan(0)
);
completed = flow.reportFindings.map(({ reportText }) => reportText);
}
await act(async () => {
dispatch.resolve(
respond({
success: false,
auditFindings: [{ severity: "error", message: "server-rejection" }],
})
);
await dispatch.promise;
});
await waitForUpdate(() =>
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
...completed,
"ERROR: server-rejection",
])
);
if (order === "server-first") {
await completeChecks(failChecks);
}
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
...completed,
"ERROR: server-rejection",
]);
}
);
test.each([
["request", "checks-first"],
["request", "server-first"],
["transport", "checks-first"],
["transport", "server-first"],
] as const)(
"retains a static %s failure with %s and preserves the site failure",
async (failure, order) => {
start("site");
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1]))
);
await act(async () => {
dispatch.resolve(respond({ success: false, error: "site-rejection" }));
await dispatch.promise;
});
await waitForUpdate(() =>
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
"site-rejection",
])
);
dispatch = deferred<Response>();
act(() => flow.publish({ target: "static", templates: ["ssg"] }));
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([2, 2]))
);
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
"site-rejection",
]);
let completed: string[] = [];
if (order === "checks-first") {
act(() => flow.openStaticReport("errors"));
await completeChecks();
await waitForUpdate(() =>
expect(
flow.reportFindings.some(({ severity }) => severity === "warning")
).toBe(true)
);
completed = flow.reportFindings.map(({ reportText }) => reportText);
}
const message = `${failure}-failure`;
await act(async () => {
if (failure === "request") {
dispatch.resolve(respond({ success: false, error: message }));
} else {
dispatch.reject(new Error(message));
}
await dispatch.promise.catch(() => {});
});
await waitForUpdate(() =>
expect(flow.staticError?.reportText).toBe(message)
);
act(() => flow.openStaticReport());
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
...completed,
message,
]);
expect(flow.selectedReport?.tab).toBe("errors");
expect(toast.error).toHaveBeenCalledWith(message);
if (order === "server-first") {
await completeChecks();
}
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
...completed,
message,
]);
act(() => flow.openSiteReport(undefined, "errors"));
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
"site-rejection",
]);
}
);
test.each(["checks-first", "server-first"] as const)(
"site transport error retains finished findings with %s",
async (order) => {
start("site");
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1]))
);
let completed: string[] = [];
if (order === "checks-first") {
await completeChecks();
await waitForUpdate(() =>
expect(
flow.reportFindings.some(({ severity }) => severity === "warning")
).toBe(true)
);
completed = flow.reportFindings.map(({ reportText }) => reportText);
}
await act(async () => {
dispatch.reject(new Error("site-transport"));
await dispatch.promise.catch(() => {});
});
await waitForUpdate(() => expect(flow.siteError).toBe("site-transport"));
if (order === "server-first") {
await completeChecks();
}
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
...completed,
"site-transport",
]);
act(() => flow.openSiteReport("other.example", "errors"));
expect(flow.reportFindings).toEqual([]);
// The popover consumes the unfiltered error even when another domain's
// report is selected; scoping must not hide the attempt's banner.
expect(flow.siteErrorSource).toBe("transport");
expect(flow.siteError).toBe("site-transport");
act(() => flow.openSiteReport("example.com", "errors"));
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
...completed,
"site-transport",
]);
}
);
test.each(["site", "static"] as const)(
"%s check failure has one visible notice while Publish is open",
async (target) => {
start(target);
publishDialog.set("publish");
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1]))
);
await completeChecks(true);
await waitForUpdate(() =>
expect(flow.reportFindings.length).toBeGreaterThan(0)
);
expect(toast.error).toHaveBeenCalledTimes(target === "site" ? 0 : 1);
}
);
test("an accepted site failure keeps the build association used by the log link", async () => {
start("site");
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1]))
);
await act(async () => {
dispatch.resolve(
respond({
success: true,
buildId: "accepted-build",
logHandle: "handle",
findings: [],
})
);
await dispatch.promise;
});
await waitForUpdate(() =>
expect(
flow.reportFindings.find(({ source }) => source === "publish")?.buildId
).toBe("accepted-build")
);
});
test.each([
["static", "request"],
["static", "transport"],
["static", "audit"],
["site", "request"],
["site", "transport"],
["site", "audit"],
] as const)(
"a newer %s %s rejection does not mix in the older accepted failure",
async (target, failure) => {
act(() => root.render(<Harness paid />));
start(target, ["example.com", "other.example"]);
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([1, 1]))
);
await completeChecks();
await act(async () => {
dispatch.resolve(
respond({
success: true,
buildId: "old-accepted",
logHandle: "old-handle",
findings: [{ severity: "warning", message: "old-audit" }],
...(target === "static" ? { name: "site.zip" } : {}),
})
);
await dispatch.promise;
});
await waitForUpdate(() => expect(flow.logs[0]?.logState).toBe("available"));
checks = deferred<Response>();
dispatch = deferred<Response>();
start(target);
await act(async () =>
vi.waitFor(() => expect([checkRequests, publishRequests]).toEqual([2, 2]))
);
const message = `new-${failure}`;
await act(async () => {
if (failure === "transport") {
dispatch.reject(new Error(message));
} else {
dispatch.resolve(
respond(
failure === "audit"
? {
success: false,
auditFindings: [{ severity: "error", message }],
}
: { success: false, error: message }
)
);
}
await dispatch.promise.catch(() => {});
});
const expected = failure === "audit" ? `ERROR: ${message}` : message;
await waitForUpdate(() =>
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
expected,
])
);
const report = () =>
getDiagnosticsReport({
findings: flow.reportFindings,
items: flow.reportItems,
canViewPublishLogs: true,
includeLatestPublishFindings: flow.includeLatestPublishFindings,
});
expect(report().findings.map(({ reportText }) => reportText)).toEqual([
expected,
]);
expect(report().issuesOmitted).toBeUndefined();
expect(report().publishes.map(({ buildId }) => buildId)).toEqual([
"old-accepted",
]);
expect(report().publishText).toBe(
target === "static"
? "Static export\nold-runner-output"
: "example.com\nother.example\nold-runner-output"
);
if (target === "site" && failure === "request") {
act(() => flow.openSiteReport("other.example", "errors"));
expect(report().findings.map(({ reportText }) => reportText)).toEqual([
"WARNING: old-audit",
"ERROR: old-build-issue",
]);
}
}
);
@@ -0,0 +1,504 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Link, Text, Tooltip, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import {
publishedDeploymentDestination,
type Templates,
} from "@webstudio-is/sdk";
import { $project } from "~/shared/sync/data-stores";
import { $publishDialog } from "~/builder/shared/nano-states";
import { nativeClient } from "~/shared/trpc/trpc-client";
import { usePublishValidationState } from "./publish-actions";
import {
usePublishProgress,
waitForPublishStatus,
refreshUntilSuccess,
getRefreshedProject,
reportPublishResult,
} from "./use-publish-progress";
import {
selectPublishLogs,
usePublishLogs,
type PublishLog,
} from "./use-publish-logs";
import {
runPublishDiagnostics,
runPublishValidation,
reportPublishValidationFailure,
getServerPublishFindings,
} from "./publish-validation";
import { runPublishAfterBestEffortChecks } from "./publish-preflight";
import type { PublishValidationFinding } from "./diagnostics";
const downloadStatic = (name: string) => {
window.location.href = `/cgi/static/ssg/${name}`;
};
const getPublishErrorFinding = (
error: JSX.Element | string,
buildId?: string
): PublishValidationFinding => ({
severity: "error",
source: "publish",
buildId,
title: error,
summary: typeof error === "string" ? error.slice(0, 160) : "Publish failed",
reportText: typeof error === "string" ? error : "Publish failed",
});
export const usePublishFlow = (
projectId: Project["id"],
allowPublishLogs: boolean,
publishDialog: "none" | "publish" | "export"
) => {
const publishLogs = usePublishLogs(projectId, allowPublishLogs);
const pendingLogs = useRef(publishLogs.items);
pendingLogs.current = publishLogs.items;
const [selectedReport, setSelectedReport] = useState<{
target: "static" | "site";
domain?: string;
tab: "warnings" | "errors" | "publish";
}>();
useEffect(() => {
setSelectedReport(undefined);
}, [projectId]);
const validation = usePublishValidationState(publishDialog);
const progress = usePublishProgress(projectId);
const {
dismissCountdown,
reconcileRefreshedProject,
watchPendingPublish,
beginPopoverRefresh,
isRefreshCurrent,
} = progress;
useEffect(() => {
if (publishDialog !== "publish") {
dismissCountdown();
}
}, [publishDialog, dismissCountdown]);
const {
complete: completePublishLog,
loadLog: loadPublishLog,
isCurrent,
} = publishLogs;
const validationFindings = progress.manualValidationFindings;
const { invalidate: invalidateValidationFindings } = validationFindings;
const { update: onValidationStateChange } = validation;
const { isCurrentProject } = progress;
const invalidateValidation = useCallback(() => {
invalidateValidationFindings();
onValidationStateChange("idle");
}, [invalidateValidationFindings, onValidationStateChange]);
const finishPublish = useCallback(
(
item: PublishLog | undefined,
result: Awaited<ReturnType<typeof waitForPublishStatus>>,
onDownload = downloadStatic
) => {
if (
item === undefined ||
!isCurrent() ||
(result?.status !== "PUBLISHED" && result?.status !== "FAILED")
) {
return;
}
const status = result.status === "PUBLISHED" ? "success" : "failed";
completePublishLog(item.buildId, status, result.code);
loadPublishLog({ ...item, status });
if (
item.target === "static" &&
status === "success" &&
item.staticName !== undefined
) {
onDownload(item.staticName);
}
},
[completePublishLog, loadPublishLog, isCurrent]
);
const waitForCompletion = async (
item: PublishLog | undefined,
previousBuildId?: string,
onDownload = downloadStatic
) => {
if (item === undefined) {
return;
}
const result = await waitForPublishStatus(
() => getRefreshedProject({ projectId, isCurrent }),
isCurrent,
previousBuildId,
{
projectId,
buildId: item.buildId,
logHandle: item.logHandle,
target: item.target,
}
);
finishPublish(item, result, onDownload);
return result;
};
useEffect(() => {
// Refresh a build that finished while the popover was closed, including
// after a publish status request failed.
if (publishDialog !== "none" && progress.isPublishing === false) {
let isOpen = true;
const generation = beginPopoverRefresh();
void refreshUntilSuccess(
async (showError) => {
const refreshedProject = await getRefreshedProject({
projectId,
showError,
isCurrent: () => isOpen && isRefreshCurrent(generation),
});
if (
isOpen &&
isRefreshCurrent(generation) &&
refreshedProject !== undefined
) {
reconcileRefreshedProject(refreshedProject);
}
return refreshedProject;
},
() => isOpen,
() => {
const target = publishDialog === "export" ? "static" : "site";
const pending = pendingLogs.current.find(
(item) => item.target === target && item.status === "pending"
);
if (target === "static" && pending === undefined) {
return;
}
void watchPendingPublish(
() =>
getRefreshedProject({
projectId,
showError: false,
isCurrent: () => isRefreshCurrent(generation),
}),
generation,
pending === undefined
? undefined
: {
projectId,
buildId: pending.buildId,
logHandle: pending.logHandle,
target,
},
(result) => finishPublish(pending, result)
);
},
() =>
pendingLogs.current.some(
(item) =>
item.target ===
(publishDialog === "export" ? "static" : "site") &&
item.status === "pending"
)
);
return () => {
isOpen = false;
};
}
}, [
projectId,
publishDialog,
progress.isPublishing,
reconcileRefreshedProject,
watchPendingPublish,
beginPopoverRefresh,
isRefreshCurrent,
finishPublish,
]);
const openSiteReport = (
domain: string | undefined,
tab: "warnings" | "errors" | "publish"
) => {
$publishDialog.set("none");
setSelectedReport({ target: "site", domain, tab });
};
const openStaticReport = (
tab: "warnings" | "errors" | "publish" = staticError === undefined
? "publish"
: "errors"
) => {
$publishDialog.set("none");
setSelectedReport({ target: "static", tab });
};
const reportItems = selectPublishLogs(
publishLogs.items,
selectedReport?.target ?? "site",
selectedReport?.domain
);
const domain = selectedReport?.domain;
const siteFindings = [
...validationFindings.findings,
...progress.publishFindings,
];
const staticDiagnostics = progress.publishDiagnostics.static;
const staticError = staticDiagnostics.rejected
? staticDiagnostics.findings
.filter(({ severity }) => severity === "error")
.at(-1)
: undefined;
const findings: PublishValidationFinding[] = [];
const diagnostics =
progress.publishDiagnostics[selectedReport?.target ?? "site"];
const isReportForDiagnostics =
domain === undefined || diagnostics.domains.includes(domain);
if (isReportForDiagnostics) {
findings.push(...diagnostics.findings);
}
if (selectedReport?.target !== "static") {
if (domain === undefined || validationFindings.domains?.includes(domain)) {
findings.push(...validationFindings.findings);
}
const { publishError, publishErrorDomains } = progress;
if (
publishError !== undefined &&
(domain === undefined ||
publishErrorDomains === undefined ||
publishErrorDomains.includes(domain))
) {
findings.push(
getPublishErrorFinding(publishError, progress.publishErrorBuildId)
);
}
}
const validate = async (domains: string[]) => {
const session = validationFindings.begin(domains);
progress.clearErrors();
progress.beginPublishDiagnostics(domains);
if (domains.length === 0) {
toast.error("Please select at least one domain to publish");
return;
}
try {
const checks = await runPublishValidation(projectId, domains);
if (validationFindings.isCurrent(session) === false) {
return;
}
validationFindings.update(session, checks.findings);
if (checks.passed === false) {
onValidationStateChange("idle");
return;
}
onValidationStateChange("passed");
} catch (error) {
if (validationFindings.isCurrent(session) === false) {
return;
}
onValidationStateChange("idle");
reportPublishValidationFailure(
error,
(findings) => validationFindings.update(session, findings),
{ showToast: $publishDialog.get() !== "publish" }
);
}
};
const publish = (
request:
| {
target: "site";
domains: string[];
timesLeft: number;
maxDailyPublishesPerUser: number;
}
| {
target: "static";
templates: readonly Templates[];
onDownload?: (name: string) => void;
}
) => {
if (!isCurrent()) {
return;
}
const domains = request.target === "site" ? request.domains : [];
if (request.target === "site") {
validationFindings.invalidate();
onValidationStateChange("idle");
if (domains.length === 0) {
toast.error("Please select at least one domain to publish");
return;
}
}
const diagnostics = progress.beginPublishDiagnostics(
domains,
request.target
);
progress.start(
async () => {
const previousBuildId =
request.target === "site"
? $project.get()?.latestBuildVirtual?.buildId
: undefined;
const publishResult = await runPublishAfterBestEffortChecks({
checks: async () => {
const checks = await runPublishDiagnostics(
projectId,
request.target === "site" ? domains : undefined
);
diagnostics.setFindings(checks.findings);
},
onCheckFailure: (error) => {
if (isCurrent() && diagnostics.isCurrent()) {
reportPublishValidationFailure(error, diagnostics.setFindings, {
publishingContinues: true,
showToast:
request.target === "static" ||
$publishDialog.get() !== "publish",
});
}
},
publish: () =>
nativeClient.domain.publish.mutate(
request.target === "site"
? {
projectId,
destination: publishedDeploymentDestination,
domains,
}
: {
projectId,
destination: "static",
templates: [...request.templates],
}
),
});
if (!isCurrent()) {
return;
}
if (publishResult.success === false) {
if ("auditFindings" in publishResult) {
diagnostics.finish((findings) => [
...findings,
...getServerPublishFindings(publishResult.auditFindings),
]);
if (request.target === "static") {
openStaticReport("errors");
}
return;
}
if (request.target === "static") {
diagnostics.finish((findings) => [
...findings,
getPublishErrorFinding(publishResult.error),
]);
toast.error(publishResult.error.slice(0, 200));
return;
}
diagnostics.finish();
console.error(publishResult.error);
let error: JSX.Element | string = publishResult.error;
if (publishResult.error === "NOT_IMPLEMENTED") {
error = (
<>
<Tooltip
content={
<Text userSelect="text">
{$project.get()?.latestBuildVirtual?.buildId}
</Text>
}
>
<span>Build data</span>
</Tooltip>{" "}
for publishing has been successfully created. Use{" "}
<Link href="https://docs.webstudio.is/university/self-hosting/cli">
Webstudio&nbsp;CLI
</Link>{" "}
to generate the code.
</>
);
}
progress.setPublishError(error, domains);
if (publishResult.error === "NOT_IMPLEMENTED") {
toast.info(error);
} else if ($publishDialog.get() !== "publish") {
toast.error(
typeof error === "string" ? error.slice(0, 200) : error
);
}
if (process.env.NODE_ENV === "development") {
// Refresh locally as it's always an error
await getRefreshedProject({ projectId, isCurrent });
}
return;
}
const accepted = publishLogs.record({
buildId: publishResult.buildId,
logHandle: publishResult.logHandle,
target: request.target,
domains,
findings: getServerPublishFindings(publishResult.findings),
staticName: "name" in publishResult ? publishResult.name : undefined,
});
if (request.target === "static" && accepted?.staticName == null) {
toast.error('File name must be defined in "result"');
}
const outcome = await waitForCompletion(
accepted,
previousBuildId,
request.target === "static" ? request.onDownload : undefined
);
if (request.target === "site") {
reportPublishResult({
result: outcome,
buildId: accepted?.buildId,
timesLeft: request.timesLeft,
maxDailyPublishesPerUser: request.maxDailyPublishesPerUser,
setPublishError: progress.setPublishStatusError,
isCurrentProject,
});
} else if (isCurrent() && outcome?.status === "FAILED") {
toast.error(outcome.statusText);
}
},
{
target: request.target,
domains,
onError: (message) =>
diagnostics.finish(
request.target === "static"
? (findings) => [...findings, getPublishErrorFinding(message)]
: undefined
),
}
);
};
return {
isPublishing: progress.isPublishing,
countdown: progress.countdown,
validationState: validation.validationState,
validatedDomains: validationFindings.domains,
siteError: progress.publishError,
siteErrorSource: progress.publishErrorSource,
siteFindings,
staticError,
logs: publishLogs.items,
loadLog: publishLogs.loadLog,
selectedReport,
closeReport: () => setSelectedReport(undefined),
reportItems,
reportFindings: findings,
includeLatestPublishFindings: !(
diagnostics.rejected && isReportForDiagnostics
),
openSiteReport,
openStaticReport,
validate,
publish,
invalidateValidation,
reset: () => {
validation.reset();
dismissCountdown();
},
};
};
@@ -0,0 +1,583 @@
import {
useCallback,
useEffect,
useRef,
useState,
type SetStateAction,
} from "react";
import { toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import { $project } from "~/shared/sync/data-stores";
import { $publishDialog } from "~/builder/shared/nano-states";
import { nativeClient } from "~/shared/trpc/trpc-client";
import {
PENDING_TIMEOUT,
getPublishStatusAndText,
getStaticPublishStatusAndText,
} from "./publish-status";
import type { PublishValidationFinding } from "./diagnostics";
const COUNTDOWN_DURATION = 60_000;
const STATUS_REFRESH_RETRY_DELAY = 5_000;
const STATUS_REFRESH_MAX_ATTEMPTS = 3;
type PublishExecution = {
projectId: string;
buildId: string;
logHandle?: string;
target?: "site" | "static";
};
export const usePublishProgress = (projectId: Project["id"]) => {
const projectScope = useRef({ projectId, token: 0 });
if (projectScope.current.projectId !== projectId) {
projectScope.current = { projectId, token: projectScope.current.token + 1 };
}
const scopeToken = projectScope.current.token;
const manualValidationFindings = useManualValidationFindings();
const invalidateManualFindings = manualValidationFindings.invalidate;
const [startedAt, setStartedAt] = useState<number>();
const [showCountdown, setShowCountdown] = useState(false);
const [isPublishing, setIsPublishing] = useState(false);
const [publishDiagnostics, setPublishDiagnostics] = useState<
Record<
"site" | "static",
{
domains: string[];
findings: PublishValidationFinding[];
rejected?: boolean;
}
>
>({
site: { domains: [], findings: [] },
static: { domains: [], findings: [] },
});
const publishDiagnosticsSession = useRef({ site: 0, static: 0 });
const [publishErrorState, setPublishErrorState] = useState<{
value: JSX.Element | string;
source: "request" | "transport" | "status";
domains?: string[];
buildId?: string;
}>();
const [now, setNow] = useState(Date.now);
const isMounted = useRef(false);
const requestBaselineBuildId = useRef<string>();
const hasStartedPublishRequest = useRef(false);
const refreshGeneration = useRef(0);
const recoveredPoll = useRef<{
generation: number;
promise: Promise<void>;
}>();
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
useEffect(() => {
publishDiagnosticsSession.current.site += 1;
publishDiagnosticsSession.current.static += 1;
setPublishDiagnostics({
site: { domains: [], findings: [] },
static: { domains: [], findings: [] },
});
setPublishErrorState(undefined);
setIsPublishing(false);
invalidateManualFindings();
}, [projectId, invalidateManualFindings]);
const isCurrentProject = useCallback(
() =>
isMounted.current &&
$project.get()?.id === projectId &&
projectScope.current.token === scopeToken,
[projectId, scopeToken]
);
const beginPopoverRefresh = useCallback(() => {
refreshGeneration.current += 1;
return refreshGeneration.current;
}, []);
const isRefreshCurrent = useCallback(
(generation: number) =>
isCurrentProject() && refreshGeneration.current === generation,
[isCurrentProject]
);
const setPublishError = (
value: JSX.Element | string | undefined,
domains?: string[]
) => {
setPublishErrorState(
value === undefined ? undefined : { value, source: "request", domains }
);
};
const setPublishStatusError = useCallback(
(value: JSX.Element | string, buildId?: string) => {
setPublishErrorState({ value, source: "status", buildId });
},
[]
);
const clearErrors = useCallback(() => {
setPublishErrorState(undefined);
}, []);
const beginPublishDiagnostics = useCallback(
(domains: string[] = [], target: "site" | "static" = "site") => {
const session = ++publishDiagnosticsSession.current[target];
setPublishDiagnostics((current) => ({
...current,
[target]: { domains, findings: [] },
}));
const setFindings = (
findings: SetStateAction<PublishValidationFinding[]>
) => {
if (publishDiagnosticsSession.current[target] === session) {
setPublishDiagnostics((current) => ({
...current,
[target]: {
domains,
findings:
typeof findings === "function"
? findings(current[target].findings)
: findings,
},
}));
}
};
return {
isCurrent: () => publishDiagnosticsSession.current[target] === session,
setFindings,
finish: (findings?: SetStateAction<PublishValidationFinding[]>) => {
if (findings !== undefined) {
setFindings(findings);
}
if (publishDiagnosticsSession.current[target] === session) {
setPublishDiagnostics((current) => ({
...current,
[target]: { ...current[target], rejected: true },
}));
publishDiagnosticsSession.current[target] += 1;
}
},
};
},
[]
);
const reconcileRefreshedProject = useCallback((project: Project) => {
const build = project.latestBuildVirtual;
if (build == null) {
setPublishErrorState((current) =>
current?.source === "status" ? undefined : current
);
return;
}
const { status, statusText } = getPublishStatusAndText(build);
const isNewBuild =
build.buildId !== undefined &&
build.buildId !== requestBaselineBuildId.current;
if (status === "FAILED") {
if (hasStartedPublishRequest.current && isNewBuild) {
setPublishErrorState({
value: statusText,
source: "status",
buildId: build.buildId,
});
}
} else {
setPublishErrorState((current) =>
current?.source === "status" ||
(isNewBuild && current?.source === "transport")
? undefined
: current
);
}
}, []);
const watchPendingPublish = useCallback(
(
refresh: () => Promise<Project | undefined>,
generation = refreshGeneration.current,
execution?: PublishExecution,
onResult?: (
result: Awaited<ReturnType<typeof waitForPublishStatus>>
) => void
) => {
if (recoveredPoll.current?.generation === generation) {
return recoveredPoll.current.promise;
}
const polling = waitForPublishStatus(
refresh,
() => isRefreshCurrent(generation),
undefined,
execution
)
.then((result) => {
if (isRefreshCurrent(generation) === false) {
return;
}
if (execution?.target !== "static") {
reportPublishResult({
result,
buildId: execution?.buildId,
setPublishError: setPublishStatusError,
isCurrentProject,
});
} else if (result?.status === "FAILED") {
toast.error(result.statusText);
}
onResult?.(result);
})
.finally(() => {
if (recoveredPoll.current?.promise === polling) {
recoveredPoll.current = undefined;
}
});
recoveredPoll.current = { generation, promise: polling };
return polling;
},
[isCurrentProject, isRefreshCurrent, setPublishStatusError]
);
useEffect(() => {
if (isPublishing === false || showCountdown === false) {
return;
}
const interval = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(interval);
}, [isPublishing, showCountdown]);
const countdown =
isPublishing && showCountdown && startedAt !== undefined
? Math.max(0, Math.ceil((COUNTDOWN_DURATION - (now - startedAt)) / 1000))
: undefined;
const dismissCountdown = useCallback(() => setShowCountdown(false), []);
const start = (
publish: () => Promise<void>,
{
target = "site",
domains,
onError,
}: {
target?: "site" | "static";
domains?: string[];
onError?: (message: string) => void;
} = {}
) => {
const startedAt = Date.now();
if (target === "site") {
hasStartedPublishRequest.current = true;
requestBaselineBuildId.current =
$project.get()?.latestBuildVirtual?.buildId;
setPublishErrorState(undefined);
}
setStartedAt(startedAt);
setNow(startedAt);
setShowCountdown(true);
setIsPublishing(true);
publish()
.catch((error) => {
if (target === "site") {
console.error(error);
}
const message =
error instanceof Error ? error.message : "Unknown error";
if (isCurrentProject()) {
onError?.(message);
if (target === "site") {
setPublishErrorState({
value: message,
source: "transport",
domains,
});
}
if (target === "static" || $publishDialog.get() !== "publish") {
toast.error(target === "static" ? message.slice(0, 200) : message);
}
}
})
.finally(() => {
if (isCurrentProject()) {
setIsPublishing(false);
}
});
};
return {
manualValidationFindings,
isPublishing,
publishFindings: publishDiagnostics.site.findings,
publishDiagnostics,
beginPublishDiagnostics,
publishError: publishErrorState?.value,
publishErrorSource: publishErrorState?.source,
publishErrorDomains: publishErrorState?.domains,
publishErrorBuildId: publishErrorState?.buildId,
setPublishError,
setPublishStatusError,
clearErrors,
isCurrentProject,
beginPopoverRefresh,
isRefreshCurrent,
reconcileRefreshedProject,
watchPendingPublish,
countdown,
start,
dismissCountdown,
};
};
export const waitForPublishStatus = async (
refresh: () => Promise<Project | undefined>,
isCurrentProject: () => boolean,
previousBuildId?: string,
execution?: PublishExecution,
getJob: (input: {
projectId: string;
jobId: string;
logHandle: string;
}) => Promise<{ status: string; code?: string }> = nativeClient.api.publish
.getJob.query
) => {
let sleepTime = 15000;
const timeToFinish = Date.now() + PENDING_TIMEOUT + 2 * sleepTime;
while (Date.now() < timeToFinish && isCurrentProject()) {
try {
let runnerPending = false;
if (execution?.logHandle !== undefined) {
try {
const job = await getJob({
projectId: execution.projectId,
jobId: execution.buildId,
logHandle: execution.logHandle,
});
if (isCurrentProject() === false) {
return;
}
if (job.status === "failed") {
return {
status: "FAILED" as const,
statusText: "Publish failed",
code: job.code,
};
}
runnerPending = job.status === "pending";
} catch (error) {
console.error("Could not refresh publish status", error);
}
}
const refreshedProject = await refresh();
if (isCurrentProject() === false) {
return;
}
const buildId =
execution?.target === "static"
? refreshedProject?.latestStaticBuild?.buildId
: refreshedProject?.latestBuildVirtual?.buildId;
if (
refreshedProject !== undefined &&
(previousBuildId === undefined || buildId !== previousBuildId) &&
(execution === undefined || buildId === execution.buildId)
) {
const { statusText, status } =
execution?.target === "static" &&
refreshedProject.latestStaticBuild != null
? getStaticPublishStatusAndText(refreshedProject.latestStaticBuild)
: refreshedProject.latestBuildVirtual != null
? getPublishStatusAndText(refreshedProject.latestBuildVirtual)
: {
statusText: "Not published",
status: "PENDING" as const,
};
if (!runnerPending && (status === "PUBLISHED" || status === "FAILED")) {
return { status, statusText };
}
}
} catch (error) {
if (isCurrentProject() === false) {
return;
}
// A failed status request should not stop watching an ongoing publish.
console.error("Could not refresh publish status", error);
}
await new Promise((resolve) => setTimeout(resolve, sleepTime));
sleepTime = Math.max(5000, sleepTime - 5000);
}
};
export const refreshUntilSuccess = async (
refresh: (showError: boolean) => Promise<Project | undefined>,
isOpen: () => boolean,
onPending: (project: Project) => void = () => {},
hasSessionPending: (project: Project) => boolean = () => false
) => {
for (
let attempt = 1;
attempt <= STATUS_REFRESH_MAX_ATTEMPTS && isOpen();
attempt++
) {
const isLastAttempt = attempt === STATUS_REFRESH_MAX_ATTEMPTS;
try {
const refreshedProject = await refresh(isLastAttempt);
if (refreshedProject !== undefined) {
if (
(refreshedProject.latestBuildVirtual != null &&
getPublishStatusAndText(refreshedProject.latestBuildVirtual)
.status === "PENDING") ||
hasSessionPending(refreshedProject)
) {
onPending(refreshedProject);
}
return;
}
} catch (error) {
console.error("Could not refresh publish status", error);
if (isLastAttempt && isOpen()) {
toast.error(error instanceof Error ? error.message : "Unknown error");
}
}
if (isLastAttempt === false && isOpen()) {
await new Promise((resolve) =>
setTimeout(resolve, STATUS_REFRESH_RETRY_DELAY)
);
}
}
};
export const reportPublishResult = ({
result,
buildId,
timesLeft,
maxDailyPublishesPerUser,
setPublishError,
isCurrentProject = () => true,
}: {
result: Awaited<ReturnType<typeof waitForPublishStatus>>;
buildId?: string;
timesLeft?: number;
maxDailyPublishesPerUser?: number;
setPublishError: (error: string | JSX.Element, buildId?: string) => void;
isCurrentProject?: () => boolean;
}) => {
if (isCurrentProject() === false) {
return;
}
if (result?.status === "PUBLISHED") {
if ($publishDialog.get() === "none") {
toast.success(
<>
The project has been successfully published.{" "}
{timesLeft !== undefined &&
maxDailyPublishesPerUser !== undefined &&
timesLeft > 0 &&
timesLeft <= 10 && (
<div>
You have {timesLeft} out of {maxDailyPublishesPerUser} daily
publications remaining. The counter resets tomorrow.
</div>
)}
</>,
{ duration: 10000 }
);
}
return;
}
if (result?.status === "FAILED") {
if ($publishDialog.get() !== "publish") {
toast.error(result.statusText);
}
setPublishError(result.statusText, buildId);
}
};
const useManualValidationFindings = () => {
const [findings, setFindings] = useState<PublishValidationFinding[]>([]);
const [domains, setDomains] = useState<string[]>();
const session = useRef(0);
const requestedDomains = useRef<string[]>([]);
useEffect(() => {
return () => {
session.current += 1;
};
}, []);
const begin = useCallback((domains: string[] = []) => {
session.current += 1;
requestedDomains.current = domains;
setFindings([]);
setDomains(undefined);
return session.current;
}, []);
const invalidate = useCallback(() => {
session.current += 1;
setFindings([]);
setDomains(undefined);
}, []);
const isCurrent = useCallback((id: number) => session.current === id, []);
const update = useCallback((id: number, next: PublishValidationFinding[]) => {
if (session.current === id) {
setFindings(next);
setDomains(next.length > 0 ? requestedDomains.current : undefined);
}
}, []);
return { findings, domains, begin, invalidate, isCurrent, update };
};
export const getRefreshedProject = async ({
projectId,
showError = true,
query = () => nativeClient.domain.project.query({ projectId }),
isCurrent = () => true,
}: {
projectId: Project["id"];
showError?: boolean;
query?: () => ReturnType<typeof nativeClient.domain.project.query>;
isCurrent?: () => boolean;
}) => {
if ($project.get()?.id !== projectId || !isCurrent()) {
return;
}
const result = await query();
if ($project.get()?.id !== projectId || !isCurrent()) {
return;
}
if (result.success) {
$project.set(result.project);
return result.project;
}
if (showError) {
toast.error(result.error);
}
};
export const __testing__ = {
usePublishProgress,
waitForPublishStatus,
refreshUntilSuccess,
reportPublishResult,
useManualValidationFindings,
getRefreshedProject,
};