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
chore: new Domain publish prepare steps (#4125)
Ivan Starkov3434322cb0b0
diff --git a/.github/workflows/migrate.yaml b/.github/workflows/migrate.yamlindex 4bb128b532..e87db669b6 100644--- a/.github/workflows/migrate.yaml+++ b/.github/workflows/migrate.yaml@@ -57,6 +57,29 @@ jobs:env:DIRECT_URL: ${{ secrets.DIRECT_URL }}+ # Execute db tests (@todo: can be done only after applying the migrations, now always())+ db-tests:+ if: always()++ needs: [migrate]++ runs-on: ubuntu-latest++ environment:+ name: ${{ (startsWith(github.ref_name, 'release') && endsWith(github.ref_name, '.staging')) && 'postgres_production' || 'postgres_development' }}++ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ github.sha }} # HEAD commit instead of merge commit++ - uses: pnpm/action-setup@v4++ - name: pnpm instal+ run: pnpm -r db-test+ env:+ DIRECT_URL: ${{ secrets.DIRECT_URL }}+# Prints pending migrationspending:if: always()diff --git a/.gitignore b/.gitignoreindex f15eedb8d6..6d0587466c 100644--- a/.gitignore+++ b/.gitignore@@ -60,4 +60,6 @@ tsconfig.tsbuildinfodist# should be here otherwise if placed inside prisma-client pnpm deploy doesn't copy it-packages/prisma-client/src/__generated__\ No newline at end of file+packages/prisma-client/src/__generated__++.temp\ No newline at end of filediff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsxindex c80bed8a8c..94983fdf8b 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsx+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.stories.tsx@@ -71,11 +71,18 @@ $project.set({isDeleted: false,userId: "userId",domain: "new-2x9tcd",++ marketplaceApprovalStatus: "UNLISTED",++ latestStaticBuild: null,+ previewImageAssetId: null,previewImageAsset: {- id: "0",- name: "0",+ projectId: "projectId",+ id: "imageId",+ name: "very-very-very-long-long-image-name.jpg",},- marketplaceApprovalStatus: "UNLISTED",+ latestBuildVirtual: null,+ domainsVirtual: [],});export const PageSettingsEdit = () => {diff --git a/apps/builder/app/builder/features/topbar/domains.tsx b/apps/builder/app/builder/features/topbar/domains.tsxindex 4fe747a6b3..06efece2b3 100644--- a/apps/builder/app/builder/features/topbar/domains.tsx+++ b/apps/builder/app/builder/features/topbar/domains.tsx@@ -21,34 +21,14 @@ import {import type { DomainStatus } from "@webstudio-is/prisma-client";import { CollapsibleDomainSection } from "./collapsible-domain-section";import { useCallback, useEffect, useState } from "react";-import type { PublishStatus } from "@webstudio-is/prisma-client";import { formatDistance } from "date-fns/formatDistance";import { Entri } from "./entri";import { trpcClient } from "~/shared/trpc/trpc-client";import { useStore } from "@nanostores/react";import { $publisherHost } from "~/shared/nano-states";+import type { Database } from "@webstudio-is/postrest/index.server";-export type Domain = {- projectId: Project["id"];- domainId: string;- domain: {- domain: string;- error: string | null;- status: DomainStatus;- updatedAt: string;- };- txtRecord: string;- cname: string;- verified: boolean;- latestBuid: null | {- projectId: string;- buildId: string;- isLatestBuild: boolean;- publishStatus: PublishStatus;- updatedAt: string;- domainId: string;- };-};+export type Domain = Project["domainsVirtual"][number];const InputEllipsis = styled(InputField, {"&>input": {@@ -79,21 +59,58 @@ const getCname = (domain: string) => {return cnameArray.join(".");};-export const getStatus = (projectDomain: Domain) =>+export const getStatus = (projectDomain: Project["domainsVirtual"][number]) =>projectDomain.verified- ? (`VERIFIED_${projectDomain.domain.status}` as const)+ ? (`VERIFIED_${projectDomain.status}` as const): `UNVERIFIED`;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 = ({- updatedAt,+ createdAt,publishStatus,-}: Pick<NonNullable<Domain["latestBuid"]>, "updatedAt" | "publishStatus">) => {+}: Pick<+ NonNullable<Domain["latestBuildVirtual"]>,+ "createdAt" | "publishStatus"+>) => {let status = publishStatus;- const delta = Date.now() - new Date(updatedAt).getTime();+ const delta = Date.now() - new Date(createdAt).getTime();// Assume build failed after 3 minutesif (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) {@@ -108,7 +125,7 @@ export const getPublishStatusAndText = ({: "Publishing started";const statusText = `${textStart} ${formatDistance(- new Date(updatedAt),+ new Date(createdAt),new Date(),{addSuffix: true,@@ -142,9 +159,9 @@ const getStatusText = (props: {isVerifiedActive = true;text = "Status: Active, not published";- if (props.projectDomain.latestBuid !== null) {+ if (props.projectDomain.latestBuildVirtual !== null) {const publishText = getPublishStatusAndText(- props.projectDomain.latestBuid+ props.projectDomain.latestBuildVirtual);text = publishText.statusText;@@ -152,7 +169,7 @@ const getStatusText = (props: {}break;case "VERIFIED_ERROR":- text = props.projectDomain.domain.error ?? text;+ text = props.projectDomain.error ?? text;break;default:@@ -237,16 +254,16 @@ const DomainItem = (props: {props.domainState !== "idle";const status = props.projectDomain.verified- ? (`VERIFIED_${props.projectDomain.domain.status}` as `VERIFIED_${DomainStatus}`)+ ? (`VERIFIED_${props.projectDomain.status}` as `VERIFIED_${DomainStatus}`): `UNVERIFIED`;const { initiallyOpen } = props;const domainId = props.projectDomain.domainId;- const domain = props.projectDomain.domain.domain;- const domainStatus = props.projectDomain.domain.status;- const domainError = props.projectDomain.domain.error;- const domainUpdatedAt = props.projectDomain.domain.updatedAt;+ 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@@ -365,7 +382,7 @@ const DomainItem = (props: {const txtRecord = {type: "TXT",host: txtEntryName,- value: props.projectDomain.txtRecord,+ value: props.projectDomain.expectedTxtRecord,ttl: 300,} as const;@@ -589,9 +606,9 @@ export const Domains = ({<>{domains.map((projectDomain) => (<DomainItem- key={projectDomain.domain.domain}+ key={projectDomain.domain}projectDomain={projectDomain}- initiallyOpen={newDomains.has(projectDomain.domain.domain)}+ initiallyOpen={newDomains.has(projectDomain.domain)}refreshDomainResult={refreshDomainResult}domainState={domainState}isPublishing={isPublishing}diff --git a/apps/builder/app/builder/features/topbar/publish.tsx b/apps/builder/app/builder/features/topbar/publish.tsxindex 7373846c3d..2003a16f77 100644--- a/apps/builder/app/builder/features/topbar/publish.tsx+++ b/apps/builder/app/builder/features/topbar/publish.tsx@@ -43,10 +43,10 @@ import { validateProjectDomain, type Project } from "@webstudio-is/project";import { $authPermit, $project, $publishedOrigin } from "~/shared/nano-states";import {Domains,- getPublishStatusAndText,getStatus,type Domain,PENDING_TIMEOUT,+ getPublishStatusAndTextNew,} from "./domains";import { CollapsibleDomainSection } from "./collapsible-domain-section";import {@@ -154,8 +154,8 @@ const ChangeProjectDomain = ({};const { statusText, status } =- project.latestBuild != null- ? getPublishStatusAndText(project.latestBuild)+ project.latestBuildVirtual != null+ ? getPublishStatusAndTextNew(project.latestBuildVirtual): {statusText: "Not published",status: "PENDING" as const,@@ -335,7 +335,7 @@ const Publish = ({{projectId: project.id,domains: domainsToPublish.map(- (projectDomain) => projectDomain.domain.domain+ (projectDomain) => projectDomain.domain),destination: "saas",},@@ -355,7 +355,10 @@ const Publish = ({const getStaticPublishStatusAndText = ({updatedAt,publishStatus,-}: Pick<NonNullable<Domain["latestBuid"]>, "updatedAt" | "publishStatus">) => {+}: {+ updatedAt: string;+ publishStatus: string;+}) => {let status = publishStatus;const delta = Date.now() - new Date(updatedAt).getTime();@@ -572,13 +575,6 @@ const Content = (props: {}) => {const [newDomains, setNewDomains] = useState(new Set<string>());- const {- data: domainsResult,- load: domainRefresh,- state: domainState,- error: domainSystemError,- } = trpcClient.domain.findMany.useQuery();-const {load: projectLoad,data: projectData,@@ -588,40 +584,27 @@ const Content = (props: {useEffect(() => {projectLoad({ projectId: props.projectId });- domainRefresh({ projectId: props.projectId });- }, [domainRefresh, props.projectId, projectLoad]);+ }, [props.projectId, projectLoad]);++ projectData?.success;const domainsToPublish = useMemo(() =>- domainsResult?.success- ? domainsResult.data.filter(+ projectData?.success+ ? projectData.project.domainsVirtual.filter((projectDomain) => getStatus(projectDomain) === "VERIFIED_ACTIVE"): [],- [domainsResult]+ [projectData]);- const latestBuilds = useMemo(- () => [- projectData?.success ? (projectData.project.latestBuild ?? null) : null,- ...domainsToPublish.map((domain) => domain.latestBuid),- ],- [domainsToPublish, projectData]- );+ const latestBuildVirtual = projectData?.success+ ? (projectData.project.latestBuildVirtual ?? undefined)+ : undefined;- const hasPendingState = useMemo(- () =>- latestBuilds.some((latestBuild) => {- if (latestBuild === null) {- return false;- }- const { status } = getPublishStatusAndText(latestBuild);- if (status === "PENDING") {- return true;- }- }),- [latestBuilds]- );+ const hasPendingState = latestBuildVirtual+ ? getPublishStatusAndTextNew(latestBuildVirtual).status === "PENDING"+ : false;const [isPublishing, setIsPublishing] = useState(hasPendingState);@@ -669,31 +652,23 @@ const Content = (props: {/>)}- {domainsResult?.success === true && (+ {projectData?.success && (<DomainsnewDomains={newDomains}- domains={domainsResult.data}- refreshDomainResult={domainRefresh}- domainState={domainState}+ domains={projectData.project.domainsVirtual}+ refreshDomainResult={projectLoad}+ domainState={projectState}isPublishing={isPublishing}/>)}-- {domainSystemError !== undefined && (- <ErrorText>{domainSystemError}</ErrorText>- )}-- {domainsResult?.success === false && (- <ErrorText>{domainsResult.error}</ErrorText>- )}</ScrollArea><Flex direction="column" justify="end" css={{ height: 0 }}><Separator /></Flex><AddDomainprojectId={props.projectId}- refreshDomainResult={domainRefresh}- domainState={domainState}+ refreshDomainResult={projectLoad}+ domainState={projectState}onCreate={(domain) => {setNewDomains((prev) => {return new Set([...prev, domain]);@@ -708,7 +683,6 @@ const Content = (props: {domainsToPublish={domainsToPublish}refresh={() => {projectLoad({ projectId: props.projectId });- domainRefresh({ projectId: props.projectId });}}isPublishing={isPublishing}setIsPublishing={setIsPublishing}diff --git a/apps/builder/app/builder/shared/sync/sync-server.ts b/apps/builder/app/builder/shared/sync/sync-server.tsindex 523d139f89..f27b052521 100644--- a/apps/builder/app/builder/shared/sync/sync-server.ts+++ b/apps/builder/app/builder/shared/sync/sync-server.ts@@ -1,6 +1,6 @@import { useEffect } from "react";import { atom } from "nanostores";-import { Project } from "@webstudio-is/project";+import type { Project } from "@webstudio-is/project";import type { Build } from "@webstudio-is/project-build";import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";import * as commandQueue from "./command-queue";diff --git a/apps/builder/app/dashboard/dashboard.stories.tsx b/apps/builder/app/dashboard/dashboard.stories.tsxindex faa89d4577..6813a5cc96 100644--- a/apps/builder/app/dashboard/dashboard.stories.tsx+++ b/apps/builder/app/dashboard/dashboard.stories.tsx@@ -2,6 +2,7 @@ import type { StoryFn } from "@storybook/react";import { createBrowserRouter, RouterProvider } from "react-router-dom";import { Dashboard } from "./dashboard";import type { UserPlanFeatures } from "~/shared/db/user-plan-features.server";+import type { DashboardProject } from "@webstudio-is/dashboard";export default {title: "Dashboard / Projects",@@ -56,13 +57,19 @@ export const WithProjects: StoryFn<typeof Dashboard> = () => {createdAt: new Date().toString(),title: "My Project",domain: "domain.com",- userId: null,+ userId: "",isDeleted: false,isPublished: false,latestBuild: null,- previewImageAsset: null,+ previewImageAsset: {+ id: "0",+ projectId: "0",+ name: "preview.jpg",+ },+ previewImageAssetId: "",+ latestBuildVirtual: null,marketplaceApprovalStatus: "UNLISTED" as const,- },+ } as DashboardProject,];const router = createRouter(<Dashboarddiff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsxindex ea4a4b4d7c..3a2d425be3 100644--- a/apps/builder/app/dashboard/projects/project-card.tsx+++ b/apps/builder/app/dashboard/projects/project-card.tsx@@ -167,7 +167,7 @@ export const ProjectCard = ({domain,isPublished,createdAt,- latestBuild,+ latestBuildVirtual,previewImageAsset,},hasProPlan,@@ -256,10 +256,10 @@ export const ProjectCard = ({content={<Text variant="small">Created on {formatDate(createdAt)}- {latestBuild?.publishStatus === "PUBLISHED" && (+ {latestBuildVirtual?.publishStatus === "PUBLISHED" && (<><br />- Published on {formatDate(latestBuild.updatedAt)}+ Published on {formatDate(latestBuildVirtual.createdAt)}</>)}</Text>diff --git a/apps/builder/app/routes/rest.buildId.$projectId.tsx b/apps/builder/app/routes/rest.buildId.$projectId.tsxindex f0eb1a4351..360315fec0 100644--- a/apps/builder/app/routes/rest.buildId.$projectId.tsx+++ b/apps/builder/app/routes/rest.buildId.$projectId.tsx@@ -34,7 +34,7 @@ export const loader = async ({const context = await createContext(request);const project = await projectDb.project.loadById(projectId, context);- const buildId = project.latestBuild?.buildId ?? null;+ const buildId = project.latestBuildVirtual?.buildId ?? null;return {buildId,diff --git a/apps/builder/app/shared/clone-project.tsx b/apps/builder/app/shared/clone-project.tsxindex 2d2ccd48d2..708303cf3a 100644--- a/apps/builder/app/shared/clone-project.tsx+++ b/apps/builder/app/shared/clone-project.tsx@@ -14,7 +14,7 @@ import {DialogActions,toast,} from "@webstudio-is/design-system";-import { Title, Project } from "@webstudio-is/project";+import { Title, type Project } from "@webstudio-is/project";import { nativeClient } from "./trpc/trpc-client";import { useEffectEvent } from "./hook-utils/effect-event";diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsxindex ca087625df..deda45fa4b 100644--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.test.tsx@@ -100,6 +100,10 @@ beforeEach(() => {isDeleted: false,previewImageAsset: null,marketplaceApprovalStatus: "PENDING",+ latestStaticBuild: null,+ domainsVirtual: [],+ latestBuildVirtual: null,+ previewImageAssetId: null,});$breakpoints.set(diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex 011a552a0f..836e556f75 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -4,7 +4,7 @@ import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { findPageByIdOrPath, getStyleDeclKey } from "@webstudio-is/sdk";import type { Build } from "@webstudio-is/prisma-client";-import { db as domainDb } from "@webstudio-is/domain/index.server";+import { db as projectDb } from "@webstudio-is/project/index.server";const getPair = <Item extends { id: string }>(item: Item): [string, Item] => [item.id,@@ -27,16 +27,9 @@ export const loadProductionCanvasData = async (throw new Error("The project is not published");}- const currentProjectDomainsResult = await domainDb.findMany(- { projectId: build.projectId },- context- );-- if (currentProjectDomainsResult.success === false) {- throw new Error(currentProjectDomainsResult.error);- }+ const project = await projectDb.project.loadById(build.projectId, context);- const currentProjectDomains = currentProjectDomainsResult.data;+ const currentProjectDomains = project.domainsVirtual;// Check that build deployment domains are still active and verified// for examle: redeploy created few days later@@ -44,8 +37,8 @@ export const loadProductionCanvasData = async (deployment.domains = deployment.domains.filter((domain) =>currentProjectDomains.some((projectDomain) =>- projectDomain.domain.domain === domain &&- projectDomain.domain.status === "ACTIVE" &&+ projectDomain.domain === domain &&+ projectDomain.status === "ACTIVE" &&projectDomain.verified));diff --git a/apps/builder/app/shared/marketplace/db.server.ts b/apps/builder/app/shared/marketplace/db.server.tsindex 78ba7bc312..d033a7b4a5 100644--- a/apps/builder/app/shared/marketplace/db.server.ts+++ b/apps/builder/app/shared/marketplace/db.server.ts@@ -5,7 +5,7 @@ import {parseConfig,} from "@webstudio-is/project-build/index.server";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";-import { Project } from "@webstudio-is/project";+import type { Project } from "@webstudio-is/project";import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";export const getBuildProdData = async (diff --git a/packages/dashboard/src/db/index.ts b/packages/dashboard/src/db/index.tsindex 18f7d72b27..c55f927311 100644--- a/packages/dashboard/src/db/index.ts+++ b/packages/dashboard/src/db/index.ts@@ -1,2 +1 @@export * as db from "./projects";-export * from "./schema";diff --git a/packages/dashboard/src/db/projects.ts b/packages/dashboard/src/db/projects.tsindex 35350e3afb..657120b61f 100644--- a/packages/dashboard/src/db/projects.ts+++ b/packages/dashboard/src/db/projects.ts@@ -3,7 +3,8 @@ import {AuthorizationError,type AppContext,} from "@webstudio-is/trpc-interface/index.server";-import type { DashboardProjects } from "./schema";++export type DashboardProject = Awaited<ReturnType<typeof findMany>>[number];export const findMany = async (userId: string, context: AppContext) => {if (context.authorization.type !== "user") {@@ -20,7 +21,7 @@ export const findMany = async (userId: string, context: AppContext) => {const data = await context.postgrest.client.from("DashboardProject")- .select("*, previewImageAsset:Asset (*)")+ .select("*, previewImageAsset:Asset (*), latestBuildVirtual (*)").eq("userId", userId).eq("isDeleted", false).order("createdAt", { ascending: false })@@ -28,9 +29,16 @@ export const findMany = async (userId: string, context: AppContext) => {if (data.error) {throw data.error;}+return data.data as SetNonNullable<- (typeof data.data)[number]- >[] satisfies DashboardProjects;+ (typeof data.data)[number],+ | "id"+ | "title"+ | "domain"+ | "isDeleted"+ | "createdAt"+ | "marketplaceApprovalStatus"+ >[];};export const findManyByIds = async (@@ -42,7 +50,7 @@ export const findManyByIds = async (}const data = await context.postgrest.client.from("DashboardProject")- .select("*, previewImageAsset:Asset (*)")+ .select("*, previewImageAsset:Asset (*), latestBuildVirtual (*)").in("id", projectIds).eq("isDeleted", false).order("createdAt", { ascending: false })@@ -51,6 +59,12 @@ export const findManyByIds = async (throw data.error;}return data.data as SetNonNullable<- (typeof data.data)[number]- >[] satisfies DashboardProjects;+ (typeof data.data)[number],+ | "id"+ | "title"+ | "domain"+ | "isDeleted"+ | "createdAt"+ | "marketplaceApprovalStatus"+ >[];};diff --git a/packages/dashboard/src/db/schema.ts b/packages/dashboard/src/db/schema.tsdeleted file mode 100644index 2cee5a407b..0000000000--- a/packages/dashboard/src/db/schema.ts+++ /dev/null@@ -1,10 +0,0 @@-import { Project } from "@webstudio-is/project";-import { z } from "zod";--export const DashboardProject = Project.extend({- isPublished: z.boolean(),-});-export type DashboardProject = z.infer<typeof DashboardProject>;--export const DashboardProjects = z.array(DashboardProject);-export type DashboardProjects = z.infer<typeof DashboardProjects>;diff --git a/packages/dashboard/src/index.ts b/packages/dashboard/src/index.tsindex 18b0f48e1e..72615097a7 100644--- a/packages/dashboard/src/index.ts+++ b/packages/dashboard/src/index.ts@@ -1,2 +1,2 @@export type { DashboardProjectRouter } from "./trpc";-export * from "./db/schema";+export type { DashboardProject } from "./db/projects";diff --git a/packages/domain/package.json b/packages/domain/package.jsonindex 412da2501d..b719c5e92c 100644--- a/packages/domain/package.json+++ b/packages/domain/package.json@@ -9,12 +9,13 @@"typecheck": "tsc"},"dependencies": {- "@webstudio-is/prisma-client": "workspace:*","@webstudio-is/project": "workspace:*","@webstudio-is/project-build": "workspace:*","@webstudio-is/trpc-interface": "workspace:*","@webstudio-is/sdk": "workspace:*",+ "@webstudio-is/postrest": "workspace:*","nanoid": "^5.0.1",+ "type-fest": "^4.24.0","zod": "^3.22.4"},"devDependencies": {diff --git a/packages/domain/src/db/domain.ts b/packages/domain/src/db/domain.tsindex 8443fd19f0..d9e4081b01 100644--- a/packages/domain/src/db/domain.ts+++ b/packages/domain/src/db/domain.ts@@ -1,10 +1,3 @@-import {- prisma,- type Project,- type Domain,- type ProjectWithDomain,- type LatestBuildPerProjectDomain,-} from "@webstudio-is/prisma-client";import {authorizeProject,type AppContext,@@ -13,53 +6,8 @@ import {import { db as projectDb } from "@webstudio-is/project/index.server";import { validateDomain } from "./validate";import { cnameFromUserId } from "./cname-from-user-id";--export type ProjectDomain = ProjectWithDomain & {- domain: Domain;- latestBuid: null | LatestBuildPerProjectDomain;-};--const getProjectDomains = async (- projectId: Project["id"]-): Promise<ProjectDomain[]> =>- await prisma.projectWithDomain.findMany({- where: {- projectId,- },- include: {- domain: true,- latestBuid: true,- },- orderBy: [- {- createdAt: "asc",- },- ],- });--export const findMany = async (- props: { projectId: Project["id"] },- context: AppContext-): Promise<- { success: false; error: string } | { success: true; data: ProjectDomain[] }-> => {- // Only builder of the project can list domains- const canList = await authorizeProject.hasProjectPermit(- { projectId: props.projectId, permit: "view" },- context- );-- if (canList === false) {- throw new Error("You don't have access to list this project domains");- }-- const projectDomains = await getProjectDomains(props.projectId);-- return {- success: true,- data: projectDomains,- };-};+import type { Project } from "@webstudio-is/project";+import type { Database } from "@webstudio-is/postrest/index.server";type Result = { success: false; error: string } | { success: true };@@ -95,7 +43,7 @@ export const create = async (throw new AuthorizationError("Project must have project userId defined");}- const totalDomainsCount = await countTotalDomains(ownerId);+ const totalDomainsCount = await countTotalDomains(ownerId, context);if (totalDomainsCount >= props.maxDomainsAllowedPerUser) {return {@@ -114,31 +62,48 @@ export const create = async (const { domain } = validationResult;// Create domain in domain table- const dbDomain = await prisma.domain.upsert({- update: {- domain,- },- create: {- domain,- status: "INITIALIZING",- },- where: {- domain,- },- });+ const upsertResult = await context.postgrest.client+ .from("Domain")+ .upsert(+ {+ id: crypto.randomUUID(),+ domain,+ status: "INITIALIZING",+ },+ // Do not update if exists+ { onConflict: "domain", ignoreDuplicates: true }+ )+ .eq("domain", domain);+ if (upsertResult.error) {+ return { success: false, error: upsertResult.error.message };+ }++ // Get domain id (upsert in postgrest does not return anything in case of conflict and ignoreDuplicates)+ const domainRow = await context.postgrest.client+ .from("Domain")+ .select("id")+ .eq("domain", domain)+ .single();++ if (domainRow.error) {+ return { success: false, error: domainRow.error.message };+ }++ const domainId = domainRow.data.id;const txtRecord = crypto.randomUUID();- // Create project domain relation- await prisma.projectDomain.create({- data: {- domainId: dbDomain.id,- projectId: props.projectId,- txtRecord,- cname: await cnameFromUserId(ownerId),- },+ const result = await context.postgrest.client.from("ProjectDomain").insert({+ domainId,+ projectId: props.projectId,+ txtRecord,+ cname: await cnameFromUserId(ownerId),});+ if (result.error) {+ return { success: false, error: result.error.message };+ }+return { success: true };};@@ -162,35 +127,50 @@ export const verify = async (throw new Error("You don't have access to create this project domains");}- const projectDomain = await prisma.projectWithDomain.findFirstOrThrow({- where: {- projectId: props.projectId,- domainId: props.domainId,- },- include: {- domain: true,- },- });+ const projectDomain = await context.postgrest.client+ .from("ProjectDomain")+ .select(+ `+ txtRecord,+ cname,+ domain:Domain(*)+ `+ )+ .eq("domainId", props.domainId)+ .eq("projectId", props.projectId)+ .single();++ if (projectDomain.error) {+ return { success: false, error: projectDomain.error.message };+ }++ const domain = projectDomain.data.domain?.domain;++ if (domain == null) {+ return { success: false, error: "Domain not found" };+ }// @todo: TXT verification and domain initialization should be implemented in the future as queue serviceconst createDomainResult = await context.domain.domainTrpc.create.mutate({- domain: projectDomain.domain.domain,- txtRecord: projectDomain.txtRecord,+ domain,+ txtRecord: projectDomain.data.txtRecord,});if (createDomainResult.success === false) {return createDomainResult;}- await prisma.domain.update({- where: {- id: props.domainId,- },- data: {+ const domainUpdateResult = await context.postgrest.client+ .from("Domain")+ .update({status: "PENDING",- txtRecord: projectDomain.txtRecord,- },- });+ txtRecord: projectDomain.data.txtRecord,+ })+ .eq("id", props.domainId);++ if (domainUpdateResult.error) {+ return { success: false, error: domainUpdateResult.error.message };+ }return { success: true };};@@ -215,12 +195,15 @@ export const remove = async (throw new Error("You don't have access to delete this project domains");}- await prisma.projectDomain.deleteMany({- where: {- projectId: props.projectId,- domainId: props.domainId,- },- });+ const deleteResult = await context.postgrest.client+ .from("ProjectDomain")+ .delete()+ .eq("domainId", props.domainId)+ .eq("projectId", props.projectId);++ if (deleteResult.error) {+ return { success: false, error: deleteResult.error.message };+ }return { success: true };};@@ -228,6 +211,8 @@ export const remove = async (type Status = "active" | "pending" | "error";type StatusEnum = Uppercase<Status>;+type Domain = Database["public"]["Tables"]["Domain"]["Row"];+type RefreshResult =| { success: false; error: string }| { success: true; domain: Domain };@@ -277,39 +262,40 @@ export const updateStatus = async (const { data } = statusResult;- if (data.status === "error") {- // update domain status- const updatedDomain = await prisma.domain.update({- where: {- domain,- },- data: {- status: statusToStatusEnum(data.status),- error: data.error,- },- });-- return { success: true, domain: updatedDomain };- }-// update domain status- const updatedDomain = await prisma.domain.update({- where: {- domain,- },- data: {+ const updatedDomainResult = await context.postgrest.client+ .from("Domain")+ .update({status: statusToStatusEnum(data.status),- error: null,- },- });+ error: data.status === "error" ? data.error : null,+ })+ .eq("domain", domain)+ .select("*")+ .single();++ if (updatedDomainResult.error) {+ return { success: false, error: updatedDomainResult.error.message };+ }- return { success: true, domain: updatedDomain };+ return { success: true, domain: updatedDomainResult.data };};-export const countTotalDomains = async (userId: string): Promise<number> => {- return await prisma.projectWithDomain.count({- where: {- userId,- },- });+export const countTotalDomains = async (+ userId: string,+ context: AppContext+): Promise<number> => {+ const result = await context.postgrest.client+ .from("Domain")+ .select("Project!ProjectDomain!inner(id)", {+ count: "exact",+ head: true,+ })+ .eq("Project.userId", userId)+ .eq("Project.isDeleted", false);++ if (result.error) {+ throw result.error;+ }++ return result.count ?? 0;};diff --git a/packages/domain/src/db/index.ts b/packages/domain/src/db/index.tsindex 4d43cd0aa9..40dfe1ac71 100644--- a/packages/domain/src/db/index.ts+++ b/packages/domain/src/db/index.ts@@ -1,2 +1 @@export * as db from "./domain";-export type { ProjectDomain } from "./domain";diff --git a/packages/domain/src/trpc/domain.ts b/packages/domain/src/trpc/domain.tsindex 596b642409..c2f4bfd5d9 100644--- a/packages/domain/src/trpc/domain.ts+++ b/packages/domain/src/trpc/domain.ts@@ -1,6 +1,5 @@import { z } from "zod";import { nanoid } from "nanoid";-import type { Project } from "@webstudio-is/project";import { db as projectDb } from "@webstudio-is/project/index.server";import { createProductionBuild } from "@webstudio-is/project-build/index.server";import { router, procedure } from "@webstudio-is/trpc-interface/index.server";@@ -29,10 +28,7 @@ export const domainRouter = router({.input(z.object({ projectId: z.string() })).query(async ({ input, ctx }) => {try {- const project: Project = await projectDb.project.loadById(- input.projectId,- ctx- );+ const project = await projectDb.project.loadById(input.projectId, ctx);return {success: true,@@ -69,22 +65,13 @@ export const domainRouter = router({let domains: string[] = [];if (input.destination === "saas") {- const currentProjectDomainsResult = await db.findMany(- { projectId: input.projectId },- ctx- );-- if (currentProjectDomainsResult.success === false) {- throw new Error(currentProjectDomainsResult.error);- }-- const currentProjectDomains = currentProjectDomainsResult.data;+ const currentProjectDomains = project.domainsVirtual;domains = input.domains.filter((domain) =>currentProjectDomains.some((projectDomain) =>- projectDomain.domain.domain === domain &&- projectDomain.domain.status === "ACTIVE" &&+ projectDomain.domain === domain &&+ projectDomain.status === "ACTIVE" &&projectDomain.verified));@@ -252,23 +239,6 @@ export const domainRouter = router({} as const;}}),- findMany: procedure- .input(- z.object({- projectId: z.string(),- })- )- .query(async ({ input, ctx }) => {- try {- return await db.findMany({ projectId: input.projectId }, ctx);- } catch (error) {- return {- success: false,- error: error instanceof Error ? error.message : "Unknown error",- } as const;- }- }),-countTotalDomains: procedure.query(async ({ ctx }) => {try {if (@@ -283,7 +253,7 @@ export const domainRouter = router({? ctx.authorization.userId: ctx.authorization.ownerId;- const data = await db.countTotalDomains(ownerId);+ const data = await db.countTotalDomains(ownerId, ctx);return { success: true, data } as const;} catch (error) {return {diff --git a/packages/postgrest/README.md b/packages/postgrest/README.mdindex 89466cba87..579309d9e7 100644--- a/packages/postgrest/README.md+++ b/packages/postgrest/README.md@@ -18,8 +18,34 @@ cd /workspaces/webstudio/packages/postgrestpnpm generate-types```+## Playground++```bash+pnpm playground ./playground/{file}.ts+# OR+pnpm tsx --env-file ../../apps/builder/.env ./playground/{file}.ts+```+## Next steps.Use https://supabase.com/docs/reference/cli/supabase-db-start or directly https://github.com/djrobstep/migra for migrations.Supabase can be used with `--db-url` flag to not reproduce "local" env++## Sql testing++```sql+CREATE SCHEMA IF NOT EXISTS pgtap;+DROP EXTENSION pgtap;+CREATE EXTENSION IF NOT EXISTS pgtap WITH SCHEMA pgtap;+```++```bash+pnpx supabase test new latest-builds+```++```shell+docker run --rm --network host -v ./supabase/tests:/tests -e PGOPTIONS='--search_path=pgtap,public' supabase/pg_prove:3.36 pg_prove -d "postgresql://postgres:pass@localhost/webstudio" --ext .sql /tests+# OR+pnpm run db-test+```diff --git a/packages/postgrest/package.json b/packages/postgrest/package.jsonindex c56cb5bb77..e9cc2c3e57 100644--- a/packages/postgrest/package.json+++ b/packages/postgrest/package.json@@ -16,7 +16,9 @@"sideEffects": false,"scripts": {"typecheck": "tsc",- "generate-types": "pnpx supabase gen types --lang=typescript --db-url postgresql://postgres:pass@localhost/webstudio > ./src/__generated__/db-types.ts"+ "generate-types": "pnpx supabase gen types --lang=typescript --db-url postgresql://postgres:pass@localhost/webstudio > ./src/__generated__/db-types.ts",+ "playground": "pnpm tsx --env-file ../../apps/builder/.env",+ "db-test": "docker run --rm --network host -v ./supabase/tests:/tests -e PGOPTIONS='--search_path=pgtap,public' supabase/pg_prove:3.36 pg_prove -d ${DIRECT_URL:-postgresql://postgres:pass@localhost/webstudio} --ext .sql /tests"},"dependencies": {"@supabase/postgrest-js": "^1.16.0"diff --git a/packages/postgrest/playground/domains.ts b/packages/postgrest/playground/domains.tsnew file mode 100755index 0000000000..88782492a2--- /dev/null+++ b/packages/postgrest/playground/domains.ts@@ -0,0 +1,54 @@+#!/usr/bin/env ./playground/pnpm-playground++import { createClient } from "../src/index.server";++const client = createClient(+ process.env.POSTGREST_URL!,+ process.env.POSTGREST_API_KEY!+);++const result = await client+ .from("Project")+ .select("domainsVirtual(*, latestBuildVirtual(*))")+ .eq("id", "090e6e14-ae50-4b2e-bd22-71733cec05bb");++console.info(JSON.stringify(result, null, " "));++/*+const domain = "hello.world";+const result = await client+ .from("Domain")+ .upsert(+ {+ id: crypto.randomUUID(),+ domain,+ status: "INITIALIZING",+ error: null,+ },+ { onConflict: "domain", ignoreDuplicates: false }+ )+ .eq("domain", domain)+ .select("*");++console.info(JSON.stringify(result, null, " "));+*/++/*+const result = await client+ .from("ProjectWithDomain")+ .select("Domain(*), latestBuildVirtual(*)")+ .eq("projectId", "1bbe90ae-f0b3-4b2d-925f-26c75f824344");++ const result = await client+ .from("Project")+ .select(+ "ProjectDomain(Domain(*), latestBuildVirtual(*)), latestBuildVirtual(*)"+ )+ .eq("id", "1bbe90ae-f0b3-4b2d-925f-26c75f824344");++ if (result.error) {+ throw result.error;+ }++ console.info(JSON.stringify(result.data, null, " "));+ */diff --git a/packages/postgrest/playground/pnpm-playground b/packages/postgrest/playground/pnpm-playgroundnew file mode 100755index 0000000000..97e6578d0d--- /dev/null+++ b/packages/postgrest/playground/pnpm-playground@@ -0,0 +1,8 @@+#!/bin/bash++# !/usr/bin/env pnpm playground will not work+# The shebang line only takes a single path to an executable,+# and everything after the path is treated as a single string, not as separate arguments.++pnpm playground "$@"+diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.tsindex 4c7f46b14a..c9a6eb8fc9 100644--- a/packages/postgrest/src/__generated__/db-types.ts+++ b/packages/postgrest/src/__generated__/db-types.ts@@ -250,6 +250,73 @@ export type Database = {};Relationships: [];};+ domainsVirtual: {+ Row: {+ cname: string;+ createdAt: string;+ domain: string;+ domainId: string;+ domainTxtRecord: string | null;+ error: string | null;+ expectedTxtRecord: string;+ id: string;+ projectId: string;+ status: Database["public"]["Enums"]["DomainStatus"];+ updatedAt: string;+ verified: boolean;+ };+ Insert: {+ cname: string;+ createdAt: string;+ domain: string;+ domainId: string;+ domainTxtRecord?: string | null;+ error?: string | null;+ expectedTxtRecord: string;+ id: string;+ projectId: string;+ status?: Database["public"]["Enums"]["DomainStatus"];+ updatedAt: string;+ verified?: boolean;+ };+ Update: {+ cname?: string;+ createdAt?: string;+ domain?: string;+ domainId?: string;+ domainTxtRecord?: string | null;+ error?: string | null;+ expectedTxtRecord?: string;+ id?: string;+ projectId?: string;+ status?: Database["public"]["Enums"]["DomainStatus"];+ updatedAt?: string;+ verified?: boolean;+ };+ Relationships: [+ {+ foreignKeyName: "domainsVirtual_domainId_fkey";+ columns: ["domainId"];+ isOneToOne: false;+ referencedRelation: "Domain";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "domainsVirtual_projectId_fkey";+ columns: ["projectId"];+ isOneToOne: false;+ referencedRelation: "DashboardProject";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "domainsVirtual_projectId_fkey";+ columns: ["projectId"];+ isOneToOne: false;+ referencedRelation: "Project";+ referencedColumns: ["id"];+ },+ ];+ };File: {Row: {createdAt: string;@@ -304,6 +371,69 @@ export type Database = {},];};+ latestBuildVirtual: {+ Row: {+ buildId: string;+ createdAt: string;+ domain: string;+ domainsVirtualId: string;+ projectId: string;+ publishStatus: Database["public"]["Enums"]["PublishStatus"];+ };+ Insert: {+ buildId: string;+ createdAt: string;+ domain: string;+ domainsVirtualId: string;+ projectId: string;+ publishStatus: Database["public"]["Enums"]["PublishStatus"];+ };+ Update: {+ buildId?: string;+ createdAt?: string;+ domain?: string;+ domainsVirtualId?: string;+ projectId?: string;+ publishStatus?: Database["public"]["Enums"]["PublishStatus"];+ };+ Relationships: [+ {+ foreignKeyName: "latestBuildVirtual_buildId_fkey";+ columns: ["buildId"];+ isOneToOne: true;+ referencedRelation: "Build";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "latestBuildVirtual_buildId_fkey";+ columns: ["buildId"];+ isOneToOne: true;+ referencedRelation: "LatestStaticBuildPerProject";+ referencedColumns: ["buildId"];+ },+ {+ foreignKeyName: "latestBuildVirtual_domainsVirtualId_fkey";+ columns: ["domainsVirtualId"];+ isOneToOne: true;+ referencedRelation: "domainsVirtual";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "latestBuildVirtual_projectId_fkey";+ columns: ["projectId"];+ isOneToOne: true;+ referencedRelation: "DashboardProject";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "latestBuildVirtual_projectId_fkey";+ columns: ["projectId"];+ isOneToOne: true;+ referencedRelation: "Project";+ referencedColumns: ["id"];+ },+ ];+ };Product: {Row: {createdAt: string;@@ -412,13 +542,6 @@ export type Database = {referencedRelation: "Domain";referencedColumns: ["id"];},- {- foreignKeyName: "ProjectDomain_domainId_fkey";- columns: ["domainId"];- isOneToOne: false;- referencedRelation: "LatestBuildPerProjectDomain";- referencedColumns: ["domainId"];- },{foreignKeyName: "ProjectDomain_projectId_fkey";columns: ["projectId"];@@ -627,58 +750,6 @@ export type Database = {},];};- LatestBuildPerProject: {- Row: {- buildId: string | null;- domain: string | null;- isLatestBuild: boolean | null;- projectId: string | null;- publishStatus: Database["public"]["Enums"]["PublishStatus"] | null;- updatedAt: string | null;- };- Relationships: [- {- foreignKeyName: "Build_projectId_fkey";- columns: ["projectId"];- isOneToOne: false;- referencedRelation: "Project";- referencedColumns: ["id"];- },- {- foreignKeyName: "Build_projectId_fkey";- columns: ["projectId"];- isOneToOne: false;- referencedRelation: "DashboardProject";- referencedColumns: ["id"];- },- ];- };- LatestBuildPerProjectDomain: {- Row: {- buildId: string | null;- domainId: string | null;- isLatestBuild: boolean | null;- projectId: string | null;- publishStatus: Database["public"]["Enums"]["PublishStatus"] | null;- updatedAt: string | null;- };- Relationships: [- {- foreignKeyName: "Build_projectId_fkey";- columns: ["projectId"];- isOneToOne: false;- referencedRelation: "Project";- referencedColumns: ["id"];- },- {- foreignKeyName: "Build_projectId_fkey";- columns: ["projectId"];- isOneToOne: false;- referencedRelation: "DashboardProject";- referencedColumns: ["id"];- },- ];- };LatestStaticBuildPerProject: {Row: {buildId: string | null;@@ -703,54 +774,6 @@ export type Database = {},];};- ProjectWithDomain: {- Row: {- cname: string | null;- createdAt: string | null;- domainId: string | null;- projectId: string | null;- txtRecord: string | null;- userId: string | null;- verified: boolean | null;- };- Relationships: [- {- foreignKeyName: "Project_userId_fkey";- columns: ["userId"];- isOneToOne: false;- referencedRelation: "User";- referencedColumns: ["id"];- },- {- foreignKeyName: "ProjectDomain_domainId_fkey";- columns: ["domainId"];- isOneToOne: false;- referencedRelation: "Domain";- referencedColumns: ["id"];- },- {- foreignKeyName: "ProjectDomain_domainId_fkey";- columns: ["domainId"];- isOneToOne: false;- referencedRelation: "LatestBuildPerProjectDomain";- referencedColumns: ["domainId"];- },- {- foreignKeyName: "ProjectDomain_projectId_fkey";- columns: ["projectId"];- isOneToOne: false;- referencedRelation: "Project";- referencedColumns: ["id"];- },- {- foreignKeyName: "ProjectDomain_projectId_fkey";- columns: ["projectId"];- isOneToOne: false;- referencedRelation: "DashboardProject";- referencedColumns: ["id"];- },- ];- };UserProduct: {Row: {customerEmail: string | null;@@ -788,6 +811,62 @@ export type Database = {};Returns: string;};+ domainsVirtual: {+ Args: {+ "": unknown;+ };+ Returns: {+ cname: string;+ createdAt: string;+ domain: string;+ domainId: string;+ domainTxtRecord: string | null;+ error: string | null;+ expectedTxtRecord: string;+ id: string;+ projectId: string;+ status: Database["public"]["Enums"]["DomainStatus"];+ updatedAt: string;+ verified: boolean;+ }[];+ };+ f_is_json: {+ Args: {+ _txt: string;+ };+ Returns: boolean;+ };+ latestBuildVirtual:+ | {+ Args: {+ "": unknown;+ };+ Returns: {+ buildId: string;+ createdAt: string;+ domain: string;+ domainsVirtualId: string;+ projectId: string;+ publishStatus: Database["public"]["Enums"]["PublishStatus"];+ }[];+ }+ | {+ Args: {+ "": unknown;+ };+ Returns: {+ buildId: string;+ createdAt: string;+ domain: string;+ domainsVirtualId: string;+ projectId: string;+ publishStatus: Database["public"]["Enums"]["PublishStatus"];+ }[];+ };+ uuid_generate_v4: {+ Args: Record<PropertyKey, never>;+ Returns: string;+ };};Enums: {AuthorizationRelation:diff --git a/packages/postgrest/supabase/SQL-TESTS-AI.md b/packages/postgrest/supabase/SQL-TESTS-AI.mdnew file mode 100644index 0000000000..579435461e--- /dev/null+++ b/packages/postgrest/supabase/SQL-TESTS-AI.md@@ -0,0 +1,161 @@+# Sql Testing AI Helpers++Extract schema++```bash+pnpx supabase db dump -s public --db-url postgresql://postgres:pass@localhost/webstudio > schema.sql+```++Promt Examples++---++Below is a partial dump of the SQL schema:++```sql++CREATE TABLE IF NOT EXISTS "public"."User" (+ "id" "text" NOT NULL,+ "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,+ "email" "text",+ "image" "text",+ "provider" "text",+ "username" "text",+ "teamId" "text"+);+++CREATE TABLE IF NOT EXISTS "public"."Domain" (+ "id" "text" NOT NULL,+ "domain" "text" NOT NULL,+ "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,+ "txtRecord" "text",+ "status" "public"."DomainStatus" DEFAULT 'INITIALIZING'::"public"."DomainStatus" NOT NULL,+ "error" "text",+ "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL+);++CREATE TABLE IF NOT EXISTS "public"."Build" (+ "id" "text" NOT NULL,+ "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,+ "pages" "text" NOT NULL,+ "projectId" "text" NOT NULL,+ "styleSources" "text" DEFAULT '[]'::"text" NOT NULL,+ "styles" "text" DEFAULT '[]'::"text" NOT NULL,+ "breakpoints" "text" DEFAULT '[]'::"text" NOT NULL,+ "styleSourceSelections" "text" DEFAULT '[]'::"text" NOT NULL,+ "props" "text" DEFAULT '[]'::"text" NOT NULL,+ "instances" "text" DEFAULT '[]'::"text" NOT NULL,+ "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,+ "version" integer DEFAULT 0 NOT NULL,+ "deployment" "text",+ "publishStatus" "public"."PublishStatus" DEFAULT 'PENDING'::"public"."PublishStatus" NOT NULL,+ "dataSources" "text" DEFAULT '[]'::"text" NOT NULL,+ "lastTransactionId" "text",+ "resources" "text" DEFAULT '[]'::"text" NOT NULL,+ "marketplaceProduct" "text" DEFAULT '{}'::"text" NOT NULL+);++CREATE TABLE IF NOT EXISTS "public"."Project" (+ "id" "text" NOT NULL,+ "title" "text" NOT NULL,+ "domain" "text" NOT NULL,+ "userId" "text",+ "isDeleted" boolean DEFAULT false NOT NULL,+ "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,+ "previewImageAssetId" "text",+ "marketplaceApprovalStatus" "public"."MarketplaceApprovalStatus" DEFAULT 'UNLISTED'::"public"."MarketplaceApprovalStatus" NOT NULL+);++CREATE TABLE IF NOT EXISTS "public"."ProjectDomain" (+ "projectId" "text" NOT NULL,+ "domainId" "text" NOT NULL,+ "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,+ "txtRecord" "text" NOT NULL,+ "cname" "text" NOT NULL+);++CREATE OR REPLACE FUNCTION "public"."latestBuildVirtual"("public"."Project") RETURNS SETOF "public"."latestBuildVirtual"+ LANGUAGE "sql" STABLE ROWS 1+ AS $_$ -- The function is expected to return 1 row+++SELECT+ b.id AS "buildId",+ b."projectId",+ -- Use CASE to determine which domain to select based on conditions+ CASE+ WHEN (b.deployment::jsonb ->> 'projectDomain') = p.domain+ OR (b.deployment::jsonb -> 'domains') @> to_jsonb(array[p.domain])+ THEN p.domain+ ELSE d.domain+ END 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+LEFT JOIN "Domain" d ON d.id = pd."domainId"+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])+ OR (b.deployment::jsonb -> 'domains') @> to_jsonb(array[d.domain])+ )+ORDER BY b."createdAt" DESC+LIMIT 1;++$_$;++```++Create a pgTAP test for the function "public"."latestBuildVirtual" that takes "public"."Project" as an argument.++---++## Additional Instructions++These instructions are sometimes necessary, while at other times they may not be required.++All fields, such as `projectId`, already reference their corresponding table columns (e.g., `"Project"."id"`), but foreign key constraints are omitted.++- **Data Integrity:** Do not create new tables for `"public"."Project"` or related entities. These tables already exist in the database. DO NOT TRUNCATE DROP or DELETE Existing tables.++- **Data Accuracy:** When inserting new data, adhere strictly to the NULL constraints. Ensure all fields without default values are filled correctly in every `INSERT` statement.+ you may omit fields with default values if they are not directly relevant to the tests, except for `"createdAt"` and `"updatedAt"` fields, which should always be specified with explicit timestamp values.++- **Timestamp Fields:** For fields like `"createdAt"` and `"updatedAt"`, always use specific timestamp values rather than functions like `NOW()`.++- **Naming Conventions:** Since field and function names use camelCase, always wrap them in double quotes (`""`) to ensure proper referencing.++- **Test Coverage:** In addition to standard tests, cover additional cases to validate that the function returns the correct data in different scenarios:++ 1. When a project has changed its domain.+ 2. When builds with the new domain do not exist and when they do exist.+ 3. When the domain is either in `Build.deployment.projectDomain` or included in `Build.deployment.domains`.++- **Function Calls:** Use precise casting for function calls, such as `(p.*)::Project`, to ensure accuracy in test execution.++Ensure the tests comprehensively validate the function’s behavior in all specified cases.++In addition to the specific test cases mentioned, any other test scenarios the model identifies would be highly appreciated.++Examples of calling the function:++```sql++select "public"."latestBuildVirtual"((p.*)::"Project") from "public"."Project" p where p.id = '1';+```++---++## PS++Initially, it may produce non-working examples. However, it seems that a multi-step improvement process can enhance the results. By incorporating the additions mentioned above, you can achieve better final outcomes. While not perfect, it serves as a good starting point.++Seems like the shorter the input the better the results. The models are seems to struggle with longer inputs.diff --git a/packages/postgrest/supabase/tests/latest-builds-domains.sql b/packages/postgrest/supabase/tests/latest-builds-domains.sqlnew file mode 100644index 0000000000..82e1d79aa9--- /dev/null+++ b/packages/postgrest/supabase/tests/latest-builds-domains.sql@@ -0,0 +1,273 @@+BEGIN;+SET LOCAL search_path = pgtap, public;++-- SET LOCAL search_path = pgtap,public;++-- Initialize the testing environment without planning any specific number of tests+SELECT no_plan();++-- Insert a new 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+INSERT 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');++-- Insert custom domains into the Domain table+INSERT 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');++-- Establish relationships between projects and custom domains+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');++-- Create a view to encapsulate the repetitive SELECT query for testing+CREATE OR REPLACE VIEW "public"."TestProjectDomains" AS+SELECT+ pd."projectId",+ pd."domainId",+ lbv."buildId"+FROM "public"."ProjectDomain" pd+LEFT JOIN LATERAL (+ SELECT * FROM "latestBuildVirtual"(ROW('', pd."domainId", pd."projectId", '', 'INITIALIZING'::"DomainStatus", NULL, 'txt','expectedTxt','cname',TRUE, NOW(),NOW())::"domainsVirtual")+) lbv ON TRUE+ORDER BY pd."domainId";++--------------------------------------------------------------------------------+-- Test Case 1: Initial State Without Builds+--------------------------------------------------------------------------------+SELECT results_eq(+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',+ $$+ SELECT * FROM (+ VALUES+ ('project1', 'project-1-custom-domain-1', NULL),+ ('project1', 'project-1-custom-domain-2', NULL)+ ) AS expected(projectId, domainId, buildId)+ ORDER BY domainId+ $$,+ 'Initial state without builds'+);++--------------------------------------------------------------------------------+-- Test Case 2: After Inserting Build1 Associated with Custom Domain 1+--------------------------------------------------------------------------------+-- Insert a build associated with a custom domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build1-for-custom-domain-1',+ '2023-01-02 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '2023-01-02 00:00:00+00',+ 'PUBLISHED'+);++SELECT results_eq(+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',+ $$+ SELECT * FROM (+ VALUES+ ('project1', 'project-1-custom-domain-1', 'build1-for-custom-domain-1'),+ ('project1', 'project-1-custom-domain-2', NULL)+ ) AS expected(projectId, domainId, buildId)+ ORDER BY domainId+ $$,+ 'After inserting build1 associated with custom domain 1'+);++--------------------------------------------------------------------------------+-- Test Case 3: After Inserting Build2 Associated with Custom Domain 1+--------------------------------------------------------------------------------+-- Insert a new build associated with the same custom domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build2-for-custom-domain-1',+ '2024-01-02 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '2024-01-02 00:00:00+00',+ 'PUBLISHED'+);++SELECT results_eq(+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',+ $$+ SELECT * FROM (+ VALUES+ ('project1', 'project-1-custom-domain-1', 'build2-for-custom-domain-1'),+ ('project1', 'project-1-custom-domain-2', NULL)+ ) AS expected(projectId, domainId, buildId)+ ORDER BY domainId+ $$,+ 'After inserting build2 associated with custom domain 1'+);++--------------------------------------------------------------------------------+-- Test Case 4: After Inserting Build3 Associated with Custom Domain 2+--------------------------------------------------------------------------------+-- Insert a new build associated with another custom domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build3-for-custom-domain-2',+ '2024-01-03 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["some-other-domain.com", "project-1-custom-domain-2.com"]}'::text,+ '2024-01-03 00:00:00+00',+ 'PUBLISHED'+);++SELECT results_eq(+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',+ $$+ SELECT * FROM (+ VALUES+ ('project1', 'project-1-custom-domain-1', 'build2-for-custom-domain-1'),+ ('project1', 'project-1-custom-domain-2', 'build3-for-custom-domain-2')+ ) AS expected(projectId, domainId, buildId)+ ORDER BY domainId+ $$,+ 'After inserting build3 associated with custom domain 2'+);++--------------------------------------------------------------------------------+-- Test Case 5: After Inserting Build4 Associated with Both Domains+--------------------------------------------------------------------------------+-- Insert a new build associated with both custom domains+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build4-for-both-domains',+ '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,+ '2024-01-04 00:00:00+00',+ 'PUBLISHED'+);++SELECT results_eq(+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',+ $$+ SELECT * FROM (+ VALUES+ ('project1', 'project-1-custom-domain-1', 'build4-for-both-domains'),+ ('project1', 'project-1-custom-domain-2', 'build4-for-both-domains')+ ) AS expected(projectId, domainId, buildId)+ ORDER BY domainId+ $$,+ 'After inserting build4 associated with both domains'+);++--------------------------------------------------------------------------------+-- Test Case 6: Insert Builds and Relationships for Project2+--------------------------------------------------------------------------------+-- Establish relationships between project2 and the same custom domains+INSERT INTO "public"."ProjectDomain" ("projectId", "domainId", "createdAt", "txtRecord", "cname")+VALUES+ ('project2', 'project-1-custom-domain-1', '2023-01-01 00:00:00+00', 'txtRecord21', 'cname21'),+ ('project2', 'project-1-custom-domain-2', '2023-01-01 00:00:00+00', 'txtRecord22', 'cname22');++-- Insert a new build for project2 associated with both domains+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build5-project2-for-both-domains',+ '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,+ '2025-01-04 00:00:00+00',+ 'PUBLISHED'+);++--------------------------------------------------------------------------------+-- Test Case 7: Verify Results for Project1 Remain Unchanged After Project2 Updates+--------------------------------------------------------------------------------+SELECT results_eq(+ 'SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = ''project1''',+ $$+ SELECT * FROM (+ VALUES+ ('project1', 'project-1-custom-domain-1', 'build4-for-both-domains'),+ ('project1', 'project-1-custom-domain-2', 'build4-for-both-domains')+ ) AS expected(projectId, domainId, buildId)+ ORDER BY domainId+ $$,+ 'Verify Project1 results remain unchanged after Project2 updates'+);++--------------------------------------------------------------------------------+-- Test Case 8: Verify Results for Project2 Reflect Latest Build+--------------------------------------------------------------------------------+SELECT results_eq(+ $$SELECT * FROM "public"."TestProjectDomains" WHERE "projectId" = 'project2'$$,+ $$+ SELECT * FROM (+ VALUES+ ('project2', 'project-1-custom-domain-1', 'build5-project2-for-both-domains'),+ ('project2', 'project-1-custom-domain-2', 'build5-project2-for-both-domains')+ ) AS expected(projectId, domainId, buildId)+ ORDER BY domainId+ $$,+ 'Verify Project2 results reflect the latest build'+);++-- Finalize the tests+SELECT finish();++ROLLBACK;\ No newline at end of filediff --git a/packages/postgrest/supabase/tests/latest-builds-projects.sql b/packages/postgrest/supabase/tests/latest-builds-projects.sqlnew file mode 100644index 0000000000..dc183cb037--- /dev/null+++ b/packages/postgrest/supabase/tests/latest-builds-projects.sql@@ -0,0 +1,399 @@+BEGIN;+SET LOCAL search_path = pgtap, public;++-- Initialize the testing environment without planning any specific number of tests+SELECT no_plan();++--------------------------------------------------------------------------------+-- Setup: Insert Initial Data+--------------------------------------------------------------------------------++-- Insert a new 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+INSERT 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');++-- Insert builds with different deployment formats+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ -- Old deployment format: includes projectDomain+ (+ 'build1',+ '2023-01-01 00:00:00+00',+ 'home',+ 'project1',+ '{"projectDomain": "project1-domain1", "domains": [""]}'::text,+ '2023-01-01 00:00:00+00',+ 'PUBLISHED'+ ),+ (+ 'build1-old',+ '2022-01-01 00:00:00+00',+ 'home',+ 'project1',+ '{"projectDomain": "project1-domain1", "domains": [""]}'::text,+ '2022-01-01 00:00:00+00',+ 'PUBLISHED'+ ),+ (+ 'build1-newest-wrong-domain',+ '2024-01-01 00:00:00+00',+ 'home',+ 'project1',+ '{"projectDomain": "project-wrong", "domains": [""]}'::text,+ '2024-01-01 00:00:00+00',+ 'PUBLISHED'+ ),+ -- New deployment format: domains array only+ (+ 'build2',+ '2023-01-02 00:00:00+00',+ 'home',+ 'project2',+ '{"domains": ["project2-domain1"]}'::text,+ '2023-01-02 00:00:00+00',+ 'PENDING'+ ),+ (+ 'build2-old',+ '2022-01-02 00:00:00+00',+ 'home',+ 'project2',+ '{"domains": ["project2-domain1"]}'::text,+ '2022-01-02 00:00:00+00',+ 'PENDING'+ );++--------------------------------------------------------------------------------+-- Test Case 1: Verify Latest Build Retrieval Using Old Deployment Format (projectDomain)+--------------------------------------------------------------------------------+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1',+ 'Test Case 1: Should return the latest build for project1 with domain matching projectDomain.'+);++--------------------------------------------------------------------------------+-- Test Case 2: Verify Latest Build Retrieval Using New Deployment Format (domains array)+--------------------------------------------------------------------------------+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project2'+ )+ )+ ),+ 'build2',+ 'Test Case 2: Should return the latest build for project2 with domain present in domains array.'+);++--------------------------------------------------------------------------------+-- Test Case 3: Update Project Domain and Verify No Build Exists for the New Domain+--------------------------------------------------------------------------------+-- Update project1's domain to a new domain+UPDATE "public"."Project"+SET "domain" = 'project1-domain2'+WHERE "id" = 'project1';++-- Verify that no build exists for the updated domain+SELECT is (+ (+ SELECT COUNT(*)::integer+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 0,+ 'Test Case 3: Should return 0 as no build exists for the updated domain project1-domain2.'+);++--------------------------------------------------------------------------------+-- Test Case 4: Insert a New Build with the Updated Domain and Verify Retrieval+--------------------------------------------------------------------------------+-- Insert a new build associated with the updated domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build1-for-domain2',+ '2023-01-01 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["some-other-domain.com", "project1-domain2"]}'::text,+ '2023-01-01 00:00:00+00',+ 'PUBLISHED'+ );++-- Verify that the latest build now reflects the updated domain+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1-for-domain2',+ 'Test Case 4: Should return the latest build for project1 with the updated domain in domains array.'+);++--------------------------------------------------------------------------------+-- Test Case 5: Register Custom Domains and Verify Latest Build for a Custom Domain+--------------------------------------------------------------------------------+-- Insert custom domains+INSERT 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');++-- Establish relationships between project1 and custom domains+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');++-- Insert a build associated with a custom domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build1-for-custom-domain-1',+ '2023-01-02 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '2023-01-02 00:00:00+00',+ 'PUBLISHED'+ );++-- Verify that the latest build reflects the custom domain association+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1-for-custom-domain-1',+ 'Test Case 5: Should return the latest build for project1 with a registered custom domain in domains array.'+);++--------------------------------------------------------------------------------+-- Test Case 6: Publish a Preview Domain and Verify Latest Build Retrieval+--------------------------------------------------------------------------------+-- Insert a build for the preview domain using the new deployment format+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build1-for-domain2-new',+ '2023-01-03 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["project1-domain2"]}'::text,+ '2023-01-03 00:00:00+00',+ 'PUBLISHED'+ );++-- Verify that the latest build reflects the preview domain+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1-for-domain2-new',+ 'Test Case 6: 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+--------------------------------------------------------------------------------+-- Insert a new build for the custom domain+INSERT INTO "public"."Build" (+ "id",+ "createdAt",+ "pages",+ "projectId",+ "deployment",+ "updatedAt",+ "publishStatus"+)+VALUES+ (+ 'build1-for-custom-domain-1-new',+ '2023-01-04 00:00:00+00',+ 'home',+ 'project1',+ '{"domains": ["some-other-domain.com", "project-1-custom-domain-1.com"]}'::text,+ '2023-01-04 00:00:00+00',+ 'PUBLISHED'+ );++-- Verify that the latest build reflects the newly published build for the custom domain+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1-for-custom-domain-1-new',+ 'Test Case 7a: Should return the latest build after publishing a new build for a custom domain.'+);++-- Delete the custom domain association+DELETE FROM "public"."ProjectDomain"+WHERE "projectId" = 'project1' AND "domainId" = 'project-1-custom-domain-1';++-- Verify that the latest build reverts to the previous latest build after deletion+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1-for-domain2-new',+ 'Test Case 7b: Should return the latest build after deleting the custom domain, reverting to the previous latest build.'+);++--------------------------------------------------------------------------------+-- Test Case 8: Publish a New Build for a Custom Domain, Move the Custom Domain, and Verify Latest Build Update+--------------------------------------------------------------------------------+-- Re-establish the custom domain association to revert Test Case 7+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');++-- Verify that the latest build is updated after re-establishing the custom domain+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1-for-custom-domain-1-new',+ 'Test Case 8a: Should return the latest build after re-publishing a new build for a custom domain.'+);++-- Move the custom domain association from project1 to project2+UPDATE "public"."ProjectDomain"+SET "projectId" = 'project2'+WHERE "projectId" = 'project1' AND "domainId" = 'project-1-custom-domain-1';++-- Verify that the latest build reverts to the previous latest build after moving the custom domain+SELECT is (+ (+ SELECT "buildId"+ FROM "public"."latestBuildVirtual"(+ (+ SELECT (p.*)::"Project"+ FROM "public"."Project" p+ WHERE p."id" = 'project1'+ )+ )+ ),+ 'build1-for-domain2-new',+ 'Test Case 8b: Should return the latest build after moving the custom domain, reverting to the previous latest build.'+);++-- Finalize the tests+SELECT finish();++ROLLBACK;\ No newline at end of filediff --git a/packages/postgrest/supabase/tests/project-domains.sql b/packages/postgrest/supabase/tests/project-domains.sqlnew file mode 100644index 0000000000..b1120da71f--- /dev/null+++ b/packages/postgrest/supabase/tests/project-domains.sql@@ -0,0 +1,77 @@+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();++-- Insert a new user into the User table for the project ownership+-- We're inserting user_1 as the user for the test projects+INSERT INTO "public"."User" ("id", "createdAt", "email", "username")+VALUES+ ('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);++-- Insert test domains into the Domain table+-- We are inserting two domains: example.com and example.org with different statuses+INSERT INTO "Domain" (id, domain, status, "txtRecord") VALUES+('domain_1', 'example.com', 'INITIALIZING', 'txtRecord1'),+('domain_2', '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+-- Note the different TXT records in ProjectDomain+INSERT INTO "ProjectDomain" ("projectId", "domainId", "txtRecord", "cname") VALUES+('project_1', 'domain_1', 'txtRecord1', 'cname1'),+('project_1', 'domain_2', 'txtRecord22', 'cname2'),+('project_2', 'domain_1', 'txtRecord3', 'cname3');++-- Test case 1: Verify that domainsVirtual returns correct values for project_1+-- Compare the result of the domainsVirtual function with an expected result set.+-- Project_1 is expected to return two domains with statuses, TXT records, and verification status+SELECT results_eq(+ $$+ SELECT domain, status, error, "domainTxtRecord", "expectedTxtRecord", verified+ FROM "domainsVirtual"(+ (SELECT (p.*)::"Project" FROM "Project" p WHERE p.id = 'project_1' ORDER BY p.id)+ )+ $$,+ $$+ 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)+ ) AS expected(domain, status, error, "domainTxtRecord", "expectedTxtRecord", verified)+ ORDER BY "domain"+ $$,+ 'Test case 1: domainsVirtual should return correct results for project_1'+);++-- Test case 2: Verify that domainsVirtual returns correct values for project_2+-- Project_2 is expected to return one domain with its corresponding status, TXT records, and verification status+SELECT results_eq(+ $$+ SELECT domain, status, error, "domainTxtRecord", "expectedTxtRecord", verified+ FROM "domainsVirtual"(+ (SELECT (p.*)::"Project" FROM "Project" p WHERE p.id = 'project_2' ORDER BY p.id)+ )+ $$,+ $$+ SELECT * FROM (+ VALUES+ ('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"+ $$,+ 'Test case 2: domainsVirtual should return correct results for project_2'+);++-- 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;\ No newline at end of filediff --git a/packages/prisma-client/prisma/migrations/20240916143551_time/migration.sql b/packages/prisma-client/prisma/migrations/20240916143551_time/migration.sqlnew file mode 100644index 0000000000..4915ebb939--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20240916143551_time/migration.sql@@ -0,0 +1,105 @@+DROP VIEW IF EXISTS "LatestBuildPerProject" CASCADE;+DROP VIEW IF EXISTS "LatestBuildPerProjectDomain" CASCADE;+DROP VIEW IF EXISTS "LatestStaticBuildPerProject" CASCADE;+DROP VIEW "ApprovedMarketplaceProduct";+DROP VIEW IF EXISTS "DashboardProject";+DROP VIEW IF EXISTS "ProjectWithDomain";++-- AlterTable+ALTER TABLE "AuthorizationToken" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "Build" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "ClientReferences" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "Domain" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),+ALTER COLUMN "updatedAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "File" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3),+ALTER COLUMN "updatedAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "Product" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "Project" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "ProjectDomain" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "TransactionLog" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);++-- AlterTable+ALTER TABLE "User" ALTER COLUMN "createdAt" SET DATA TYPE TIMESTAMPTZ(3);+++CREATE OR REPLACE VIEW "LatestStaticBuildPerProject" AS+SELECT DISTINCT ON ("projectId")+ bld.id AS "buildId",+ bld."projectId",+ bld."updatedAt",+ bld."publishStatus"+FROM+ "Build" bld+WHERE+ bld.deployment IS NOT NULL+ AND bld.deployment::jsonb ->> 'destination'::text = 'static'+ORDER BY+ bld."projectId",+ bld."createdAt" DESC,+ "buildId";++++CREATE VIEW "ApprovedMarketplaceProduct" AS+SELECT DISTINCT ON (build."projectId")+ build."projectId",+ build."marketplaceProduct",+ (+ SELECT+ token+ FROM+ "AuthorizationToken" auth+ WHERE+ auth."projectId" = build."projectId" AND+ auth.relation = 'viewers'+ ORDER BY+ auth."token"+ LIMIT 1+ ) AS "authorizationToken"+FROM+ "Build" build+WHERE+ build.deployment IS NOT NULL -- published+ AND build."projectId" IN (+ SELECT+ "id"+ FROM+ "Project"+ WHERE ("isDeleted" = FALSE+ AND "marketplaceApprovalStatus" = CAST('APPROVED'::text AS "MarketplaceApprovalStatus")))+ORDER BY+ build."projectId",+ build."createdAt" DESC,+ build.id;++CREATE VIEW "DashboardProject" AS+SELECT+ *,+ EXISTS (+ SELECT+ 1+ from+ "Build"+ WHERE+ "Build"."projectId" = "Project".id+ AND "Build"."deployment" IS NOT NULL+ ) AS "isPublished"+FROM+ "Project";+diff --git a/packages/prisma-client/prisma/migrations/20240917152817_pgtap/migration.sql b/packages/prisma-client/prisma/migrations/20240917152817_pgtap/migration.sqlnew file mode 100644index 0000000000..8de9f80f69--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20240917152817_pgtap/migration.sql@@ -0,0 +1,4 @@+CREATE SCHEMA IF NOT EXISTS pgtap;++-- Enable pg_tap+CREATE EXTENSION IF NOT EXISTS pgtap WITH SCHEMA pgtap;diff --git a/packages/prisma-client/prisma/migrations/20240918100751_latest-virtual-build/migration.sql b/packages/prisma-client/prisma/migrations/20240918100751_latest-virtual-build/migration.sqlnew file mode 100644index 0000000000..0225b113c0--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20240918100751_latest-virtual-build/migration.sql@@ -0,0 +1,187 @@+-- Drop the "domainsVirtual" table if it already exists, cascading to any dependent objects.+DROP TABLE IF EXISTS "domainsVirtual" CASCADE;++-- Create the "domainsVirtual" table to represent a virtual view of the relationship between domains and projects.+-- This table enforces a 1-1 relationship between Project and Domain, used primarily for postgrest types and API purposes.+CREATE TABLE "domainsVirtual" (+ "id" text PRIMARY KEY NOT NULL, -- Primary key for the virtual table.+ "domainId" text REFERENCES "Domain" (id) NOT NULL, -- Foreign key referencing the Domain table's ID.+ "projectId" text REFERENCES "Project" (id) NOT NULL, -- Foreign key referencing the Project table's ID.+ "domain" text NOT NULL, -- Domain name (must not be null).+ "status" "DomainStatus" NOT NULL DEFAULT 'INITIALIZING'::"DomainStatus", -- Status of the domain, defaulting to 'INITIALIZING'.+ "error" text, -- Optional error message, populated if status is 'ERROR'.+ "domainTxtRecord" text, -- Current TXT record for the domain, retrieved from the Domain table.+ "expectedTxtRecord" text NOT NULL, -- Expected TXT record, coming from the ProjectDomain table.+ "cname" text NOT NULL, -- CNAME record for the domain, coming from the ProjectDomain table.+ "verified" boolean NOT NULL DEFAULT false, -- Boolean flag indicating if the domain is verified (if TXT records match).+ "createdAt" timestamp(3) with time zone NOT NULL, -- Creation timestamp from ProjectDomain.+ "updatedAt" timestamp(3) with time zone NOT NULL -- Last update timestamp from Domain.+);++-- Add detailed comments for the table and each relevant column.+COMMENT ON TABLE "domainsVirtual" IS 'Virtual table representing domains related to each project. This table enforces a 1-1 relationship with the Project table and is used for API interaction (postgrest types).';++COMMENT ON COLUMN "domainsVirtual"."domainId" IS 'Unique identifier for the domain (Domain table reference).';+COMMENT ON COLUMN "domainsVirtual"."projectId" IS 'Unique identifier for the project, acting as the primary key (1-1 relationship with Project table).';+COMMENT ON COLUMN "domainsVirtual"."domain" IS 'The domain name (must not be NULL).';+COMMENT ON COLUMN "domainsVirtual"."status" IS 'Current status of the domain, with a default of INITIALIZING.';+COMMENT ON COLUMN "domainsVirtual"."error" IS 'Optional error message field populated if the domain status is ERROR.';+COMMENT ON COLUMN "domainsVirtual"."domainTxtRecord" IS 'Current TXT record for the domain, coming from the Domain table.';+COMMENT ON COLUMN "domainsVirtual"."expectedTxtRecord" IS 'Expected TXT record for the domain, pulled from the ProjectDomain table.';+COMMENT ON COLUMN "domainsVirtual"."verified" IS 'Boolean flag indicating whether the domain is verified (true if TXT records match, false otherwise).';+COMMENT ON COLUMN "domainsVirtual"."createdAt" IS 'Timestamp indicating when the ProjectDomain entry was created.';+COMMENT ON COLUMN "domainsVirtual"."updatedAt" IS 'Timestamp indicating when the Domain was last updated.';++-- 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+$$+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.';++++DROP TABLE IF EXISTS "latestBuildVirtual" CASCADE;++-- In the postgrest-js type system, it appears that Project has a 1-1 relationship with latestBuild+CREATE TABLE "latestBuildVirtual" (+ "buildId" text REFERENCES "Build" (id) unique NOT NULL,+ "projectId" text PRIMARY KEY REFERENCES "Project" (id) NOT NULL, -- PRIMARY KEY indicates a 1-1 relationship https://docs.postgrest.org/en/v12/references/api/resource_embedding.html#one-to-one-relationships+ "domainsVirtualId" text REFERENCES "domainsVirtual" ("id") unique NOT NULL, -- UNIQUE KEY indicates a 1-1 relationship https://docs.postgrest.org/en/v12/references/api/resource_embedding.html#one-to-one-relationships+ domain text NOT NULL,+ "createdAt" timestamp(3) with time zone NOT NULL,+ "publishStatus" "PublishStatus" NOT NULL+);++-- Adding comments for the table and specific column+COMMENT ON TABLE "latestBuildVirtual" IS 'Virtual table representing the latest build for each project, enforcing a 1-1 relationship with the Project table. Used ONLY for postgrest types';++COMMENT ON COLUMN "latestBuildVirtual"."projectId" IS 'Identifier for the project, enforcing a 1-1 relationship with the Project table as a primary key';+++-- 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 "latestBuildVirtual"("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 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",+ -- Use CASE to determine which domain to select based on conditions+ CASE+ WHEN (b.deployment::jsonb ->> 'projectDomain') = p.domain+ OR (b.deployment::jsonb -> 'domains') @> to_jsonb(array[p.domain])+ THEN p.domain+ ELSE d.domain+ END 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+LEFT JOIN "Domain" d ON d.id = pd."domainId"+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])+ OR (b.deployment::jsonb -> 'domains') @> to_jsonb(array[d.domain])+ )+ORDER BY b."createdAt" DESC+LIMIT 1;++$$+STABLE+LANGUAGE sql;++-- Comment on the function to provide additional context+COMMENT ON FUNCTION "latestBuildVirtual"("Project") IS 'This function computes the latest build for a project, 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.';++-- Example:+-- select p.id, p.domain, lbv.* from "Project" p+-- LEFT JOIN LATERAL (+-- SELECT * FROM "latestBuildVirtual"(p)+-- ) lbv ON TRUE;+++++++-- This function defines a computed field "latestBuildVirtual" for PostgREST+-- It returns the latest build associated with a given Project and Domain.+-- Reference: https://docs.postgrest.org/en/v12/references/api/resource_embedding.html#computed-relationships++CREATE OR REPLACE FUNCTION "latestBuildVirtual"("domainsVirtual")+RETURNS SETOF "latestBuildVirtual"+ROWS 1 AS $$ -- The function is expected to return at most 1 row since it fetches the latest build++SELECT+ b.id AS "buildId", -- ID of the Build+ b."projectId", -- ID of the Project to which the build belongs+ '' as "domainsVirtualId", -- Placeholder for the domainsVirtual ID (not used in this context)+ d."domain", -- Domain associated with the build+ b."createdAt", -- Timestamp of when the build was created+ b."publishStatus" -- Status of the build (e.g., published, draft, etc.)+FROM "Build" b+JOIN "Domain" d ON d.id = $1."domainId" -- Join the "Build" and "Domain" tables using the domain ID+WHERE+ b."projectId" = $1."projectId" -- Ensure the Build belongs to the specified project+ AND b.deployment IS NOT NULL -- Ensure the Build has a non-null deployment field+ AND (b.deployment::jsonb -> 'domains') @> to_jsonb(array[d.domain]) -- Check if the domain exists in the deployment JSON array+ORDER BY b."createdAt" DESC -- Order builds by creation date in descending order to get the latest one+LIMIT 1; -- Limit the result to the most recent build++$$+STABLE -- Declares that the function always returns the same result for the same input parameters+LANGUAGE sql;++-- Adding a comment to provide more context about the function's purpose+COMMENT ON FUNCTION "latestBuildVirtual"("domainsVirtual") IS 'Returns the latest build for a given project and domain as a computed field for PostgREST.';++++DROP VIEW IF EXISTS "LatestBuildPerProject" CASCADE;diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prismaindex a1f429bd25..a3a8fde150 100644--- a/packages/prisma-client/prisma/schema.prisma+++ b/packages/prisma-client/prisma/schema.prisma@@ -33,8 +33,8 @@ model File {format Stringsize Intdescription String?- createdAt DateTime @default(now())- updatedAt DateTime @default(now()) @updatedAt+ createdAt DateTime @default(now()) @db.Timestamptz(3)+ updatedAt DateTime @default(now()) @updatedAt @db.Timestamptz(3)meta String @default("{}")status UploadStatus @default(UPLOADING)isDeleted Boolean @default(false)@@ -60,7 +60,7 @@ model User {provider String?image String?username String?- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)team Team? @relation(fields: [teamId], references: [id])teamId String?projects Project[]@@ -73,7 +73,7 @@ model User {model ClientReferences {reference String @default(dbgenerated())service String- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)user User @relation(fields: [userId], references: [id])userId String@@ -89,7 +89,7 @@ model Product {images String[]meta Json- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)checkout TransactionLog[]userProducts UserProduct[]}@@ -103,7 +103,7 @@ model TransactionLog {productId String?product Product? @relation(fields: [productId], references: [id])- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)eventData Json? @default(dbgenerated())@@ -140,7 +140,7 @@ view UserProduct {model Project {id String @id @default(uuid())- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)title Stringdomain String @uniqueuser User? @relation(fields: [userId], references: [id])@@ -149,7 +149,6 @@ model Project {isDeleted Boolean @default(false)files File[]projectDomain ProjectDomain[]- latestBuild LatestBuildPerProject?authorizationToken AuthorizationToken[]previewImageAsset Asset? @relation(fields: [previewImageAssetId, id], references: [id, projectId])previewImageAssetId String?@@ -180,7 +179,7 @@ model Build {id String @unique @default(uuid())version Int @default(0)lastTransactionId String?- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)updatedAt DateTime @default(now()) @updatedAt @db.Timestamptz(3)pages String@@ -201,7 +200,6 @@ model Build {deployment String?publishStatus PublishStatus @default(PENDING)- latestBuildPerProject LatestBuildPerProject?latestStaticBuildPerProject LatestStaticBuildPerProject?@@id([id, projectId])@@ -222,7 +220,7 @@ model AuthorizationToken {project Project @relation(fields: [projectId], references: [id])name String @default("")relation AuthorizationRelation @default(viewers)- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)canClone Boolean @default(true)canCopy Boolean @default(true)@@ -244,8 +242,8 @@ enum DomainStatus {model Domain {id String @id @default(uuid())domain String @unique- createdAt DateTime @default(now())- updatedAt DateTime @default(now()) @updatedAt+ createdAt DateTime @default(now()) @db.Timestamptz(3)+ updatedAt DateTime @default(now()) @updatedAt @db.Timestamptz(3)ProjectDomain ProjectDomain[]// Last known txtRecord of the domain (to check domain ownership)@@ -254,8 +252,6 @@ model Domain {status DomainStatus @default(INITIALIZING)// In case of status="error", this will contain the error messageerror String?-- projectWithDomain ProjectWithDomain[]}model ProjectDomain {@@ -263,7 +259,7 @@ model ProjectDomain {project Project @relation(fields: [projectId], references: [id])domainId Stringdomain Domain @relation(fields: [domainId], references: [id])- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)// Generated txt record to check domain ownershiptxtRecord String @unique @default(uuid())@@ -274,57 +270,6 @@ model ProjectDomain {@@index([domainId])}-view ProjectWithDomain {- projectId String-- domainId String- domain Domain @relation(fields: [domainId], references: [id])- txtRecord String-- createdAt DateTime-- // CNAME record to point to the domain- cname String-- verified Boolean- // To count statistics per user- userId String?-- // We can deploy on per domain basis, here for each project domain we have latest build- latestBuid LatestBuildPerProjectDomain?-- @@id([projectId, domainId])-}--view LatestBuildPerProjectDomain {- domainId String- buildId String- projectId String- projectWithDomain ProjectWithDomain @relation(fields: [projectId, domainId], references: [projectId, domainId])-- isLatestBuild Boolean- publishStatus PublishStatus- updatedAt DateTime-- @@id([projectId, domainId])-}--view LatestBuildPerProject {- buildId String- build Build @relation(fields: [buildId, projectId], references: [id, projectId])-- projectId String- domain String- project Project @relation(fields: [projectId, domain], references: [id, domain])-- isLatestBuild Boolean- publishStatus PublishStatus- updatedAt DateTime-- @@id([projectId, domain])- @@unique([buildId, projectId])-}-view LatestStaticBuildPerProject {buildId Stringbuild Build @relation(fields: [buildId, projectId], references: [id, projectId])@@ -333,7 +278,7 @@ view LatestStaticBuildPerProject {project Project @relation(fields: [projectId], references: [id])publishStatus PublishStatus- updatedAt DateTime+ updatedAt DateTime @db.Timestamptz(3)@@id([projectId])@@unique([buildId, projectId])@@ -342,7 +287,7 @@ view LatestStaticBuildPerProject {// Dashboardview DashboardProject {id String @id @default(uuid())- createdAt DateTime @default(now())+ createdAt DateTime @default(now()) @db.Timestamptz(3)title Stringdomain StringuserId String?diff --git a/packages/prisma-client/src/prisma.ts b/packages/prisma-client/src/prisma.tsindex 345bbef64a..603247ee9b 100644--- a/packages/prisma-client/src/prisma.ts+++ b/packages/prisma-client/src/prisma.ts@@ -10,9 +10,6 @@ export type {AuthorizationToken,DomainStatus,Domain,- ProjectWithDomain,- LatestBuildPerProjectDomain,- LatestBuildPerProject,PublishStatus,Product,$Enums,diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.tsindex e4a81d7fe9..d148245c5d 100644--- a/packages/project-build/src/db/build.ts+++ b/packages/project-build/src/db/build.ts@@ -182,29 +182,29 @@ export const loadApprovedProdBuildByProjectId = async (context: AppContext,projectId: Build["projectId"]) => {- const latestBuild = await context.postgrest.client- .from("LatestBuildPerProject")+ const project = await context.postgrest.client+ .from("Project").select(`- buildId,- project:Project!inner (id)+ id,+ latestBuildVirtual(buildId)`)- .eq("projectId", projectId)- .eq("isLatestBuild", true)- .eq("project.isDeleted", false)- .eq("project.marketplaceApprovalStatus", "APPROVED")+ .eq("id", projectId)+ .eq("isDeleted", false)+ .eq("marketplaceApprovalStatus", "APPROVED").single();- if (latestBuild.error) {- throw latestBuild.error;+ if (project.error) {+ throw project.error;}- if (latestBuild.data.buildId === null) {+ if (project.data.latestBuildVirtual === null) {throw Error("Build not found");}+const build = await context.postgrest.client.from("Build").select()- .eq("id", latestBuild.data.buildId);+ .eq("id", project.data.latestBuildVirtual.buildId);// .single(); Note: Single response is not compressed. Uncomment the following line once the issue is resolved: https://github.com/orgs/supabase/discussions/28757if (build.error) {diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.tsindex 6bbee0752a..70ef6bebf8 100644--- a/packages/project/src/db/project.ts+++ b/packages/project/src/db/project.ts@@ -5,7 +5,7 @@ import {AuthorizationError,} from "@webstudio-is/trpc-interface/index.server";import { createBuild } from "@webstudio-is/project-build/index.server";-import { MarketplaceApprovalStatus, Project, Title } from "../shared/schema";+import { MarketplaceApprovalStatus, Title } from "../shared/schema";import { generateDomain, validateProjectDomain } from "./project-domain";import type { SetNonNullable } from "type-fest";@@ -39,10 +39,9 @@ export const findProjectIdsByUserId = async (return result.data;};-export const loadById = async (- projectId: Project["id"],- context: AppContext-) => {+export type Project = Awaited<ReturnType<typeof loadById>>;++export const loadById = async (projectId: string, context: AppContext) => {const canRead = await authorizeProject.hasProjectPermit({ projectId, permit: "view" },context@@ -58,37 +57,28 @@ export const loadById = async (`*,previewImageAsset:Asset (*),- latestBuilds:LatestBuildPerProject (*),- latestStaticBuild:LatestStaticBuildPerProject (*)+ latestBuildVirtual(*),+ latestStaticBuild:LatestStaticBuildPerProject (*),+ domainsVirtual(*, latestBuildVirtual(*))`).eq("id", projectId).eq("isDeleted", false).single();+if (data.error) {throw data.error;}- const { latestBuilds, latestStaticBuild, ...project } = data.data;-- // latestBuilds is an array containing the latest builds for each project domain (which can be renamed).- // We need to find the latest build for the current project domain.- // postgres marks all view fields as nullable- // workaround this by casting to non nullable- const latestBuild = (latestBuilds.filter(- (build) => build.domain === project.domain- )?.[0] ?? null) as null | SetNonNullable<- NonNullable<(typeof latestBuilds)[number]>- >;+ const { latestStaticBuild, ...project } = data.data;return {...project,- latestBuild,// postgres marks all view fields as nullable// workaround this by casting to non nullablelatestStaticBuild: (latestStaticBuild[0] ?? null) as null | SetNonNullable<NonNullable<(typeof latestStaticBuild)[0]>>,- } satisfies Project;+ };};export const create = async (diff --git a/packages/project/src/index.ts b/packages/project/src/index.tsindex e39f6835d8..c924fefcdc 100644--- a/packages/project/src/index.ts+++ b/packages/project/src/index.ts@@ -1,3 +1,4 @@export * from "./shared/schema";+export type { Project } from "./db/project";export type { ProjectRouter } from "./trpc";export { validateProjectDomain } from "./db/project-domain";diff --git a/packages/project/src/shared/schema.ts b/packages/project/src/shared/schema.tsindex 7ddbb9b856..4800758d99 100644--- a/packages/project/src/shared/schema.ts+++ b/packages/project/src/shared/schema.ts@@ -19,43 +19,3 @@ export const MarketplaceApprovalStatus = z.enum([export type MarketplaceApprovalStatus = z.infer<typeof MarketplaceApprovalStatus>;--export const Project = z.object({- id: z.string(),- title: Title,- createdAt: z.date().transform((date) => date.toISOString()),- userId: z.string().nullable(),- isDeleted: z.boolean(),- domain: z.string(),- previewImageAsset: z- .object({- id: z.string(),- name: z.string(),- })- .nullable(),- latestBuild: z.optional(- z- .object({- buildId: z.string(),- isLatestBuild: z.boolean(),- publishStatus: z.enum(["PENDING", "PUBLISHED", "FAILED"]),- updatedAt: z.date().transform((date) => date.toISOString()),- })- .nullable()- ),- latestStaticBuild: z.optional(- z- .object({- buildId: z.string(),- publishStatus: z.enum(["PENDING", "PUBLISHED", "FAILED"]),- updatedAt: z.date().transform((date) => date.toISOString()),- })- .nullable()- ),- marketplaceApprovalStatus: MarketplaceApprovalStatus,-});--export type Project = z.infer<typeof Project>;--export const Projects = z.array(Project);-export type Projects = z.infer<typeof Projects>;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dcf7a19811..2f47d39753 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1460,9 +1460,9 @@ importers:packages/domain:dependencies:- '@webstudio-is/prisma-client':+ '@webstudio-is/postrest':specifier: workspace:*- version: link:../prisma-client+ version: link:../postgrest'@webstudio-is/project':specifier: workspace:*version: link:../project@@ -1478,6 +1478,9 @@ importers:nanoid:specifier: ^5.0.1version: 5.0.1+ type-fest:+ specifier: ^4.24.0+ version: 4.24.0zod:specifier: ^3.22.4version: 3.22.4