diff --git a/apps/builder/app/builder/features/sync-status.test.tsx b/apps/builder/app/builder/features/sync-status.test.tsx index 311962716f..e04d663875 100644 --- a/apps/builder/app/builder/features/sync-status.test.tsx +++ b/apps/builder/app/builder/features/sync-status.test.tsx @@ -3,6 +3,11 @@ import { createRoot, type Root } from "react-dom/client"; import { act } from "react-dom/test-utils"; import { afterEach, describe, expect, test, vi } from "vitest"; import { $syncStatus } from "@webstudio-is/sync-client"; +import { + $externalContentRoots, + $externalContentAssetStatuses, +} from "~/shared/external-content-mutations"; +import { usePreventUnload } from "~/shared/sync/project-queue"; import { SyncStatusDot } from "./sync-status"; ( @@ -38,6 +43,8 @@ afterEach(() => { root = undefined; document.body.innerHTML = ""; $syncStatus.set({ status: "idle" }); + $externalContentRoots.set(new Map()); + $externalContentAssetStatuses.set(new Map()); vi.useRealTimers(); }); @@ -62,6 +69,59 @@ describe("SyncStatusDot", () => { ); }); + test("keeps pending status until an MDX Asset save completes", () => { + const { getDot } = renderSyncStatusDot(); + act(() => { + $externalContentAssetStatuses.set(new Map([["asset", "pending"]])); + }); + expect(getDot().getAttribute("data-sync-status")).toBe("pending"); + act(() => { + $externalContentAssetStatuses.set(new Map([["asset", "saving"]])); + }); + expect(getDot().getAttribute("data-sync-status")).toBe("pending"); + act(() => { + $externalContentAssetStatuses.set(new Map()); + }); + expect(getDot().getAttribute("data-sync-status")).toBe("saved"); + }); + + test("keeps pending status when the last MDX root unmounts", () => { + const { getDot } = renderSyncStatusDot(); + act(() => { + $externalContentRoots.set( + new Map([ + [ + "block", + { + blockInstanceId: "block", + instanceIds: new Set(), + mutationRevision: 1, + savedMutationRevision: 0, + }, + ], + ]) + ); + $externalContentAssetStatuses.set(new Map([["asset", "pending"]])); + }); + act(() => { + $externalContentRoots.set(new Map()); + }); + expect(getDot().getAttribute("data-sync-status")).toBe("pending"); + }); + + test.each(["failed", "conflicting"] as const)( + "renders an MDX Asset %s status as an error", + (assetContentStatus) => { + const { getDot } = renderSyncStatusDot(); + act(() => { + $externalContentAssetStatuses.set( + new Map([["asset", assetContentStatus]]) + ); + }); + expect(getDot().getAttribute("data-sync-status")).toBe("error"); + } + ); + test("renders saved status briefly after pending changes become idle", () => { vi.useFakeTimers(); const { getDot } = renderSyncStatusDot(); @@ -103,3 +163,24 @@ describe("SyncStatusDot", () => { ); }); }); + +test("warns before unloading while an MDX Asset save is pending", () => { + const Guard = () => { + usePreventUnload(); + return null; + }; + root = createRoot(document.createElement("div")); + act(() => root?.render(createElement(Guard))); + act(() => { + $externalContentAssetStatuses.set(new Map([["asset", "pending"]])); + }); + const event = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + act(() => { + $externalContentAssetStatuses.set(new Map([["asset", "failed"]])); + }); + const failedEvent = new Event("beforeunload", { cancelable: true }); + window.dispatchEvent(failedEvent); + expect(failedEvent.defaultPrevented).toBe(true); +}); diff --git a/apps/builder/app/builder/features/sync-status.tsx b/apps/builder/app/builder/features/sync-status.tsx index 96b2206d63..1ac3c5d4db 100644 --- a/apps/builder/app/builder/features/sync-status.tsx +++ b/apps/builder/app/builder/features/sync-status.tsx @@ -12,6 +12,7 @@ import { } from "@webstudio-is/design-system"; import { OfflineIcon } from "@webstudio-is/icons"; import { $hasUnsavedSyncChanges, $syncStatus } from "@webstudio-is/sync-client"; +import { $externalContentAssetStatuses } from "~/shared/external-content-mutations"; const syncStatusDotSavedDuration = 2000; const syncStatusDotPendingColor = cssVar("--foreground-warning"); @@ -55,13 +56,23 @@ const subscribeIsOnline = () => { export const SyncStatusDot = () => { const statusObject = useStore($syncStatus); const hasUnsavedSyncChanges = useStore($hasUnsavedSyncChanges); + const externalContentAssetStatuses = useStore($externalContentAssetStatuses); + const hasUnsavedChanges = + hasUnsavedSyncChanges || externalContentAssetStatuses.size > 0; + const hasExternalContentError = Array.from( + externalContentAssetStatuses.values() + ).some((status) => status === "failed" || status === "conflicting"); const hadUnsavedSyncChangesRef = useRef(false); const savedTimeoutRef = useRef>(); const [savedUntil, setSavedUntil] = useState(0); let visibleStatus: SyncStatusDotStatus = "idle"; - if (statusObject.status === "failed" || statusObject.status === "fatal") { + if ( + statusObject.status === "failed" || + statusObject.status === "fatal" || + hasExternalContentError + ) { visibleStatus = "error"; - } else if (hasUnsavedSyncChanges) { + } else if (hasUnsavedChanges) { visibleStatus = "pending"; } else if (Date.now() < savedUntil) { visibleStatus = "saved"; @@ -73,7 +84,7 @@ export const SyncStatusDot = () => { : statusConfig.label; useEffect(() => { - if (hasUnsavedSyncChanges) { + if (hasUnsavedChanges) { hadUnsavedSyncChangesRef.current = true; return; } @@ -89,7 +100,7 @@ export const SyncStatusDot = () => { setSavedUntil(0); }, syncStatusDotSavedDuration); } - }, [hasUnsavedSyncChanges, statusObject.status]); + }, [hasUnsavedChanges, statusObject.status]); useEffect(() => { return () => clearTimeout(savedTimeoutRef.current); diff --git a/apps/builder/app/shared/external-content-mutations.ts b/apps/builder/app/shared/external-content-mutations.ts index 32c3f234a7..868ccbe3bb 100644 --- a/apps/builder/app/shared/external-content-mutations.ts +++ b/apps/builder/app/shared/external-content-mutations.ts @@ -25,6 +25,7 @@ import type { MdxTemplateInsertion, } from "@webstudio-is/project-build/runtime"; import type { MdxDocument } from "@webstudio-is/content-engine/mdx"; +import type { AssetContentSessionState } from "@webstudio-is/content-engine/asset-content-session"; import { atom, type ReadableAtom } from "nanostores"; import type { ExternalContentOwnership } from "./external-content-persistence"; import type { FrontmatterSource } from "./content-block-document"; @@ -176,6 +177,9 @@ export const getExternalContentSourceSelector = ({ export const $externalContentRoots = atom( new Map() ); +export const $externalContentAssetStatuses = atom( + new Map() +); const mutationListeners = new Set<(rootKeys: readonly string[]) => void>(); const templateMutationListeners = new Set< (rootKeys: readonly string[]) => void diff --git a/apps/builder/app/shared/external-content-roots.test.ts b/apps/builder/app/shared/external-content-roots.test.ts index 0e816f2d66..589b0e79d8 100644 --- a/apps/builder/app/shared/external-content-roots.test.ts +++ b/apps/builder/app/shared/external-content-roots.test.ts @@ -42,6 +42,7 @@ import { selectPage, } from "./nano-states"; import { + $externalContentAssetStatuses, findExternalContentRoot, getExternalContentRoots, resolveExternalContentOccurrence, @@ -2162,6 +2163,9 @@ test("finishes a queued canvas save after its external root is released", async }); release(); + expect($externalContentAssetStatuses.get().get('["project","asset"]')).toBe( + "pending" + ); continueUpdate?.(); await blockingUpdate; await flushExternalContentAsset({ projectId: "project", assetId: asset.id }); @@ -2169,6 +2173,9 @@ test("finishes a queued canvas save after its external root is released", async expect(statuses).not.toContain("failed"); expect(writes).toEqual(["# Stale update\n"]); + expect($externalContentAssetStatuses.get().has('["project","asset"]')).toBe( + false + ); }); test("retains a failed queued update when project teardown cannot drain it", async () => { @@ -2225,6 +2232,11 @@ test("retains a failed queued update when project teardown cannot drain it", asy update, }) ).rejects.toThrow("Temporary serialization failure"); + expect( + $externalContentAssetStatuses + .get() + .get('["teardown-project","teardown-asset"]') + ).toBe("failed"); await expect( disposeExternalContentProject({ projectId: teardownAsset.projectId!, @@ -2247,6 +2259,11 @@ test("retains a failed queued update when project teardown cannot drain it", asy projectId: teardownAsset.projectId!, session, }); + expect( + $externalContentAssetStatuses + .get() + .has('["teardown-project","teardown-asset"]') + ).toBe(false); }); test("retains pending content when the repository write fails during teardown", async () => { diff --git a/apps/builder/app/shared/external-content-roots.ts b/apps/builder/app/shared/external-content-roots.ts index df9b72c2ed..594f5267dd 100644 --- a/apps/builder/app/shared/external-content-roots.ts +++ b/apps/builder/app/shared/external-content-roots.ts @@ -62,6 +62,7 @@ import type { import { getAssetContentBridge } from "./asset-content-bridge.client"; import { $externalContentRoots, + $externalContentAssetStatuses, clearExternalContentTemplateInsertions, getAffectedExternalContentTemplateRootKeys, getExternalContentRoots, @@ -195,6 +196,40 @@ const assetQueues = new Map(); const subscribedSessions = new WeakSet(); const getAssetQueueKey = (projectId: string, assetId: string) => JSON.stringify([projectId, assetId]); +const publishAssetSaveStatus = ({ + projectId, + assetId, + status, + queue, +}: { + projectId: string; + assetId: string; + status: AssetContentSessionState["status"] | undefined; + queue?: AssetQueue; +}) => { + const key = getAssetQueueKey(projectId, assetId); + const next = new Map($externalContentAssetStatuses.get()); + const visibleStatus = queue?.error + ? "failed" + : status === "failed" || status === "conflicting" + ? status + : (queue?.pendingSnapshots ?? 0) > 0 + ? "pending" + : status; + if ( + (visibleStatus === "saved" || visibleStatus === undefined + ? undefined + : visibleStatus) === next.get(key) + ) { + return; + } + if (visibleStatus === "saved" || visibleStatus === undefined) { + next.delete(key); + } else { + next.set(key, visibleStatus); + } + $externalContentAssetStatuses.set(next); +}; const getRootKey = ( projectId: string, sourceBlockInstanceId: string, @@ -962,6 +997,13 @@ const getSession = (projectId: string) => { subscribedSessions.add(session); session.subscribe((assetId, state) => { const queueKey = getAssetQueueKey(projectId, assetId); + const queue = assetQueues.get(queueKey); + publishAssetSaveStatus({ + projectId, + assetId, + status: state.status, + queue, + }); if (state.status === "conflicting") { getAssetContentBridge().requireReload( state.error?.message ?? @@ -969,7 +1011,6 @@ const getSession = (projectId: string) => { ); return; } - const queue = assetQueues.get(queueKey); if ((queue?.pendingSnapshots ?? 0) === 0 && queue?.error === undefined) { void rematerializeAsset( projectId, @@ -1058,6 +1099,12 @@ const enqueueAssetUpdate = ({ queue.pendingSnapshots += 1; queue.error = undefined; publishAssetQueueError(queue); + publishAssetSaveStatus({ + projectId, + assetId, + status: session.get(assetId)?.status, + queue, + }); const saving = queue.serialization.then(async () => { const state = session.get(assetId); if (state === undefined) { @@ -1098,6 +1145,12 @@ const enqueueAssetUpdate = ({ queue.failedPreservedRootKey = undefined; queue.error = undefined; publishAssetQueueError(queue); + publishAssetSaveStatus({ + projectId, + assetId, + status: session.get(assetId)?.status, + queue, + }); }, (error) => { queue.failedUpdate = update; @@ -1110,6 +1163,12 @@ const enqueueAssetUpdate = ({ getAssetContentBridge().requireReload(queue.error.message); } publishAssetQueueError(queue); + publishAssetSaveStatus({ + projectId, + assetId, + status: session.get(assetId)?.status, + queue, + }); throw queue.error; } ); @@ -1117,6 +1176,12 @@ const enqueueAssetUpdate = ({ .catch(() => {}) .then(async () => { queue.pendingSnapshots -= 1; + publishAssetSaveStatus({ + projectId, + assetId, + status: session.get(assetId)?.status, + queue, + }); if (queue.pendingSnapshots === 0 && succeeded) { const state = session.get(assetId); if (state !== undefined) { @@ -2210,6 +2275,13 @@ export const disposeExternalContentProject = async ({ } } subscribedSessions.delete(session); + const assetStatuses = new Map($externalContentAssetStatuses.get()); + for (const key of assetStatuses.keys()) { + if ((JSON.parse(key) as [string, string])[0] === projectId) { + assetStatuses.delete(key); + } + } + $externalContentAssetStatuses.set(assetStatuses); const history = new Map($externalContentHistory.get()); history.delete(projectId); $externalContentHistory.set(history); diff --git a/apps/builder/app/shared/sync/project-queue.ts b/apps/builder/app/shared/sync/project-queue.ts index da245e2076..b8321442d4 100644 --- a/apps/builder/app/shared/sync/project-queue.ts +++ b/apps/builder/app/shared/sync/project-queue.ts @@ -15,6 +15,7 @@ import { type SyncStatus, } from "@webstudio-is/sync-client"; import { publicStaticEnv } from "~/env/env.static"; +import { $externalContentAssetStatuses } from "~/shared/external-content-mutations"; import { createNativeClient, nativeClient } from "~/shared/trpc/trpc-client"; import * as commandQueue from "./command-queue"; import type { SyncStorage } from "~/shared/sync-client"; @@ -420,7 +421,10 @@ export const isSyncIdle = () => { export const usePreventUnload = () => { useEffect(() => { const handler = (event: BeforeUnloadEvent) => { - if ($hasUnsavedSyncChanges.get() === false) { + if ( + $hasUnsavedSyncChanges.get() === false && + $externalContentAssetStatuses.get().size === 0 + ) { return; } event.preventDefault(); diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts index e30ef1f4ff..3bca9cc157 100644 --- a/apps/builder/app/shared/sync/sync-stores.ts +++ b/apps/builder/app/shared/sync/sync-stores.ts @@ -88,7 +88,10 @@ import { areInstanceSelectorsEqual, type InstanceSelector, } from "@webstudio-is/project-build/runtime"; -import { $externalContentRoots } from "../external-content-mutations"; +import { + $externalContentRoots, + $externalContentAssetStatuses, +} from "../external-content-mutations"; import { $externalContentHistory } from "../external-content-history"; enableMapSet(); @@ -417,6 +420,10 @@ export const createObjectPool = () => { new NanostoresSyncObject("canvasScrollbarWidth", $canvasScrollbarSize), new NanostoresSyncObject("systemDataByPage", $systemDataByPage), new NanostoresSyncObject("externalContentRoots", $externalContentRoots), + new NanostoresSyncObject( + "externalContentAssetStatuses", + $externalContentAssetStatuses + ), new NanostoresSyncObject("externalContentHistory", $externalContentHistory), ]); }; diff --git a/apps/builder/e2e/fixtures/assets/nested-heading-source.mdx b/apps/builder/e2e/fixtures/assets/nested-heading-source.mdx new file mode 100644 index 0000000000..afd5322ac2 --- /dev/null +++ b/apps/builder/e2e/fixtures/assets/nested-heading-source.mdx @@ -0,0 +1,11 @@ + + + +

+ JÄRKI
+ myyntistrategian
+ perustukset +

+
+
+
diff --git a/apps/builder/e2e/fixtures/mdx-content-block-project.ts b/apps/builder/e2e/fixtures/mdx-content-block-project.ts index f53fbc89b2..8af7824f4f 100644 --- a/apps/builder/e2e/fixtures/mdx-content-block-project.ts +++ b/apps/builder/e2e/fixtures/mdx-content-block-project.ts @@ -95,6 +95,33 @@ export const configureNamedTemplateLifecycle = async (projectId: string) => { await updateBuild(build.id, { instances: JSON.stringify(instances) }); }; +export const configureNestedHeadingTemplates = async (projectId: string) => { + const { build, instances } = await getBuildData(projectId); + const templates = instances.find((instance) => instance.id === templateId); + if (templates === undefined) { + throw new Error("Expected the Content Block templates fixture instance"); + } + const nestedTemplates = [ + { id: "service-card-template", name: "ServiceCard", tag: "a" }, + { id: "card-shell-template", name: "CardShell", tag: "div" }, + { id: "card-text-template", name: "CardText", tag: "div" }, + ]; + templates.children.push( + ...nestedTemplates.map(({ id }) => ({ type: "id", value: id })) + ); + instances.push( + ...nestedTemplates.map(({ id, name, tag }) => ({ + type: "instance" as const, + id, + component: "ws:element", + tag, + name, + children: [{ type: "text", value: "Template default" }], + })) + ); + await updateBuild(build.id, { instances: JSON.stringify(instances) }); +}; + const configureSourceBlock = ({ instances, props, diff --git a/apps/builder/e2e/schema/schema-72278df70bfbd0a76257228baefbb4d8a1007695.sql b/apps/builder/e2e/schema/schema-72278df70bfbd0a76257228baefbb4d8a1007695.sql new file mode 100644 index 0000000000..939198687f --- /dev/null +++ b/apps/builder/e2e/schema/schema-72278df70bfbd0a76257228baefbb4d8a1007695.sql @@ -0,0 +1,1914 @@ +-- +-- PostgreSQL database dump +-- + +\restrict webstudioE2ESchema + +-- Dumped from database version 15.19 (Debian 15.19-1.pgdg12+2) +-- Dumped by pg_dump version 15.19 (Debian 15.19-1.pgdg12+2) + +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_domainsVirtualId_fkey"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_buildId_fkey"; +ALTER TABLE IF EXISTS ONLY public."domainsVirtual" DROP CONSTRAINT IF EXISTS "domainsVirtual_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."domainsVirtual" DROP CONSTRAINT IF EXISTS "domainsVirtual_domainId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Workspace" DROP CONSTRAINT IF EXISTS "Workspace_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."WorkspaceMember" DROP CONSTRAINT IF EXISTS "WorkspaceMember_workspaceId_fkey"; +ALTER TABLE IF EXISTS ONLY public."WorkspaceMember" DROP CONSTRAINT IF EXISTS "WorkspaceMember_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."TransactionLog" DROP CONSTRAINT IF EXISTS "TransactionLog_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."TransactionLog" DROP CONSTRAINT IF EXISTS "TransactionLog_productId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_workspaceId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_previewImageAssetId_id_fkey"; +ALTER TABLE IF EXISTS ONLY public."ProjectDomain" DROP CONSTRAINT IF EXISTS "ProjectDomain_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."ProjectDomain" DROP CONSTRAINT IF EXISTS "ProjectDomain_domainId_fkey"; +ALTER TABLE IF EXISTS ONLY public."File" DROP CONSTRAINT IF EXISTS "File_uploaderProjectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."ClientReferences" DROP CONSTRAINT IF EXISTS "ClientReferences_userId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Build" DROP CONSTRAINT IF EXISTS "Build_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AuthorizationToken" DROP CONSTRAINT IF EXISTS "AuthorizationToken_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."Asset" DROP CONSTRAINT IF EXISTS "Asset_name_fkey"; +ALTER TABLE IF EXISTS ONLY public."Asset" DROP CONSTRAINT IF EXISTS "Asset_folderId_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFolder" DROP CONSTRAINT IF EXISTS "AssetFolder_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFolder" DROP CONSTRAINT IF EXISTS "AssetFolder_parentId_projectId_fkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFileMetadata" DROP CONSTRAINT IF EXISTS "AssetFileMetadata_assetId_projectId_fkey"; +DROP INDEX IF EXISTS public."Workspace_userId_isDefault_key"; +DROP INDEX IF EXISTS public."WorkspaceMember_userId_idx"; +DROP INDEX IF EXISTS public."User_email_key"; +DROP INDEX IF EXISTS public."TransactionLog_eventId_productId_key"; +DROP INDEX IF EXISTS public."Project_isDeleted_marketplaceApprovalStatus_idx"; +DROP INDEX IF EXISTS public."Project_id_isDeleted_key"; +DROP INDEX IF EXISTS public."Project_id_domain_key"; +DROP INDEX IF EXISTS public."Project_domain_key"; +DROP INDEX IF EXISTS public."Project_domain_isDeleted_key"; +DROP INDEX IF EXISTS public."ProjectDomain_txtRecord_key"; +DROP INDEX IF EXISTS public."ProjectDomain_domainId_idx"; +DROP INDEX IF EXISTS public."Notification_recipientId_status_idx"; +DROP INDEX IF EXISTS public."File_uploaderProjectId_contentHash_extension_key"; +DROP INDEX IF EXISTS public."Domain_domain_key"; +DROP INDEX IF EXISTS public."ClientReferences_reference_service_key"; +DROP INDEX IF EXISTS public."Build_projectId_createdAt_idx"; +DROP INDEX IF EXISTS public."Build_id_key"; +DROP INDEX IF EXISTS public."Build_dev_index"; +DROP INDEX IF EXISTS public."AuthorizationToken_token_key"; +DROP INDEX IF EXISTS public."AssetFolder_unique_sibling_name"; +DROP INDEX IF EXISTS public."AssetFolder_projectId_parentId_idx"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_pkey"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_domainsVirtualId_key"; +ALTER TABLE IF EXISTS ONLY public."latestBuildVirtual" DROP CONSTRAINT IF EXISTS "latestBuildVirtual_buildId_key"; +ALTER TABLE IF EXISTS ONLY public."domainsVirtual" DROP CONSTRAINT IF EXISTS "domainsVirtual_pkey"; +ALTER TABLE IF EXISTS ONLY public._prisma_migrations DROP CONSTRAINT IF EXISTS _prisma_migrations_pkey; +ALTER TABLE IF EXISTS ONLY public."Workspace" DROP CONSTRAINT IF EXISTS "Workspace_pkey"; +ALTER TABLE IF EXISTS ONLY public."WorkspaceMember" DROP CONSTRAINT IF EXISTS "WorkspaceMember_pkey"; +ALTER TABLE IF EXISTS ONLY public."User" DROP CONSTRAINT IF EXISTS "User_pkey"; +ALTER TABLE IF EXISTS ONLY public."TransactionLog" DROP CONSTRAINT IF EXISTS "TransactionLog_pkey"; +ALTER TABLE IF EXISTS ONLY public."Project" DROP CONSTRAINT IF EXISTS "Project_pkey"; +ALTER TABLE IF EXISTS ONLY public."ProjectDomain" DROP CONSTRAINT IF EXISTS "ProjectDomain_pkey"; +ALTER TABLE IF EXISTS ONLY public."Product" DROP CONSTRAINT IF EXISTS "Product_pkey"; +ALTER TABLE IF EXISTS ONLY public."Notification" DROP CONSTRAINT IF EXISTS "Notification_pkey"; +ALTER TABLE IF EXISTS ONLY public."File" DROP CONSTRAINT IF EXISTS "File_pkey"; +ALTER TABLE IF EXISTS ONLY public."Domain" DROP CONSTRAINT IF EXISTS "Domain_pkey"; +ALTER TABLE IF EXISTS ONLY public."ClientReferences" DROP CONSTRAINT IF EXISTS "ClientReferences_pkey"; +ALTER TABLE IF EXISTS ONLY public."Build" DROP CONSTRAINT IF EXISTS "Build_pkey"; +ALTER TABLE IF EXISTS ONLY public."AuthorizationToken" DROP CONSTRAINT IF EXISTS "AuthorizationToken_pkey"; +ALTER TABLE IF EXISTS ONLY public."Asset" DROP CONSTRAINT IF EXISTS "Asset_pkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFolder" DROP CONSTRAINT IF EXISTS "AssetFolder_pkey"; +ALTER TABLE IF EXISTS ONLY public."AssetFileMetadata" DROP CONSTRAINT IF EXISTS "AssetFileMetadata_pkey"; +DROP VIEW IF EXISTS public.user_publish_count; +DROP VIEW IF EXISTS public.published_builds; +DROP TABLE IF EXISTS public._prisma_migrations; +DROP VIEW IF EXISTS public."WorkspaceProjectAuthorization"; +DROP TABLE IF EXISTS public."WorkspaceMember"; +DROP TABLE IF EXISTS public."Workspace"; +DROP VIEW IF EXISTS public."UserProduct"; +DROP TABLE IF EXISTS public."User"; +DROP TABLE IF EXISTS public."TransactionLog"; +DROP TABLE IF EXISTS public."ProjectDomain"; +DROP TABLE IF EXISTS public."Product"; +DROP TABLE IF EXISTS public."Notification"; +DROP VIEW IF EXISTS public."LatestStaticBuildPerProject"; +DROP TABLE IF EXISTS public."File"; +DROP TABLE IF EXISTS public."Domain"; +DROP TABLE IF EXISTS public."ClientReferences"; +DROP TABLE IF EXISTS public."AssetFolder"; +DROP TABLE IF EXISTS public."AssetFileMetadata"; +DROP TABLE IF EXISTS public."Asset"; +DROP VIEW IF EXISTS public."ApprovedMarketplaceProduct"; +DROP TABLE IF EXISTS public."AuthorizationToken"; +DROP FUNCTION IF EXISTS public.swap_asset_file(project_id text, asset_id text, expected_name text, replacement_name text); +DROP FUNCTION IF EXISTS public.restore_development_build(project_id text, from_build_id text); +DROP FUNCTION IF EXISTS public.replace_asset_file_metadata(p_project_id text, p_asset_id text, p_revision text, p_document jsonb, p_source jsonb); +DROP FUNCTION IF EXISTS public."latestProjectDomainBuildVirtual"(public."Project"); +DROP FUNCTION IF EXISTS public."latestBuildVirtual"(public."domainsVirtual"); +DROP FUNCTION IF EXISTS public."latestBuildVirtual"(public."Project"); +DROP FUNCTION IF EXISTS public."latestBuildVirtual"(public."DashboardProject"); +DROP TABLE IF EXISTS public."latestBuildVirtual"; +DROP VIEW IF EXISTS public."DashboardProject"; +DROP TABLE IF EXISTS public."Build"; +DROP FUNCTION IF EXISTS public."domainsVirtual"(public."Project"); +DROP TABLE IF EXISTS public."domainsVirtual"; +DROP FUNCTION IF EXISTS public.delete_stale_asset_file_metadata(p_project_id text, p_asset_ids text[]); +DROP FUNCTION IF EXISTS public.delete_asset_file_metadata_if_matches(p_project_id text, p_asset_id text, p_revision text, p_document jsonb); +DROP FUNCTION IF EXISTS public.database_cleanup(from_date timestamp without time zone, to_date timestamp without time zone); +DROP FUNCTION IF EXISTS public.create_production_build_expected(project_id text, deployment text, expected_version integer); +DROP FUNCTION IF EXISTS public.create_production_build(project_id text, deployment text); +DROP FUNCTION IF EXISTS public.clone_project(project_id text, user_id text, title text, domain text); +DROP TABLE IF EXISTS public."Project"; +DROP TYPE IF EXISTS public."UploadStatus"; +DROP TYPE IF EXISTS public."PublishStatus"; +DROP TYPE IF EXISTS public."MarketplaceApprovalStatus"; +DROP TYPE IF EXISTS public."DomainStatus"; +DROP TYPE IF EXISTS public."AuthorizationRelation"; +DROP SCHEMA IF EXISTS public; +-- +-- Name: public; Type: SCHEMA; Schema: -; Owner: - +-- + +CREATE SCHEMA public; + + +-- +-- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: - +-- + +COMMENT ON SCHEMA public IS 'standard public schema'; + + +-- +-- Name: AuthorizationRelation; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."AuthorizationRelation" AS ENUM ( + 'viewers', + 'editors', + 'builders', + 'administrators' +); + + +-- +-- Name: DomainStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."DomainStatus" AS ENUM ( + 'INITIALIZING', + 'ACTIVE', + 'ERROR', + 'PENDING' +); + + +-- +-- Name: MarketplaceApprovalStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."MarketplaceApprovalStatus" AS ENUM ( + 'UNLISTED', + 'PENDING', + 'APPROVED', + 'REJECTED' +); + + +-- +-- Name: PublishStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."PublishStatus" AS ENUM ( + 'PENDING', + 'PUBLISHED', + 'FAILED' +); + + +-- +-- Name: UploadStatus; Type: TYPE; Schema: public; Owner: - +-- + +CREATE TYPE public."UploadStatus" AS ENUM ( + 'UPLOADING', + 'UPLOADED' +); + + +SET default_tablespace = ''; + +SET default_table_access_method = heap; + +-- +-- Name: Project; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE 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, + tags text[], + "workspaceId" uuid +); + + +-- +-- Name: clone_project(text, text, text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.clone_project(project_id text, user_id text, title text, domain text) RETURNS public."Project" + LANGUAGE plpgsql + AS $$ +DECLARE + old_project "Project"; + new_project "Project"; +BEGIN + SELECT * FROM "Project" WHERE id = project_id INTO old_project; + + INSERT INTO "Project" (id, "userId", title, domain) + VALUES (gen_random_uuid(), user_id, title, domain) + RETURNING * INTO new_project; + + INSERT INTO "AssetFolder" (id, "projectId", name, "parentId", "createdAt") + SELECT id, new_project.id, name, "parentId", "createdAt" + FROM "AssetFolder" + WHERE "projectId" = old_project.id; + + INSERT INTO "Asset" ( + id, + name, + "projectId", + filename, + description, + "folderId" + ) + SELECT + asset.id, + asset.name, + new_project.id, + asset.filename, + asset.description, + asset."folderId" + FROM "Asset" AS asset, "File" AS file + WHERE + asset.name = file.name AND + file.status = 'UPLOADED' AND + asset."projectId" = old_project.id; + + UPDATE "Project" + SET "previewImageAssetId" = old_project."previewImageAssetId" + WHERE id = new_project.id; + + INSERT INTO "Build" ( + id, + "projectId", + pages, + "styleSources", + "styleSourceSelections", + styles, + breakpoints, + props, + instances, + "dataSources", + resources, + "marketplaceProduct", + "projectSettings" + ) + SELECT + gen_random_uuid(), + new_project.id, + pages, + "styleSources", + "styleSourceSelections", + styles, + breakpoints, + props, + instances, + "dataSources", + resources, + "marketplaceProduct", + "projectSettings" + FROM "Build" + WHERE "projectId" = old_project.id AND deployment IS NULL; + + RETURN new_project; +END; +$$; + + +-- +-- Name: create_production_build(text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.create_production_build(project_id text, deployment text) RETURNS text + LANGUAGE plpgsql + AS $$ +DECLARE + new_build_id text; +BEGIN + INSERT INTO "Build" ( + version, + "lastTransactionId", + pages, + breakpoints, + styles, + "styleSources", + "styleSourceSelections", + props, + "dataSources", + resources, + instances, + "marketplaceProduct", + "projectSettings", + "publishStatus", + "projectId", + id, + deployment + ) + SELECT + version, + "lastTransactionId", + pages, + breakpoints, + styles, + "styleSources", + "styleSourceSelections", + props, + "dataSources", + resources, + instances, + "marketplaceProduct", + "projectSettings", + "publishStatus", + "projectId", + extensions.uuid_generate_v4(), + create_production_build.deployment + FROM "Build" + WHERE "projectId" = project_id AND "Build".deployment IS NULL + RETURNING id INTO new_build_id; + + RETURN new_build_id; +END; +$$; + + +-- +-- Name: create_production_build_expected(text, text, integer); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.create_production_build_expected(project_id text, deployment text, expected_version integer) RETURNS text + LANGUAGE plpgsql + AS $$ +DECLARE + new_build_id text; +BEGIN + INSERT INTO "Build" ( + version, "lastTransactionId", pages, breakpoints, styles, "styleSources", + "styleSourceSelections", props, "dataSources", resources, instances, + "marketplaceProduct", "projectSettings", "publishStatus", "projectId", id, + deployment + ) + SELECT + version, "lastTransactionId", pages, breakpoints, styles, "styleSources", + "styleSourceSelections", props, "dataSources", resources, instances, + "marketplaceProduct", "projectSettings", "publishStatus", "projectId", + extensions.uuid_generate_v4(), create_production_build_expected.deployment + FROM "Build" + WHERE "projectId" = project_id + AND "Build".deployment IS NULL + AND version = expected_version + RETURNING id INTO new_build_id; + + RETURN new_build_id; +END; +$$; + + +-- +-- Name: database_cleanup(timestamp without time zone, timestamp without time zone); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.database_cleanup(from_date timestamp without time zone DEFAULT '2020-01-01 00:00:00'::timestamp without time zone, to_date timestamp without time zone DEFAULT '2099-12-31 23:59:59'::timestamp without time zone) RETURNS void + LANGUAGE plpgsql + AS $$ +BEGIN + WITH latest_builds AS ( + SELECT "buildId" FROM "Project" p, LATERAL "latestProjectDomainBuildVirtual"(p) + UNION + SELECT "buildId" FROM "Project" p, LATERAL "latestBuildVirtual"(p) + UNION + SELECT lb."buildId" + FROM "Project" p, LATERAL "domainsVirtual"(p) dv, LATERAL "latestBuildVirtual"(dv) lb + ) + UPDATE "Build" + SET + "styleSources" = '[]', + styles = '[]', + breakpoints = '[]', + "styleSourceSelections" = '[]', + props = '[]', + instances = '[]', + "dataSources" = '[]', + resources = '[]', + "marketplaceProduct" = '{}', + "projectSettings" = '{"meta":{},"compiler":{}}', + "isCleaned" = true + WHERE deployment IS NOT NULL + AND id NOT IN (SELECT "buildId" FROM latest_builds) + AND "isCleaned" = false + AND "createdAt" BETWEEN from_date AND to_date; +END; +$$; + + +-- +-- Name: delete_asset_file_metadata_if_matches(text, text, text, jsonb); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.delete_asset_file_metadata_if_matches(p_project_id text, p_asset_id text, p_revision text, p_document jsonb) RETURNS integer + LANGUAGE plpgsql + AS $$ +DECLARE + deleted_count INTEGER; +BEGIN + PERFORM pg_catalog.pg_advisory_xact_lock( + pg_catalog.hashtextextended( + pg_catalog.jsonb_build_array(p_project_id, p_asset_id)::TEXT, + 0 + ) + ); + + DELETE FROM public."AssetFileMetadata" + WHERE "projectId" = p_project_id + AND "assetId" = p_asset_id + AND "revision" = p_revision + AND "document" = p_document; + GET DIAGNOSTICS deleted_count = ROW_COUNT; + RETURN deleted_count; +END; +$$; + + +-- +-- Name: delete_stale_asset_file_metadata(text, text[]); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.delete_stale_asset_file_metadata(p_project_id text, p_asset_ids text[]) RETURNS integer + LANGUAGE plpgsql + AS $$ +DECLARE + asset_id TEXT; + deleted_count INTEGER; + total_deleted INTEGER := 0; +BEGIN + FOR asset_id IN + SELECT DISTINCT requested_asset_id + FROM pg_catalog.unnest(p_asset_ids) AS requested_asset_id + ORDER BY requested_asset_id + LOOP + PERFORM pg_catalog.pg_advisory_xact_lock( + pg_catalog.hashtextextended( + pg_catalog.jsonb_build_array(p_project_id, asset_id)::TEXT, + 0 + ) + ); + + IF NOT EXISTS ( + SELECT 1 + FROM public."Asset" AS asset + INNER JOIN public."File" AS file ON file."name" = asset."name" + WHERE asset."projectId" = p_project_id + AND asset."id" = asset_id + AND file."status" = 'UPLOADED' + ) THEN + DELETE FROM public."AssetFileMetadata" + WHERE "projectId" = p_project_id + AND "assetId" = asset_id; + GET DIAGNOSTICS deleted_count = ROW_COUNT; + total_deleted := total_deleted + deleted_count; + END IF; + END LOOP; + + RETURN total_deleted; +END; +$$; + + +-- +-- Name: domainsVirtual; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."domainsVirtual" ( + id text NOT NULL, + "domainId" text NOT NULL, + "projectId" text NOT NULL, + domain text NOT NULL, + status public."DomainStatus" DEFAULT 'INITIALIZING'::public."DomainStatus" NOT NULL, + error text, + "domainTxtRecord" text, + "expectedTxtRecord" text NOT NULL, + cname text NOT NULL, + verified boolean DEFAULT false NOT NULL, + "createdAt" timestamp(3) with time zone NOT NULL, + "updatedAt" timestamp(3) with time zone NOT NULL +); + + +-- +-- Name: TABLE "domainsVirtual"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON TABLE public."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).'; + + +-- +-- Name: COLUMN "domainsVirtual"."domainId"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."domainId" IS 'Unique identifier for the domain (Domain table reference).'; + + +-- +-- Name: COLUMN "domainsVirtual"."projectId"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."projectId" IS 'Unique identifier for the project, acting as the primary key (1-1 relationship with Project table).'; + + +-- +-- Name: COLUMN "domainsVirtual".domain; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".domain IS 'The domain name (must not be NULL).'; + + +-- +-- Name: COLUMN "domainsVirtual".status; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".status IS 'Current status of the domain, with a default of INITIALIZING.'; + + +-- +-- Name: COLUMN "domainsVirtual".error; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".error IS 'Optional error message field populated if the domain status is ERROR.'; + + +-- +-- Name: COLUMN "domainsVirtual"."domainTxtRecord"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."domainTxtRecord" IS 'Current TXT record for the domain, coming from the Domain table.'; + + +-- +-- Name: COLUMN "domainsVirtual"."expectedTxtRecord"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."expectedTxtRecord" IS 'Expected TXT record for the domain, pulled from the ProjectDomain table.'; + + +-- +-- Name: COLUMN "domainsVirtual".verified; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual".verified IS 'Boolean flag indicating whether the domain is verified (true if TXT records match, false otherwise).'; + + +-- +-- Name: COLUMN "domainsVirtual"."createdAt"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."createdAt" IS 'Timestamp indicating when the ProjectDomain entry was created.'; + + +-- +-- Name: COLUMN "domainsVirtual"."updatedAt"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."domainsVirtual"."updatedAt" IS 'Timestamp indicating when the Domain was last updated.'; + + +-- +-- Name: domainsVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."domainsVirtual"(public."Project") RETURNS SETOF public."domainsVirtual" + LANGUAGE sql STABLE + AS $_$ + -- This function retrieves all the domain information associated with a specific project by joining the Domain and ProjectDomain tables. + -- It returns a result set conforming to the "domainsVirtual" structure, including fields such as domain status, error, verification status, etc. + SELECT + "Domain".id || '-' || "ProjectDomain"."projectId" as id, + "Domain".id AS "domainId", -- Domain ID from Domain table + "ProjectDomain"."projectId", -- Project ID from ProjectDomain table + "Domain".domain, -- Domain name + "Domain".status, -- Current domain status + "Domain".error, -- Error message, if any + "Domain"."txtRecord" AS "domainTxtRecord", -- Current TXT record from Domain table + "ProjectDomain"."txtRecord" AS "expectedTxtRecord", -- Expected TXT record from ProjectDomain table + "ProjectDomain"."cname" AS "cname", + CASE + WHEN "Domain"."txtRecord" = "ProjectDomain"."txtRecord" THEN true -- If TXT records match, domain is verified + ELSE false + END AS "verified", -- Boolean flag for verification status + "ProjectDomain"."createdAt", -- Creation timestamp from ProjectDomain table + "Domain"."updatedAt" -- Last updated timestamp from Domain table + FROM + "Domain" + JOIN + "ProjectDomain" ON "Domain".id = "ProjectDomain"."domainId" -- Joining Domain and ProjectDomain on domainId + WHERE + "ProjectDomain"."projectId" = $1.id -- Filtering by projectId passed as an argument to the function + ORDER BY "ProjectDomain"."createdAt", "Domain".id; -- Stable sort +$_$; + + +-- +-- Name: FUNCTION "domainsVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."domainsVirtual"(public."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.'; + + +-- +-- Name: Build; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE 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, + "isCleaned" boolean DEFAULT false, + "projectSettings" text DEFAULT '{"meta":{},"compiler":{}}'::text NOT NULL +); + + +-- +-- Name: DashboardProject; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."DashboardProject" AS + SELECT "Project".id, + "Project".title, + "Project".tags, + "Project".domain, + "Project"."userId", + "Project"."workspaceId", + "Project"."isDeleted", + "Project"."createdAt", + "Project"."previewImageAssetId", + "Project"."marketplaceApprovalStatus", + (EXISTS ( SELECT 1 + FROM public."Build" + WHERE (("Build"."projectId" = "Project".id) AND ("Build".deployment IS NOT NULL)))) AS "isPublished" + FROM public."Project"; + + +-- +-- Name: latestBuildVirtual; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."latestBuildVirtual" ( + "buildId" text NOT NULL, + "projectId" text NOT NULL, + "domainsVirtualId" text NOT NULL, + domain text NOT NULL, + "createdAt" timestamp(3) with time zone NOT NULL, + "publishStatus" public."PublishStatus" NOT NULL, + "updatedAt" timestamp(3) with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: TABLE "latestBuildVirtual"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON TABLE public."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'; + + +-- +-- Name: COLUMN "latestBuildVirtual"."projectId"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."latestBuildVirtual"."projectId" IS 'Identifier for the project, enforcing a 1-1 relationship with the Project table as a primary key'; + + +-- +-- Name: COLUMN "latestBuildVirtual"."updatedAt"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON COLUMN public."latestBuildVirtual"."updatedAt" IS 'Timestamp indicating when the Build was last updated'; + + +-- +-- Name: latestBuildVirtual(public."DashboardProject"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestBuildVirtual"(public."DashboardProject") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +SELECT + lbv.* +FROM + "Project" p, + LATERAL "latestBuildVirtual"(p) lbv +WHERE + p.id = $1.id +LIMIT 1; + +$_$; + + +-- +-- Name: FUNCTION "latestBuildVirtual"(public."DashboardProject"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestBuildVirtual"(public."DashboardProject") IS 'Wrapper function to make latestBuildVirtual work with DashboardProject view for PostgREST computed fields.'; + + +-- +-- Name: latestBuildVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestBuildVirtual"(public."Project") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +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", + b."updatedAt" +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; + +$_$; + + +-- +-- Name: FUNCTION "latestBuildVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestBuildVirtual"(public."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.'; + + +-- +-- Name: latestBuildVirtual(public."domainsVirtual"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestBuildVirtual"(public."domainsVirtual") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +SELECT + b.id AS "buildId", + b."projectId", + '' as "domainsVirtualId", + d."domain", + b."createdAt", + b."publishStatus", + b."updatedAt" +FROM + "Build" b + JOIN "Domain" d ON d.id = $1."domainId" +WHERE + b."projectId" = $1."projectId" + AND b.deployment IS NOT NULL + AND (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [d.domain]) +ORDER BY + b."createdAt" DESC +LIMIT + 1; + +$_$; + + +-- +-- Name: FUNCTION "latestBuildVirtual"(public."domainsVirtual"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestBuildVirtual"(public."domainsVirtual") IS 'Returns the latest build for a given project and domain as a computed field for PostgREST.'; + + +-- +-- Name: latestProjectDomainBuildVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public."latestProjectDomainBuildVirtual"(public."Project") RETURNS SETOF public."latestBuildVirtual" + LANGUAGE sql STABLE ROWS 1 + AS $_$ +SELECT + b.id AS "buildId", + b."projectId", + '' as "domainsVirtualId", + p.domain AS "domain", + b."createdAt", + b."publishStatus", + b."updatedAt" +FROM + "Build" b + JOIN "Project" p ON b."projectId" = p.id + LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id +WHERE + b."projectId" = $1.id + AND b.deployment IS NOT NULL + AND ( + (b.deployment :: jsonb ->> 'destination') IS NULL + OR (b.deployment :: jsonb ->> 'destination') = 'saas' + ) + AND ( + (b.deployment :: jsonb ->> 'projectDomain') = p.domain + OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [p.domain]) + ) +ORDER BY + b."createdAt" DESC +LIMIT + 1; + +$_$; + + +-- +-- Name: FUNCTION "latestProjectDomainBuildVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON FUNCTION public."latestProjectDomainBuildVirtual"(public."Project") IS 'This function computes the latest build for a project domain, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.'; + + +-- +-- Name: replace_asset_file_metadata(text, text, text, jsonb, jsonb); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.replace_asset_file_metadata(p_project_id text, p_asset_id text, p_revision text, p_document jsonb, p_source jsonb) RETURNS boolean + LANGUAGE plpgsql + AS $$ +BEGIN + PERFORM pg_catalog.pg_advisory_xact_lock( + pg_catalog.hashtextextended( + pg_catalog.jsonb_build_array(p_project_id, p_asset_id)::TEXT, + 0 + ) + ); + + PERFORM 1 + FROM public."Asset" AS asset + INNER JOIN public."File" AS file ON file."name" = asset."name" + WHERE asset."projectId" = p_project_id + AND asset."id" = p_asset_id + AND asset."filename" IS NOT DISTINCT FROM p_source->>'filename' + AND asset."description" IS NOT DISTINCT FROM p_source->>'description' + AND asset."folderId" IS NOT DISTINCT FROM p_source->>'folderId' + AND file."name" = p_source->>'storageName' + AND file."updatedAt" = (p_source->>'fileUpdatedAt')::TIMESTAMPTZ + AND file."size" = (p_source->>'fileSize')::INTEGER + AND file."status" = 'UPLOADED' + FOR UPDATE OF asset, file; + + IF NOT FOUND THEN + RETURN FALSE; + END IF; + + INSERT INTO public."AssetFileMetadata" ( + "projectId", + "assetId", + "revision", + "document", + "updatedAt" + ) VALUES ( + p_project_id, + p_asset_id, + p_revision, + p_document, + CURRENT_TIMESTAMP + ) + ON CONFLICT ("projectId", "assetId") + DO UPDATE SET + "revision" = EXCLUDED."revision", + "document" = EXCLUDED."document", + "updatedAt" = EXCLUDED."updatedAt" + WHERE "AssetFileMetadata"."revision" IS DISTINCT FROM EXCLUDED."revision" + OR "AssetFileMetadata"."document" IS DISTINCT FROM EXCLUDED."document"; + + RETURN TRUE; +END; +$$; + + +-- +-- Name: restore_development_build(text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.restore_development_build(project_id text, from_build_id text) RETURNS text + LANGUAGE plpgsql + AS $$ +BEGIN + UPDATE "Build" + SET + version = source.version, + "lastTransactionId" = source."lastTransactionId", + pages = source.pages, + breakpoints = source.breakpoints, + styles = source.styles, + "styleSources" = source."styleSources", + "styleSourceSelections" = source."styleSourceSelections", + props = source.props, + "dataSources" = source."dataSources", + resources = source.resources, + instances = source.instances, + "marketplaceProduct" = source."marketplaceProduct", + "projectSettings" = source."projectSettings" + FROM ( + SELECT * FROM "Build" + WHERE "projectId" = project_id AND id = from_build_id + ) AS source + WHERE "Build"."projectId" = project_id AND "Build".deployment IS NULL; + RETURN 'OK'; +END; +$$; + + +-- +-- Name: swap_asset_file(text, text, text, text); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.swap_asset_file(project_id text, asset_id text, expected_name text, replacement_name text) RETURNS text + LANGUAGE plpgsql + AS $$ +DECLARE + current_name text; +BEGIN + SELECT "name" + INTO current_name + FROM "Asset" + WHERE "projectId" = project_id AND "id" = asset_id + FOR UPDATE; + + IF current_name IS NULL THEN + RETURN 'not_found'; + END IF; + + IF current_name <> expected_name THEN + RETURN 'conflict'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM "File" + WHERE + "name" = replacement_name + AND "status" = 'UPLOADED' + AND "uploaderProjectId" = project_id + ) THEN + RETURN 'invalid_revision'; + END IF; + + UPDATE "File" + SET "isDeleted" = false + WHERE "name" = replacement_name; + + UPDATE "Asset" + SET "name" = replacement_name + WHERE "projectId" = project_id AND "id" = asset_id; + + UPDATE "File" + SET "isDeleted" = true + WHERE + "name" = expected_name + AND NOT EXISTS ( + SELECT 1 FROM "Asset" WHERE "name" = expected_name + ); + + RETURN 'updated'; +END; +$$; + + +-- +-- Name: AuthorizationToken; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."AuthorizationToken" ( + token text NOT NULL, + "projectId" text NOT NULL, + name text DEFAULT ''::text NOT NULL, + relation public."AuthorizationRelation" DEFAULT 'viewers'::public."AuthorizationRelation" NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "canClone" boolean DEFAULT true NOT NULL, + "canCopy" boolean DEFAULT true NOT NULL, + "canPublish" boolean DEFAULT false NOT NULL, + "canUseApi" boolean DEFAULT false NOT NULL +); + + +-- +-- Name: ApprovedMarketplaceProduct; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."ApprovedMarketplaceProduct" AS + SELECT DISTINCT ON (build."projectId") build."projectId", + build."marketplaceProduct", + ( SELECT auth.token + FROM public."AuthorizationToken" auth + WHERE ((auth."projectId" = build."projectId") AND (auth.relation = 'viewers'::public."AuthorizationRelation")) + ORDER BY auth.token + LIMIT 1) AS "authorizationToken" + FROM public."Build" build + WHERE ((build.deployment IS NOT NULL) AND (build."projectId" IN ( SELECT "Project".id + FROM public."Project" + WHERE (("Project"."isDeleted" = false) AND ("Project"."marketplaceApprovalStatus" = ('APPROVED'::text)::public."MarketplaceApprovalStatus"))))) + ORDER BY build."projectId", build."createdAt" DESC, build.id; + + +-- +-- Name: Asset; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Asset" ( + id text NOT NULL, + "projectId" text NOT NULL, + name text NOT NULL, + description text, + filename text, + "folderId" text +); + + +-- +-- Name: AssetFileMetadata; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."AssetFileMetadata" ( + "projectId" text NOT NULL, + "assetId" text NOT NULL, + revision text NOT NULL, + document jsonb NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + CONSTRAINT "AssetFileMetadata_document_identity_check" CHECK ((((jsonb_typeof(document) = 'object'::text) AND (jsonb_typeof((document -> '_id'::text)) = 'string'::text) AND ((document ->> '_id'::text) = "assetId") AND (jsonb_typeof((document -> 'revision'::text)) = 'string'::text) AND ((document ->> 'revision'::text) = revision)) IS TRUE)) +); + + +-- +-- Name: AssetFolder; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."AssetFolder" ( + id text DEFAULT gen_random_uuid() NOT NULL, + "projectId" text NOT NULL, + name text NOT NULL, + "parentId" text, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + CONSTRAINT "AssetFolder_name_not_blank" CHECK ((btrim(name) <> ''::text)) +); + + +-- +-- Name: ClientReferences; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."ClientReferences" ( + reference text DEFAULT extensions.uuid_generate_v4() NOT NULL, + service text NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "userId" text NOT NULL +); + + +-- +-- Name: Domain; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE 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 +); + + +-- +-- Name: File; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."File" ( + name text NOT NULL, + format text NOT NULL, + size integer NOT NULL, + description text, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + meta text DEFAULT '{}'::text NOT NULL, + status public."UploadStatus" DEFAULT 'UPLOADING'::public."UploadStatus" NOT NULL, + "uploaderProjectId" text, + "isDeleted" boolean DEFAULT false NOT NULL, + "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "contentHash" character varying(64) +); + + +-- +-- Name: LatestStaticBuildPerProject; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."LatestStaticBuildPerProject" AS + SELECT DISTINCT ON (bld."projectId") bld.id AS "buildId", + bld."projectId", + bld."updatedAt", + bld."publishStatus" + FROM public."Build" bld + WHERE ((bld.deployment IS NOT NULL) AND (((bld.deployment)::jsonb ->> 'destination'::text) = 'static'::text)) + ORDER BY bld."projectId", bld."createdAt" DESC, bld.id; + + +-- +-- Name: Notification; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Notification" ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + type text NOT NULL, + "recipientId" text NOT NULL, + "senderId" text NOT NULL, + status text DEFAULT 'pending'::text NOT NULL, + payload jsonb DEFAULT '{}'::jsonb NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL, + "respondedAt" timestamp(3) with time zone +); + + +-- +-- Name: Product; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Product" ( + id text NOT NULL, + name text NOT NULL, + description text, + features text[], + images text[], + meta jsonb NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL +); + + +-- +-- Name: ProjectDomain; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE 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 +); + + +-- +-- Name: TransactionLog; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."TransactionLog" ( + "eventId" text NOT NULL, + "productId" text, + "userId" text, + "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL, + "eventData" jsonb, + "eventCreated" integer GENERATED ALWAYS AS ((("eventData" #>> '{created}'::text[]))::integer) STORED, + "eventType" text GENERATED ALWAYS AS (("eventData" #>> '{type}'::text[])) STORED, + status text GENERATED ALWAYS AS (("eventData" #>> '{data,object,status}'::text[])) STORED, + "customerId" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,customer}'::text[])) STORED, + "customerEmail" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,customer_details,email}'::text[])) STORED, + "subscriptionId" text GENERATED ALWAYS AS ( +CASE + WHEN (("eventData" #>> '{data,object,object}'::text[]) = 'subscription'::text) THEN ("eventData" #>> '{data,object,id}'::text[]) + ELSE ("eventData" #>> '{data,object,subscription}'::text[]) +END) STORED, + "paymentIntent" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,payment_intent}'::text[])) STORED +); + + +-- +-- Name: User; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE 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, + "projectsTags" jsonb DEFAULT '[]'::jsonb NOT NULL +); + + +-- +-- Name: UserProduct; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."UserProduct" AS +( SELECT tl."userId", + tl."subscriptionId", + tl."productId", + tl."customerId", + tl."customerEmail" + FROM public."TransactionLog" tl + WHERE ((tl.status = 'complete'::text) AND (tl."eventType" = 'checkout.session.completed'::text) AND (NOT (EXISTS ( SELECT 1 + FROM public."TransactionLog" failed + WHERE ((failed."eventType" = 'checkout.session.async_payment_failed'::text) AND ((failed."eventData" #>> '{data,object,id}'::text[]) = (tl."eventData" #>> '{data,object,id}'::text[])) AND (failed."eventCreated" >= tl."eventCreated"))))) AND (NOT (EXISTS ( SELECT 1 + FROM public."TransactionLog" tlexsists + WHERE ((tlexsists."subscriptionId" = tl."subscriptionId") AND (tlexsists."eventType" = 'customer.subscription.deleted'::text) AND (tlexsists.status = 'canceled'::text) AND (tlexsists."eventCreated" > tl."eventCreated"))))) AND (NOT (EXISTS ( SELECT 1 + FROM public."TransactionLog" tlexsists + WHERE ((tlexsists."paymentIntent" = tl."paymentIntent") AND (tlexsists."eventType" = 'charge.refunded'::text) AND (tlexsists.status = 'succeeded'::text) AND (tlexsists."eventCreated" > tl."eventCreated")))))) + ORDER BY tl."userId", tl."eventCreated" DESC) +UNION ALL + SELECT "TransactionLog"."userId", + "TransactionLog"."subscriptionId", + "TransactionLog"."productId", + "TransactionLog"."customerId", + "TransactionLog"."customerEmail" + FROM public."TransactionLog" + WHERE ("TransactionLog"."eventType" = 'appsumo.activate'::text); + + +-- +-- Name: Workspace; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."Workspace" ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + name text NOT NULL, + "isDefault" boolean DEFAULT false NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL, + "userId" text NOT NULL, + "isDeleted" boolean DEFAULT false NOT NULL +); + + +-- +-- Name: WorkspaceMember; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public."WorkspaceMember" ( + "workspaceId" uuid NOT NULL, + "userId" text NOT NULL, + relation public."AuthorizationRelation" DEFAULT 'administrators'::public."AuthorizationRelation" NOT NULL, + "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL, + "removedAt" timestamp(3) with time zone +); + + +-- +-- Name: WorkspaceProjectAuthorization; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public."WorkspaceProjectAuthorization" AS + SELECT w."userId", + p.id AS "projectId", + 'own'::text AS relation + FROM (public."Workspace" w + JOIN public."Project" p ON ((p."workspaceId" = w.id))) + WHERE ((w."isDeleted" = false) AND (p."isDeleted" = false)) +UNION ALL + SELECT wm."userId", + p.id AS "projectId", + (wm.relation)::text AS relation + FROM ((public."WorkspaceMember" wm + JOIN public."Workspace" w ON ((w.id = wm."workspaceId"))) + JOIN public."Project" p ON ((p."workspaceId" = wm."workspaceId"))) + WHERE ((wm."removedAt" IS NULL) AND (w."isDeleted" = false) AND (p."isDeleted" = false)); + + +-- +-- Name: _prisma_migrations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public._prisma_migrations ( + id character varying(36) NOT NULL, + checksum character varying(64) NOT NULL, + finished_at timestamp with time zone, + migration_name character varying(255) NOT NULL, + logs text, + rolled_back_at timestamp with time zone, + started_at timestamp with time zone DEFAULT now() NOT NULL, + applied_steps_count integer DEFAULT 0 NOT NULL +); + + +-- +-- Name: published_builds; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public.published_builds AS + SELECT build.id AS "buildId", + build."projectId", + build."createdAt", + ( SELECT string_agg(list.value, ', '::text) AS string_agg + FROM jsonb_array_elements_text(((build.deployment)::jsonb -> 'domains'::text)) list(value)) AS domains + FROM public."Build" build + WHERE ((build.deployment IS NOT NULL) AND (build."isCleaned" = false)) + ORDER BY build."projectId", build."createdAt" DESC; + + +-- +-- Name: user_publish_count; Type: VIEW; Schema: public; Owner: - +-- + +CREATE VIEW public.user_publish_count AS + SELECT DISTINCT "Project"."userId" AS user_id, + count(*) AS count + FROM (public."Build" + LEFT JOIN public."Project" ON (("Project".id = "Build"."projectId"))) + WHERE ((date_trunc('day'::text, "Build"."createdAt") = date_trunc('day'::text, now())) AND ("Build".deployment IS NOT NULL)) + GROUP BY "Project"."userId"; + + +-- +-- Name: AssetFileMetadata AssetFileMetadata_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFileMetadata" + ADD CONSTRAINT "AssetFileMetadata_pkey" PRIMARY KEY ("projectId", "assetId"); + + +-- +-- Name: AssetFolder AssetFolder_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFolder" + ADD CONSTRAINT "AssetFolder_pkey" PRIMARY KEY (id, "projectId"); + + +-- +-- Name: Asset Asset_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Asset" + ADD CONSTRAINT "Asset_pkey" PRIMARY KEY (id, "projectId"); + + +-- +-- Name: AuthorizationToken AuthorizationToken_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AuthorizationToken" + ADD CONSTRAINT "AuthorizationToken_pkey" PRIMARY KEY (token, "projectId"); + + +-- +-- Name: Build Build_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Build" + ADD CONSTRAINT "Build_pkey" PRIMARY KEY (id, "projectId"); + + +-- +-- Name: ClientReferences ClientReferences_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ClientReferences" + ADD CONSTRAINT "ClientReferences_pkey" PRIMARY KEY ("userId", service); + + +-- +-- Name: Domain Domain_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Domain" + ADD CONSTRAINT "Domain_pkey" PRIMARY KEY (id); + + +-- +-- Name: File File_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."File" + ADD CONSTRAINT "File_pkey" PRIMARY KEY (name); + + +-- +-- Name: Notification Notification_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Notification" + ADD CONSTRAINT "Notification_pkey" PRIMARY KEY (id); + + +-- +-- Name: Product Product_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Product" + ADD CONSTRAINT "Product_pkey" PRIMARY KEY (id); + + +-- +-- Name: ProjectDomain ProjectDomain_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ProjectDomain" + ADD CONSTRAINT "ProjectDomain_pkey" PRIMARY KEY ("projectId", "domainId"); + + +-- +-- Name: Project Project_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_pkey" PRIMARY KEY (id); + + +-- +-- Name: TransactionLog TransactionLog_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."TransactionLog" + ADD CONSTRAINT "TransactionLog_pkey" PRIMARY KEY ("eventId"); + + +-- +-- Name: User User_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."User" + ADD CONSTRAINT "User_pkey" PRIMARY KEY (id); + + +-- +-- Name: WorkspaceMember WorkspaceMember_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."WorkspaceMember" + ADD CONSTRAINT "WorkspaceMember_pkey" PRIMARY KEY ("workspaceId", "userId"); + + +-- +-- Name: Workspace Workspace_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Workspace" + ADD CONSTRAINT "Workspace_pkey" PRIMARY KEY (id); + + +-- +-- Name: _prisma_migrations _prisma_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public._prisma_migrations + ADD CONSTRAINT _prisma_migrations_pkey PRIMARY KEY (id); + + +-- +-- Name: domainsVirtual domainsVirtual_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."domainsVirtual" + ADD CONSTRAINT "domainsVirtual_pkey" PRIMARY KEY (id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_buildId_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_buildId_key" UNIQUE ("buildId"); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_domainsVirtualId_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_domainsVirtualId_key" UNIQUE ("domainsVirtualId"); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_pkey" PRIMARY KEY ("projectId"); + + +-- +-- Name: AssetFolder_projectId_parentId_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "AssetFolder_projectId_parentId_idx" ON public."AssetFolder" USING btree ("projectId", "parentId"); + + +-- +-- Name: AssetFolder_unique_sibling_name; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "AssetFolder_unique_sibling_name" ON public."AssetFolder" USING btree ("projectId", COALESCE("parentId", ''::text), lower(btrim(name))); + + +-- +-- Name: AuthorizationToken_token_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "AuthorizationToken_token_key" ON public."AuthorizationToken" USING btree (token); + + +-- +-- Name: Build_dev_index; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Build_dev_index" ON public."Build" USING btree ("projectId") WHERE (deployment IS NULL); + + +-- +-- Name: Build_id_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Build_id_key" ON public."Build" USING btree (id); + + +-- +-- Name: Build_projectId_createdAt_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "Build_projectId_createdAt_idx" ON public."Build" USING btree ("projectId", "createdAt" DESC); + + +-- +-- Name: INDEX "Build_projectId_createdAt_idx"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON INDEX public."Build_projectId_createdAt_idx" IS 'Used to speedup ApprovedMarketplaceProduct view'; + + +-- +-- Name: ClientReferences_reference_service_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "ClientReferences_reference_service_key" ON public."ClientReferences" USING btree (reference, service); + + +-- +-- Name: Domain_domain_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Domain_domain_key" ON public."Domain" USING btree (domain); + + +-- +-- Name: File_uploaderProjectId_contentHash_extension_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "File_uploaderProjectId_contentHash_extension_key" ON public."File" USING btree ("uploaderProjectId", "contentHash", ( +CASE + WHEN ((strpos(reverse(name), '.'::text) = ANY (ARRAY[0, 1])) OR (((length(name) - strpos(reverse(name), '.'::text)) + 1) = 1)) THEN ''::text + ELSE lower(reverse(split_part(reverse(name), '.'::text, 1))) +END)) WHERE ("contentHash" IS NOT NULL); + + +-- +-- Name: Notification_recipientId_status_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "Notification_recipientId_status_idx" ON public."Notification" USING btree ("recipientId", status); + + +-- +-- Name: ProjectDomain_domainId_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "ProjectDomain_domainId_idx" ON public."ProjectDomain" USING btree ("domainId"); + + +-- +-- Name: ProjectDomain_txtRecord_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "ProjectDomain_txtRecord_key" ON public."ProjectDomain" USING btree ("txtRecord"); + + +-- +-- Name: Project_domain_isDeleted_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_domain_isDeleted_key" ON public."Project" USING btree (domain, "isDeleted"); + + +-- +-- Name: Project_domain_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_domain_key" ON public."Project" USING btree (domain); + + +-- +-- Name: Project_id_domain_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_id_domain_key" ON public."Project" USING btree (id, domain); + + +-- +-- Name: Project_id_isDeleted_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Project_id_isDeleted_key" ON public."Project" USING btree (id, "isDeleted"); + + +-- +-- Name: Project_isDeleted_marketplaceApprovalStatus_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "Project_isDeleted_marketplaceApprovalStatus_idx" ON public."Project" USING btree ("isDeleted", "marketplaceApprovalStatus"); + + +-- +-- Name: INDEX "Project_isDeleted_marketplaceApprovalStatus_idx"; Type: COMMENT; Schema: public; Owner: - +-- + +COMMENT ON INDEX public."Project_isDeleted_marketplaceApprovalStatus_idx" IS 'Used to speedup ApprovedMarketplaceProduct view'; + + +-- +-- Name: TransactionLog_eventId_productId_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "TransactionLog_eventId_productId_key" ON public."TransactionLog" USING btree ("eventId", "productId"); + + +-- +-- Name: User_email_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "User_email_key" ON public."User" USING btree (email); + + +-- +-- Name: WorkspaceMember_userId_idx; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX "WorkspaceMember_userId_idx" ON public."WorkspaceMember" USING btree ("userId"); + + +-- +-- Name: Workspace_userId_isDefault_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX "Workspace_userId_isDefault_key" ON public."Workspace" USING btree ("userId", "isDefault") WHERE ("isDefault" = true); + + +-- +-- Name: AssetFileMetadata AssetFileMetadata_assetId_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFileMetadata" + ADD CONSTRAINT "AssetFileMetadata_assetId_projectId_fkey" FOREIGN KEY ("assetId", "projectId") REFERENCES public."Asset"(id, "projectId") ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: AssetFolder AssetFolder_parentId_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFolder" + ADD CONSTRAINT "AssetFolder_parentId_projectId_fkey" FOREIGN KEY ("parentId", "projectId") REFERENCES public."AssetFolder"(id, "projectId") ON UPDATE CASCADE; + + +-- +-- Name: AssetFolder AssetFolder_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AssetFolder" + ADD CONSTRAINT "AssetFolder_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: Asset Asset_folderId_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Asset" + ADD CONSTRAINT "Asset_folderId_projectId_fkey" FOREIGN KEY ("folderId", "projectId") REFERENCES public."AssetFolder"(id, "projectId") ON UPDATE CASCADE; + + +-- +-- Name: Asset Asset_name_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Asset" + ADD CONSTRAINT "Asset_name_fkey" FOREIGN KEY (name) REFERENCES public."File"(name) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: AuthorizationToken AuthorizationToken_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."AuthorizationToken" + ADD CONSTRAINT "AuthorizationToken_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: Build Build_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Build" + ADD CONSTRAINT "Build_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: ClientReferences ClientReferences_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ClientReferences" + ADD CONSTRAINT "ClientReferences_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: File File_uploaderProjectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."File" + ADD CONSTRAINT "File_uploaderProjectId_fkey" FOREIGN KEY ("uploaderProjectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: ProjectDomain ProjectDomain_domainId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ProjectDomain" + ADD CONSTRAINT "ProjectDomain_domainId_fkey" FOREIGN KEY ("domainId") REFERENCES public."Domain"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: ProjectDomain ProjectDomain_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."ProjectDomain" + ADD CONSTRAINT "ProjectDomain_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: Project Project_previewImageAssetId_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_previewImageAssetId_id_fkey" FOREIGN KEY ("previewImageAssetId", id) REFERENCES public."Asset"(id, "projectId") ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: Project Project_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: Project Project_workspaceId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Project" + ADD CONSTRAINT "Project_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES public."Workspace"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: TransactionLog TransactionLog_productId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."TransactionLog" + ADD CONSTRAINT "TransactionLog_productId_fkey" FOREIGN KEY ("productId") REFERENCES public."Product"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: TransactionLog TransactionLog_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."TransactionLog" + ADD CONSTRAINT "TransactionLog_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE SET NULL; + + +-- +-- Name: WorkspaceMember WorkspaceMember_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."WorkspaceMember" + ADD CONSTRAINT "WorkspaceMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: WorkspaceMember WorkspaceMember_workspaceId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."WorkspaceMember" + ADD CONSTRAINT "WorkspaceMember_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES public."Workspace"(id) ON UPDATE CASCADE ON DELETE CASCADE; + + +-- +-- Name: Workspace Workspace_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."Workspace" + ADD CONSTRAINT "Workspace_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE RESTRICT; + + +-- +-- Name: domainsVirtual domainsVirtual_domainId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."domainsVirtual" + ADD CONSTRAINT "domainsVirtual_domainId_fkey" FOREIGN KEY ("domainId") REFERENCES public."Domain"(id); + + +-- +-- Name: domainsVirtual domainsVirtual_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."domainsVirtual" + ADD CONSTRAINT "domainsVirtual_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_buildId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_buildId_fkey" FOREIGN KEY ("buildId") REFERENCES public."Build"(id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_domainsVirtualId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_domainsVirtualId_fkey" FOREIGN KEY ("domainsVirtualId") REFERENCES public."domainsVirtual"(id); + + +-- +-- Name: latestBuildVirtual latestBuildVirtual_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public."latestBuildVirtual" + ADD CONSTRAINT "latestBuildVirtual_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id); + + +-- +-- PostgreSQL database dump complete +-- + +\unrestrict webstudioE2ESchema + diff --git a/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts index 8e94d8769a..183b263bcf 100644 --- a/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts +++ b/apps/builder/e2e/tests/mdx-content-block.[shard-4].e2e.ts @@ -4,6 +4,7 @@ import { configureDynamicDetailContentBlock, configureEmptyHeadingTemplate, configureNamedTemplateLifecycle, + configureNestedHeadingTemplates, configureRepresentableContentBlockBody, configureRepeatedContentBlock, } from "../fixtures/mdx-content-block-project"; @@ -46,6 +47,7 @@ const alternateFilename = "alternate-source.mdx"; const unresolvedFilename = "unresolved-source.mdx"; const namedTemplateFilename = "named-template-source.mdx"; const emptyFilename = "empty-source.mdx"; +const nestedHeadingFilename = "nested-heading-source.mdx"; const sourceHeading = "MDX source heading"; const editedHeading = "Edited MDX source heading"; @@ -180,6 +182,60 @@ const openFixture = async ({ await waitForSyncStatus({ page, status: "idle" }); }; +test("Nested MDX heading edits survive immediate Builder reload", async ({ + page, + context, +}) => { + const fixture = await createContentModeProject({ + context, + devPlan: e2ePaidPlanName, + email: "mdx-nested-heading-e2e@webstudio.test", + title: "MDX Nested Heading E2E", + }); + await configureRepresentableContentBlockBody(fixture.projectId); + await configureNestedHeadingTemplates(fixture.projectId); + await openFixture({ + page, + projectId: fixture.projectId, + authToken: fixture.builderToken, + }); + await openAssetsPanel({ page }); + await uploadAsset({ page, filename: nestedHeadingFilename }); + await selectContentBlock({ page }); + await chooseContentBlockSource({ page, filename: nestedHeadingFilename }); + await confirmContentBlockConnection({ page }); + await waitForSyncStatus({ page, status: "idle" }); + await openFixture({ + page, + projectId: fixture.projectId, + authToken: fixture.editorToken, + mode: "content", + }); + await waitForContentEditMode({ page }); + + const canvas = await waitForCanvasFrame({ page }); + const heading = canvas.locator("h3", { hasText: "perustukset" }); + await heading.waitFor({ state: "visible" }); + await page.route("**/rest/assets/*/content?*", async (route) => { + if (route.request().method() === "PUT") { + await new Promise((resolve) => setTimeout(resolve, 2_000)); + } + await route.continue(); + }); + await replaceCanvasText({ + page, + currentText: "perustukset", + text: "Edited nested heading", + waitForProjectSync: false, + }); + await waitForSyncStatus({ page, status: "idle" }); + await page.reload(); + const reopenedCanvas = await waitForCanvasFrame({ page }); + await reopenedCanvas + .locator("h3", { hasText: "Edited nested heading" }) + .waitFor(); +}); + test("Content Block MDX source lifecycle persists edits and resets to empty", async ({ page, context, diff --git a/packages/project-build/src/runtime/mdx-authored-content.test.ts b/packages/project-build/src/runtime/mdx-authored-content.test.ts index 749f31f656..391b06a14a 100644 --- a/packages/project-build/src/runtime/mdx-authored-content.test.ts +++ b/packages/project-build/src/runtime/mdx-authored-content.test.ts @@ -7,6 +7,7 @@ import { } from "@webstudio-is/content-engine/mdx"; import { elementComponent, + type Asset, type ContentBlockExternalContentIdentity, type WebstudioFragment, } from "@webstudio-is/sdk"; @@ -1964,7 +1965,102 @@ describe("MDX authored content", () => { } changedAsset.value = "other-asset"; expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow( - 'Asset prop "src" cannot be represented losslessly in MDX' + "Changes to assets cannot be represented losslessly in MDX" + ); + }); + + test("compares existing Asset records by their fields", async () => { + const article: Asset = { + id: "article", + projectId: "project", + name: "article.md", + type: "file", + format: "md", + size: 7, + createdAt: "2026-01-01T00:00:00.000Z", + description: null, + meta: {}, + }; + const root = materializeMdxAuthoredContent({ + identity, + document: await parseMdxDocument({ source: "Before" }), + templateMaterialization: emptyTemplates, + }); + root.fragment.assets.push(article); + const next = structuredClone(root.fragment); + next.assets[0] = Object.assign(Object.create(null), article); + next.assets[0]!.meta = Object.create(null); + next.instances[0]!.children = [{ type: "text", value: "After" }]; + + expect( + serializeMdxDocument( + reconcileMdxAuthoredContent({ root, fragment: next }) + ) + ).toBe("After\n"); + }); + + test("preserves template image assets while editing MDX text", async () => { + const templateImage: Asset = { + id: "template-image", + projectId: "project", + name: "template-image.png", + type: "image", + format: "png", + size: 100, + createdAt: "2026-01-01T00:00:00.000Z", + description: null, + meta: { width: 100, height: 100 }, + }; + const root = materializeMdxAuthoredContent({ + identity, + document: await parseMdxDocument({ + source: 'Before', + }), + templateMaterialization: emptyTemplates, + assetReferenceValues: new Map([ + [templateImage.id, "./template-image.png"], + ]), + }); + const heading = root.fragment.instances[0]; + if (heading === undefined) { + throw new Error("Expected an authored heading"); + } + root.fragment.breakpoints.push({ id: "base", label: "Base" }); + root.fragment.styleSources.push({ type: "local", id: "template-style" }); + root.fragment.styleSourceSelections.push({ + instanceId: heading.id, + values: ["template-style"], + }); + root.fragment.styles.push({ + styleSourceId: "template-style", + breakpointId: "base", + property: "backgroundImage", + value: { + type: "image", + value: { type: "asset", value: templateImage.id }, + }, + }); + + const next = structuredClone(root.fragment); + next.props.push({ + id: "template-image-prop", + instanceId: heading.id, + name: "src", + type: "asset", + value: templateImage.id, + }); + next.instances[0]!.children = [{ type: "text", value: "After" }]; + + expect( + serializeMdxDocument( + reconcileMdxAuthoredContent({ root, fragment: next }) + ) + ).toBe('

After

\n'); + + next.assets.push({ ...templateImage, id: "unknown-image" }); + next.props[0]!.value = "unknown-image"; + expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow( + "Changes to assets cannot be represented losslessly in MDX" ); }); diff --git a/packages/project-build/src/runtime/mdx-authored-content.ts b/packages/project-build/src/runtime/mdx-authored-content.ts index 4a7b084a95..9ebcb90aaf 100644 --- a/packages/project-build/src/runtime/mdx-authored-content.ts +++ b/packages/project-build/src/runtime/mdx-authored-content.ts @@ -1865,10 +1865,25 @@ const assertSupportedNamespaces = ({ deletedTemplateRootIds: ReadonlySet; }) => { for (const namespace of unsupportedNamespaces) { - if (namespace === "assets" && root.assetReferenceValues !== undefined) { + if (namespace === "assets") { const originalById = new Map( root.fragment.assets.map((asset) => [asset.id, asset]) ); + const authoredAssetPropIds = new Set( + root.provenance.nodes.flatMap((node) => + node.type === "template" + ? [ + ...node.assetProps.map(({ assetId }) => assetId), + ...node.overlaidDescendants.flatMap((descendant) => + descendant.assetProps.map(({ assetId }) => assetId) + ), + ] + : node.assetProps.map(({ assetId }) => assetId) + ) + ); + const isKnownAsset = (assetId: string) => + root.assetReferenceValues?.has(assetId) === true || + authoredAssetPropIds.has(assetId); const referencedAssetIds = new Set( fragment.props.flatMap((prop) => prop.type === "asset" ? [prop.value] : [] @@ -1877,12 +1892,15 @@ const assertSupportedNamespaces = ({ const assetIds = new Set(); for (const asset of fragment.assets) { const original = originalById.get(asset.id); + // Template assets can be referenced by styles or data sources too. if ( assetIds.has(asset.id) || (original === undefined - ? referencedAssetIds.has(asset.id) === false || - root.assetReferenceValues.has(asset.id) === false - : equal(original, asset) === false) + ? isKnownAsset(asset.id) === false + : equal( + JSON.parse(JSON.stringify(original)), + JSON.parse(JSON.stringify(asset)) + ) === false) ) { throw new Error( "Changes to assets cannot be represented losslessly in MDX" @@ -1892,7 +1910,8 @@ const assertSupportedNamespaces = ({ } if ( Array.from(referencedAssetIds).some( - (assetId) => assetIds.has(assetId) === false + (assetId) => + assetIds.has(assetId) === false && isKnownAsset(assetId) === false ) ) { throw new Error(