From ea3c6175bdb544a174fa745a392850f87cb5fab0 Mon Sep 17 00:00:00 2001 From: Oleg Isonen Date: Sun, 15 Nov 2026 11:16:08 +0000 Subject: [PATCH] refactor: simplify publish diagnostics UI --- .../app/builder/features/publish/constants.ts | 2 +- .../features/publish/diagnostics-utils.ts | 2 +- .../features/publish/diagnostics.test.tsx | 2 +- .../builder/features/publish/diagnostics.tsx | 4 +- .../features/publish/domain-status-button.tsx | 2 +- .../builder/features/publish/domains.test.tsx | 2 +- .../app/builder/features/publish/domains.tsx | 2 +- .../features/publish/publish-actions.test.tsx | 144 +- .../features/publish/publish-actions.tsx | 37 +- .../publish/publish-click.render.test.tsx | 124 + .../publish/publish-flow.render.test.tsx | 761 ++++++ .../publish/publish-progress.render.test.tsx | 807 ++++++ .../publish/publish-progress.test.tsx | 1017 +------- .../features/publish/publish-progress.tsx | 219 ++ .../publish/publish-session.render.test.tsx | 429 ++++ .../features/publish/publish-static.test.tsx | 243 +- .../features/publish/publish-status.test.tsx | 4 +- .../builder/features/publish/publish-ui.tsx | 1167 +++++++++ .../app/builder/features/publish/publish.tsx | 2211 ++++++++--------- .../publish/session-publishes.test.ts | 52 + .../features/publish/session-publishes.ts | 54 + .../publish/use-publish-flow.test.tsx | 465 ---- .../features/publish/use-publish-flow.tsx | 504 ---- .../features/publish/use-publish-progress.tsx | 581 ----- .../publish/use-session-publishes.test.tsx | 314 --- .../publish/use-session-publishes.tsx | 293 --- 26 files changed, 4818 insertions(+), 4624 deletions(-) create mode 100644 apps/builder/app/builder/features/publish/publish-flow.render.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-progress.render.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-progress.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-session.render.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-ui.tsx create mode 100644 apps/builder/app/builder/features/publish/session-publishes.test.ts create mode 100644 apps/builder/app/builder/features/publish/session-publishes.ts delete mode 100644 apps/builder/app/builder/features/publish/use-publish-flow.test.tsx delete mode 100644 apps/builder/app/builder/features/publish/use-publish-flow.tsx delete mode 100644 apps/builder/app/builder/features/publish/use-publish-progress.tsx delete mode 100644 apps/builder/app/builder/features/publish/use-session-publishes.test.tsx delete mode 100644 apps/builder/app/builder/features/publish/use-session-publishes.tsx diff --git a/apps/builder/app/builder/features/publish/constants.ts b/apps/builder/app/builder/features/publish/constants.ts index f991dfe569..0c1c67a6d3 100644 --- a/apps/builder/app/builder/features/publish/constants.ts +++ b/apps/builder/app/builder/features/publish/constants.ts @@ -1,6 +1,6 @@ import { cssVar } from "@webstudio-is/design-system"; import { AlertIcon, CheckCircleIcon, SpinnerIcon } from "@webstudio-is/icons"; -import type { SessionPublish } from "./use-session-publishes"; +import type { SessionPublish } from "./session-publishes"; export const publishLogStatus = { pending: { diff --git a/apps/builder/app/builder/features/publish/diagnostics-utils.ts b/apps/builder/app/builder/features/publish/diagnostics-utils.ts index 16fa174d2a..d4ce058cfd 100644 --- a/apps/builder/app/builder/features/publish/diagnostics-utils.ts +++ b/apps/builder/app/builder/features/publish/diagnostics-utils.ts @@ -1,5 +1,5 @@ import type { DiagnosticFinding } from "./diagnostics"; -import type { SessionPublish } from "./use-session-publishes"; +import type { SessionPublish } from "./session-publishes"; import { publishLogStatus } from "./constants"; export const getDiagnosticsReport = ({ diff --git a/apps/builder/app/builder/features/publish/diagnostics.test.tsx b/apps/builder/app/builder/features/publish/diagnostics.test.tsx index a4774ba796..9f686a0557 100644 --- a/apps/builder/app/builder/features/publish/diagnostics.test.tsx +++ b/apps/builder/app/builder/features/publish/diagnostics.test.tsx @@ -8,7 +8,7 @@ import { PublishValidationBanner, type DiagnosticFinding, } from "./diagnostics"; -import type { SessionPublish } from "./use-session-publishes"; +import type { SessionPublish } from "./session-publishes"; let root: Root | undefined; let container: HTMLDivElement | undefined; diff --git a/apps/builder/app/builder/features/publish/diagnostics.tsx b/apps/builder/app/builder/features/publish/diagnostics.tsx index e6f0caad7b..a77030ba86 100644 --- a/apps/builder/app/builder/features/publish/diagnostics.tsx +++ b/apps/builder/app/builder/features/publish/diagnostics.tsx @@ -26,8 +26,8 @@ import { } from "@webstudio-is/design-system"; import { CopyIcon } from "@webstudio-is/icons"; import { CopyToClipboard } from "~/shared/copy-to-clipboard"; -import type { SessionPublish } from "./use-session-publishes"; -import { getPublishDuration } from "./use-session-publishes"; +import type { SessionPublish } from "./session-publishes"; +import { getPublishDuration } from "./session-publishes"; import { publishLogStatus } from "./constants"; export type DiagnosticFinding = { diff --git a/apps/builder/app/builder/features/publish/domain-status-button.tsx b/apps/builder/app/builder/features/publish/domain-status-button.tsx index d2b54b2acb..857adf9903 100644 --- a/apps/builder/app/builder/features/publish/domain-status-button.tsx +++ b/apps/builder/app/builder/features/publish/domain-status-button.tsx @@ -2,7 +2,7 @@ import type { ReactNode } from "react"; import { IconButton, Tooltip } from "@webstudio-is/design-system"; import type { AlertIcon } from "@webstudio-is/icons"; import { publishLogStatus } from "./constants"; -import type { SessionPublish } from "./use-session-publishes"; +import type { SessionPublish } from "./session-publishes"; export const DomainStatusButton = ({ domain, diff --git a/apps/builder/app/builder/features/publish/domains.test.tsx b/apps/builder/app/builder/features/publish/domains.test.tsx index 3a10a4a56a..d7fa0e9084 100644 --- a/apps/builder/app/builder/features/publish/domains.test.tsx +++ b/apps/builder/app/builder/features/publish/domains.test.tsx @@ -4,7 +4,7 @@ import { afterEach, expect, test, vi } from "vitest"; import { TooltipProvider } from "@webstudio-is/design-system"; import { __testing__, type Domain } from "./domains"; import { PENDING_TIMEOUT } from "./publish-status"; -import type { SessionPublish } from "./use-session-publishes"; +import type { SessionPublish } from "./session-publishes"; const { StatusIcon } = __testing__; let root: Root | undefined; diff --git a/apps/builder/app/builder/features/publish/domains.tsx b/apps/builder/app/builder/features/publish/domains.tsx index 252645b795..55c3e8186b 100644 --- a/apps/builder/app/builder/features/publish/domains.tsx +++ b/apps/builder/app/builder/features/publish/domains.tsx @@ -43,7 +43,7 @@ import { CopyToClipboard } from "~/shared/copy-to-clipboard"; import { getPublishStatusDisplay } from "./publish-status"; import { $currentSystem } from "~/shared/system"; import { getPublishUrl } from "./publish-url"; -import type { SessionPublish } from "./use-session-publishes"; +import type { SessionPublish } from "./session-publishes"; import { DomainStatusButton } from "./domain-status-button"; export type Domain = Project["domainsVirtual"][number]; diff --git a/apps/builder/app/builder/features/publish/publish-actions.test.tsx b/apps/builder/app/builder/features/publish/publish-actions.test.tsx index 1d4fc47d28..d82837edbe 100644 --- a/apps/builder/app/builder/features/publish/publish-actions.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-actions.test.tsx @@ -2,8 +2,8 @@ import { createRef, useState } from "react"; import { createRoot, type Root } from "react-dom/client"; import { act } from "react-dom/test-utils"; import { afterEach, expect, test, vi } from "vitest"; -import { TooltipProvider, toast } from "@webstudio-is/design-system"; -import { PublishActions, usePublishValidationState } from "./publish-actions"; +import { TooltipProvider } from "@webstudio-is/design-system"; +import { PublishActions } from "./publish-actions"; let root: Root | undefined; let container: HTMLDivElement | undefined; @@ -74,146 +74,6 @@ test("shows the successful validation state in the action", () => { expect(validate).toBeEnabled(); }); -test("clears the validation result when the publish popover closes", async () => { - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const { validationState, update, reset } = usePublishValidationState( - isOpen ? "publish" : "none" - ); - - return ( - - {isOpen && ( - ()} - onValidate={async () => { - update("passed"); - }} - onPublish={vi.fn()} - /> - )} - - {isOpen === false && ( - - )} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - const [validate, , close] = Array.from( - container.querySelectorAll("button") - ); - await act(async () => validate.click()); - expect(validate.textContent).toBe("Validated"); - - act(() => close.click()); - const reopen = - container.querySelector("button:last-child"); - act(() => reopen?.click()); - - const [reopenedValidate] = Array.from( - container.querySelectorAll("button") - ); - expect(reopenedValidate.textContent).toBe("Validate"); - expect(reopenedValidate.querySelector("svg")).toBeNull(); -}); - -test.each([ - { destination: "none" as const, expectedToasts: 1 }, - { destination: "none" as const, reopen: true, expectedToasts: 0 }, - { destination: "export" as const, expectedToasts: 1 }, - { destination: "publish" as const, expectedToasts: 0 }, -])( - "reports validation success after switching to $destination (reopen: $reopen)", - async ({ destination, reopen, expectedToasts }) => { - const successToast = vi - .spyOn(toast, "success") - .mockImplementation(() => ""); - let finishValidation: () => void = () => {}; - const validation = new Promise((resolve) => { - finishValidation = resolve; - }); - - const Harness = () => { - const [dialog, setDialog] = useState<"none" | "publish" | "export">( - "publish" - ); - const { validationState, update } = usePublishValidationState(dialog); - return ( - - {dialog === "publish" && ( - ()} - onValidate={async () => { - await validation; - update("passed"); - }} - onPublish={vi.fn()} - /> - )} - - - {validationState} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [validate, , switchDialog, reopenDialog] = - container.querySelectorAll("button"); - act(() => validate.click()); - act(() => switchDialog.click()); - if (reopen) { - act(() => reopenDialog.click()); - } - await act(async () => { - finishValidation(); - await validation; - }); - - expect(successToast).toHaveBeenCalledTimes(expectedToasts); - expect(container.querySelector("output")?.textContent).toBe( - destination === "publish" || reopen ? "passed" : "idle" - ); - } -); - test("shows the countdown and disables actions during publish progress", () => { const [validate, publish] = render( "idle", diff --git a/apps/builder/app/builder/features/publish/publish-actions.tsx b/apps/builder/app/builder/features/publish/publish-actions.tsx index 534d3a2068..bc927ed032 100644 --- a/apps/builder/app/builder/features/publish/publish-actions.tsx +++ b/apps/builder/app/builder/features/publish/publish-actions.tsx @@ -1,42 +1,9 @@ -import { useCallback, useEffect, useRef, useState, type Ref } from "react"; -import { Button, Flex, Tooltip, toast } from "@webstudio-is/design-system"; +import { useState, type Ref } from "react"; +import { Button, Flex, Tooltip } from "@webstudio-is/design-system"; import { CheckCircleIcon } from "@webstudio-is/icons"; export type PublishValidationState = "idle" | "passed"; -export const usePublishValidationState = ( - dialog: "none" | "publish" | "export" -) => { - const [validationState, setValidationState] = - useState("idle"); - const dialogRef = useRef(dialog); - dialogRef.current = dialog; - - const reset = useCallback(() => { - setValidationState("idle"); - }, []); - - const update = useCallback((state: PublishValidationState) => { - if (state === "passed" && dialogRef.current !== "publish") { - toast.success("Validation passed. Ready to publish.", { - duration: Number.POSITIVE_INFINITY, - }); - return; - } - if (dialogRef.current === "publish") { - setValidationState(state); - } - }, []); - - useEffect(() => { - if (dialog !== "publish") { - reset(); - } - }, [dialog, reset]); - - return { validationState, update, reset }; -}; - export const PublishActions = ({ validationState, validateDisabled, diff --git a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx index 363f97224b..3fb6292147 100644 --- a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx @@ -1,4 +1,5 @@ import { act } from "react-dom/test-utils"; +import { userEvent } from "@vitest/browser/context"; import { createRoot, type Root } from "react-dom/client"; import { afterAll, @@ -29,6 +30,7 @@ const requests: Array<{ path: string; input: unknown }> = []; let publishResponse: unknown = { success: false, error: "Publish blocked" }; let jobStatus: "failed" | "success" = "failed"; let didPublish = false; +const logCursors: Array = []; beforeAll(async () => { Object.defineProperty(Element.prototype, "scrollIntoView", { @@ -62,6 +64,34 @@ beforeAll(async () => { case "/trpc/api.publish.getJob": data = { status: jobStatus, code: "BUILD_FAILED" }; break; + case "/trpc/api.publish.getLog": { + const cursor = (input[String(index)] as { cursor?: number }) + .cursor; + logCursors.push(cursor); + data = { + availability: "available", + startedAt: "2026-11-13T10:00:00.000Z", + completedAt: "2026-11-13T10:00:03.000Z", + log: { + encoding: "base64url", + chunk: btoa( + String.fromCharCode( + ...(cursor === undefined ? [0xe2] : [0x82, 0xac]) + ) + ), + complete: cursor !== undefined, + nextCursor: cursor === undefined ? 1 : undefined, + issues: [ + { + severity: cursor === undefined ? "warning" : "error", + message: + cursor === undefined ? "Early warning" : "Late error", + }, + ], + }, + }; + break; + } case "/trpc/domain.project": data = { success: true, @@ -121,6 +151,11 @@ beforeEach(() => { requests.length = 0; jobStatus = "failed"; didPublish = false; + logCursors.length = 0; + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); }); test("a successful site runner finishes the current publish and retains its report", async () => { @@ -208,9 +243,98 @@ afterEach(() => { root = undefined; resetStores = undefined; document.body.innerHTML = ""; + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); vi.restoreAllMocks(); }); +test("a paid publish loads every log page and hides it after downgrade", async () => { + jobStatus = "success"; + publishResponse = { + success: true, + buildId: "build-1", + logHandle: "log-handle", + findings: [], + }; + stores.$project.set({ + id: "project-1", + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + } as unknown as Project); + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + builderStates.$publishDialog.set("publish"); + resetStores = () => { + stores.$project.set(undefined); + builderStates.$publishDialog.set("none"); + }; + const container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => + root?.render( + + + + ) + ); + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + )!; + if (!domain.checked) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } + const publish = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent === "Publish") + .at(-1)!; + await act(async () => publish.click()); + await act(async () => + vi.waitFor(() => expect(logCursors).toEqual([undefined, 1])) + ); + const report = document.body.querySelector( + 'button[aria-label^="Publish log:"]' + )!; + await act(async () => report.click()); + expect(document.body.textContent).toContain("€"); + const selectTab = async (name: string) => { + const tab = Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((candidate) => candidate.textContent?.startsWith(name)); + expect(tab).toBeDefined(); + await act(async () => userEvent.click(tab!)); + }; + await selectTab("Errors"); + expect(document.body.textContent).toContain("Late error"); + await selectTab("Warnings"); + expect(document.body.textContent).toContain("Early warning"); + await selectTab("Publish"); + + await act(async () => + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }) + ); + expect(document.body.textContent).not.toContain("€"); + expect(document.body.textContent).toContain( + "Upgrade to Pro to view publish logs." + ); +}); + afterAll(() => { vi.unstubAllGlobals(); vi.resetModules(); diff --git a/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx b/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx new file mode 100644 index 0000000000..bd615af808 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx @@ -0,0 +1,761 @@ +import { act } from "react-dom/test-utils"; +import { createRoot, type Root } from "react-dom/client"; +import { userEvent } from "@vitest/browser/context"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, + vi, +} from "vitest"; +import { TooltipProvider, toast } from "@webstudio-is/design-system"; +import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session"; +import type { Project } from "@webstudio-is/project"; +import type { Pages } from "@webstudio-is/sdk"; + +const deferred = () => { + 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 root: Root; +let container: HTMLDivElement; +let PublishButton: typeof import("./publish").PublishButton; +let stores: typeof import("~/shared/sync/data-stores"); +let nanoStates: typeof import("~/shared/nano-states"); +let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog; +let assetBridge: typeof import("~/shared/asset-content-bridge.client"); +let contentSession: ReturnType; + +beforeAll(async () => { + ( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } + ).IS_REACT_ACT_ENVIRONMENT = true; + vi.resetModules(); + vi.stubGlobal("fetch", async (requestInfo: RequestInfo | URL) => { + const path = new URL(String(requestInfo), "http://localhost").pathname; + if (path.includes(",")) { + const results = path + .slice("/trpc/".length) + .split(",") + .map((route) => { + if (route === "domain.project") { + return { + result: { + data: { success: true, project: stores.$project.get() }, + }, + }; + } + if (route === "domain.countTotalDomains") { + return { result: { data: { success: true, data: 0 } } }; + } + if (route === "project.userPublishCount") { + return { result: { data: { success: true, data: 0, limit: 100 } } }; + } + if (route === "api.publish.getLog") { + return { + result: { + data: { + availability: "available", + log: { + encoding: "base64url", + chunk: btoa("older publish output"), + complete: true, + issues: [ + { severity: "error", message: "older build issue" }, + ], + }, + }, + }, + }; + } + throw new Error(`Unexpected request: ${route}`); + }); + return new Response(JSON.stringify(results), { + headers: { "Content-Type": "application/json" }, + }); + } + if (path === "/trpc/domain.publish") { + publishRequests += 1; + return dispatch.promise; + } + if (path === "/trpc/api.publish.getJob") { + return respond({ status: "failed", code: "BUILD_FAILED" }); + } + if (path === "/trpc/api.publish.getLog") { + return respond({ + availability: "available", + log: { + encoding: "base64url", + chunk: btoa("older publish output"), + complete: true, + issues: [{ severity: "error", message: "older build issue" }], + }, + }); + } + if (path === "/trpc/domain.project") { + return respond({ success: true, project: stores.$project.get() }); + } + if (path === "/trpc/domain.countTotalDomains") { + return respond({ success: true, data: 0 }); + } + if (path === "/trpc/project.userPublishCount") { + return respond({ success: true, data: 0, limit: 100 }); + } + if ( + path === "/trpc/api.publish.validate" || + path === "/trpc/build.contentDatabasePublishDiagnostics" + ) { + checkRequests += 1; + try { + const response = (await checks.promise).clone(); + const json = response.json.bind(response); + response.json = async () => { + const result = await json(); + checksRead += 1; + return result; + }; + return response; + } catch (error) { + checksRead += 1; + throw error; + } + } + throw new Error(`Unexpected request: ${path}`); + }); + PublishButton = (await import("./publish")).PublishButton; + stores = await import("~/shared/sync/data-stores"); + nanoStates = await import("~/shared/nano-states"); + publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog; + assetBridge = await import("~/shared/asset-content-bridge.client"); + (await import("~/shared/csrf.client")).updateCsrfToken("test-token"); +}); + +beforeEach(() => { + contentSession = createAssetContentSession({ + authorize: () => true, + repository: { + readContent: async () => { + throw new Error("No assets in this project"); + }, + updateContent: async () => { + throw new Error("No assets in this project"); + }, + }, + }); + assetBridge.__testing__.initBridge( + assetBridge.createAssetContentBridge({ + origin: location.origin, + request: fetch, + authorize: () => true, + requireReload: () => {}, + getContentSession: () => contentSession, + }) + ); + checks = deferred(); + dispatch = deferred(); + checkRequests = 0; + checksRead = 0; + publishRequests = 0; + vi.spyOn(toast, "error").mockImplementation(() => ""); + stores.$project.set({ + id: "project", + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + } as unknown as Project); + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); + publishDialog.set("none"); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(async () => { + act(() => root.unmount()); + checks.resolve(respond({ mdxErrors: [], mdxOmissions: [] })); + dispatch.resolve(respond({ success: false, error: "cleanup" })); + await act(async () => + vi.waitFor(() => expect(checksRead).toBe(checkRequests)) + ); + container.remove(); + assetBridge.__testing__.clearBridge(); + contentSession.dispose(); + stores.$project.set(undefined); + stores.$pages.set(undefined); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); + publishDialog.set("none"); + vi.restoreAllMocks(); +}); + +afterAll(() => vi.unstubAllGlobals()); + +const mount = async (target: "site" | "static") => { + publishDialog.set(target === "site" ? "publish" : "export"); + await act(async () => + root.render( + + + + ) + ); + if (target === "static") { + const destination = document.body.querySelector( + 'button[role="combobox"]' + ); + await act(async () => + destination?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ) + ); + const staticOption = Array.from( + document.body.querySelectorAll('[role="option"]') + ).find((option) => option.textContent?.trim() === "Static"); + await act(async () => staticOption?.click()); + return; + } + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + ); + if (domain?.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } +}; + +const clickPublish = async (target: "site" | "static", expected = 1) => { + const label = + target === "site" ? "Publish" : "Build and download static site"; + const button = Array.from( + document.body.querySelectorAll("button") + ) + .filter((candidate) => candidate.textContent?.trim() === label) + .at(-1); + expect(button).toBeDefined(); + await act(async () => vi.waitFor(() => expect(button?.disabled).toBe(false))); + await act(async () => button?.click()); + await act(async () => + vi.waitFor(() => + expect([checkRequests, publishRequests]).toEqual([expected, expected]) + ) + ); +}; + +const completeChecks = async (fail: boolean) => { + await act(async () => { + if (fail) { + checks.reject(new Error("check failure")); + } else { + checks.resolve( + respond({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: false, + mdxErrors: [], + mdxOmissions: [{ filename: "check.mdx", templateName: "missing" }], + }) + ); + } + await checks.promise.catch(() => {}); + await vi.waitFor(() => expect(checksRead).toBe(checkRequests)); + }); +}; + +const openErrors = async (target: "site" | "static") => { + if (target === "site") { + const issues = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See issues"); + const status = document.body.querySelector( + 'button[aria-label^="Publish log:"]' + ); + expect(issues ?? status).toBeDefined(); + if (issues !== undefined) { + await act(async () => userEvent.click(issues)); + } else { + await act(async () => status?.click()); + } + } + const findErrors = () => + Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((tab) => tab.textContent?.startsWith("Errors")); + await act(async () => vi.waitFor(() => expect(findErrors()).toBeDefined())); + const errors = findErrors(); + expect(errors).toBeDefined(); + await act(async () => userEvent.click(errors!)); + return document.body.querySelector( + '[role="tabpanel"][data-state="active"]' + ); +}; + +const closeReport = async () => { + const close = document.body.querySelector( + '[role="dialog"] button[aria-label="Close"]' + ); + expect(close).toBeDefined(); + await act(async () => close?.click()); + await vi.waitFor(async () => { + await act(async () => {}); + expect(document.body.querySelector('[role="dialog"]')).toBeNull(); + }); +}; + +test.each([ + ["site", "checks-first", false], + ["site", "checks-first", true], + ["site", "server-first", false], + ["site", "server-first", true], + ["static", "checks-first", false], + ["static", "checks-first", true], + ["static", "server-first", false], + ["static", "server-first", true], +] as const)( + "%s audit rejection remains visible with %s (failed checks: %s)", + async (target, order, failChecks) => { + await mount(target); + await clickPublish(target); + if (order === "checks-first") { + await completeChecks(failChecks); + } + await act(async () => { + dispatch.resolve( + respond({ + success: false, + auditFindings: [{ severity: "error", message: "server rejection" }], + }) + ); + await dispatch.promise; + }); + const errors = await openErrors(target); + expect(errors?.textContent).toContain("server rejection"); + if (order === "server-first") { + await completeChecks(failChecks); + } + if (failChecks) { + expect(errors?.textContent?.includes("check failure")).toBe( + order === "checks-first" + ); + } else { + expect( + Array.from(document.body.querySelectorAll('[role="tab"]')).some((tab) => + tab.textContent?.startsWith("Warnings") + ) + ).toBe(order === "checks-first"); + } + } +); + +test("closing Publish clears a completed validation", async () => { + stores.$pages.set({ + pages: new Map(), + folders: new Map(), + } as unknown as Pages); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + await mount("site"); + const validate = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent?.trim() === "Validate") + .at(-1); + expect(validate).toBeDefined(); + await act(async () => validate?.click()); + await act(async () => vi.waitFor(() => expect(checkRequests).toBe(1))); + await act(async () => { + checks.resolve( + respond({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }) + ); + await checks.promise; + await vi.waitFor(() => expect(checksRead).toBe(1)); + }); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "Validated" + ) + ).toBe(true); + await act(async () => publishDialog.set("none")); + await act(async () => publishDialog.set("publish")); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "Validate" + ) + ).toBe(true); +}); + +test.each([ + ["request", "checks-first"], + ["request", "server-first"], + ["transport", "checks-first"], + ["transport", "server-first"], +] as const)( + "static %s failure remains visible with %s checks", + async (failure, order) => { + await mount("static"); + await clickPublish("static"); + if (order === "checks-first") { + await completeChecks(false); + } + const message = `${failure} failure`; + await act(async () => { + if (failure === "request") { + dispatch.resolve(respond({ success: false, error: message })); + } else { + dispatch.reject(new Error(message)); + } + await dispatch.promise.catch(() => {}); + }); + if (order === "server-first") { + await completeChecks(false); + } + const status = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + await act(async () => status?.click()); + const errors = await openErrors("static"); + expect(errors?.textContent).toContain(message); + } +); + +test.each(["checks-first", "server-first"] as const)( + "site transport failure remains visible with %s checks", + async (order) => { + await mount("site"); + await clickPublish("site"); + if (order === "checks-first") { + await completeChecks(false); + } + await act(async () => { + dispatch.reject(new Error("site transport failure")); + await dispatch.promise.catch(() => {}); + }); + if (order === "server-first") { + await completeChecks(false); + } + const errors = await openErrors("site"); + expect(errors?.textContent).toContain("site transport failure"); + } +); + +test.each(["request", "transport"] as const)( + "a static %s failure does not replace an earlier site failure", + async (failure) => { + await mount("site"); + await clickPublish("site"); + await completeChecks(false); + await act(async () => { + dispatch.resolve(respond({ success: false, error: "site rejection" })); + await dispatch.promise; + }); + const originalSiteErrors = await openErrors("site"); + expect(originalSiteErrors?.textContent).toContain("site rejection"); + await closeReport(); + checks = deferred(); + dispatch = deferred(); + await mount("static"); + await clickPublish("static", 2); + await completeChecks(false); + await act(async () => { + if (failure === "request") { + dispatch.resolve( + respond({ success: false, error: "static rejection" }) + ); + } else { + dispatch.reject(new Error("static transport")); + } + await dispatch.promise.catch(() => {}); + }); + await act(async () => + vi.waitFor(() => + expect(toast.error).toHaveBeenCalledWith( + failure === "request" ? "static rejection" : "static transport" + ) + ) + ); + const staticStatus = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + expect(staticStatus).toBeDefined(); + await act(async () => staticStatus?.click()); + const staticErrors = await openErrors("static"); + expect(staticErrors?.textContent).toContain( + failure === "request" ? "static rejection" : "static transport" + ); + await closeReport(); + await mount("site"); + const siteErrors = await openErrors("site"); + expect(siteErrors?.textContent).toContain("site rejection"); + expect(siteErrors?.textContent).not.toContain("static rejection"); + expect(siteErrors?.textContent).not.toContain("static transport"); + } +); + +test("a site transport error appears only for its attempted domain", async () => { + stores.$project.set({ + id: "project", + domain: "example", + domainsVirtual: [ + { + domain: "other.example", + projectId: "project", + domainId: "other-id", + status: "ACTIVE", + verified: true, + updatedAt: new Date().toISOString(), + latestBuildVirtual: null, + }, + ], + latestStaticBuild: null, + } as unknown as Project); + await mount("site"); + await clickPublish("site"); + await completeChecks(false); + await act(async () => { + dispatch.reject(new Error("scoped transport failure")); + await dispatch.promise.catch(() => {}); + }); + const otherDomainStatus = document.body.querySelector( + 'button[aria-label="Publish log: other.example"]' + ); + expect(otherDomainStatus).toBeDefined(); + await act(async () => otherDomainStatus?.click()); + expect( + document.body.querySelector('[role="dialog"]')?.textContent + ).not.toContain("scoped transport failure"); + await closeReport(); + await mount("site"); + const attemptedDomainStatus = Array.from( + document.body.querySelectorAll( + 'button[aria-label^="Publish log:"]' + ) + ).find( + (button) => + button.getAttribute("aria-label") !== "Publish log: other.example" + ); + expect(attemptedDomainStatus).toBeDefined(); + await act(async () => attemptedDomainStatus?.click()); + expect(document.body.querySelector('[role="dialog"]')?.textContent).toContain( + "scoped transport failure" + ); +}); + +test.each(["site", "static"] as const)( + "%s check failure has one notice while Publish is open", + async (target) => { + await mount(target); + await clickPublish(target); + publishDialog.set("publish"); + await completeChecks(true); + expect(toast.error).toHaveBeenCalledTimes(target === "site" ? 0 : 1); + } +); + +test("an accepted site failure links to its own publish log", async () => { + await mount("site"); + await clickPublish("site"); + await completeChecks(false); + await act(async () => { + dispatch.resolve( + respond({ + success: true, + buildId: "accepted-build", + logHandle: "handle", + findings: [], + }) + ); + await dispatch.promise; + }); + const errors = await openErrors("site"); + const showLogs = Array.from( + errors?.querySelectorAll("button") ?? [] + ).find((button) => button.textContent?.trim() === "show logs"); + expect(showLogs).toBeDefined(); + await act(async () => showLogs?.click()); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); +}); + +test.each([ + ["none", false, 1], + ["none", true, 0], + ["export", false, 1], + ["publish", false, 0], +] as const)( + "validation completed after switching to %s (reopened: %s)", + async (destination, reopen, expectedToasts) => { + const successToast = vi + .spyOn(toast, "success") + .mockImplementation(() => ""); + stores.$pages.set({ + pages: new Map(), + folders: new Map(), + } as unknown as Pages); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + await mount("site"); + const validate = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent?.trim() === "Validate") + .at(-1); + expect(validate).toBeDefined(); + await act(async () => + vi.waitFor(() => expect(validate?.disabled).toBe(false)) + ); + expect( + new FormData(validate?.closest("form")!).getAll("domainToPublish[]") + ).toEqual(["example"]); + await act(async () => validate?.click()); + expect(validate?.dataset.state).toBe("pending"); + await act(async () => vi.waitFor(() => expect(checkRequests).toBe(1))); + await act(async () => publishDialog.set(destination)); + if (reopen) { + expect( + document.body.querySelector('input[name="domainToPublish[]"]') + ).toBeNull(); + await act(async () => publishDialog.set("publish")); + } + await act(async () => { + checks.resolve( + respond({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }) + ); + await checks.promise; + await vi.waitFor(() => expect(checksRead).toBe(1)); + }); + expect(successToast).toHaveBeenCalledTimes(expectedToasts); + if (destination === "publish" || reopen) { + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "Validated" + ) + ).toBe(true); + } else { + await act(async () => publishDialog.set("publish")); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "Validate" + ) + ).toBe(true); + } + } +); + +test.each([ + ["site", "request"], + ["site", "transport"], + ["site", "audit"], + ["static", "request"], + ["static", "transport"], + ["static", "audit"], +] as const)( + "a newer %s %s rejection does not show an older build issue", + async (target, failure) => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + await mount(target); + await clickPublish(target); + await completeChecks(false); + await act(async () => { + dispatch.resolve( + respond({ + success: true, + buildId: "older-build", + logHandle: "older-handle", + findings: [], + ...(target === "static" ? { name: "site.zip" } : {}), + }) + ); + await dispatch.promise; + }); + await act(async () => + vi.waitFor(() => + expect( + document.body.querySelector( + 'button[aria-label^="Publish log:"]' + ) + ).not.toBeNull() + ) + ); + checks = deferred(); + dispatch = deferred(); + await mount(target); + await clickPublish(target, 2); + const message = `new ${failure} failure`; + await act(async () => { + if (failure === "transport") { + dispatch.reject(new Error(message)); + } else { + dispatch.resolve( + respond( + failure === "audit" + ? { + success: false, + auditFindings: [{ severity: "error", message }], + } + : { success: false, error: message } + ) + ); + } + await dispatch.promise.catch(() => {}); + }); + await completeChecks(false); + if (target === "static") { + const status = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + await act(async () => status?.click()); + } + const errors = await openErrors(target); + expect(errors?.textContent).toContain(message); + expect(errors?.textContent).not.toContain("older build issue"); + } +); diff --git a/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx b/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx new file mode 100644 index 0000000000..980bbbcca8 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx @@ -0,0 +1,807 @@ +import { act } from "react-dom/test-utils"; +import { createRoot, type Root } from "react-dom/client"; +import { userEvent } from "@vitest/browser/context"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, + vi, +} from "vitest"; +import { TooltipProvider, toast } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session"; + +const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; +const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; + +const deferred = () => { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +}; + +let root: Root | undefined; +let container: HTMLDivElement; +let PublishButton: typeof import("./publish").PublishButton; +let stores: typeof import("~/shared/sync/data-stores"); +let nanoStates: typeof import("~/shared/nano-states"); +let dialog: typeof import("~/builder/shared/nano-states").$publishDialog; +let assetBridge: typeof import("~/shared/asset-content-bridge.client"); +let contentSession: ReturnType; +let initialPlan: ReturnType; +let project: Project; +let publish: () => Promise; +let refresh: () => Promise; +let validate: () => Promise; +let job: () => Promise; +const requests: { route: string; input: unknown }[] = []; +const checks = { + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, +}; +const warningChecks = { ...checks, cssValid: false }; +const makeProject = ( + id = "project", + build?: { buildId: string; publishStatus: string } +) => + ({ + id, + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + latestBuildVirtual: + build === undefined + ? null + : { + ...build, + domain: "example", + createdAt: new Date().toISOString(), + }, + }) as unknown as Project; + +beforeAll(async () => { + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true; + vi.resetModules(); + vi.stubGlobal( + "fetch", + async (info: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(info), location.href); + const inputs = JSON.parse( + init?.body === undefined + ? (url.searchParams.get("input") ?? "{}") + : String(init.body) + ); + const results = await Promise.all( + url.pathname + .slice("/trpc/".length) + .split(",") + .map(async (route, index) => { + requests.push({ route, input: inputs[String(index)] }); + let data: unknown; + switch (route) { + case "domain.project": + data = await refresh(); + break; + case "domain.publish": + data = await publish(); + break; + case "api.publish.validate": + case "build.contentDatabasePublishDiagnostics": + data = await validate(); + break; + case "api.publish.getJob": + data = await job(); + break; + case "domain.countTotalDomains": + data = { success: true, data: 0 }; + break; + case "project.userPublishCount": + data = { success: true, data: 0, limit: 100 }; + break; + default: + throw new Error(`Unexpected request: ${route}`); + } + return { result: { data } }; + }) + ); + return new Response(JSON.stringify(results), { + headers: { "Content-Type": "application/json" }, + }); + } + ); + PublishButton = (await import("./publish")).PublishButton; + stores = await import("~/shared/sync/data-stores"); + nanoStates = await import("~/shared/nano-states"); + initialPlan = nanoStates.$planFeatures.get(); + dialog = (await import("~/builder/shared/nano-states")).$publishDialog; + assetBridge = await import("~/shared/asset-content-bridge.client"); + (await import("~/shared/csrf.client")).updateCsrfToken("test-token"); +}); + +beforeEach(() => { + contentSession = createAssetContentSession({ + authorize: () => true, + repository: { + readContent: async () => { + throw new Error("No assets in this project"); + }, + updateContent: async () => { + throw new Error("No assets in this project"); + }, + }, + }); + assetBridge.__testing__.initBridge( + assetBridge.createAssetContentBridge({ + origin: location.origin, + request: fetch, + authorize: () => true, + requireReload: () => {}, + getContentSession: () => contentSession, + }) + ); + project = makeProject(); + publish = async () => ({ success: false, error: "request rejection" }); + refresh = async () => ({ success: true, project }); + validate = async () => checks; + job = async () => ({ status: "failed", code: "runner_failed" }); + requests.length = 0; + stores.$project.set(project); + stores.$pages.set({ + homePageId: "home", + rootFolderId: "root", + pages: new Map(), + folders: new Map(), + }); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + nanoStates.$planFeatures.set({ + ...initialPlan, + allowPublishLogs: false, + }); + dialog.set("publish"); + vi.spyOn(toast, "error").mockImplementation(() => ""); + vi.spyOn(toast, "success").mockImplementation(() => ""); + vi.spyOn(console, "error").mockImplementation(() => {}); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(async () => { + act(() => root?.unmount()); + root = undefined; + container.remove(); + dialog.set("none"); + stores.$project.set(undefined); + stores.$pages.set(undefined); + assetBridge.__testing__.clearBridge(); + contentSession.dispose(); + nanoStates.$planFeatures.set(initialPlan); + nanoStates.$authPermit.set("view"); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +afterAll(() => { + vi.unstubAllGlobals(); + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment; +}); + +const button = (label: string) => + Array.from(document.body.querySelectorAll("button")) + .filter((candidate) => { + const copy = candidate.cloneNode(true) as HTMLElement; + copy.querySelectorAll("svg").forEach((icon) => icon.remove()); + return copy.textContent?.trim() === label; + }) + .at(-1); +const click = async (label: string) => { + const target = button(label); + expect(target).toBeDefined(); + expect(target?.disabled).toBe(false); + await act(async () => target?.click()); +}; +const mount = async (projectId = "project") => { + await act(async () => + root?.render( + + + + ) + ); + if (vi.isFakeTimers()) { + await act(async () => vi.advanceTimersByTimeAsync(10)); + } + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + ); + if (domain?.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } +}; +const toggle = async (value: "publish" | "none" | "export") => { + if (value === "none") { + await act(async () => + document.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }) + ) + ); + } else if (value === "publish" && dialog.get() === "none") { + await act(async () => + container.querySelector("button")?.click() + ); + } else { + await act(async () => dialog.set(value)); + } + if (vi.isFakeTimers()) { + await act(async () => vi.advanceTimersByTimeAsync(20)); + } + if (value === "publish") { + const domains = Array.from( + document.body.querySelectorAll( + 'input[name="domainToPublish[]"]' + ) + ); + if (domains.length > 0 && domains.every((domain) => !domain.checked)) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } + } +}; +const waitFor = async (check: () => void) => { + await vi.waitFor(async () => { + await act(async () => {}); + check(); + }); +}; +const banner = () => button("See issues")?.parentElement; +const accept = () => ({ + success: true, + buildId: "accepted", + logHandle: "handle", + findings: [], +}); +const openReport = async (tab: "Errors" | "Warnings") => { + await click("See issues"); + await waitFor(() => + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull() + ); + const target = Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((item) => item.textContent?.startsWith(tab)); + expect(target).toBeDefined(); + await act(async () => userEvent.click(target!)); + const report = document.body.querySelector( + '[role="tabpanel"][data-state="active"]' + ); + expect(report).not.toBeNull(); + return report!; +}; + +test.each(["open", "closed", "reopened"] as const)( + "a transport failure uses the current %s panel without duplicate notices", + async (state) => { + const response = deferred(); + publish = () => response.promise; + await mount(); + await click("Publish"); + await waitFor(() => + expect(requests.some(({ route }) => route === "domain.publish")).toBe( + true + ) + ); + if (state !== "open") { + await toggle("none"); + } + if (state === "reopened") { + await toggle("publish"); + } + await act(async () => response.reject(new Error("transport failure"))); + await waitFor(() => + expect( + state === "closed" ? toast.error : button("See issues") + ).toBeDefined() + ); + if (state === "closed") { + await waitFor(() => expect(toast.error).toHaveBeenCalledOnce()); + await toggle("publish"); + } else { + expect(toast.error).not.toHaveBeenCalled(); + } + await waitFor(() => + expect(banner()?.textContent).toContain("transport failure") + ); + await toggle("none"); + await toggle("publish"); + expect(banner()).toBeDefined(); + } +); + +test("starting validation clears a request failure", async () => { + await mount(); + await click("Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + await click("Validate"); + await waitFor(() => expect(button("Validated")).toBeDefined()); + expect(banner()).toBeUndefined(); +}); + +test.each(["PUBLISHED", "none"] as const)( + "a %s refresh clears a retained status error", + async (status) => { + publish = async () => accept(); + project = makeProject("project", { + buildId: "accepted", + publishStatus: "FAILED", + }); + await mount(); + await click("Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + await toggle("none"); + await toggle("publish"); + expect(banner()).toBeDefined(); + project = + status === "none" + ? makeProject() + : makeProject("project", { + buildId: "accepted", + publishStatus: status, + }); + await toggle("none"); + await toggle("publish"); + await waitFor(() => expect(banner()).toBeUndefined()); + } +); + +test.each(["PUBLISHED", "none"] as const)( + "a %s refresh preserves a rejected request error", + async (status) => { + project = + status === "none" + ? makeProject() + : makeProject("project", { buildId: "old", publishStatus: status }); + await mount(); + await click("Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + await toggle("none"); + await toggle("publish"); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.project").length + ).toBeGreaterThan(1) + ); + expect(banner()?.textContent).toContain("request rejection"); + } +); + +test.each(["PUBLISHED", "FAILED"] as const)( + "a recovered %s build replaces a lost response only when the build changes", + async (status) => { + project = makeProject("project", { + buildId: "old", + publishStatus: "PUBLISHED", + }); + publish = async () => { + throw new Error("transport failure"); + }; + await mount(); + await click("Publish"); + await waitFor(() => + expect(banner()?.textContent).toContain("transport failure") + ); + await toggle("none"); + await toggle("publish"); + expect(banner()?.textContent).toContain("transport failure"); + project = makeProject("project", { buildId: "new", publishStatus: status }); + await toggle("none"); + await toggle("publish"); + await waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new") + ); + if (status === "PUBLISHED") { + expect(banner()).toBeUndefined(); + } else { + expect(banner()).toBeDefined(); + expect(banner()?.textContent).not.toContain("transport failure"); + } + } +); + +test("a recovered pending build keeps polling after the popover closes", async () => { + vi.useFakeTimers(); + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PENDING", + }); + await mount(); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.project") + ).toHaveLength(2) + ); + await act(async () => vi.advanceTimersByTimeAsync(10)); + await toggle("none"); + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PUBLISHED", + }); + await act(async () => vi.advanceTimersByTimeAsync(15_100)); + expect(toast.success).toHaveBeenCalledOnce(); +}); + +test("an older recovered poll cannot replace a newer popover refresh", async () => { + const stale = deferred(); + let refreshes = 0; + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PENDING", + }); + refresh = async () => + ++refreshes === 2 ? stale.promise : { success: true, project }; + await mount(); + await waitFor(() => expect(refreshes).toBe(2)); + project = makeProject("project", { + buildId: "new", + publishStatus: "PUBLISHED", + }); + await toggle("none"); + await toggle("publish"); + await waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new") + ); + await act(async () => + stale.resolve({ + success: true, + project: makeProject("project", { + buildId: "old", + publishStatus: "PUBLISHED", + }), + }) + ); + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new"); +}); + +test("an old status request cannot update a remounted copy of the same project", async () => { + const stale = deferred(); + let refreshes = 0; + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PENDING", + }); + refresh = async () => + ++refreshes === 2 ? stale.promise : { success: true, project }; + await mount(); + await waitFor(() => expect(refreshes).toBe(2)); + act(() => root?.unmount()); + project = makeProject("other"); + stores.$project.set(project); + project = makeProject("project", { + buildId: "new", + publishStatus: "PUBLISHED", + }); + stores.$project.set(project); + root = createRoot(container); + await mount(); + await act(async () => + stale.resolve({ + success: true, + project: makeProject("project", { + buildId: "old", + publishStatus: "PUBLISHED", + }), + }) + ); + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new"); + expect(toast.success).not.toHaveBeenCalled(); +}); + +test.each(["success", "transport"] as const)( + "an old project's %s response cannot finish a new project's publish", + async (outcome) => { + const old = deferred(); + const current = deferred(); + let publishes = 0; + publish = () => (++publishes === 1 ? old.promise : current.promise); + await mount(); + await click("Publish"); + await waitFor(() => expect(publishes).toBe(1)); + project = makeProject("new-project"); + await act(async () => stores.$project.set(project)); + await mount("new-project"); + await click("Publish"); + await waitFor(() => expect(publishes).toBe(2)); + await act(async () => { + if (outcome === "success") { + old.resolve(accept()); + } else { + old.reject(new Error("old failure")); + } + }); + expect(button("Publishing (60s)")?.disabled).toBe(true); + expect(toast.error).not.toHaveBeenCalled(); + expect(toast.success).not.toHaveBeenCalled(); + await act(async () => + current.resolve({ success: false, error: "current failure" }) + ); + await waitFor(() => expect(banner()).toBeDefined()); + } +); + +test("closing publish hides its countdown while polling continues to completion", async () => { + vi.useFakeTimers(); + const pending = deferred(); + publish = async () => accept(); + job = () => pending.promise; + await mount(); + await click("Publish"); + await waitFor(() => + expect(requests.some(({ route }) => route === "api.publish.getJob")).toBe( + true + ) + ); + expect(button("Publishing (60s)")?.disabled).toBe(true); + await act(async () => vi.advanceTimersByTimeAsync(10_000)); + expect(button("Publishing (50s)")?.disabled).toBe(true); + await toggle("none"); + await toggle("publish"); + expect(button("Publish")?.disabled).toBe(true); + await toggle("none"); + project = makeProject("project", { + buildId: "accepted", + publishStatus: "PUBLISHED", + }); + await act(async () => pending.resolve({ status: "success" })); + await act(async () => vi.advanceTimersByTimeAsync(100)); + await toggle("publish"); + expect(button("Publish")?.disabled).toBe(false); + expect(button("Publish")?.dataset.state).not.toBe("pending"); + expect(toast.success).toHaveBeenCalledOnce(); +}); + +test.each(["validation", "publish"] as const)( + "%s diagnostics remain available after the popover reopens", + async (action) => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + const response = deferred(); + publish = () => response.promise; + validate = async () => warningChecks; + await mount(); + await click(action === "validation" ? "Validate" : "Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + if (action === "publish") { + await act(async () => + response.resolve({ success: false, error: "request rejection" }) + ); + await waitFor(() => expect(button("Publish")?.disabled).toBe(false)); + } + await toggle("none"); + await toggle("publish"); + expect(banner()).toBeDefined(); + const report = await openReport("Warnings"); + expect(report?.querySelector("button")).not.toBeNull(); + } +); + +test("an older validation cannot replace a newer report", async () => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + const old = deferred(); + let validations = 0; + validate = async () => (++validations === 1 ? old.promise : warningChecks); + await mount(); + await click("Validate"); + await waitFor(() => expect(validations).toBe(1)); + await toggle("none"); + await toggle("publish"); + await click("Validate"); + await waitFor(() => expect(validations).toBe(2)); + await waitFor(() => expect(banner()).toBeDefined()); + await act(async () => old.resolve(checks)); + expect(banner()).toBeDefined(); + expect(button("Validated")).toBeDefined(); + const report = await openReport("Warnings"); + expect(report?.querySelector("button")).not.toBeNull(); +}); + +test("older publish diagnostics cannot replace a newer operation", async () => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + const old = deferred(); + let validations = 0; + validate = async () => (++validations === 1 ? old.promise : warningChecks); + await mount(); + await click("Publish"); + await waitFor(() => expect(button("Publish")?.disabled).toBe(false)); + await click("Validate"); + await waitFor(() => expect(validations).toBe(2)); + await waitFor(() => expect(banner()).toBeDefined()); + await act(async () => old.resolve(checks)); + expect(banner()).toBeDefined(); + const report = await openReport("Warnings"); + expect(report?.querySelector("button")).not.toBeNull(); +}); + +test("reopening restores validated domains and publishes only those domains", async () => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowStagingPublish: true, + }); + nanoStates.$authPermit.set("own"); + project = { + ...makeProject("project", { buildId: "old", publishStatus: "PUBLISHED" }), + domainsVirtual: [ + { + projectId: "project", + domainId: "custom", + domain: "custom.example", + status: "ACTIVE", + verified: true, + latestBuildVirtual: null, + updatedAt: new Date().toISOString(), + }, + ], + } as Project; + stores.$project.set(project); + validate = async () => warningChecks; + await mount(); + const checkboxes = () => + Array.from( + document.body.querySelectorAll('[role="checkbox"]') + ); + expect(checkboxes()).toHaveLength(2); + // The saved build makes staging selected by default. Validate only the custom domain. + await act(async () => checkboxes()[0].click()); + if (checkboxes()[1].getAttribute("aria-checked") === "false") { + await act(async () => checkboxes()[1].click()); + } + await click("Validate"); + await waitFor(() => expect(banner()).toBeDefined()); + await toggle("none"); + await toggle("publish"); + expect(checkboxes().map((item) => item.getAttribute("aria-checked"))).toEqual( + ["false", "true"] + ); + const form = button("Publish")!.closest("form")!; + expect(new FormData(form).getAll("domainToPublish[]")).toEqual([ + "custom.example", + ]); + await click("Publish"); + await waitFor(() => + expect( + requests.find(({ route }) => route === "domain.publish") + ).toBeDefined() + ); + expect( + requests.find(({ route }) => route === "domain.publish")?.input + ).toMatchObject({ domains: ["custom.example"] }); + await waitFor(() => expect(button("Publish")?.disabled).toBe(false)); + await act(async () => checkboxes()[1].click()); + expect(new FormData(form).getAll("domainToPublish[]")).toEqual([]); +}); + +const selectStatic = async () => { + await toggle("export"); + const destination = document.body.querySelector( + 'button[role="combobox"]' + ); + await act(async () => + destination?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ) + ); + const option = Array.from( + document.body.querySelectorAll('[role="option"]') + ).find((item) => item.textContent?.trim() === "Static"); + expect(option).toBeDefined(); + await act(async () => option?.click()); +}; + +test.each(["site", "static"] as const)( + "starting diagnostics for the other target keeps %s findings", + async (first) => { + let target: "site" | "static" = first; + publish = async () => ({ + success: false, + auditFindings: [{ severity: "error", message: `${target} diagnostic` }], + }); + await mount(); + if (first === "static") { + await selectStatic(); + } + await click( + first === "site" ? "Publish" : "Build and download static site" + ); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.publish") + ).toHaveLength(1) + ); + await waitFor(() => { + if (first === "static") { + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull(); + } else { + expect(banner()).toBeDefined(); + expect(button("Publish")?.disabled).toBe(false); + } + }); + if (first === "static") { + // Close the report before returning to the other publish target. + const close = document.body.querySelector( + '[role="dialog"] button[aria-label="Close"]' + ); + expect(close).not.toBeNull(); + await act(async () => close?.click()); + } + target = first === "site" ? "static" : "site"; + if (target === "static") { + await selectStatic(); + } else { + await toggle("publish"); + } + await click( + target === "site" ? "Publish" : "Build and download static site" + ); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.publish") + ).toHaveLength(2) + ); + if (target === "static") { + await waitFor(() => + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull() + ); + await act(async () => + document.body + .querySelector( + '[role="dialog"] button[aria-label="Close"]' + ) + ?.click() + ); + } + if (first === "site") { + await toggle("publish"); + const report = await openReport("Errors"); + expect(report?.textContent).toContain("site diagnostic"); + expect(report?.textContent).not.toContain("static diagnostic"); + } else { + await selectStatic(); + const reportButton = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + expect(reportButton).not.toBeNull(); + await act(async () => reportButton?.click()); + await waitFor(() => + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull() + ); + expect( + document.body.querySelector('[role="tabpanel"][data-state="active"]') + ?.textContent + ).toContain("static diagnostic"); + } + } +); diff --git a/apps/builder/app/builder/features/publish/publish-progress.test.tsx b/apps/builder/app/builder/features/publish/publish-progress.test.tsx index c379af1b3c..178e60918e 100644 --- a/apps/builder/app/builder/features/publish/publish-progress.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-progress.test.tsx @@ -1,128 +1,22 @@ -import { useState } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { act } from "react-dom/test-utils"; import { afterEach, expect, test, vi } from "vitest"; -import { TooltipProvider, toast } from "@webstudio-is/design-system"; +import { toast } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; import { $publishDialog } from "~/builder/shared/nano-states"; import { $project } from "~/shared/sync/data-stores"; -import { __testing__ } from "./use-publish-progress"; -import { DomainCheckbox, domainToPublishName } from "./domain-checkbox"; -import { PublishDiagnosticsDialog } from "./diagnostics"; - -const { - usePublishProgress, +import { waitForPublishStatus, refreshProjectWithRetry, - useManualValidationFindings, fetchAndStoreProject, reportPublishResult, -} = __testing__; - -let root: Root | undefined; -let container: HTMLDivElement | undefined; - -( - globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } -).IS_REACT_ACT_ENVIRONMENT = true; +} from "./publish-progress"; afterEach(() => { - act(() => root?.unmount()); - root = undefined; - container?.remove(); - container = undefined; $publishDialog.set("none"); $project.set(undefined); vi.useRealTimers(); vi.restoreAllMocks(); }); -test("closing publish hides the countdown while polling continues and completion clears pending", async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date("2026-10-20T12:00:00Z")); - $project.set({ id: "project" } as Project); - - let status: "PENDING" | "PUBLISHED" = "PENDING"; - let statusRequests = 0; - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const [completedStatus, setCompletedStatus] = useState(); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && ( - - {progress.isPublishing ? "pending" : "complete"}: - {progress.countdown ?? "no countdown"}:{completedStatus ?? "none"} - - )} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - const [start, close, open] = container.querySelectorAll("button"); - act(() => start.click()); - expect(container.querySelector("output")?.textContent).toBe( - "pending:60:none" - ); - - await act(async () => vi.advanceTimersByTimeAsync(10_000)); - expect(container.querySelector("output")?.textContent).toBe( - "pending:50:none" - ); - - act(() => close.click()); - act(() => open.click()); - expect(container.querySelector("output")?.textContent).toBe( - "pending:no countdown:none" - ); - - act(() => close.click()); - status = "PUBLISHED"; - await act(async () => vi.advanceTimersByTimeAsync(5_000)); - act(() => open.click()); - expect(container.querySelector("output")?.textContent).toBe( - "complete:no countdown:PUBLISHED" - ); - expect(statusRequests).toBe(2); -}); - test("a verified runner failure finishes the existing status wait without a project refresh", async () => { const refresh = vi.fn(async () => undefined); const getJob = vi.fn(async () => ({ @@ -282,33 +176,6 @@ test("reopening resumes a retained pending session even after the Build is publi expect(onPending).toHaveBeenCalledWith(project); }); -test("an old publish completion cannot clear the new project's pending state", async () => { - let finishOld: (() => void) | undefined; - let progress: ReturnType; - const Harness = ({ projectId }: { projectId: string }) => { - progress = usePublishProgress(projectId); - return {progress.isPublishing ? "pending" : "idle"}; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - $project.set({ id: "project-a" } as Project); - act(() => root?.render()); - act(() => - progress.start( - () => - new Promise((resolve) => { - finishOld = resolve; - }) - ) - ); - $project.set({ id: "project-b" } as Project); - act(() => root?.render()); - act(() => progress.start(() => new Promise(() => {}))); - await act(async () => finishOld?.()); - expect(container.querySelector("output")?.textContent).toBe("pending"); -}); - test("reopening stops after three unsuccessful project refreshes and shows the error", async () => { vi.useFakeTimers(); $project.set({ id: "project" } as Project); @@ -333,59 +200,6 @@ test("reopening stops after three unsuccessful project refreshes and shows the e expect(errorToast).toHaveBeenCalledOnce(); }); -test("a recovered pending build keeps polling after the popover closes", async () => { - vi.useFakeTimers(); - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - const successToast = vi.spyOn(toast, "success").mockImplementation(() => ""); - let status: "PENDING" | "PUBLISHED" = "PENDING"; - let pollRequests = 0; - const refreshedProject = () => - ({ - id: "project", - latestBuildVirtual: { - buildId: "recovered", - createdAt: new Date().toISOString(), - publishStatus: status, - }, - }) as Project; - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - await act(async () => container?.querySelector("button")?.click()); - expect(pollRequests).toBe(1); - - $publishDialog.set("none"); - status = "PUBLISHED"; - await act(async () => vi.advanceTimersByTimeAsync(15_000)); - - expect(pollRequests).toBe(2); - expect(successToast).toHaveBeenCalledOnce(); -}); - test("an in-flight status request cannot replace the project after navigation", async () => { const oldProject = { id: "old-project" } as Project; const newProject = { id: "new-project" } as Project; @@ -446,54 +260,6 @@ test("an older popover refresh cannot overwrite a newer result", async () => { expect($project.get()).toBe(currentProject); }); -test("an older recovered poll cannot overwrite a newer popover refresh", async () => { - $project.set({ id: "project" } as Project); - let progress: ReturnType | undefined; - const Harness = () => { - progress = usePublishProgress("project"); - return null; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - let finishOldQuery: (result: { - success: true; - project: Project; - }) => void = () => {}; - const oldQuery = new Promise<{ success: true; project: Project }>( - (resolve) => { - finishOldQuery = resolve; - } - ); - const oldGeneration = progress!.beginPopoverRefresh(); - const polling = progress!.watchPendingPublish( - () => - fetchAndStoreProject({ - projectId: "project", - query: () => oldQuery, - isCurrent: () => progress!.isRefreshCurrent(oldGeneration), - }), - oldGeneration - ); - - const newGeneration = progress!.beginPopoverRefresh(); - const currentProject = { id: "project", domain: "new" } as Project; - await fetchAndStoreProject({ - projectId: "project", - query: async () => ({ success: true, project: currentProject }), - isCurrent: () => progress!.isRefreshCurrent(newGeneration), - }); - finishOldQuery({ - success: true, - project: { id: "project", domain: "old" } as Project, - }); - await polling; - - expect($project.get()).toBe(currentProject); -}); - test("publish polling stops after navigating to another project", async () => { const oldProject = { id: "old-project" } as Project; const newProject = { id: "new-project" } as Project; @@ -520,49 +286,6 @@ test("publish polling stops after navigating to another project", async () => { expect($project.get()).toBe(newProject); }); -test("an old poll cannot update a newly mounted copy of the same project", async () => { - const firstProject = { id: "project" } as Project; - $project.set(firstProject); - let progress: ReturnType | undefined; - const Harness = () => { - progress = usePublishProgress("project"); - return null; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - let finishQuery: (result: { - success: true; - project: Project; - }) => void = () => {}; - const query = new Promise<{ success: true; project: Project }>((resolve) => { - finishQuery = resolve; - }); - const polling = waitForPublishStatus( - () => - fetchAndStoreProject({ - projectId: "project", - isCurrent: progress!.isCurrentProject, - query: () => query, - }), - progress!.isCurrentProject - ); - - act(() => root?.unmount()); - $project.set({ id: "another-project" } as Project); - const reopenedProject = { id: "project", domain: "new" } as Project; - $project.set(reopenedProject); - finishQuery({ - success: true, - project: { id: "project", domain: "old" } as Project, - }); - - await expect(polling).resolves.toBeUndefined(); - expect($project.get()).toBe(reopenedProject); -}); - test("publish failure updates the banner without a duplicate toast while Publish is open", () => { const successToast = vi.spyOn(toast, "success").mockImplementation(() => ""); const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); @@ -650,737 +373,3 @@ test("publish completion shows a toast after the dialog closes", () => { expect(errorToast).toHaveBeenCalledOnce(); expect(setPublishError).toHaveBeenCalledWith(failedStatusText, undefined); }); - -test("a rejected publish request updates the banner without a duplicate toast", async () => { - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - $publishDialog.set("publish"); - $project.set({ id: "project" } as Project); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - await act(async () => container?.querySelector("button")?.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - expect(errorToast).not.toHaveBeenCalled(); -}); - -test("starting validation clears a previous request failure", async () => { - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [publish, validate] = container.querySelectorAll("button"); - await act(async () => publish.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => validate.click()); - expect(container.querySelector("output")?.textContent).toBe(""); -}); - -test("a rejected publish request shows a toast after the dialog closes", async () => { - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - $publishDialog.set("publish"); - $project.set({ id: "project" } as Project); - let rejectPublish: (error: Error) => void = () => {}; - const publish = new Promise((_, reject) => { - rejectPublish = reject; - }); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - act(() => container?.querySelector("button")?.click()); - - $publishDialog.set("none"); - await act(async () => rejectPublish(new Error("Network unavailable"))); - - expect(errorToast).toHaveBeenCalledOnce(); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); -}); - -test("a rejected publish request does not duplicate its banner after the panel reopens", async () => { - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - $publishDialog.set("publish"); - $project.set({ id: "project" } as Project); - let rejectPublish: (error: Error) => void = () => {}; - const publish = new Promise((_, reject) => { - rejectPublish = reject; - }); - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && {progress.publishError}} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [start, close, reopen] = container.querySelectorAll("button"); - act(() => start.click()); - act(() => close.click()); - act(() => reopen.click()); - - await act(async () => rejectPublish(new Error("Network unavailable"))); - - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - expect(errorToast).not.toHaveBeenCalled(); -}); - -test("a publish failure remains available after the panel remounts", () => { - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && {progress.publishError}} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [close, reopen, finish] = container.querySelectorAll("button"); - act(() => close.click()); - act(() => reopen.click()); - act(() => finish.click()); - - expect(container.querySelector("output")?.textContent).toBe("Build failed"); - expect(errorToast).not.toHaveBeenCalled(); -}); - -test("a successful status refresh clears a persisted publish failure", () => { - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [fail, refresh] = container.querySelectorAll("button"); - act(() => fail.click()); - expect(container.querySelector("output")?.textContent).toBe("Publish failed"); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe(""); -}); - -test("refreshing a project without a build clears a status error but preserves a request error", () => { - $project.set({ id: "project" } as Project); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [fail, reject, refresh] = container.querySelectorAll("button"); - - act(() => fail.click()); - expect(container.querySelector("output")?.textContent).toBe("Publish failed"); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe(""); - - act(() => reject.click()); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Request rejected" - ); -}); - -test("refreshing an older published build preserves a rejected request error", () => { - $project.set({ id: "project" } as Project); - const oldPublishedProject = { - id: "project", - latestBuildVirtual: { - createdAt: new Date().toISOString(), - publishStatus: "PUBLISHED", - }, - } as Project; - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [reject, refresh] = container.querySelectorAll("button"); - act(() => reject.click()); - act(() => refresh.click()); - - expect(container.querySelector("output")?.textContent).toBe( - "Request rejected" - ); -}); - -test("a newer build clears a recovered transport error", async () => { - $project.set({ - id: "project", - latestBuildVirtual: { buildId: "old" }, - } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [publish, oldBuild, refresh] = container.querySelectorAll("button"); - await act(async () => publish.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => oldBuild.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe(""); -}); - -test("a recovered failed build replaces a lost response error", async () => { - $project.set({ - id: "project", - latestBuildVirtual: { buildId: "old" }, - } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [publish, refresh] = container.querySelectorAll("button"); - await act(async () => publish.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toContain( - "Publish failed" - ); -}); - -test("publish diagnostics remain visible after the panel remounts", () => { - $project.set({ id: "project" } as Project); - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && {progress.publishFindings.length}} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [close, reopen, finish] = container.querySelectorAll("button"); - act(() => close.click()); - act(() => reopen.click()); - act(() => finish.click()); - - expect(container.querySelector("output")?.textContent).toBe("1"); -}); - -test("an older validation cannot replace newer findings", () => { - const finish: ((title: string) => void)[] = []; - - const Harness = () => { - const validation = useManualValidationFindings(); - return ( - <> - - {validation.findings[0]?.title} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const validate = container.querySelector("button")!; - act(() => validate.click()); - act(() => validate.click()); - act(() => finish[1]("new")); - act(() => finish[0]("old")); - - expect(container.querySelector("output")?.textContent).toBe("new"); -}); - -test("manual validation report stays available after the popover reopens", () => { - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const { manualValidationFindings } = usePublishProgress("project"); - return ( - <> - - - - {isOpen && ( - - )} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [close, reopen, validate] = container.querySelectorAll("button"); - act(() => validate.click()); - expect(container.textContent).toContain("Publish check found 1 warning."); - act(() => close.click()); - act(() => reopen.click()); - expect(container.textContent).toContain("Publish check found 1 warning."); - expect( - [...container.querySelectorAll("button")].some( - (button) => button.textContent === "See issues" - ) - ).toBe(true); -}); - -test("reopening shows the domains used by the validation report and submits only those domains", () => { - let validation: ReturnType | undefined; - const Harness = () => { - validation = useManualValidationFindings(); - return null; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - act(() => { - const session = validation!.begin(["custom.example"]); - validation!.update(session, [ - { severity: "warning", title: "Check", reportText: "Check" }, - ]); - }); - - act(() => root?.unmount()); - $project.set({ - id: "project", - domainsVirtual: [{ status: "ACTIVE", verified: true }], - } as Project); - root = createRoot(container); - const renderCheckboxes = (validatedDomains?: string[]) => - act(() => - root?.render( - -
- - - -
- ) - ); - renderCheckboxes(); - - const form = container.querySelector("form")!; - const [staging, custom] = form.querySelectorAll('[role="checkbox"]'); - expect(staging.getAttribute("aria-checked")).toBe("true"); - expect(custom.getAttribute("aria-checked")).toBe("false"); - - renderCheckboxes(validation!.domains); - expect(staging.getAttribute("aria-checked")).toBe("false"); - expect(custom.getAttribute("aria-checked")).toBe("true"); - expect([...new FormData(form).getAll(domainToPublishName)]).toEqual([ - "custom.example", - ]); - act(() => (custom as HTMLButtonElement).click()); - renderCheckboxes(); - expect(custom.getAttribute("aria-checked")).toBe("false"); - expect([...new FormData(form).getAll(domainToPublishName)]).toEqual([]); -}); - -test("older publish diagnostics cannot replace a newer operation", () => { - let progress: ReturnType | undefined; - const Harness = () => { - progress = usePublishProgress("project"); - return {progress.publishFindings[0]?.title}; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - const oldAttempt = progress!.beginPublishDiagnostics(); - const currentAttempt = progress!.beginPublishDiagnostics(); - act(() => - currentAttempt.setFindings([ - { severity: "warning", title: "New", reportText: "New" }, - ]) - ); - act(() => - oldAttempt.setFindings([ - { severity: "warning", title: "Old", reportText: "Old" }, - ]) - ); - - expect(oldAttempt.isCurrent()).toBe(false); - expect(container.querySelector("output")?.textContent).toBe("New"); -}); - -test("a rejected request after project navigation does not show a stale toast", async () => { - $project.set({ id: "old-project" } as Project); - $publishDialog.set("publish"); - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - let rejectPublish: (error: Error) => void = () => {}; - const publish = new Promise((_, reject) => { - rejectPublish = reject; - }); - - const Harness = () => { - const progress = usePublishProgress("old-project"); - return ; - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - act(() => container?.querySelector("button")?.click()); - act(() => root?.unmount()); - $project.set({ id: "new-project" } as Project); - - await act(async () => rejectPublish(new Error("Network unavailable"))); - expect(errorToast).not.toHaveBeenCalled(); -}); - -test.each(["site", "static"] as const)( - "keeps %s findings when diagnostics for the other target start", - (firstTarget) => { - const secondTarget = firstTarget === "site" ? "static" : "site"; - let progress: ReturnType; - const Harness = () => { - progress = usePublishProgress("project"); - return null; - }; - $project.set({ id: "project" } as Project); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - act(() => { - progress - .beginPublishDiagnostics([], firstTarget) - .setFindings([ - { severity: "warning", title: firstTarget, reportText: firstTarget }, - ]); - }); - act(() => { - progress.beginPublishDiagnostics([], secondTarget).setFindings([ - { - severity: "warning", - title: secondTarget, - reportText: secondTarget, - }, - ]); - }); - expect( - progress!.publishDiagnostics[firstTarget].findings.map( - ({ reportText }) => reportText - ) - ).toEqual([firstTarget]); - } -); diff --git a/apps/builder/app/builder/features/publish/publish-progress.tsx b/apps/builder/app/builder/features/publish/publish-progress.tsx new file mode 100644 index 0000000000..a59b088f55 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-progress.tsx @@ -0,0 +1,219 @@ +import { toast } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { $project } from "~/shared/sync/data-stores"; +import { $publishDialog } from "~/builder/shared/nano-states"; +import { nativeClient } from "~/shared/trpc/trpc-client"; +import { + PENDING_TIMEOUT, + getPublishStatusDisplay, + getStaticPublishStatusDisplay, +} from "./publish-status"; + +const STATUS_REFRESH_RETRY_DELAY = 5_000; + +const STATUS_REFRESH_MAX_ATTEMPTS = 3; + +export type PublishExecution = { + projectId: string; + buildId: string; + logHandle?: string; + target?: "site" | "static"; +}; + +export const waitForPublishStatus = async ( + refresh: () => Promise, + 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); + } +}; + +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 ( - - {flow.isPublishing ? "pending" : "idle"} - {flow.publishes[0]?.status} - {flow.staticFailureFinding?.severity} - {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 ( + + Upgrade for CMS + 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 + +
    + + + + props.flow.openSiteReport(domain, "publish") + } + latestPublish={props.flow.publishes.find( + (item) => + item.target === "site" && + item.domains.includes(project.domain) + )} + /> + + + props.flow.openSiteReport(domain, "publish") + } + sessionPublishes={props.flow.publishes} + /> + + + + + + + { + setNewDomains((prev) => new Set([...prev, domain])); + }} + /> + {isAddingDomain && } + + {hasUnpublishedDomains && ( + + + + Don't forget to publish + + + You have a custom domain that hasn't been published yet. Hit + publish to make it live. + + + )} + + +
    + + ); +}; + +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 + + +