refactor: simplify publish diagnostics UI

This commit is contained in:
Oleg Isonen committed 2026-11-15 11:16:08 +00:00
1 parent 0fc46b6ad8
commit ea3c6175bd
26 files changed
+4818 -4624

No files matched your search

@@ -1,6 +1,6 @@
import { cssVar } from "@webstudio-is/design-system";
import { AlertIcon, CheckCircleIcon, SpinnerIcon } from "@webstudio-is/icons";
import type { SessionPublish } from "./use-session-publishes";
import type { SessionPublish } from "./session-publishes";
export const publishLogStatus = {
pending: {
@@ -1,5 +1,5 @@
import type { DiagnosticFinding } from "./diagnostics";
import type { SessionPublish } from "./use-session-publishes";
import type { SessionPublish } from "./session-publishes";
import { publishLogStatus } from "./constants";
export const getDiagnosticsReport = ({
@@ -8,7 +8,7 @@ import {
PublishValidationBanner,
type DiagnosticFinding,
} from "./diagnostics";
import type { SessionPublish } from "./use-session-publishes";
import type { SessionPublish } from "./session-publishes";
let root: Root | undefined;
let container: HTMLDivElement | undefined;
@@ -26,8 +26,8 @@ import {
} from "@webstudio-is/design-system";
import { CopyIcon } from "@webstudio-is/icons";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import type { SessionPublish } from "./use-session-publishes";
import { getPublishDuration } from "./use-session-publishes";
import type { SessionPublish } from "./session-publishes";
import { getPublishDuration } from "./session-publishes";
import { publishLogStatus } from "./constants";
export type DiagnosticFinding = {
@@ -2,7 +2,7 @@ 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 { SessionPublish } from "./use-session-publishes";
import type { SessionPublish } from "./session-publishes";
export const DomainStatusButton = ({
domain,
@@ -4,7 +4,7 @@ import { afterEach, expect, test, vi } from "vitest";
import { TooltipProvider } from "@webstudio-is/design-system";
import { __testing__, type Domain } from "./domains";
import { PENDING_TIMEOUT } from "./publish-status";
import type { SessionPublish } from "./use-session-publishes";
import type { SessionPublish } from "./session-publishes";
const { StatusIcon } = __testing__;
let root: Root | undefined;
@@ -43,7 +43,7 @@ import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { getPublishStatusDisplay } from "./publish-status";
import { $currentSystem } from "~/shared/system";
import { getPublishUrl } from "./publish-url";
import type { SessionPublish } from "./use-session-publishes";
import type { SessionPublish } from "./session-publishes";
import { DomainStatusButton } from "./domain-status-button";
export type Domain = Project["domainsVirtual"][number];
@@ -2,8 +2,8 @@ import { createRef, useState } from "react";
import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
import { afterEach, expect, test, vi } from "vitest";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import { PublishActions, usePublishValidationState } from "./publish-actions";
import { TooltipProvider } from "@webstudio-is/design-system";
import { PublishActions } from "./publish-actions";
let root: Root | undefined;
let container: HTMLDivElement | undefined;
@@ -74,146 +74,6 @@ test("shows the successful validation state in the action", () => {
expect(validate).toBeEnabled();
});
test("clears the validation result when the publish popover closes", async () => {
const Harness = () => {
const [isOpen, setIsOpen] = useState(true);
const { validationState, update, reset } = usePublishValidationState(
isOpen ? "publish" : "none"
);
return (
<TooltipProvider>
{isOpen && (
<PublishActions
validationState={validationState}
validateDisabled={false}
publishDisabled={false}
publishInProgress={false}
publishPending={false}
hasSelectedDomains
publishLabel="Publish"
publishButtonRef={createRef<HTMLButtonElement>()}
onValidate={async () => {
update("passed");
}}
onPublish={vi.fn()}
/>
)}
<button
type="button"
onClick={() => {
reset();
setIsOpen(false);
}}
>
Close
</button>
{isOpen === false && (
<button type="button" onClick={() => setIsOpen(true)}>
Open
</button>
)}
</TooltipProvider>
);
};
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(<Harness />));
const [validate, , close] = Array.from(
container.querySelectorAll<HTMLButtonElement>("button")
);
await act(async () => validate.click());
expect(validate.textContent).toBe("Validated");
act(() => close.click());
const reopen =
container.querySelector<HTMLButtonElement>("button:last-child");
act(() => reopen?.click());
const [reopenedValidate] = Array.from(
container.querySelectorAll<HTMLButtonElement>("button")
);
expect(reopenedValidate.textContent).toBe("Validate");
expect(reopenedValidate.querySelector("svg")).toBeNull();
});
test.each([
{ destination: "none" as const, expectedToasts: 1 },
{ destination: "none" as const, reopen: true, expectedToasts: 0 },
{ destination: "export" as const, expectedToasts: 1 },
{ destination: "publish" as const, expectedToasts: 0 },
])(
"reports validation success after switching to $destination (reopen: $reopen)",
async ({ destination, reopen, expectedToasts }) => {
const successToast = vi
.spyOn(toast, "success")
.mockImplementation(() => "");
let finishValidation: () => void = () => {};
const validation = new Promise<void>((resolve) => {
finishValidation = resolve;
});
const Harness = () => {
const [dialog, setDialog] = useState<"none" | "publish" | "export">(
"publish"
);
const { validationState, update } = usePublishValidationState(dialog);
return (
<TooltipProvider>
{dialog === "publish" && (
<PublishActions
validationState={validationState}
validateDisabled={false}
publishDisabled={false}
publishInProgress={false}
publishPending={false}
hasSelectedDomains
publishLabel="Publish"
publishButtonRef={createRef<HTMLButtonElement>()}
onValidate={async () => {
await validation;
update("passed");
}}
onPublish={vi.fn()}
/>
)}
<button type="button" onClick={() => setDialog(destination)}>
Switch
</button>
<button type="button" onClick={() => setDialog("publish")}>
Reopen
</button>
<output>{validationState}</output>
</TooltipProvider>
);
};
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => root?.render(<Harness />));
const [validate, , switchDialog, reopenDialog] =
container.querySelectorAll("button");
act(() => validate.click());
act(() => switchDialog.click());
if (reopen) {
act(() => reopenDialog.click());
}
await act(async () => {
finishValidation();
await validation;
});
expect(successToast).toHaveBeenCalledTimes(expectedToasts);
expect(container.querySelector("output")?.textContent).toBe(
destination === "publish" || reopen ? "passed" : "idle"
);
}
);
test("shows the countdown and disables actions during publish progress", () => {
const [validate, publish] = render(
"idle",
@@ -1,42 +1,9 @@
import { useCallback, useEffect, useRef, useState, type Ref } from "react";
import { Button, Flex, Tooltip, toast } from "@webstudio-is/design-system";
import { useState, type Ref } from "react";
import { Button, Flex, Tooltip } from "@webstudio-is/design-system";
import { CheckCircleIcon } from "@webstudio-is/icons";
export type PublishValidationState = "idle" | "passed";
export const usePublishValidationState = (
dialog: "none" | "publish" | "export"
) => {
const [validationState, setValidationState] =
useState<PublishValidationState>("idle");
const dialogRef = useRef(dialog);
dialogRef.current = dialog;
const reset = useCallback(() => {
setValidationState("idle");
}, []);
const update = useCallback((state: PublishValidationState) => {
if (state === "passed" && dialogRef.current !== "publish") {
toast.success("Validation passed. Ready to publish.", {
duration: Number.POSITIVE_INFINITY,
});
return;
}
if (dialogRef.current === "publish") {
setValidationState(state);
}
}, []);
useEffect(() => {
if (dialog !== "publish") {
reset();
}
}, [dialog, reset]);
return { validationState, update, reset };
};
export const PublishActions = ({
validationState,
validateDisabled,
@@ -1,4 +1,5 @@
import { act } from "react-dom/test-utils";
import { userEvent } from "@vitest/browser/context";
import { createRoot, type Root } from "react-dom/client";
import {
afterAll,
@@ -29,6 +30,7 @@ const requests: Array<{ path: string; input: unknown }> = [];
let publishResponse: unknown = { success: false, error: "Publish blocked" };
let jobStatus: "failed" | "success" = "failed";
let didPublish = false;
const logCursors: Array<number | undefined> = [];
beforeAll(async () => {
Object.defineProperty(Element.prototype, "scrollIntoView", {
@@ -62,6 +64,34 @@ beforeAll(async () => {
case "/trpc/api.publish.getJob":
data = { status: jobStatus, code: "BUILD_FAILED" };
break;
case "/trpc/api.publish.getLog": {
const cursor = (input[String(index)] as { cursor?: number })
.cursor;
logCursors.push(cursor);
data = {
availability: "available",
startedAt: "2026-11-13T10:00:00.000Z",
completedAt: "2026-11-13T10:00:03.000Z",
log: {
encoding: "base64url",
chunk: btoa(
String.fromCharCode(
...(cursor === undefined ? [0xe2] : [0x82, 0xac])
)
),
complete: cursor !== undefined,
nextCursor: cursor === undefined ? 1 : undefined,
issues: [
{
severity: cursor === undefined ? "warning" : "error",
message:
cursor === undefined ? "Early warning" : "Late error",
},
],
},
};
break;
}
case "/trpc/domain.project":
data = {
success: true,
@@ -121,6 +151,11 @@ beforeEach(() => {
requests.length = 0;
jobStatus = "failed";
didPublish = false;
logCursors.length = 0;
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
});
});
test("a successful site runner finishes the current publish and retains its report", async () => {
@@ -208,9 +243,98 @@ afterEach(() => {
root = undefined;
resetStores = undefined;
document.body.innerHTML = "";
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
});
vi.restoreAllMocks();
});
test("a paid publish loads every log page and hides it after downgrade", 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,
});
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: 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) {
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(logCursors).toEqual([undefined, 1]))
);
const report = document.body.querySelector<HTMLButtonElement>(
'button[aria-label^="Publish log:"]'
)!;
await act(async () => report.click());
expect(document.body.textContent).toContain("€");
const selectTab = async (name: string) => {
const tab = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
).find((candidate) => candidate.textContent?.startsWith(name));
expect(tab).toBeDefined();
await act(async () => userEvent.click(tab!));
};
await selectTab("Errors");
expect(document.body.textContent).toContain("Late error");
await selectTab("Warnings");
expect(document.body.textContent).toContain("Early warning");
await selectTab("Publish");
await act(async () =>
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
})
);
expect(document.body.textContent).not.toContain("€");
expect(document.body.textContent).toContain(
"Upgrade to Pro to view publish logs."
);
});
afterAll(() => {
vi.unstubAllGlobals();
vi.resetModules();
@@ -0,0 +1,761 @@
import { act } from "react-dom/test-utils";
import { createRoot, type Root } from "react-dom/client";
import { userEvent } from "@vitest/browser/context";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
expect,
test,
vi,
} from "vitest";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
import type { Project } from "@webstudio-is/project";
import type { Pages } from "@webstudio-is/sdk";
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 root: Root;
let container: HTMLDivElement;
let PublishButton: typeof import("./publish").PublishButton;
let stores: typeof import("~/shared/sync/data-stores");
let nanoStates: typeof import("~/shared/nano-states");
let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog;
let assetBridge: typeof import("~/shared/asset-content-bridge.client");
let contentSession: ReturnType<typeof createAssetContentSession>;
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.includes(",")) {
const results = path
.slice("/trpc/".length)
.split(",")
.map((route) => {
if (route === "domain.project") {
return {
result: {
data: { success: true, project: stores.$project.get() },
},
};
}
if (route === "domain.countTotalDomains") {
return { result: { data: { success: true, data: 0 } } };
}
if (route === "project.userPublishCount") {
return { result: { data: { success: true, data: 0, limit: 100 } } };
}
if (route === "api.publish.getLog") {
return {
result: {
data: {
availability: "available",
log: {
encoding: "base64url",
chunk: btoa("older publish output"),
complete: true,
issues: [
{ severity: "error", message: "older build issue" },
],
},
},
},
};
}
throw new Error(`Unexpected request: ${route}`);
});
return new Response(JSON.stringify(results), {
headers: { "Content-Type": "application/json" },
});
}
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("older publish output"),
complete: true,
issues: [{ severity: "error", message: "older build issue" }],
},
});
}
if (path === "/trpc/domain.project") {
return respond({ success: true, project: stores.$project.get() });
}
if (path === "/trpc/domain.countTotalDomains") {
return respond({ success: true, data: 0 });
}
if (path === "/trpc/project.userPublishCount") {
return respond({ success: true, data: 0, limit: 100 });
}
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}`);
});
PublishButton = (await import("./publish")).PublishButton;
stores = await import("~/shared/sync/data-stores");
nanoStates = await import("~/shared/nano-states");
publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog;
assetBridge = await import("~/shared/asset-content-bridge.client");
(await import("~/shared/csrf.client")).updateCsrfToken("test-token");
});
beforeEach(() => {
contentSession = createAssetContentSession({
authorize: () => true,
repository: {
readContent: async () => {
throw new Error("No assets in this project");
},
updateContent: async () => {
throw new Error("No assets in this project");
},
},
});
assetBridge.__testing__.initBridge(
assetBridge.createAssetContentBridge({
origin: location.origin,
request: fetch,
authorize: () => true,
requireReload: () => {},
getContentSession: () => contentSession,
})
);
checks = deferred<Response>();
dispatch = deferred<Response>();
checkRequests = 0;
checksRead = 0;
publishRequests = 0;
vi.spyOn(toast, "error").mockImplementation(() => "");
stores.$project.set({
id: "project",
domain: "example",
domainsVirtual: [],
latestStaticBuild: null,
} as unknown as Project);
nanoStates.$authTokenPermissions.set({
canClone: true,
canCopy: true,
canPublish: true,
});
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
});
publishDialog.set("none");
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
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();
assetBridge.__testing__.clearBridge();
contentSession.dispose();
stores.$project.set(undefined);
stores.$pages.set(undefined);
stores.$instances.set(new Map());
stores.$props.set(new Map());
stores.$dataSources.set(new Map());
stores.$resources.set(new Map());
stores.$assets.set(new Map());
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
});
publishDialog.set("none");
vi.restoreAllMocks();
});
afterAll(() => vi.unstubAllGlobals());
const mount = async (target: "site" | "static") => {
publishDialog.set(target === "site" ? "publish" : "export");
await act(async () =>
root.render(
<TooltipProvider>
<PublishButton projectId="project" />
</TooltipProvider>
)
);
if (target === "static") {
const destination = document.body.querySelector<HTMLButtonElement>(
'button[role="combobox"]'
);
await act(async () =>
destination?.dispatchEvent(
new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
)
);
const staticOption = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="option"]')
).find((option) => option.textContent?.trim() === "Static");
await act(async () => staticOption?.click());
return;
}
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
);
if (domain?.checked === false) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
};
const clickPublish = async (target: "site" | "static", expected = 1) => {
const label =
target === "site" ? "Publish" : "Build and download static site";
const button = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
)
.filter((candidate) => candidate.textContent?.trim() === label)
.at(-1);
expect(button).toBeDefined();
await act(async () => vi.waitFor(() => expect(button?.disabled).toBe(false)));
await act(async () => button?.click());
await act(async () =>
vi.waitFor(() =>
expect([checkRequests, publishRequests]).toEqual([expected, expected])
)
);
};
const completeChecks = async (fail: boolean) => {
await 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" }],
})
);
}
await checks.promise.catch(() => {});
await vi.waitFor(() => expect(checksRead).toBe(checkRequests));
});
};
const openErrors = async (target: "site" | "static") => {
if (target === "site") {
const issues = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
).find((button) => button.textContent?.trim() === "See issues");
const status = document.body.querySelector<HTMLButtonElement>(
'button[aria-label^="Publish log:"]'
);
expect(issues ?? status).toBeDefined();
if (issues !== undefined) {
await act(async () => userEvent.click(issues));
} else {
await act(async () => status?.click());
}
}
const findErrors = () =>
Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
).find((tab) => tab.textContent?.startsWith("Errors"));
await act(async () => vi.waitFor(() => expect(findErrors()).toBeDefined()));
const errors = findErrors();
expect(errors).toBeDefined();
await act(async () => userEvent.click(errors!));
return document.body.querySelector<HTMLElement>(
'[role="tabpanel"][data-state="active"]'
);
};
const closeReport = async () => {
const close = document.body.querySelector<HTMLButtonElement>(
'[role="dialog"] button[aria-label="Close"]'
);
expect(close).toBeDefined();
await act(async () => close?.click());
await vi.waitFor(async () => {
await act(async () => {});
expect(document.body.querySelector('[role="dialog"]')).toBeNull();
});
};
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 remains visible with %s (failed checks: %s)",
async (target, order, failChecks) => {
await mount(target);
await clickPublish(target);
if (order === "checks-first") {
await completeChecks(failChecks);
}
await act(async () => {
dispatch.resolve(
respond({
success: false,
auditFindings: [{ severity: "error", message: "server rejection" }],
})
);
await dispatch.promise;
});
const errors = await openErrors(target);
expect(errors?.textContent).toContain("server rejection");
if (order === "server-first") {
await completeChecks(failChecks);
}
if (failChecks) {
expect(errors?.textContent?.includes("check failure")).toBe(
order === "checks-first"
);
} else {
expect(
Array.from(document.body.querySelectorAll('[role="tab"]')).some((tab) =>
tab.textContent?.startsWith("Warnings")
)
).toBe(order === "checks-first");
}
}
);
test("closing Publish clears a completed validation", async () => {
stores.$pages.set({
pages: new Map(),
folders: new Map(),
} as unknown as Pages);
stores.$instances.set(new Map());
stores.$props.set(new Map());
stores.$dataSources.set(new Map());
stores.$resources.set(new Map());
stores.$assets.set(new Map());
await mount("site");
const validate = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
)
.filter((button) => button.textContent?.trim() === "Validate")
.at(-1);
expect(validate).toBeDefined();
await act(async () => validate?.click());
await act(async () => vi.waitFor(() => expect(checkRequests).toBe(1)));
await act(async () => {
checks.resolve(
respond({
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
})
);
await checks.promise;
await vi.waitFor(() => expect(checksRead).toBe(1));
});
expect(
Array.from(document.body.querySelectorAll("button")).some(
(button) => button.textContent?.trim() === "Validated"
)
).toBe(true);
await act(async () => publishDialog.set("none"));
await act(async () => publishDialog.set("publish"));
expect(
Array.from(document.body.querySelectorAll("button")).some(
(button) => button.textContent?.trim() === "Validate"
)
).toBe(true);
});
test.each([
["request", "checks-first"],
["request", "server-first"],
["transport", "checks-first"],
["transport", "server-first"],
] as const)(
"static %s failure remains visible with %s checks",
async (failure, order) => {
await mount("static");
await clickPublish("static");
if (order === "checks-first") {
await completeChecks(false);
}
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(() => {});
});
if (order === "server-first") {
await completeChecks(false);
}
const status = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
);
await act(async () => status?.click());
const errors = await openErrors("static");
expect(errors?.textContent).toContain(message);
}
);
test.each(["checks-first", "server-first"] as const)(
"site transport failure remains visible with %s checks",
async (order) => {
await mount("site");
await clickPublish("site");
if (order === "checks-first") {
await completeChecks(false);
}
await act(async () => {
dispatch.reject(new Error("site transport failure"));
await dispatch.promise.catch(() => {});
});
if (order === "server-first") {
await completeChecks(false);
}
const errors = await openErrors("site");
expect(errors?.textContent).toContain("site transport failure");
}
);
test.each(["request", "transport"] as const)(
"a static %s failure does not replace an earlier site failure",
async (failure) => {
await mount("site");
await clickPublish("site");
await completeChecks(false);
await act(async () => {
dispatch.resolve(respond({ success: false, error: "site rejection" }));
await dispatch.promise;
});
const originalSiteErrors = await openErrors("site");
expect(originalSiteErrors?.textContent).toContain("site rejection");
await closeReport();
checks = deferred<Response>();
dispatch = deferred<Response>();
await mount("static");
await clickPublish("static", 2);
await completeChecks(false);
await act(async () => {
if (failure === "request") {
dispatch.resolve(
respond({ success: false, error: "static rejection" })
);
} else {
dispatch.reject(new Error("static transport"));
}
await dispatch.promise.catch(() => {});
});
await act(async () =>
vi.waitFor(() =>
expect(toast.error).toHaveBeenCalledWith(
failure === "request" ? "static rejection" : "static transport"
)
)
);
const staticStatus = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
);
expect(staticStatus).toBeDefined();
await act(async () => staticStatus?.click());
const staticErrors = await openErrors("static");
expect(staticErrors?.textContent).toContain(
failure === "request" ? "static rejection" : "static transport"
);
await closeReport();
await mount("site");
const siteErrors = await openErrors("site");
expect(siteErrors?.textContent).toContain("site rejection");
expect(siteErrors?.textContent).not.toContain("static rejection");
expect(siteErrors?.textContent).not.toContain("static transport");
}
);
test("a site transport error appears only for its attempted domain", async () => {
stores.$project.set({
id: "project",
domain: "example",
domainsVirtual: [
{
domain: "other.example",
projectId: "project",
domainId: "other-id",
status: "ACTIVE",
verified: true,
updatedAt: new Date().toISOString(),
latestBuildVirtual: null,
},
],
latestStaticBuild: null,
} as unknown as Project);
await mount("site");
await clickPublish("site");
await completeChecks(false);
await act(async () => {
dispatch.reject(new Error("scoped transport failure"));
await dispatch.promise.catch(() => {});
});
const otherDomainStatus = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: other.example"]'
);
expect(otherDomainStatus).toBeDefined();
await act(async () => otherDomainStatus?.click());
expect(
document.body.querySelector('[role="dialog"]')?.textContent
).not.toContain("scoped transport failure");
await closeReport();
await mount("site");
const attemptedDomainStatus = Array.from(
document.body.querySelectorAll<HTMLButtonElement>(
'button[aria-label^="Publish log:"]'
)
).find(
(button) =>
button.getAttribute("aria-label") !== "Publish log: other.example"
);
expect(attemptedDomainStatus).toBeDefined();
await act(async () => attemptedDomainStatus?.click());
expect(document.body.querySelector('[role="dialog"]')?.textContent).toContain(
"scoped transport failure"
);
});
test.each(["site", "static"] as const)(
"%s check failure has one notice while Publish is open",
async (target) => {
await mount(target);
await clickPublish(target);
publishDialog.set("publish");
await completeChecks(true);
expect(toast.error).toHaveBeenCalledTimes(target === "site" ? 0 : 1);
}
);
test("an accepted site failure links to its own publish log", async () => {
await mount("site");
await clickPublish("site");
await completeChecks(false);
await act(async () => {
dispatch.resolve(
respond({
success: true,
buildId: "accepted-build",
logHandle: "handle",
findings: [],
})
);
await dispatch.promise;
});
const errors = await openErrors("site");
const showLogs = Array.from(
errors?.querySelectorAll<HTMLButtonElement>("button") ?? []
).find((button) => button.textContent?.trim() === "show logs");
expect(showLogs).toBeDefined();
await act(async () => showLogs?.click());
expect(
document.body.querySelector('[role="tab"][aria-selected="true"]')
?.textContent
).toBe("Publish");
});
test.each([
["none", false, 1],
["none", true, 0],
["export", false, 1],
["publish", false, 0],
] as const)(
"validation completed after switching to %s (reopened: %s)",
async (destination, reopen, expectedToasts) => {
const successToast = vi
.spyOn(toast, "success")
.mockImplementation(() => "");
stores.$pages.set({
pages: new Map(),
folders: new Map(),
} as unknown as Pages);
stores.$instances.set(new Map());
stores.$props.set(new Map());
stores.$dataSources.set(new Map());
stores.$resources.set(new Map());
stores.$assets.set(new Map());
await mount("site");
const validate = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
)
.filter((button) => button.textContent?.trim() === "Validate")
.at(-1);
expect(validate).toBeDefined();
await act(async () =>
vi.waitFor(() => expect(validate?.disabled).toBe(false))
);
expect(
new FormData(validate?.closest("form")!).getAll("domainToPublish[]")
).toEqual(["example"]);
await act(async () => validate?.click());
expect(validate?.dataset.state).toBe("pending");
await act(async () => vi.waitFor(() => expect(checkRequests).toBe(1)));
await act(async () => publishDialog.set(destination));
if (reopen) {
expect(
document.body.querySelector('input[name="domainToPublish[]"]')
).toBeNull();
await act(async () => publishDialog.set("publish"));
}
await act(async () => {
checks.resolve(
respond({
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
})
);
await checks.promise;
await vi.waitFor(() => expect(checksRead).toBe(1));
});
expect(successToast).toHaveBeenCalledTimes(expectedToasts);
if (destination === "publish" || reopen) {
expect(
Array.from(document.body.querySelectorAll("button")).some(
(button) => button.textContent?.trim() === "Validated"
)
).toBe(true);
} else {
await act(async () => publishDialog.set("publish"));
expect(
Array.from(document.body.querySelectorAll("button")).some(
(button) => button.textContent?.trim() === "Validate"
)
).toBe(true);
}
}
);
test.each([
["site", "request"],
["site", "transport"],
["site", "audit"],
["static", "request"],
["static", "transport"],
["static", "audit"],
] as const)(
"a newer %s %s rejection does not show an older build issue",
async (target, failure) => {
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
await mount(target);
await clickPublish(target);
await completeChecks(false);
await act(async () => {
dispatch.resolve(
respond({
success: true,
buildId: "older-build",
logHandle: "older-handle",
findings: [],
...(target === "static" ? { name: "site.zip" } : {}),
})
);
await dispatch.promise;
});
await act(async () =>
vi.waitFor(() =>
expect(
document.body.querySelector<HTMLButtonElement>(
'button[aria-label^="Publish log:"]'
)
).not.toBeNull()
)
);
checks = deferred<Response>();
dispatch = deferred<Response>();
await mount(target);
await clickPublish(target, 2);
const message = `new ${failure} 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(() => {});
});
await completeChecks(false);
if (target === "static") {
const status = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
);
await act(async () => status?.click());
}
const errors = await openErrors(target);
expect(errors?.textContent).toContain(message);
expect(errors?.textContent).not.toContain("older build issue");
}
);
@@ -0,0 +1,807 @@
import { act } from "react-dom/test-utils";
import { createRoot, type Root } from "react-dom/client";
import { userEvent } from "@vitest/browser/context";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
expect,
test,
vi,
} from "vitest";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT;
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 };
};
let root: Root | undefined;
let container: HTMLDivElement;
let PublishButton: typeof import("./publish").PublishButton;
let stores: typeof import("~/shared/sync/data-stores");
let nanoStates: typeof import("~/shared/nano-states");
let dialog: typeof import("~/builder/shared/nano-states").$publishDialog;
let assetBridge: typeof import("~/shared/asset-content-bridge.client");
let contentSession: ReturnType<typeof createAssetContentSession>;
let initialPlan: ReturnType<typeof nanoStates.$planFeatures.get>;
let project: Project;
let publish: () => Promise<unknown>;
let refresh: () => Promise<unknown>;
let validate: () => Promise<unknown>;
let job: () => Promise<unknown>;
const requests: { route: string; input: unknown }[] = [];
const checks = {
diagnostics: { mdxErrors: [], mdxOmissions: [] },
cssValid: true,
};
const warningChecks = { ...checks, cssValid: false };
const makeProject = (
id = "project",
build?: { buildId: string; publishStatus: string }
) =>
({
id,
domain: "example",
domainsVirtual: [],
latestStaticBuild: null,
latestBuildVirtual:
build === undefined
? null
: {
...build,
domain: "example",
createdAt: new Date().toISOString(),
},
}) as unknown as Project;
beforeAll(async () => {
reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
vi.resetModules();
vi.stubGlobal(
"fetch",
async (info: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(String(info), location.href);
const inputs = JSON.parse(
init?.body === undefined
? (url.searchParams.get("input") ?? "{}")
: String(init.body)
);
const results = await Promise.all(
url.pathname
.slice("/trpc/".length)
.split(",")
.map(async (route, index) => {
requests.push({ route, input: inputs[String(index)] });
let data: unknown;
switch (route) {
case "domain.project":
data = await refresh();
break;
case "domain.publish":
data = await publish();
break;
case "api.publish.validate":
case "build.contentDatabasePublishDiagnostics":
data = await validate();
break;
case "api.publish.getJob":
data = await job();
break;
case "domain.countTotalDomains":
data = { success: true, data: 0 };
break;
case "project.userPublishCount":
data = { success: true, data: 0, limit: 100 };
break;
default:
throw new Error(`Unexpected request: ${route}`);
}
return { result: { data } };
})
);
return new Response(JSON.stringify(results), {
headers: { "Content-Type": "application/json" },
});
}
);
PublishButton = (await import("./publish")).PublishButton;
stores = await import("~/shared/sync/data-stores");
nanoStates = await import("~/shared/nano-states");
initialPlan = nanoStates.$planFeatures.get();
dialog = (await import("~/builder/shared/nano-states")).$publishDialog;
assetBridge = await import("~/shared/asset-content-bridge.client");
(await import("~/shared/csrf.client")).updateCsrfToken("test-token");
});
beforeEach(() => {
contentSession = createAssetContentSession({
authorize: () => true,
repository: {
readContent: async () => {
throw new Error("No assets in this project");
},
updateContent: async () => {
throw new Error("No assets in this project");
},
},
});
assetBridge.__testing__.initBridge(
assetBridge.createAssetContentBridge({
origin: location.origin,
request: fetch,
authorize: () => true,
requireReload: () => {},
getContentSession: () => contentSession,
})
);
project = makeProject();
publish = async () => ({ success: false, error: "request rejection" });
refresh = async () => ({ success: true, project });
validate = async () => checks;
job = async () => ({ status: "failed", code: "runner_failed" });
requests.length = 0;
stores.$project.set(project);
stores.$pages.set({
homePageId: "home",
rootFolderId: "root",
pages: new Map(),
folders: new Map(),
});
stores.$instances.set(new Map());
stores.$props.set(new Map());
stores.$dataSources.set(new Map());
stores.$resources.set(new Map());
stores.$assets.set(new Map());
nanoStates.$authTokenPermissions.set({
canClone: true,
canCopy: true,
canPublish: true,
});
nanoStates.$planFeatures.set({
...initialPlan,
allowPublishLogs: false,
});
dialog.set("publish");
vi.spyOn(toast, "error").mockImplementation(() => "");
vi.spyOn(toast, "success").mockImplementation(() => "");
vi.spyOn(console, "error").mockImplementation(() => {});
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
act(() => root?.unmount());
root = undefined;
container.remove();
dialog.set("none");
stores.$project.set(undefined);
stores.$pages.set(undefined);
assetBridge.__testing__.clearBridge();
contentSession.dispose();
nanoStates.$planFeatures.set(initialPlan);
nanoStates.$authPermit.set("view");
vi.useRealTimers();
vi.restoreAllMocks();
});
afterAll(() => {
vi.unstubAllGlobals();
reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
});
const button = (label: string) =>
Array.from(document.body.querySelectorAll<HTMLButtonElement>("button"))
.filter((candidate) => {
const copy = candidate.cloneNode(true) as HTMLElement;
copy.querySelectorAll("svg").forEach((icon) => icon.remove());
return copy.textContent?.trim() === label;
})
.at(-1);
const click = async (label: string) => {
const target = button(label);
expect(target).toBeDefined();
expect(target?.disabled).toBe(false);
await act(async () => target?.click());
};
const mount = async (projectId = "project") => {
await act(async () =>
root?.render(
<TooltipProvider>
<PublishButton projectId={projectId} />
</TooltipProvider>
)
);
if (vi.isFakeTimers()) {
await act(async () => vi.advanceTimersByTimeAsync(10));
}
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
);
if (domain?.checked === false) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
};
const toggle = async (value: "publish" | "none" | "export") => {
if (value === "none") {
await act(async () =>
document.dispatchEvent(
new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
)
);
} else if (value === "publish" && dialog.get() === "none") {
await act(async () =>
container.querySelector<HTMLButtonElement>("button")?.click()
);
} else {
await act(async () => dialog.set(value));
}
if (vi.isFakeTimers()) {
await act(async () => vi.advanceTimersByTimeAsync(20));
}
if (value === "publish") {
const domains = Array.from(
document.body.querySelectorAll<HTMLInputElement>(
'input[name="domainToPublish[]"]'
)
);
if (domains.length > 0 && domains.every((domain) => !domain.checked)) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
}
};
const waitFor = async (check: () => void) => {
await vi.waitFor(async () => {
await act(async () => {});
check();
});
};
const banner = () => button("See issues")?.parentElement;
const accept = () => ({
success: true,
buildId: "accepted",
logHandle: "handle",
findings: [],
});
const openReport = async (tab: "Errors" | "Warnings") => {
await click("See issues");
await waitFor(() =>
expect(document.body.querySelector('[role="tablist"]')).not.toBeNull()
);
const target = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
).find((item) => item.textContent?.startsWith(tab));
expect(target).toBeDefined();
await act(async () => userEvent.click(target!));
const report = document.body.querySelector(
'[role="tabpanel"][data-state="active"]'
);
expect(report).not.toBeNull();
return report!;
};
test.each(["open", "closed", "reopened"] as const)(
"a transport failure uses the current %s panel without duplicate notices",
async (state) => {
const response = deferred<unknown>();
publish = () => response.promise;
await mount();
await click("Publish");
await waitFor(() =>
expect(requests.some(({ route }) => route === "domain.publish")).toBe(
true
)
);
if (state !== "open") {
await toggle("none");
}
if (state === "reopened") {
await toggle("publish");
}
await act(async () => response.reject(new Error("transport failure")));
await waitFor(() =>
expect(
state === "closed" ? toast.error : button("See issues")
).toBeDefined()
);
if (state === "closed") {
await waitFor(() => expect(toast.error).toHaveBeenCalledOnce());
await toggle("publish");
} else {
expect(toast.error).not.toHaveBeenCalled();
}
await waitFor(() =>
expect(banner()?.textContent).toContain("transport failure")
);
await toggle("none");
await toggle("publish");
expect(banner()).toBeDefined();
}
);
test("starting validation clears a request failure", async () => {
await mount();
await click("Publish");
await waitFor(() => expect(banner()).toBeDefined());
await click("Validate");
await waitFor(() => expect(button("Validated")).toBeDefined());
expect(banner()).toBeUndefined();
});
test.each(["PUBLISHED", "none"] as const)(
"a %s refresh clears a retained status error",
async (status) => {
publish = async () => accept();
project = makeProject("project", {
buildId: "accepted",
publishStatus: "FAILED",
});
await mount();
await click("Publish");
await waitFor(() => expect(banner()).toBeDefined());
await toggle("none");
await toggle("publish");
expect(banner()).toBeDefined();
project =
status === "none"
? makeProject()
: makeProject("project", {
buildId: "accepted",
publishStatus: status,
});
await toggle("none");
await toggle("publish");
await waitFor(() => expect(banner()).toBeUndefined());
}
);
test.each(["PUBLISHED", "none"] as const)(
"a %s refresh preserves a rejected request error",
async (status) => {
project =
status === "none"
? makeProject()
: makeProject("project", { buildId: "old", publishStatus: status });
await mount();
await click("Publish");
await waitFor(() => expect(banner()).toBeDefined());
await toggle("none");
await toggle("publish");
await waitFor(() =>
expect(
requests.filter(({ route }) => route === "domain.project").length
).toBeGreaterThan(1)
);
expect(banner()?.textContent).toContain("request rejection");
}
);
test.each(["PUBLISHED", "FAILED"] as const)(
"a recovered %s build replaces a lost response only when the build changes",
async (status) => {
project = makeProject("project", {
buildId: "old",
publishStatus: "PUBLISHED",
});
publish = async () => {
throw new Error("transport failure");
};
await mount();
await click("Publish");
await waitFor(() =>
expect(banner()?.textContent).toContain("transport failure")
);
await toggle("none");
await toggle("publish");
expect(banner()?.textContent).toContain("transport failure");
project = makeProject("project", { buildId: "new", publishStatus: status });
await toggle("none");
await toggle("publish");
await waitFor(() =>
expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new")
);
if (status === "PUBLISHED") {
expect(banner()).toBeUndefined();
} else {
expect(banner()).toBeDefined();
expect(banner()?.textContent).not.toContain("transport failure");
}
}
);
test("a recovered pending build keeps polling after the popover closes", async () => {
vi.useFakeTimers();
project = makeProject("project", {
buildId: "recovered",
publishStatus: "PENDING",
});
await mount();
await waitFor(() =>
expect(
requests.filter(({ route }) => route === "domain.project")
).toHaveLength(2)
);
await act(async () => vi.advanceTimersByTimeAsync(10));
await toggle("none");
project = makeProject("project", {
buildId: "recovered",
publishStatus: "PUBLISHED",
});
await act(async () => vi.advanceTimersByTimeAsync(15_100));
expect(toast.success).toHaveBeenCalledOnce();
});
test("an older recovered poll cannot replace a newer popover refresh", async () => {
const stale = deferred<unknown>();
let refreshes = 0;
project = makeProject("project", {
buildId: "recovered",
publishStatus: "PENDING",
});
refresh = async () =>
++refreshes === 2 ? stale.promise : { success: true, project };
await mount();
await waitFor(() => expect(refreshes).toBe(2));
project = makeProject("project", {
buildId: "new",
publishStatus: "PUBLISHED",
});
await toggle("none");
await toggle("publish");
await waitFor(() =>
expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new")
);
await act(async () =>
stale.resolve({
success: true,
project: makeProject("project", {
buildId: "old",
publishStatus: "PUBLISHED",
}),
})
);
expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new");
});
test("an old status request cannot update a remounted copy of the same project", async () => {
const stale = deferred<unknown>();
let refreshes = 0;
project = makeProject("project", {
buildId: "recovered",
publishStatus: "PENDING",
});
refresh = async () =>
++refreshes === 2 ? stale.promise : { success: true, project };
await mount();
await waitFor(() => expect(refreshes).toBe(2));
act(() => root?.unmount());
project = makeProject("other");
stores.$project.set(project);
project = makeProject("project", {
buildId: "new",
publishStatus: "PUBLISHED",
});
stores.$project.set(project);
root = createRoot(container);
await mount();
await act(async () =>
stale.resolve({
success: true,
project: makeProject("project", {
buildId: "old",
publishStatus: "PUBLISHED",
}),
})
);
expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new");
expect(toast.success).not.toHaveBeenCalled();
});
test.each(["success", "transport"] as const)(
"an old project's %s response cannot finish a new project's publish",
async (outcome) => {
const old = deferred<unknown>();
const current = deferred<unknown>();
let publishes = 0;
publish = () => (++publishes === 1 ? old.promise : current.promise);
await mount();
await click("Publish");
await waitFor(() => expect(publishes).toBe(1));
project = makeProject("new-project");
await act(async () => stores.$project.set(project));
await mount("new-project");
await click("Publish");
await waitFor(() => expect(publishes).toBe(2));
await act(async () => {
if (outcome === "success") {
old.resolve(accept());
} else {
old.reject(new Error("old failure"));
}
});
expect(button("Publishing (60s)")?.disabled).toBe(true);
expect(toast.error).not.toHaveBeenCalled();
expect(toast.success).not.toHaveBeenCalled();
await act(async () =>
current.resolve({ success: false, error: "current failure" })
);
await waitFor(() => expect(banner()).toBeDefined());
}
);
test("closing publish hides its countdown while polling continues to completion", async () => {
vi.useFakeTimers();
const pending = deferred<unknown>();
publish = async () => accept();
job = () => pending.promise;
await mount();
await click("Publish");
await waitFor(() =>
expect(requests.some(({ route }) => route === "api.publish.getJob")).toBe(
true
)
);
expect(button("Publishing (60s)")?.disabled).toBe(true);
await act(async () => vi.advanceTimersByTimeAsync(10_000));
expect(button("Publishing (50s)")?.disabled).toBe(true);
await toggle("none");
await toggle("publish");
expect(button("Publish")?.disabled).toBe(true);
await toggle("none");
project = makeProject("project", {
buildId: "accepted",
publishStatus: "PUBLISHED",
});
await act(async () => pending.resolve({ status: "success" }));
await act(async () => vi.advanceTimersByTimeAsync(100));
await toggle("publish");
expect(button("Publish")?.disabled).toBe(false);
expect(button("Publish")?.dataset.state).not.toBe("pending");
expect(toast.success).toHaveBeenCalledOnce();
});
test.each(["validation", "publish"] as const)(
"%s diagnostics remain available after the popover reopens",
async (action) => {
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
const response = deferred<unknown>();
publish = () => response.promise;
validate = async () => warningChecks;
await mount();
await click(action === "validation" ? "Validate" : "Publish");
await waitFor(() => expect(banner()).toBeDefined());
if (action === "publish") {
await act(async () =>
response.resolve({ success: false, error: "request rejection" })
);
await waitFor(() => expect(button("Publish")?.disabled).toBe(false));
}
await toggle("none");
await toggle("publish");
expect(banner()).toBeDefined();
const report = await openReport("Warnings");
expect(report?.querySelector("button")).not.toBeNull();
}
);
test("an older validation cannot replace a newer report", async () => {
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
const old = deferred<unknown>();
let validations = 0;
validate = async () => (++validations === 1 ? old.promise : warningChecks);
await mount();
await click("Validate");
await waitFor(() => expect(validations).toBe(1));
await toggle("none");
await toggle("publish");
await click("Validate");
await waitFor(() => expect(validations).toBe(2));
await waitFor(() => expect(banner()).toBeDefined());
await act(async () => old.resolve(checks));
expect(banner()).toBeDefined();
expect(button("Validated")).toBeDefined();
const report = await openReport("Warnings");
expect(report?.querySelector("button")).not.toBeNull();
});
test("older publish diagnostics cannot replace a newer operation", async () => {
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
const old = deferred<unknown>();
let validations = 0;
validate = async () => (++validations === 1 ? old.promise : warningChecks);
await mount();
await click("Publish");
await waitFor(() => expect(button("Publish")?.disabled).toBe(false));
await click("Validate");
await waitFor(() => expect(validations).toBe(2));
await waitFor(() => expect(banner()).toBeDefined());
await act(async () => old.resolve(checks));
expect(banner()).toBeDefined();
const report = await openReport("Warnings");
expect(report?.querySelector("button")).not.toBeNull();
});
test("reopening restores validated domains and publishes only those domains", async () => {
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowStagingPublish: true,
});
nanoStates.$authPermit.set("own");
project = {
...makeProject("project", { buildId: "old", publishStatus: "PUBLISHED" }),
domainsVirtual: [
{
projectId: "project",
domainId: "custom",
domain: "custom.example",
status: "ACTIVE",
verified: true,
latestBuildVirtual: null,
updatedAt: new Date().toISOString(),
},
],
} as Project;
stores.$project.set(project);
validate = async () => warningChecks;
await mount();
const checkboxes = () =>
Array.from(
document.body.querySelectorAll<HTMLButtonElement>('[role="checkbox"]')
);
expect(checkboxes()).toHaveLength(2);
// The saved build makes staging selected by default. Validate only the custom domain.
await act(async () => checkboxes()[0].click());
if (checkboxes()[1].getAttribute("aria-checked") === "false") {
await act(async () => checkboxes()[1].click());
}
await click("Validate");
await waitFor(() => expect(banner()).toBeDefined());
await toggle("none");
await toggle("publish");
expect(checkboxes().map((item) => item.getAttribute("aria-checked"))).toEqual(
["false", "true"]
);
const form = button("Publish")!.closest("form")!;
expect(new FormData(form).getAll("domainToPublish[]")).toEqual([
"custom.example",
]);
await click("Publish");
await waitFor(() =>
expect(
requests.find(({ route }) => route === "domain.publish")
).toBeDefined()
);
expect(
requests.find(({ route }) => route === "domain.publish")?.input
).toMatchObject({ domains: ["custom.example"] });
await waitFor(() => expect(button("Publish")?.disabled).toBe(false));
await act(async () => checkboxes()[1].click());
expect(new FormData(form).getAll("domainToPublish[]")).toEqual([]);
});
const selectStatic = async () => {
await toggle("export");
const destination = document.body.querySelector<HTMLButtonElement>(
'button[role="combobox"]'
);
await act(async () =>
destination?.dispatchEvent(
new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
)
);
const option = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="option"]')
).find((item) => item.textContent?.trim() === "Static");
expect(option).toBeDefined();
await act(async () => option?.click());
};
test.each(["site", "static"] as const)(
"starting diagnostics for the other target keeps %s findings",
async (first) => {
let target: "site" | "static" = first;
publish = async () => ({
success: false,
auditFindings: [{ severity: "error", message: `${target} diagnostic` }],
});
await mount();
if (first === "static") {
await selectStatic();
}
await click(
first === "site" ? "Publish" : "Build and download static site"
);
await waitFor(() =>
expect(
requests.filter(({ route }) => route === "domain.publish")
).toHaveLength(1)
);
await waitFor(() => {
if (first === "static") {
expect(document.body.querySelector('[role="tablist"]')).not.toBeNull();
} else {
expect(banner()).toBeDefined();
expect(button("Publish")?.disabled).toBe(false);
}
});
if (first === "static") {
// Close the report before returning to the other publish target.
const close = document.body.querySelector<HTMLButtonElement>(
'[role="dialog"] button[aria-label="Close"]'
);
expect(close).not.toBeNull();
await act(async () => close?.click());
}
target = first === "site" ? "static" : "site";
if (target === "static") {
await selectStatic();
} else {
await toggle("publish");
}
await click(
target === "site" ? "Publish" : "Build and download static site"
);
await waitFor(() =>
expect(
requests.filter(({ route }) => route === "domain.publish")
).toHaveLength(2)
);
if (target === "static") {
await waitFor(() =>
expect(document.body.querySelector('[role="tablist"]')).not.toBeNull()
);
await act(async () =>
document.body
.querySelector<HTMLButtonElement>(
'[role="dialog"] button[aria-label="Close"]'
)
?.click()
);
}
if (first === "site") {
await toggle("publish");
const report = await openReport("Errors");
expect(report?.textContent).toContain("site diagnostic");
expect(report?.textContent).not.toContain("static diagnostic");
} else {
await selectStatic();
const reportButton = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
);
expect(reportButton).not.toBeNull();
await act(async () => reportButton?.click());
await waitFor(() =>
expect(document.body.querySelector('[role="tablist"]')).not.toBeNull()
);
expect(
document.body.querySelector('[role="tabpanel"][data-state="active"]')
?.textContent
).toContain("static diagnostic");
}
}
);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,219 @@
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,
getPublishStatusDisplay,
getStaticPublishStatusDisplay,
} from "./publish-status";
const STATUS_REFRESH_RETRY_DELAY = 5_000;
const STATUS_REFRESH_MAX_ATTEMPTS = 3;
export type PublishExecution = {
projectId: string;
buildId: string;
logHandle?: string;
target?: "site" | "static";
};
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,
statusContent: "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 { statusContent, status } =
execution?.target === "static" &&
refreshedProject.latestStaticBuild != null
? getStaticPublishStatusDisplay(refreshedProject.latestStaticBuild)
: refreshedProject.latestBuildVirtual != null
? getPublishStatusDisplay(refreshedProject.latestBuildVirtual)
: {
statusContent: "Not published",
status: "PENDING" as const,
};
if (!runnerPending && (status === "PUBLISHED" || status === "FAILED")) {
return { status, statusContent };
}
}
} 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 refreshProjectWithRetry = 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 &&
getPublishStatusDisplay(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.statusContent);
}
setPublishError(result.statusContent, buildId);
}
};
export const fetchAndStoreProject = 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);
}
};
@@ -0,0 +1,429 @@
import { act } from "react-dom/test-utils";
import { createRoot, type Root } from "react-dom/client";
import { userEvent } from "@vitest/browser/context";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
expect,
test,
vi,
} from "vitest";
import { TooltipProvider } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
const deferred = <T,>() => {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
};
const encoded = (bytes: number[]) => btoa(String.fromCharCode(...bytes));
const logRequests: Array<{
cursor?: number;
projectId: string;
buildId: string;
}> = [];
let publishRequests = 0;
let buildId = "build-1";
let acceptedBuildId = "previous-build";
let withHandle = true;
let holdLog:
| { cursor?: number; response: ReturnType<typeof deferred<void>> }
| undefined;
let heldJob: ReturnType<typeof deferred<unknown>> | undefined;
let heldPublish: ReturnType<typeof deferred<unknown>> | undefined;
let PublishButton: typeof import("./publish").PublishButton;
let stores: typeof import("~/shared/sync/data-stores");
let nanoStates: typeof import("~/shared/nano-states");
let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog;
let root: Root;
let container: HTMLDivElement;
const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT;
const originalScrollIntoView = Object.getOwnPropertyDescriptor(
Element.prototype,
"scrollIntoView"
);
beforeAll(async () => {
reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
Object.defineProperty(Element.prototype, "scrollIntoView", {
configurable: true,
value: () => {},
});
vi.resetModules();
vi.stubGlobal(
"fetch",
async (requestInfo: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(String(requestInfo), "http://localhost");
const inputs = JSON.parse(
init?.body === undefined
? (url.searchParams.get("input") ?? "{}")
: String(init.body)
);
const results = await Promise.all(
url.pathname
.slice("/trpc/".length)
.split(",")
.map(async (route, index) => {
const input = inputs[String(index)];
let data: unknown;
switch (route) {
case "domain.project":
data = {
success: true,
project: {
...stores.$project.get(),
latestBuildVirtual: {
domain: "example",
buildId: acceptedBuildId,
createdAt: new Date().toISOString(),
publishStatus: "PUBLISHED",
},
},
};
break;
case "domain.countTotalDomains":
data = { success: true, data: 0 };
break;
case "project.userPublishCount":
data = { success: true, data: 0, limit: 100 };
break;
case "domain.publish":
publishRequests += 1;
data = heldPublish
? await heldPublish.promise
: {
success: true,
buildId,
...(withHandle ? { logHandle: "handle" } : {}),
findings: [],
};
acceptedBuildId = (data as { buildId: string }).buildId;
break;
case "api.publish.getJob":
data = heldJob ? await heldJob.promise : { status: "success" };
break;
case "api.publish.getLog": {
logRequests.push(input);
const first = input.cursor === undefined;
if (
input.buildId === "build-1" &&
holdLog &&
holdLog.cursor === input.cursor
) {
await holdLog.response.promise;
}
data = {
availability: "available",
startedAt: "2026-11-13T10:00:00.000Z",
completedAt: "2026-11-13T10:00:03.000Z",
log: {
encoding: "base64url",
chunk: first ? encoded([0xe2]) : encoded([0x82, 0xac]),
complete: !first,
nextCursor: first ? 1 : undefined,
issues: [
{
severity: first ? "warning" : "error",
message: first ? "Early warning" : "Late error",
},
],
issuesOmitted: first ? 1 : 0,
},
};
break;
}
case "build.contentDatabasePublishDiagnostics":
data = { mdxErrors: [], mdxOmissions: [] };
break;
default:
throw new Error(`Unexpected request: ${route}`);
}
return { result: { data } };
})
);
return new Response(JSON.stringify(results), {
headers: { "Content-Type": "application/json" },
});
}
);
PublishButton = (await import("./publish")).PublishButton;
stores = await import("~/shared/sync/data-stores");
nanoStates = await import("~/shared/nano-states");
publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog;
(await import("~/shared/csrf.client")).updateCsrfToken("test-token");
});
const project = (id: string) =>
({
id,
domain: "example",
domainsVirtual: [],
latestStaticBuild: null,
latestBuildVirtual: {
domain: "example",
buildId: "previous-build",
createdAt: new Date().toISOString(),
publishStatus: "PUBLISHED",
},
}) as unknown as Project;
beforeEach(() => {
buildId = "build-1";
acceptedBuildId = "previous-build";
publishRequests = 0;
logRequests.length = 0;
withHandle = true;
holdLog = undefined;
heldJob = undefined;
heldPublish = undefined;
nanoStates.$authTokenPermissions.set({
canClone: true,
canCopy: true,
canPublish: true,
});
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
stores.$project.set(project("project-1"));
publishDialog.set("publish");
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
act(() => root.unmount());
holdLog?.response.resolve();
heldJob?.resolve({ status: "success" });
heldPublish?.resolve({ success: true, buildId: "stale-build", findings: [] });
await act(async () => {});
container.remove();
stores.$project.set(undefined);
publishDialog.set("none");
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
});
vi.useRealTimers();
});
afterAll(() => {
vi.unstubAllGlobals();
vi.resetModules();
reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
if (originalScrollIntoView === undefined) {
Reflect.deleteProperty(Element.prototype, "scrollIntoView");
} else {
Object.defineProperty(
Element.prototype,
"scrollIntoView",
originalScrollIntoView
);
}
});
const render = async (projectId = "project-1") => {
await act(async () =>
root.render(
<TooltipProvider>
<PublishButton projectId={projectId} />
</TooltipProvider>
)
);
};
const setPaid = async (allowPublishLogs: boolean) => {
await act(async () =>
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs,
})
);
};
const publish = async () => {
await act(async () => publishDialog.set("none"));
await act(async () => publishDialog.set("publish"));
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
);
expect(domain).not.toBeNull();
if (domain?.checked === false) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
const button = Array.from(
domain!.closest("form")!.querySelectorAll<HTMLButtonElement>("button")
).at(-1)!;
await waitFor(() => expect(button.disabled).toBe(false));
const previousRequests = publishRequests;
await act(async () => button.click());
await act(async () =>
vi.waitFor(() => expect(publishRequests).toBe(previousRequests + 1))
);
};
const openReport = async () => {
await act(async () =>
document.body
.querySelector<HTMLButtonElement>('button[aria-label^="Publish log:"]')
?.click()
);
expect(document.body.querySelector('[role="tablist"]')).not.toBeNull();
};
const panel = () =>
document.body.querySelector<HTMLElement>(
'[role="tabpanel"][data-state="active"]'
)!;
const waitFor = async (assertion: () => void) => {
await vi.waitFor(async () => {
await act(async () => {});
assertion();
});
};
const entries = () =>
Array.from(
panel().querySelectorAll<HTMLElement>('[aria-labelledby^="publish-title-"]')
);
const changeProject = async (id: string) => {
await act(async () => {
stores.$project.set(project(id));
});
await render(id);
};
test("a pending publish shows its local start time, then the runner time and duration", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-11-15T10:00:00.000Z"));
heldJob = deferred<unknown>();
await render();
const localStart = new Date().toLocaleString();
await publish();
await openReport();
// Timestamp and duration formatting are the report's public data contract.
expect(panel().textContent).toContain(`Started: ${localStart}`);
await act(async () => heldJob?.resolve({ status: "success" }));
await waitFor(() =>
expect(panel().querySelector("pre")?.textContent).toBe("€")
);
expect(panel().textContent).toContain(
`Started: ${new Date("2026-11-13T10:00:00.000Z").toLocaleString()}`
);
expect(panel().textContent).toContain("Duration: 3s");
await setPaid(false);
expect(panel().textContent).not.toContain("Started:");
expect(panel().textContent).not.toContain("Duration:");
});
test("Free does not fetch logs; upgrading reads UTF-8 from byte zero and preserves issue severity", async () => {
await setPaid(false);
await render();
await publish();
await openReport();
expect(logRequests).toHaveLength(0);
expect(panel().querySelector("pre")).toBeNull();
expect(panel().querySelector('[role="note"]')).not.toBeNull();
await setPaid(true);
await waitFor(() =>
expect(panel().querySelector("pre")?.textContent).toBe("€")
);
expect(logRequests.map(({ cursor }) => cursor)).toEqual([undefined, 1]);
for (const [name, message] of [
["Errors", "Late error"],
["Warnings", "Early warning"],
]) {
const tab = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
).find((candidate) => candidate.textContent?.startsWith(name))!;
await act(async () => userEvent.click(tab));
expect(panel().textContent).toContain(message);
// Issue truncation is returned by the runner, not inferred from visible issues.
expect(panel().textContent).toContain("1 more issues not shown.");
}
await setPaid(false);
expect(panel().textContent).not.toContain("Late error");
expect(panel().textContent).not.toContain("Early warning");
expect(document.body.querySelector("pre")).toBeNull();
});
test("an accepted publish without a log handle is retained without retrying dispatch or reading logs", async () => {
withHandle = false;
await render();
await publish();
await openReport();
expect(entries()).toHaveLength(1);
expect(publishRequests).toBe(1);
expect(logRequests).toHaveLength(0);
});
test("a paid response after downgrade cannot restore logs; upgrading restarts from byte zero", async () => {
holdLog = { cursor: 1, response: deferred<void>() };
await render();
await publish();
await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(2)));
await openReport();
await setPaid(false);
await act(async () => holdLog?.response.resolve());
expect(panel().querySelector("pre")).toBeNull();
await setPaid(true);
await waitFor(() =>
expect(panel().querySelector("pre")?.textContent).toBe("€")
);
expect(logRequests.slice(2).map(({ cursor }) => cursor)).toEqual([
undefined,
1,
]);
});
test("a log response from the previous project cannot populate the new project's report", async () => {
holdLog = { response: deferred<void>() };
await render();
await publish();
await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(1)));
await changeProject("project-2");
await act(async () => holdLog?.response.resolve());
await openReport();
expect(entries()).toHaveLength(0);
expect(logRequests).toHaveLength(1);
});
test("a dispatch accepted after leaving and returning to its project cannot restore the old session", async () => {
heldPublish = deferred<unknown>();
await render();
await publish();
await changeProject("project-2");
await changeProject("project-1");
await act(async () =>
heldPublish?.resolve({
success: true,
buildId: "stale-build",
logHandle: "stale-handle",
findings: [],
})
);
await openReport();
expect(entries()).toHaveLength(0);
expect(logRequests).toHaveLength(0);
});
test("keeping ten publishes evicts an older in-flight reader before its next page", async () => {
holdLog = { response: deferred<void>() };
await render();
await publish();
await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(1)));
for (let index = 0; index < 10; index++) {
buildId = `new-build-${index}`;
await publish();
}
await act(async () => holdLog?.response.resolve());
await openReport();
expect(entries()).toHaveLength(10);
expect(document.getElementById("publish-title-build-1")).toBeNull();
expect(
logRequests.filter((request) => request.buildId === "build-1")
).toHaveLength(1);
});
@@ -8,8 +8,8 @@ import type { Project } from "@webstudio-is/project";
let root: Root | undefined;
let container: HTMLDivElement | undefined;
let publishModule: typeof import("./publish");
let flowModule: typeof import("./use-publish-flow");
let diagnosticsModule: typeof import("./diagnostics");
let nanoStates: typeof import("~/shared/nano-states");
let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog;
const acceptedResponse = {
success: true,
buildId: "static-1",
@@ -22,9 +22,17 @@ let projectStore: (typeof import("~/shared/sync/data-stores"))["$project"];
let getJobStatus: "pending" | "success" | "failed" = "pending";
let publishRequests = 0;
let jobRequests = 0;
let projectRequests = 0;
const downloads = vi.fn();
// Observe the real download URL without navigating away from the test runner.
const interceptDownload = (event: NavigateEvent) => {
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/cgi/static/ssg/")) {
event.preventDefault();
downloads(url.pathname);
}
};
const respond = (data: unknown) =>
new Response(JSON.stringify([{ result: { data } }]), {
headers: { "Content-Type": "application/json" },
@@ -35,9 +43,25 @@ const respond = (data: unknown) =>
).IS_REACT_ACT_ENVIRONMENT = true;
beforeAll(async () => {
window.navigation.addEventListener("navigate", interceptDownload);
vi.resetModules();
vi.stubGlobal("fetch", async (requestInfo: RequestInfo | URL) => {
const path = new URL(String(requestInfo), "http://localhost").pathname;
if (path.includes(",")) {
const responses = await Promise.all(
path
.slice("/trpc/".length)
.split(",")
.map(async (route) => {
const response = await fetch(`/trpc/${route}`);
const results = (await response.json()) as unknown[];
return results[0];
})
);
return new Response(JSON.stringify(responses), {
headers: { "Content-Type": "application/json" },
});
}
if (path === "/trpc/build.contentDatabasePublishDiagnostics") {
return respond({ mdxErrors: [], mdxOmissions: [] });
}
@@ -50,142 +74,152 @@ beforeAll(async () => {
return respond({ status: getJobStatus });
}
if (path === "/trpc/domain.project") {
projectRequests += 1;
return respond({
success: true,
project: {
id: "project-a",
latestStaticBuild: {
buildId: "static-1",
updatedAt: new Date().toISOString(),
publishStatus: "PUBLISHED",
},
...projectStore.get(),
latestStaticBuild:
publishRequests === 0
? null
: {
buildId: "static-1",
updatedAt: new Date().toISOString(),
publishStatus: "PUBLISHED",
},
},
});
}
throw new Error(`Unexpected request: ${path}`);
});
publishModule = await import("./publish");
flowModule = await import("./use-publish-flow");
diagnosticsModule = await import("./diagnostics");
nanoStates = await import("~/shared/nano-states");
publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog;
projectStore = (await import("~/shared/sync/data-stores")).$project;
const { updateCsrfToken } = await import("~/shared/csrf.client");
updateCsrfToken("test-token");
});
afterEach(() => {
act(() => root?.unmount());
afterEach(async () => {
await act(async () => root?.unmount());
if (vi.isFakeTimers()) {
// Finish queued tRPC batches before switching back to real timers.
await act(async () => vi.runAllTimersAsync());
}
root = undefined;
container?.remove();
container = undefined;
projectStore.set(undefined);
publishDialog.set("none");
getJobStatus = "pending";
staticResponse = acceptedResponse;
publishRequests = 0;
jobRequests = 0;
projectRequests = 0;
downloads.mockClear();
vi.useRealTimers();
vi.restoreAllMocks();
});
afterAll(() => vi.unstubAllGlobals());
afterAll(() => {
window.navigation.removeEventListener("navigate", interceptDownload);
vi.unstubAllGlobals();
});
const Harness = ({
open,
projectId = "project-a",
}: {
open: boolean;
projectId?: string;
}) => {
const flow = flowModule.usePublishFlow(projectId, false, "none");
return (
<TooltipProvider>
<output>{flow.isPublishing ? "pending" : "idle"}</output>
<output data-log-status>{flow.publishes[0]?.status}</output>
<output data-static-error>{flow.staticFailureFinding?.severity}</output>
{open && (
<publishModule.__testing__.PublishStatic
templates={["ssg"]}
flow={flow}
onDownload={downloads}
/>
)}
<diagnosticsModule.PublishDiagnosticsDialog
findings={flow.reportFindings}
includeLatestPublishFindings={flow.includeLatestPublishFindings}
items={flow.reportPublishes}
open={flow.diagnosticsSelection !== undefined}
onOpenChange={(open) => {
if (!open) {
flow.closeReport();
}
}}
initialTab={flow.diagnosticsSelection?.tab}
canViewPublishLogs={false}
/>
</TooltipProvider>
const createProject = (id = "project-a") =>
({
id,
domain: "example",
domainsVirtual: [],
latestStaticBuild: null,
}) as unknown as Project;
const staticButton = () =>
Array.from(document.body.querySelectorAll<HTMLButtonElement>("button")).find(
(button) => button.textContent?.startsWith("Build and download static site")
);
};
const render = (open: boolean, projectId = "project-a") => {
const render = async (open: boolean, projectId = "project-a") => {
nanoStates.$authTokenPermissions.set({
canClone: true,
canCopy: true,
canPublish: true,
});
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: false,
});
if (container === undefined) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
}
act(() => root?.render(<Harness open={open} projectId={projectId} />));
await act(async () => {
publishDialog.set(open ? "export" : "none");
root?.render(
<TooltipProvider>
<publishModule.PublishButton projectId={projectId} />
</TooltipProvider>
);
});
if (open && staticButton() === undefined) {
await act(async () =>
document.body
.querySelector<HTMLButtonElement>('button[role="combobox"]')
?.dispatchEvent(
new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
)
);
const option = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="option"]')
).find((option) => option.textContent?.trim() === "Static");
expect(option).toBeDefined();
await act(async () => option?.click());
}
};
test("reopening an active static publish keeps one status owner and one download", async () => {
vi.useFakeTimers();
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"
);
projectStore.set(createProject());
await render(true);
const button = staticButton();
expect(button).toBeDefined();
await act(async () => button?.click());
await act(async () => vi.waitFor(() => expect(projectRequests).toBe(1)));
await act(async () => vi.waitFor(() => expect(jobRequests).toBe(1)));
expect(publishRequests).toBe(1);
expect(jobRequests).toBe(1);
expect(downloads).not.toHaveBeenCalled();
render(false);
render(true);
expect(container?.querySelector("output")?.textContent).toBe("pending");
await render(false);
await render(true);
expect(staticButton()?.dataset.state).toBe("pending");
getJobStatus = "success";
await act(async () => vi.advanceTimersByTimeAsync(15_000));
expect(downloads).toHaveBeenCalledExactlyOnceWith("site.zip");
expect(container?.querySelector("[data-log-status]")?.textContent).toBe(
"success"
);
await vi.waitFor(async () => {
await act(async () => {});
expect(downloads).toHaveBeenCalledOnce();
});
expect(downloads).toHaveBeenCalledExactlyOnceWith("/cgi/static/ssg/site.zip");
expect(staticButton()?.dataset.state).not.toBe("pending");
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 () => {
vi.useFakeTimers();
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
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"
);
projectStore.set(createProject());
await render(true);
const button = staticButton();
expect(button).toBeDefined();
await act(async () => button?.click());
await act(async () => vi.waitFor(() => expect(projectRequests).toBe(1)));
await act(async () => vi.waitFor(() => expect(jobRequests).toBe(1)));
await act(async () =>
vi.waitFor(() =>
expect(projectStore.get()?.latestStaticBuild?.buildId).toBe("static-1")
)
);
act(() =>
projectStore.set({ id: "project-b", latestStaticBuild: null } as Project)
);
render(false, "project-b");
act(() =>
projectStore.set({ id: "project-a", latestStaticBuild: null } as Project)
);
render(false, "project-a");
act(() => projectStore.set(createProject("project-b")));
await render(false, "project-b");
act(() => projectStore.set(createProject()));
await render(false, "project-a");
getJobStatus = "success";
await act(async () => vi.advanceTimersByTimeAsync(15_000));
await act(async () => vi.advanceTimersByTimeAsync(1_000));
@@ -196,25 +230,21 @@ test("project navigation suppresses an old static download and error toast", asy
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"
);
projectStore.set(createProject());
await render(true);
const button = staticButton();
expect(button).toBeDefined();
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");
expect(staticButton()?.dataset.state).not.toBe("pending");
await act(async () =>
userEvent.click(
container!.querySelector<HTMLButtonElement>(
document.body
.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
)!
)
)
?.click()
);
const errors = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
@@ -223,7 +253,7 @@ test("a failed static runner clears progress without starting a download", async
await act(async () => userEvent.click(errors!));
const showLogs = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
).find((button) => button.textContent === "show logs");
).find((button) => button.textContent?.trim() === "show logs");
expect(showLogs).toBeDefined();
await act(async () => userEvent.click(showLogs!));
expect(
@@ -239,28 +269,20 @@ test("a failed static runner clears progress without starting a download", async
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")!;
projectStore.set(createProject());
await render(true);
const publish = staticButton()!;
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");
expect(downloads).toHaveBeenCalledOnce();
expect(staticButton()?.dataset.state).not.toBe("pending");
});
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()
);
await act(async () => staticButton()?.click());
const activeTab = () =>
document.body.querySelector('[role="tab"][aria-selected="true"]')
?.textContent;
@@ -277,8 +299,9 @@ test("the static status reopens an audit rejection instead of an older successfu
await act(async () => {});
expect(document.body.querySelector('[role="dialog"]')).toBeNull();
});
await render(true);
await act(async () =>
container!
document.body
.querySelector<HTMLButtonElement>(
'button[aria-label="Publish log: Static export"]'
)
@@ -1,8 +1,6 @@
import { expect, test, vi } from "vitest";
import type { Project } from "@webstudio-is/project";
import { __testing__ } from "./use-publish-progress";
const { waitForPublishStatus } = __testing__;
import { waitForPublishStatus } from "./publish-progress";
test("a new publish waits past the previous build's failure", async () => {
vi.useFakeTimers();
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
import { expect, test } from "vitest";
import {
getPublishDuration,
selectSessionPublishes,
} from "./session-publishes";
test("duration is omitted for invalid or reversed job timestamps", () => {
expect(
getPublishDuration({
startedAt: "invalid",
completedAt: "2026-11-13T10:00:00.000Z",
} as never)
).toBeUndefined();
expect(
getPublishDuration({
startedAt: "2026-11-13T10:00:03.000Z",
completedAt: "2026-11-13T10:00:00.000Z",
} as never)
).toBeUndefined();
});
test("session selection keeps repeated domain publishes separate from static exports", () => {
const base = { findings: [], status: "success" as const };
const items = [
{
...base,
buildId: "site-1",
target: "site" as const,
domains: ["a.example", "b.example"],
},
{
...base,
buildId: "site-2",
target: "site" as const,
domains: ["b.example"],
},
{ ...base, buildId: "static-1", target: "static" as const, domains: [] },
];
expect(
selectSessionPublishes(items, "site", "a.example").map(
({ buildId }) => buildId
)
).toEqual(["site-1"]);
expect(
selectSessionPublishes(items, "site", "b.example").map(
({ buildId }) => buildId
)
).toEqual(["site-1", "site-2"]);
expect(
selectSessionPublishes(items, "static").map(({ buildId }) => buildId)
).toEqual(["static-1"]);
});
@@ -0,0 +1,54 @@
import type { DiagnosticFinding } from "./diagnostics";
export type SessionPublish = {
buildId: string;
domains: string[];
target: "site" | "static";
staticName?: string;
findings: DiagnosticFinding[];
logHandle?: string;
status: "pending" | "success" | "failed";
code?: string;
startedAt?: string;
completedAt?: string;
failedStage?: string;
issues?: { severity: "error" | "warning"; message: string }[];
issuesOmitted?: number;
logState?: "loading" | "available" | "unavailable";
logText?: string;
};
const decodeChunk = (chunk: string) => {
const binary = atob(chunk.replaceAll("-", "+").replaceAll("_", "/"));
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
};
export const decodePublishLog = (chunks: string[]) => {
const decoder = new TextDecoder();
return chunks
.map((chunk, index) =>
decoder.decode(decodeChunk(chunk), { stream: index < chunks.length - 1 })
)
.join("");
};
export const getPublishDuration = (item: SessionPublish) => {
if (item.startedAt === undefined || item.completedAt === undefined) {
return;
}
const duration = Date.parse(item.completedAt) - Date.parse(item.startedAt);
if (Number.isFinite(duration) && duration >= 0) {
return Math.round(duration / 1000);
}
};
export const selectSessionPublishes = (
items: SessionPublish[],
target: "site" | "static",
domain?: string
) =>
items.filter(
(item) =>
item.target === target &&
(domain === undefined || item.domains.includes(domain))
);
@@ -1,465 +0,0 @@
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.staticFailureFinding?.reportText).toBe(message)
);
act(() => flow.openStaticReport());
expect(flow.reportFindings.map(({ reportText }) => reportText)).toEqual([
...completed,
message,
]);
expect(flow.diagnosticsSelection?.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.publishes[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.reportPublishes,
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",
]);
}
}
);
@@ -1,504 +0,0 @@
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,
refreshProjectWithRetry,
fetchAndStoreProject,
reportPublishResult,
} from "./use-publish-progress";
import {
selectSessionPublishes,
useSessionPublishes,
type SessionPublish,
} from "./use-session-publishes";
import {
runPublishDiagnostics,
runPublishValidation,
reportPublishValidationFailure,
getServerPublishFindings,
} from "./publish-validation";
import { runPublishAfterBestEffortChecks } from "./publish-preflight";
import type { DiagnosticFinding } from "./diagnostics";
const downloadStatic = (name: string) => {
window.location.href = `/cgi/static/ssg/${name}`;
};
const getPublishErrorFinding = (
error: JSX.Element | string,
buildId?: string
): DiagnosticFinding => ({
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 sessionPublishes = useSessionPublishes(projectId, allowPublishLogs);
const sessionPublishesRef = useRef(sessionPublishes.items);
sessionPublishesRef.current = sessionPublishes.items;
const [diagnosticsSelection, setDiagnosticsSelection] = useState<{
target: "static" | "site";
domain?: string;
tab: "warnings" | "errors" | "publish";
}>();
useEffect(() => {
setDiagnosticsSelection(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,
} = sessionPublishes;
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: SessionPublish | 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: SessionPublish | undefined,
previousBuildId?: string,
onDownload = downloadStatic
) => {
if (item === undefined) {
return;
}
const result = await waitForPublishStatus(
() => fetchAndStoreProject({ 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 refreshProjectWithRetry(
async (showError) => {
const refreshedProject = await fetchAndStoreProject({
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 = sessionPublishesRef.current.find(
(item) => item.target === target && item.status === "pending"
);
if (target === "static" && pending === undefined) {
return;
}
void watchPendingPublish(
() =>
fetchAndStoreProject({
projectId,
showError: false,
isCurrent: () => isRefreshCurrent(generation),
}),
generation,
pending === undefined
? undefined
: {
projectId,
buildId: pending.buildId,
logHandle: pending.logHandle,
target,
},
(result) => finishPublish(pending, result)
);
},
() =>
sessionPublishesRef.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");
setDiagnosticsSelection({ target: "site", domain, tab });
};
const openStaticReport = (
tab: "warnings" | "errors" | "publish" = staticFailureFinding === undefined
? "publish"
: "errors"
) => {
$publishDialog.set("none");
setDiagnosticsSelection({ target: "static", tab });
};
const reportPublishes = selectSessionPublishes(
sessionPublishes.items,
diagnosticsSelection?.target ?? "site",
diagnosticsSelection?.domain
);
const domain = diagnosticsSelection?.domain;
const siteFindings = [
...validationFindings.findings,
...progress.publishFindings,
];
const staticDiagnostics = progress.publishDiagnostics.static;
const staticFailureFinding = staticDiagnostics.rejected
? staticDiagnostics.findings
.filter(({ severity }) => severity === "error")
.at(-1)
: undefined;
const findings: DiagnosticFinding[] = [];
const diagnostics =
progress.publishDiagnostics[diagnosticsSelection?.target ?? "site"];
const includesSelectedDomain =
domain === undefined || diagnostics.domains.includes(domain);
if (includesSelectedDomain) {
findings.push(...diagnostics.findings);
}
if (diagnosticsSelection?.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 fetchAndStoreProject({ projectId, isCurrent });
}
return;
}
const accepted = sessionPublishes.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.statusContent);
}
},
{
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,
staticFailureFinding,
publishes: sessionPublishes.items,
loadLog: sessionPublishes.loadLog,
diagnosticsSelection,
closeReport: () => setDiagnosticsSelection(undefined),
reportPublishes,
reportFindings: findings,
includeLatestPublishFindings: !(
diagnostics.rejected && includesSelectedDomain
),
openSiteReport,
openStaticReport,
validate,
publish,
invalidateValidation,
reset: () => {
validation.reset();
dismissCountdown();
},
};
};
@@ -1,581 +0,0 @@
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,
getPublishStatusDisplay,
getStaticPublishStatusDisplay,
} from "./publish-status";
import type { DiagnosticFinding } 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: DiagnosticFinding[];
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<DiagnosticFinding[]>) => {
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<DiagnosticFinding[]>) => {
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, statusContent } = getPublishStatusDisplay(build);
const isNewBuild =
build.buildId !== undefined &&
build.buildId !== requestBaselineBuildId.current;
if (status === "FAILED") {
if (hasStartedPublishRequest.current && isNewBuild) {
setPublishErrorState({
value: statusContent,
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.statusContent);
}
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,
statusContent: "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 { statusContent, status } =
execution?.target === "static" &&
refreshedProject.latestStaticBuild != null
? getStaticPublishStatusDisplay(refreshedProject.latestStaticBuild)
: refreshedProject.latestBuildVirtual != null
? getPublishStatusDisplay(refreshedProject.latestBuildVirtual)
: {
statusContent: "Not published",
status: "PENDING" as const,
};
if (!runnerPending && (status === "PUBLISHED" || status === "FAILED")) {
return { status, statusContent };
}
}
} 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 refreshProjectWithRetry = 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 &&
getPublishStatusDisplay(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.statusContent);
}
setPublishError(result.statusContent, buildId);
}
};
const useManualValidationFindings = () => {
const [findings, setFindings] = useState<DiagnosticFinding[]>([]);
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: DiagnosticFinding[]) => {
if (session.current === id) {
setFindings(next);
setDomains(next.length > 0 ? requestedDomains.current : undefined);
}
}, []);
return { findings, domains, begin, invalidate, isCurrent, update };
};
export const fetchAndStoreProject = 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,
refreshProjectWithRetry,
reportPublishResult,
useManualValidationFindings,
fetchAndStoreProject,
};
@@ -1,314 +0,0 @@
import { act } from "react-dom/test-utils";
import { createRoot, type Root } from "react-dom/client";
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
let root: Root | undefined;
let container: HTMLDivElement | undefined;
let sessionModule: typeof import("./use-session-publishes");
let session: ReturnType<typeof sessionModule.useSessionPublishes>;
let paid = false;
let holdFirst = false;
let releaseFirst: (() => void) | undefined;
let holdSecond = false;
let releaseSecond: (() => void) | undefined;
const requests: Array<{ cursor?: number; projectId: string }> = [];
const respond = (data: unknown) =>
new Response(JSON.stringify([{ result: { data } }]), {
headers: { "Content-Type": "application/json" },
});
const encoded = (bytes: number[]) => btoa(String.fromCharCode(...bytes));
const Harness = ({
projectId,
canViewPublishLogs,
}: {
projectId: string;
canViewPublishLogs: boolean;
}) => {
session = sessionModule.useSessionPublishes(projectId, canViewPublishLogs);
return (
<output>
{session.items
.map(
({ buildId, logText, issues }) =>
`${buildId}:${logText ?? ""}:${issues?.length ?? 0}`
)
.join("|")}
</output>
);
};
beforeAll(async () => {
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
vi.resetModules();
vi.stubGlobal("fetch", async (requestInfo: RequestInfo | URL) => {
const url = new URL(String(requestInfo), "http://localhost");
expect(url.pathname).toBe("/trpc/api.publish.getLog");
const input = JSON.parse(url.searchParams.get("input") ?? "{}")["0"] as {
cursor?: number;
projectId: string;
};
requests.push(input);
const first = input.cursor === undefined;
const response = respond({
availability: "available",
outcome: "failed",
logAvailability: "available",
startedAt: "2026-11-13T10:00:00.000Z",
completedAt: "2026-11-13T10:00:03.000Z",
failedStage: "deploy",
code: "failure",
log: {
...(paid
? {
encoding: "base64url",
chunk: first ? encoded([0xe2]) : encoded([0x82, 0xac]),
}
: {}),
complete: !first,
nextCursor: first ? 1 : undefined,
issues: [
{
severity: first ? "warning" : "error",
message: first ? "Early warning" : "Late error",
},
],
issuesOmitted: first ? 1 : 0,
},
});
if (holdFirst && first) {
holdFirst = false;
return await new Promise<Response>((resolve) => {
releaseFirst = () => resolve(response);
});
}
if (holdSecond && !first) {
holdSecond = false;
return await new Promise<Response>((resolve) => {
releaseSecond = () => resolve(response);
});
}
return response;
});
sessionModule = await import("./use-session-publishes");
const { updateCsrfToken } = await import("~/shared/csrf.client");
updateCsrfToken("test-token");
});
afterEach(() => {
act(() => root?.unmount());
root = undefined;
container?.remove();
container = undefined;
requests.length = 0;
paid = false;
holdFirst = false;
releaseFirst = undefined;
holdSecond = false;
releaseSecond = undefined;
});
afterAll(() => vi.unstubAllGlobals());
const render = (canViewPublishLogs: boolean, projectId = "project-1") => {
paid = canViewPublishLogs;
if (container === undefined) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
}
act(() =>
root?.render(
<Harness projectId={projectId} canViewPublishLogs={canViewPublishLogs} />
)
);
};
const record = () =>
act(() =>
session.record({
buildId: "build-1",
logHandle: "handle-1",
target: "site",
domains: ["example.com"],
findings: [],
})
);
test("records a start time immediately and replaces it with the runner time", async () => {
render(true);
const beforeRecord = Date.now();
record();
const startedAt = Date.parse(session.items[0]?.startedAt ?? "");
expect(startedAt).toBeGreaterThanOrEqual(beforeRecord);
expect(startedAt).toBeLessThanOrEqual(Date.now());
await act(async () => session.loadLog(session.items[0]!));
expect(session.items[0]?.startedAt).toBe("2026-11-13T10:00:00.000Z");
render(false);
expect(session.items[0]?.startedAt).toBeUndefined();
});
test("Free does not fetch logs, then Pro reads the full UTF-8 log from byte zero", async () => {
render(false);
record();
expect(requests).toHaveLength(0);
expect(session.items[0]?.issues).toBeUndefined();
expect(session.items[0]?.logText).toBeUndefined();
render(true);
await act(async () => session.loadLog(session.items[0]!));
expect(requests.map(({ cursor }) => cursor)).toEqual([undefined, 1]);
expect(session.items[0]?.logText).toBe("€");
expect(session.items[0]?.issues?.map(({ severity }) => severity)).toEqual([
"error",
"warning",
]);
expect(session.items[0]?.issuesOmitted).toBe(1);
expect(sessionModule.getPublishDuration(session.items[0]!)).toBe(3);
render(false);
expect(session.items[0]?.logText).toBeUndefined();
expect(session.items[0]?.issues).toBeUndefined();
});
test("missing execution handle does not retry an accepted publish", () => {
render(false);
act(() =>
session.record({
buildId: "build-2",
target: "static",
domains: [],
findings: [],
})
);
expect(session.items[0]?.status).toBe("pending");
expect(requests).toHaveLength(0);
});
test("a paid response arriving after downgrade cannot restore raw logs", async () => {
holdSecond = true;
render(true);
record();
const loading = act(async () => session.loadLog(session.items[0]!));
await act(async () => vi.waitFor(() => expect(requests).toHaveLength(2)));
render(false);
await act(async () => releaseSecond?.());
await loading;
expect(session.items[0]?.logText).toBeUndefined();
expect(session.items[0]?.logState).toBeUndefined();
render(true);
await act(async () => session.loadLog(session.items[0]!));
expect(requests.slice(2).map(({ cursor }) => cursor)).toEqual([undefined, 1]);
expect(session.items[0]?.logText).toBe("€");
});
test("duration is omitted for invalid or reversed job timestamps", () => {
expect(
sessionModule.getPublishDuration({
startedAt: "invalid",
completedAt: "2026-11-13T10:00:00.000Z",
} as never)
).toBeUndefined();
expect(
sessionModule.getPublishDuration({
startedAt: "2026-11-13T10:00:03.000Z",
completedAt: "2026-11-13T10:00:00.000Z",
} as never)
).toBeUndefined();
});
test("a response from the previous project cannot populate the new project", async () => {
holdFirst = true;
render(true, "project-1");
record();
const loading = act(async () => session.loadLog(session.items[0]!));
await act(async () => vi.waitFor(() => expect(requests).toHaveLength(1)));
render(true, "project-2");
await act(async () => releaseFirst?.());
await loading;
expect(session.items).toEqual([]);
});
test("an old callback cannot restore data after returning to the same project", () => {
render(false, "project-1");
const oldSession = session;
render(false, "project-2");
render(false, "project-1");
act(() => {
oldSession.record({
buildId: "stale-build",
target: "site",
domains: ["example.com"],
findings: [],
});
oldSession.complete("stale-build", "failed");
});
expect(session.items).toEqual([]);
});
test("evicting a build stops its in-flight log reader before the next page", async () => {
holdFirst = true;
render(true);
record();
const loading = act(async () => session.loadLog(session.items[0]!));
await act(async () => vi.waitFor(() => expect(requests).toHaveLength(1)));
act(() => {
for (let index = 0; index < 10; index++) {
session.record({
buildId: `new-build-${index}`,
target: "site",
domains: ["example.com"],
findings: [],
});
}
});
await act(async () => releaseFirst?.());
await loading;
expect(requests).toHaveLength(1);
expect(session.items.some(({ buildId }) => buildId === "build-1")).toBe(
false
);
});
test("session selection keeps repeated domain publishes separate from static exports", () => {
const base = {
buildId: "build-1",
findings: [],
status: "success" as const,
};
const items = [
{
...base,
buildId: "site-1",
target: "site" as const,
domains: ["a.example", "b.example"],
},
{
...base,
buildId: "site-2",
target: "site" as const,
domains: ["b.example"],
},
{ ...base, buildId: "static-1", target: "static" as const, domains: [] },
];
expect(
sessionModule
.selectSessionPublishes(items, "site", "a.example")
.map(({ buildId }) => buildId)
).toEqual(["site-1"]);
expect(
sessionModule
.selectSessionPublishes(items, "site", "b.example")
.map(({ buildId }) => buildId)
).toEqual(["site-1", "site-2"]);
expect(
sessionModule
.selectSessionPublishes(items, "static")
.map(({ buildId }) => buildId)
).toEqual(["static-1"]);
});
@@ -1,293 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { nativeClient } from "~/shared/trpc/trpc-client";
import type { DiagnosticFinding } from "./diagnostics";
export type SessionPublish = {
buildId: string;
domains: string[];
target: "site" | "static";
staticName?: string;
findings: DiagnosticFinding[];
logHandle?: string;
status: "pending" | "success" | "failed";
code?: string;
startedAt?: string;
completedAt?: string;
failedStage?: string;
issues?: { severity: "error" | "warning"; message: string }[];
issuesOmitted?: number;
logState?: "loading" | "available" | "unavailable";
logText?: string;
};
const decodeChunk = (chunk: string) => {
const binary = atob(chunk.replaceAll("-", "+").replaceAll("_", "/"));
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
};
export const decodePublishLog = (chunks: string[]) => {
const decoder = new TextDecoder();
return chunks
.map((chunk, index) =>
decoder.decode(decodeChunk(chunk), { stream: index < chunks.length - 1 })
)
.join("");
};
export const getPublishDuration = (item: SessionPublish) => {
if (item.startedAt === undefined || item.completedAt === undefined) {
return;
}
const duration = Date.parse(item.completedAt) - Date.parse(item.startedAt);
if (Number.isFinite(duration) && duration >= 0) {
return Math.round(duration / 1000);
}
};
export const selectSessionPublishes = (
items: SessionPublish[],
target: "site" | "static",
domain?: string
) =>
items.filter(
(item) =>
item.target === target &&
(domain === undefined || item.domains.includes(domain))
);
export const useSessionPublishes = (
projectId: string,
canViewPublishLogs: boolean
) => {
const [items, setItems] = useState<SessionPublish[]>([]);
const itemsProjectId = useRef(projectId);
const currentProjectId = useRef(projectId);
currentProjectId.current = projectId;
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 active = useRef(true);
const generation = useRef(0);
const permission = useRef({ allowed: canViewPublishLogs, generation: 0 });
if (permission.current.allowed !== canViewPublishLogs) {
permission.current = {
allowed: canViewPublishLogs,
generation: permission.current.generation + 1,
};
}
const loading = useRef(
new Map<string, { permissionGeneration: number; scopeToken: number }>()
);
const retainedBuilds = useRef(new Set<string>());
const isCurrent = useCallback(
() =>
active.current &&
currentProjectId.current === projectId &&
projectScope.current.token === scopeToken,
[projectId, scopeToken]
);
useEffect(() => {
active.current = true;
generation.current += 1;
itemsProjectId.current = projectId;
setItems([]);
loading.current.clear();
retainedBuilds.current.clear();
return () => {
active.current = false;
generation.current += 1;
};
}, [projectId]);
useEffect(() => {
if (canViewPublishLogs === false) {
setItems((current) =>
current.map((item) => ({
...item,
startedAt: undefined,
completedAt: undefined,
failedStage: undefined,
code: undefined,
issues: undefined,
issuesOmitted: undefined,
logState: undefined,
logText: undefined,
}))
);
}
}, [canViewPublishLogs]);
const update = useCallback(
(buildId: string, change: Partial<SessionPublish>) => {
setItems((current) =>
current.map((item) =>
item.buildId === buildId ? { ...item, ...change } : item
)
);
},
[]
);
const record = useCallback(
(item: Omit<SessionPublish, "status">) => {
if (isCurrent() === false) {
return;
}
const accepted: SessionPublish = {
...item,
status: "pending",
startedAt: permission.current.allowed
? new Date().toISOString()
: undefined,
};
retainedBuilds.current.delete(item.buildId);
retainedBuilds.current.add(item.buildId);
setItems((current) =>
[
accepted,
...current.filter(({ buildId }) => buildId !== item.buildId),
].slice(0, 10)
);
if (retainedBuilds.current.size > 10) {
const oldest = [...retainedBuilds.current][0];
retainedBuilds.current.delete(oldest);
}
return accepted;
},
[isCurrent]
);
const complete = useCallback(
(buildId: string, status: "success" | "failed", code?: string) => {
if (isCurrent() && retainedBuilds.current.has(buildId)) {
update(buildId, {
status,
code: permission.current.allowed ? code : undefined,
});
}
},
[isCurrent, update]
);
const loadLog = useCallback(
async (item: SessionPublish) => {
if (
isCurrent() === false ||
retainedBuilds.current.has(item.buildId) === false ||
item.logHandle === undefined ||
permission.current.allowed === false ||
item.logState === "available" ||
(loading.current.get(item.buildId)?.permissionGeneration ===
permission.current.generation &&
loading.current.get(item.buildId)?.scopeToken === scopeToken)
) {
return;
}
const currentGeneration = generation.current;
const currentPermissionGeneration = permission.current.generation;
const request = {
permissionGeneration: currentPermissionGeneration,
scopeToken,
};
loading.current.set(item.buildId, request);
update(item.buildId, { logState: "loading" });
const isReadCurrent = () =>
generation.current === currentGeneration &&
isCurrent() &&
retainedBuilds.current.has(item.buildId) &&
permission.current.allowed &&
permission.current.generation === currentPermissionGeneration;
try {
let cursor: number | undefined;
const chunks: string[] = [];
const issues: NonNullable<SessionPublish["issues"]> = [];
let issuesOmitted = 0;
while (isReadCurrent()) {
const result = await nativeClient.api.publish.getLog.query({
projectId,
buildId: item.buildId,
logHandle: item.logHandle,
cursor,
});
if (isReadCurrent() === false) {
return;
}
if (result.availability !== "available") {
update(item.buildId, { logState: "unavailable" });
return;
}
update(item.buildId, {
startedAt: result.startedAt ?? item.startedAt,
completedAt: result.completedAt,
failedStage: result.failedStage,
code: result.code,
});
const log = result.log;
if (log === undefined || !("chunk" in log)) {
update(item.buildId, { logState: "unavailable" });
return;
}
chunks.push(log.chunk);
for (const issue of log.issues ?? []) {
if (issues.length < 20) {
issues.push(issue);
} else if (issue.severity === "error") {
const warningIndex = issues.findIndex(
({ severity }) => severity === "warning"
);
if (warningIndex !== -1) {
issues.splice(warningIndex, 1, issue);
}
issuesOmitted += 1;
} else {
issuesOmitted += 1;
}
}
issuesOmitted += log.issuesOmitted ?? 0;
if (log.complete) {
update(item.buildId, {
logState: "available",
logText: decodePublishLog(chunks),
issues: [
...issues.filter(({ severity }) => severity === "error"),
...issues.filter(({ severity }) => severity === "warning"),
],
issuesOmitted,
startedAt: result.startedAt ?? item.startedAt,
completedAt: result.completedAt,
failedStage: result.failedStage,
code: result.code,
});
return;
}
if (log.nextCursor === undefined || log.nextCursor === cursor) {
update(item.buildId, { logState: "unavailable" });
return;
}
cursor = log.nextCursor;
}
} catch {
if (isReadCurrent()) {
update(item.buildId, { logState: "unavailable" });
}
} finally {
if (loading.current.get(item.buildId) === request) {
loading.current.delete(item.buildId);
}
}
},
[isCurrent, projectId, scopeToken, update]
);
return {
items: itemsProjectId.current === projectId ? items : [],
record,
complete,
loadLog,
isCurrent,
};
};