>;
+ 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 && (
+
+ You have {timesLeft} out of {maxDailyPublishesPerUser} daily
+ publications remaining. The counter resets tomorrow.
+
+ )}
+ >,
+ { 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;
+ 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);
+ }
+};
diff --git a/apps/builder/app/builder/features/publish/publish-session.render.test.tsx b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx
new file mode 100644
index 0000000000..b89a3b368c
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx
@@ -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 = () => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((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> }
+ | undefined;
+let heldJob: ReturnType> | undefined;
+let heldPublish: ReturnType> | 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(
+
+
+
+ )
+ );
+};
+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(
+ 'input[name="domainToPublish[]"]'
+ );
+ expect(domain).not.toBeNull();
+ if (domain?.checked === false) {
+ await act(async () =>
+ document.body.querySelector('[role="checkbox"]')?.click()
+ );
+ }
+ const button = Array.from(
+ domain!.closest("form")!.querySelectorAll("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('button[aria-label^="Publish log:"]')
+ ?.click()
+ );
+ expect(document.body.querySelector('[role="tablist"]')).not.toBeNull();
+};
+const panel = () =>
+ document.body.querySelector(
+ '[role="tabpanel"][data-state="active"]'
+ )!;
+const waitFor = async (assertion: () => void) => {
+ await vi.waitFor(async () => {
+ await act(async () => {});
+ assertion();
+ });
+};
+const entries = () =>
+ Array.from(
+ panel().querySelectorAll('[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();
+ 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('[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() };
+ 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() };
+ 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();
+ 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() };
+ 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);
+});
diff --git a/apps/builder/app/builder/features/publish/publish-static.test.tsx b/apps/builder/app/builder/features/publish/publish-static.test.tsx
index c97f94682d..ef2de3038c 100644
--- a/apps/builder/app/builder/features/publish/publish-static.test.tsx
+++ b/apps/builder/app/builder/features/publish/publish-static.test.tsx
@@ -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 (
-
-
-
-
- {open && (
-
- )}
- {
- if (!open) {
- flow.closeReport();
- }
- }}
- initialTab={flow.diagnosticsSelection?.tab}
- canViewPublishLogs={false}
- />
-
+const createProject = (id = "project-a") =>
+ ({
+ id,
+ domain: "example",
+ domainsVirtual: [],
+ latestStaticBuild: null,
+ }) as unknown as Project;
+
+const staticButton = () =>
+ Array.from(document.body.querySelectorAll("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());
+ await act(async () => {
+ publishDialog.set(open ? "export" : "none");
+ root?.render(
+
+
+
+ );
+ });
+ if (open && staticButton() === undefined) {
+ await act(async () =>
+ document.body
+ .querySelector('button[role="combobox"]')
+ ?.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
+ )
+ );
+ const option = Array.from(
+ document.body.querySelectorAll('[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(
+ document.body
+ .querySelector(
'button[aria-label="Publish log: Static export"]'
- )!
- )
+ )
+ ?.click()
);
const errors = Array.from(
document.body.querySelectorAll('[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("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("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("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(
'button[aria-label="Publish log: Static export"]'
)
diff --git a/apps/builder/app/builder/features/publish/publish-status.test.tsx b/apps/builder/app/builder/features/publish/publish-status.test.tsx
index cf4a0a7db4..4c32b6daee 100644
--- a/apps/builder/app/builder/features/publish/publish-status.test.tsx
+++ b/apps/builder/app/builder/features/publish/publish-status.test.tsx
@@ -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();
diff --git a/apps/builder/app/builder/features/publish/publish-ui.tsx b/apps/builder/app/builder/features/publish/publish-ui.tsx
new file mode 100644
index 0000000000..791c104750
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-ui.tsx
@@ -0,0 +1,1167 @@
+import stripIndent from "strip-indent";
+import { computed } from "nanostores";
+import {
+ useEffect,
+ useState,
+ useOptimistic,
+ startTransition,
+ useRef,
+ useId,
+} from "react";
+import { useStore } from "@nanostores/react";
+import {
+ PanelContent,
+ Button,
+ cssVar,
+ Tooltip,
+ InfoTooltip,
+ IconButton,
+ Grid,
+ Flex,
+ Label,
+ Text,
+ InputField,
+ Separator,
+ ScrollArea,
+ rawTheme,
+ Select,
+ theme,
+ TextArea,
+ Link,
+ LinkButton,
+ PanelBanner,
+ toast,
+ RadioGroup,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ PopoverTitle,
+ PopoverClose,
+ PopoverTitleActions,
+ css,
+ textVariants,
+ SmallIconButton,
+} from "@webstudio-is/design-system";
+import { validateProjectDomain, type Project } from "@webstudio-is/project";
+import {
+ $selectedPageId,
+ selectInstance,
+ $editingPageId,
+ $permissions,
+ $stagingUsername,
+ $stagingPassword,
+} from "~/shared/nano-states";
+import {
+ $publisherHost,
+ $project,
+ $dataSources,
+ $instances,
+ $pages,
+ $projectSettings,
+ $resources,
+} from "~/shared/sync/data-stores";
+import { setActiveSidebarPanel } from "../../shared/nano-states";
+import { Domains } from "./domains";
+import { CollapsibleDomainSection } from "./collapsible-domain-section";
+import {
+ ActivityIcon,
+ AlertIcon,
+ CheckCircleIcon,
+ CopyIcon,
+ GearIcon,
+ UpgradeIcon,
+ HelpIcon,
+ InfoCircleIcon,
+ EllipsesIcon,
+ PlusIcon,
+ SpinnerIcon,
+ TerminalIcon,
+} from "@webstudio-is/icons";
+import { AddDomain } from "./add-domain";
+import { humanizeString } from "~/shared/string-utils";
+import { trpcClient, nativeClient } from "~/shared/trpc/trpc-client";
+import type { Templates } from "@webstudio-is/sdk";
+import { DomainCheckbox, domainToPublishName } from "./domain-checkbox";
+import { CopyToClipboard } from "~/shared/copy-to-clipboard";
+import { $openProjectSettings } from "~/shared/nano-states/project-settings";
+import cmsUpgradeBanner from "~/shared/cms-upgrade-banner.svg?url";
+import { $currentSystem } from "~/shared/system";
+import { getPublishUrl } from "./publish-url";
+import {
+ getRestrictedFeatures,
+ type RestrictedFeature,
+} from "./restricted-features";
+import { PublishValidationBanner, type DiagnosticFinding } from "./diagnostics";
+import type { SessionPublish } from "./session-publishes";
+import { PublishActions, type PublishValidationState } from "./publish-actions";
+import { fetchAndStoreProject } from "./publish-progress";
+import {
+ getPublishStatusDisplay,
+ getStaticPublishStatusDisplay,
+} from "./publish-status";
+import { DomainStatusButton } from "./domain-status-button";
+
+type PublishUiState = {
+ isPublishing: boolean;
+ countdown?: number;
+ validationState: PublishValidationState;
+ validatedDomains?: string[];
+ invalidateValidation: () => void;
+ publishes: SessionPublish[];
+ siteError?: string | JSX.Element;
+ siteErrorSource?: "request" | "transport" | "status";
+ siteFindings: DiagnosticFinding[];
+ staticFailureFinding?: DiagnosticFinding;
+ openSiteReport: (
+ domain: string | undefined,
+ tab: "warnings" | "errors" | "publish"
+ ) => void;
+ openStaticReport: (tab?: "warnings" | "errors" | "publish") => void;
+ validate: (domains: string[]) => Promise;
+ publishSite: (
+ domains: string[],
+ timesLeft: number,
+ maxDailyPublishesPerUser: number
+ ) => void;
+ exportStatic: (templates: readonly Templates[]) => void;
+};
+
+type ChangeProjectDomainProps = {
+ project: Project;
+ refresh: () => Promise;
+ validatedDomains?: readonly string[];
+ onOpenReport: (domain: string) => void;
+ latestPublish?: SessionPublish;
+};
+
+const ChangeProjectDomain = ({
+ project,
+ refresh,
+ validatedDomains,
+ onOpenReport,
+ latestPublish,
+}: ChangeProjectDomainProps) => {
+ const id = useId();
+ const currentSystem = useStore($currentSystem);
+ const stagingUsername = useStore($stagingUsername);
+ const stagingPassword = useStore($stagingPassword);
+ const publisherHost = useStore($publisherHost);
+
+ const [domain, setDomain] = useState(project.domain);
+ const [error, setError] = useState();
+ const [isUpdateInProgress, setIsUpdateInProgress] = useOptimistic(false);
+ const [isUnpublishing, setIsUnpublishing] = useOptimistic(false);
+
+ const pageUrl = getPublishUrl({
+ domain: `${project.domain}.${publisherHost}`,
+ pathname: currentSystem.pathname,
+ username: stagingUsername,
+ password: stagingPassword,
+ });
+
+ const updateProjectDomain = async () => {
+ setIsUpdateInProgress(true);
+ const validationResult = validateProjectDomain(domain);
+
+ if (validationResult.success === false) {
+ setError(validationResult.error);
+ return;
+ }
+
+ const updateResult = await nativeClient.domain.updateProjectDomain.mutate({
+ domain,
+ projectId: project.id,
+ });
+
+ if (updateResult.success === false) {
+ setError(updateResult.error);
+ return;
+ }
+
+ await refresh();
+ };
+
+ const handleUpdateProjectDomain = () => {
+ startTransition(async () => {
+ await updateProjectDomain();
+ });
+ };
+
+ const handleUnpublish = async () => {
+ setIsUnpublishing(true);
+ const result = await nativeClient.domain.unpublish.mutate({
+ projectId: project.id,
+ domain: `${project.domain}.${publisherHost}`,
+ });
+ if (result.success === false) {
+ toast.error(result.message);
+ return;
+ }
+ await refresh();
+ toast.success(result.message);
+ };
+
+ const latestProjectDomainBuild =
+ project.latestBuildVirtual?.domain === project.domain
+ ? project.latestBuildVirtual
+ : undefined;
+
+ const { statusContent, color, Icon } =
+ latestProjectDomainBuild != null
+ ? getPublishStatusDisplay(latestProjectDomainBuild)
+ : {
+ statusContent: "Not published",
+ color: cssVar("--foreground-secondary"),
+ Icon: InfoCircleIcon,
+ };
+
+ const isPublished = latestProjectDomainBuild != null;
+
+ return (
+
+ }
+ suffix={
+
+ {statusContent},
+ }}
+ onOpenReport={() => onOpenReport(project.domain)}
+ />
+
+
+
+
+
+
+
+ }
+ >
+
+
+
+
+
+
+ {
+ setError(undefined);
+ setDomain(event.target.value);
+ }}
+ onBlur={handleUpdateProjectDomain}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ handleUpdateProjectDomain();
+ }
+
+ if (event.key === "Escape") {
+ if (project.domain !== domain) {
+ setDomain(project.domain);
+ event.preventDefault();
+ }
+ }
+ }}
+ color={error !== undefined ? "error" : undefined}
+ />
+ {error !== undefined && {error}}
+
+ {stagingUsername && (
+
+
+
+
+ )}
+ {stagingPassword && (
+
+
+
+
+
+
+
+ )}
+ {isPublished && (
+
+
+
+ )}
+
+
+ );
+};
+
+const $restrictedFeatures = computed(
+ [
+ $pages,
+ $projectSettings,
+ $dataSources,
+ $resources,
+ $instances,
+ $permissions,
+ ],
+ (pages, projectSettings, dataSources, resources, instances, permissions) =>
+ getRestrictedFeatures({
+ pages,
+ projectSettings,
+ dataSources,
+ resources,
+ instances,
+ permissions,
+ })
+);
+
+const matchesValidatedDomains = (form: HTMLFormElement, domains: string[]) => {
+ const selected = new Set(domains);
+ const current = new FormData(form)
+ .getAll(domainToPublishName)
+ .map((domain) => domain.toString());
+ return (
+ current.length === selected.size &&
+ current.every((domain) => selected.has(domain))
+ );
+};
+
+const Publish = ({
+ project,
+ quota,
+ restrictedFeatures,
+ flow,
+}: {
+ project: Project;
+ quota: { userPublishCount: number; maxDailyPublishesPerUser: number };
+ restrictedFeatures: Map;
+ flow: PublishUiState;
+}) => {
+ const {
+ isPublishing,
+ countdown,
+ validationState,
+ validatedDomains,
+ invalidateValidation,
+ publishes,
+ siteError,
+ siteErrorSource,
+ openSiteReport: onOpenReport,
+ } = flow;
+ const { userPublishCount, maxDailyPublishesPerUser } = quota;
+ const buttonRef = useRef(null);
+ const [hasSelectedDomains, setHasSelectedDomains] = useState(false);
+ const [hasCustomDomainsSelected, setHasCustomDomainsSelected] =
+ useState(false);
+ const previousDomainsKey = useRef();
+ const hasPendingState = project.latestBuildVirtual
+ ? getPublishStatusDisplay(project.latestBuildVirtual).status === "PENDING"
+ : false;
+ const isPublishInProgress = isPublishing || hasPendingState;
+
+ useEffect(() => {
+ const form = buttonRef.current?.closest("form");
+
+ if (form == null) {
+ return;
+ }
+
+ const handleFormInput = () => {
+ const formData = new FormData(form);
+ const domainsSelected = formData
+ .getAll(domainToPublishName)
+ .map((domain) => domain.toString());
+ const domainsKey = domainsSelected.join("\u0000");
+
+ if (
+ previousDomainsKey.current !== undefined &&
+ previousDomainsKey.current !== domainsKey
+ ) {
+ invalidateValidation();
+ }
+ previousDomainsKey.current = domainsKey;
+
+ setHasSelectedDomains(domainsSelected.length > 0);
+
+ // Check if any custom domains are selected
+ // Custom domains are those that are NOT the staging domain (project.domain)
+ const hasCustom = domainsSelected.some(
+ (domain) => domain !== project.domain
+ );
+ setHasCustomDomainsSelected(hasCustom);
+ };
+
+ const observer = new MutationObserver(() => {
+ handleFormInput();
+ });
+
+ observer.observe(form, {
+ attributes: true,
+ childList: true,
+ subtree: true,
+ attributeFilter: ["value", "checked"],
+ });
+
+ if (validatedDomains !== undefined) {
+ if (matchesValidatedDomains(form, validatedDomains)) {
+ previousDomainsKey.current = validatedDomains.join("\u0000");
+ } else {
+ invalidateValidation();
+ }
+ }
+
+ handleFormInput();
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [invalidateValidation, project.domain, validatedDomains]);
+
+ const getDomainsFromForm = (formData: FormData) =>
+ formData
+ .getAll(domainToPublishName)
+ .map((domainEntry) => domainEntry.toString());
+
+ const getForm = () => buttonRef.current?.closest("form");
+ const findings = flow.siteFindings;
+ const hasSessionPublish = publishes.some(({ target }) => target === "site");
+
+ return (
+
+ {siteError !== undefined ? (
+
+
+
+ {typeof siteError === "string"
+ ? siteError.slice(0, 160)
+ : siteError}
+
+
+
+
+ ) : (
+
+ onOpenReport(
+ undefined,
+ findings.some(({ severity }) => severity === "error")
+ ? "errors"
+ : "warnings"
+ )
+ }
+ />
+ )}
+ 0 && hasCustomDomainsSelected) ||
+ userPublishCount >= maxDailyPublishesPerUser
+ }
+ publishInProgress={isPublishInProgress}
+ publishPending={
+ isPublishInProgress && (countdown === undefined || countdown === 0)
+ }
+ hasSelectedDomains={hasSelectedDomains}
+ publishLabel={
+ countdown !== undefined && countdown > 0
+ ? `Publishing (${countdown}s)`
+ : "Publish"
+ }
+ onValidate={async () => {
+ const form = getForm();
+ if (form) {
+ await flow.validate(getDomainsFromForm(new FormData(form)));
+ }
+ }}
+ onPublish={() => {
+ const form = getForm();
+ if (form) {
+ flow.publishSite(
+ getDomainsFromForm(new FormData(form)),
+ maxDailyPublishesPerUser - userPublishCount,
+ maxDailyPublishesPerUser
+ );
+ }
+ }}
+ />
+
+ );
+};
+
+const PublishStatic = ({
+ templates,
+ flow,
+}: {
+ templates: readonly Templates[];
+ flow: PublishUiState;
+}) => {
+ const {
+ isPublishing,
+ publishes,
+ staticFailureFinding,
+ openStaticReport: onOpenReport,
+ } = flow;
+ const project = useStore($project);
+
+ if (project == null) {
+ throw new Error("Project not found");
+ }
+
+ const { status, statusContent } =
+ project.latestStaticBuild == null
+ ? { status: "LOADED" as const, statusContent: "Not published" }
+ : getStaticPublishStatusDisplay(project.latestStaticBuild);
+ const latestPublish = publishes.find(
+ (item) =>
+ item.target === "static" &&
+ item.buildId === project.latestStaticBuild?.buildId
+ );
+ const logStatus =
+ staticFailureFinding !== undefined
+ ? "FAILED"
+ : latestPublish?.status === "pending"
+ ? "PENDING"
+ : latestPublish?.status === "failed"
+ ? "FAILED"
+ : latestPublish?.status === "success"
+ ? "PUBLISHED"
+ : status;
+
+ const isPublishInProgress = status === "PENDING" || isPublishing;
+
+ return (
+
+
+
+ onOpenReport()}
+ >
+ {logStatus === "FAILED" ? (
+
+ ) : logStatus === "PUBLISHED" ? (
+
+ ) : logStatus === "PENDING" ? (
+
+ ) : (
+
+ )}
+
+
+
+
+
+
+
+
+ );
+};
+
+const refreshProject = async () => {
+ await fetchAndStoreProject({ projectId: $project.get()!.id });
+};
+
+const buttonLinkClass = css({
+ all: "unset",
+ cursor: "pointer",
+ ...textVariants.link,
+}).toString();
+
+const UpgradeBanner = ({
+ hasCustomDomains,
+ quota,
+}: {
+ hasCustomDomains: boolean;
+ quota: { userPublishCount: number; maxDailyPublishesPerUser: number };
+}) => {
+ const restrictedFeatures = useStore($restrictedFeatures);
+ const { load, data } = trpcClient.domain.countTotalDomains.useQuery();
+ const { maxDomainsAllowedPerUser } = useStore($permissions);
+ const project = useStore($project);
+ const activeDomainsCount = project?.domainsVirtual.filter(
+ (domain) => domain.status === "ACTIVE" && domain.verified
+ ).length;
+ useEffect(() => {
+ if (project?.id !== undefined) {
+ load({ projectId: project.id });
+ }
+ }, [load, activeDomainsCount, project?.id]);
+ const canAddDomain = data
+ ? data.success && data.data < maxDomainsAllowedPerUser
+ : true;
+ const { userPublishCount, maxDailyPublishesPerUser } = quota;
+ if (userPublishCount >= maxDailyPublishesPerUser) {
+ return (
+
+
+ Upgrade to publish more than {maxDailyPublishesPerUser} times per day:
+
+
+ Upgrade
+
+
+ );
+ }
+
+ // Only show Pro feature upgrade banner if custom domains are available
+ // Free tier users can still publish to staging domain with Pro features
+ if (restrictedFeatures.size > 0 && hasCustomDomains) {
+ return (
+
+
+ Following Pro features are used:
+
+ {Array.from(restrictedFeatures).map(
+ ([message, { navigate, view, info } = {}], index) => (
+
+
+ {navigate ? (
+
+ ) : (
+ message
+ )}
+ {info && (
+
+ } />
+
+ )}
+
+
+ )
+ )}
+
+
+ You can delete these features or upgrade to publish to custom domains.
+
+
+
+
+ Upgrade to Pro
+
+
+
+ );
+ }
+ if (canAddDomain === false) {
+ return (
+
+
+
+ Upgrade to a Pro account
+ {" "}
+ to add unlimited domains and publish to each domain individually.
+
+
+
+
+ Upgrade to Pro
+
+
+
+ );
+ }
+};
+
+export const Content = (props: {
+ projectId: Project["id"];
+ onExportClick: () => void;
+ flow: PublishUiState;
+}) => {
+ const restrictedFeatures = useStore($restrictedFeatures);
+ const [newDomains, setNewDomains] = useState(new Set());
+ const [isAddingDomain, setIsAddingDomain] = useState(false);
+
+ const project = useStore($project);
+
+ if (project == null) {
+ throw new Error("Project not found");
+ }
+
+ const { load: loadPublishCount, data: publishCount } =
+ trpcClient.project.userPublishCount.useQuery();
+ const { maxDailyPublishesPerUser } = useStore($permissions);
+ useEffect(() => {
+ loadPublishCount({ projectId: project.id });
+ }, [loadPublishCount, project.id]);
+ const quota = {
+ userPublishCount: publishCount?.success ? publishCount.data : 0,
+ maxDailyPublishesPerUser:
+ publishCount?.success && "limit" in publishCount
+ ? publishCount.limit
+ : maxDailyPublishesPerUser,
+ };
+
+ const hasUnpublishedDomains = project.domainsVirtual.some(
+ (domain) =>
+ domain.verified &&
+ domain.status === "ACTIVE" &&
+ domain.latestBuildVirtual == null
+ );
+
+ // Check if any custom domains exist (active and verified)
+ const hasCustomDomains = project.domainsVirtual.some(
+ (domain) => domain.status === "ACTIVE" && domain.verified
+ );
+ const hasSitePublish = props.flow.publishes.some(
+ ({ target }) => target === "site"
+ );
+ const diagnosticFindings = props.flow.siteFindings;
+ const hasDiagnostics =
+ hasSitePublish ||
+ diagnosticFindings.length > 0 ||
+ props.flow.siteError !== undefined;
+
+ return (
+ <>
+
+
+
+
+
+
+
+
+ }
+ onSelect={() => setIsAddingDomain(true)}
+ >
+ Add new domain
+
+ }
+ onSelect={props.onExportClick}
+ >
+ Export
+
+ }
+ disabled={!hasDiagnostics}
+ onSelect={() =>
+ props.flow.openSiteReport(
+ undefined,
+ hasSitePublish
+ ? "publish"
+ : props.flow.siteError !== undefined ||
+ diagnosticFindings.some(
+ ({ severity }) => severity === "error"
+ )
+ ? "errors"
+ : "warnings"
+ )
+ }
+ >
+ Diagnostics
+
+
+ }
+ onSelect={() => $openProjectSettings.set("publish")}
+ >
+ Publish settings
+
+
+
+
+
+ }
+ >
+ Publish
+
+
+ >
+ );
+};
+
+type DeployTarget = {
+ docs?: string;
+ command?: string;
+ ssgTemplates?: Templates[];
+};
+
+const deployTargets: Record = {
+ docker: {
+ docs: "https://docs.docker.com",
+ command: `
+ docker build -t my-image .
+ docker run my-image
+ `,
+ },
+ static: {
+ ssgTemplates: ["ssg"],
+ },
+ vercel: {
+ docs: "https://vercel.com/docs/cli",
+ command: "npx vercel@latest",
+ ssgTemplates: ["ssg-vercel"],
+ },
+ netlify: {
+ docs: "https://docs.netlify.com/cli/get-started/",
+ command: `
+npx netlify-cli@latest login
+npx netlify-cli sites:create
+npx netlify-cli build
+npx netlify-cli deploy`,
+ ssgTemplates: ["ssg-netlify"],
+ },
+};
+
+type DeployTargets = keyof typeof deployTargets;
+
+const isDeployTargets = (value: string): value is DeployTargets =>
+ Object.keys(deployTargets).includes(value);
+
+export const ExportContent = (props: { flow: PublishUiState }) => {
+ const npxCommand = "npx webstudio@latest";
+ const [deployTarget, setDeployTarget] = useState("docker");
+
+ return (
+
+
+
+
+
+ Destination
+
+
+
+
+
+ {deployTargets[deployTarget].ssgTemplates && (
+
+
+
+
+ Learn about deploying static sites{" "}
+
+ here
+
+
+
+ )}
+
+ {deployTargets[deployTarget].command && (
+
+
+
+ CLI
+
+
+
+
+ Step 1
+
+
+ Download and install Node v20+ from{" "}
+
+ nodejs.org
+ {" "}
+ or with{" "}
+
+ a package manager
+
+ .
+
+
+
+
+
+
+ Step 2
+
+
+ Run this command in your Terminal to install Webstudio CLI and
+ sync your project.
+
+
+
+
+
+ }>
+ Copy
+
+
+
+
+
+
+
+
+ Step 3
+
+
+ Run this command to publish to{" "}
+
+ {humanizeString(deployTarget)}
+ {" "}
+
+
+
+
+
+ }
+ >
+ Copy
+
+
+
+
+
+
+
+ Read the detailed documentation{" "}
+
+ here
+
+
+
+
+ )}
+
+ );
+};
diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx
index f6a0d3e84c..50673fcce6 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -1,1183 +1,1086 @@
-import stripIndent from "strip-indent";
-import { computed } from "nanostores";
import {
+ useCallback,
useEffect,
- useState,
- useOptimistic,
- startTransition,
useRef,
- useId,
+ useState,
+ type SetStateAction,
} from "react";
import { useStore } from "@nanostores/react";
import {
- PanelContent,
Button,
- cssVar,
- Tooltip,
- InfoTooltip,
- IconButton,
- Grid,
- Flex,
- Label,
- Text,
- InputField,
- Separator,
- ScrollArea,
- rawTheme,
- Select,
- theme,
- TextArea,
Link,
- LinkButton,
- PanelBanner,
- toast,
- RadioGroup,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
Popover,
- PopoverTrigger,
PopoverContent,
PopoverTitle,
- PopoverClose,
- PopoverTitleActions,
- css,
- textVariants,
- SmallIconButton,
+ PopoverTrigger,
+ Text,
+ Tooltip,
+ rawTheme,
+ theme,
+ toast,
} from "@webstudio-is/design-system";
-import { validateProjectDomain, type Project } from "@webstudio-is/project";
+import type { Project } from "@webstudio-is/project";
+import {
+ publishedDeploymentDestination,
+ type Templates,
+} from "@webstudio-is/sdk";
import {
- $planFeatures,
- $selectedPageId,
- selectInstance,
$authTokenPermissions,
- $editingPageId,
$permissions,
- $stagingUsername,
- $stagingPassword,
+ $planFeatures,
} from "~/shared/nano-states";
-import { $publisherHost } from "~/shared/sync/data-stores";
-import {
- $publishDialog,
- setActiveSidebarPanel,
-} from "../../shared/nano-states";
+import { $publishDialog } from "~/builder/shared/nano-states";
import { $project } from "~/shared/sync/data-stores";
-import { Domains } from "./domains";
-import { CollapsibleDomainSection } from "./collapsible-domain-section";
-import {
- ActivityIcon,
- AlertIcon,
- CheckCircleIcon,
- CopyIcon,
- GearIcon,
- UpgradeIcon,
- HelpIcon,
- InfoCircleIcon,
- EllipsesIcon,
- PlusIcon,
- SpinnerIcon,
- TerminalIcon,
-} from "@webstudio-is/icons";
-import { AddDomain } from "./add-domain";
-import { humanizeString } from "~/shared/string-utils";
-import { trpcClient, nativeClient } from "~/shared/trpc/trpc-client";
-import type { Templates } from "@webstudio-is/sdk";
-import { DomainCheckbox, domainToPublishName } from "./domain-checkbox";
-import { CopyToClipboard } from "~/shared/copy-to-clipboard";
-import { $openProjectSettings } from "~/shared/nano-states/project-settings";
-import {
- $dataSources,
- $instances,
- $pages,
- $projectSettings,
- $resources,
-} from "~/shared/sync/data-stores";
-import cmsUpgradeBanner from "~/shared/cms-upgrade-banner.svg?url";
-import { $currentSystem } from "~/shared/system";
-import { getPublishUrl } from "./publish-url";
-import {
- getRestrictedFeatures,
- type RestrictedFeature,
-} from "./restricted-features";
+import { nativeClient } from "~/shared/trpc/trpc-client";
import {
PublishDiagnosticsDialog,
- PublishValidationBanner,
+ type DiagnosticFinding,
} from "./diagnostics";
-import type { SessionPublish } from "./use-session-publishes";
-import { PublishActions } from "./publish-actions";
-import { usePublishFlow } from "./use-publish-flow";
-import { fetchAndStoreProject } from "./use-publish-progress";
import {
- getPublishStatusDisplay,
- getStaticPublishStatusDisplay,
-} from "./publish-status";
-import { DomainStatusButton } from "./domain-status-button";
-
-type ChangeProjectDomainProps = {
- project: Project;
- refresh: () => Promise;
- validatedDomains?: readonly string[];
- onOpenReport: (domain: string) => void;
- latestPublish?: SessionPublish;
-};
-
-const ChangeProjectDomain = ({
- project,
- refresh,
- validatedDomains,
- onOpenReport,
- latestPublish,
-}: ChangeProjectDomainProps) => {
- const id = useId();
- const currentSystem = useStore($currentSystem);
- const stagingUsername = useStore($stagingUsername);
- const stagingPassword = useStore($stagingPassword);
- const publisherHost = useStore($publisherHost);
-
- const [domain, setDomain] = useState(project.domain);
- const [error, setError] = useState();
- const [isUpdateInProgress, setIsUpdateInProgress] = useOptimistic(false);
- const [isUnpublishing, setIsUnpublishing] = useOptimistic(false);
-
- const pageUrl = getPublishUrl({
- domain: `${project.domain}.${publisherHost}`,
- pathname: currentSystem.pathname,
- username: stagingUsername,
- password: stagingPassword,
- });
-
- const updateProjectDomain = async () => {
- setIsUpdateInProgress(true);
- const validationResult = validateProjectDomain(domain);
-
- if (validationResult.success === false) {
- setError(validationResult.error);
- return;
- }
-
- const updateResult = await nativeClient.domain.updateProjectDomain.mutate({
- domain,
- projectId: project.id,
- });
-
- if (updateResult.success === false) {
- setError(updateResult.error);
- return;
- }
-
- await refresh();
- };
-
- const handleUpdateProjectDomain = () => {
- startTransition(async () => {
- await updateProjectDomain();
- });
- };
-
- const handleUnpublish = async () => {
- setIsUnpublishing(true);
- const result = await nativeClient.domain.unpublish.mutate({
- projectId: project.id,
- domain: `${project.domain}.${publisherHost}`,
- });
- if (result.success === false) {
- toast.error(result.message);
- return;
- }
- await refresh();
- toast.success(result.message);
- };
-
- const latestProjectDomainBuild =
- project.latestBuildVirtual?.domain === project.domain
- ? project.latestBuildVirtual
- : undefined;
-
- const { statusContent, color, Icon } =
- latestProjectDomainBuild != null
- ? getPublishStatusDisplay(latestProjectDomainBuild)
- : {
- statusContent: "Not published",
- color: cssVar("--foreground-secondary"),
- Icon: InfoCircleIcon,
- };
-
- const isPublished = latestProjectDomainBuild != null;
-
- return (
-
- }
- suffix={
-
- {statusContent},
- }}
- onOpenReport={() => onOpenReport(project.domain)}
- />
-
-
-
-
-
-
-
- }
- >
-
-
-
-
-
-
- {
- setError(undefined);
- setDomain(event.target.value);
- }}
- onBlur={handleUpdateProjectDomain}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- handleUpdateProjectDomain();
- }
-
- if (event.key === "Escape") {
- if (project.domain !== domain) {
- setDomain(project.domain);
- event.preventDefault();
- }
- }
- }}
- color={error !== undefined ? "error" : undefined}
- />
- {error !== undefined && {error}}
-
- {stagingUsername && (
-
-
-
-
- )}
- {stagingPassword && (
-
-
-
-
-
-
-
- )}
- {isPublished && (
-
-
-
- )}
-
-
- );
-};
-
-const $restrictedFeatures = computed(
- [
- $pages,
- $projectSettings,
- $dataSources,
- $resources,
- $instances,
- $permissions,
- ],
- (pages, projectSettings, dataSources, resources, instances, permissions) =>
- getRestrictedFeatures({
- pages,
- projectSettings,
- dataSources,
- resources,
- instances,
- permissions,
- })
-);
-
-const matchesValidatedDomains = (form: HTMLFormElement, domains: string[]) => {
- const selected = new Set(domains);
- const current = new FormData(form)
- .getAll(domainToPublishName)
- .map((domain) => domain.toString());
- return (
- current.length === selected.size &&
- current.every((domain) => selected.has(domain))
- );
-};
-
-const Publish = ({
- project,
- quota,
- restrictedFeatures,
- flow,
-}: {
- project: Project;
- quota: ReturnType;
- restrictedFeatures: Map;
- flow: ReturnType;
-}) => {
- const {
- isPublishing,
- countdown,
- validationState,
- validatedDomains,
- invalidateValidation,
- publishes,
- siteError,
- siteErrorSource,
- openSiteReport: onOpenReport,
- } = flow;
- const { userPublishCount, maxDailyPublishesPerUser } = quota;
- const buttonRef = useRef(null);
- const [hasSelectedDomains, setHasSelectedDomains] = useState(false);
- const [hasCustomDomainsSelected, setHasCustomDomainsSelected] =
- useState(false);
- const previousDomainsKey = useRef();
- const hasPendingState = project.latestBuildVirtual
- ? getPublishStatusDisplay(project.latestBuildVirtual).status === "PENDING"
- : false;
- const isPublishInProgress = isPublishing || hasPendingState;
-
- useEffect(() => {
- const form = buttonRef.current?.closest("form");
-
- if (form == null) {
- return;
- }
-
- const handleFormInput = () => {
- const formData = new FormData(form);
- const domainsSelected = formData
- .getAll(domainToPublishName)
- .map((domain) => domain.toString());
- const domainsKey = domainsSelected.join("\u0000");
-
- if (
- previousDomainsKey.current !== undefined &&
- previousDomainsKey.current !== domainsKey
- ) {
- invalidateValidation();
- }
- previousDomainsKey.current = domainsKey;
-
- setHasSelectedDomains(domainsSelected.length > 0);
-
- // Check if any custom domains are selected
- // Custom domains are those that are NOT the staging domain (project.domain)
- const hasCustom = domainsSelected.some(
- (domain) => domain !== project.domain
- );
- setHasCustomDomainsSelected(hasCustom);
- };
-
- const observer = new MutationObserver(() => {
- handleFormInput();
- });
-
- observer.observe(form, {
- attributes: true,
- childList: true,
- subtree: true,
- attributeFilter: ["value", "checked"],
- });
-
- if (validatedDomains !== undefined) {
- if (matchesValidatedDomains(form, validatedDomains)) {
- previousDomainsKey.current = validatedDomains.join("\u0000");
- } else {
- invalidateValidation();
- }
- }
-
- handleFormInput();
-
- return () => {
- observer.disconnect();
- };
- }, [invalidateValidation, project.domain, validatedDomains]);
-
- const getDomainsFromForm = (formData: FormData) =>
- formData
- .getAll(domainToPublishName)
- .map((domainEntry) => domainEntry.toString());
-
- const getForm = () => buttonRef.current?.closest("form");
- const findings = flow.siteFindings;
- const hasSessionPublish = publishes.some(({ target }) => target === "site");
-
- return (
-
- {siteError !== undefined ? (
-
-
-
- {typeof siteError === "string"
- ? siteError.slice(0, 160)
- : siteError}
-
-
-
-
- ) : (
-
- onOpenReport(
- undefined,
- findings.some(({ severity }) => severity === "error")
- ? "errors"
- : "warnings"
- )
- }
- />
- )}
- 0 && hasCustomDomainsSelected) ||
- userPublishCount >= maxDailyPublishesPerUser
- }
- publishInProgress={isPublishInProgress}
- publishPending={
- isPublishInProgress && (countdown === undefined || countdown === 0)
- }
- hasSelectedDomains={hasSelectedDomains}
- publishLabel={
- countdown !== undefined && countdown > 0
- ? `Publishing (${countdown}s)`
- : "Publish"
- }
- onValidate={async () => {
- const form = getForm();
- if (form) {
- await flow.validate(getDomainsFromForm(new FormData(form)));
- }
- }}
- onPublish={() => {
- const form = getForm();
- if (form) {
- flow.publish({
- target: "site",
- domains: getDomainsFromForm(new FormData(form)),
- timesLeft: maxDailyPublishesPerUser - userPublishCount,
- maxDailyPublishesPerUser,
- });
- }
- }}
- />
-
- );
-};
-
-const PublishStatic = ({
- templates,
- flow,
- onDownload,
-}: {
- templates: readonly Templates[];
- flow: ReturnType;
- onDownload?: (name: string) => void;
-}) => {
- const {
- isPublishing,
- publishes,
- staticFailureFinding,
- openStaticReport: onOpenReport,
- } = flow;
- const project = useStore($project);
-
- if (project == null) {
- throw new Error("Project not found");
- }
-
- const { status, statusContent } =
- project.latestStaticBuild == null
- ? { status: "LOADED" as const, statusContent: "Not published" }
- : getStaticPublishStatusDisplay(project.latestStaticBuild);
- const latestPublish = publishes.find(
- (item) =>
- item.target === "static" &&
- item.buildId === project.latestStaticBuild?.buildId
- );
- const logStatus =
- staticFailureFinding !== undefined
- ? "FAILED"
- : latestPublish?.status === "pending"
- ? "PENDING"
- : latestPublish?.status === "failed"
- ? "FAILED"
- : latestPublish?.status === "success"
- ? "PUBLISHED"
- : status;
-
- const isPublishInProgress = status === "PENDING" || isPublishing;
-
- return (
-
-
-
- onOpenReport()}
- >
- {logStatus === "FAILED" ? (
-
- ) : logStatus === "PUBLISHED" ? (
-
- ) : logStatus === "PENDING" ? (
-
- ) : (
-
- )}
-
-
-
-
-
-
-
-
- );
-};
-
-const useCanAddDomain = () => {
- const { load, data } = trpcClient.domain.countTotalDomains.useQuery();
- const { maxDomainsAllowedPerUser } = useStore($permissions);
- const project = useStore($project);
- const activeDomainsCount = project?.domainsVirtual.filter(
- (domain) => domain.status === "ACTIVE" && domain.verified
- ).length;
- useEffect(() => {
- if (project?.id !== undefined) {
- load({ projectId: project.id });
- }
- }, [load, activeDomainsCount, project?.id]);
- const canAddDomain = data
- ? data.success && data.data < maxDomainsAllowedPerUser
- : true;
- return { canAddDomain, maxDomainsAllowedPerUser };
-};
-
-const useUserPublishCount = () => {
- const { load, data } = trpcClient.project.userPublishCount.useQuery();
- const { maxDailyPublishesPerUser } = useStore($permissions);
- const project = useStore($project);
- useEffect(() => {
- if (project?.id !== undefined) {
- load({ projectId: project.id });
- }
- }, [load, project?.id]);
- return {
- userPublishCount: data?.success ? data.data : 0,
- maxDailyPublishesPerUser:
- data?.success && "limit" in data ? data.limit : maxDailyPublishesPerUser,
- };
-};
-
-const refreshProject = async () => {
- await fetchAndStoreProject({ projectId: $project.get()!.id });
-};
-
-const buttonLinkClass = css({
- all: "unset",
- cursor: "pointer",
- ...textVariants.link,
-}).toString();
-
-const UpgradeBanner = ({
- hasCustomDomains,
- quota,
-}: {
- hasCustomDomains: boolean;
- quota: ReturnType;
-}) => {
- const restrictedFeatures = useStore($restrictedFeatures);
- const { canAddDomain } = useCanAddDomain();
- const { userPublishCount, maxDailyPublishesPerUser } = quota;
- if (userPublishCount >= maxDailyPublishesPerUser) {
- return (
-
-
- Upgrade to publish more than {maxDailyPublishesPerUser} times per day:
-
-
- Upgrade
-
-
- );
- }
-
- // Only show Pro feature upgrade banner if custom domains are available
- // Free tier users can still publish to staging domain with Pro features
- if (restrictedFeatures.size > 0 && hasCustomDomains) {
- return (
-
-
- Following Pro features are used:
-
- {Array.from(restrictedFeatures).map(
- ([message, { navigate, view, info } = {}], index) => (
-
-
- {navigate ? (
-
- ) : (
- message
- )}
- {info && (
-
- } />
-
- )}
-
-
- )
- )}
-
-
- You can delete these features or upgrade to publish to custom domains.
-
-
-
-
- Upgrade to Pro
-
-
-
- );
- }
- if (canAddDomain === false) {
- return (
-
-
-
- Upgrade to a Pro account
- {" "}
- to add unlimited domains and publish to each domain individually.
-
-
-
-
- Upgrade to Pro
-
-
-
- );
- }
-};
-
-const Content = (props: {
- projectId: Project["id"];
- onExportClick: () => void;
- flow: ReturnType;
-}) => {
- const restrictedFeatures = useStore($restrictedFeatures);
- const [newDomains, setNewDomains] = useState(new Set());
- const [isAddingDomain, setIsAddingDomain] = useState(false);
-
- const project = useStore($project);
-
- if (project == null) {
- throw new Error("Project not found");
- }
-
- const quota = useUserPublishCount();
-
- const hasUnpublishedDomains = project.domainsVirtual.some(
- (domain) =>
- domain.verified &&
- domain.status === "ACTIVE" &&
- domain.latestBuildVirtual == null
- );
-
- // Check if any custom domains exist (active and verified)
- const hasCustomDomains = project.domainsVirtual.some(
- (domain) => domain.status === "ACTIVE" && domain.verified
- );
- const hasSitePublish = props.flow.publishes.some(
- ({ target }) => target === "site"
- );
- const diagnosticFindings = props.flow.siteFindings;
- const hasDiagnostics =
- hasSitePublish ||
- diagnosticFindings.length > 0 ||
- props.flow.siteError !== undefined;
-
- return (
- <>
-
-
-
-
-
-
-
-
- }
- onSelect={() => setIsAddingDomain(true)}
- >
- Add new domain
-
- }
- onSelect={props.onExportClick}
- >
- Export
-
- }
- disabled={!hasDiagnostics}
- onSelect={() =>
- props.flow.openSiteReport(
- undefined,
- hasSitePublish
- ? "publish"
- : props.flow.siteError !== undefined ||
- diagnosticFindings.some(
- ({ severity }) => severity === "error"
- )
- ? "errors"
- : "warnings"
- )
- }
- >
- Diagnostics
-
-
- }
- onSelect={() => $openProjectSettings.set("publish")}
- >
- Publish settings
-
-
-
-
-
- }
- >
- Publish
-
-
- >
- );
-};
-
-type DeployTarget = {
- docs?: string;
- command?: string;
- ssgTemplates?: Templates[];
-};
-
-const deployTargets: Record = {
- docker: {
- docs: "https://docs.docker.com",
- command: `
- docker build -t my-image .
- docker run my-image
- `,
- },
- static: {
- ssgTemplates: ["ssg"],
- },
- vercel: {
- docs: "https://vercel.com/docs/cli",
- command: "npx vercel@latest",
- ssgTemplates: ["ssg-vercel"],
- },
- netlify: {
- docs: "https://docs.netlify.com/cli/get-started/",
- command: `
-npx netlify-cli@latest login
-npx netlify-cli sites:create
-npx netlify-cli build
-npx netlify-cli deploy`,
- ssgTemplates: ["ssg-netlify"],
- },
-};
-
-type DeployTargets = keyof typeof deployTargets;
-
-const isDeployTargets = (value: string): value is DeployTargets =>
- Object.keys(deployTargets).includes(value);
-
-const ExportContent = (props: { flow: ReturnType }) => {
- const npxCommand = "npx webstudio@latest";
- const [deployTarget, setDeployTarget] = useState("docker");
-
- return (
-
-
-
-
-
- Destination
-
-
-
-
-
- {deployTargets[deployTarget].ssgTemplates && (
-
-
-
-
- Learn about deploying static sites{" "}
-
- here
-
-
-
- )}
-
- {deployTargets[deployTarget].command && (
-
-
-
- CLI
-
-
-
-
- Step 1
-
-
- Download and install Node v20+ from{" "}
-
- nodejs.org
- {" "}
- or with{" "}
-
- a package manager
-
- .
-
-
-
-
-
-
- Step 2
-
-
- Run this command in your Terminal to install Webstudio CLI and
- sync your project.
-
-
-
-
-
- }>
- Copy
-
-
-
-
-
-
-
-
- Step 3
-
-
- Run this command to publish to{" "}
-
- {humanizeString(deployTarget)}
- {" "}
-
-
-
-
-
- }
- >
- Copy
-
-
-
-
-
-
-
- Read the detailed documentation{" "}
-
- here
-
-
-
-
- )}
-
- );
-};
+ decodePublishLog,
+ selectSessionPublishes,
+ type SessionPublish,
+} from "./session-publishes";
+import type { PublishValidationState } from "./publish-actions";
+import {
+ fetchAndStoreProject,
+ waitForPublishStatus,
+ refreshProjectWithRetry,
+ reportPublishResult,
+ type PublishExecution,
+} from "./publish-progress";
+import {
+ runPublishDiagnostics,
+ runPublishValidation,
+ reportPublishValidationFailure,
+ getServerPublishFindings,
+} from "./publish-validation";
+import { runPublishAfterBestEffortChecks } from "./publish-preflight";
+import { getPublishStatusDisplay } from "./publish-status";
+import { Content, ExportContent } from "./publish-ui";
type PublishProps = {
projectId: Project["id"];
};
+const COUNTDOWN_DURATION = 60_000;
+
+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 PublishButton = ({ projectId }: PublishProps) => {
const publishDialog = useStore($publishDialog);
const authTokenPermissions = useStore($authTokenPermissions);
const { allowPublishLogs = false } = useStore($planFeatures);
- const flow = usePublishFlow(projectId, allowPublishLogs, publishDialog);
- const { diagnosticsSelection, closeReport, reportFindings, reportPublishes } =
- flow;
+ const [manualFindings, setManualFindings] = useState([]);
+ const [manualDomains, setManualDomains] = useState();
+ const validationSession = useRef(0);
+ const requestedManualDomains = useRef([]);
+
+ useEffect(() => {
+ return () => {
+ validationSession.current += 1;
+ };
+ }, []);
+
+ const beginManualValidation = useCallback((manualDomains: string[] = []) => {
+ validationSession.current += 1;
+ requestedManualDomains.current = manualDomains;
+ setManualFindings([]);
+ setManualDomains(undefined);
+ return validationSession.current;
+ }, []);
+
+ const invalidateManualValidation = useCallback(() => {
+ validationSession.current += 1;
+ setManualFindings([]);
+ setManualDomains(undefined);
+ }, []);
+
+ const isManualValidationCurrent = useCallback(
+ (id: number) => validationSession.current === id,
+ []
+ );
+
+ const updateManualValidation = useCallback(
+ (id: number, next: DiagnosticFinding[]) => {
+ if (validationSession.current === id) {
+ setManualFindings(next);
+ setManualDomains(
+ next.length > 0 ? requestedManualDomains.current : undefined
+ );
+ }
+ },
+ []
+ );
+
+ 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 [startedAt, setStartedAt] = useState();
+ 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();
+ const hasStartedPublishRequest = useRef(false);
+ const refreshGeneration = useRef(0);
+ const recoveredPoll = useRef<{
+ generation: number;
+ promise: Promise;
+ }>();
+
+ 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);
+ invalidateManualValidation();
+ }, [projectId, invalidateManualValidation]);
+
+ 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) => {
+ 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) => {
+ 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,
+ generation = refreshGeneration.current,
+ execution?: PublishExecution,
+ onResult?: (
+ result: Awaited>
+ ) => 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,
+ {
+ 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);
+ }
+ });
+ };
+
+ const [items, setItems] = useState([]);
+ const itemsProjectId = useRef(projectId);
+ const generation = useRef(0);
+ const permission = useRef({ allowed: allowPublishLogs, generation: 0 });
+ if (permission.current.allowed !== allowPublishLogs) {
+ permission.current = {
+ allowed: allowPublishLogs,
+ generation: permission.current.generation + 1,
+ };
+ }
+ const loading = useRef(
+ new Map()
+ );
+ const retainedBuilds = useRef(new Set());
+
+ useEffect(() => {
+ generation.current += 1;
+ itemsProjectId.current = projectId;
+ setItems([]);
+ loading.current.clear();
+ retainedBuilds.current.clear();
+ return () => {
+ generation.current += 1;
+ };
+ }, [projectId]);
+
+ useEffect(() => {
+ if (allowPublishLogs === false) {
+ setItems((current) =>
+ current.map((item) => ({
+ ...item,
+ startedAt: undefined,
+ completedAt: undefined,
+ failedStage: undefined,
+ code: undefined,
+ issues: undefined,
+ issuesOmitted: undefined,
+ logState: undefined,
+ logText: undefined,
+ }))
+ );
+ }
+ }, [allowPublishLogs]);
+
+ const update = useCallback(
+ (buildId: string, change: Partial) => {
+ setItems((current) =>
+ current.map((item) =>
+ item.buildId === buildId ? { ...item, ...change } : item
+ )
+ );
+ },
+ []
+ );
+
+ const record = useCallback(
+ (item: Omit) => {
+ if (isCurrentProject() === 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;
+ },
+ [isCurrentProject]
+ );
+
+ const complete = useCallback(
+ (buildId: string, status: "success" | "failed", code?: string) => {
+ if (isCurrentProject() && retainedBuilds.current.has(buildId)) {
+ update(buildId, {
+ status,
+ code: permission.current.allowed ? code : undefined,
+ });
+ }
+ },
+ [isCurrentProject, update]
+ );
+
+ const loadLog = useCallback(
+ async (item: SessionPublish) => {
+ if (
+ isCurrentProject() === 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 &&
+ isCurrentProject() &&
+ retainedBuilds.current.has(item.buildId) &&
+ permission.current.allowed &&
+ permission.current.generation === currentPermissionGeneration;
+ try {
+ let cursor: number | undefined;
+ const chunks: string[] = [];
+ const issues: NonNullable = [];
+ 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);
+ }
+ }
+ },
+ [isCurrentProject, projectId, scopeToken, update]
+ );
+
+ const visiblePublishes = itemsProjectId.current === projectId ? items : [];
+
+ const [validationState, setValidationState] =
+ useState("idle");
+ const dialogRef = useRef(publishDialog);
+ dialogRef.current = publishDialog;
+
+ const resetValidationState = useCallback(() => {
+ setValidationState("idle");
+ }, []);
+
+ const updateValidationState = 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 (publishDialog !== "publish") {
+ resetValidationState();
+ }
+ }, [publishDialog, resetValidationState]);
+
+ const sessionPublishesRef = useRef(visiblePublishes);
+ sessionPublishesRef.current = visiblePublishes;
+ const [diagnosticsSelection, setDiagnosticsSelection] = useState<{
+ target: "static" | "site";
+ domain?: string;
+ tab: "warnings" | "errors" | "publish";
+ }>();
+ useEffect(() => {
+ setDiagnosticsSelection(undefined);
+ }, [projectId]);
+ useEffect(() => {
+ if (publishDialog !== "publish") {
+ dismissCountdown();
+ }
+ }, [publishDialog, dismissCountdown]);
+ const invalidateValidation = useCallback(() => {
+ invalidateManualValidation();
+ updateValidationState("idle");
+ }, [invalidateManualValidation, updateValidationState]);
+
+ const finishPublish = useCallback(
+ (
+ item: SessionPublish | undefined,
+ result: Awaited>
+ ) => {
+ if (
+ item === undefined ||
+ !isCurrentProject() ||
+ (result?.status !== "PUBLISHED" && result?.status !== "FAILED")
+ ) {
+ return;
+ }
+ const status = result.status === "PUBLISHED" ? "success" : "failed";
+ complete(item.buildId, status, result.code);
+ loadLog({ ...item, status });
+ if (
+ item.target === "static" &&
+ status === "success" &&
+ item.staticName !== undefined
+ ) {
+ window.location.href = `/cgi/static/ssg/${item.staticName}`;
+ }
+ },
+ [complete, loadLog, isCurrentProject]
+ );
+
+ const waitForCompletion = async (
+ item: SessionPublish | undefined,
+ previousBuildId?: string
+ ) => {
+ if (item === undefined) {
+ return;
+ }
+ const result = await waitForPublishStatus(
+ () => fetchAndStoreProject({ projectId, isCurrent: isCurrentProject }),
+ isCurrentProject,
+ previousBuildId,
+ {
+ projectId,
+ buildId: item.buildId,
+ logHandle: item.logHandle,
+ target: item.target,
+ }
+ );
+ finishPublish(item, result);
+ return result;
+ };
+ useEffect(() => {
+ // Refresh a build that finished while the popover was closed, including
+ // after a publish status request failed.
+ if (publishDialog !== "none" && 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,
+ 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(
+ visiblePublishes,
+ diagnosticsSelection?.target ?? "site",
+ diagnosticsSelection?.domain
+ );
+ const domain = diagnosticsSelection?.domain;
+ const siteFindings = [...manualFindings, ...publishDiagnostics.site.findings];
+ const staticDiagnostics = publishDiagnostics.static;
+ const staticFailureFinding = staticDiagnostics.rejected
+ ? staticDiagnostics.findings
+ .filter(({ severity }) => severity === "error")
+ .at(-1)
+ : undefined;
+ const findings: DiagnosticFinding[] = [];
+ const diagnostics =
+ 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 || manualDomains?.includes(domain)) {
+ findings.push(...manualFindings);
+ }
+ const publishError = publishErrorState?.value;
+ const publishErrorDomains = publishErrorState?.domains;
+ if (
+ publishError !== undefined &&
+ (domain === undefined ||
+ publishErrorDomains === undefined ||
+ publishErrorDomains.includes(domain))
+ ) {
+ findings.push(
+ getPublishErrorFinding(publishError, publishErrorState?.buildId)
+ );
+ }
+ }
+
+ const validate = async (domains: string[]) => {
+ const session = beginManualValidation(domains);
+ clearErrors();
+ 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 (isManualValidationCurrent(session) === false) {
+ return;
+ }
+ updateManualValidation(session, checks.findings);
+ if (checks.passed === false) {
+ updateValidationState("idle");
+ return;
+ }
+ updateValidationState("passed");
+ } catch (error) {
+ if (isManualValidationCurrent(session) === false) {
+ return;
+ }
+ updateValidationState("idle");
+ reportPublishValidationFailure(
+ error,
+ (findings) => updateManualValidation(session, findings),
+ { showToast: $publishDialog.get() !== "publish" }
+ );
+ }
+ };
+
+ const publishSite = (
+ domains: string[],
+ timesLeft: number,
+ maxDailyPublishesPerUser: number
+ ) => {
+ if (!isCurrentProject()) {
+ return;
+ }
+ invalidateManualValidation();
+ updateValidationState("idle");
+ if (domains.length === 0) {
+ toast.error("Please select at least one domain to publish");
+ return;
+ }
+ const diagnostics = beginPublishDiagnostics(domains);
+ start(
+ async () => {
+ const previousBuildId = $project.get()?.latestBuildVirtual?.buildId;
+ const publishResult = await runPublishAfterBestEffortChecks({
+ checks: async () => {
+ const checks = await runPublishDiagnostics(projectId, domains);
+ diagnostics.setFindings(checks.findings);
+ },
+ onCheckFailure: (error) => {
+ if (isCurrentProject() && diagnostics.isCurrent()) {
+ reportPublishValidationFailure(error, diagnostics.setFindings, {
+ publishingContinues: true,
+ showToast: $publishDialog.get() !== "publish",
+ });
+ }
+ },
+ publish: () =>
+ nativeClient.domain.publish.mutate({
+ projectId,
+ destination: publishedDeploymentDestination,
+ domains,
+ }),
+ });
+ if (!isCurrentProject()) {
+ return;
+ }
+ if (publishResult.success === false) {
+ if ("auditFindings" in publishResult) {
+ diagnostics.finish((findings) => [
+ ...findings,
+ ...getServerPublishFindings(publishResult.auditFindings),
+ ]);
+ return;
+ }
+ diagnostics.finish();
+ console.error(publishResult.error);
+
+ let error: JSX.Element | string = publishResult.error;
+ if (publishResult.error === "NOT_IMPLEMENTED") {
+ error = (
+ <>
+
+ {$project.get()?.latestBuildVirtual?.buildId}
+
+ }
+ >
+ Build data
+ {" "}
+ for publishing has been successfully created. Use{" "}
+
+ Webstudio CLI
+ {" "}
+ to generate the code.
+ >
+ );
+ }
+ 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: isCurrentProject,
+ });
+ }
+
+ return;
+ }
+
+ const accepted = record({
+ buildId: publishResult.buildId,
+ logHandle: publishResult.logHandle,
+ target: "site",
+ domains,
+ findings: getServerPublishFindings(publishResult.findings),
+ });
+ const outcome = await waitForCompletion(accepted, previousBuildId);
+ reportPublishResult({
+ result: outcome,
+ buildId: accepted?.buildId,
+ timesLeft,
+ maxDailyPublishesPerUser,
+ setPublishError: setPublishStatusError,
+ isCurrentProject,
+ });
+ },
+ {
+ domains,
+ onError: () => diagnostics.finish(),
+ }
+ );
+ };
+
+ const exportStatic = (templates: readonly Templates[]) => {
+ if (!isCurrentProject()) {
+ return;
+ }
+ const diagnostics = beginPublishDiagnostics([], "static");
+ start(
+ async () => {
+ const publishResult = await runPublishAfterBestEffortChecks({
+ checks: async () => {
+ const checks = await runPublishDiagnostics(projectId);
+ diagnostics.setFindings(checks.findings);
+ },
+ onCheckFailure: (error) => {
+ if (isCurrentProject() && diagnostics.isCurrent()) {
+ reportPublishValidationFailure(error, diagnostics.setFindings, {
+ publishingContinues: true,
+ showToast: true,
+ });
+ }
+ },
+ publish: () =>
+ nativeClient.domain.publish.mutate({
+ projectId,
+ destination: "static",
+ templates: [...templates],
+ }),
+ });
+ if (!isCurrentProject()) {
+ return;
+ }
+ if (publishResult.success === false) {
+ if ("auditFindings" in publishResult) {
+ diagnostics.finish((findings) => [
+ ...findings,
+ ...getServerPublishFindings(publishResult.auditFindings),
+ ]);
+ openStaticReport("errors");
+ return;
+ }
+ diagnostics.finish((findings) => [
+ ...findings,
+ getPublishErrorFinding(publishResult.error),
+ ]);
+ toast.error(publishResult.error.slice(0, 200));
+ return;
+ }
+ const accepted = record({
+ buildId: publishResult.buildId,
+ logHandle: publishResult.logHandle,
+ target: "static",
+ domains: [],
+ findings: getServerPublishFindings(publishResult.findings),
+ staticName: "name" in publishResult ? publishResult.name : undefined,
+ });
+ if (accepted?.staticName == null) {
+ toast.error('File name must be defined in "result"');
+ }
+ const outcome = await waitForCompletion(accepted);
+ if (isCurrentProject() && outcome?.status === "FAILED") {
+ toast.error(outcome.statusContent);
+ }
+ },
+ {
+ target: "static",
+ domains: [],
+ onError: (message) =>
+ diagnostics.finish((findings) => [
+ ...findings,
+ getPublishErrorFinding(message),
+ ]),
+ }
+ );
+ };
+ const flow = {
+ isPublishing,
+ countdown,
+ validationState,
+ validatedDomains: manualDomains,
+ siteError: publishErrorState?.value,
+ siteErrorSource: publishErrorState?.source,
+ siteFindings,
+ staticFailureFinding,
+ publishes: visiblePublishes,
+ loadLog,
+ diagnosticsSelection,
+ closeReport: () => setDiagnosticsSelection(undefined),
+ reportPublishes,
+ reportFindings: findings,
+ includeLatestPublishFindings: !(
+ diagnostics.rejected && includesSelectedDomain
+ ),
+ openSiteReport,
+ openStaticReport,
+ validate,
+ publishSite,
+ exportStatic,
+ invalidateValidation,
+ reset: () => {
+ resetValidationState();
+ dismissCountdown();
+ },
+ };
const { canPublishToStagingOnly } = useStore($permissions);
const isPublishEnabled =
authTokenPermissions.canPublish || canPublishToStagingOnly;
@@ -1237,12 +1140,12 @@ export const PublishButton = ({ projectId }: PublishProps) => {
{
if (open === false) {
- closeReport();
+ flow.closeReport();
}
}}
target={
@@ -1251,12 +1154,10 @@ export const PublishButton = ({ projectId }: PublishProps) => {
: diagnosticsSelection?.domain
}
initialTab={diagnosticsSelection?.tab}
- items={reportPublishes}
+ items={flow.reportPublishes}
canViewPublishLogs={allowPublishLogs}
onLoadLog={flow.loadLog}
/>
>
);
};
-
-export const __testing__ = { PublishStatic };
diff --git a/apps/builder/app/builder/features/publish/session-publishes.test.ts b/apps/builder/app/builder/features/publish/session-publishes.test.ts
new file mode 100644
index 0000000000..f98cdb0de2
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/session-publishes.test.ts
@@ -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"]);
+});
diff --git a/apps/builder/app/builder/features/publish/session-publishes.ts b/apps/builder/app/builder/features/publish/session-publishes.ts
new file mode 100644
index 0000000000..0fb8532ae7
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/session-publishes.ts
@@ -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))
+ );
diff --git a/apps/builder/app/builder/features/publish/use-publish-flow.test.tsx b/apps/builder/app/builder/features/publish/use-publish-flow.test.tsx
deleted file mode 100644
index f56d3efe01..0000000000
--- a/apps/builder/app/builder/features/publish/use-publish-flow.test.tsx
+++ /dev/null
@@ -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 = () => {
- let resolve!: (value: T) => void;
- let reject!: (error: Error) => void;
- const promise = new Promise((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();
-let dispatch = deferred();
-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;
-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();
- dispatch = deferred();
- 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());
-});
-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();
- 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());
- 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();
- dispatch = deferred();
- 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",
- ]);
- }
- }
-);
diff --git a/apps/builder/app/builder/features/publish/use-publish-flow.tsx b/apps/builder/app/builder/features/publish/use-publish-flow.tsx
deleted file mode 100644
index 7fcc9d667a..0000000000
--- a/apps/builder/app/builder/features/publish/use-publish-flow.tsx
+++ /dev/null
@@ -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>,
- 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 = (
- <>
-
- {$project.get()?.latestBuildVirtual?.buildId}
-
- }
- >
- Build data
- {" "}
- for publishing has been successfully created. Use{" "}
-
- Webstudio CLI
- {" "}
- 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();
- },
- };
-};
diff --git a/apps/builder/app/builder/features/publish/use-publish-progress.tsx b/apps/builder/app/builder/features/publish/use-publish-progress.tsx
deleted file mode 100644
index f8ac9602a1..0000000000
--- a/apps/builder/app/builder/features/publish/use-publish-progress.tsx
+++ /dev/null
@@ -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();
- 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();
- const hasStartedPublishRequest = useRef(false);
- const refreshGeneration = useRef(0);
- const recoveredPoll = useRef<{
- generation: number;
- promise: Promise;
- }>();
-
- 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) => {
- 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) => {
- 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,
- generation = refreshGeneration.current,
- execution?: PublishExecution,
- onResult?: (
- result: Awaited>
- ) => 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,
- {
- 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,
- 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,
- 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>;
- 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 && (
-
- You have {timesLeft} out of {maxDailyPublishesPerUser} daily
- publications remaining. The counter resets tomorrow.
-
- )}
- >,
- { 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([]);
- const [domains, setDomains] = useState();
- const session = useRef(0);
- const requestedDomains = useRef([]);
-
- 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;
- 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,
-};
diff --git a/apps/builder/app/builder/features/publish/use-session-publishes.test.tsx b/apps/builder/app/builder/features/publish/use-session-publishes.test.tsx
deleted file mode 100644
index 9f16d16520..0000000000
--- a/apps/builder/app/builder/features/publish/use-session-publishes.test.tsx
+++ /dev/null
@@ -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;
-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 (
-
- );
-};
-
-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((resolve) => {
- releaseFirst = () => resolve(response);
- });
- }
- if (holdSecond && !first) {
- holdSecond = false;
- return await new Promise((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(
-
- )
- );
-};
-
-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"]);
-});
diff --git a/apps/builder/app/builder/features/publish/use-session-publishes.tsx b/apps/builder/app/builder/features/publish/use-session-publishes.tsx
deleted file mode 100644
index a3ceeb029e..0000000000
--- a/apps/builder/app/builder/features/publish/use-session-publishes.tsx
+++ /dev/null
@@ -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([]);
- 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()
- );
- const retainedBuilds = useRef(new Set());
-
- 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) => {
- setItems((current) =>
- current.map((item) =>
- item.buildId === buildId ? { ...item, ...change } : item
- )
- );
- },
- []
- );
-
- const record = useCallback(
- (item: Omit) => {
- 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 = [];
- 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,
- };
-};