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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Preview by publishing to subdomain only aka staging (#4143)
Ivan Starkov6ba6fc5ce8f8
diff --git a/apps/builder/app/builder/features/topbar/add-domain.tsx b/apps/builder/app/builder/features/topbar/add-domain.tsxindex 8a87a750e2..269c547e3c 100644--- a/apps/builder/app/builder/features/topbar/add-domain.tsx+++ b/apps/builder/app/builder/features/topbar/add-domain.tsx@@ -7,46 +7,38 @@ import {theme,Text,Grid,+ toast,} from "@webstudio-is/design-system";import { validateDomain } from "@webstudio-is/domain";import type { Project } from "@webstudio-is/project";-import { useId, useState } from "react";+import { useId, useOptimistic, useRef, useState } from "react";import { CustomCodeIcon } from "@webstudio-is/icons";-import { trpcClient } from "~/shared/trpc/trpc-client";+import { nativeClient } from "~/shared/trpc/trpc-client";type DomainsAddProps = {projectId: Project["id"];onCreate: (domain: string) => void;onExportClick: () => void;- refreshDomainResult: (- input: { projectId: Project["id"] },- onSuccess: () => void- ) => void;- domainState: "idle" | "submitting";- isPublishing: boolean;+ refresh: () => Promise<void>;};export const AddDomain = ({projectId,onCreate,- refreshDomainResult,- domainState,- isPublishing,+ refresh,onExportClick,}: DomainsAddProps) => {const id = useId();- const {- send: create,- state: сreateState,- error: сreateSystemError,- } = trpcClient.domain.create.useMutation();const [isOpen, setIsOpen] = useState(false);- const [domain, setDomain] = useState("");const [error, setError] = useState<string>();+ const buttonRef = useRef<HTMLButtonElement>(null);+ const [isPending, setIsPendingOptimistic] = useOptimistic(false);- const handleCreate = () => {- setError(undefined);+ const handleCreateDomain = async (formData: FormData) => {+ // Will be automatically reset on action end+ setIsPendingOptimistic(true);+ const domain = formData.get("domain")?.toString() ?? "";const validationResult = validateDomain(domain);if (validationResult.success === false) {@@ -54,18 +46,22 @@ export const AddDomain = ({return;}- create({ domain: validationResult.domain, projectId }, (data) => {- if (data.success === false) {- setError(data.error);- return;- }-- refreshDomainResult({ projectId }, () => {- setDomain("");- setIsOpen(false);- onCreate(validationResult.domain);- });+ const result = await nativeClient.domain.create.mutate({+ domain,+ projectId,});++ if (result.success === false) {+ toast.error(result.error);+ setError(result.error);+ return;+ }++ onCreate(domain);++ await refresh();++ setIsOpen(false);};return (@@ -81,7 +77,6 @@ export const AddDomain = ({direction={"column"}onKeyDown={(event) => {if (event.key === "Escape") {- setDomain("");setIsOpen(false);event.preventDefault();}@@ -94,26 +89,21 @@ export const AddDomain = ({</Label><InputFieldid={id}+ name="domain"autoFocusplaceholder="your-domain.com"- value={domain}- disabled={- isPublishing || сreateState !== "idle" || domainState !== "idle"- }+ disabled={isPending}onKeyDown={(event) => {if (event.key === "Enter") {- handleCreate();+ buttonRef.current+ ?.closest("form")+ ?.requestSubmit(buttonRef.current);}if (event.key === "Escape") {- setDomain("");setIsOpen(false);event.preventDefault();}}}- onChange={(event) => {- setError(undefined);- setDomain(event.target.value);- }}color={error !== undefined ? "error" : undefined}/>{error !== undefined && (@@ -121,29 +111,21 @@ export const AddDomain = ({<Text color="destructive">{error}</Text></>)}- {сreateSystemError !== undefined && (- <>- {/* Something happened with network, api etc */}- <Text color="destructive">{сreateSystemError}</Text>- <Text color="subtle">Please try again later</Text>- </>- )}</>)}<Grid gap={2} columns={2}><Button- disabled={- isPublishing || сreateState !== "idle" || domainState !== "idle"- }+ ref={buttonRef}+ formAction={handleCreateDomain}+ state={isPending ? "pending" : undefined}color={isOpen ? "primary" : "neutral"}- onClick={() => {+ onClick={(event) => {if (isOpen === false) {setIsOpen(true);+ event.preventDefault();return;}-- handleCreate();}}>{isOpen ? "Add domain" : "Add a new domain"}@@ -152,6 +134,7 @@ export const AddDomain = ({<Buttoncolor={"dark"}prefix={<CustomCodeIcon />}+ type="button"onClick={onExportClick}>Exportdiff --git a/apps/builder/app/builder/features/topbar/collapsible-domain-section.tsx b/apps/builder/app/builder/features/topbar/collapsible-domain-section.tsxindex 72da9b5485..717d85d6cf 100644--- a/apps/builder/app/builder/features/topbar/collapsible-domain-section.tsx+++ b/apps/builder/app/builder/features/topbar/collapsible-domain-section.tsx@@ -4,6 +4,7 @@ import {Label,theme,SectionTitle,+ Grid,} from "@webstudio-is/design-system";import { useEffect, useRef, useState, type ReactNode } from "react";import { CollapsibleSectionRoot } from "~/builder/shared/collapsible-section";@@ -13,9 +14,11 @@ export const CollapsibleDomainSection = ({children,title,suffix,+ prefix,}: {initiallyOpen?: boolean;children: ReactNode;+ prefix: ReactNode;suffix: ReactNode;title: string;}) => {@@ -53,7 +56,10 @@ export const CollapsibleDomainSection = ({</Box>}>- <Label truncate>{title}</Label>+ <Grid flow={"column"} align="center" justify={"start"}>+ {prefix}+ <Label truncate>{title}</Label>+ </Grid></SectionTitle>}>diff --git a/apps/builder/app/builder/features/topbar/domain-checkbox.tsx b/apps/builder/app/builder/features/topbar/domain-checkbox.tsxnew file mode 100644index 0000000000..cb8e986fa1--- /dev/null+++ b/apps/builder/app/builder/features/topbar/domain-checkbox.tsx@@ -0,0 +1,82 @@+import { useStore } from "@nanostores/react";+import {+ Flex,+ Tooltip,+ Text,+ theme,+ Link,+ buttonStyle,+ Checkbox,+} from "@webstudio-is/design-system";+import { $userPlanFeatures } from "~/builder/shared/nano-states";+import { $project } from "~/shared/nano-states";++export const domainToPublishName = "domainToPublish[]";++interface DomainCheckboxProps {+ defaultChecked?: boolean;+ domain: string;+ buildId: string | undefined;+ disabled?: boolean;+}++const DomainCheckbox = (props: DomainCheckboxProps) => {+ const hasProPlan = useStore($userPlanFeatures).hasProPlan;+ const project = useStore($project);++ if (project === undefined) {+ return;+ }++ const tooltipContentForFreeUsers = hasProPlan ? undefined : (+ <Flex direction="column" gap="2" css={{ maxWidth: theme.spacing[28] }}>+ <Text variant="titles">Publish to Staging</Text>+ <Text>+ <Flex direction="column">+ Staging allows you to preview a production version of your site+ without potentially breaking what production site visitors will see.+ <>+ <br />+ <br />+ Upgrade to Pro account to publish to each domain individually.+ <br /> <br />+ <Link+ className={buttonStyle({ color: "gradient" })}+ color="contrast"+ underline="none"+ href="https://webstudio.is/pricing"+ target="_blank"+ >+ Upgrade+ </Link>+ </>+ </Flex>+ </Text>+ </Flex>+ );++ const defaultChecked = hasProPlan ? props.defaultChecked : true;+ const disabled = hasProPlan ? props.disabled : true;++ const hideDomainCheckbox =+ project.domainsVirtual.filter(+ (domain) => domain.status === "ACTIVE" && domain.verified+ ).length === 0 && hasProPlan;++ return (+ <div style={{ display: hideDomainCheckbox ? "none" : "contents" }}>+ <Tooltip content={tooltipContentForFreeUsers} variant="wrapped">+ <Checkbox+ disabled={disabled}+ key={props.buildId ?? "-"}+ defaultChecked={hideDomainCheckbox || defaultChecked}+ css={{ pointerEvents: "all" }}+ name={domainToPublishName}+ value={props.domain}+ />+ </Tooltip>+ </div>+ );+};++export default DomainCheckbox;diff --git a/apps/builder/app/builder/features/topbar/domains.tsx b/apps/builder/app/builder/features/topbar/domains.tsxindex 3efbf74d8d..00264c68e1 100644--- a/apps/builder/app/builder/features/topbar/domains.tsx+++ b/apps/builder/app/builder/features/topbar/domains.tsx@@ -10,6 +10,7 @@ import {Flex,NestedInputButton,Separator,+ toast,} from "@webstudio-is/design-system";import type { Project } from "@webstudio-is/project";import {@@ -20,14 +21,21 @@ import {} from "@webstudio-is/icons";import type { DomainStatus } from "@webstudio-is/prisma-client";import { CollapsibleDomainSection } from "./collapsible-domain-section";-import { useCallback, useEffect, useState } from "react";+import {+ startTransition,+ useEffect,+ useOptimistic,+ useRef,+ useState,+} from "react";import { formatDistance } from "date-fns/formatDistance";import { Entri } from "./entri";-import { trpcClient } from "~/shared/trpc/trpc-client";+import { nativeClient } from "~/shared/trpc/trpc-client";import { useStore } from "@nanostores/react";import { $publisherHost } from "~/shared/nano-states";import { extractCname } from "./cname";-import type { Database } from "@webstudio-is/postrest/index.server";+import { useEffectEvent } from "~/shared/hook-utils/effect-event";+import DomainCheckbox from "./domain-checkbox";export type Domain = Project["domainsVirtual"][number];@@ -41,6 +49,7 @@ const CopyToClipboard = (props: { text: string }) => {return (<Tooltip content={"Copy to clipboard"}><NestedInputButton+ type="button"onClick={() => {navigator.clipboard.writeText(props.text);}}@@ -59,40 +68,6 @@ export const getStatus = (projectDomain: Domain) =>export const PENDING_TIMEOUT =process.env.NODE_ENV === "production" ? 60 * 3 * 1000 : 35000;-export const getPublishStatusAndTextNew = ({- createdAt,- publishStatus,-}: Pick<- Database["public"]["Tables"]["latestBuildVirtual"]["Row"],- "createdAt" | "publishStatus"->) => {- let status = publishStatus;-- const delta = Date.now() - new Date(createdAt).getTime();- // Assume build failed after 3 minutes-- if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) {- status = "FAILED";- }-- const textStart =- status === "PUBLISHED"- ? "Published"- : status === "FAILED"- ? "Publish failed"- : "Publishing started";-- const statusText = `${textStart} ${formatDistance(- new Date(createdAt),- new Date(),- {- addSuffix: true,- }- )}`;-- return { statusText, status };-};-export const getPublishStatusAndText = ({createdAt,publishStatus,@@ -207,151 +182,113 @@ const StatusIcon = (props: { projectDomain: Domain; isLoading: boolean }) => {const DomainItem = (props: {initiallyOpen: boolean;projectDomain: Domain;- refreshDomainResult: (- input: { projectId: Project["id"] },- onSuccess?: () => void- ) => void;- domainState: "idle" | "submitting";- isPublishing: boolean;+ refresh: () => Promise<void>;+ project: Project;}) => {- const {- send: verify,- state: verifyState,- data: verifyData,- error: verifySystemError,- } = trpcClient.domain.verify.useMutation();-- const {- send: remove,- state: removeState,- data: removeData,- error: removeSystemError,- } = trpcClient.domain.remove.useMutation();-- const {- send: updateStatus,- state: updateStatusState,- data: updateStatusData,- error: updateStatusError,- } = trpcClient.domain.updateStatus.useMutation();-- const [isStatusLoading, setIsStatusLoading] = useState(true);-- const isRemoveInProgress =- removeState !== "idle" || props.domainState !== "idle";-- const isCheckStateInProgress =- verifyState !== "idle" ||- updateStatusState !== "idle" ||- props.domainState !== "idle";+ const timeSinceLastUpdateMs =+ Date.now() - new Date(props.projectDomain.updatedAt).getTime();++ const DAY_IN_MS = 24 * 60 * 60 * 1000;const status = props.projectDomain.verified? (`VERIFIED_${props.projectDomain.status}` as `VERIFIED_${DomainStatus}`): `UNVERIFIED`;- const { initiallyOpen } = props;-- const domainId = props.projectDomain.domainId;- const domain = props.projectDomain.domain;- const domainStatus = props.projectDomain.status;- const domainError = props.projectDomain.error;- const domainUpdatedAt = props.projectDomain.updatedAt;-- const projectId = props.projectDomain.projectId;- // const domain-- const refreshDomainResult = props.refreshDomainResult;-- // @todo this should gone https://github.com/webstudio-is/webstudio/issues/1723- const handleVerify = useCallback(() => {- verify(- {- domainId,- projectId,- },- (verifyResponse) => {- setIsStatusLoading(false);-- if (verifyResponse.success) {- refreshDomainResult({- projectId,- });- }- }- );- }, [domainId, projectId, refreshDomainResult, verify]);-- // @todo this should gone https://github.com/webstudio-is/webstudio/issues/1723- const handleUpdateStatus = useCallback(() => {- updateStatus(- {- domain,- projectId,- },- (data) => {- setIsStatusLoading(false);-- if (data.success) {- if (- domainStatus !== data.domain.status ||- domainError !== data.domain.error- ) {- refreshDomainResult({- projectId,- });- }- }- }- );- }, [- domain,- domainError,- domainStatus,- projectId,- refreshDomainResult,- updateStatus,- ]);-- // @todo this should gone https://github.com/webstudio-is/webstudio/issues/1723- useEffect(() => {- if (initiallyOpen) {- setIsStatusLoading(false);+ const [isStatusLoading, setIsStatusLoading] = useState(+ props.initiallyOpen ||+ status === "VERIFIED_ACTIVE" ||+ timeSinceLastUpdateMs > DAY_IN_MS+ ? false+ : true+ );++ const [isCheckStateInProgress, setIsCheckStateInProgress] =+ useOptimistic(false);++ const [isRemoveInProgress, setIsRemoveInProgress] = useOptimistic(false);++ const handleRemoveDomain = async () => {+ setIsRemoveInProgress(true);+ const result = await nativeClient.domain.remove.mutate({+ projectId: props.projectDomain.projectId,+ domainId: props.projectDomain.domainId,+ });++ if (result.success === false) {+ toast.error(result.error);return;}- if (status === "VERIFIED_ACTIVE") {- setIsStatusLoading(false);+ await props.refresh();+ };++ const [verifyError, setVerifyError] = useState<string | undefined>(undefined);++ const handleVerify = useEffectEvent(async () => {+ setVerifyError(undefined);+ setIsCheckStateInProgress(true);++ const verifyResult = await nativeClient.domain.verify.mutate({+ projectId: props.projectDomain.projectId,+ domainId: props.projectDomain.domainId,+ });++ if (verifyResult.success === false) {+ setVerifyError(verifyResult.error);return;}- const timeSinceLastUpdateMs =- Date.now() - new Date(domainUpdatedAt).getTime();+ await props.refresh();+ });++ const [updateStatusError, setUpdateStatusError] = useState<+ string | undefined+ >(undefined);++ const handleUpdateStatus = useEffectEvent(async () => {+ setUpdateStatusError(undefined);+ setIsCheckStateInProgress(true);++ const updateStatusResult = await nativeClient.domain.updateStatus.mutate({+ projectId: props.projectDomain.projectId,+ domain: props.projectDomain.domain,+ });++ setIsStatusLoading(false);- const DAY_IN_MS = 24 * 60 * 60 * 1000;- // Do not check status if it updated more than one day ago- if (timeSinceLastUpdateMs > DAY_IN_MS) {- setIsStatusLoading(false);+ if (updateStatusResult.success === false) {+ setUpdateStatusError(updateStatusResult.error);return;}- if (status === "UNVERIFIED") {- handleVerify();+ await props.refresh();+ });++ const onceRef = useRef(false);+ useEffect(() => {+ if (onceRef.current) {return;}+ onceRef.current = true;- handleUpdateStatus();+ if (isStatusLoading === false) {+ return;+ }- // Update status automatically- }, [- status,- initiallyOpen,- handleVerify,- handleUpdateStatus,- domainUpdatedAt,- ]);+ if (status === "UNVERIFIED") {+ startTransition(async () => {+ await handleVerify();+ await handleUpdateStatus();+ });+ return;+ }+ startTransition(async () => {+ await handleUpdateStatus();+ });+ }, [status, handleVerify, handleUpdateStatus, isStatusLoading]);const publisherHost = useStore($publisherHost);- const cnameEntryName = extractCname(domain);+ const cnameEntryName = extractCname(props.projectDomain.domain);const cnameEntryValue = `${props.projectDomain.cname}.customers.${publisherHost}`;const txtEntryName =@@ -359,10 +296,7 @@ const DomainItem = (props: {? "_webstudio_is": `_webstudio_is.${cnameEntryName}`;- const { isVerifiedActive, text } = getStatusText({- projectDomain: props.projectDomain,- isLoading: false,- });+ const domainStatus = getStatus(props.projectDomain);const cnameRecord = {type: "CNAME",@@ -380,10 +314,27 @@ const DomainItem = (props: {const dnsRecords = [cnameRecord, txtRecord];+ const { isVerifiedActive, text } = getStatusText({+ projectDomain: props.projectDomain,+ isLoading: false,+ });+return (<CollapsibleDomainSection+ prefix={+ <DomainCheckbox+ buildId={props.projectDomain.latestBuildVirtual?.buildId}+ defaultChecked={+ props.projectDomain.latestBuildVirtual?.buildId != null &&+ props.projectDomain.latestBuildVirtual?.buildId ===+ props.project.latestBuildVirtual?.buildId+ }+ domain={props.projectDomain.domain}+ disabled={domainStatus !== "VERIFIED_ACTIVE"}+ />+ }initiallyOpen={props.initiallyOpen}- title={domain}+ title={props.projectDomain.domain}suffix={<Grid flow="column"><StatusIcon@@ -391,12 +342,12 @@ const DomainItem = (props: {projectDomain={props.projectDomain}/>- <Tooltip content={`Proceed to ${domain}`}>+ <Tooltip content={`Proceed to ${props.projectDomain.domain}`}><IconButtontabIndex={-1}disabled={status !== "VERIFIED_ACTIVE"}onClick={(event) => {- const url = new URL(`https://${domain}`);+ const url = new URL(`https://${props.projectDomain.domain}`);window.open(url.href, "_blank");event.preventDefault();}}@@ -409,14 +360,11 @@ const DomainItem = (props: {>{status === "UNVERIFIED" && (<>- {verifySystemError !== undefined && (- <Text color="destructive">{verifySystemError}</Text>- )}<Button- disabled={props.isPublishing || isCheckStateInProgress}+ formAction={handleVerify}+ state={isCheckStateInProgress ? "pending" : undefined}color="primary"css={{ width: "100%", flexShrink: 0, mt: theme.spacing[3] }}- onClick={handleVerify}>Check status</Button>@@ -425,40 +373,25 @@ const DomainItem = (props: {{status !== "UNVERIFIED" && (<>- {updateStatusData?.success === false && (- <Text color="destructive">{updateStatusData.error}</Text>- )}- {updateStatusError !== undefined && (+ {updateStatusError && (<Text color="destructive">{updateStatusError}</Text>)}<Button- disabled={props.isPublishing || isCheckStateInProgress}+ formAction={handleUpdateStatus}+ state={isCheckStateInProgress ? "pending" : undefined}color="primary"css={{ width: "100%", flexShrink: 0, mt: theme.spacing[3] }}- onClick={handleUpdateStatus}>Check status</Button></>)}- {removeData?.success === false && (- <Text color="destructive">{removeData.error}</Text>- )}-- {removeSystemError !== undefined && (- <Text color="destructive">{removeSystemError}</Text>- )}-<Button- disabled={props.isPublishing || isRemoveInProgress}+ formAction={handleRemoveDomain}+ state={isRemoveInProgress ? "pending" : undefined}color="neutral"css={{ width: "100%", flexShrink: 0 }}- onClick={() => {- remove({ projectId, domainId }, () => {- props.refreshDomainResult({ projectId });- });- }}>Remove domain</Button>@@ -467,11 +400,11 @@ const DomainItem = (props: {<Grid gap={1}>{status === "UNVERIFIED" && (<>- {verifyData?.success === false ? (+ {verifyError ? (<Text color="destructive">Status: Failed to verify<br />- {verifyData.error}+ {verifyError}</Text>) : (<>@@ -558,18 +491,21 @@ const DomainItem = (props: {<EntridnsRecords={dnsRecords}- domain={domain}+ domain={props.projectDomain.domain}onClose={() => {// Sometimes Entri modal dialog hangs even if it's successful,// until they fix that, we'll just refresh the status here on every onClose eventif (status === "UNVERIFIED") {- handleVerify();+ startTransition(async () => {+ await handleVerify();+ await handleUpdateStatus();+ });return;}-- handleUpdateStatus();+ startTransition(async () => {+ await handleUpdateStatus();+ });}}- isPublishing={props.isPublishing}/></Grid></CollapsibleDomainSection>@@ -579,20 +515,15 @@ const DomainItem = (props: {type DomainsProps = {newDomains: Set<string>;domains: Domain[];- refreshDomainResult: (- input: { projectId: Project["id"] },- onSuccess?: () => void- ) => void;- domainState: "idle" | "submitting";- isPublishing: boolean;+ refresh: () => Promise<void>;+ project: Project;};export const Domains = ({newDomains,domains,- refreshDomainResult,- domainState,- isPublishing,+ refresh,+ project,}: DomainsProps) => {return (<>@@ -601,9 +532,8 @@ export const Domains = ({key={projectDomain.domain}projectDomain={projectDomain}initiallyOpen={newDomains.has(projectDomain.domain)}- refreshDomainResult={refreshDomainResult}- domainState={domainState}- isPublishing={isPublishing}+ refresh={refresh}+ project={project}/>))}</>diff --git a/apps/builder/app/builder/features/topbar/entri.tsx b/apps/builder/app/builder/features/topbar/entri.tsxindex c57824cca0..cffbf3c01f 100644--- a/apps/builder/app/builder/features/topbar/entri.tsx+++ b/apps/builder/app/builder/features/topbar/entri.tsx@@ -10,12 +10,10 @@ export const Entri = ({dnsRecords,domain,onClose,- isPublishing,}: {dnsRecords: DnsRecord[];domain: string;onClose: (detail: EntriCloseDetail) => void;- isPublishing: boolean;}) => {entriGlobalStyles();const { error, isOpen, showDialog } = useEntri({@@ -29,9 +27,10 @@ export const Entri = ({{error !== undefined && <Text color="destructive">{error}</Text>}<Button- disabled={isOpen || isPublishing}+ disabled={isOpen}color="neutral"css={{ width: "100%", flexShrink: 0 }}+ type="button"onClick={() => {showDialog();}}diff --git a/apps/builder/app/builder/features/topbar/publish.tsx b/apps/builder/app/builder/features/topbar/publish.tsxindex dde88e9efc..b355de9f7b 100644--- a/apps/builder/app/builder/features/topbar/publish.tsx+++ b/apps/builder/app/builder/features/topbar/publish.tsx@@ -1,10 +1,10 @@import {- useCallback,useEffect,- useMemo,useState,useOptimistic,useTransition,+ startTransition,+ useRef,} from "react";import { useStore } from "@nanostores/react";import {@@ -24,7 +24,6 @@ import {InputField,Separator,ScrollArea,- Box,rawTheme,Select,theme,@@ -33,6 +32,7 @@ import {PanelBanner,buttonStyle,toast,+ RadioGroup,} from "@webstudio-is/design-system";import stripIndent from "strip-indent";import {@@ -41,13 +41,7 @@ import {} from "../../shared/nano-states";import { validateProjectDomain, type Project } from "@webstudio-is/project";import { $authPermit, $project, $publishedOrigin } from "~/shared/nano-states";-import {- Domains,- getStatus,- type Domain,- PENDING_TIMEOUT,- getPublishStatusAndTextNew,-} from "./domains";+import { Domains, PENDING_TIMEOUT, getPublishStatusAndText } from "./domains";import { CollapsibleDomainSection } from "./collapsible-domain-section";import {CheckCircleIcon,@@ -61,74 +55,27 @@ import { trpcClient, nativeClient } from "~/shared/trpc/trpc-client";import { isFeatureEnabled } from "@webstudio-is/feature-flags";import type { Templates } from "@webstudio-is/sdk";import { formatDistance } from "date-fns/formatDistance";--type ProjectData =- | {- success: true;- project: Project;- }- | {- success: false;- error: string;- };+import DomainCheckbox, { domainToPublishName } from "./domain-checkbox";type ChangeProjectDomainProps = {project: Project;projectState: "idle" | "submitting";- isPublishing: boolean;- projectLoad: (- props: { projectId: Project["id"] },- callback: (projectData: ProjectData) => void- ) => void;+ refresh: () => void;};-type TimeoutId = undefined | ReturnType<typeof setTimeout>;-const ChangeProjectDomain = ({project,- projectLoad,- projectState,- isPublishing,+ refresh,}: ChangeProjectDomainProps) => {const id = useId();const publishedOrigin = useStore($publishedOrigin);- const {- send: updateProjectDomain,- state: updateProjectDomainState,- error: updateProjectSystemError,- } = trpcClient.domain.updateProjectDomain.useMutation();-const [domain, setDomain] = useState(project.domain);const [error, setError] = useState<string>();+ const [isUpdateInProgress, setIsUpdateInProgress] = useOptimistic(false);- const refreshProject = useCallback(- () =>- projectLoad({ projectId: project.id }, (projectData) => {- if (projectData?.success === false) {- setError(projectData.error);- return;- }-- const currenProject = $project.get();-- if (currenProject?.id === projectData.project.id) {- $project.set({- ...currenProject,- domain: projectData.project.domain,- });- }-- setDomain(projectData.project.domain);- }),- [projectLoad, project.id]- );-- useEffect(() => {- refreshProject();- }, [refreshProject]);-- const handleUpdateProjectDomain = () => {+ const updateProjectDomain = async () => {+ setIsUpdateInProgress(true);const validationResult = validateProjectDomain(domain);if (validationResult.success === false) {@@ -136,26 +83,28 @@ const ChangeProjectDomain = ({return;}- if (updateProjectDomainState !== "idle") {- return;- }- if (domain === project.domain) {+ const updateResult = await nativeClient.domain.updateProjectDomain.mutate({+ domain,+ projectId: project.id,+ });++ if (updateResult.success === false) {+ setError(updateResult.error);return;}- updateProjectDomain({ domain, projectId: project.id }, (data) => {- if (data?.success === false) {- setError(data.error);- return;- }+ await refresh();+ };- refreshProject();+ const handleUpdateProjectDomain = () => {+ startTransition(async () => {+ await updateProjectDomain();});};const { statusText, status } =project.latestBuildVirtual != null- ? getPublishStatusAndTextNew(project.latestBuildVirtual)+ ? getPublishStatusAndText(project.latestBuildVirtual): {statusText: "Not published",status: "PENDING" as const,@@ -164,8 +113,15 @@ const ChangeProjectDomain = ({return (<CollapsibleDomainSectiontitle={new URL(publishedOrigin).host}+ prefix={+ <DomainCheckbox+ defaultChecked={project.latestBuildVirtual?.domain === domain}+ buildId={project.latestBuildVirtual?.buildId}+ domain={domain}+ />+ }suffix={- <Grid flow="column">+ <Grid flow="column" align="center"><Tooltip content={error !== undefined ? error : statusText}><Flexalign={"center"}@@ -190,7 +146,6 @@ const ChangeProjectDomain = ({<Tooltip content={`Proceed to ${publishedOrigin}`}><IconButtontabIndex={-1}- disabled={error !== undefined || status !== "PUBLISHED"}onClick={(event) => {window.open(publishedOrigin, "_blank");event.preventDefault();@@ -210,11 +165,7 @@ const ChangeProjectDomain = ({id={id}placeholder="Domain"value={domain}- disabled={- isPublishing ||- updateProjectDomainState !== "idle" ||- projectState !== "idle"- }+ disabled={isUpdateInProgress}onChange={(event) => {setError(undefined);setDomain(event.target.value);@@ -232,16 +183,9 @@ const ChangeProjectDomain = ({}}}}- color={- error !== undefined || updateProjectSystemError !== undefined- ? "error"- : undefined- }+ color={error !== undefined ? "error" : undefined}/>{error !== undefined && <Text color="destructive">{error}</Text>}- {updateProjectSystemError !== undefined && (- <Text color="destructive">{updateProjectSystemError}</Text>- )}</Grid></Grid></CollapsibleDomainSection>@@ -250,55 +194,135 @@ const ChangeProjectDomain = ({const Publish = ({project,- domainsToPublish,refresh,-- isPublishing,- setIsPublishing,}: {project: Project;- domainsToPublish: Domain[];- refresh: () => void;- isPublishing: boolean;- setIsPublishing: (isPublishing: boolean) => void;+ refresh: () => Promise<void>;}) => {- const {- send: publish,- state: publishState,- data: publishData,- error: publishSystemError,- } = trpcClient.domain.publish.useMutation();+ const [publishError, setPublishError] = useState<string | undefined>();+ const [isPublishing, setIsPublishing] = useOptimistic(false);+ const buttonRef = useRef<HTMLButtonElement>(null);+ const [hasSelectedDomains, setHasSelectedDomains] = useState(false);+ const hasProPlan = useStore($userPlanFeatures).hasProPlan;useEffect(() => {- if (isPublishing) {- let timeoutHandle: TimeoutId;- let totalCalls = 0;- const timeout = 10000;- // Repeat few more times than timeout- const repeat = PENDING_TIMEOUT / timeout + 5;-- // Call refresh- const execRefresh = () => {- if (totalCalls < repeat) {- totalCalls += 1;- clearTimeout(timeoutHandle);- timeoutHandle = setTimeout(() => {- refresh();- execRefresh();- }, timeout);- }- };+ if (hasProPlan === false) {+ setHasSelectedDomains(true);+ return;+ }+ const form = buttonRef.current?.closest("form");++ if (form == null) {+ return;+ }++ const handleFormInput = () => {+ const formData = new FormData(form);+ const domainsSelected = formData.getAll(domainToPublishName).length;+ setHasSelectedDomains(domainsSelected > 0);+ };++ const observer = new MutationObserver(() => {+ handleFormInput();+ });++ observer.observe(form, {+ attributes: true,+ childList: true,+ subtree: true,+ attributeFilter: ["value", "checked"],+ });++ handleFormInput();++ return () => {+ observer.disconnect();+ };+ }, [hasProPlan]);++ const handlePublish = async (formData: FormData) => {+ setPublishError(undefined);+ setIsPublishing(true);++ const domains = hasProPlan+ ? formData+ .getAll(domainToPublishName)+ .map((domainEntry) => domainEntry.toString())+ : [+ project.domain,+ ...project.domainsVirtual+ .filter((domain) => domain.verified && domain.status === "ACTIVE")+ .map((domain) => domain.domain),+ ];++ if (domains.length === 0) {+ toast.error("Please select at least one domain to publish");+ return;+ }++ const publishResult = await nativeClient.domain.publish.mutate({+ projectId: project.id,+ domains,+ destination: "saas",+ });++ if (publishResult.success === false) {+ console.error(publishResult.error);++ setPublishError(publishResult.error);+ toast.error(publishResult.error);++ if (process.env.NODE_ENV === "development") {+ // Refresh locally as it's always an error+ await refresh();+ }++ return;+ }++ let sleepTime = 15000;+ const timeToFinish = Date.now() + PENDING_TIMEOUT + 2 * sleepTime;++ // Wait until project is published or failed+ while (Date.now() < timeToFinish) {+ await refresh();++ const project = $project.get();++ if (project == null) {+ throw new Error("Project not found");+ }++ const { statusText, status } =+ project.latestBuildVirtual != null+ ? getPublishStatusAndText(project.latestBuildVirtual)+ : {+ statusText: "Not published",+ status: "PENDING" as const,+ };++ if (status === "PUBLISHED") {+ break;+ }++ if (status === "FAILED") {+ toast.error(statusText);+ setPublishError(statusText);+ break;+ }- execRefresh();+ await new Promise((resolve) => setTimeout(resolve, sleepTime));- return () => {- clearTimeout(timeoutHandle);- };+ sleepTime = Math.max(5000, sleepTime - 5000);}- }, [isPublishing, refresh]);+ };++ const hasPendingState = project.latestBuildVirtual+ ? getPublishStatusAndText(project.latestBuildVirtual).status === "PENDING"+ : false;- const isPublishInProgress = publishState !== "idle" || isPublishing;+ const isPublishInProgress = isPublishing || hasPendingState;return (<Flex@@ -312,38 +336,23 @@ const Publish = ({shrink={false}direction={"column"}>- {publishSystemError !== undefined && (- <Text color="destructive">{publishSystemError}</Text>- )}-- {publishData?.success === false && (- <Text color="destructive">{publishData.error}</Text>- )}+ {publishError && <Text color="destructive">{publishError}</Text>}<Tooltipcontent={- isPublishInProgress ? "Publish process in progress" : undefined+ isPublishInProgress+ ? "Publish process in progress"+ : hasSelectedDomains+ ? undefined+ : "Select at least one domain to publish"}><Button+ ref={buttonRef}+ formAction={handlePublish}color="positive"state={isPublishInProgress ? "pending" : undefined}- onClick={() => {- setIsPublishing(true);-- publish(- {- projectId: project.id,- domains: domainsToPublish.map(- (projectDomain) => projectDomain.domain- ),- destination: "saas",- },- () => {- refresh();- }- );- }}+ disabled={hasSelectedDomains === false}>Publish</Button>@@ -386,33 +395,6 @@ const getStaticPublishStatusAndText = ({return { statusText, status };};-const fetchProjectDataStatus = async (projectId: Project["id"]) => {- const projectData = await nativeClient.domain.project.query({- projectId,- });-- if (projectData.success === false) {- throw new Error(projectData.error);- }-- if (projectData.project.latestStaticBuild == null) {- return {- status: "LOADED" as const,- statusText: "Not published",- };- }-- const { status, statusText } = getStaticPublishStatusAndText(- projectData.project.latestStaticBuild- );-- return { status, statusText };-};--type StaticProjectStatus =- | Awaited<ReturnType<typeof fetchProjectDataStatus>>- | { status: "INITIAL"; statusText: string };-const PublishStatic = ({projectId,templates,@@ -420,58 +402,38 @@ const PublishStatic = ({projectId: Project["id"];templates: readonly Templates[];}) => {+ const project = useStore($project);const [_, startTransition] = useTransition();- const [projectDataStatus, setProjectDataStatus] =- useState<StaticProjectStatus>({- status: "INITIAL",- statusText: "Loading",- });+ if (project == null) {+ throw new Error("Project not found");+ }- useEffect(() => {- startTransition(async () => {- try {- const projectDataStatus = await fetchProjectDataStatus(projectId);- setProjectDataStatus(projectDataStatus);- } catch (error) {- setProjectDataStatus({- status: "FAILED",- statusText: error instanceof Error ? error.message : "Unknown error",- });- }- });- }, [projectId]);+ const { status, statusText } =+ project.latestStaticBuild == null+ ? { status: "LOADED" as const, statusText: "Not published" }+ : getStaticPublishStatusAndText(project.latestStaticBuild);- const [optimisticPendingStatus, setOptimisticPendingStatus] = useOptimistic(- projectDataStatus,- (_currentState, optimisticValue: StaticProjectStatus) => {- return optimisticValue;- }- );+ const [isPending, setIsPendingOptimistic] = useOptimistic(false);const isPublishInProgress =- optimisticPendingStatus.status === "PENDING" ||- optimisticPendingStatus.status === "INITIAL";+ project.latestStaticBuild?.publishStatus === "PENDING" || isPending;return (<Flex gap={2} shrink={false} direction={"column"}>- {optimisticPendingStatus.status === "FAILED" && (- <Text color="destructive">{optimisticPendingStatus.statusText}</Text>- )}+ {status === "FAILED" && <Text color="destructive">{statusText}</Text>}<Tooltipcontent={isPublishInProgress ? "Preparing static site" : undefined}><Button+ type="button"color="positive"state={isPublishInProgress ? "pending" : undefined}onClick={() => {startTransition(async () => {try {- setOptimisticPendingStatus({- status: "PENDING",- statusText: "Publishing",- });+ setIsPendingOptimistic(true);const result = await nativeClient.domain.publish.mutate({projectId,@@ -496,30 +458,40 @@ const PublishStatic = ({// Repeat few more times than timeoutconst repeat = PENDING_TIMEOUT / timeout + 5;- let projectDataStatus: StaticProjectStatus | undefined;-for (let i = 0; i !== repeat; i++) {await new Promise((resolve) => setTimeout(resolve, timeout));- projectDataStatus = await fetchProjectDataStatus(projectId);+ await refreshProject();++ const latestStaticBuild = $project.get()?.latestStaticBuild;++ if (latestStaticBuild == null) {+ continue;+ }++ const { status } =+ getStaticPublishStatusAndText(latestStaticBuild);- if (projectDataStatus.status !== "PENDING") {+ if (status !== "PENDING") {break;}}- if (projectDataStatus == null) {- return;+ const latestStaticBuild = $project.get()?.latestStaticBuild;++ if (latestStaticBuild == null) {+ throw new Error("Static build not found");}- setProjectDataStatus(projectDataStatus);+ const { status, statusText } =+ getStaticPublishStatusAndText(latestStaticBuild);- if (projectDataStatus.status === "FAILED") {+ if (status === "FAILED") {// Report if Export failed- toast.error(projectDataStatus.statusText);+ toast.error(statusText);}- if (projectDataStatus.status === "PUBLISHED") {+ if (status === "PUBLISHED") {window.location.href = `/cgi/static/ssg/${name}`;}} catch (error) {@@ -537,26 +509,22 @@ const PublishStatic = ({);};-const ErrorText = ({ children }: { children: string }) => (- <Flex- css={{- m: theme.spacing[9],- overflowWrap: "anywhere",- }}- gap={2}- direction={"column"}- >- <Text color="destructive">{children}</Text>- <Text color="subtle">Please try again later</Text>- </Flex>-);-const useCanAddDomain = () => {const { load, data } = trpcClient.domain.countTotalDomains.useQuery();const { maxDomainsAllowedPerUser, hasProPlan } = useStore($userPlanFeatures);+ const project = useStore($project);++ const activeDomainsCount = project?.domainsVirtual.filter(+ (domain) => domain.status === "ACTIVE" && domain.verified+ ).length;+useEffect(() => {load();- }, [load]);+ }, [load, activeDomainsCount]);++ if (hasProPlan) {+ return { canAddDomain: true, maxDomainsAllowedPerUser };+ }if (data?.success === false) {return { canAddDomain: false, maxDomainsAllowedPerUser };@@ -566,56 +534,44 @@ const useCanAddDomain = () => {? data.success && data.data < maxDomainsAllowedPerUser: true;const canAddDomain = hasProPlan || withinFreeLimit;+return { canAddDomain, maxDomainsAllowedPerUser };};+const refreshProject = async () => {+ const result = await nativeClient.domain.project.query(+ {+ projectId: $project.get()!.id,+ }+ // Pass abort signal+ // { signal: undefined }+ );++ if (result.success) {+ $project.set(result.project);+ return;+ }++ toast.error(result.error);+};+const Content = (props: {projectId: Project["id"];onExportClick: () => void;}) => {const [newDomains, setNewDomains] = useState(new Set<string>());- const {- load: projectLoad,- data: projectData,- state: projectState,- error: projectSystemError,- } = trpcClient.domain.project.useQuery();-- useEffect(() => {- projectLoad({ projectId: props.projectId });- }, [props.projectId, projectLoad]);-- projectData?.success;-- const domainsToPublish = useMemo(- () =>- projectData?.success- ? projectData.project.domainsVirtual.filter(- (projectDomain) => getStatus(projectDomain) === "VERIFIED_ACTIVE"- )- : [],- [projectData]- );+ const project = useStore($project);- const latestBuildVirtual = projectData?.success- ? (projectData.project.latestBuildVirtual ?? undefined)- : undefined;-- const hasPendingState = latestBuildVirtual- ? getPublishStatusAndTextNew(latestBuildVirtual).status === "PENDING"- : false;-- const [isPublishing, setIsPublishing] = useState(hasPendingState);-- useEffect(() => {- setIsPublishing(hasPendingState);- }, [hasPendingState, setIsPublishing]);+ if (project == null) {+ throw new Error("Project not found");+ }+ const projectState = "idle";const { canAddDomain, maxDomainsAllowedPerUser } = useCanAddDomain();return (- <>+ <form><ScrollArea>{canAddDomain === false && (<PanelBanner>@@ -626,7 +582,7 @@ const Content = (props: {<Text variant="regularBold" inline>Upgrade to a Pro account</Text>{" "}- to add unlimited domains.+ to add unlimited domains and publish to each domain individually.</Text><LinkclassName={buttonStyle({ color: "gradient" })}@@ -639,59 +595,38 @@ const Content = (props: {</Link></PanelBanner>)}- {projectSystemError !== undefined && (- <ErrorText>{projectSystemError}</ErrorText>- )}-- {projectData?.success && (+ <RadioGroup name="publishDomain"><ChangeProjectDomain- projectLoad={projectLoad}+ refresh={refreshProject}projectState={projectState}- project={projectData.project}- isPublishing={isPublishing}+ project={project}/>- )}- {projectData?.success && (<DomainsnewDomains={newDomains}- domains={projectData.project.domainsVirtual}- refreshDomainResult={projectLoad}- domainState={projectState}- isPublishing={isPublishing}+ domains={project.domainsVirtual}+ refresh={refreshProject}+ project={project}/>- )}+ </RadioGroup></ScrollArea><Flex direction="column" justify="end" css={{ height: 0 }}><Separator /></Flex>+<AddDomainprojectId={props.projectId}- refreshDomainResult={projectLoad}- domainState={projectState}+ refresh={refreshProject}onCreate={(domain) => {setNewDomains((prev) => {return new Set([...prev, domain]);});}}- isPublishing={isPublishing}onExportClick={props.onExportClick}/>- {projectData?.success === true && (- <Publish- project={projectData.project}- domainsToPublish={domainsToPublish}- refresh={() => {- projectLoad({ projectId: props.projectId });- }}- isPublishing={isPublishing}- setIsPublishing={setIsPublishing}- />- )}- {projectData?.success !== true && (- <Box css={{ height: theme.spacing[8] }} />- )}- </>++ <Publish project={project} refresh={refreshProject} />+ </form>);};@@ -845,6 +780,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {<Tooltip content={"Copy to clipboard"}><Button+ type="button"color="neutral"onClick={() => {navigator.clipboard.writeText(npxCommand);@@ -886,6 +822,7 @@ const ExportContent = (props: { projectId: Project["id"] }) => {/><Tooltip content={"Copy to clipboard"}><Button+ type="button"css={{ flexShrink: 0 }}color="neutral"onClick={() => {@@ -959,7 +896,11 @@ export const PublishButton = ({ projectId }: PublishProps) => {sideOffset={Number.parseFloat(rawTheme.spacing[5])}><FloatingPanelPopoverTrigger asChild>- <Button disabled={isPublishEnabled === false} color="positive">+ <Button+ type="button"+ disabled={isPublishEnabled === false}+ color="positive"+ >Publish</Button></FloatingPanelPopoverTrigger>diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex 836e556f75..f98ede7183 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -34,13 +34,15 @@ export const loadProductionCanvasData = async (// Check that build deployment domains are still active and verified// for examle: redeploy created few days laterif (deployment.destination !== "static") {- deployment.domains = deployment.domains.filter((domain) =>- currentProjectDomains.some(- (projectDomain) =>- projectDomain.domain === domain &&- projectDomain.status === "ACTIVE" &&- projectDomain.verified- )+ deployment.domains = deployment.domains.filter(+ (domain) =>+ project.domain === domain ||+ currentProjectDomains.some(+ (projectDomain) =>+ projectDomain.domain === domain &&+ projectDomain.status === "ACTIVE" &&+ projectDomain.verified+ ));}diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex 4d4facffb5..815baf721c 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -430,23 +430,25 @@ export const prebuild = async (options: {const assetsToDownload: Promise<void>[] = [];- const appDomain = options.preview ? "wstd.work" : "wstd.io";-- const domain =- siteData.build.deployment?.destination === "static"- ? siteData.build.deployment?.assetsDomain- : siteData.build.deployment?.projectDomain;- if (domain === undefined) {- throw new Error(`Project domain is missing from the project data`);- }+ if (options.assets === true) {+ const appDomain = options.preview ? "wstd.work" : "wstd.io";+ const domain =+ siteData.build.deployment?.assetsDomain ??+ // fallback to project domain should not be used since 2025-01-01 (for now is used for backward compatibility)+ (siteData.build.deployment?.destination !== "static"+ ? siteData.build.deployment?.projectDomain+ : undefined);++ if (domain === undefined) {+ throw new Error(`Project domain is missing from the project data`);+ }- const assetBuildUrl = `https://${domain}.${appDomain}/cgi/asset/`;+ const assetBuildUrl = `https://${domain}.${appDomain}/cgi/asset/`;- const imageLoader = createImageLoader({- imageBaseUrl: assetBuildUrl,- });+ const imageLoader = createImageLoader({+ imageBaseUrl: assetBuildUrl,+ });- if (options.assets === true) {for (const asset of siteData.assets) {if (asset.type === "image") {const imageSrc = imageLoader({diff --git a/packages/design-system/src/components/checkbox.stories.tsx b/packages/design-system/src/components/checkbox.stories.tsxindex 3072af99c1..f1d58b9936 100644--- a/packages/design-system/src/components/checkbox.stories.tsx+++ b/packages/design-system/src/components/checkbox.stories.tsx@@ -1,6 +1,7 @@import { Label } from "./label";import { Checkbox, CheckboxAndLabel } from "./checkbox";import { StorySection, StoryGrid } from "./storybook";+import { Tooltip } from "./tooltip";export default {title: "Library/Checkbox",@@ -45,6 +46,15 @@ export const Demo = () => {<Label htmlFor="B">Label B</Label></CheckboxAndLabel></StorySection>++ <StorySection title="With Tooltip">+ <Tooltip content="Tooltip content">+ <Checkbox defaultChecked />+ </Tooltip>+ <Tooltip content="Tooltip content">+ <Checkbox disabled />+ </Tooltip>+ </StorySection></>);};diff --git a/packages/design-system/src/components/checkbox.tsx b/packages/design-system/src/components/checkbox.tsxindex 159aa5edd4..ebeb1b4055 100644--- a/packages/design-system/src/components/checkbox.tsx+++ b/packages/design-system/src/components/checkbox.tsx@@ -56,24 +56,49 @@ const iconByState = {indeterminate: CheckboxMixedFilledIcon,};+type ButtonProps = ComponentProps<"button"> &+ Pick<ComponentProps<typeof Primitive.Checkbox>, "aria-checked">;++type AriaChecked = ComponentProps<typeof Primitive.Checkbox>["aria-checked"];++const ariaCheckedToDataState = (+ ariaChecked: AriaChecked+): keyof typeof iconByState => {+ if (ariaChecked === "true" || ariaChecked === true) {+ return "checked";+ }+ if (ariaChecked === "false" || ariaChecked === false) {+ return "unchecked";+ }++ if (ariaChecked === "mixed" || ariaChecked === undefined) {+ return "indeterminate";+ }++ ariaChecked satisfies never;+ return "indeterminate";+};+// We need this component basicslly just to get access to "data-state".// We could render all icons and hide one using CSS,// but that probably will be less performant.-const Button = forwardRef(- (- props: ComponentProps<"button"> & {- "data-state"?: "checked" | "unchecked" | "indeterminate";- },- ref: Ref<HTMLButtonElement>- ) => {- const Icon = iconByState[props["data-state"] ?? "unchecked"];- return (- <button {...props} ref={ref}>- <Icon className={iconStyle()} />- </button>- );- }-);+const Button = forwardRef((props: ButtonProps, ref: Ref<HTMLButtonElement>) => {+ // Using aria-checked instead of data-state ensures compatibility with Tooltip,+ // as Tooltip overrides the Checkbox's data-state attribute.+ const dataState = ariaCheckedToDataState(props["aria-checked"]);+ const Icon = iconByState[dataState];++ return (+ <button+ {...props}+ data-state={dataState}+ type={props.type ?? "button"}+ ref={ref}+ >+ <Icon className={iconStyle()} />+ </button>+ );+});Button.displayName = "Button";export const Checkbox = forwardRef(diff --git a/packages/design-system/src/components/section-title.tsx b/packages/design-system/src/components/section-title.tsxindex 38a6f430da..864ef5d195 100644--- a/packages/design-system/src/components/section-title.tsx+++ b/packages/design-system/src/components/section-title.tsx@@ -32,6 +32,9 @@ const containerStyle = css({height: theme.spacing[15],[buttonContentColor]: theme.colors.foregroundIconMain,[labelTextColor]: theme.colors.foregroundMain,+ "&:hover": {+ [chevronOpacity]: 1,+ },});const titleButtonLayoutStyle = css({@@ -54,9 +57,6 @@ const labelContainerStyle = css({const titleButtonStyle = css(titleButtonLayoutStyle, {"&:focus-visible": focusRingStyle(),- "&:hover": {- [chevronOpacity]: 1,- },});const suffixSlotStyle = css({diff --git a/packages/domain/src/trpc/domain.ts b/packages/domain/src/trpc/domain.tsindex c2f4bfd5d9..88eebe04f6 100644--- a/packages/domain/src/trpc/domain.ts+++ b/packages/domain/src/trpc/domain.ts@@ -62,19 +62,32 @@ export const domainRouter = router({const name = `${project.id}-${nanoid()}.zip`;- let domains: string[] = [];+ const domains: string[] = [];++ let hasCustomDomain = false;if (input.destination === "saas") {const currentProjectDomains = project.domainsVirtual;- domains = input.domains.filter((domain) =>- currentProjectDomains.some(- (projectDomain) =>- projectDomain.domain === domain &&- projectDomain.status === "ACTIVE" &&- projectDomain.verified+ if (input.domains.includes(project.domain)) {+ domains.push(project.domain);+ }++ domains.push(+ ...input.domains.filter((domain) =>+ currentProjectDomains.some(+ (projectDomain) =>+ projectDomain.domain === domain &&+ projectDomain.status === "ACTIVE" &&+ projectDomain.verified+ )));++ hasCustomDomain = currentProjectDomains.some(+ (projectDomain) =>+ projectDomain.status === "ACTIVE" && projectDomain.verified+ );}const build = await createProductionBuild(@@ -85,7 +98,8 @@ export const domainRouter = router({? {destination: input.destination,domains: domains,- projectDomain: project.domain,+ assetsDomain: project.domain,+ excludeWstdDomainFromSearch: hasCustomDomain,}: {destination: input.destination,@@ -114,7 +128,7 @@ export const domainRouter = router({branchName: env.GITHUB_REF_NAME,destination: input.destination,// action log helper (not used for deployment, but for action logs readablity)- projectDomainName: project.domain,+ logProjectName: `${project.title} - ${project.id}`,});if (input.destination === "static" && result.success) {diff --git a/packages/postgrest/supabase/tests/cleanup-builds.sql b/packages/postgrest/supabase/tests/cleanup-builds.sqlnew file mode 100644index 0000000000..d2a0c90b65--- /dev/null+++ b/packages/postgrest/supabase/tests/cleanup-builds.sql@@ -0,0 +1,227 @@+BEGIN;+SET LOCAL search_path = pgtap, public;+-- Initialize the testing environment without planning any specific number of tests+-- We are using SELECT no_plan() because we don't specify the exact number of tests upfront.+SELECT no_plan();++-- =========================================+-- Setup: Insert initial data for Users, Projects, Domains, ProjectDomains, and Builds+-- =========================================++-- Insert a user into the "User" table+INSERT INTO "public"."User" ("id", "createdAt", "email", "username")+VALUES+ ('user1', '2023-01-01 00:00:00+00', '[email protected]', 'user1');++-- Insert projects associated with the user into the "Project" table+INSERT INTO "public"."Project" ("id", "title", "domain", "userId", "isDeleted", "createdAt")+VALUES+ ('project1', 'Project One', '517cce32-9af3-project1-domain1', 'user1', false, '2023-01-01 00:00:00+00'),+ ('project2', 'Project Two', '517cce32-9af3-project2-domain1', 'user1', false, '2023-01-01 00:00:00+00');++-- Insert custom domains into the "Domain" table+INSERT INTO "public"."Domain" ("id", "domain", "createdAt", "status", "updatedAt")+VALUES+ ('project-1-custom-domain-1', '517cce32-9af3-project-1-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),+ ('project-1-custom-domain-2', '517cce32-9af3-project-1-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),+ ('project-2-custom-domain-1', '517cce32-9af3-project-2-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),+ ('project-2-custom-domain-2', '517cce32-9af3-project-2-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00');++-- Establish relationships between projects and custom domains in the "ProjectDomain" table+INSERT INTO "public"."ProjectDomain" ("projectId", "domainId", "createdAt", "txtRecord", "cname")+VALUES+ ('project1', 'project-1-custom-domain-1', '2023-01-01 00:00:00+00', 'txtRecord1', 'cname1'),+ ('project1', 'project-1-custom-domain-2', '2023-01-01 00:00:00+00', 'txtRecord2', 'cname2'),+ ('project2', 'project-2-custom-domain-1', '2023-01-01 00:00:00+00', 'p2-txtRecord1', 'cname1'),+ ('project2', 'project-2-custom-domain-2', '2023-01-01 00:00:00+00', 'p2-txtRecord2', 'cname2');++-- Insert initial builds into the "Build" table+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ -- Development Build for Project1+ (+ 'build1-development',+ '1990-01-01 00:00:00+00',+ 'home',+ 'project1',+ NULL,+ '1990-01-01 00:00:00+00',+ 'PENDING'+ ),+ -- Development Build for Project2+ (+ 'project2-build1-development',+ '1990-01-01 00:00:00+00',+ 'home',+ 'project2',+ NULL,+ '1990-01-01 00:00:00+00',+ 'PENDING'+ ),+ -- Custom Domain Build for Project2+ (+ 'project2-build1-for-custom-domain-1',+ '1990-01-02 00:00:00+00',+ 'home',+ 'project2',+ '{"domains": ["517cce32-9af3-project-2-custom-domain-1.com"]}'::text,+ '1990-01-02 00:00:00+00',+ 'PUBLISHED'+ ),+ -- Project Domain Build for Project2+ (+ 'project2-build1-for-project-domain-1',+ '1990-01-01 00:00:00+00',+ 'home',+ 'project2',+ '{"domains": ["517cce32-9af3-project2-domain1"]}'::text,+ '1990-01-01 00:00:00+00',+ 'PUBLISHED'+ ),+ -- Custom Domain Build for Project1+ (+ 'build1-for-custom-domain-1',+ '1990-01-02 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["517cce32-9af3-project-1-custom-domain-1.com"]}'::text,+ '1990-01-02 00:00:00+00',+ 'PUBLISHED'+ ),+ -- Project Domain Build for Project1+ (+ 'build1-for-project-domain-1',+ '1990-01-01 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["517cce32-9af3-project1-domain1"]}'::text,+ '1990-01-01 00:00:00+00',+ 'PUBLISHED'+ );++-- =========================================+-- Test 1: Verify that initial cleanup does not clean any builds+-- =========================================++-- Run the database cleanup function for builds created in 1990+SELECT database_cleanup('1990-01-01 00:00:00', '1990-12-31 23:59:59');++-- Assert that no builds have been cleaned up initially+SELECT is(+ (SELECT count(*)::integer FROM "Build" WHERE "createdAt" BETWEEN '1990-01-01' AND '1990-12-31' AND "isCleaned" = TRUE),+ 0,+ 'Test 1: No builds should be cleaned up on initial cleanup'+);++-- =========================================+-- Test 2: Insert a new project domain build and verify cleanup+-- =========================================++-- Insert a new build for the project domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ -- New Project Domain Build for Project1+ (+ 'build2-for-project-domain-1',+ '1990-01-02 00:00:00+00', -- A later date than the previous build+ 'home',+ 'project1',+ '{"domains": ["517cce32-9af3-project1-domain1"]}'::text,+ '1990-01-02 00:00:00+00',+ 'PUBLISHED'+ );++-- Run the database cleanup function again+SELECT database_cleanup('1990-01-01 00:00:00', '1990-12-31 23:59:59');++-- Assert that one build has been cleaned (the previous project domain build)+SELECT is(+ (SELECT count(*)::integer FROM "Build" WHERE "createdAt" BETWEEN '1990-01-01' AND '1990-12-31' AND "isCleaned" = TRUE),+ 1,+ 'Test 2: Previous project domain build should be cleaned up after new build is published'+);++-- Assert that the specific build cleaned is 'build1-for-project-domain-1'+SELECT is(+ (SELECT id FROM "Build" WHERE "createdAt" BETWEEN '1990-01-01' AND '1990-12-31' AND "isCleaned" = TRUE),+ 'build1-for-project-domain-1',+ 'Test 2: Build "build1-for-project-domain-1" should be marked as cleaned'+);++-- =========================================+-- Test 3: Insert a new custom domain build and verify cleanup+-- =========================================++-- Insert a new build for the custom domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ -- New Custom Domain Build for Project1+ (+ 'build2-for-custom-domain-1',+ '1990-01-03 00:00:00+00', -- A later date than the previous build+ 'home',+ 'project1',+ '{"domains": ["517cce32-9af3-project-1-custom-domain-1.com"]}'::text,+ '1990-01-03 00:00:00+00',+ 'PUBLISHED'+ );++-- Run the database cleanup function again+SELECT database_cleanup('1990-01-01 00:00:00', '1990-12-31 23:59:59');++-- Assert that two builds have been cleaned (the previous project domain and custom domain builds)+SELECT is(+ (SELECT count(*)::integer FROM "Build" WHERE "createdAt" BETWEEN '1990-01-01' AND '1990-12-31' AND "isCleaned" = TRUE),+ 2,+ 'Test 3: Previous custom domain build should be cleaned up after new build is published'+);++-- Assert that the builds cleaned are 'build1-for-custom-domain-1' and 'build1-for-project-domain-1'+SELECT results_eq(+ $$+ SELECT id FROM "Build" WHERE "createdAt" BETWEEN '1990-01-01' AND '1990-12-31' AND "isCleaned" = TRUE ORDER BY id+ $$,+ $$+ SELECT * FROM (+ VALUES+ ('build1-for-custom-domain-1'),+ ('build1-for-project-domain-1')+ ) AS expected(id)+ ORDER BY "id"+ $$,+ 'Test 3: Builds "build1-for-custom-domain-1" and "build1-for-project-domain-1" should be marked as cleaned'+);++-- =========================================+-- Finish the test+-- =========================================++-- Finish the test by calling the finish() function, which outputs the test summary+SELECT finish();++-- Rollback the transaction to ensure no changes are persisted in the database+ROLLBACK;diff --git a/packages/postgrest/supabase/tests/latest-builds-domains.sql b/packages/postgrest/supabase/tests/latest-builds-domains.sqlindex 82e1d79aa9..afcb3a5842 100644--- a/packages/postgrest/supabase/tests/latest-builds-domains.sql+++ b/packages/postgrest/supabase/tests/latest-builds-domains.sql@@ -9,19 +9,19 @@ SELECT no_plan();-- Insert a new user into the User tableINSERT INTO "public"."User" ("id", "createdAt", "email", "username")VALUES- ('user1', '2023-01-01 00:00:00+00', '[email protected]', 'user1');+ ('user1', '2023-01-01 00:00:00+00', '[email protected]', 'user1');-- Insert projects associated with the userINSERT INTO "public"."Project" ("id", "title", "domain", "userId", "isDeleted", "createdAt")VALUES- ('project1', 'Project One', 'project1-domain1', 'user1', false, '2023-01-01 00:00:00+00'),- ('project2', 'Project Two', 'project2-domain1', 'user1', false, '2023-01-01 00:00:00+00');+ ('project1', 'Project One', '517cce32-9af3-project1-domain1', 'user1', false, '2023-01-01 00:00:00+00'),+ ('project2', 'Project Two', '517cce32-9af3-project2-domain1', 'user1', false, '2023-01-01 00:00:00+00');-- Insert custom domains into the Domain tableINSERT INTO "public"."Domain" ("id", "domain", "createdAt", "status", "updatedAt")VALUES- ('project-1-custom-domain-1', 'project-1-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),- ('project-1-custom-domain-2', 'project-1-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00');+ ('project-1-custom-domain-1', '517cce32-9af3-project-1-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),+ ('project-1-custom-domain-2', '517cce32-9af3-project-1-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00');-- Establish relationships between projects and custom domainsINSERT INTO "public"."ProjectDomain" ("projectId", "domainId", "createdAt", "txtRecord", "cname")@@ -76,7 +76,7 @@ VALUES'2023-01-02 00:00:00+00','home','project1',- '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,'2023-01-02 00:00:00+00','PUBLISHED');@@ -113,7 +113,7 @@ VALUES'2024-01-02 00:00:00+00','home','project1',- '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,'2024-01-02 00:00:00+00','PUBLISHED');@@ -150,7 +150,7 @@ VALUES'2024-01-03 00:00:00+00','home','project1',- '{"domains": ["some-other-domain.com", "project-1-custom-domain-2.com"]}'::text,+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com"]}'::text,'2024-01-03 00:00:00+00','PUBLISHED');@@ -187,7 +187,7 @@ VALUES'2024-01-04 00:00:00+00','home','project1',- '{"domains": ["some-other-domain.com", "project-1-custom-domain-2.com", "project-1-custom-domain-1.com"]}'::text,+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,'2024-01-04 00:00:00+00','PUBLISHED');@@ -230,7 +230,7 @@ VALUES'2025-01-04 00:00:00+00','home','project2',- '{"domains": ["some-other-domain.com", "project-1-custom-domain-2.com", "project-1-custom-domain-1.com"]}'::text,+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-2.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,'2025-01-04 00:00:00+00','PUBLISHED');diff --git a/packages/postgrest/supabase/tests/latest-builds-projects.sql b/packages/postgrest/supabase/tests/latest-builds-projects.sqlindex dc183cb037..631d302e74 100644--- a/packages/postgrest/supabase/tests/latest-builds-projects.sql+++ b/packages/postgrest/supabase/tests/latest-builds-projects.sql@@ -16,8 +16,8 @@ VALUES-- Insert projects associated with the userINSERT INTO "public"."Project" ("id", "title", "domain", "userId", "isDeleted", "createdAt")VALUES- ('project1', 'Project One', 'project1-domain1', 'user1', false, '2023-01-01 00:00:00+00'),- ('project2', 'Project Two', 'project2-domain1', 'user1', false, '2023-01-01 00:00:00+00');+ ('project1', 'Project One', '517cce32-9af3-project1-domain1', 'user1', false, '2023-01-01 00:00:00+00'),+ ('project2', 'Project Two', '517cce32-9af3-project2-domain1', 'user1', false, '2023-01-01 00:00:00+00');-- Insert builds with different deployment formatsINSERT INTO "public"."Build" (@@ -36,7 +36,7 @@ VALUES'2023-01-01 00:00:00+00','home','project1',- '{"projectDomain": "project1-domain1", "domains": [""]}'::text,+ '{"projectDomain": "517cce32-9af3-project1-domain1", "domains": [""]}'::text,'2023-01-01 00:00:00+00','PUBLISHED'),@@ -45,7 +45,7 @@ VALUES'2022-01-01 00:00:00+00','home','project1',- '{"projectDomain": "project1-domain1", "domains": [""]}'::text,+ '{"projectDomain": "517cce32-9af3-project1-domain1", "domains": [""]}'::text,'2022-01-01 00:00:00+00','PUBLISHED'),@@ -64,7 +64,7 @@ VALUES'2023-01-02 00:00:00+00','home','project2',- '{"domains": ["project2-domain1"]}'::text,+ '{"domains": ["517cce32-9af3-project2-domain1"]}'::text,'2023-01-02 00:00:00+00','PENDING'),@@ -73,7 +73,7 @@ VALUES'2022-01-02 00:00:00+00','home','project2',- '{"domains": ["project2-domain1"]}'::text,+ '{"domains": ["517cce32-9af3-project2-domain1"]}'::text,'2022-01-02 00:00:00+00','PENDING');@@ -83,7 +83,7 @@ VALUES--------------------------------------------------------------------------------SELECT is ((- SELECT "buildId"+ SELECT ARRAY["buildId", "domain"]FROM "public"."latestBuildVirtual"((SELECT (p.*)::"Project"@@ -92,8 +92,24 @@ SELECT is ())),- 'build1',- 'Test Case 1: Should return the latest build for project1 with domain matching projectDomain.'+ ARRAY['build1', '517cce32-9af3-project1-domain1'],+ 'Test Case 1.1: Should return the latest build for project1 with domain matching projectDomain.'+);+++SELECT is (+ (+ SELECT ARRAY["buildId", "domain"]+ FROM "public"."latestProjectDomainBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ ARRAY['build1', '517cce32-9af3-project1-domain1'],+ 'Test Case 1.2: Should return the latest build for project1 with domain matching projectDomain.');--------------------------------------------------------------------------------@@ -111,9 +127,23 @@ SELECT is ()),'build2',- 'Test Case 2: Should return the latest build for project2 with domain present in domains array.'+ 'Test Case 2.1: Should return the latest build for project2 with domain present in domains array.');+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestProjectDomainBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project2'+ )+ )+ ),+ 'build2',+ 'Test Case 2.2: Should return the latest build for project2 domain with domain present in domains array.'+);---------------------------------------------------------------------------------- Test Case 3: Update Project Domain and Verify No Build Exists for the New Domain--------------------------------------------------------------------------------@@ -135,7 +165,22 @@ SELECT is ()),0,- 'Test Case 3: Should return 0 as no build exists for the updated domain project1-domain2.'+ 'Test Case 3.1: Should return 0 as no build exists for the updated domain project1-domain2.'+);++SELECT is (+ (+ SELECT COUNT(*)::integer+ FROM "public"."latestProjectDomainBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 0,+ 'Test Case 3.2: Should return 0 as no build exists for the updated domain project1-domain2.');--------------------------------------------------------------------------------@@ -165,7 +210,7 @@ VALUES-- Verify that the latest build now reflects the updated domainSELECT is ((- SELECT "buildId"+ SELECT ARRAY["buildId", "domain"]FROM "public"."latestBuildVirtual"((SELECT (p.*)::"Project"@@ -174,10 +219,26 @@ SELECT is ())),- 'build1-for-domain2',- 'Test Case 4: Should return the latest build for project1 with the updated domain in domains array.'+ ARRAY['build1-for-domain2','project1-domain2'],+ 'Test Case 4.1: Should return the latest build for project1 with the updated domain in domains array.');+SELECT is (+ (+ SELECT ARRAY["buildId", "domain"]+ FROM "public"."latestProjectDomainBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ ARRAY['build1-for-domain2','project1-domain2'],+ 'Test Case 4.2: Should return the latest build for project1 domain with the updated domain in domains array.'+);++---------------------------------------------------------------------------------- Test Case 5: Register Custom Domains and Verify Latest Build for a Custom Domain--------------------------------------------------------------------------------@@ -190,8 +251,8 @@ INSERT INTO "public"."Domain" ("updatedAt")VALUES- ('project-1-custom-domain-1', 'project-1-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),- ('project-1-custom-domain-2', 'project-1-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00');+ ('project-1-custom-domain-1', '517cce32-9af3-project-1-custom-domain-1.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00'),+ ('project-1-custom-domain-2', '517cce32-9af3-project-1-custom-domain-2.com', '2023-01-01 00:00:00+00', 'INITIALIZING', '2023-01-01 00:00:00+00');-- Establish relationships between project1 and custom domainsINSERT INTO "public"."ProjectDomain" (@@ -221,7 +282,7 @@ VALUES'2023-01-02 00:00:00+00','home','project1',- '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,'2023-01-02 00:00:00+00','PUBLISHED');@@ -229,7 +290,7 @@ VALUES-- Verify that the latest build reflects the custom domain associationSELECT is ((- SELECT "buildId"+ SELECT ARRAY["buildId", "domain"]FROM "public"."latestBuildVirtual"((SELECT (p.*)::"Project"@@ -238,8 +299,26 @@ SELECT is ())),- 'build1-for-custom-domain-1',- 'Test Case 5: Should return the latest build for project1 with a registered custom domain in domains array.'+ ARRAY['build1-for-custom-domain-1','517cce32-9af3-project-1-custom-domain-1.com'],+ 'Test Case 5.1: Should return the latest build for project1 with a registered custom domain in domains array.'+);+++-- Ensure the latest project domain build has not changed+-- The difference between latestProjectDomainBuildVirtual and latestBuildVirtual is that the first returns data only for the project domain+SELECT is (+ (+ SELECT ARRAY["buildId", "domain"]+ FROM "public"."latestProjectDomainBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ ARRAY['build1-for-domain2','project1-domain2'],+ 'Test Case 5.2: Should return the latest build for project1 domain and not affected by custom domains');--------------------------------------------------------------------------------@@ -261,7 +340,7 @@ VALUES'2023-01-03 00:00:00+00','home','project1',- '{"domains": ["project1-domain2"]}'::text,+ '{"domains": ["517cce32-9af3-project-1-custom-domain-1.com", "project1-domain2"]}'::text,'2023-01-03 00:00:00+00','PUBLISHED');@@ -269,7 +348,7 @@ VALUES-- Verify that the latest build reflects the preview domainSELECT is ((- SELECT "buildId"+ SELECT ARRAY["buildId", "domain"]FROM "public"."latestBuildVirtual"((SELECT (p.*)::"Project"@@ -278,10 +357,26 @@ SELECT is ())),- 'build1-for-domain2-new',- 'Test Case 6: Should return the latest build for project1 with the preview domain in domains array.'+ ARRAY['build1-for-domain2-new', 'project1-domain2'],+ 'Test Case 6.1: Should return the latest build for project1 with the preview domain in domains array.'+);++SELECT is (+ (+ SELECT ARRAY["buildId", "domain"]+ FROM "public"."latestProjectDomainBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ ARRAY['build1-for-domain2-new', 'project1-domain2'],+ 'Test Case 6.2: Should return the latest build for project1 with the preview domain in domains array.');+---------------------------------------------------------------------------------- Test Case 7: Publish a New Build for a Custom Domain, Delete the Custom Domain, and Verify Latest Build Update--------------------------------------------------------------------------------@@ -301,7 +396,7 @@ VALUES'2023-01-04 00:00:00+00','home','project1',- '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '{"domains": ["some-other-domain.com", "517cce32-9af3-project-1-custom-domain-1.com"]}'::text,'2023-01-04 00:00:00+00','PUBLISHED');diff --git a/packages/postgrest/supabase/tests/project-domains.sql b/packages/postgrest/supabase/tests/project-domains.sqlindex b1120da71f..08ca2d7467 100644--- a/packages/postgrest/supabase/tests/project-domains.sql+++ b/packages/postgrest/supabase/tests/project-domains.sql@@ -8,19 +8,19 @@ SELECT no_plan();-- We're inserting user_1 as the user for the test projectsINSERT INTO "public"."User" ("id", "createdAt", "email", "username")VALUES- ('user_1', '2023-01-01 00:00:00+00', '[email protected]', 'user1');+ ('user_1', '2023-01-01 00:00:00+00', '[email protected]', 'user1');-- Insert test projects into the Project table-- project_1 and project_2 belong to user_1 and are not deleted (isDeleted = false)INSERT INTO "Project" (id, title, domain, "userId", "isDeleted") VALUES-('project_1', 'Test Project 1', 'testproject1.com', 'user_1', false),-('project_2', 'Test Project 1', 'testproject2.com', 'user_1', false);+('project_1', 'Test Project 1', '517cce32-9af3-testproject1.com', 'user_1', false),+('project_2', 'Test Project 1', '517cce32-9af3-testproject2.com', 'user_1', false);-- Insert test domains into the Domain table--- We are inserting two domains: example.com and example.org with different statuses+-- We are inserting two domains: 517cce32-9af3-example.com and 517cce32-9af3-example.org with different statusesINSERT INTO "Domain" (id, domain, status, "txtRecord") VALUES-('domain_1', 'example.com', 'INITIALIZING', 'txtRecord1'),-('domain_2', 'example.org', 'ACTIVE', 'txtRecord21');+('domain_1', '517cce32-9af3-example.com', 'INITIALIZING', 'txtRecord1'),+('domain_2', '517cce32-9af3-example.org', 'ACTIVE', 'txtRecord21');-- Insert test data into the ProjectDomain table-- Mapping domains to projects, project_1 has two domains, project_2 has one domain@@ -43,8 +43,8 @@ SELECT results_eq($$SELECT * FROM (VALUES- ('example.com','INITIALIZING'::"DomainStatus",NULL,E'txtRecord1',E'txtRecord1',TRUE), -- Verified domain (TXT records match)- ('example.org','ACTIVE'::"DomainStatus",NULL,E'txtRecord21',E'txtRecord22',FALSE) -- Not verified domain (TXT records do not match)+ ('517cce32-9af3-example.com','INITIALIZING'::"DomainStatus",NULL,E'txtRecord1',E'txtRecord1',TRUE), -- Verified domain (TXT records match)+ ('517cce32-9af3-example.org','ACTIVE'::"DomainStatus",NULL,E'txtRecord21',E'txtRecord22',FALSE) -- Not verified domain (TXT records do not match)) AS expected(domain, status, error, "domainTxtRecord", "expectedTxtRecord", verified)ORDER BY "domain"$$,@@ -63,7 +63,7 @@ SELECT results_eq($$SELECT * FROM (VALUES- ('example.com','INITIALIZING'::"DomainStatus",NULL,E'txtRecord1',E'txtRecord3',FALSE) -- Not verified domain (TXT records do not match)+ ('517cce32-9af3-example.com','INITIALIZING'::"DomainStatus",NULL,E'txtRecord1',E'txtRecord3',FALSE) -- Not verified domain (TXT records do not match)) AS expected(domain, status, error, "domainTxtRecord", "expectedTxtRecord", verified)ORDER BY "domain"$$,diff --git a/packages/prisma-client/prisma/migrations/20240920091253_domain-ordering/migration.sql b/packages/prisma-client/prisma/migrations/20240920091253_domain-ordering/migration.sqlnew file mode 100644index 0000000000..78ead59d2f--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20240920091253_domain-ordering/migration.sql@@ -0,0 +1,34 @@+-- Create the "domainsVirtual" function to return all domain-related data for a specific project.+CREATE OR REPLACE FUNCTION "domainsVirtual"("Project")+RETURNS SETOF "domainsVirtual" AS $$+ -- This function retrieves all the domain information associated with a specific project by joining the Domain and ProjectDomain tables.+ -- It returns a result set conforming to the "domainsVirtual" structure, including fields such as domain status, error, verification status, etc.+ SELECT+ "Domain".id || '-' || "ProjectDomain"."projectId" as id,+ "Domain".id AS "domainId", -- Domain ID from Domain table+ "ProjectDomain"."projectId", -- Project ID from ProjectDomain table+ "Domain".domain, -- Domain name+ "Domain".status, -- Current domain status+ "Domain".error, -- Error message, if any+ "Domain"."txtRecord" AS "domainTxtRecord", -- Current TXT record from Domain table+ "ProjectDomain"."txtRecord" AS "expectedTxtRecord", -- Expected TXT record from ProjectDomain table+ "ProjectDomain"."cname" AS "cname",+ CASE+ WHEN "Domain"."txtRecord" = "ProjectDomain"."txtRecord" THEN true -- If TXT records match, domain is verified+ ELSE false+ END AS "verified", -- Boolean flag for verification status+ "ProjectDomain"."createdAt", -- Creation timestamp from ProjectDomain table+ "Domain"."updatedAt" -- Last updated timestamp from Domain table+ FROM+ "Domain"+ JOIN+ "ProjectDomain" ON "Domain".id = "ProjectDomain"."domainId" -- Joining Domain and ProjectDomain on domainId+ WHERE+ "ProjectDomain"."projectId" = $1.id -- Filtering by projectId passed as an argument to the function+ ORDER BY "ProjectDomain"."createdAt", "Domain".id; -- Stable sort+$$+STABLE+LANGUAGE sql;++-- Add function-specific comments to explain its behavior.+COMMENT ON FUNCTION "domainsVirtual"("Project") IS 'Function that retrieves domain-related data for a given project by joining the Domain and ProjectDomain tables. It returns a result set that conforms to the structure defined in the domainsVirtual virtual table.';diff --git a/packages/prisma-client/prisma/migrations/20240924174536_cleanup/migration.sql b/packages/prisma-client/prisma/migrations/20240924174536_cleanup/migration.sqlnew file mode 100644index 0000000000..a9f7496a1a--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20240924174536_cleanup/migration.sql@@ -0,0 +1,81 @@+ALTER TABLE "Build" ADD COLUMN "isCleaned" BOOLEAN DEFAULT FALSE;++-- PostgREST will use this function as a computed field+-- See: https://docs.postgrest.org/en/v12/references/api/resource_embedding.html#computed-relationships+CREATE OR REPLACE FUNCTION "latestProjectDomainBuildVirtual"("Project")+RETURNS SETOF "latestBuildVirtual"+ROWS 1 AS $$ -- The function is expected to return 1 row++-- This function selects the latest build for a given project domain where:+-- 1. The "deployment" field is not NULL, ensuring it is a production build.+-- 2. The 'destination' field in the JSONB "deployment" is either NULL (for backward compatibility)+-- or equal to 'saas', indicating a non-static build.+-- 3. The selected "domain" must exist in the "Domain" table (many-to-many relation with "Project" via "ProjectDomain")+-- or it must match the "Project.domain" field directly.+-- 4. If 'projectDomain' exists in the JSONB "deployment", it is used as the "domain".+-- If not, the first element of 'domains' in the JSONB "deployment" array is used as the "domain".+-- The function returns the most recent (by "createdAt") valid build.+SELECT+ b.id AS "buildId",+ b."projectId",+ '' as "domainsVirtualId",+ p.domain AS "domain",+ b."createdAt",+ b."publishStatus"+FROM "Build" b+JOIN "Project" p ON b."projectId" = p.id+LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id+WHERE b."projectId" = $1.id+ AND b.deployment IS NOT NULL+ -- 'destination' IS NULL for backward compatibility; 'destination' = 'saas' for non-static builds+ AND ((b.deployment::jsonb ->> 'destination') IS NULL OR (b.deployment::jsonb ->> 'destination') = 'saas')+ AND (+ -- Check if 'projectDomain' matches p.domain+ (b.deployment::jsonb ->> 'projectDomain') = p.domain+ -- Check if 'domains' contains p.domain or d.domain+ OR (b.deployment::jsonb -> 'domains') @> to_jsonb(array[p.domain])+ )+ORDER BY b."createdAt" DESC+LIMIT 1;+$$+STABLE+LANGUAGE sql;++-- Comment on the function to provide additional context+COMMENT ON FUNCTION "latestProjectDomainBuildVirtual"("Project") IS 'This function computes the latest build for a project domain, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.';++++CREATE OR REPLACE FUNCTION database_cleanup(+ from_date timestamp DEFAULT '2020-01-01 00:00:00',+ to_date timestamp DEFAULT '2099-12-31 23:59:59' -- SQL should die long before this date!+) RETURNS VOID AS $$+BEGIN+ WITH latest_builds AS (+ SELECT "buildId" FROM "Project" p, LATERAL "latestProjectDomainBuildVirtual"(p)+ UNION+ SELECT "buildId" FROM "Project" p, LATERAL "latestBuildVirtual"(p)+ UNION+ SELECT lb."buildId"+ FROM "Project" p, LATERAL "domainsVirtual"(p) dv, LATERAL "latestBuildVirtual"(dv) lb+ )+ UPDATE "Build"+ SET+ "styleSources" = '[]'::text,+ styles = '[]'::text,+ breakpoints = '[]'::text,+ "styleSourceSelections" = '[]'::text,+ props = '[]'::text,+ instances = '[]'::text,+ "dataSources" = '[]'::text,+ resources = '[]'::text,+ "marketplaceProduct" = '{}'::text,+ "isCleaned" = TRUE+ WHERE deployment IS NOT NULL+ AND id NOT IN (SELECT "buildId" FROM latest_builds)+ AND "isCleaned" = FALSE+ AND "createdAt" BETWEEN from_date AND to_date; -- Filter by date range (for testing purposes)+END;+$$ LANGUAGE plpgsql;++-- SELECT database_cleanup();diff --git a/packages/sdk/src/schema/deployment.ts b/packages/sdk/src/schema/deployment.tsindex a41b1e0bcc..bb61b61833 100644--- a/packages/sdk/src/schema/deployment.ts+++ b/packages/sdk/src/schema/deployment.ts@@ -23,7 +23,12 @@ export const Deployment = z.union([z.object({destination: z.literal("saas").optional(),domains: z.array(z.string()),- projectDomain: z.string(),+ assetsDomain: z.string().optional(),+ /**+ * @deprecated This field is deprecated, use `domains` instead.+ */+ projectDomain: z.string().optional(),+ excludeWstdDomainFromSearch: z.boolean().optional(),}),]);diff --git a/packages/trpc-interface/src/shared/deployment.ts b/packages/trpc-interface/src/shared/deployment.tsindex 6e24ad5ce7..2dc10dc169 100644--- a/packages/trpc-interface/src/shared/deployment.ts+++ b/packages/trpc-interface/src/shared/deployment.ts@@ -1,7 +1,8 @@import { z } from "zod";import { router, procedure } from "./trpc";-const PublishInput = z.object({+// Has corresponding type in saas+export const PublishInput = z.object({// used to load build data from the builder see routes/rest.build.$buildId.tsbuildId: z.string(),builderOrigin: z.string(),@@ -11,10 +12,10 @@ const PublishInput = z.object({// preview supportbranchName: z.string(),// action log helper (not used for deployment, but for action logs readablity)- projectDomainName: z.string(),+ logProjectName: z.string(),});-const Output = z.discriminatedUnion("success", [+export const Output = z.discriminatedUnion("success", [z.object({success: z.literal(true),}),