Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: Stop slow diagnostics from blocking publishing and clarify publish status (#6416)

Oleg Isonen804cd39bc23b
diff --git a/apps/builder/app/builder/features/publish/add-domain.test.tsx b/apps/builder/app/builder/features/publish/add-domain.test.tsx
new file mode 100644
index 0000000000..814aec7c4f
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/add-domain.test.tsx
@@ -0,0 +1,61 @@
+import { useState } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { act } from "react-dom/test-utils";
+import { afterEach, expect, test } from "vitest";
+import { AddDomain } from "./add-domain";
+
+let root: Root | undefined;
+let container: HTMLDivElement | undefined;
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ container?.remove();
+ container = undefined;
+});
+
+test("shows the domain form only while requested and lets the user cancel", () => {
+ const Harness = () => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <form>
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open domain form
+ </button>
+ <AddDomain
+ projectId="project-id"
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ onCreate={() => {}}
+ refresh={async () => {}}
+ />
+ </form>
+ );
+ };
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => root?.render(<Harness />));
+
+ expect(container.querySelector('input[name="domain"]')).toBeNull();
+ expect(container.textContent).not.toContain("Export");
+
+ const open = container.querySelector<HTMLButtonElement>("button");
+ act(() => open?.click());
+
+ expect(container.querySelector('input[name="domain"]')).not.toBeNull();
+ expect(container.textContent).toContain("Add domain");
+
+ const cancel = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ ).find((button) => button.textContent === "Cancel");
+ act(() => cancel?.click());
+
+ expect(container.querySelector('input[name="domain"]')).toBeNull();
+});
diff --git a/apps/builder/app/builder/features/publish/add-domain.tsx b/apps/builder/app/builder/features/publish/add-domain.tsx
index cd3b614244..bfa1563495 100644
--- a/apps/builder/app/builder/features/publish/add-domain.tsx
+++ b/apps/builder/app/builder/features/publish/add-domain.tsx
@@ -1,40 +1,44 @@
import {
Button,
Flex,
+ Grid,
InputField,
Label,
- Separator,
- theme,
Text,
- Grid,
toast,
} from "@webstudio-is/design-system";
import { validateDomain } from "@webstudio-is/domain";
import type { Project } from "@webstudio-is/project";
-import { useId, useOptimistic, useRef, useState } from "react";
-import { TerminalIcon } from "@webstudio-is/icons";
+import { useEffect, useId, useOptimistic, useRef, useState } from "react";
import { nativeClient } from "~/shared/trpc/trpc-client";
import { extractCname } from "./cname";
type DomainsAddProps = {
projectId: Project["id"];
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
onCreate: (domain: string) => void;
- onExportClick: () => void;
refresh: () => Promise<void>;
};
export const AddDomain = ({
projectId,
+ isOpen,
+ onOpenChange,
onCreate,
refresh,
- onExportClick,
}: DomainsAddProps) => {
const id = useId();
- const [isOpen, setIsOpen] = useState(false);
const [error, setError] = useState<string>();
const buttonRef = useRef<HTMLButtonElement>(null);
const [isPending, setIsPendingOptimistic] = useOptimistic(false);
+ useEffect(() => {
+ if (isOpen) {
+ setError(undefined);
+ }
+ }, [isOpen]);
+
const handleCreateDomain = async (formData: FormData) => {
// Will be automatically reset on action end
setIsPendingOptimistic(true);
@@ -74,82 +78,68 @@ export const AddDomain = ({
await refresh();
- setIsOpen(false);
+ onOpenChange(false);
};
+ if (isOpen === false) {
+ return;
+ }
+
return (
- <>
- <Flex
- gap={2}
- shrink={false}
- direction={"column"}
+ <Flex
+ gap={2}
+ shrink={false}
+ direction="column"
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ onOpenChange(false);
+ event.preventDefault();
+ }
+ }}
+ >
+ <Label htmlFor={id} text="title">
+ New Domain
+ </Label>
+ <InputField
+ id={id}
+ name="domain"
+ autoFocus
+ placeholder="your-domain.com"
+ disabled={isPending}
onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ buttonRef.current
+ ?.closest("form")
+ ?.requestSubmit(buttonRef.current);
+ }
if (event.key === "Escape") {
- setIsOpen(false);
+ onOpenChange(false);
event.preventDefault();
}
}}
- >
- {isOpen && (
- <>
- <Label htmlFor={id} text="title">
- New Domain
- </Label>
- <InputField
- id={id}
- name="domain"
- autoFocus
- placeholder="your-domain.com"
- disabled={isPending}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- buttonRef.current
- ?.closest("form")
- ?.requestSubmit(buttonRef.current);
- }
- if (event.key === "Escape") {
- setIsOpen(false);
- event.preventDefault();
- }
- }}
- color={error !== undefined ? "error" : undefined}
- />
- {error !== undefined && (
- <>
- <Text color="destructive">{error}</Text>
- </>
- )}
- </>
- )}
-
- <Grid gap={2} columns={2}>
- <Button
- ref={buttonRef}
- formAction={handleCreateDomain}
- state={isPending ? "pending" : undefined}
- color={isOpen ? "primary" : "neutral"}
- onClick={(event) => {
- if (isOpen === false) {
- setIsOpen(true);
- event.preventDefault();
- return;
- }
- }}
- >
- {isOpen ? "Add domain" : "Add a new domain"}
- </Button>
-
- <Button
- prefix={<TerminalIcon />}
- type="button"
- onClick={onExportClick}
- >
- Export
- </Button>
- </Grid>
- </Flex>
- {isOpen && <Separator css={{ mb: theme.spacing[5] }} />}
- </>
+ color={error !== undefined ? "error" : undefined}
+ />
+ {error !== undefined && <Text color="destructive">{error}</Text>}
+ <Grid gap={2} columns={2}>
+ <Button
+ ref={buttonRef}
+ formAction={handleCreateDomain}
+ state={isPending ? "pending" : undefined}
+ color="primary"
+ disabled={isPending}
+ >
+ Add domain
+ </Button>
+ <Button
+ type="button"
+ color="neutral"
+ disabled={isPending}
+ onClick={() => onOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ </Grid>
+ </Flex>
);
};
diff --git a/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsx b/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsx
index 6fd3b785f1..7238cd637a 100644
--- a/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsx
+++ b/apps/builder/app/builder/features/publish/collapsible-domain-section.stories.tsx
@@ -486,7 +486,14 @@ export const PublishDialogLayout = () => (
</Flex>
<PanelContent as={Flex} direction="column" gap="2">
- <Button color="primary">Publish</Button>
+ <Flex gap={2}>
+ <Button color="positive" css={{ flex: 1 }}>
+ Validate
+ </Button>
+ <Button color="primary" css={{ flex: 1 }}>
+ Publish
+ </Button>
+ </Flex>
</PanelContent>
</Flex>
</StorySection>
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.test.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.tsx
new file mode 100644
index 0000000000..c655c9af24
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.tsx
@@ -0,0 +1,69 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, test, vi } from "vitest";
+import {
+ getContentDatabasePublishWarning,
+ showContentDatabasePublishWarning,
+} from "./content-database-publish-warning";
+
+const mdxDiagnostics = (count: number) => ({
+ stats: undefined,
+ affectedResources: [],
+ mdxOmissions: Array.from({ length: count }, (_, index) => ({
+ assetId: `asset-${index}`,
+ blockInstanceId: `block-${index}`,
+ filename: `post-${index}.mdx`,
+ templateName: `Post ${index}`,
+ })),
+});
+
+describe("content database publish warning", () => {
+ test("returns no warning when diagnostics are clean", () => {
+ expect(getContentDatabasePublishWarning(mdxDiagnostics(0))).toBeUndefined();
+ });
+
+ test("lists ten omitted templates and reports the remaining count", () => {
+ const warning = getContentDatabasePublishWarning(mdxDiagnostics(11));
+ const markup = renderToStaticMarkup(warning);
+
+ expect(markup).toContain("post-0.mdx: Post 0");
+ expect(markup).toContain("post-9.mdx: Post 9");
+ expect(markup).not.toContain("post-10.mdx");
+ expect(markup).toContain("And 1 more template references.");
+ });
+
+ test("does not wait for advisory diagnostics", () => {
+ const diagnostics = new Promise<never>(() => {});
+
+ expect(
+ showContentDatabasePublishWarning({
+ diagnostics,
+ setWarning: vi.fn(),
+ })
+ ).toBeUndefined();
+ });
+
+ test("shows a warning when diagnostics finish", async () => {
+ const setWarning = vi.fn();
+ showContentDatabasePublishWarning({
+ diagnostics: Promise.resolve(mdxDiagnostics(1)),
+ setWarning,
+ });
+
+ await vi.waitFor(() => expect(setWarning).toHaveBeenCalledOnce());
+ expect(renderToStaticMarkup(setWarning.mock.calls[0][0])).toContain(
+ "post-0.mdx: Post 0"
+ );
+ });
+
+ test("swallows an advisory diagnostics failure", async () => {
+ const setWarning = vi.fn();
+ showContentDatabasePublishWarning({
+ diagnostics: Promise.reject(new Error("diagnostics unavailable")),
+ setWarning,
+ });
+
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(setWarning).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
index 92244c4cf7..742c48018f 100644
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
@@ -1,26 +1,21 @@
-import type { Project } from "@webstudio-is/project";
-import { nativeClient } from "~/shared/trpc/trpc-client";
+import type { nativeClient } from "~/shared/trpc/trpc-client";
import { ContentDatabasePublishWarning } from "./content-database-publish-warning-view";
import { showPublishWarning } from "./publish-warning";
-export const showContentDatabasePublishWarning = async ({
- projectId,
- setWarning,
-}: {
- projectId: Project["id"];
- setWarning: (warning: JSX.Element) => void;
-}) => {
- const diagnostics =
- await nativeClient.build.contentDatabasePublishDiagnostics.query({
- projectId,
- });
+type ContentDatabasePublishDiagnostics = Awaited<
+ ReturnType<typeof nativeClient.build.contentDatabasePublishDiagnostics.query>
+>;
+
+export const getContentDatabasePublishWarning = (
+ diagnostics: ContentDatabasePublishDiagnostics
+) => {
const databaseWarning =
diagnostics.stats?.truncated &&
diagnostics.stats.omissionReason !== undefined;
if (!databaseWarning && diagnostics.mdxOmissions.length === 0) {
return;
}
- const message = (
+ return (
<>
{diagnostics.mdxOmissions.length > 0 && (
<div>
@@ -53,5 +48,23 @@ export const showContentDatabasePublishWarning = async ({
)}
</>
);
- showPublishWarning({ message, setWarning });
+};
+
+export const showContentDatabasePublishWarning = ({
+ diagnostics,
+ setWarning,
+}: {
+ diagnostics: Promise<ContentDatabasePublishDiagnostics>;
+ setWarning: (warning: JSX.Element) => void;
+}) => {
+ void diagnostics
+ .then((diagnostics) => {
+ const warning = getContentDatabasePublishWarning(diagnostics);
+ if (warning !== undefined) {
+ showPublishWarning({ message: warning, setWarning });
+ }
+ })
+ .catch(() => {
+ // Content warnings are advisory and must not block publishing.
+ });
};
diff --git a/apps/builder/app/builder/features/publish/domains.test.tsx b/apps/builder/app/builder/features/publish/domains.test.tsx
new file mode 100644
index 0000000000..b4d29a9fd8
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/domains.test.tsx
@@ -0,0 +1,80 @@
+import { act } from "react-dom/test-utils";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, test } from "vitest";
+import { TooltipProvider } from "@webstudio-is/design-system";
+import { __testing__, PENDING_TIMEOUT, type Domain } from "./domains";
+
+const { StatusIcon } = __testing__;
+let root: Root | undefined;
+let container: HTMLDivElement | undefined;
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ container?.remove();
+ container = undefined;
+});
+
+const renderStatus = (
+ publishStatus: "PENDING" | "PUBLISHED" | "FAILED" | undefined,
+ age = 0,
+ isLoading = false
+) => {
+ if (container === undefined) {
+ container = document.createElement("div");
+ container.style.setProperty("--foreground-warning", "rgb(200, 160, 0)");
+ container.style.setProperty("--foreground-positive", "rgb(0, 160, 0)");
+ container.style.setProperty("--foreground-negative", "rgb(200, 0, 0)");
+ container.style.setProperty("--foreground-secondary", "rgb(100, 100, 100)");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ }
+ const projectDomain = {
+ status: "ACTIVE",
+ verified: true,
+ latestBuildVirtual:
+ publishStatus === undefined
+ ? null
+ : {
+ publishStatus,
+ createdAt: new Date(Date.now() - age).toISOString(),
+ },
+ } as Domain;
+ act(() =>
+ root?.render(
+ <TooltipProvider>
+ <StatusIcon projectDomain={projectDomain} isLoading={isLoading} />
+ </TooltipProvider>
+ )
+ );
+ const icon = container.querySelector("svg");
+ expect(icon).not.toBeNull();
+ return getComputedStyle(icon!).color;
+};
+
+test.each([
+ { status: "PUBLISHED" as const, color: "rgb(0, 160, 0)" },
+ { status: "FAILED" as const, color: "rgb(200, 0, 0)" },
+])(
+ "shows yellow while publishing, then the $status color",
+ ({ status, color }) => {
+ expect(renderStatus("PENDING")).toBe("rgb(200, 160, 0)");
+ expect(renderStatus(status)).toBe(color);
+ }
+);
+
+test("keeps status loading neutral and expired publishing red", () => {
+ expect(renderStatus("PENDING")).toBe("rgb(200, 160, 0)");
+ expect(renderStatus("PENDING", 0, true)).toBe("rgb(100, 100, 100)");
+ expect(renderStatus("PENDING", PENDING_TIMEOUT + 1000)).toBe(
+ "rgb(200, 0, 0)"
+ );
+});
+
+test("does not show success for a domain that has never been published", () => {
+ expect(renderStatus(undefined)).toBe("rgb(100, 100, 100)");
+});
diff --git a/apps/builder/app/builder/features/publish/domains.tsx b/apps/builder/app/builder/features/publish/domains.tsx
index 50eb1e675c..ee26859c8e 100644
--- a/apps/builder/app/builder/features/publish/domains.tsx
+++ b/apps/builder/app/builder/features/publish/domains.tsx
@@ -21,6 +21,8 @@ import {
CheckCircleIcon,
CopyIcon,
HelpIcon,
+ InfoCircleIcon,
+ SpinnerIcon,
} from "@webstudio-is/icons";
import { CollapsibleDomainSection } from "./collapsible-domain-section";
import {
@@ -91,7 +93,20 @@ export const getPublishStatusAndText = ({
</>
);
- return { statusText, status };
+ const color =
+ status === "PUBLISHED"
+ ? cssVar("--foreground-positive")
+ : status === "FAILED"
+ ? cssVar("--foreground-negative")
+ : cssVar("--foreground-warning");
+ const Icon =
+ status === "PUBLISHED"
+ ? CheckCircleIcon
+ : status === "FAILED"
+ ? AlertIcon
+ : SpinnerIcon;
+
+ return { statusText, status, color, Icon };
};
const getStatusText = (props: {
@@ -100,7 +115,8 @@ const getStatusText = (props: {
}) => {
const status = getStatus(props.projectDomain);
- let isVerifiedActive = false;
+ let color = cssVar("--foreground-negative");
+ let Icon = AlertIcon;
let text: ReactNode = "Something went wrong";
switch (status) {
@@ -115,7 +131,8 @@ const getStatusText = (props: {
text = "Status: Waiting for CNAME propagation";
break;
case "VERIFIED_ACTIVE":
- isVerifiedActive = true;
+ color = cssVar("--foreground-secondary");
+ Icon = InfoCircleIcon;
text = "Status: Active, not published";
if (props.projectDomain.latestBuildVirtual !== null) {
@@ -124,7 +141,8 @@ const getStatusText = (props: {
);
text = publishText.statusText;
- isVerifiedActive = publishText.status !== "FAILED";
+ color = publishText.color;
+ Icon = publishText.Icon;
}
break;
case "VERIFIED_ERROR":
@@ -139,15 +157,14 @@ const getStatusText = (props: {
}
return {
- isVerifiedActive,
+ color: props.isLoading ? cssVar("--foreground-secondary") : color,
+ Icon,
text: props.isLoading ? "Loading status..." : text,
};
};
const StatusIcon = (props: { projectDomain: Domain; isLoading: boolean }) => {
- const { isVerifiedActive, text } = getStatusText(props);
-
- const Icon = isVerifiedActive ? CheckCircleIcon : AlertIcon;
+ const { color, Icon, text } = getStatusText(props);
return (
<Tooltip content={text}>
@@ -158,11 +175,7 @@ const StatusIcon = (props: { projectDomain: Domain; isLoading: boolean }) => {
cursor: "pointer",
width: theme.sizes.controlHeight,
height: theme.sizes.controlHeight,
- color: props.isLoading
- ? cssVar("--foreground-secondary")
- : isVerifiedActive
- ? cssVar("--foreground-positive")
- : cssVar("--foreground-negative"),
+ color,
}}
>
<Icon />
@@ -305,7 +318,7 @@ const DomainItem = ({
const domainStatus = getStatus(projectDomain);
- const { isVerifiedActive, text } = getStatusText({
+ const { color, text } = getStatusText({
projectDomain,
isLoading: false,
});
@@ -440,7 +453,9 @@ const DomainItem = ({
{status !== "UNVERIFIED" && (
<>
- <Text color={isVerifiedActive ? "success" : "destructive"}>
+ <Text
+ css={{ color, overflowWrap: "anywhere", userSelect: "text" }}
+ >
{text}
</Text>
</>
@@ -584,3 +599,5 @@ export const Domains = ({
undefined;
undefined;
+
+export const __testing__ = { StatusIcon };
diff --git a/apps/builder/app/builder/features/publish/publish-actions.test.tsx b/apps/builder/app/builder/features/publish/publish-actions.test.tsx
new file mode 100644
index 0000000000..d9c520bacb
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-actions.test.tsx
@@ -0,0 +1,202 @@
+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 } from "@webstudio-is/design-system";
+import { PublishActions, usePublishValidationState } from "./publish-actions";
+
+let root: Root | undefined;
+let container: HTMLDivElement | undefined;
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ container?.remove();
+ container = undefined;
+});
+
+const render = (
+ validationState: "idle" | "passed",
+ publishInProgress = false,
+ publishDisabled = false
+) => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root?.render(
+ <TooltipProvider>
+ <PublishActions
+ validationState={validationState}
+ validateDisabled={publishInProgress}
+ publishDisabled={publishDisabled}
+ publishInProgress={publishInProgress}
+ hasSelectedDomains
+ publishLabel="Publish"
+ publishButtonRef={createRef<HTMLButtonElement>()}
+ onValidate={vi.fn(async () => {})}
+ onPublish={vi.fn()}
+ />
+ </TooltipProvider>
+ );
+ });
+ return Array.from(container.querySelectorAll<HTMLButtonElement>("button"));
+};
+
+test("gives both actions equal width", () => {
+ const [validate, publish] = render("idle");
+
+ expect(validate.dataset.state).toBe("auto");
+ expect(validate.dataset.buttonColor).toBe("positive");
+ expect(validate).toBeEnabled();
+ expect(publish).toBeEnabled();
+ expect(getComputedStyle(validate).flexGrow).toBe("1");
+ expect(getComputedStyle(publish).flexGrow).toBe("1");
+ expect(validate.getBoundingClientRect().width).toBe(
+ publish.getBoundingClientRect().width
+ );
+});
+
+test("shows the successful validation state in the action", () => {
+ const [validate] = render("passed");
+
+ expect(validate.textContent).toBe("Validated");
+ expect(validate.dataset.buttonColor).toBe("positive");
+ expect(validate.querySelector("svg")).not.toBeNull();
+ 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);
+
+ return (
+ <TooltipProvider>
+ {isOpen && (
+ <PublishActions
+ validationState={validationState}
+ validateDisabled={false}
+ publishDisabled={false}
+ publishInProgress={false}
+ hasSelectedDomains
+ publishLabel="Publish"
+ publishButtonRef={createRef<HTMLButtonElement>()}
+ onValidate={async () => {
+ update("passed");
+ }}
+ onPublish={vi.fn()}
+ />
+ )}
+ <button
+ type="button"
+ onClick={() => {
+ reset();
+ setIsOpen(false);
+ }}
+ >
+ Close
+ </button>
+ {isOpen === false && (
+ <button type="button" onClick={() => setIsOpen(true)}>
+ Open
+ </button>
+ )}
+ </TooltipProvider>
+ );
+ };
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => root?.render(<Harness />));
+
+ const [validate, , close] = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ );
+ await act(async () => validate.click());
+ expect(validate.textContent).toBe("Validated");
+
+ act(() => close.click());
+ const reopen =
+ container.querySelector<HTMLButtonElement>("button:last-child");
+ act(() => reopen?.click());
+
+ const [reopenedValidate] = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ );
+ expect(reopenedValidate.textContent).toBe("Validate");
+ expect(reopenedValidate.querySelector("svg")).toBeNull();
+});
+
+test("shows publish progress and disables actions immediately", () => {
+ const [validate, publish] = render("idle", true, true);
+
+ expect(validate).toBeDisabled();
+ expect(publish.dataset.state).toBe("pending");
+ expect(publish).toBeDisabled();
+ expect(publish.querySelector("svg")).not.toBeNull();
+});
+
+test("shows pending immediately after Validate is clicked", async () => {
+ let resolveValidation: () => void = () => {};
+ const validation = new Promise<void>((resolve) => {
+ resolveValidation = resolve;
+ });
+
+ const Harness = () => {
+ const [validationState, setValidationState] = useState<"idle" | "passed">(
+ "idle"
+ );
+
+ return (
+ <TooltipProvider>
+ <PublishActions
+ validationState={validationState}
+ validateDisabled={false}
+ publishDisabled={false}
+ publishInProgress={false}
+ hasSelectedDomains
+ publishLabel="Publish"
+ publishButtonRef={createRef<HTMLButtonElement>()}
+ onValidate={async () => {
+ await validation;
+ setValidationState("passed");
+ }}
+ onPublish={vi.fn()}
+ />
+ </TooltipProvider>
+ );
+ };
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => root?.render(<Harness />));
+
+ const [validate] = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ );
+ act(() => validate.click());
+
+ expect(validate.dataset.state).toBe("pending");
+ expect(validate).toBeDisabled();
+ expect(validate.querySelector("svg")).not.toBeNull();
+ const [, publish] = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ );
+ expect(publish).toBeDisabled();
+
+ await act(async () => {
+ resolveValidation();
+ await validation;
+ });
+
+ expect(validate.textContent).toBe("Validated");
+ expect(validate).toBeEnabled();
+});
diff --git a/apps/builder/app/builder/features/publish/publish-actions.tsx b/apps/builder/app/builder/features/publish/publish-actions.tsx
new file mode 100644
index 0000000000..45e1c38987
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-actions.tsx
@@ -0,0 +1,108 @@
+import { useCallback, useEffect, useRef, 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 = (isOpen: boolean) => {
+ const [validationState, setValidationState] =
+ useState<PublishValidationState>("idle");
+ const session = useRef(0);
+ const sessionAtRender = session.current;
+ const isOpenRef = useRef(isOpen);
+ isOpenRef.current = isOpen;
+
+ const reset = useCallback(() => {
+ session.current += 1;
+ setValidationState("idle");
+ }, []);
+
+ const update = useCallback(
+ (state: PublishValidationState) => {
+ if (isOpenRef.current && session.current === sessionAtRender) {
+ setValidationState(state);
+ }
+ },
+ [sessionAtRender]
+ );
+
+ useEffect(() => {
+ if (isOpen === false) {
+ reset();
+ }
+ }, [isOpen, reset]);
+
+ return { validationState, update, reset };
+};
+
+export const PublishActions = ({
+ validationState,
+ validateDisabled,
+ publishDisabled,
+ publishInProgress,
+ hasSelectedDomains,
+ publishLabel,
+ publishButtonRef,
+ onValidate,
+ onPublish,
+}: {
+ validationState: PublishValidationState;
+ validateDisabled: boolean;
+ publishDisabled: boolean;
+ publishInProgress: boolean;
+ hasSelectedDomains: boolean;
+ publishLabel: string;
+ publishButtonRef: Ref<HTMLButtonElement>;
+ onValidate: () => Promise<void>;
+ onPublish: () => void;
+}) => {
+ const [isValidating, setIsValidating] = useState(false);
+
+ const handleValidate = async () => {
+ setIsValidating(true);
+ try {
+ await onValidate();
+ } finally {
+ setIsValidating(false);
+ }
+ };
+
+ return (
+ <Flex gap={2}>
+ <Button
+ type="button"
+ color="positive"
+ state={isValidating ? "pending" : undefined}
+ disabled={validateDisabled}
+ css={{ flex: 1 }}
+ prefix={validationState === "passed" ? <CheckCircleIcon /> : undefined}
+ onClick={handleValidate}
+ >
+ {validationState === "passed" ? "Validated" : "Validate"}
+ </Button>
+ <Tooltip
+ content={
+ publishInProgress
+ ? "Publish process in progress"
+ : hasSelectedDomains
+ ? undefined
+ : "Select at least one domain to publish"
+ }
+ >
+ <Button
+ ref={publishButtonRef}
+ type="button"
+ onClick={onPublish}
+ color="primary"
+ state={publishInProgress ? "pending" : undefined}
+ css={{ flex: 1 }}
+ disabled={
+ publishInProgress === false && (publishDisabled || isValidating)
+ }
+ >
+ {publishLabel}
+ </Button>
+ </Tooltip>
+ </Flex>
+ );
+};
diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx
index 1fe93a421a..e7fc4465cb 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -32,6 +32,11 @@ import {
PanelBanner,
toast,
RadioGroup,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
Popover,
PopoverTrigger,
PopoverContent,
@@ -64,13 +69,15 @@ import { $project } from "~/shared/sync/data-stores";
import { Domains, PENDING_TIMEOUT, getPublishStatusAndText } from "./domains";
import { CollapsibleDomainSection } from "./collapsible-domain-section";
import {
- CheckCircleIcon,
AlertIcon,
CopyIcon,
GearIcon,
UpgradeIcon,
HelpIcon,
InfoCircleIcon,
+ EllipsesIcon,
+ PlusIcon,
+ TerminalIcon,
} from "@webstudio-is/icons";
import { AddDomain } from "./add-domain";
import { humanizeString } from "~/shared/string-utils";
@@ -102,7 +109,15 @@ import {
runPrePublishAudit,
type PrePublishAuditFinding,
} from "@webstudio-is/project-build/runtime";
-import { showContentDatabasePublishWarning } from "./content-database-publish-warning";
+import {
+ getContentDatabasePublishWarning,
+ showContentDatabasePublishWarning,
+} from "./content-database-publish-warning";
+import {
+ PublishActions,
+ usePublishValidationState,
+ type PublishValidationState,
+} from "./publish-actions";
import { showPublishWarning } from "./publish-warning";
import { flushExternalContentProject } from "~/shared/external-content-roots";
import { getPrePublishErrorMessage } from "./publish-error";
@@ -252,12 +267,13 @@ const ChangeProjectDomain = ({
toast.success(result.message);
};
- const { statusText, status } =
+ const { statusText, color, Icon } =
project.latestBuildVirtual != null
? getPublishStatusAndText(project.latestBuildVirtual)
: {
statusText: "Not published",
- status: "PENDING" as const,
+ color: cssVar("--foreground-secondary"),
+ Icon: InfoCircleIcon,
};
// Check if the wstd domain specifically is published (not just any custom domain)
@@ -286,16 +302,10 @@ const ChangeProjectDomain = ({
width: theme.sizes.controlHeight,
height: theme.sizes.controlHeight,
color:
- error !== undefined || status === "FAILED"
- ? cssVar("--foreground-negative")
- : cssVar("--foreground-positive"),
+ error !== undefined ? cssVar("--foreground-negative") : color,
}}
>
- {error !== undefined || status === "FAILED" ? (
- <AlertIcon />
- ) : (
- <CheckCircleIcon />
- )}
+ {error !== undefined ? <AlertIcon /> : <Icon />}
</Flex>
</Tooltip>
@@ -464,12 +474,20 @@ const Publish = ({
disabled,
refresh,
restrictedFeatures,
+ validationState,
+ onValidationStateChange,
+ isPublishing,
+ setIsPublishing,
}: {
project: Project;
timesLeft: number;
disabled: boolean;
refresh: () => Promise<void>;
restrictedFeatures: Map<string, RestrictedFeature>;
+ validationState: PublishValidationState;
+ onValidationStateChange: (state: PublishValidationState) => void;
+ isPublishing: boolean;
+ setIsPublishing: (isPublishing: boolean) => void;
}) => {
const { userPublishCount, maxDailyPublishesPerUser } = useUserPublishCount();
const [publishError, setPublishError] = useState<
@@ -478,11 +496,11 @@ const Publish = ({
const [publishWarning, setPublishWarning] = useState<
undefined | JSX.Element | string
>();
- const [isPublishing, setIsPublishing] = useOptimistic(false);
const buttonRef = useRef<HTMLButtonElement>(null);
const [hasSelectedDomains, setHasSelectedDomains] = useState(false);
const [hasCustomDomainsSelected, setHasCustomDomainsSelected] =
useState(false);
+ const previousDomainsKey = useRef<string>();
const countdown = usePublishCountdown(isPublishing);
useEffect(() => {
@@ -497,6 +515,15 @@ const Publish = ({
const domainsSelected = formData
.getAll(domainToPublishName)
.map((domain) => domain.toString());
+ const domainsKey = domainsSelected.join("\u0000");
+
+ if (
+ previousDomainsKey.current !== undefined &&
+ previousDomainsKey.current !== domainsKey
+ ) {
+ onValidationStateChange("idle");
+ }
+ previousDomainsKey.current = domainsKey;
setHasSelectedDomains(domainsSelected.length > 0);
@@ -524,7 +551,7 @@ const Publish = ({
return () => {
observer.disconnect();
};
- }, [project.domain]);
+ }, [onValidationStateChange, project.domain]);
const publish = async (domains: string[]) => {
const publishResult = await nativeClient.domain.publish.mutate({
@@ -621,15 +648,79 @@ const Publish = ({
}
};
+ const runPrePublishChecks = async (): Promise<boolean> => {
+ await nativeClient.build.checkProjectBuildPermission.query({
+ projectId: project.id,
+ });
+ await flushExternalContentProject({ projectId: project.id });
+
+ const { error: auditError, warning: auditWarning } =
+ getPrePublishAuditMessages();
+ if (auditError !== undefined) {
+ toast.error(auditError);
+ setPublishError(auditError);
+ return false;
+ }
+ if (auditWarning !== undefined) {
+ showPublishWarning({
+ message: auditWarning,
+ setWarning: setPublishWarning,
+ });
+ }
+
+ return true;
+ };
+
+ const getDomainsFromForm = (formData: FormData) =>
+ formData
+ .getAll(domainToPublishName)
+ .map((domainEntry) => domainEntry.toString());
+
+ const handleValidate = async (formData: FormData) => {
+ setPublishError(undefined);
+ setPublishWarning(undefined);
+ const domains = getDomainsFromForm(formData);
+ if (domains.length === 0) {
+ toast.error("Please select at least one domain to publish");
+ return;
+ }
+
+ try {
+ const passed = await runPrePublishChecks();
+ if (!passed) {
+ onValidationStateChange("idle");
+ return;
+ }
+ const diagnostics =
+ await nativeClient.build.contentDatabasePublishDiagnostics.query({
+ projectId: project.id,
+ });
+ const contentWarning = getContentDatabasePublishWarning(diagnostics);
+ if (contentWarning !== undefined) {
+ showPublishWarning({
+ message: contentWarning,
+ setWarning: setPublishWarning,
+ });
+ }
+ onValidationStateChange("passed");
+ toast.success("Validation passed. Ready to publish.", {
+ duration: Number.POSITIVE_INFINITY,
+ });
+ } catch (error) {
+ onValidationStateChange("idle");
+ const message = getPrePublishErrorMessage(error);
+ toast.error(message);
+ setPublishError(message);
+ }
+ };
+
const handlePublish = (formData: FormData) => {
setPublishError(undefined);
setPublishWarning(undefined);
// Custom domain checkboxes are disabled on free plan so they are never
// submitted — only the staging (wstd.io) domain can appear in formData.
- const domains = formData
- .getAll(domainToPublishName)
- .map((domainEntry) => domainEntry.toString());
+ const domains = getDomainsFromForm(formData);
if (domains.length === 0) {
toast.error("Please select at least one domain to publish");
@@ -640,30 +731,22 @@ const Publish = ({
setIsPublishing(true);
try {
- await flushExternalContentProject({ projectId: project.id });
- const { error: auditError, warning: auditWarning } =
- getPrePublishAuditMessages();
- if (auditError !== undefined) {
- toast.error(auditError);
- setPublishError(auditError);
+ const passed = await runPrePublishChecks();
+ if (!passed) {
return;
}
- if (auditWarning !== undefined) {
- showPublishWarning({
- message: auditWarning,
- setWarning: setPublishWarning,
- });
- }
- await showContentDatabasePublishWarning({
- projectId: project.id,
- setWarning: setPublishWarning,
- });
} catch (error) {
const message = getPrePublishErrorMessage(error);
toast.error(message);
setPublishError(message);
return;
}
+ showContentDatabasePublishWarning({
+ diagnostics: nativeClient.build.contentDatabasePublishDiagnostics.query(
+ { projectId: project.id }
+ ),
+ setWarning: setPublishWarning,
+ });
await publish(domains);
});
};
@@ -673,8 +756,7 @@ const Publish = ({
: false;
const isPublishInProgress = isPublishing || hasPendingState;
- const showPendingState =
- isPublishInProgress && (countdown === undefined || countdown === 0);
+ const getForm = () => buttonRef.current?.closest("form");
return (
<Flex gap={2} shrink={false} direction={"column"}>
@@ -685,38 +767,36 @@ const Publish = ({
</PanelBanner>
)}
- <Tooltip
- content={
- isPublishInProgress
- ? "Publish process in progress"
- : hasSelectedDomains
- ? undefined
- : "Select at least one domain to publish"
+ <PublishActions
+ publishButtonRef={buttonRef}
+ validationState={validationState}
+ validateDisabled={disabled || isPublishInProgress}
+ publishDisabled={
+ hasSelectedDomains === false ||
+ disabled ||
+ (restrictedFeatures.size > 0 && hasCustomDomainsSelected) ||
+ userPublishCount >= maxDailyPublishesPerUser
}
- >
- <Button
- ref={buttonRef}
- type="button"
- onClick={() => {
- const form = buttonRef.current?.closest("form");
- if (form) {
- handlePublish(new FormData(form));
- }
- }}
- color="primary"
- state={showPendingState ? "pending" : undefined}
- disabled={
- hasSelectedDomains === false ||
- disabled ||
- (restrictedFeatures.size > 0 && hasCustomDomainsSelected) ||
- userPublishCount >= maxDailyPublishesPerUser
- }
- >
- {countdown !== undefined && countdown > 0
+ publishInProgress={isPublishInProgress}
+ hasSelectedDomains={hasSelectedDomains}
+ publishLabel={
+ countdown !== undefined && countdown > 0
? `Publishing (${countdown}s)`
- : "Publish"}
- </Button>
- </Tooltip>
+ : "Publish"
+ }
+ onValidate={async () => {
+ const form = getForm();
+ if (form) {
+ await handleValidate(new FormData(form));
+ }
+ }}
+ onPublish={() => {
+ const form = getForm();
+ if (form) {
+ handlePublish(new FormData(form));
+ }
+ }}
+ />
</Flex>
);
};
@@ -816,8 +896,11 @@ const PublishStatic = ({
try {
setIsPendingOptimistic(true);
- await showContentDatabasePublishWarning({
- projectId,
+ showContentDatabasePublishWarning({
+ diagnostics:
+ nativeClient.build.contentDatabasePublishDiagnostics.query({
+ projectId,
+ }),
setWarning: setPublishWarning,
});
@@ -1061,9 +1144,14 @@ const UpgradeBanner = ({ hasCustomDomains }: { hasCustomDomains: boolean }) => {
const Content = (props: {
projectId: Project["id"];
onExportClick: () => void;
+ validationState: PublishValidationState;
+ onValidationStateChange: (state: PublishValidationState) => void;
+ isPublishing: boolean;
+ setIsPublishing: (isPublishing: boolean) => void;
}) => {
const restrictedFeatures = useStore($restrictedFeatures);
const [newDomains, setNewDomains] = useState(new Set<string>());
+ const [isAddingDomain, setIsAddingDomain] = useState(false);
const project = useStore($project);
@@ -1087,59 +1175,103 @@ const Content = (props: {
);
return (
- <form>
- <ScrollArea>
- <RadioGroup name="publishDomain">
- <ChangeProjectDomain
- refresh={refreshProject}
- projectState={projectState}
- project={project}
- />
+ <>
+ <PopoverTitle
+ suffix={
+ <PopoverTitleActions>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <SmallIconButton
+ aria-label="Publish options"
+ icon={<EllipsesIcon />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ icon={<PlusIcon />}
+ onSelect={() => setIsAddingDomain(true)}
+ >
+ Add new domain
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ icon={<TerminalIcon />}
+ onSelect={props.onExportClick}
+ >
+ Export
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ icon={<GearIcon />}
+ onSelect={() => $openProjectSettings.set("publish")}
+ >
+ Publish settings
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <PopoverClose />
+ </PopoverTitleActions>
+ }
+ >
+ Publish
+ </PopoverTitle>
+ <form>
+ <ScrollArea>
+ <RadioGroup name="publishDomain">
+ <ChangeProjectDomain
+ refresh={refreshProject}
+ projectState={projectState}
+ project={project}
+ />
- <Domains
- newDomains={newDomains}
- domains={project.domainsVirtual}
+ <Domains
+ newDomains={newDomains}
+ domains={project.domainsVirtual}
+ refresh={refreshProject}
+ project={project}
+ />
+ </RadioGroup>
+ </ScrollArea>
+ <Flex direction="column" justify="end" css={{ height: 0 }}>
+ <Separator />
+ </Flex>
+ <PanelContent as={Flex} direction="column" gap="2">
+ <AddDomain
+ projectId={props.projectId}
+ isOpen={isAddingDomain}
+ onOpenChange={setIsAddingDomain}
refresh={refreshProject}
+ onCreate={(domain) => {
+ setNewDomains((prev) => new Set([...prev, domain]));
+ }}
+ />
+ {isAddingDomain && <Separator />}
+ <UpgradeBanner hasCustomDomains={hasCustomDomains} />
+ {hasUnpublishedDomains && (
+ <PanelBanner>
+ <Flex align="center" gap="1">
+ <InfoCircleIcon color={cssVar("--foreground-primary")} />
+ <Text variant="regularBold">Don't forget to publish</Text>
+ </Flex>
+ <Text>
+ You have a custom domain that hasn't been published yet. Hit
+ publish to make it live.
+ </Text>
+ </PanelBanner>
+ )}
+ <Publish
project={project}
+ refresh={refreshProject}
+ timesLeft={maxDailyPublishesPerUser - userPublishCount}
+ disabled={false}
+ restrictedFeatures={restrictedFeatures}
+ validationState={props.validationState}
+ onValidationStateChange={props.onValidationStateChange}
+ isPublishing={props.isPublishing}
+ setIsPublishing={props.setIsPublishing}
/>
- </RadioGroup>
- </ScrollArea>
- <Flex direction="column" justify="end" css={{ height: 0 }}>
- <Separator />
- </Flex>
- <PanelContent as={Flex} direction="column" gap="2">
- <AddDomain
- projectId={props.projectId}
- refresh={refreshProject}
- onCreate={(domain) => {
- setNewDomains((prev) => {
- return new Set([...prev, domain]);
- });
- }}
- onExportClick={props.onExportClick}
- />
- <UpgradeBanner hasCustomDomains={hasCustomDomains} />
- {hasUnpublishedDomains && (
- <PanelBanner>
- <Flex align="center" gap="1">
- <InfoCircleIcon color={cssVar("--foreground-primary")} />
- <Text variant="regularBold">Don't forget to publish</Text>
- </Flex>
- <Text>
- You have a custom domain that hasn't been published yet. Hit
- publish to make it live.
- </Text>
- </PanelBanner>
- )}
- <Publish
- project={project}
- refresh={refreshProject}
- timesLeft={maxDailyPublishesPerUser - userPublishCount}
- disabled={false}
- restrictedFeatures={restrictedFeatures}
- />
- </PanelContent>
- </form>
+ </PanelContent>
+ </form>
+ </>
);
};
@@ -1363,19 +1495,26 @@ type PublishProps = {
export const PublishButton = ({ projectId }: PublishProps) => {
const publishDialog = useStore($publishDialog);
const authTokenPermissions = useStore($authTokenPermissions);
+ const { validationState, update, reset } = usePublishValidationState(
+ publishDialog === "publish"
+ );
+ const [isPublishing, setIsPublishing] = useOptimistic(false);
const { canPublishToStagingOnly } = useStore($permissions);
const isPublishEnabled =
authTokenPermissions.canPublish || canPublishToStagingOnly;
-
const tooltipContent = isPublishEnabled
? undefined
: "Only the owner, an admin, or content editors with publish permissions can publish projects";
const handleExportClick = () => {
+ reset();
$publishDialog.set("export");
};
const handleOpenChange = (isOpen: boolean) => {
+ if (isOpen === false) {
+ reset();
+ }
$publishDialog.set(isOpen ? "publish" : "none");
};
@@ -1412,26 +1551,14 @@ export const PublishButton = ({ projectId }: PublishProps) => {
)}
{publishDialog === "publish" && (
- <>
- <PopoverTitle
- suffix={
- <PopoverTitleActions>
- <IconButton
- type="button"
- onClick={() => {
- $openProjectSettings.set("publish");
- }}
- >
- <GearIcon />
- </IconButton>
- <PopoverClose />
- </PopoverTitleActions>
- }
- >
- Publish
- </PopoverTitle>
- <Content projectId={projectId} onExportClick={handleExportClick} />
- </>
+ <Content
+ projectId={projectId}
+ onExportClick={handleExportClick}
+ validationState={validationState}
+ onValidationStateChange={update}
+ isPublishing={isPublishing}
+ setIsPublishing={setIsPublishing}
+ />
)}
</PopoverContent>
</Popover>
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index 5229e0d4a6..74ad066fec 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import { z } from "zod";
import { createDefaultPages } from "@webstudio-is/project-build";
import type { CompactBuild } from "@webstudio-is/project-build";
+import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixtures";
import * as projectBuild from "@webstudio-is/project-build/server";
import * as projectApi from "@webstudio-is/project/index.server";
import {
@@ -23,6 +24,7 @@ import { DocumentSourceDiagnosticsError } from "@webstudio-is/content-engine/com
import * as assetUploader from "@webstudio-is/asset-uploader/server";
import { apiRouter, __testing__ } from "./api-router.server";
import * as assetQueryPreview from "./asset-query-preview.server";
+import * as db from "~/shared/db";
import {
getApiRouterProcedures,
getProcedureInputSchemaMetadata,
@@ -859,6 +861,188 @@ describe("api router permits", () => {
).not.toThrow();
});
+ test.each([
+ {
+ target: "staging" as const,
+ domains: ["project.wstd.dev"],
+ expected: ["project.wstd.dev"],
+ },
+ {
+ target: "production" as const,
+ domains: ["custom.example.com"],
+ expected: ["custom.example.com"],
+ },
+ {
+ target: "production" as const,
+ domains: undefined,
+ expected: ["project.wstd.dev", "custom.example.com"],
+ },
+ ])(
+ "validates $target publish domains $domains and content without publishing",
+ async ({ target, domains, expected }) => {
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(
+ createToken({ relation: "editors", canPublish: true })
+ );
+ vi.spyOn(projectApi, "loadById").mockResolvedValue({
+ domain: "project.wstd.dev",
+ domainsVirtual: [
+ { domain: "custom.example.com", status: "ACTIVE", verified: true },
+ ],
+ } as never);
+ const loadBuild = vi
+ .spyOn(projectBuild, "loadDevBuildByProjectId")
+ .mockResolvedValue({
+ dataSources: [],
+ props: [],
+ resources: [],
+ instances: [],
+ } as never);
+ const loadBundle = vi
+ .spyOn(db, "loadProjectBundleByProjectId")
+ .mockResolvedValue(createPublishedProjectBundleFixture());
+ const caller = createCaller(createContext(true));
+
+ await expect(
+ caller.publish.validate({
+ projectId: "project-1",
+ target,
+ domains,
+ })
+ ).resolves.toMatchObject({
+ valid: true,
+ target,
+ domains: expected,
+ diagnostics: { mdxOmissions: [] },
+ });
+ expect(loadBuild).toHaveBeenCalledWith(expect.anything(), "project-1");
+ expect(loadBundle).toHaveBeenCalledWith(
+ "project-1",
+ expect.anything(),
+ expect.objectContaining({
+ onMdxTemplateOmissions: expect.any(Function),
+ })
+ );
+ }
+ );
+
+ test.each(
+ [
+ [],
+ ["unknown.example.com"],
+ ["unverified.example.com"],
+ ["inactive.example.com"],
+ ["project.wstd.dev", "unknown.example.com"],
+ ].map((domains) => ({ domains }))
+ )(
+ "rejects unusable publish domains $domains before loading content",
+ async ({ domains }) => {
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(
+ createToken({ canPublish: true })
+ );
+ vi.spyOn(projectApi, "loadById").mockResolvedValue({
+ domain: "project.wstd.dev",
+ domainsVirtual: [
+ {
+ domain: "unverified.example.com",
+ status: "ACTIVE",
+ verified: false,
+ },
+ { domain: "inactive.example.com", status: "PENDING", verified: true },
+ ],
+ } as never);
+ const loadBuild = vi.spyOn(projectBuild, "loadDevBuildByProjectId");
+ const loadBundle = vi
+ .spyOn(db, "loadProjectBundleByProjectId")
+ .mockResolvedValue(createPublishedProjectBundleFixture());
+ const caller = createCaller(createContext(true));
+
+ await expect(
+ caller.publish.validate({
+ projectId: "project-1",
+ target: "production",
+ domains,
+ })
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ expect(loadBuild).not.toHaveBeenCalled();
+ expect(loadBundle).not.toHaveBeenCalled();
+ }
+ );
+
+ test.each(["variable", "prop"])(
+ "rejects a missing resource referenced by a %s before diagnostics",
+ async (source) => {
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());
+ vi.spyOn(projectApi, "loadById").mockResolvedValue({
+ domain: "project.wstd.dev",
+ domainsVirtual: [],
+ } as never);
+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue({
+ resources: [],
+ instances: [],
+ dataSources:
+ source === "variable"
+ ? [
+ {
+ id: "broken",
+ type: "resource",
+ name: "Broken",
+ scopeInstanceId: "body",
+ resourceId: "missing-resource",
+ },
+ ]
+ : [],
+ props:
+ source === "prop"
+ ? [
+ {
+ id: "broken",
+ instanceId: "body",
+ name: "data",
+ type: "resource",
+ value: "missing-resource",
+ },
+ ]
+ : [],
+ } as never);
+ const loadBundle = vi
+ .spyOn(db, "loadProjectBundleByProjectId")
+ .mockResolvedValue(createPublishedProjectBundleFixture());
+ const caller = createCaller(createContext(true));
+
+ await expect(
+ caller.publish.validate({
+ projectId: "project-1",
+ target: "staging",
+ })
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ expect(loadBundle).not.toHaveBeenCalled();
+ }
+ );
+
+ test("does not run publish diagnostics when the selected domains are forbidden", async () => {
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(
+ createToken({ relation: "builders", canPublish: false })
+ );
+ vi.spyOn(projectApi, "loadById").mockResolvedValue({
+ domain: "project.wstd.dev",
+ } as never);
+ const loadBundle = vi.spyOn(db, "loadProjectBundleByProjectId");
+ const caller = createCaller(createContext(true));
+
+ await expect(
+ caller.publish.validate({
+ projectId: "project-1",
+ target: "production",
+ domains: ["custom.example.com"],
+ })
+ ).rejects.toThrow("Authorization token does not have publish permission");
+ expect(loadBundle).not.toHaveBeenCalled();
+ });
+
test("allows editor api tokens to commit content-mode payloads only", () => {
const build = {
id: "build",
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index f03627c8ad..19291b5874 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -17,6 +17,7 @@ import {
createUnpublishJobId,
deleteProjectDomain,
getDefaultPublishDomains,
+ getVerifiedPublishDomains,
getProjectPublishJob,
listProjectDomains,
listProjectPublishes,
@@ -27,6 +28,8 @@ import {
} from "@webstudio-is/domain/index.server";
import {
getBuilderRuntimeOperationInputSchema,
+ getBuildIntegrityIssues,
+ formatBuildIntegrityError,
paginateOutput,
paginatedOutputInputSchema,
} from "@webstudio-is/project-build/runtime";
@@ -93,6 +96,7 @@ import {
import { createAssetClient } from "../shared/asset-client";
import { previewProjectAssetQuery } from "./asset-query-preview.server";
import { publishConfiguredIssueReport } from "./github-issue-report.server";
+import { loadContentDatabasePublishDiagnostics } from "./content-database-publish-diagnostics.server";
const assertApiPublishDomains = ({
auth,
@@ -1055,6 +1059,56 @@ export const apiRouter = router({
}),
publish: router({
+ validate: projectQuery(
+ projectIdInput.extend({
+ target: z.enum(["staging", "production"]),
+ domains: z.array(z.string()).optional(),
+ }),
+ "edit",
+ async ({ auth, ctx, input }) => {
+ const project = await loadById(input.projectId, ctx);
+ const domains =
+ input.domains ?? getDefaultPublishDomains(project, input.target);
+ assertApiPublishDomains({ auth, domains, project });
+ if (domains.length === 0) {
+ throwApiError(
+ "BAD_REQUEST",
+ "Select at least one domain to publish."
+ );
+ }
+ const verifiedDomains = getVerifiedPublishDomains(project, domains);
+ const invalidDomains = domains.filter(
+ (domain) => verifiedDomains.includes(domain) === false
+ );
+ if (invalidDomains.length > 0) {
+ throwApiError(
+ "BAD_REQUEST",
+ `Publish domains must belong to this project and be active and verified: ${invalidDomains.join(", ")}`
+ );
+ }
+ const build = await loadDevBuildByProjectId(ctx, input.projectId);
+ const issues = getBuildIntegrityIssues(build);
+ if (issues[0] !== undefined) {
+ throwApiError(
+ "BAD_REQUEST",
+ formatBuildIntegrityError(issues[0], "Cannot publish"),
+ { issues }
+ );
+ }
+ const diagnostics = await loadContentDatabasePublishDiagnostics(
+ input.projectId,
+ ctx
+ );
+ return {
+ valid: true,
+ target: input.target,
+ domains,
+ diagnostics,
+ };
+ },
+ { command: "check-publish-readiness", client: "checkPublishReadiness" }
+ ),
+
list: projectQuery(
paginatedProjectInput,
"view",
diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.ts
index fb4db951b6..a5672d8c60 100644
--- a/apps/builder/app/services/build-router.server.ts
+++ b/apps/builder/app/services/build-router.server.ts
@@ -33,7 +33,6 @@ import { removeAgentInstructionsFromProjectSettings } from "@webstudio-is/projec
import { hydrateRestorePointTransaction } from "@webstudio-is/project-build/project-session";
import {
loadProjectBundleByBuildId,
- loadProjectBundleByProjectId,
loadPublishedProjectBundleByProjectId,
} from "~/shared/db";
import {
@@ -50,11 +49,7 @@ import {
commitBuildTransactions,
} from "./api-build.server";
import { assertApiProjectPermit } from "./api-permits.server";
-import {
- getContentDatabasePublishDiagnostics,
- formatMdxTemplatePublishDiagnostics,
-} from "./content-database.server";
-import type { PublishedMdxTemplateOmission } from "@webstudio-is/project-build";
+import { loadContentDatabasePublishDiagnostics } from "./content-database-publish-diagnostics.server";
const projectBundleInput = z.object({
projectId: z.string(),
@@ -107,30 +102,6 @@ const prepareProjectBundleForClient = async (
};
};
-const loadContentDatabasePublishDiagnostics = async (
- projectId: string,
- ctx: AppContext,
- dependencies = { loadProjectBundleByProjectId }
-) => {
- let mdxTemplateOmissions: readonly PublishedMdxTemplateOmission[] = [];
- const bundle = await dependencies.loadProjectBundleByProjectId(
- projectId,
- ctx,
- {
- onMdxTemplateOmissions: (issues) => {
- mdxTemplateOmissions = issues;
- },
- }
- );
- return {
- ...getContentDatabasePublishDiagnostics(bundle),
- mdxOmissions: formatMdxTemplatePublishDiagnostics(
- bundle,
- mdxTemplateOmissions
- ),
- };
-};
-
type ImportProjectBundleDependencies = {
importPublishedProjectBundle: typeof importPublishedProjectBundle;
readStagedUploadText: typeof readStagedUploadText;
diff --git a/apps/builder/app/services/content-database-publish-diagnostics.server.ts b/apps/builder/app/services/content-database-publish-diagnostics.server.ts
new file mode 100644
index 0000000000..efaa4fb946
--- /dev/null
+++ b/apps/builder/app/services/content-database-publish-diagnostics.server.ts
@@ -0,0 +1,33 @@
+import { loadProjectBundleByProjectId } from "~/shared/db";
+import {
+ formatMdxTemplatePublishDiagnostics,
+ getContentDatabasePublishDiagnostics,
+} from "./content-database.server";
+import type { PublishedMdxTemplateOmission } from "@webstudio-is/project-build";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+
+export const loadContentDatabasePublishDiagnostics = async (
+ projectId: string,
+ ctx: AppContext,
+ dependencies: {
+ loadProjectBundleByProjectId: typeof loadProjectBundleByProjectId;
+ } = { loadProjectBundleByProjectId }
+) => {
+ let mdxTemplateOmissions: readonly PublishedMdxTemplateOmission[] = [];
+ const bundle = await dependencies.loadProjectBundleByProjectId(
+ projectId,
+ ctx,
+ {
+ onMdxTemplateOmissions: (issues) => {
+ mdxTemplateOmissions = issues;
+ },
+ }
+ );
+ return {
+ ...getContentDatabasePublishDiagnostics(bundle),
+ mdxOmissions: formatMdxTemplatePublishDiagnostics(
+ bundle,
+ mdxTemplateOmissions
+ ),
+ };
+};
diff --git a/docs/university/foundations/publishing-and-custom-domains.md b/docs/university/foundations/publishing-and-custom-domains.md
index 982ad8960e..dce12094d3 100644
--- a/docs/university/foundations/publishing-and-custom-domains.md
+++ b/docs/university/foundations/publishing-and-custom-domains.md
@@ -80,6 +80,10 @@ You must publish your site _after_ the domain is verified, or else "[Worker not
Keep the Publish dialog open to follow the build and deployment status. Resolve any reported error before trying again.
+Each domain shows a yellow progress icon while publishing and a green checkmark
+once publishing finishes. A red icon indicates a failure. Hover over the icon
+to see the status and when publishing started.
+
Once your site is live, you can visit it by clicking the open icon next to the green checkmark.
---
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index 1d72bc8a07..6e7cc31397 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -211,6 +211,7 @@ const apiCommandOptionsByCommand: Partial<
"delete-resource": apiCommand.deleteResourceCommandOptions,
"list-domains": apiCommand.paginatedListCommandOptions,
publish: apiCommand.publishCommandOptions,
+ "check-publish-readiness": apiCommand.checkPublishReadinessCommandOptions,
"get-publish-job": apiCommand.publishJobCommandOptions,
unpublish: apiCommand.unpublishCommandOptions,
"create-domain": apiCommand.createDomainCommandOptions,
@@ -246,6 +247,10 @@ export const apiCommandMetadata = publicApiOperations.map((operation) => ({
export const highLevelCliCommands = [
{ command: "audit", operation: "audit" },
+ {
+ command: "check-publish-readiness",
+ operation: "check-publish-readiness",
+ },
{ command: "permissions", operation: "permissions" },
{ command: "get-assets-resource", operation: "get-assets-resource" },
{ command: "create-assets-resource", operation: "create-assets-resource" },
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index 7cfdc5c831..204b44726d 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -1767,6 +1767,21 @@ test("publishes project", async () => {
});
});
+test("checks publish readiness without publishing", async () => {
+ await expectCommandCall({
+ options: {
+ command: "check-publish-readiness",
+ target: "production",
+ domain: ["example.com,www.example.com"],
+ },
+ call: apiCalls.checkPublishReadiness,
+ connection: {
+ target: "production",
+ domains: ["example.com", "www.example.com"],
+ },
+ });
+});
+
test("lists publishes", async () => {
await expectCommandCall({
options: { command: "list-publishes" },
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index 5963d45205..d0fe072e84 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -1132,6 +1132,9 @@ export const publishCommandOptions = (yargs: CommonYargsArgv) =>
describe: "Optional idempotency key for retrying the same publish",
});
+export const checkPublishReadinessCommandOptions = (yargs: CommonYargsArgv) =>
+ publishDomainsOption(publishTargetOption(apiCommandOptions(yargs)));
+
export const publishJobCommandOptions = (yargs: CommonYargsArgv) =>
apiCommandOptions(yargs).option("job", {
type: "string",
@@ -2964,6 +2967,18 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
};
return runProjectSessionCommand("publish", input, connection, dependencies);
},
+ "check-publish-readiness": async (options, connection, dependencies) => {
+ const input = {
+ target: publishTargetValue(options.target),
+ domains: listStringOption(options.domain),
+ };
+ return runProjectSessionCommand(
+ "check-publish-readiness",
+ input,
+ connection,
+ dependencies
+ );
+ },
"list-publishes": async (options, connection, dependencies) =>
runProjectSessionCommand(
"list-publishes",
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index bbfbc4ef0c..6f497c5bc8 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -497,7 +497,9 @@ const apiCommandsByArea = {
publishAndDomains: cliCommandMetadata
.filter(
({ cliCommand }) =>
- cliCommand.startsWith("publish ") || cliCommand.startsWith("domains ")
+ cliCommand === "check-publish-readiness" ||
+ cliCommand.startsWith("publish ") ||
+ cliCommand.startsWith("domains ")
)
.map(({ cliCommand }) => cliCommand),
pagesAndSettings: cliCommandMetadata
diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.ts
index 803592f12a..78469800b3 100644
--- a/packages/cli/src/commands/schema.test.ts
+++ b/packages/cli/src/commands/schema.test.ts
@@ -149,7 +149,7 @@ test("prints compact mcp tool summaries as json by default", () => {
inputSchema,
})
);
- expect(JSON.stringify(handshakePayload).length).toBeLessThan(216_000);
+ expect(JSON.stringify(handshakePayload).length).toBeLessThan(217_000);
expect(
JSON.stringify(
expectedTools.find(({ name }) => name === "insert-page-transfer-item")
@@ -167,6 +167,11 @@ test("prints compact mcp tool summaries as json by default", () => {
operationId: "instances.insertFragment",
method: "mutation",
}),
+ expect.objectContaining({
+ name: "check-publish-readiness",
+ operationId: "publish.validate",
+ method: "query",
+ }),
expect.objectContaining({
name: "screenshot.diff",
examples: expect.arrayContaining([
diff --git a/packages/design-system/src/components/button.stories.tsx b/packages/design-system/src/components/button.stories.tsx
index 13e6e57f47..f6326ccfa9 100644
--- a/packages/design-system/src/components/button.stories.tsx
+++ b/packages/design-system/src/components/button.stories.tsx
@@ -12,6 +12,7 @@ export default {
const colors: ReadonlyArray<ComponentProps<typeof ButtonComponent>["color"]> = [
"primary",
+ "positive",
"neutral",
"destructive",
"neutral-destructive",
diff --git a/packages/design-system/src/components/button.tsx b/packages/design-system/src/components/button.tsx
index 11b4e83149..f95486767c 100644
--- a/packages/design-system/src/components/button.tsx
+++ b/packages/design-system/src/components/button.tsx
@@ -21,6 +21,7 @@ import {
const colors = [
"primary",
+ "positive",
"destructive",
"neutral",
"ghost",
@@ -44,6 +45,7 @@ const chromaticPressedOverlay = `oklch(from ${cssVar(
const backgrounds: Record<ButtonColor, string> = {
primary: cssVar("--background-accent"),
+ positive: cssVar("--background-positive"),
neutral: neutralControlBackground,
"neutral-destructive": neutralControlBackground,
destructive: cssVar("--background-negative"),
@@ -53,6 +55,7 @@ const backgrounds: Record<ButtonColor, string> = {
const foregrounds: Record<ButtonColor, string> = {
primary: cssVar("--foreground-on-accent"),
+ positive: cssVar("--foreground-on-positive"),
destructive: cssVar("--foreground-on-negative"),
"neutral-destructive": cssVar("--foreground-negative"),
neutral: cssVar("--foreground-primary"),
@@ -62,7 +65,10 @@ const foregrounds: Record<ButtonColor, string> = {
const perColorStyle = (variant: ButtonColor) => {
const isTransparent = variant === "ghost" || variant === "ghost-destructive";
- const isChromatic = variant === "primary" || variant === "destructive";
+ const isChromatic =
+ variant === "primary" ||
+ variant === "positive" ||
+ variant === "destructive";
let hoverOverlay = cssVar("--overlay-interaction-hover");
let pressedOverlay = cssVar("--overlay-interaction-pressed");
if (isChromatic) {
@@ -131,6 +137,7 @@ export const buttonStyle = css({
variants: {
color: {
primary: perColorStyle("primary"),
+ positive: perColorStyle("positive"),
destructive: perColorStyle("destructive"),
"neutral-destructive": perColorStyle("neutral-destructive"),
neutral: perColorStyle("neutral"),
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index c164552750..d2014c2599 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -91,6 +91,7 @@ import {
loadProjectBundleByProjectId,
moveInstance,
publish,
+ checkPublishReadiness,
readProjectAssetContent,
parseBuildPatchTransactions,
parseBuilderUrl,
@@ -772,6 +773,11 @@ test("wraps project api trpc calls in named functions", async () => {
scopeInstanceId: "body-id",
});
await listPublishes(params);
+ await checkPublishReadiness({
+ ...params,
+ target: "production",
+ domains: ["example.com"],
+ });
await publish({
...params,
target: "production",
@@ -1007,6 +1013,7 @@ test("wraps project api trpc calls in named functions", async () => {
expectRequest("/trpc/api.variables.list"),
expectRequest("/trpc/api.resources.list"),
expectRequest("/trpc/api.publish.list"),
+ expectRequest("/trpc/api.publish.validate"),
expectBodyRequest(
"/trpc/api.publish.create",
'"idempotencyKey":"publish-key"'
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 0abbdf2d9b..7ef4fc0868 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -2234,6 +2234,13 @@ export const listPublishes = projectQueryInput<
AuthProjectParams & PaginatedQueryInput
>("list-publishes");
+export const checkPublishReadiness = projectQueryInput<
+ AuthProjectParams & {
+ target: "staging" | "production";
+ domains?: string[];
+ }
+>("check-publish-readiness");
+
export const publish = projectMutationInput<
AuthProjectParams & {
target: "staging" | "production";
diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
index 41c4240e73..96f1cbfd0e 100644
--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
@@ -1399,6 +1399,30 @@ export const serverOnlyRouterOperationMetadata = {
additionalProperties: true,
},
},
+ "publish.validate": {
+ id: "publish.validate",
+ command: "check-publish-readiness",
+ method: "query",
+ path: "api.publish.validate",
+ client: "checkPublishReadiness",
+ permit: "edit",
+ inputSchema: {
+ type: "object",
+ properties: {
+ target: {
+ type: "string",
+ enum: ["staging", "production"],
+ },
+ domains: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["target"],
+ },
+ },
"publish.list": {
id: "publish.list",
command: "list-publishes",
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index ce10547e3b..31dd77d2af 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -694,6 +694,16 @@ const curatedPublicApiOperationDocumentation = [
requiredOptions: ["resource", "json"],
examples: ["webstudio delete-resource --resource resource-id --json"],
},
+ {
+ command: "check-publish-readiness",
+ description:
+ "Check publish access, selected domains, and content diagnostics without starting a publish. Use audit for project-wide quality checks.",
+ requiredOptions: ["target", "json"],
+ examples: [
+ "webstudio check-publish-readiness --target production --json",
+ 'MCP tool: check-publish-readiness {"target":"production"}',
+ ],
+ },
{
command: "publish",
description: