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
fix: content mode permissions (#5795)
Oleg Isonen392c9089beff
diff --git a/.github/workflows/main.yml b/.github/workflows/main.ymlindex fab7186d90..a4375c8219 100644--- a/.github/workflows/main.yml+++ b/.github/workflows/main.yml@@ -23,7 +23,7 @@ jobs:github.event_name == 'push' ||github.event_name == 'pull_request' ||(github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy')-+timeout-minutes: 20strategy:@@ -156,3 +156,76 @@ jobs:console.error('Some fixtures exceeded limits')process.exit(1)}++ builder-e2e:+ # Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks)+ if: |+ github.event_name == 'push' ||+ github.event_name == 'pull_request' ||+ (github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy')++ timeout-minutes: 40++ runs-on: ubuntu-24.04++ environment:+ name: development++ env:+ AUTH_SECRET: test+ DATABASE_URL: postgresql://user:pass@localhost:55432/webstudio+ DIRECT_URL: postgresql://user:pass@localhost:55432/webstudio+ E2E_PGPORT: 55432+ E2E_POSTGREST_PORT: 55433+ POSTGREST_API_KEY: ""+ POSTGREST_URL: http://127.0.0.1:55433+ TRPC_SERVER_API_TOKEN: e2e-service-token++ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ github.event.pull_request.head.sha || github.sha }}++ - uses: ./.github/actions/submodules-checkout+ with:+ submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}++ - uses: pnpm/action-setup@v4++ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm++ - name: Pnpm install+ run: pnpm install++ - name: Cache Playwright browsers+ uses: actions/cache@v4+ with:+ path: ~/.cache/ms-playwright+ key: builder-e2e-playwright-${{ runner.os }}-${{ hashFiles('apps/builder/package.json', 'pnpm-lock.yaml') }}++ - name: Run builder e2e+ run: |+ set +e+ E2E_SKIP_CLEANUP=true E2E_TEST_COMMAND_TIMEOUT_SECONDS=900 pnpm e2e:builder+ status="$?"+ set -e+ if [ "$status" -eq 0 ]; then+ exit 0+ fi++ echo "::warning::Builder e2e failed on the first attempt. Restarting services and retrying once."+ docker compose -f apps/builder/docker-compose.e2e.yaml logs || true+ docker compose -f apps/builder/docker-compose.e2e.yaml down --volumes --remove-orphans || true++ E2E_SKIP_CLEANUP=true E2E_TEST_COMMAND_TIMEOUT_SECONDS=900 pnpm e2e:builder++ - name: Print e2e service logs+ if: failure()+ run: docker compose -f apps/builder/docker-compose.e2e.yaml logs++ - name: Stop e2e services+ if: always()+ run: docker compose -f apps/builder/docker-compose.e2e.yaml down --volumes --remove-orphansdiff --git a/apps/builder/app/builder/features/pages/page-context-menu.tsx b/apps/builder/app/builder/features/pages/page-context-menu.tsxindex 87ffadf33c..1a4dbc73fb 100644--- a/apps/builder/app/builder/features/pages/page-context-menu.tsx+++ b/apps/builder/app/builder/features/pages/page-context-menu.tsx@@ -14,18 +14,24 @@ import { selectPage } from "~/shared/nano-states";type PageContextMenuProps = {children: ReactNode;+ canManagePages: boolean;onRequestDeletePage: (pageId: string) => void;onRequestDeleteFolder: (folderId: string) => void;};export const PageContextMenu = ({children,+ canManagePages,onRequestDeletePage,onRequestDeleteFolder,}: PageContextMenuProps) => {const [pageId, setPageId] = useState<string | undefined>();const [folderId, setFolderId] = useState<string | undefined>();+ if (canManagePages === false) {+ return <>{children}</>;+ }+const handleDuplicate = () => {if (pageId) {duplicatePage(pageId);@@ -93,15 +99,21 @@ export const PageContextMenu = ({type TemplateContextMenuProps = {children: ReactNode;+ canManageTemplates: boolean;onRequestDeleteTemplate: (templateId: string) => void;};export const TemplateContextMenu = ({children,+ canManageTemplates,onRequestDeleteTemplate,}: TemplateContextMenuProps) => {const [templateId, setTemplateId] = useState<string | undefined>();+ if (canManageTemplates === false) {+ return <>{children}</>;+ }+const handleDuplicate = () => {if (templateId) {const newTemplateId = duplicateTemplate(templateId);diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.tsindex 4ae0d2b83c..8f6400538b 100644--- a/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts@@ -23,9 +23,12 @@ vi.mock("../page-utils", () => ({const { __testing__ } = await import("./page-settings");const {+ addContentModePathError,+ canEditPagePathInMode,computePagePath,fieldDefaultValues,getAuthFromValues,+ getInitialPageMeta,toFormValues,validateValues,} = __testing__;@@ -125,6 +128,82 @@ describe("computePagePath", () => {});});+describe("canEditPagePathInMode", () => {+ test("allows design mode to edit every page path", () => {+ expect(+ canEditPagePathInMode({+ isDesignMode: true,+ isContentMode: false,+ path: "/posts/:slug",+ })+ ).toBe(true);+ });++ test("allows content mode to edit only literal paths", () => {+ expect(+ canEditPagePathInMode({+ isDesignMode: false,+ isContentMode: true,+ path: "/about",+ })+ ).toBe(true);+ expect(+ canEditPagePathInMode({+ isDesignMode: false,+ isContentMode: true,+ path: "/posts/:slug",+ })+ ).toBe(false);+ expect(+ canEditPagePathInMode({+ isDesignMode: false,+ isContentMode: true,+ path: "/docs/*",+ })+ ).toBe(false);+ });++ test("disallows path edits outside design and content modes", () => {+ expect(+ canEditPagePathInMode({+ isDesignMode: false,+ isContentMode: false,+ path: "/about",+ })+ ).toBe(false);+ });+});++describe("addContentModePathError", () => {+ test("adds an error only for non-static content-mode paths", () => {+ const errors = {};+ addContentModePathError({+ errors,+ isContentMode: true,+ path: "/posts/:slug",+ });+ expect(errors).toEqual({+ path: ["Editors can only set static page paths"],+ });++ const staticErrors = {};+ addContentModePathError({+ errors: staticErrors,+ isContentMode: true,+ path: "/about",+ });+ expect(staticErrors).toEqual({});++ const designErrors = {};+ addContentModePathError({+ errors: designErrors,+ isContentMode: false,+ path: "/posts/:slug",+ });+ expect(designErrors).toEqual({});+ });+});+describe("validateValues", () => {test("accumulates duplicate path errors from the general section", () => {mocks.isPathAvailable.mockReturnValueOnce(false);@@ -239,6 +318,26 @@ describe("auth form values", () => {).toBeUndefined();});+ test("omits auth key from initial page meta when auth is empty", () => {+ expect(getInitialPageMeta(createValues())).toEqual({});+ expect(+ getInitialPageMeta(+ createValues({+ auth: {+ login: "admin",+ password: "secret",+ },+ })+ )+ ).toEqual({+ auth: {+ method: "basic",+ login: "admin",+ password: "secret",+ },+ });+ });+test("maps page auth metadata into form values", () => {const page = createPage({id: "private",diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsxindex f53f0db360..a9271121c0 100644--- a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx@@ -51,7 +51,7 @@ import {import { CollapsibleSection } from "~/builder/shared/collapsible-section";import { Form } from "../form";import { findMatchingRedirect } from "~/shared/project-settings/utils";-import { isPathnamePattern } from "~/builder/shared/url-pattern";+import { isContentModePagePath } from "@webstudio-is/project/content-mode-permissions";import { AuthSection, validateAuthSection } from "./section-auth";import {CustomMetadataSection,@@ -219,22 +219,53 @@ const getAuthFromValues = (values: Values): Page["meta"]["auth"] => {};};+const getInitialPageMeta = (values: Values): Page["meta"] => {+ const meta: Page["meta"] = {};+ const auth = getAuthFromValues(values);+ if (auth !== undefined) {+ meta.auth = auth;+ }+ return meta;+};++export const canEditPagePathInMode = ({+ isDesignMode,+ isContentMode,+ path,+}: {+ isDesignMode: boolean;+ isContentMode: boolean;+ path: string;+}) => {+ return isDesignMode || (isContentMode && isContentModePagePath(path));+};++export const addContentModePathError = ({+ errors,+ isContentMode,+ path,+}: {+ errors: Errors;+ isContentMode: boolean;+ path: string;+}) => {+ if (isContentMode && isContentModePagePath(path) === false) {+ errors.path = errors.path ?? [];+ errors.path.push("Editors can only set static page paths");+ }+};+export const __testing__ = {+ addContentModePathError,computePagePath,+ canEditPagePathInMode,fieldDefaultValues,getAuthFromValues,+ getInitialPageMeta,toFormValues,validateValues,};-export const isEditorEditablePagePath = (path: string) => {- return (- isPathnamePattern(path) === false &&- path.includes(":") === false &&- path.includes("*") === false- );-};-export const FormFields = ({autoSelect,errors,@@ -247,12 +278,12 @@ export const FormFields = ({canEditPath = true,showHomePageControl = true,showPathField = true,- showStatusField = true,- showRedirectField = true,- showDocumentTypeField = true,+ showStatusField = isEditorContext === false,+ showRedirectField = isEditorContext === false,+ showDocumentTypeField = isEditorContext === false,showRedirectWarning = showPathField,showAuthSection = isEditorContext === false,- showTextContentSection = true,+ showTextContentSection = isEditorContext === false,showMarketplaceSection = isEditorContext === false,}: {autoSelect?: boolean;@@ -520,9 +551,7 @@ const createPage = (pageId: Page["id"], values: Values) => {path: values.path,title: values.title,rootInstanceId,- meta: {- auth: getAuthFromValues(values),- },+ meta: getInitialPageMeta(values),});instances.set(rootInstanceId, {type: "instance",@@ -676,6 +705,7 @@ export const PageSettings = ({const pages = useStore($pages);const page = pages && findPageByIdOrPath(pageId, pages);const isDesignMode = useStore($isDesignMode);+ const isContentMode = useStore($isContentMode);const isHomePage = page?.id === pages?.homePageId;@@ -713,6 +743,13 @@ export const PageSettings = ({const { variableValues } = useStore($pageRootScope);errors = validateValues(pages, pageId, values, variableValues);+ if (unsavedValues.path !== undefined) {+ addContentModePathError({+ errors,+ isContentMode,+ path: unsavedValues.path,+ });+ }useEffect(() => {// we can't flush immediately as setState haven't propagated at that time@@ -754,8 +791,12 @@ export const PageSettings = ({errors={errors}values={values}isEditorContext={isDesignMode === false}- canEditName={isDesignMode}- canEditPath={isDesignMode}+ canEditName={isDesignMode || isContentMode}+ canEditPath={canEditPagePathInMode({+ isDesignMode,+ isContentMode,+ path: page.path,+ })}onChange={handleChange}/></PageSettingsView>diff --git a/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsxindex c92d069ad0..bec9b4fdfa 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx@@ -43,7 +43,7 @@ export const CustomMetadataSection = ({}) => {return (<InputErrorsTooltip errors={errors.customMetas}>- <div>+ <div role="group" aria-label="Custom metadata"><CustomMetadatacustomMetas={values.customMetas}disabled={disabled}diff --git a/apps/builder/app/builder/features/pages/page-utils.test.ts b/apps/builder/app/builder/features/pages/page-utils.test.tsindex 46e4482b07..87cd7ec8ea 100644--- a/apps/builder/app/builder/features/pages/page-utils.test.ts+++ b/apps/builder/app/builder/features/pages/page-utils.test.ts@@ -25,6 +25,7 @@ import {isPathAvailable,reparentPageOrFolderMutable,deletePageMutable,+ instantiateTemplate,} from "./page-utils";import { $dataSourceVariables } from "~/shared/nano-states";import {@@ -1215,3 +1216,91 @@ describe("duplicateTemplate", () => {});});});++describe("instantiateTemplate", () => {+ $project.set({ id: "projectId" } as Project);++ test("uses content-safe copy when creating page from template in content mode", () => {+ const { pages: pagesData } = createPages();+ pagesData.pageTemplates = new Map([+ [+ "templateId",+ {+ id: "templateId",+ name: "Template",+ title: `"Template title"`,+ rootInstanceId: "templateRootId",+ meta: {+ description: `"Description"`,+ excludePageFromSearch: "false",+ language: `"en-US"`,+ socialImageAssetId: "assetId",+ socialImageUrl: `"https://example.com/image.png"`,+ custom: [{ property: "og:type", content: `"website"` }],+ auth: { method: "basic", login: "user", password: "password" },+ content: `"text"`,+ documentType: "text",+ redirect: `"/redirect"`,+ status: "404",+ },+ },+ ],+ ]);++ $pages.set(pagesData);+ $instances.set(+ new Map([+ [+ "rootInstanceId",+ {+ type: "instance",+ id: "rootInstanceId",+ component: "Body",+ children: [],+ },+ ],+ [+ "templateRootId",+ {+ type: "instance",+ id: "templateRootId",+ component: "Body",+ children: [],+ },+ ],+ ])+ );+ $props.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $breakpoints.set(new Map());+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $styles.set(new Map());+ $assets.set(new Map());++ const pageId = instantiateTemplate({+ templateId: "templateId",+ overrides: { name: "New page", path: "/new-page" },+ folderId: pagesData.rootFolderId,+ contentMode: true,+ });++ const page = $pages.get()?.pages.get(pageId ?? "");+ expect(page).toEqual({+ id: pageId,+ name: "New page",+ path: "/new-page",+ title: `"Template title"`,+ rootInstanceId: expect.not.stringMatching("templateRootId"),+ meta: {+ description: `"Description"`,+ excludePageFromSearch: "false",+ language: `"en-US"`,+ socialImageAssetId: "assetId",+ socialImageUrl: `"https://example.com/image.png"`,+ custom: [{ property: "og:type", content: `"website"` }],+ },+ });+ });+});diff --git a/apps/builder/app/builder/features/pages/page-utils.ts b/apps/builder/app/builder/features/pages/page-utils.tsindex 08fd9be075..351b04835b 100644--- a/apps/builder/app/builder/features/pages/page-utils.ts+++ b/apps/builder/app/builder/features/pages/page-utils.ts@@ -30,8 +30,8 @@ import {copyAndTransformPageMeta,insertPageCopyMutable,insertPageFromTemplateMutable,- replaceDataSourcesInExpression,} from "~/shared/page-utils";+import { replaceDataSourcesInExpression } from "~/shared/data-variables";import {$selectedPage,getInstanceKey,@@ -616,10 +616,12 @@ export const instantiateTemplate = ({templateId,overrides,folderId,+ contentMode,}: {templateId: PageTemplate["id"];overrides: { name: string; path: string };folderId: Folder["id"];+ contentMode?: boolean;}) => {let newPageId: undefined | string;updateWebstudioData((data) => {@@ -628,6 +630,7 @@ export const instantiateTemplate = ({source: { data },target: { data, folderId },overrides,+ contentMode,});});return newPageId;diff --git a/apps/builder/app/builder/features/pages/pages.test.ts b/apps/builder/app/builder/features/pages/pages.test.tsnew file mode 100644index 0000000000..963e92fe2a--- /dev/null+++ b/apps/builder/app/builder/features/pages/pages.test.ts@@ -0,0 +1,88 @@+import { describe, expect, test } from "vitest";+import { __testing__ } from "./pages";++const { canEditPagesPanelItemSettings, canEditPagesTreeItemSettings } =+ __testing__;++describe("canEditPagesTreeItemSettings", () => {+ test("allows page settings when page settings are editable", () => {+ expect(+ canEditPagesTreeItemSettings({+ itemType: "page",+ canManagePages: false,+ canEditPageSettings: true,+ })+ ).toBe(true);+ });++ test("keeps folder settings design-only", () => {+ expect(+ canEditPagesTreeItemSettings({+ itemType: "folder",+ canManagePages: false,+ canEditPageSettings: true,+ })+ ).toBe(false);+ expect(+ canEditPagesTreeItemSettings({+ itemType: "folder",+ canManagePages: true,+ canEditPageSettings: false,+ })+ ).toBe(true);+ });++ test("hides page settings when page settings are not editable", () => {+ expect(+ canEditPagesTreeItemSettings({+ itemType: "page",+ canManagePages: true,+ canEditPageSettings: false,+ })+ ).toBe(false);+ });+});++describe("canEditPagesPanelItemSettings", () => {+ const folders = new Map([+ [+ "folder-id",+ {+ id: "folder-id",+ name: "Folder",+ slug: "folder",+ children: [],+ },+ ],+ ]);++ test("keeps open folder settings design-only", () => {+ expect(+ canEditPagesPanelItemSettings({+ itemId: "folder-id",+ folders,+ canManagePages: false,+ canEditPageSettings: true,+ })+ ).toBe(false);+ expect(+ canEditPagesPanelItemSettings({+ itemId: "folder-id",+ folders,+ canManagePages: true,+ canEditPageSettings: false,+ })+ ).toBe(true);+ });++ test("allows open page settings when page settings are editable", () => {+ expect(+ canEditPagesPanelItemSettings({+ itemId: "page-id",+ folders,+ canManagePages: false,+ canEditPageSettings: true,+ })+ ).toBe(true);+ });+});diff --git a/apps/builder/app/builder/features/pages/pages.tsx b/apps/builder/app/builder/features/pages/pages.tsxindex 1767f2f035..5b7f06a54e 100644--- a/apps/builder/app/builder/features/pages/pages.tsx+++ b/apps/builder/app/builder/features/pages/pages.tsx@@ -90,26 +90,17 @@ const ItemSuffix = ({editingItemId,onEdit,type,+ canEdit,}: {itemId: string;editingItemId: string | undefined;onEdit: (itemId: string | undefined) => void;type: "folder" | "page";+ canEdit: boolean;}) => {- const isEditing = editingItemId === itemId;-- const menuLabel =- type === "page"- ? isEditing- ? "Close page settings"- : "Open page settings"- : isEditing- ? "Close folder settings"- : "Open folder settings";-const buttonRef = useRef<HTMLButtonElement | null>(null);-const prevEditingItemId = useRef(editingItemId);+useEffect(() => {// when settings panel close, move focus back to the menu buttonif (@@ -122,6 +113,21 @@ const ItemSuffix = ({prevEditingItemId.current = editingItemId;}, [editingItemId, itemId]);+ if (canEdit === false) {+ return;+ }++ const isEditing = editingItemId === itemId;++ const menuLabel =+ type === "page"+ ? isEditing+ ? "Close page settings"+ : "Open page settings"+ : isEditing+ ? "Close folder settings"+ : "Open folder settings";+return (<Tooltip content={menuLabel} disableHoverableContent><SmallIconButton@@ -277,11 +283,15 @@ const PagesTree = ({selectedPageId,onEdit,editingItemId,+ canManagePages,+ canEditPageSettings,}: {onSelect: (pageId: string) => void;selectedPageId: string;onEdit: (pageId: string | undefined) => void;editingItemId?: string;+ canManagePages: boolean;+ canEditPageSettings: boolean;}) => {const pages = useStore($pages);const flatPagesTree = useStore($flatPagesTree);@@ -373,6 +383,13 @@ const PagesTree = ({isHighlighted={dropTarget?.parentId === item.id}isExpanded={item.isExpanded}onExpand={handleExpand}+ nodeProps={{+ role: "group",+ "aria-label":+ item.type === "page"+ ? `Page ${item.page.name}`+ : `Folder ${item.folder.name}`,+ }}buttonProps={{onClick: (event) => {if (item.type === "folder") {@@ -397,6 +414,11 @@ const PagesTree = ({itemId={item.id}editingItemId={editingItemId}onEdit={onEdit}+ canEdit={canEditPagesTreeItemSettings({+ itemType: item.type,+ canManagePages,+ canEditPageSettings,+ })}/>}>@@ -432,6 +454,42 @@ const PagesTree = ({const newPageId = "new-page";const newTemplateId = "new-template";+const canEditPagesTreeItemSettings = ({+ itemType,+ canManagePages,+ canEditPageSettings,+}: {+ itemType: PagesTreeItem["type"];+ canManagePages: boolean;+ canEditPageSettings: boolean;+}) => {+ return itemType === "page" ? canEditPageSettings : canManagePages;+};++const canEditPagesPanelItemSettings = ({+ itemId,+ folders,+ canManagePages,+ canEditPageSettings,+}: {+ itemId: string;+ folders: Map<Folder["id"], Folder>;+ canManagePages: boolean;+ canEditPageSettings: boolean;+}) => {+ return canEditPagesTreeItemSettings({+ itemType:+ itemId === newFolderId || isFolder(itemId, folders) ? "folder" : "page",+ canManagePages,+ canEditPageSettings,+ });+};++export const __testing__ = {+ canEditPagesPanelItemSettings,+ canEditPagesTreeItemSettings,+};+const CreateItemMenu = ({editingItemId,editingTemplateItemId,@@ -891,7 +949,7 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {const isContentMode = useStore($isContentMode);const authPermit = useStore($authPermit);const canOpenPageTemplates = useStore($canOpenPageTemplates);- const canCreatePageFromTemplate =+ const canEditPageContent =isDesignMode || (isContentMode && authPermit !== "view");const [containerElement, setContainerElement] =useState<HTMLDivElement | null>(null);@@ -973,6 +1031,14 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {? undefined: pages.pageTemplates?.get(templateIdToDelete);const hasPageTemplates = (pages.pageTemplates?.size ?? 0) > 0;+ const canEditSettingsPanel =+ editingItemId !== undefined &&+ canEditPagesPanelItemSettings({+ itemId: editingItemId,+ folders: pages.folders,+ canManagePages: isDesignMode,+ canEditPageSettings: canEditPageContent,+ });return (<div@@ -1000,6 +1066,7 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {<Separator /><PageContextMenu+ canManagePages={isDesignMode}onRequestDeletePage={setPageIdToDelete}onRequestDeleteFolder={setFolderIdToDelete}>@@ -1011,7 +1078,20 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {onClose();}}editingItemId={editingItemId}+ canManagePages={isDesignMode}+ canEditPageSettings={canEditPageContent}onEdit={(itemId) => {+ if (+ itemId &&+ canEditPagesPanelItemSettings({+ itemId,+ folders: pages.folders,+ canManagePages: isDesignMode,+ canEditPageSettings: canEditPageContent,+ }) === false+ ) {+ return;+ }// always select page when edit its settingsif (itemId && isFolder(itemId, pages.folders) === false) {selectPage(itemId);@@ -1022,12 +1102,13 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {</div></PageContextMenu>- {(isDesignMode || isContentMode) && hasPageTemplates && (+ {canEditPageContent && hasPageTemplates && (<><Separator /><PanelTitle>Page templates</PanelTitle>{canOpenPageTemplates ? (<TemplateContextMenu+ canManageTemplates={isDesignMode}onRequestDeleteTemplate={setTemplateIdToDelete}><ScrollAreaNative@@ -1052,9 +1133,9 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {onCreatePageFromTemplate={(id) => {$creatingPageFromTemplateId.set(id);}}- canManageTemplates={true}+ canManageTemplates={isDesignMode}canSelectTemplate={true}- canCreatePageFromTemplate={canCreatePageFromTemplate}+ canCreatePageFromTemplate={canEditPageContent}/></ScrollAreaNative></TemplateContextMenu>@@ -1076,14 +1157,14 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {}}canManageTemplates={false}canSelectTemplate={false}- canCreatePageFromTemplate={canCreatePageFromTemplate}+ canCreatePageFromTemplate={canEditPageContent}/></ScrollAreaNative>)}</>)}- {editingItemId !== undefined && (+ {canEditSettingsPanel && (<FloatingPanelcontent={editingItemId === newFolderId ||@@ -1123,28 +1204,30 @@ export const PagesPanel = ({ onClose }: { onClose: () => void }) => {</FloatingPanel>)}- {canOpenPageTemplates && editingTemplateItemId !== undefined && (- <FloatingPanel- content={- <TemplateEditor- editingTemplateId={editingTemplateItemId}- onClose={() => $editingTemplateId.set(undefined)}- />- }- placement="right-start"- width={Number.parseFloat(rawTheme.spacing[35])}- open={true}- onOpenChange={(isOpen) => {- if (!isOpen) {- $editingTemplateId.set(undefined);+ {isDesignMode &&+ canOpenPageTemplates &&+ editingTemplateItemId !== undefined && (+ <FloatingPanel+ content={+ <TemplateEditor+ editingTemplateId={editingTemplateItemId}+ onClose={() => $editingTemplateId.set(undefined)}+ />}- }}- >- <span style={{ display: "none" }} />- </FloatingPanel>- )}+ placement="right-start"+ width={Number.parseFloat(rawTheme.spacing[35])}+ open={true}+ onOpenChange={(isOpen) => {+ if (!isOpen) {+ $editingTemplateId.set(undefined);+ }+ }}+ >+ <span style={{ display: "none" }} />+ </FloatingPanel>+ )}- {canCreatePageFromTemplate && creatingFromTemplateId !== undefined && (+ {canEditPageContent && creatingFromTemplateId !== undefined && (<FloatingPanelcontent={<CreatePageFromTemplateSettingsdiff --git a/apps/builder/app/builder/features/pages/social-preview.tsx b/apps/builder/app/builder/features/pages/social-preview.tsxindex 8c2c14169d..b9029973a7 100644--- a/apps/builder/app/builder/features/pages/social-preview.tsx+++ b/apps/builder/app/builder/features/pages/social-preview.tsx@@ -44,6 +44,7 @@ export const SocialPreview = ({}}><Image+ alt="Social sharing preview image"src={ogImageUrl}loader={wsImageLoader}className={imgStyle({diff --git a/apps/builder/app/builder/features/pages/template-settings.test.ts b/apps/builder/app/builder/features/pages/template-settings.test.tsindex e0335bfd71..756337dd3d 100644--- a/apps/builder/app/builder/features/pages/template-settings.test.ts+++ b/apps/builder/app/builder/features/pages/template-settings.test.ts@@ -11,7 +11,7 @@ const createValues = (values: Partial<Values>): Values => ({describe("template settings", () => {test("filters content mode page creation values without dropping custom metadata", () => {const initialValues = createValues({- path: "template",+ path: "/template",title: "boundTitle",description: `"Template description"`,excludePageFromSearch: "boundExclude",@@ -21,7 +21,7 @@ describe("template settings", () => {customMetas: [{ property: "og:type", content: "boundType" }],});const values = createValues({- path: "edited",+ path: "/edited",name: "Edited",title: `"Edited title"`,description: `"Edited description"`,@@ -36,10 +36,22 @@ describe("template settings", () => {__testing__.getEditorCreatePageValues(initialValues, values)).toEqual({name: "Edited",- path: "edited",+ path: "/edited",description: `"Edited description"`,language: `"fr-FR"`,customMetas: [{ property: "og:type", content: `"article"` }],});});++ test("does not allow editor page path override when initial path is invalid", () => {+ const editorValues = __testing__.getEditorCreatePageValues(+ createValues({ path: "template" }),+ createValues({ path: "/edited" })+ );+ expect(editorValues.path).toBeUndefined();+ expect(editorValues).toMatchObject({+ name: "Untitled",+ customMetas: [{ property: "", content: `""` }],+ });+ });});diff --git a/apps/builder/app/builder/features/pages/template-settings.tsx b/apps/builder/app/builder/features/pages/template-settings.tsxindex 5006f1b464..da35550e36 100644--- a/apps/builder/app/builder/features/pages/template-settings.tsx+++ b/apps/builder/app/builder/features/pages/template-settings.tsx@@ -20,6 +20,7 @@ import {import { CopyIcon, TrashIcon } from "@webstudio-is/icons";import { $isContentMode, $isDesignMode } from "~/shared/nano-states";import { $instances, $pages } from "~/shared/sync/data-stores";+import { isContentModePagePath } from "@webstudio-is/project/content-mode-permissions";import { serverSyncStore } from "~/shared/sync/sync-stores";import { selectInstance } from "~/shared/nano-states";import {@@ -30,7 +31,8 @@ import {} from "./page-utils";import {fieldDefaultValues,- isEditorEditablePagePath,+ canEditPagePathInMode,+ addContentModePathError,validateValues,updatePage,FormFields,@@ -388,7 +390,7 @@ const getEditorCreatePageValues = (name: values.name,};- if (isEditorEditablePagePath(initialValues.path)) {+ if (isContentModePagePath(initialValues.path)) {allowedValues.path = values.path;}if (isLiteralExpression(initialValues.title)) {@@ -425,6 +427,7 @@ export const CreatePageFromTemplateSettings = ({}) => {const pages = useStore($pages);const isContentMode = useStore($isContentMode);+ const isDesignMode = useStore($isDesignMode);const template = pages?.pageTemplates?.get(templateId);const { variableValues } = useStore($pageRootScope);@@ -439,6 +442,7 @@ export const CreatePageFromTemplateSettings = ({const [values, setValues] = useState<Values>(initialValues);const errors = validateValues(pages, undefined, values, variableValues);+ addContentModePathError({ errors, isContentMode, path: values.path });const handleSubmit = () => {if (Object.keys(errors).length === 0) {@@ -446,6 +450,7 @@ export const CreatePageFromTemplateSettings = ({templateId,overrides: { name: values.name, path: values.path },folderId: values.parentFolderId,+ contentMode: isContentMode,});if (newPageId) {updatePage(@@ -483,10 +488,11 @@ export const CreatePageFromTemplateSettings = ({values={values}isEditorContext={isContentMode}canEditName- canEditPath={- isContentMode === false ||- isEditorEditablePagePath(initialValues.path)- }+ canEditPath={canEditPagePathInMode({+ isDesignMode,+ isContentMode,+ path: initialValues.path,+ })}onChange={(change) => {setValues((prev) => {const next = { ...prev, [change.field]: change.value };diff --git a/apps/builder/app/builder/features/settings-panel/property-label.test.ts b/apps/builder/app/builder/features/settings-panel/property-label.test.tsnew file mode 100644index 0000000000..fb86f7d0f1--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/property-label.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from "vitest";+import type { Prop } from "@webstudio-is/sdk";+import { __testing__ } from "./property-label";++const { getPropIdsToDelete } = __testing__;++const prop = (name: string): Prop => ({+ id: `${name}-id`,+ instanceId: "image-id",+ name,+ type: "string",+ value: "",+});++describe("getPropIdsToDelete", () => {+ const imageProps = new Map<Prop["name"], Prop>([+ ["src", prop("src")],+ ["width", prop("width")],+ ["height", prop("height")],+ ]);++ test("deletes related image dimensions with src", () => {+ expect(+ getPropIdsToDelete({+ instanceComponent: "Image",+ instanceProps: imageProps,+ propName: "src",+ })+ ).toEqual(new Set(["src-id", "width-id", "height-id"]));+ });++ test("deletes only the requested prop for non-image components", () => {+ expect(+ getPropIdsToDelete({+ instanceComponent: "Box",+ instanceProps: imageProps,+ propName: "src",+ })+ ).toEqual(new Set(["src-id"]));+ });+});diff --git a/apps/builder/app/builder/features/settings-panel/property-label.tsx b/apps/builder/app/builder/features/settings-panel/property-label.tsxindex c950ab965f..8a5b9dda9e 100644--- a/apps/builder/app/builder/features/settings-panel/property-label.tsx+++ b/apps/builder/app/builder/features/settings-panel/property-label.tsx@@ -65,27 +65,52 @@ const useProp = (name: string) => {return useStore(store);};+const getPropIdsToDelete = ({+ instanceComponent,+ instanceProps,+ propName,+}: {+ instanceComponent: string | undefined;+ instanceProps: Map<Prop["name"], Prop>;+ propName: Prop["name"];+}) => {+ const propIds = new Set<Prop["id"]>();+ const prop = instanceProps.get(propName);+ if (prop) {+ propIds.add(prop.id);+ }+ if (instanceComponent === "Image" && propName === "src") {+ const widthProp = instanceProps.get("width");+ if (widthProp) {+ propIds.add(widthProp.id);+ }+ const heightProp = instanceProps.get("height");+ if (heightProp) {+ propIds.add(heightProp.id);+ }+ }+ return propIds;+};++export const __testing__ = {+ getPropIdsToDelete,+};+const deleteProp = (name: string) => {const instance = $selectedInstance.get();const instanceProps = $selectedInstanceProps.get();updateWebstudioData((data) => {const prop = instanceProps.get(name);- if (prop) {- data.props.delete(prop.id);+ for (const propId of getPropIdsToDelete({+ instanceComponent: instance?.component,+ instanceProps,+ propName: name,+ })) {+ data.props.delete(propId);}if (prop?.type === "resource") {data.resources.delete(prop.value);}- if (instance?.component === "Image" && name === "src") {- const widthProp = instanceProps.get("width");- if (widthProp) {- data.props.delete(widthProp.id);- }- const heightProp = instanceProps.get("height");- if (heightProp) {- data.props.delete(heightProp.id);- }- }});};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.tsnew file mode 100644index 0000000000..bc1e011414--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.test.ts@@ -0,0 +1,135 @@+import { describe, expect, test } from "vitest";+import { rootComponent } from "@webstudio-is/sdk";+import { __testing__ } from "./props-section";++const {+ shouldShowPropertiesSection,+ shouldRenderPropsSectionContainer,+ shouldSyncMediaAssetProps,+} = __testing__;++describe("shouldShowPropertiesSection", () => {+ test("shows properties in design mode even when empty", () => {+ expect(+ shouldShowPropertiesSection({+ isDesignMode: true,+ isContentMode: false,+ hasProperties: false,+ })+ ).toBe(true);+ });++ test("shows content-mode properties when any visible item exists", () => {+ expect(+ shouldShowPropertiesSection({+ isDesignMode: false,+ isContentMode: true,+ hasProperties: true,+ })+ ).toBe(true);+ });++ test("hides properties outside design mode when there are no visible items", () => {+ expect(+ shouldShowPropertiesSection({+ isDesignMode: false,+ isContentMode: true,+ hasProperties: false,+ })+ ).toBe(false);+ expect(+ shouldShowPropertiesSection({+ isDesignMode: false,+ isContentMode: false,+ hasProperties: true,+ })+ ).toBe(false);+ });+});++describe("shouldRenderPropsSectionContainer", () => {+ test("renders when component metadata exists", () => {+ expect(+ shouldRenderPropsSectionContainer({+ component: "Box",+ propsMetasSize: 1,+ hasVisibleProps: false,+ isContentMode: false,+ })+ ).toBe(true);+ });++ test("renders content-mode visible props without component metadata", () => {+ expect(+ shouldRenderPropsSectionContainer({+ component: "Box",+ propsMetasSize: 0,+ hasVisibleProps: true,+ isContentMode: true,+ })+ ).toBe(true);+ });++ test("hides root and empty metadata without content-visible props", () => {+ expect(+ shouldRenderPropsSectionContainer({+ component: rootComponent,+ propsMetasSize: 1,+ hasVisibleProps: true,+ isContentMode: true,+ })+ ).toBe(false);+ expect(+ shouldRenderPropsSectionContainer({+ component: "Box",+ propsMetasSize: 0,+ hasVisibleProps: true,+ isContentMode: false,+ })+ ).toBe(false);+ expect(+ shouldRenderPropsSectionContainer({+ component: "Box",+ propsMetasSize: 0,+ hasVisibleProps: false,+ isContentMode: true,+ })+ ).toBe(false);+ });+});++describe("shouldSyncMediaAssetProps", () => {+ test("syncs related media props for image and video source assets", () => {+ expect(+ shouldSyncMediaAssetProps({+ component: "Image",+ propName: "src",+ propValue: { type: "asset" },+ })+ ).toBe(true);+ expect(+ shouldSyncMediaAssetProps({+ component: "Video",+ propName: "src",+ propValue: { type: "asset" },+ })+ ).toBe(true);+ });++ test("ignores non-source and non-asset changes", () => {+ expect(+ shouldSyncMediaAssetProps({+ component: "Image",+ propName: "alt",+ propValue: { type: "asset" },+ })+ ).toBe(false);+ expect(+ shouldSyncMediaAssetProps({+ component: "Image",+ propName: "src",+ propValue: { type: "string" },+ })+ ).toBe(false);+ });+});diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsxindex 42cf1d5d5f..6d771d4067 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx@@ -80,6 +80,48 @@ const matchOrSuggestToCreate = (return matched;};+const shouldShowPropertiesSection = ({+ isDesignMode,+ isContentMode,+ hasProperties,+}: {+ isDesignMode: boolean;+ isContentMode: boolean;+ hasProperties: boolean;+}) => {+ return isDesignMode || (isContentMode && hasProperties);+};++const shouldRenderPropsSectionContainer = ({+ component,+ propsMetasSize,+ hasVisibleProps,+ isContentMode,+}: {+ component: Instance["component"];+ propsMetasSize: number;+ hasVisibleProps: boolean;+ isContentMode: boolean;+}) => {+ if (component === rootComponent) {+ return false;+ }+ return propsMetasSize > 0 || (isContentMode && hasVisibleProps);+};++const shouldSyncMediaAssetProps = ({+ component,+ propName,+ propValue,+}: {+ component: Instance["component"];+ propName: string;+ propValue: { type: string };+}) =>+ (component === "Image" || component === "Video") &&+ propName === "src" &&+ propValue.type === "asset";+const renderProperty = ({propsLogic: logic,@@ -114,9 +156,11 @@ const renderProperty = (logic.handleChange({ prop, propName }, propValue);if (- (component === "Image" || component === "Video") &&- propName === "src" &&- propValue.type === "asset"+ shouldSyncMediaAssetProps({+ component,+ propName,+ propValue,+ })) {logic.handleChangeByPropName("width", propValue);logic.handleChangeByPropName("height", propValue);@@ -229,8 +273,9 @@ export const PropsSection = (props: PropsSectionProps) => {const matchMediaValue = matchMediaBreakpoints(matchingBreakpoints);- const hasItems =- logic.addedProps.length > 0 || addingProp || logic.initialProps.length > 0;+ const hasProperties =+ logic.addedProps.length > 0 || logic.initialProps.length > 0;+ const hasItems = hasProperties || (isDesignMode && addingProp);const animationAction = logic.initialProps.find((prop) => prop.meta.type === "animationAction"@@ -238,8 +283,11 @@ export const PropsSection = (props: PropsSectionProps) => {const hasAnimation = animationAction !== undefined;- const showPropertiesSection =- isDesignMode || (isContentMode && logic.initialProps.length > 0);+ const showPropertiesSection = shouldShowPropertiesSection({+ isDesignMode,+ isContentMode,+ hasProperties,+ });return hasAnimation && selectedBreakpoint?.id !== undefined ? (<>@@ -311,7 +359,7 @@ export const PropsSection = (props: PropsSectionProps) => {hasItems={hasItems}><Flex gap="1" direction="column">- {addingProp && (+ {isDesignMode && addingProp && (<AddPropertyOrAttributeonPropSelected={(propName) => {setAddingProp(false);@@ -328,6 +376,12 @@ export const PropsSection = (props: PropsSectionProps) => {);};+export const __testing__ = {+ shouldShowPropertiesSection,+ shouldRenderPropsSectionContainer,+ shouldSyncMediaAssetProps,+};+const $propValues = computed([$propValuesByInstanceSelector, $selectedInstanceKey],(propValuesByInstanceSelector, instanceKey) =>@@ -367,7 +421,19 @@ export const PropsSectionContainer = ({});const propsMetas = useStore($selectedInstancePropsMetas);- if (propsMetas.size === 0 || instance.component === rootComponent) {+ const isContentMode = useStore($isContentMode);+ const hasVisibleProps =+ logic.systemProps.length > 0 ||+ logic.initialProps.length > 0 ||+ logic.addedProps.length > 0;+ if (+ shouldRenderPropsSectionContainer({+ component: instance.component,+ propsMetasSize: propsMetas.size,+ hasVisibleProps,+ isContentMode,+ }) === false+ ) {return;}diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.tsnew file mode 100644index 0000000000..689fdb1e20--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.test.ts@@ -0,0 +1,278 @@+import { describe, expect, test } from "vitest";+import type { Prop, PropMeta } from "@webstudio-is/sdk";+import { textContentAttribute } from "@webstudio-is/react-sdk";+import { __testing__ } from "./use-props-logic";+import type { ContentModeCapabilities } from "@webstudio-is/project/content-mode-permissions";++const {+ isPropVisibleInContentMode,+ getStartingValue,+ getDefaultMetaForType,+ getAndDelete,+} = __testing__;++const getInput = (+ input: Partial<Parameters<typeof isPropVisibleInContentMode>[0]> = {}+): Parameters<typeof isPropVisibleInContentMode>[0] => ({+ propName: "title",+ props: [],+ propsMetas: new Map(),+ selectedInstanceSelector: ["editable-instance"],+ capabilities: {+ editablePropIds: new Set(),+ editableInstanceIds: new Set(["editable-instance"]),+ instances: new Map([+ [+ "editable-instance",+ {+ type: "instance",+ id: "editable-instance",+ component: "Box",+ children: [],+ },+ ],+ ]),+ metas: new Map(),+ props: new Map(),+ htmlTagsByInstanceId: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ contentRootIds: new Set(["editable-instance"]),+ } satisfies ContentModeCapabilities,+ ...input,+});++describe("isPropVisibleInContentMode", () => {+ test("hides props when no editable instance is selected", () => {+ expect(+ isPropVisibleInContentMode(+ getInput({ selectedInstanceSelector: undefined })+ )+ ).toBe(false);+ expect(+ isPropVisibleInContentMode(+ getInput({+ selectedInstanceSelector: ["readonly-instance"],+ })+ )+ ).toBe(false);+ });++ test("shows text content for editable instances", () => {+ expect(+ isPropVisibleInContentMode(getInput({ propName: textContentAttribute }))+ ).toBe(true);+ });++ test("shows existing asset props as content", () => {+ const prop: Prop = {+ id: "image-prop",+ instanceId: "editable-instance",+ name: "image",+ type: "asset",+ value: "asset-id",+ };++ expect(+ isPropVisibleInContentMode(+ getInput({+ propName: "image",+ props: [prop],+ capabilities: {+ ...getInput().capabilities,+ editablePropIds: new Set(["image-prop"]),+ },+ })+ )+ ).toBe(true);+ });++ test("shows unset file controls as content-editable asset props", () => {+ const fileMeta: PropMeta = {+ type: "string",+ control: "file",+ required: false,+ };++ expect(+ isPropVisibleInContentMode(+ getInput({+ propName: "image",+ propsMetas: new Map([["image", fileMeta]]),+ })+ )+ ).toBe(true);+ });++ test("shows only props marked as content mode in metadata", () => {+ const contentModeMeta: PropMeta = {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ };+ const designMeta: PropMeta = {+ type: "string",+ control: "text",+ required: false,+ };++ expect(+ isPropVisibleInContentMode(+ getInput({+ propName: "content",+ propsMetas: new Map([["content", contentModeMeta]]),+ })+ )+ ).toBe(true);+ expect(+ isPropVisibleInContentMode(+ getInput({+ propName: "design",+ propsMetas: new Map([["design", designMeta]]),+ })+ )+ ).toBe(false);+ });+});++describe("getStartingValue", () => {+ test("returns defaults for primitive editable prop metas", () => {+ expect(+ getStartingValue(+ {+ type: "string",+ control: "text",+ required: false,+ defaultValue: "Text",+ },+ false+ )+ ).toEqual({ type: "string", value: "Text" });+ expect(+ getStartingValue(+ {+ type: "number",+ control: "number",+ required: false,+ defaultValue: 12,+ },+ false+ )+ ).toEqual({ type: "number", value: 12 });+ expect(+ getStartingValue(+ {+ type: "boolean",+ control: "boolean",+ required: false,+ },+ true+ )+ ).toEqual({ type: "boolean", value: true });+ });++ test("returns defaults for list and action metas", () => {+ expect(+ getStartingValue(+ {+ type: "string[]",+ control: "multi-select",+ required: false,+ options: ["a", "b"],+ },+ false+ )+ ).toEqual({ type: "string[]", value: [] });+ expect(+ getStartingValue(+ {+ type: "action",+ control: "action",+ required: false,+ },+ false+ )+ ).toEqual({ type: "action", value: [] });+ });++ test("does not create a starting value for file controls", () => {+ expect(+ getStartingValue(+ {+ type: "string",+ control: "file",+ required: false,+ },+ false+ )+ ).toBeUndefined();+ });+});++describe("getDefaultMetaForType", () => {+ test("returns fallback meta for primitive prop types", () => {+ expect(getDefaultMetaForType("string")).toEqual({+ type: "string",+ control: "text",+ required: false,+ });+ expect(getDefaultMetaForType("number")).toEqual({+ type: "number",+ control: "number",+ required: false,+ });+ expect(getDefaultMetaForType("boolean")).toEqual({+ type: "boolean",+ control: "boolean",+ required: false,+ });+ });++ test("returns fallback meta for known special prop types", () => {+ expect(getDefaultMetaForType("asset")).toEqual({+ type: "string",+ control: "file",+ required: false,+ });+ expect(getDefaultMetaForType("page")).toEqual({+ type: "string",+ control: "url",+ required: false,+ });+ expect(getDefaultMetaForType("action")).toEqual({+ type: "action",+ control: "action",+ required: false,+ });+ });++ test("throws for prop types that require explicit metadata", () => {+ expect(() => getDefaultMetaForType("string[]")).toThrow("must have a meta");+ expect(() => getDefaultMetaForType("json")).toThrow("must have a meta");+ expect(() => getDefaultMetaForType("expression")).toThrow(+ "must have a meta"+ );+ expect(() => getDefaultMetaForType("parameter")).toThrow(+ "must have a meta"+ );+ expect(() => getDefaultMetaForType("resource")).toThrow("must have a meta");+ });+});++describe("getAndDelete", () => {+ test("returns and removes an existing map value", () => {+ const map = new Map([["key", 1]]);++ expect(getAndDelete(map, "key")).toBe(1);+ expect(map.has("key")).toBe(false);+ });++ test("returns undefined and still deletes missing keys", () => {+ const map = new Map([["key", 1]]);++ expect(getAndDelete(map, "missing")).toBeUndefined();+ expect(map).toEqual(new Map([["key", 1]]));+ });+});diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.tsindex 44543f1f87..9f3327e64c 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts@@ -3,6 +3,10 @@ import { computed } from "nanostores";import { useStore } from "@nanostores/react";import type { PropMeta, Instance, Prop } from "@webstudio-is/sdk";import { descendantComponent } from "@webstudio-is/sdk";+import {+ getContentModeCapabilities,+ type ContentModeCapabilities,+} from "@webstudio-is/project/content-mode-permissions";import {reactPropsToStandardAttributes,showAttribute,@@ -15,6 +19,7 @@ import {} from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { $props } from "~/shared/sync/data-stores";+import { $styleSources } from "~/shared/sync/data-stores";import { isRichText, isRichTextTree } from "~/shared/content-model";import { $selectedInstancePath } from "~/shared/nano-states";import {@@ -34,6 +39,43 @@ export type PropAndMeta = {instanceSelector?: Instance["id"][];};+const isPropVisibleInContentMode = ({+ propName,+ props,+ propsMetas,+ selectedInstanceSelector,+ capabilities,+}: {+ propName: string;+ props: Prop[];+ propsMetas: Map<string, PropMeta>;+ selectedInstanceSelector: undefined | Instance["id"][];+ capabilities: ContentModeCapabilities;+}) => {+ if (+ selectedInstanceSelector === undefined ||+ capabilities.editableInstanceIds.has(selectedInstanceSelector[0]) === false+ ) {+ return false;+ }+ if (propName === textContentAttribute) {+ return true;+ }+ if (+ props.some(+ (prop) =>+ prop.name === propName && capabilities.editablePropIds.has(prop.id)+ )+ ) {+ return true;+ }+ const propMeta = propsMetas.get(propName);+ if (propMeta?.type === "string" && propMeta.control === "file") {+ return true;+ }+ return propMeta?.contentMode === true;+};+// The value we set prop to when it's added//// If undefined is returned,@@ -127,7 +169,7 @@ const getDefaultMetaForType = (type: Prop["type"]): PropMeta => {"A prop with type resource must have a meta, we can't provide a default one because we need a list of options");default:- throw new Error(`Usupported data type: ${type satisfies never}`);+ throw new Error(`Unsupported data type: ${type satisfies never}`);}};@@ -143,6 +185,13 @@ const getAndDelete = <Value>(map: Map<string, Value>, key: string) => {return value;};+export const __testing__ = {+ isPropVisibleInContentMode,+ getStartingValue,+ getDefaultMetaForType,+ getAndDelete,+};+const $canHaveTextContent = computed([$instances,@@ -181,6 +230,19 @@ export const usePropsLogic = ({}: UsePropsLogicInput) => {const isContentMode = useStore($isContentMode);const propsMetas = useStore($selectedInstancePropsMetas);+ const instances = useStore($instances);+ const allProps = useStore($props);+ const styleSources = useStore($styleSources);+ const metas = useStore($registeredComponentMetas);+ const selectedInstancePath = useStore($selectedInstancePath);+ const contentModeCapabilities = isContentMode+ ? getContentModeCapabilities({+ instances,+ metas,+ props: allProps,+ styleSources,+ })+ : undefined;/*** In content edit mode we show only props marked with contentMode: true@@ -190,11 +252,16 @@ export const usePropsLogic = ({if (!isContentMode) {return true;}- if (propName === textContentAttribute) {- return true;+ if (contentModeCapabilities === undefined) {+ return false;}- const propMeta = propsMetas.get(propName);- return propMeta?.contentMode === true;+ return isPropVisibleInContentMode({+ propName,+ props,+ propsMetas,+ selectedInstanceSelector: selectedInstancePath?.[0].instanceSelector,+ capabilities: contentModeCapabilities,+ });};const savedProps = props;@@ -217,9 +284,6 @@ export const usePropsLogic = ({}const canHaveTextContent = useStore($canHaveTextContent);- const instances = useStore($instances);- const selectedInstancePath = useStore($selectedInstancePath);-const getTextContentTarget = () => {const canEditChildren = (target: Instance) => {const hasNoChildren = target.children.length === 0;@@ -296,8 +360,8 @@ export const usePropsLogic = ({// For initial props, if prop is not saved, we want to show default value if available.//- // Important to not use infer stating value if default is not available- // beacuse user may have this experience:+ // Important to not infer starting value if default is not available+ // because user may have this experience:// - they open props panel of an Image// - they see 0 in the control for "width"// - where 0 is a fallback when no default is available@@ -332,7 +396,9 @@ export const usePropsLogic = ({propMeta = propsMetas.get(name);}prop = { ...prop, name };- propMeta ??= getDefaultMetaForType("string");+ propMeta ??= getDefaultMetaForType(+ prop.type === "asset" ? "asset" : "string"+ );addedProps.push({prop,@@ -379,7 +445,7 @@ export const usePropsLogic = ({handleChange,handleChangeByPropName,/** Similar to Initial, but displayed as a separate group in UI etc.- * Currentrly used only for the ID prop. */+ * Currently used only for the ID prop. */systemProps: systemProps.filter(({ propName }) => isPropVisible(propName)),/** Initial (not deletable) props */initialProps: initialProps.filter(({ propName }) =>diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsxindex 9706ce2093..4757e41c10 100644--- a/apps/builder/app/builder/features/settings-panel/shared.tsx+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx@@ -24,6 +24,7 @@ import {SYSTEM_VARIABLE_ID,systemParameter,} from "@webstudio-is/sdk";+import { getContentModePropNamesByTag } from "@webstudio-is/project/content-mode-permissions";import type { PropMeta, Prop, Asset } from "@webstudio-is/sdk";import { InfoCircleIcon } from "@webstudio-is/icons";import {@@ -382,36 +383,9 @@ const attributeToMeta = (attribute: Attribute): PropMeta => {throw Error("impossible case");};-// Derive tag → content-mode attribute names from registered component metas,-// so a prop marked `contentMode: true` in a .ws.ts file also surfaces on-// `ws:element` instances rendering the same tag.-const $contentModeAttributesByTag = computed(+const $contentModePropNamesByTag = computed([$registeredComponentMetas],- (metas) => {- const byTag = new Map<string, Set<string>>();- for (const componentMeta of metas.values()) {- const tags = Object.keys(componentMeta.presetStyle ?? {});- if (tags.length === 0) {- continue;- }- for (const [propName, propMeta] of Object.entries(- componentMeta.props ?? {}- )) {- if (propMeta.contentMode !== true) {- continue;- }- for (const tag of tags) {- let names = byTag.get(tag);- if (names === undefined) {- names = new Set();- byTag.set(tag, names);- }- names.add(propName);- }- }- }- return byTag;- }+ getContentModePropNamesByTag);export const $selectedInstancePropsMetas = computed(@@ -419,13 +393,13 @@ export const $selectedInstancePropsMetas = computed($selectedInstance,$registeredComponentMetas,$instanceTags,- $contentModeAttributesByTag,+ $contentModePropNamesByTag,],(instance,metas,instanceTags,- contentModeAttributesByTag+ contentModePropNamesByTag): Map<string, PropMeta> => {if (instance === undefined) {return new Map();@@ -433,11 +407,11 @@ export const $selectedInstancePropsMetas = computed(const meta = metas.get(instance.component);const tag = instanceTags.get(instance.id);const propsMetas = new Map<Prop["name"], PropMeta>();- const contentModeAttributes =- tag === undefined ? undefined : contentModeAttributesByTag.get(tag);+ const contentModePropNames =+ tag === undefined ? undefined : contentModePropNamesByTag.get(tag);const toAttributeMeta = (attribute: Attribute): PropMeta => {const propMeta = attributeToMeta(attribute);- if (contentModeAttributes?.has(attribute.name)) {+ if (contentModePropNames?.has(attribute.name)) {return { ...propMeta, contentMode: true };}return propMeta;diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsxindex 57ed5a0f99..bf15415449 100644--- a/apps/builder/app/builder/features/style-panel/shared/model.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx@@ -13,6 +13,7 @@ import {type VarValue,} from "@webstudio-is/css-engine";import {+ getHtmlTagFromInstance,ROOT_INSTANCE_ID,type Styles,type StyleSourceSelections,@@ -63,30 +64,16 @@ const $presetStyles = computed($registeredComponentMetas, (metas) => {return presetStyles;});-const $tagByInstanceId = computed($props, (props) => {- const tagByInstanceId = new Map<Instance["id"], string>();- for (const prop of props.values()) {- if (prop.type === "string" && prop.name === "tag") {- tagByInstanceId.set(prop.instanceId, prop.value);- }- }- return tagByInstanceId;-});-export const $instanceTags = computed(- [$registeredComponentMetas, $selectedInstancePathWithRoot, $tagByInstanceId],- (metas, instancePath, tagByInstanceId) => {+ [$registeredComponentMetas, $props, $selectedInstancePathWithRoot],+ (metas, props, instancePath) => {const instanceTags = new Map<Instance["id"], HtmlTags>();if (instancePath === undefined) {return instanceTags;}for (const { instance } of instancePath) {- const meta = metas.get(instance.component);- const tags = Object.keys(meta?.presetStyle ?? {});- if (tags.length > 0) {- const metaTag = tags[0];- const propTag = tagByInstanceId.get(instance.id);- const tag = instance.tag ?? propTag ?? metaTag;+ const tag = getHtmlTagFromInstance({ instance, metas, props });+ if (tag !== undefined) {instanceTags.set(instance.id, tag as HtmlTags);}}diff --git a/apps/builder/app/builder/features/sync-status.test.tsx b/apps/builder/app/builder/features/sync-status.test.tsxnew file mode 100644index 0000000000..311962716f--- /dev/null+++ b/apps/builder/app/builder/features/sync-status.test.tsx@@ -0,0 +1,105 @@+import { createElement } from "react";+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 { SyncStatusDot } from "./sync-status";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++const renderSyncStatusDot = () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ act(() => {+ root?.render(createElement(SyncStatusDot));+ });++ const getDot = () => {+ const dot = document.querySelector('[role="status"]');+ if (dot === null) {+ throw new Error("Expected sync status dot to be rendered");+ }+ return dot;+ };++ return { getDot };+};++afterEach(() => {+ act(() => {+ root?.unmount();+ });+ root = undefined;+ document.body.innerHTML = "";+ $syncStatus.set({ status: "idle" });+ vi.useRealTimers();+});++describe("SyncStatusDot", () => {+ test("renders idle status by default", () => {+ const { getDot } = renderSyncStatusDot();++ expect(getDot().getAttribute("data-sync-status")).toBe("idle");+ expect(getDot().getAttribute("aria-label")).toBe("Sync status: idle");+ });++ test("renders pending status while changes are syncing", () => {+ const { getDot } = renderSyncStatusDot();++ act(() => {+ $syncStatus.set({ status: "syncing" });+ });++ expect(getDot().getAttribute("data-sync-status")).toBe("pending");+ expect(getDot().getAttribute("aria-label")).toBe(+ "Sync status: pending changes"+ );+ });++ test("renders saved status briefly after pending changes become idle", () => {+ vi.useFakeTimers();+ const { getDot } = renderSyncStatusDot();++ act(() => {+ $syncStatus.set({ status: "syncing" });+ });+ act(() => {+ $syncStatus.set({ status: "idle" });+ });++ expect(getDot().getAttribute("data-sync-status")).toBe("saved");+ expect(getDot().getAttribute("aria-label")).toBe("Sync status: saved");++ act(() => {+ vi.advanceTimersByTime(2000);+ });++ expect(getDot().getAttribute("data-sync-status")).toBe("idle");+ });++ test("renders error status for recoverable and fatal sync errors", () => {+ const { getDot } = renderSyncStatusDot();++ act(() => {+ $syncStatus.set({ status: "failed" });+ });++ expect(getDot().getAttribute("data-sync-status")).toBe("error");+ expect(getDot().getAttribute("aria-label")).toBe("Sync status: error");++ act(() => {+ $syncStatus.set({ status: "fatal", error: "broken" });+ });++ expect(getDot().getAttribute("data-sync-status")).toBe("error");+ expect(getDot().getAttribute("aria-label")).toBe(+ "Sync status: error: broken"+ );+ });+});diff --git a/apps/builder/app/builder/features/sync-status.tsx b/apps/builder/app/builder/features/sync-status.tsxindex 5e49eeec03..b085f21d3d 100644--- a/apps/builder/app/builder/features/sync-status.tsx+++ b/apps/builder/app/builder/features/sync-status.tsx@@ -1,17 +1,46 @@import { useStore } from "@nanostores/react";import { atom } from "nanostores";+import { useEffect, useRef, useState } from "react";import {+ Box,Flex,+ keyframes,rawTheme,Text,theme,Tooltip,} from "@webstudio-is/design-system";import { OfflineIcon } from "@webstudio-is/icons";-import { useEffect } from "react";-import { $syncStatus } from "@webstudio-is/sync-client";+import { $hasUnsavedSyncChanges, $syncStatus } from "@webstudio-is/sync-client";+const syncStatusDotSavedDuration = 2000;+const syncStatusDotPendingColor = "#f4c430";const $isOnline = atom(false);+const syncStatusDotConfig = {+ idle: {+ label: "Sync status: idle",+ color: "transparent",+ },+ pending: {+ label: "Sync status: pending changes",+ color: syncStatusDotPendingColor,+ },+ saved: {+ label: "Sync status: saved",+ color: theme.colors.foregroundSuccess,+ },+ error: {+ label: "Sync status: error",+ color: theme.colors.foregroundDestructive,+ },+} satisfies Record<string, { label: string; color: string }>;++type SyncStatusDotStatus = keyof typeof syncStatusDotConfig;++const syncStatusDotPendingPulse = keyframes({+ "0%": { backgroundColor: syncStatusDotPendingColor },+ "100%": { backgroundColor: "transparent" },+});const subscribeIsOnline = () => {const handle = () => $isOnline.set(navigator.onLine);@@ -23,6 +52,76 @@ const subscribeIsOnline = () => {};};+export const SyncStatusDot = () => {+ const statusObject = useStore($syncStatus);+ const hasUnsavedSyncChanges = useStore($hasUnsavedSyncChanges);+ const hadUnsavedSyncChangesRef = useRef(false);+ const savedTimeoutRef = useRef<ReturnType<typeof setTimeout>>();+ const [savedUntil, setSavedUntil] = useState(0);+ let visibleStatus: SyncStatusDotStatus = "idle";+ if (statusObject.status === "failed" || statusObject.status === "fatal") {+ visibleStatus = "error";+ } else if (hasUnsavedSyncChanges) {+ visibleStatus = "pending";+ } else if (Date.now() < savedUntil) {+ visibleStatus = "saved";+ }+ const statusConfig = syncStatusDotConfig[visibleStatus];+ const syncStatusDotLabel =+ visibleStatus === "error" && statusObject.status === "fatal"+ ? `${statusConfig.label}: ${statusObject.error}`+ : statusConfig.label;++ useEffect(() => {+ if (hasUnsavedSyncChanges) {+ hadUnsavedSyncChangesRef.current = true;+ return;+ }++ if (+ statusObject.status === "idle" &&+ hadUnsavedSyncChangesRef.current === true+ ) {+ hadUnsavedSyncChangesRef.current = false;+ setSavedUntil(Date.now() + syncStatusDotSavedDuration);+ clearTimeout(savedTimeoutRef.current);+ savedTimeoutRef.current = setTimeout(() => {+ setSavedUntil(0);+ }, syncStatusDotSavedDuration);+ }+ }, [hasUnsavedSyncChanges, statusObject.status]);++ useEffect(() => {+ return () => clearTimeout(savedTimeoutRef.current);+ }, []);++ return (+ <Box+ role="status"+ aria-label={syncStatusDotLabel}+ aria-live="polite"+ data-sync-status={visibleStatus}+ title={syncStatusDotLabel}+ style={{+ animation:+ visibleStatus === "pending"+ ? `${syncStatusDotPendingPulse} 1.8s ease-in-out infinite alternate`+ : "none",+ backgroundColor: statusConfig.color,+ }}+ css={{+ position: "absolute",+ top: theme.spacing[2],+ right: theme.spacing[2],+ width: 4,+ height: 4,+ borderRadius: 3,+ transition: "background-color 160ms ease",+ }}+ />+ );+};+export const SyncStatus = () => {const statusObject = useStore($syncStatus);const isOnline = useStore($isOnline);@@ -33,7 +132,7 @@ export const SyncStatus = () => {statusObject.status === "syncing" ||statusObject.status === "recovering") {- return null;+ return;}const containerProps = {diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsxindex 4e6adf718e..08cfe474c3 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx@@ -1,5 +1,6 @@import { useRef, useState } from "react";import { useStore } from "@nanostores/react";+import { shallowEqual } from "shallow-equal";import {Box,DropdownMenu,@@ -33,6 +34,7 @@ import { $instances } from "~/shared/sync/data-stores";import { $clampingRect, $scale } from "~/builder/shared/nano-states";import type { InstanceSelector } from "~/shared/tree-utils";import {+ canDeleteInstanceInContentMode,deleteInstanceMutable,updateWebstudioData,} from "~/shared/instance-utils";@@ -281,7 +283,17 @@ export const BlockChildHoveredInstanceOutline = () => {// Check if the top edge of the component is hidden (clipped by viewport/clamping)const isTopEdgeHidden = rect.top < clampingRect.top;- const isAddMode = isMenuOpen || !modifierKeys.altKey || !hasChildren;+ const canDeleteHoveredInstance =+ shallowEqual(outline.selector, outline.hoveredSelector) &&+ canDeleteInstanceInContentMode({+ instanceSelector: outline.selector,+ instances,+ });+ const isAddMode =+ isMenuOpen ||+ !modifierKeys.altKey ||+ !hasChildren ||+ canDeleteHoveredInstance === false;const tooltipContent = (<Grid>@@ -360,6 +372,7 @@ export const BlockChildHoveredInstanceOutline = () => {preventFocusOnHover={false}><IconButton+ aria-label={isAddMode ? "Insert block" : "Delete block"}variant={isAddMode ? "local" : "overwritten"}onClick={() => {if (isAddMode) {@@ -379,6 +392,9 @@ export const BlockChildHoveredInstanceOutline = () => {$hoveredInstanceOutline.set(undefined);}}css={{+ "& svg, & svg *": {+ pointerEvents: "none",+ },borderStyle: "solid",borderColor: isAddMode? `oklch(from ${theme.colors.backgroundPrimary} l c h / 0.7)`diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.tsnew file mode 100644index 0000000000..07e5956b04--- /dev/null+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts@@ -0,0 +1,39 @@+import { describe, expect, test, vi } from "vitest";+import type { WebstudioFragment } from "@webstudio-is/sdk";+import { __testing__ } from "./block-utils";++const { getTemplateTokenConflicts } = __testing__;++const fragment: WebstudioFragment = {+ children: [],+ instances: [],+ assets: [],+ dataSources: [],+ resources: [],+ props: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+};++describe("getTemplateTokenConflicts", () => {+ test("does not scan template token conflicts in content mode", () => {+ const detect = vi.fn(() => []);++ expect(+ getTemplateTokenConflicts({ fragment, contentMode: true, detect })+ ).toEqual([]);+ expect(detect).not.toHaveBeenCalled();+ });++ test("delegates template token conflict detection outside content mode", () => {+ const conflicts: ReturnType<typeof getTemplateTokenConflicts> = [];+ const detect = vi.fn(() => conflicts);++ expect(+ getTemplateTokenConflicts({ fragment, contentMode: false, detect })+ ).toBe(conflicts);+ expect(detect).toHaveBeenCalledWith({ fragment });+ });+});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.tsindex 201323300d..9757a90163 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts@@ -1,4 +1,4 @@-import type { Instance, Instances } from "@webstudio-is/sdk";+import type { Instance, Instances, WebstudioFragment } from "@webstudio-is/sdk";import { blockTemplateComponent } from "@webstudio-is/sdk";import { shallowEqual } from "shallow-equal";import { selectInstance } from "~/shared/nano-states";@@ -15,6 +15,7 @@ import {} from "~/shared/instance-utils";import {$registeredComponentMetas,+ $isContentMode,$textEditingInstanceSelector,findBlockChildSelector,findBlockSelector,@@ -71,6 +72,26 @@ const getInsertionIndex = (return insertBefore ? index : index + 1;};+const getTemplateTokenConflicts = ({+ fragment,+ contentMode,+ detect = detectFragmentTokenConflicts,+}: {+ fragment: WebstudioFragment;+ contentMode: boolean;+ detect?: typeof detectFragmentTokenConflicts;+}) => {+ if (contentMode) {+ return [];+ }+ return detect({ fragment });+};++export const __testing__ = {+ getInsertionIndex,+ getTemplateTokenConflicts,+};+export const insertListItemAt = (listItemSelector: InstanceSelector) => {const project = $project.get();const instances = $instances.get();@@ -178,7 +199,8 @@ export const insertTemplateAt = async (};try {- const conflicts = detectFragmentTokenConflicts({ fragment });+ const contentMode = $isContentMode.get();+ const conflicts = getTemplateTokenConflicts({ fragment, contentMode });const conflictResolution =conflicts.length > 0? await builderApi.showTokenConflictDialog(conflicts)@@ -194,6 +216,7 @@ export const insertTemplateAt = async (}),projectId: project.id,conflictResolution,+ contentMode,});const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);if (newRootInstanceId === undefined) {diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsxindex ddad968432..6b5466ed97 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx@@ -637,7 +637,10 @@ const AssetInfoContent = ({</Tooltip>) : (<Tooltip side="bottom" content="Replace asset">- <IconButton onClick={() => replaceInputRef.current?.click()}>+ <IconButton+ aria-label="Replace asset"+ onClick={() => replaceInputRef.current?.click()}+ ><RefreshCcwIcon /></IconButton></Tooltip>diff --git a/apps/builder/app/builder/shared/assets/asset-upload.tsx b/apps/builder/app/builder/shared/assets/asset-upload.tsxindex 1fa483d53f..3f07db81dc 100644--- a/apps/builder/app/builder/shared/assets/asset-upload.tsx+++ b/apps/builder/app/builder/shared/assets/asset-upload.tsx@@ -121,6 +121,7 @@ const EnabledAssetUpload = ({ accept, type }: AssetUploadProps) => {style={{ display: "none" }}/><Button+ aria-label="Upload asset"color="ghost"type="button"onClick={() => inputRef?.current?.click()}diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.tsnew file mode 100644index 0000000000..f24a522b56--- /dev/null+++ b/apps/builder/app/builder/shared/commands.test.ts@@ -0,0 +1,39 @@+import { describe, expect, test } from "vitest";+import { __testing__ } from "./commands";++const { canRunDesignModeCommand, guardDesignModeCommand } = __testing__;++describe("canRunDesignModeCommand", () => {+ test("keeps design commands design-only", () => {+ expect(canRunDesignModeCommand({ isDesignMode: true })).toBe(true);+ expect(canRunDesignModeCommand({ isDesignMode: false })).toBe(false);+ });+});++describe("guardDesignModeCommand", () => {+ test("allows design mode commands without showing a message", () => {+ const messages: string[] = [];++ expect(+ guardDesignModeCommand({+ isDesignMode: true,+ message: "Blocked",+ toastInfo: (message) => messages.push(message),+ })+ ).toBe(true);+ expect(messages).toEqual([]);+ });++ test("blocks non-design mode commands and reports a message", () => {+ const messages: string[] = [];++ expect(+ guardDesignModeCommand({+ isDesignMode: false,+ message: "Blocked",+ toastInfo: (message) => messages.push(message),+ })+ ).toBe(false);+ expect(messages).toEqual(["Blocked"]);+ });+});diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 3c72959655..bc450c919b 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -88,6 +88,30 @@ const exitPreviewModeFromNonCanvasSource = (source: string) => {toggleBuilderMode("preview");};+const canRunDesignModeCommand = ({ isDesignMode }: { isDesignMode: boolean }) =>+ isDesignMode;++const guardDesignModeCommand = ({+ isDesignMode,+ message,+ toastInfo = builderApi.toast.info,+}: {+ isDesignMode: boolean;+ message: string;+ toastInfo?: (message: string) => void;+}) => {+ if (canRunDesignModeCommand({ isDesignMode })) {+ return true;+ }+ toastInfo(message);+ return false;+};++export const __testing__ = {+ canRunDesignModeCommand,+ guardDesignModeCommand,+};+export const { emitCommand, subscribeCommands } = createCommandsEmitter({source: "builder",externalCommands: [@@ -325,19 +349,45 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({name: "paste",description: "Paste copied instance",category: "Navigator",- handler: emitPaste,+ handler: () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Pasting is only allowed in design mode.",+ })+ ) {+ emitPaste();+ }+ },},{name: "cut",description: "Cut selected instance",category: "Navigator",- handler: cutInstance,+ handler: () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Cutting is only allowed in design mode.",+ })+ ) {+ cutInstance();+ }+ },},{name: "toggleShow",description: "Toggle instance visibility",category: "Navigator",handler: () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Toggling visibility is only allowed in design mode.",+ }) === false+ ) {+ return;+ }const instancePath = $selectedInstancePath.get();if (instancePath?.[0]) {toggleInstanceShow(instancePath[0].instance.id);@@ -365,8 +415,12 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({if (project === undefined) {return;}- if ($isDesignMode.get() === false) {- builderApi.toast.info("Duplicating is only allowed in design mode.");+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Duplicating is only allowed in design mode.",+ }) === false+ ) {return;}const instancePath = $selectedInstancePath.get();@@ -448,6 +502,14 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({category: "Navigator",defaultHotkeys: ["meta+e", "ctrl+e"],handler: () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Renaming is only allowed in design mode.",+ }) === false+ ) {+ return;+ }const instancePath = $selectedInstancePath.get();if (instancePath === undefined) {return;@@ -464,6 +526,14 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({defaultHotkeys: ["meta+alt+g", "ctrl+alt+g"],keepCommandPanelOpen: true,handler: () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Wrapping is only allowed in design mode.",+ }) === false+ ) {+ return;+ }showWrapComponentsList();},},@@ -472,7 +542,16 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({description: "Remove parent wrapper",category: "Navigator",defaultHotkeys: ["meta+shift+g", "ctrl+shift+g"],- handler: () => unwrapInstance(),+ handler: () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Unwrapping is only allowed in design mode.",+ })+ ) {+ unwrapInstance();+ }+ },},{name: "convert",@@ -481,6 +560,14 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({category: "Navigator",keepCommandPanelOpen: true,handler: () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Converting is only allowed in design mode.",+ }) === false+ ) {+ return;+ }showConvertComponentsList();},},@@ -490,6 +577,14 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({label: "Paste HTML with Tailwind classes",description: "Convert Tailwind to CSS",handler: async () => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Pasting HTML is only allowed in design mode.",+ }) === false+ ) {+ return;+ }const html = await navigator.clipboard.readText();const parseResult = generateFragmentFromHtml(html);const { skippedSelectors } = parseResult;diff --git a/apps/builder/app/builder/shared/instance-context-menu.test.ts b/apps/builder/app/builder/shared/instance-context-menu.test.tsnew file mode 100644index 0000000000..3c888e6205--- /dev/null+++ b/apps/builder/app/builder/shared/instance-context-menu.test.ts@@ -0,0 +1,279 @@+import { describe, expect, test, beforeEach } from "vitest";+import {+ ROOT_FOLDER_ID,+ ROOT_INSTANCE_ID,+ blockComponent,+ blockTemplateComponent,+ type Instance,+ type Instances,+ type Page,+ type Pages,+} from "@webstudio-is/sdk";+import type { InstancePath } from "~/shared/nano-states";+import { $selectedPageId } from "~/shared/nano-states";+import { $pages } from "~/shared/sync/data-stores";+import { __testing__ } from "./instance-context-menu";++const { getMenuPermissions } = __testing__;++const emptyInstances: Instances = new Map();++const createInstance = (+ id: string,+ component = "Box",+ children: Instance["children"] = []+): Instance => ({+ type: "instance",+ id,+ component,+ children,+});++const page: Page = {+ id: "page",+ name: "Page",+ path: "",+ title: `"Page"`,+ meta: {},+ rootInstanceId: "body",+};++const pages: Pages = {+ homePageId: page.id,+ rootFolderId: ROOT_FOLDER_ID,+ pages: new Map([[page.id, page]]),+ folders: new Map([+ [+ ROOT_FOLDER_ID,+ {+ id: ROOT_FOLDER_ID,+ name: "Root",+ slug: "",+ children: [page.id],+ },+ ],+ ]),+};++beforeEach(() => {+ $pages.set(pages);+ $selectedPageId.set(page.id);+});++describe("getMenuPermissions", () => {+ test("keeps design actions available for regular instances", () => {+ const instancePath: InstancePath = [+ {+ instance: createInstance("child"),+ instanceSelector: ["child", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath,+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: true,+ canPaste: true,+ canCut: true,+ canDuplicate: true,+ canHide: true,+ canRename: true,+ canWrap: true,+ canConvert: true,+ canAddToken: true,+ canOpenSettings: true,+ canDelete: true,+ });+ });++ test("protects root and page body in design mode", () => {+ const rootPath: InstancePath = [+ {+ instance: createInstance(ROOT_INSTANCE_ID),+ instanceSelector: [ROOT_INSTANCE_ID],+ },+ ];+ const bodyPath: InstancePath = [+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath: rootPath,+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: false,+ canPaste: false,+ canCut: false,+ canDuplicate: false,+ canDelete: false,+ });+ expect(+ getMenuPermissions({+ instancePath: bodyPath,+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: false,+ canPaste: true,+ canCut: false,+ canDuplicate: false,+ canDelete: false,+ });+ });++ test("disables design mutations outside of design and content modes", () => {+ const instancePath: InstancePath = [+ {+ instance: createInstance("child"),+ instanceSelector: ["child", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath,+ isContentMode: false,+ isDesignMode: false,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: false,+ canPaste: false,+ canCut: false,+ canDuplicate: false,+ canHide: false,+ canRename: false,+ canWrap: false,+ canUnwrap: false,+ canConvert: false,+ canAddToken: false,+ canOpenSettings: true,+ canDelete: false,+ });+ });++ test("content mode exposes only direct content block child deletion and settings", () => {+ const instances: Instances = new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "child" },+ { type: "id", value: "template" },+ ]),+ ],+ [+ "child",+ createInstance("child", "Box", [{ type: "id", value: "nested" }]),+ ],+ ["nested", createInstance("nested")],+ ["template", createInstance("template", blockTemplateComponent)],+ ]);+ const blockPath: InstancePath = [+ {+ instance: createInstance("block", blockComponent),+ instanceSelector: ["block", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];+ const childPath: InstancePath = [+ {+ instance: createInstance("child"),+ instanceSelector: ["child", "block", "body"],+ },+ {+ instance: createInstance("block", blockComponent),+ instanceSelector: ["block", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];+ const nestedPath: InstancePath = [+ {+ instance: createInstance("nested"),+ instanceSelector: ["nested", "child", "block", "body"],+ },+ {+ instance: createInstance("child"),+ instanceSelector: ["child", "block", "body"],+ },+ {+ instance: createInstance("block", blockComponent),+ instanceSelector: ["block", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];+ const templatePath: InstancePath = [+ {+ instance: createInstance("template", blockTemplateComponent),+ instanceSelector: ["template", "block", "body"],+ },+ {+ instance: createInstance("block", blockComponent),+ instanceSelector: ["block", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ const permissions = getMenuPermissions({+ instancePath: childPath,+ isContentMode: true,+ isDesignMode: false,+ instances,+ });++ expect(permissions).toMatchObject({+ canCopy: false,+ canPaste: false,+ canCut: false,+ canDuplicate: false,+ canHide: false,+ canRename: false,+ canWrap: false,+ canUnwrap: false,+ canConvert: false,+ canAddToken: false,+ canOpenSettings: true,+ canDelete: true,+ });+ expect(+ getMenuPermissions({+ instancePath: blockPath,+ isContentMode: true,+ isDesignMode: false,+ instances,+ }).canDelete+ ).toBe(false);+ expect(+ getMenuPermissions({+ instancePath: nestedPath,+ isContentMode: true,+ isDesignMode: false,+ instances,+ }).canDelete+ ).toBe(false);+ expect(+ getMenuPermissions({+ instancePath: templatePath,+ isContentMode: true,+ isDesignMode: false,+ instances,+ }).canDelete+ ).toBe(false);+ });+});diff --git a/apps/builder/app/builder/shared/instance-context-menu.tsx b/apps/builder/app/builder/shared/instance-context-menu.tsxindex 66afdc8c99..9e74920838 100644--- a/apps/builder/app/builder/shared/instance-context-menu.tsx+++ b/apps/builder/app/builder/shared/instance-context-menu.tsx@@ -16,39 +16,94 @@ import { emitCommand } from "./commands";import {$selectedInstancePath,$selectedPage,+ $isContentMode,+ $isDesignMode,getInstanceKey,} from "~/shared/nano-states";-import { canUnwrapInstance } from "~/shared/instance-utils";+import {+ canDeleteInstanceInContentMode,+ canUnwrapInstance,+} from "~/shared/instance-utils";import { $propValuesByInstanceSelector } from "~/shared/nano-states";-import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";+import { $instances } from "~/shared/sync/data-stores";+import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";import type { InstancePath } from "~/shared/nano-states";-const getMenuPermissions = (instancePath: InstancePath | undefined) => {+const canDeleteInContentMode = ({+ instancePath,+ instances,+}: {+ instancePath: InstancePath | undefined;+ instances: Instances;+}) => {+ const instanceSelector = instancePath?.[0]?.instanceSelector;+ return (+ instanceSelector !== undefined &&+ canDeleteInstanceInContentMode({ instanceSelector, instances })+ );+};++const getMenuPermissions = ({+ instancePath,+ isContentMode,+ isDesignMode,+ instances,+}: {+ instancePath: InstancePath | undefined;+ isContentMode: boolean;+ isDesignMode: boolean;+ instances: Instances;+}) => {const instanceId = instancePath?.[0]?.instance.id;const rootInstanceId = $selectedPage.get()?.rootInstanceId;const isRoot = instanceId === ROOT_INSTANCE_ID;const isBody = instanceId === rootInstanceId;const isRootOrBody = isRoot || isBody;- const canUnwrap = instancePath ? canUnwrapInstance(instancePath) : false;++ if (isContentMode) {+ return {+ canCopy: false,+ canPaste: false,+ canCut: false,+ canDuplicate: false,+ canHide: false,+ canRename: false,+ canWrap: false,+ canUnwrap: false,+ canConvert: false,+ canAddToken: false,+ canOpenSettings: true,+ canDelete: canDeleteInContentMode({ instancePath, instances }),+ };+ }++ const canMutateDesign = isDesignMode;+ const canUnwrap =+ canMutateDesign && instancePath ? canUnwrapInstance(instancePath) : false;return {- canCopy: !isRootOrBody,- canPaste: !isRoot,- canCut: !isRootOrBody,- canDuplicate: !isRootOrBody,- canHide: !isRoot,- canRename: !isRoot,- canWrap: !isRootOrBody,+ canCopy: canMutateDesign && !isRootOrBody,+ canPaste: canMutateDesign && !isRoot,+ canCut: canMutateDesign && !isRootOrBody,+ canDuplicate: canMutateDesign && !isRootOrBody,+ canHide: canMutateDesign && !isRoot,+ canRename: canMutateDesign && !isRoot,+ canWrap: canMutateDesign && !isRootOrBody,canUnwrap,- canConvert: !isRootOrBody,- canDelete: !isRootOrBody,+ canConvert: canMutateDesign && !isRootOrBody,+ canAddToken: canMutateDesign,+ canOpenSettings: true,+ canDelete: canMutateDesign && !isRootOrBody,};};export const MenuItems = () => {const instancePath = useStore($selectedInstancePath);+ const instances = useStore($instances);const propValues = useStore($propValuesByInstanceSelector);+ const isContentMode = useStore($isContentMode);+ const isDesignMode = useStore($isDesignMode);const instanceSelector = instancePath?.[0]?.instanceSelector;@@ -59,7 +114,12 @@ export const MenuItems = () => {): true;- const permissions = getMenuPermissions(instancePath);+ const permissions = getMenuPermissions({+ instancePath,+ isContentMode,+ isDesignMode,+ instances,+ });return (<Box css={{ width: theme.spacing[28] }}>@@ -158,26 +218,30 @@ export const MenuItems = () => {Convert</ContextMenuItem><ContextMenuSeparator />- <ContextMenuItem- onSelect={() => {- emitCommand("focusStyleSources");- }}- >- Add token- <ContextMenuItemRightSlot>- <Kbd value={["meta", "enter"]} />- </ContextMenuItemRightSlot>- </ContextMenuItem>- <ContextMenuItem- onSelect={() => {- emitCommand("openSettingsPanel");- }}- >- Open settings- <ContextMenuItemRightSlot>- <Kbd value={["d"]} />- </ContextMenuItemRightSlot>- </ContextMenuItem>+ {permissions.canAddToken && (+ <ContextMenuItem+ onSelect={() => {+ emitCommand("focusStyleSources");+ }}+ >+ Add token+ <ContextMenuItemRightSlot>+ <Kbd value={["meta", "enter"]} />+ </ContextMenuItemRightSlot>+ </ContextMenuItem>+ )}+ {permissions.canOpenSettings && (+ <ContextMenuItem+ onSelect={() => {+ emitCommand("openSettingsPanel");+ }}+ >+ Open settings+ <ContextMenuItemRightSlot>+ <Kbd value={["d"]} />+ </ContextMenuItemRightSlot>+ </ContextMenuItem>+ )}<ContextMenuSeparator /><ContextMenuItemdisabled={!permissions.canDelete}@@ -215,3 +279,8 @@ export const InstanceContextMenu = ({ children }: { children: ReactNode }) => {</ContextMenu>);};++export const __testing__ = {+ canDeleteInContentMode,+ getMenuPermissions,+};diff --git a/apps/builder/app/builder/shared/topbar.tsx b/apps/builder/app/builder/shared/topbar.tsxindex 107ee193e9..fe5cc56020 100644--- a/apps/builder/app/builder/shared/topbar.tsx+++ b/apps/builder/app/builder/shared/topbar.tsx@@ -19,7 +19,7 @@ import { $editingPageId, $editingTemplateId } from "~/shared/nano-states";import { ShareButton } from "~/builder/features/share";import { PublishButton } from "~/builder/features/publish";-import { SyncStatus } from "~/builder/features/sync-status";+import { SyncStatusDot, SyncStatus } from "~/builder/features/sync-status";import { Menu } from "~/builder/features/menu";import { BreakpointsContainer } from "~/builder/features/breakpoints";import { ViewMode } from "~/builder/features/view-mode";@@ -238,6 +238,7 @@ export const Topbar = ({ project, css, loading, isUiHidden }: TopbarProps) => {)}<SafeModeButton /><ViewMode />+ <SyncStatusDot /><SyncStatus /><BuilderModeDropDown /><ShareButton projectId={project.id} />diff --git a/apps/builder/app/builder/sidebar-left/sidebar-left.tsx b/apps/builder/app/builder/sidebar-left/sidebar-left.tsxindex 22807de7ec..799dfa8ef0 100644--- a/apps/builder/app/builder/sidebar-left/sidebar-left.tsx+++ b/apps/builder/app/builder/sidebar-left/sidebar-left.tsx@@ -67,6 +67,7 @@ const HelpTabTrigger = () => {type PanelConfig = {name: SidebarPanelName;+ ariaLabel?: string;label: ReactNode;Icon: IconComponent;Panel: (props: { publish: Publish; onClose: () => void }) => ReactNode;@@ -116,6 +117,7 @@ const isPanelDisabled = (const panels: PanelConfig[] = [{name: "components",+ ariaLabel: "Components",label: (<Text>Components @@ -137,6 +139,7 @@ const panels: PanelConfig[] = [},{name: "navigator",+ ariaLabel: "Navigator",label: (<Text>Navigator @@ -259,12 +262,13 @@ export const SidebarLeft = ({ publish }: SidebarLeftProps) => {<SidebarTabsList>{panels.filter((panel) => isPanelVisible(panel, modes))- .map(({ name, Icon, label, visibility }) => {+ .map(({ name, Icon, label, visibility, ariaLabel }) => {const disabled = isPanelDisabled({ visibility }, modes);return (<SidebarTabsTriggerkey={name}label={label}+ aria-label={ariaLabel}value={name}disabled={disabled}onClick={() => {diff --git a/apps/builder/app/builder/sidebar-left/sidebar-tabs.tsx b/apps/builder/app/builder/sidebar-left/sidebar-tabs.tsxindex 90208a439f..bb58f57517 100644--- a/apps/builder/app/builder/sidebar-left/sidebar-tabs.tsx+++ b/apps/builder/app/builder/sidebar-left/sidebar-tabs.tsx@@ -81,13 +81,16 @@ export const SidebarTabsTrigger = forwardRef<HTMLButtonElement,ComponentProps<typeof TabsTrigger> & { label: ReactNode | string }>(({ label, children, ...props }, ref) => {+ const ariaLabel =+ props["aria-label"] ?? (typeof label === "string" ? label : undefined);+return (<Tooltip side="right" content={label}><Box><TabsTrigger{...props}ref={ref}- aria-label={typeof label === "string" ? label : undefined}+ aria-label={ariaLabel}className={buttonStyle()}>{children}diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 932e4bd9d6..ac167b4287 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -1,4 +1,11 @@-import { useMemo, useEffect, useState, useLayoutEffect, useRef } from "react";+import {+ useMemo,+ useEffect,+ useState,+ useLayoutEffect,+ useRef,+ type ReactNode,+} from "react";import { ErrorBoundary, type FallbackProps } from "react-error-boundary";import { useStore } from "@nanostores/react";import { type Instances, coreMetas } from "@webstudio-is/sdk";@@ -208,7 +215,7 @@ const DesignMode = () => {return null;};-const ContentEditMode = () => {+const ContentEditMode = (): ReactNode => {const debounceEffect = useDebounceEffect();const ref = useRef<undefined | Instances>(undefined);@@ -238,11 +245,14 @@ const ContentEditMode = () => {subscribeFontLoadingDone(options);initCopyPasteForContentEditMode(options);subscribeModifierKeys(options);+ // E2E tests wait for this after opening content mode before editing canvas text.+ document.body.dataset.wsContentEditMode = "ready";return () => {+ delete document.body.dataset.wsContentEditMode;abortController.abort();};}, []);- return null;+ return;};export const Canvas = () => {diff --git a/apps/builder/app/canvas/instance-hovering.ts b/apps/builder/app/canvas/instance-hovering.tsindex df35a6d342..a16d60e661 100644--- a/apps/builder/app/canvas/instance-hovering.ts+++ b/apps/builder/app/canvas/instance-hovering.ts@@ -137,6 +137,7 @@ export const subscribeInstanceHovering = ({$blockChildOutline.set({selector: blockChildSelector,+ hoveredSelector: instanceSelector,rect: blockChildRect,});};diff --git a/apps/builder/app/shared/content-model.ts b/apps/builder/app/shared/content-model.tsindex fcd5705943..fa7eade5b5 100644--- a/apps/builder/app/shared/content-model.ts+++ b/apps/builder/app/shared/content-model.ts@@ -1,6 +1,8 @@import { elementsByTag } from "@webstudio-is/html-data";import {elementComponent,+ getHtmlTagFromInstance,+ getHtmlTagsFromProps,parseComponentName,type ContentModel,type Instance,@@ -13,20 +15,18 @@ import { setIsSubsetOf } from "./shim";type Metas = Map<Instance["component"], WsComponentMeta>;-const tagByInstanceIdCache = new WeakMap<Props, Map<Instance["id"], string>>();+const htmlTagsByInstanceIdCache = new WeakMap<+ Props,+ Map<Instance["id"], string>+>();-const getTagByInstanceId = (props: Props) => {- let tagByInstanceId = tagByInstanceIdCache.get(props);- if (tagByInstanceId === undefined) {- tagByInstanceId = new Map<Instance["id"], string>();- for (const prop of props.values()) {- if (prop.type === "string" && prop.name === "tag") {- tagByInstanceId.set(prop.instanceId, prop.value);- }- }- tagByInstanceIdCache.set(props, tagByInstanceId);+const getHtmlTagsByInstanceId = (props: Props) => {+ let tags = htmlTagsByInstanceIdCache.get(props);+ if (tags === undefined) {+ tags = getHtmlTagsFromProps(props);+ htmlTagsByInstanceIdCache.set(props, tags);}- return tagByInstanceId;+ return tags;};const getTag = ({@@ -38,13 +38,12 @@ const getTag = ({metas: Metas;props: Props;}) => {- // ignore tag property on xml nodes- if (instance.component === "XmlNode") {- return;- }- const meta = metas.get(instance.component);- const metaTag = Object.keys(meta?.presetStyle ?? {}).at(0);- return instance.tag ?? getTagByInstanceId(props).get(instance.id) ?? metaTag;+ return getHtmlTagFromInstance({+ instance,+ metas,+ props,+ htmlTagsByInstanceId: getHtmlTagsByInstanceId(props),+ });};const isIntersected = (arrayA: string[], arrayB: string[]) => {diff --git a/apps/builder/app/shared/data-variables.test.tsx b/apps/builder/app/shared/data-variables.test.tsxindex 50d3e2cf6f..9583c2c71f 100644--- a/apps/builder/app/shared/data-variables.test.tsx+++ b/apps/builder/app/shared/data-variables.test.tsx@@ -28,6 +28,7 @@ import {deleteVariableMutable,findAvailableVariables,findVariableUsagesByInstance,+ replaceDataSourcesInExpression,} from "./data-variables";test("encode data variable name when necessary", () => {@@ -159,6 +160,15 @@ test("restore expression variables", () => {).toEqual("$ws$dataSource$myId + missingVariable");});+test("replace data source ids in expression", () => {+ expect(+ replaceDataSourcesInExpression(+ `$ws$dataSource$oldId + missingVariable`,+ new Map([["oldId", "newId"]])+ )+ ).toEqual("$ws$dataSource$newId + missingVariable");+});+test("compute expression with decoded ids", () => {expect(computeExpression("$ws$dataSource$myId", new Map([["myId", "value"]]))diff --git a/apps/builder/app/shared/data-variables.ts b/apps/builder/app/shared/data-variables.tsindex c9e31dda38..90b0a394f0 100644--- a/apps/builder/app/shared/data-variables.ts+++ b/apps/builder/app/shared/data-variables.ts@@ -12,7 +12,9 @@ import {SYSTEM_VARIABLE_ID,collectionComponent,decodeDataVariableId,+ decodeDataSourceVariable,encodeDataVariableId,+ encodeDataSourceVariable,findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,getAllPages,@@ -114,6 +116,24 @@ export const restoreExpressionVariables = ({}};+export const replaceDataSourcesInExpression = (+ expression: string,+ replacements: Map<DataSource["id"], DataSource["id"]>+) => {+ return transpileExpression({+ expression,+ replaceVariable: (identifier) => {+ const dataSourceId = decodeDataSourceVariable(identifier);+ if (dataSourceId === undefined) {+ return;+ }+ return encodeDataSourceVariable(+ replacements.get(dataSourceId) ?? dataSourceId+ );+ },+ });+};+export const computeExpression = (expression: string,variables: Map<DataSource["name"], unknown>diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsxindex fff8658537..fc4d00136d 100644--- a/apps/builder/app/shared/instance-utils.test.tsx+++ b/apps/builder/app/shared/instance-utils.test.tsx@@ -27,6 +27,9 @@ import type {} from "@webstudio-is/sdk";import {coreMetas,+ getStyleDeclKey,+ blockComponent,+ blockTemplateComponent,portalComponent,elementComponent,ROOT_INSTANCE_ID,@@ -54,6 +57,8 @@ import {convertInstance,deleteSelectedInstance,detectPageTokenConflicts,+ canDeleteInstanceInContentMode,+ __testing__,} from "./instance-utils";import type { InstancePath } from "./nano-states";import { $registeredComponentMetas } from "./nano-states";@@ -199,6 +204,178 @@ const createFontAsset = (id: string, family: string): Asset => {};};+describe("fragment copy helpers", () => {+ test("builds fragment instance maps and portal content roots", () => {+ const fragment = createFragment({+ instances: [+ createInstance("portal", portalComponent, [+ { type: "id", value: "portal-root" },+ ]),+ createInstance("portal-root", "Box", []),+ ],+ });++ const { fragmentInstances, portalContentRootIds } =+ __testing__.getFragmentInstancesData(fragment);++ expect(Array.from(fragmentInstances.keys())).toEqual([+ "portal",+ "portal-root",+ ]);+ expect(portalContentRootIds).toEqual(new Set(["portal-root"]));+ });++ test("inserts fragment assets without overwriting existing assets", () => {+ const existingAsset = createImageAsset(+ "existing-asset",+ "Existing",+ "target-project"+ );+ const assets = new Map<Asset["id"], Asset>([+ [existingAsset.id, existingAsset],+ ]);++ __testing__.insertFragmentAssetsMutable({+ fragment: createFragment({+ assets: [+ createImageAsset("existing-asset", "Source Existing", "source"),+ createImageAsset("new-asset", "New", "source"),+ ],+ }),+ projectId: "target-project",+ assets,+ });++ expect(assets.get("existing-asset")).toBe(existingAsset);+ expect(assets.get("new-asset")).toEqual({+ ...createImageAsset("new-asset", "New", "source"),+ projectId: "target-project",+ });+ });++ test("inserts fragment breakpoints and reports limit merges", () => {+ const baseBreakpoint: Breakpoint = { id: "base", label: "Base" };+ const breakpoints = new Map<Breakpoint["id"], Breakpoint>([+ [baseBreakpoint.id, baseBreakpoint],+ ]);+ let didMergeDueToLimit = false;++ const mergedBreakpointIds = __testing__.insertFragmentBreakpointsMutable({+ fragment: createFragment({+ breakpoints: [+ baseBreakpoint,+ { id: "desktop", label: "Desktop", minWidth: 1024 },+ ],+ }),+ breakpoints,+ onBreakpointLimitMerge: () => {+ didMergeDueToLimit = true;+ },+ });++ expect(mergedBreakpointIds.get("base")).toBe("base");+ expect(breakpoints.get("desktop")).toEqual({+ id: "desktop",+ label: "Desktop",+ minWidth: 1024,+ });+ expect(didMergeDueToLimit).toBe(false);+ });++ test("builds content-mode capabilities for fragment roots", () => {+ const registeredComponentMetas = $registeredComponentMetas.get();+ $registeredComponentMetas.set(+ createFakeComponentMetas({+ props: {+ href: {+ type: "string",+ control: "url",+ required: false,+ contentMode: true,+ },+ },+ })+ );+ try {+ const fragment = createFragment({+ children: [{ type: "id", value: "link" }],+ instances: [createInstance("link", "Item", [])],+ props: [+ {+ id: "href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/",+ },+ ],+ });+ const { fragmentInstances } =+ __testing__.getFragmentInstancesData(fragment);++ const capabilities = __testing__.getFragmentContentModeCapabilities({+ fragment,+ fragmentInstances,+ styleSources: new Map(),+ });++ expect(capabilities.contentRootIds).toEqual(new Set(["link"]));+ expect(capabilities.editablePropIds.has("href-prop")).toBe(true);+ } finally {+ $registeredComponentMetas.set(registeredComponentMetas);+ }+ });+});++describe("canDeleteInstanceInContentMode", () => {+ const instances = new Map([+ ["body", createInstance("body", "Body", [{ type: "id", value: "block" }])],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "child" },+ { type: "id", value: "template" },+ ]),+ ],+ [+ "child",+ createInstance("child", "Box", [{ type: "id", value: "nested" }]),+ ],+ ["nested", createInstance("nested", "Box", [])],+ ["template", createInstance("template", blockTemplateComponent, [])],+ ]);++ test("allows deleting direct content block children", () => {+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["child", "block", "body"],+ instances,+ })+ ).toBe(true);+ });++ test("protects content block roots, nested descendants, and templates", () => {+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["block", "body"],+ instances,+ })+ ).toBe(false);+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["nested", "child", "block", "body"],+ instances,+ })+ ).toBe(false);+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["template", "block", "body"],+ instances,+ })+ ).toBe(false);+ });+});+describe("insert instance children", () => {test("insert instance children into empty target", () => {const data = renderData(@@ -1507,6 +1684,237 @@ describe("insert webstudio fragment copy", () => {]);});+ test("copies local styles with new ids and reuses existing token styles in content mode", () => {+ const localStyleSource: StyleSource = { type: "local", id: "localBox" };+ const unsupportedLocalStyleSource: StyleSource = {+ type: "local",+ id: "unsupportedLocal",+ };+ const tokenStyleSource: StyleSource = {+ type: "token",+ id: "token",+ name: "Token",+ };+ const style = createStyleDecl("localBox", "base", "color", "red");+ const unsupportedBreakpointStyle = createStyleDecl(+ "localBox",+ "desktop",+ "backgroundColor",+ "blue"+ );+ const unsupportedLocalStyle = createStyleDecl(+ "unsupportedLocal",+ "desktop",+ "color",+ "green"+ );+ const data = getWebstudioDataStub({+ breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),+ instances: toMap([+ createInstance("body", "Body", []),+ createInstance("templateBox", "Box", []),+ ]),+ styleSources: toMap([+ localStyleSource,+ unsupportedLocalStyleSource,+ tokenStyleSource,+ ]),+ styleSourceSelections: new Map([+ [+ "templateBox",+ {+ instanceId: "templateBox",+ values: ["localBox", "unsupportedLocal", "token"],+ },+ ],+ ]),+ styles: new Map([+ [getStyleDeclKey(style), style],+ [+ getStyleDeclKey(unsupportedBreakpointStyle),+ unsupportedBreakpointStyle,+ ],+ [getStyleDeclKey(unsupportedLocalStyle), unsupportedLocalStyle],+ ]),+ });+ const fragment = createFragment({+ children: [{ type: "id", value: "templateBox" }],+ instances: [createInstance("templateBox", "Box", [])],+ styleSources: [+ localStyleSource,+ unsupportedLocalStyleSource,+ tokenStyleSource,+ ],+ styleSourceSelections: [+ {+ instanceId: "templateBox",+ values: ["localBox", "unsupportedLocal", "token"],+ },+ ],+ styles: [style, unsupportedBreakpointStyle, unsupportedLocalStyle],+ });++ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ contentMode: true,+ });+ const newInstanceId = newInstanceIds.get("templateBox");++ expect(newInstanceId).toBeDefined();+ const selection = data.styleSourceSelections.get(newInstanceId ?? "");+ expect(selection).toEqual({+ instanceId: newInstanceId,+ values: [expect.any(String), "token"],+ });+ const newLocalStyleSourceId = selection?.values[0];+ expect(newLocalStyleSourceId).not.toBe("localBox");+ expect(data.styleSources.get(newLocalStyleSourceId ?? "")).toEqual({+ type: "local",+ id: newLocalStyleSourceId,+ });+ expect(data.styles.get(getStyleDeclKey(style))).toEqual(style);+ expect(+ data.styles.get(+ getStyleDeclKey({+ ...style,+ styleSourceId: newLocalStyleSourceId ?? "",+ })+ )+ ).toEqual({ ...style, styleSourceId: newLocalStyleSourceId });+ expect(+ data.styles.has(+ getStyleDeclKey({+ ...unsupportedBreakpointStyle,+ styleSourceId: newLocalStyleSourceId ?? "",+ })+ )+ ).toBe(false);+ expect(+ Array.from(data.styleSources.values()).some(+ (styleSource) =>+ styleSource.type === "local" &&+ styleSource.id !== "localBox" &&+ styleSource.id !== "unsupportedLocal" &&+ styleSource.id !== newLocalStyleSourceId+ )+ ).toBe(false);+ });++ test("copies assets and asset props in content mode", () => {+ const asset = createImageAsset("asset", "Template image", "source_project");+ const data = getWebstudioDataStub();+ $registeredComponentMetas.set(+ new Map([+ ...defaultMetasMap,+ [+ "Item",+ {+ label: "Item",+ icon: "",+ props: {+ image: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ } satisfies WsComponentMeta,+ ],+ ])+ );+ const fragment = createFragment({+ children: [{ type: "id", value: "item" }],+ instances: [createInstance("item", "Item", [])],+ props: [+ {+ id: "image",+ instanceId: "item",+ name: "image",+ type: "asset",+ value: "asset",+ },+ ],+ assets: [asset],+ });++ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ contentMode: true,+ });+ const newInstanceId = newInstanceIds.get("item");++ expect(data.assets.get("asset")).toEqual({+ ...asset,+ projectId: "current_project",+ });+ expect(Array.from(data.props.values())).toEqual([+ expect.objectContaining({+ instanceId: newInstanceId,+ name: "image",+ type: "asset",+ value: "asset",+ }),+ ]);+ });++ test("copies tag-derived content mode props for generic elements", () => {+ const data = getWebstudioDataStub();+ const fragment = createFragment({+ children: [{ type: "id", value: "image" }],+ instances: [+ {+ type: "instance",+ id: "image",+ component: elementComponent,+ tag: "img",+ children: [],+ },+ ],+ props: [+ {+ id: "alt",+ instanceId: "image",+ name: "alt",+ type: "string",+ value: "Description",+ },+ {+ id: "class",+ instanceId: "image",+ name: "class",+ type: "string",+ value: "card",+ },+ ],+ });++ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ contentMode: true,+ });+ const newInstanceId = newInstanceIds.get("image");++ expect(newInstanceId).toBeDefined();+ expect(Array.from(data.props.values())).toEqual([+ expect.objectContaining({+ instanceId: newInstanceId,+ name: "alt",+ type: "string",+ value: "Description",+ }),+ ]);+ });+test("merge breakpoints with existing ones", () => {const breakpoints = toMap<Breakpoint>([{ id: "existing_base", label: "base" },diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex b89f23d06d..2e658bf894 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -17,20 +17,16 @@ import {type Resource,type WsComponentMeta,type Pages,- getStyleDeclKey,findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,- decodeDataSourceVariable,- encodeDataSourceVariable,- transpileExpression,getAllPages,getHomePage,findPageByIdOrPath,ROOT_INSTANCE_ID,portalComponent,collectionComponent,- Prop,- Props,+ type Prop,+ type Props,elementComponent,tags,blockTemplateComponent,@@ -71,7 +67,7 @@ import {wrapEditableChildrenAroundDropTargetMutable,} from "./tree-utils";import {- insertStyleSources,+ insertTokenStyleSources,insertPortalLocalStyleSources,insertLocalStyleSourcesWithNewIds,deleteLocalStyleSourcesMutable,@@ -92,6 +88,7 @@ import { selectInstance } from "./nano-states";import { findClosestInstanceMatchingFragment } from "./matcher";import {findAvailableVariables,+ replaceDataSourcesInExpression,restoreExpressionVariables,unsetExpressionVariables,} from "./data-variables";@@ -102,6 +99,10 @@ import {isRichTextContent,} from "./content-model";import type { Project } from "@webstudio-is/project";+import {+ getContentModeCapabilities,+ isContentModeCopyableProp,+} from "@webstudio-is/project/content-mode-permissions";import { getInstanceLabel } from "~/builder/shared/instance-label";import { $instanceTags } from "~/builder/features/style-panel/shared/model";import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";@@ -113,6 +114,29 @@ import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";export const unwrap = <Value>(value: Value) =>isDraft(value) ? current(value) : value;+export const canDeleteInstanceInContentMode = ({+ instanceSelector,+ instances,+}: {+ instanceSelector: InstanceSelector;+ instances: Instances;+}) => {+ const blockSelector = findBlockSelector(instanceSelector, instances);+ if (blockSelector === undefined) {+ return false;+ }++ const isDirectBlockChild =+ instanceSelector.length - blockSelector.length === 1;+ if (isDirectBlockChild === false) {+ return false;+ }++ return (+ instances.get(instanceSelector[0])?.component !== blockTemplateComponent+ );+};+export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {const selectedPage = $selectedPage.get();if (isPageTemplate(selectedPage) && $canOpenPageTemplates.get() === false) {@@ -1264,29 +1288,12 @@ export const deleteSelectedInstance = () => {}if ($isContentMode.get()) {- // In content mode we are allowing to delete childen of the editable block- const editableInstanceSelector = findBlockSelector(- selectedInstanceSelector,- instances- );- if (editableInstanceSelector === undefined) {- builderApi.toast.info("You can't delete this instance in conent mode.");- return;- }-- const isChildOfBlock =- selectedInstanceSelector.length - editableInstanceSelector.length === 1;-- const isTemplateInstance =- instances.get(selectedInstanceSelector[0])?.component ===- blockTemplateComponent;-- if (isTemplateInstance) {- builderApi.toast.info("You can't delete this instance in content mode.");- return;- }-- if (!isChildOfBlock) {+ if (+ canDeleteInstanceInContentMode({+ instanceSelector: selectedInstanceSelector,+ instances,+ }) === false+ ) {builderApi.toast.info("You can't delete this instance in content mode.");return;}@@ -1564,22 +1571,97 @@ export const extractWebstudioFragment = (};};-const replaceDataSources = (- code: string,- replacements: Map<DataSource["id"], DataSource["id"]>-) => {- return transpileExpression({- expression: code,- replaceVariable: (identifier) => {- const dataSourceId = decodeDataSourceVariable(identifier);- if (dataSourceId === undefined) {- return;+const getFragmentInstancesData = (fragment: WebstudioFragment) => {+ const fragmentInstances: Instances = new Map();+ const portalContentRootIds = new Set<Instance["id"]>();+ for (const instance of fragment.instances) {+ fragmentInstances.set(instance.id, instance);+ if (instance.component === portalComponent) {+ for (const child of instance.children) {+ if (child.type === "id") {+ portalContentRootIds.add(child.value);+ }}- return encodeDataSourceVariable(- replacements.get(dataSourceId) ?? dataSourceId- );- },+ }+ }+ return { fragmentInstances, portalContentRootIds };+};++const insertFragmentAssetsMutable = ({+ fragment,+ projectId,+ assets,+}: {+ fragment: WebstudioFragment;+ projectId: Project["id"];+ assets: WebstudioData["assets"];+}) => {+ for (const asset of fragment.assets) {+ // asset can be already present if pasting to the same project+ if (assets.has(asset.id) === false) {+ // we use the same asset.id so the references are preserved+ assets.set(asset.id, { ...asset, projectId });+ }+ }+};++const insertFragmentBreakpointsMutable = ({+ fragment,+ breakpoints,+ onBreakpointLimitMerge,+}: {+ fragment: WebstudioFragment;+ breakpoints: Breakpoints;+ onBreakpointLimitMerge?: () => void;+}) => {+ let didMergeBreakpointsDueToLimit = false;+ const mergedBreakpointIds = buildMergedBreakpointIds(+ fragment.breakpoints,+ breakpoints,+ {+ maxBreakpointCount: maxBreakpoints,+ onBreakpointMergedDueToLimit: () => {+ didMergeBreakpointsDueToLimit = true;+ },+ }+ );+ if (didMergeBreakpointsDueToLimit) {+ onBreakpointLimitMerge?.();+ }+ for (const newBreakpoint of fragment.breakpoints) {+ if (mergedBreakpointIds.has(newBreakpoint.id) === false) {+ breakpoints.set(newBreakpoint.id, newBreakpoint);+ }+ }+ return mergedBreakpointIds;+};++const getFragmentContentModeCapabilities = ({+ fragment,+ fragmentInstances,+ styleSources,+}: {+ fragment: WebstudioFragment;+ fragmentInstances: Instances;+ styleSources: WebstudioData["styleSources"];+}) =>+ getContentModeCapabilities({+ instances: fragmentInstances,+ metas: $registeredComponentMetas.get(),+ props: new Map(fragment.props.map((prop) => [prop.id, prop])),+ styleSources,+ contentRootIds: new Set(+ fragment.children+ .filter((child) => child.type === "id")+ .map((child) => child.value)+ ),});++export const __testing__ = {+ getFragmentInstancesData,+ insertFragmentAssetsMutable,+ insertFragmentBreakpointsMutable,+ getFragmentContentModeCapabilities,};export const insertWebstudioFragmentCopy = ({@@ -1589,6 +1671,9 @@ export const insertWebstudioFragmentCopy = ({projectId,conflictResolution = "theirs",onBreakpointLimitMerge,+ // In content mode, insertion keeps content-editable instance data, creates+ // local styles for inserted instances, and avoids data/resource records.+ contentMode = false,}: {data: Omit<WebstudioData, "pages">;fragment: WebstudioFragment;@@ -1596,6 +1681,7 @@ export const insertWebstudioFragmentCopy = ({projectId: Project["id"];conflictResolution?: ConflictResolution;onBreakpointLimitMerge?: () => void;+ contentMode?: boolean;}) => {const newInstanceIds = new Map<Instance["id"], Instance["id"]>();const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();@@ -1604,18 +1690,8 @@ export const insertWebstudioFragmentCopy = ({newDataSourceIds,};- const fragmentInstances: Instances = new Map();- const portalContentRootIds = new Set<Instance["id"]>();- for (const instance of fragment.instances) {- fragmentInstances.set(instance.id, instance);- if (instance.component === portalComponent) {- for (const child of instance.children) {- if (child.type === "id") {- portalContentRootIds.add(child.value);- }- }- }- }+ const { fragmentInstances, portalContentRootIds } =+ getFragmentInstancesData(fragment);const {assets,@@ -1641,69 +1717,34 @@ export const insertWebstudioFragmentCopy = ({* and those ids are used instead*/- // insert assets+ const mergedBreakpointIds =+ contentMode === false+ ? insertFragmentBreakpointsMutable({+ fragment,+ breakpoints,+ onBreakpointLimitMerge,+ })+ : new Map<StyleDecl["breakpointId"], StyleDecl["breakpointId"]>();- for (const asset of fragment.assets) {- // asset can be already present if pasting to the same project- if (assets.has(asset.id) === false) {- // we use the same asset.id so the references are preserved- assets.set(asset.id, { ...asset, projectId });- }- }+ insertFragmentAssetsMutable({ fragment, projectId, assets });- // merge breakpoints-- let didMergeBreakpointsDueToLimit = false;- const mergedBreakpointIds = buildMergedBreakpointIds(- fragment.breakpoints,- breakpoints,- {- maxBreakpointCount: maxBreakpoints,- onBreakpointMergedDueToLimit: () => {- didMergeBreakpointsDueToLimit = true;- },- }- );- if (didMergeBreakpointsDueToLimit) {- onBreakpointLimitMerge?.();- }- for (const newBreakpoint of fragment.breakpoints) {- if (mergedBreakpointIds.has(newBreakpoint.id) === false) {- breakpoints.set(newBreakpoint.id, newBreakpoint);- }- }+ let styleSourceIdMap = new Map<+ StyleDecl["styleSourceId"],+ StyleDecl["styleSourceId"]+ >();- // insert tokens with their styles+ if (contentMode === false) {+ // insert tokens with their styles- const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =- insertStyleSources({+ styleSourceIdMap = insertTokenStyleSources({fragmentStyleSources: fragment.styleSources,fragmentStyles: fragment.styles,- existingStyleSources: styleSources,- existingStyles: styles,+ styleSources,+ styles,breakpoints,mergedBreakpointIds,conflictResolution,});-- // Update styleSources map with the new tokens- for (const [id, styleSource] of updatedStyleSources) {- styleSources.set(id, styleSource);- }-- for (const styleDecl of fragment.styles) {- if (styleSourceIds.has(styleDecl.styleSourceId)) {- const { breakpointId } = styleDecl;- const newStyleDecl: StyleDecl = {- ...styleDecl,- breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,- // Remap the styleSourceId to the new token ID- styleSourceId:- styleSourceIdMap.get(styleDecl.styleSourceId) ??- styleDecl.styleSourceId,- };- styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);- }}let portalContentIds = new Set<Instance["id"]>();@@ -1725,29 +1766,31 @@ export const insertWebstudioFragmentCopy = ({continue;}- const usedResourceIds = new Set<Resource["id"]>();- for (const dataSource of fragment.dataSources) {- // insert only data sources within portal content- if (instanceIds.has(dataSource.scopeInstanceId ?? "")) {- dataSources.set(dataSource.id, dataSource);- if (dataSource.type === "resource") {- usedResourceIds.add(dataSource.resourceId);+ if (contentMode === false) {+ const usedResourceIds = new Set<Resource["id"]>();+ for (const dataSource of fragment.dataSources) {+ // insert only data sources within portal content+ if (instanceIds.has(dataSource.scopeInstanceId ?? "")) {+ dataSources.set(dataSource.id, dataSource);+ if (dataSource.type === "resource") {+ usedResourceIds.add(dataSource.resourceId);+ }}}- }- for (const prop of fragment.props) {- if (instanceIds.has(prop.instanceId)) {- props.set(prop.id, prop);- if (prop.type === "resource") {- usedResourceIds.add(prop.value);+ for (const prop of fragment.props) {+ if (instanceIds.has(prop.instanceId)) {+ props.set(prop.id, prop);+ if (prop.type === "resource") {+ usedResourceIds.add(prop.value);+ }}}- }- for (const resource of fragment.resources) {- if (usedResourceIds.has(resource.id)) {- resources.set(resource.id, resource);+ for (const resource of fragment.resources) {+ if (usedResourceIds.has(resource.id)) {+ resources.set(resource.id, resource);+ }}}@@ -1757,18 +1800,20 @@ export const insertWebstudioFragmentCopy = ({}}- // insert local style sources with their styles+ if (contentMode === false) {+ // insert local style sources with their styles- insertPortalLocalStyleSources({- fragmentStyleSources: fragment.styleSources,- fragmentStyleSourceSelections: fragment.styleSourceSelections,- fragmentStyles: fragment.styles,- instanceIds,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });+ insertPortalLocalStyleSources({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyleSourceSelections: fragment.styleSourceSelections,+ fragmentStyles: fragment.styles,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });+ }}/**@@ -1796,39 +1841,59 @@ export const insertWebstudioFragmentCopy = ({maskedIdByName.set(dataSource.name, dataSource.id);}const newResourceIds = new Map<Resource["id"], Resource["id"]>();- for (let dataSource of fragment.dataSources) {- const scopeInstanceId = dataSource.scopeInstanceId ?? "";- if (scopeInstanceId === ROOT_INSTANCE_ID) {- // add global variable only if not exist already- if (- dataSources.has(dataSource.id) === false &&- maskedIdByName.has(dataSource.name) === false- ) {- dataSources.set(dataSource.id, dataSource);+ if (contentMode === false) {+ for (let dataSource of fragment.dataSources) {+ const scopeInstanceId = dataSource.scopeInstanceId ?? "";+ if (scopeInstanceId === ROOT_INSTANCE_ID) {+ // add global variable only if not exist already+ if (+ dataSources.has(dataSource.id) === false &&+ maskedIdByName.has(dataSource.name) === false+ ) {+ dataSources.set(dataSource.id, dataSource);+ }+ continue;}- continue;- }- // insert only data sources within portal content- if (fragmentInstanceIds.has(scopeInstanceId)) {- const newDataSourceId = nanoid();- newDataSourceIds.set(dataSource.id, newDataSourceId);- dataSource = structuredClone(unwrap(dataSource));- dataSource.id = newDataSourceId;- dataSource.scopeInstanceId =- newInstanceIds.get(scopeInstanceId) ?? scopeInstanceId;- if (dataSource.type === "resource") {- const newResourceId = nanoid();- newResourceIds.set(dataSource.resourceId, newResourceId);- dataSource.resourceId = newResourceId;+ // insert only data sources within portal content+ if (fragmentInstanceIds.has(scopeInstanceId)) {+ const newDataSourceId = nanoid();+ newDataSourceIds.set(dataSource.id, newDataSourceId);+ dataSource = structuredClone(unwrap(dataSource));+ dataSource.id = newDataSourceId;+ dataSource.scopeInstanceId =+ newInstanceIds.get(scopeInstanceId) ?? scopeInstanceId;+ if (dataSource.type === "resource") {+ const newResourceId = nanoid();+ newResourceIds.set(dataSource.resourceId, newResourceId);+ dataSource.resourceId = newResourceId;+ }+ dataSources.set(dataSource.id, dataSource);}- dataSources.set(dataSource.id, dataSource);}}+ const fragmentContentModeCapabilities =+ contentMode === false+ ? undefined+ : getFragmentContentModeCapabilities({+ fragment,+ fragmentInstances,+ styleSources,+ });for (let prop of fragment.props) {if (fragmentInstanceIds.has(prop.instanceId) === false) {continue;}+ if (+ contentMode &&+ (fragmentContentModeCapabilities === undefined ||+ isContentModeCopyableProp({+ capabilities: fragmentContentModeCapabilities,+ prop,+ }) === false)+ ) {+ continue;+ }prop = structuredClone(unwrap(prop));prop.id = nanoid();prop.instanceId = newInstanceIds.get(prop.instanceId) ?? prop.instanceId;@@ -1837,7 +1902,7 @@ export const insertWebstudioFragmentCopy = ({expression: prop.value,maskedIdByName,});- prop.value = replaceDataSources(prop.value, newDataSourceIds);+ prop.value = replaceDataSourcesInExpression(prop.value, newDataSourceIds);}if (prop.type === "action") {for (const value of prop.value) {@@ -1845,7 +1910,10 @@ export const insertWebstudioFragmentCopy = ({expression: value.code,maskedIdByName,});- value.code = replaceDataSources(value.code, newDataSourceIds);+ value.code = replaceDataSourcesInExpression(+ value.code,+ newDataSourceIds+ );}}if (prop.type === "parameter") {@@ -1859,44 +1927,55 @@ export const insertWebstudioFragmentCopy = ({props.set(prop.id, prop);}- for (let resource of fragment.resources) {- if (newResourceIds.has(resource.id) === false) {- continue;- }- resource = structuredClone(unwrap(resource));- resource.id = newResourceIds.get(resource.id) ?? resource.id;- resource.url = restoreExpressionVariables({- expression: resource.url,- maskedIdByName,- });- resource.url = replaceDataSources(resource.url, newDataSourceIds);- for (const header of resource.headers) {- header.value = restoreExpressionVariables({- expression: header.value,+ if (contentMode === false) {+ for (let resource of fragment.resources) {+ if (newResourceIds.has(resource.id) === false) {+ continue;+ }+ resource = structuredClone(unwrap(resource));+ resource.id = newResourceIds.get(resource.id) ?? resource.id;+ resource.url = restoreExpressionVariables({+ expression: resource.url,maskedIdByName,});- header.value = replaceDataSources(header.value, newDataSourceIds);- }- if (resource.searchParams) {- for (const searchParam of resource.searchParams) {- searchParam.value = restoreExpressionVariables({- expression: searchParam.value,+ resource.url = replaceDataSourcesInExpression(+ resource.url,+ newDataSourceIds+ );+ for (const header of resource.headers) {+ header.value = restoreExpressionVariables({+ expression: header.value,maskedIdByName,});- searchParam.value = replaceDataSources(- searchParam.value,+ header.value = replaceDataSourcesInExpression(+ header.value,newDataSourceIds);}+ if (resource.searchParams) {+ for (const searchParam of resource.searchParams) {+ searchParam.value = restoreExpressionVariables({+ expression: searchParam.value,+ maskedIdByName,+ });+ searchParam.value = replaceDataSourcesInExpression(+ searchParam.value,+ newDataSourceIds+ );+ }+ }+ if (resource.body) {+ resource.body = restoreExpressionVariables({+ expression: resource.body,+ maskedIdByName,+ });+ resource.body = replaceDataSourcesInExpression(+ resource.body,+ newDataSourceIds+ );+ }+ resources.set(resource.id, resource);}- if (resource.body) {- resource.body = restoreExpressionVariables({- expression: resource.body,- maskedIdByName,- });- resource.body = replaceDataSources(resource.body, newDataSourceIds);- }- resources.set(resource.id, resource);}for (let instance of fragment.instances) {@@ -1912,27 +1991,41 @@ export const insertWebstudioFragmentCopy = ({expression: child.value,maskedIdByName,});- child.value = replaceDataSources(child.value, newDataSourceIds);+ child.value = replaceDataSourcesInExpression(+ child.value,+ newDataSourceIds+ );}}instances.set(instance.id, instance);}}- // insert local styles with new ids-- insertLocalStyleSourcesWithNewIds({+ const localStyleSourceInput = {fragmentStyleSources: fragment.styleSources,fragmentStyleSourceSelections: fragment.styleSourceSelections,fragmentStyles: fragment.styles,fragmentInstanceIds,newInstanceIds,- styleSourceIdMap,styleSources,styleSourceSelections,styles,- mergedBreakpointIds,- });+ };+ if (contentMode) {+ insertLocalStyleSourcesWithNewIds({+ ...localStyleSourceInput,+ contentMode: true,+ breakpoints,+ });+ } else {+ insertLocalStyleSourcesWithNewIds({+ ...localStyleSourceInput,+ contentMode: false,+ styleSourceIdMap,+ mergedBreakpointIds,+ breakpoints,+ });+ }return newDataIds;};diff --git a/apps/builder/app/shared/nano-states/canvas.ts b/apps/builder/app/shared/nano-states/canvas.tsindex 6a8f5e579f..158d245f5f 100644--- a/apps/builder/app/shared/nano-states/canvas.ts+++ b/apps/builder/app/shared/nano-states/canvas.ts@@ -24,6 +24,7 @@ type InstanceOutline = {export type BlockChildOutline = {selector: InstanceSelector;+ hoveredSelector: InstanceSelector;rect: DOMRect;};diff --git a/apps/builder/app/shared/page-utils.test.tsx b/apps/builder/app/shared/page-utils.test.tsxindex a2528c1cb3..c485aa540b 100644--- a/apps/builder/app/shared/page-utils.test.tsx+++ b/apps/builder/app/shared/page-utils.test.tsx@@ -5,6 +5,7 @@ import {ROOT_INSTANCE_ID,encodeDataVariableId,getHomePage,+ type Page,type Instance,type WebstudioData,} from "@webstudio-is/sdk";@@ -15,8 +16,10 @@ import {} from "@webstudio-is/project-build";import { $project } from "./sync/data-stores";import {+ __testing__,insertPageCopyMutable,insertPageFromTemplateMutable,+ copyAndTransformPageMeta,} from "./page-utils";import {$,@@ -52,6 +55,119 @@ const getWebstudioDataStub = (...data,});+const getPagesWithSiblings = () =>+ migratePages({+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "homeBody",+ },+ pages: [+ {+ id: "about",+ name: "About",+ path: "/about",+ title: `"About"`,+ meta: {},+ rootInstanceId: "aboutBody",+ },+ {+ id: "about-copy",+ name: "About (1)",+ path: "/copy-1/about",+ title: `"About"`,+ meta: {},+ rootInstanceId: "aboutCopyBody",+ },+ ],+ folders: [createRootFolder(["home", "about", "about-copy"])],+ });++describe("page utility helpers", () => {+ test("deduplicates names within the target folder", () => {+ const pages = getPagesWithSiblings();++ expect(+ __testing__.deduplicateName(pages, ROOT_FOLDER_ID, "Contact")+ ).toEqual("Contact");+ expect(__testing__.deduplicateName(pages, ROOT_FOLDER_ID, "About")).toEqual(+ "About (2)"+ );+ expect(+ __testing__.deduplicateName(pages, ROOT_FOLDER_ID, "About (1)")+ ).toEqual("About (2)");+ });++ test("deduplicates paths within the target folder", () => {+ const pages = getPagesWithSiblings();++ expect(+ __testing__.deduplicatePath(pages, ROOT_FOLDER_ID, "/contact")+ ).toEqual("/contact");+ expect(+ __testing__.deduplicatePath(pages, ROOT_FOLDER_ID, "/about")+ ).toEqual("/copy-2/about");+ expect(__testing__.deduplicatePath(pages, ROOT_FOLDER_ID, "/")).toEqual(+ "/copy-1"+ );+ });++ test("joins path parts without duplicate slashes", () => {+ expect(__testing__.joinPath("/", "/blog", "/post")).toEqual("/blog/post");+ expect(__testing__.joinPath("/docs/", "/guide")).toEqual("/docs/guide");+ });+});++describe("page meta copy helpers", () => {+ test("copies and transforms selected page meta fields", () => {+ const target: Page["meta"] = {};++ copyAndTransformPageMeta(+ {+ title: "old",+ description: "old",+ documentType: "text",+ auth: { method: "basic", login: "u", password: "p" },+ },+ target,+ (value) => value.replace("old", "new"),+ { fields: new Set(["title", "documentType"]) }+ );++ expect(target).toEqual({+ title: "new",+ documentType: "text",+ });+ });++ test("copies only caller-selected page meta fields", () => {+ const target: Page["meta"] = {};++ copyAndTransformPageMeta(+ {+ title: "old",+ description: "old",+ documentType: "text",+ auth: { method: "basic", login: "u", password: "p" },+ custom: [{ property: "og:type", content: "old" }],+ },+ target,+ (value) => value.replace("old", "new"),+ { fields: new Set(["title", "description", "custom"]) }+ );++ expect(target).toEqual({+ title: "new",+ description: "new",+ custom: [{ property: "og:type", content: "new" }],+ });+ });+});+describe("insert page copy", () => {$project.set({ id: "projectId" } as Project);diff --git a/apps/builder/app/shared/page-utils.ts b/apps/builder/app/shared/page-utils.tsindex 207de19123..aee6ddfc10 100644--- a/apps/builder/app/shared/page-utils.ts+++ b/apps/builder/app/shared/page-utils.ts@@ -1,11 +1,8 @@import { nanoid } from "nanoid";import {- decodeDataSourceVariable,- encodeDataSourceVariable,findPageByIdOrPath,getFolderById,getPagePath,- transpileExpression,type Folder,type DataSource,type Page,@@ -14,6 +11,7 @@ import {type WebstudioData,ROOT_INSTANCE_ID,} from "@webstudio-is/sdk";+import { contentModePageMetaFields } from "@webstudio-is/project/content-mode-permissions";import {extractWebstudioFragment,insertWebstudioFragmentCopy,@@ -21,6 +19,7 @@ import {} from "./instance-utils";import {findAvailableVariables,+ replaceDataSourcesInExpression,restoreExpressionVariables,unsetExpressionVariables,} from "./data-variables";@@ -79,24 +78,6 @@ const deduplicatePath = (// Normalize to avoid double slashes when folderPath is "/" (empty-slug folder).const joinPath = (...parts: string[]) => parts.join("").replace(/\/+/g, "/");-export const replaceDataSourcesInExpression = (- expression: string,- replacements: Map<DataSource["id"], DataSource["id"]>-) => {- return transpileExpression({- expression,- replaceVariable: (identifier) => {- const dataSourceId = decodeDataSourceVariable(identifier);- if (dataSourceId === undefined) {- return;- }- return encodeDataSourceVariable(- replacements.get(dataSourceId) ?? dataSourceId- );- },- });-};-/*** Copies the project :root and the given page/template body from `source`* into `target`. Returns the remapped instance ids plus an expression@@ -108,28 +89,32 @@ const copyPageRootAndBodyMutable = ({sourceRootInstanceId,systemDataSourceId,conflictResolution,+ contentMode = false,}: {source: WebstudioData;target: WebstudioData;sourceRootInstanceId: string;systemDataSourceId: string | undefined;conflictResolution: ConflictResolution | undefined;+ contentMode?: boolean;}) => {const project = $project.get();if (project === undefined) {return;}- // copy paste project :root- insertWebstudioFragmentCopy({- data: target,- fragment: extractWebstudioFragment(source, ROOT_INSTANCE_ID),- availableVariables: findAvailableVariables({- ...target,- startingInstanceId: ROOT_INSTANCE_ID,- }),- projectId: project.id,- conflictResolution,- });+ if (contentMode === false) {+ // copy paste project :root+ insertWebstudioFragmentCopy({+ data: target,+ fragment: extractWebstudioFragment(source, ROOT_INSTANCE_ID),+ availableVariables: findAvailableVariables({+ ...target,+ startingInstanceId: ROOT_INSTANCE_ID,+ }),+ projectId: project.id,+ conflictResolution,+ });+ }const unsetVariables = new Set<DataSource["id"]>();const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();// replace legacy page system with global variable@@ -154,6 +139,7 @@ const copyPageRootAndBodyMutable = ({availableVariables,projectId: project.id,conflictResolution,+ contentMode,});const transformExpression = (expression: string) => {// rebind expressions from page system variable to the global one@@ -165,50 +151,55 @@ const copyPageRootAndBodyMutable = ({return { newInstanceIds, transformExpression };};-/**- * For each defined field on `source.meta`, write a transformed copy onto- * `target.meta`. Safe to call with source === target (used by page copy,- * where the target was produced by structuredClone of the source page).- */export const copyAndTransformPageMeta = (source: Page["meta"],target: Page["meta"],- transform: (expression: string) => string+ transform: (expression: string) => string,+ options?: { fields?: Set<string> }) => {- if (source.description !== undefined) {+ const { fields } = options ?? {};+ const canCopy = (field: string) => fields === undefined || fields.has(field);++ if (source.description !== undefined && canCopy("description")) {target.description = transform(source.description);}- if (source.title !== undefined) {+ if (source.title !== undefined && canCopy("title")) {target.title = transform(source.title);}- if (source.excludePageFromSearch !== undefined) {+ if (+ source.excludePageFromSearch !== undefined &&+ canCopy("excludePageFromSearch")+ ) {target.excludePageFromSearch = transform(source.excludePageFromSearch);}- if (source.socialImageUrl !== undefined) {+ if (source.socialImageUrl !== undefined && canCopy("socialImageUrl")) {target.socialImageUrl = transform(source.socialImageUrl);}- if (source.socialImageAssetId !== undefined) {+ if (+ source.socialImageAssetId !== undefined &&+ canCopy("socialImageAssetId")+ ) {target.socialImageAssetId = source.socialImageAssetId;}- if (source.documentType !== undefined) {+ if (source.documentType !== undefined && canCopy("documentType")) {target.documentType = source.documentType;}- if (source.content !== undefined) {+ if (source.content !== undefined && canCopy("content")) {target.content = source.content;}- if (source.auth !== undefined) {+ if (source.auth !== undefined && canCopy("auth")) {target.auth = { ...source.auth };}- if (source.language !== undefined) {+ if (source.language !== undefined && canCopy("language")) {target.language = transform(source.language);}- if (source.status !== undefined) {+ if (source.status !== undefined && canCopy("status")) {target.status = transform(source.status);}- if (source.redirect !== undefined) {+ if (source.redirect !== undefined && canCopy("redirect")) {target.redirect = transform(source.redirect);}- if (source.custom) {+ if (source.custom && canCopy("custom")) {target.custom = source.custom.map(({ property, content }) => ({property,content: transform(content),@@ -216,18 +207,26 @@ export const copyAndTransformPageMeta = (}};+export const __testing__ = {+ deduplicateName,+ deduplicatePath,+ joinPath,+};+export const insertPageFromTemplateMutable = ({templateId,source,target,overrides,conflictResolution,+ contentMode = false,}: {templateId: PageTemplate["id"];source: { data: WebstudioData };target: { data: WebstudioData; folderId: Folder["id"] };overrides: { name: string; path: string };conflictResolution?: ConflictResolution;+ contentMode?: boolean;}) => {const template = source.data.pages.pageTemplates?.get(templateId);if (template === undefined) {@@ -239,6 +238,7 @@ export const insertPageFromTemplateMutable = ({sourceRootInstanceId: template.rootInstanceId,systemDataSourceId: template.systemDataSourceId,conflictResolution,+ contentMode,});if (copied === undefined) {return;@@ -256,7 +256,10 @@ export const insertPageFromTemplateMutable = ({copyAndTransformPageMeta(template.meta,newPage.meta,- copied.transformExpression+ copied.transformExpression,+ {+ fields: contentMode ? contentModePageMetaFields : undefined,+ });target.data.pages.pages.set(newPage.id, newPage);target.data.pages.folders.get(target.folderId)?.children.push(newPage.id);diff --git a/apps/builder/app/shared/share-project/share-project-container.tsx b/apps/builder/app/shared/share-project/share-project-container.tsxindex 8941db411a..d895039f78 100644--- a/apps/builder/app/shared/share-project/share-project-container.tsx+++ b/apps/builder/app/shared/share-project/share-project-container.tsx@@ -19,6 +19,7 @@ const useShareProjectContainer = (projectId: string) => {const { send: updateToken, state: updateState } =trpcClient.authorizationToken.update.useMutation();const [links, setLinks] = useState(data ?? []);+ const [isChangingLink, setIsChangingLink] = useState(false);const deletingLinks = useRef(new Set<string>());useEffect(() => {@@ -30,23 +31,34 @@ const useShareProjectContainer = (projectId: string) => {const handleChangeDebounced = useDebouncedCallback((link: LinkOptions) => {// Link is about to get deleted, no need to update.if (deletingLinks.current.has(link.token)) {+ setIsChangingLink(false);return;}const updatedLink = {projectId: projectId,...link,};- const updatedLinks = links.map((currentLink) => {- if (currentLink.token === updatedLink.token) {- return { ...currentLink, ...updatedLink };- }- return currentLink;+ setLinks((links) => {+ return links.map((currentLink) => {+ if (currentLink.token === updatedLink.token) {+ return { ...currentLink, ...updatedLink };+ }+ return currentLink;+ });+ });+ updateToken(updatedLink, () => {+ load({ projectId }, (data) => {+ setLinks(data ?? []);+ setIsChangingLink(false);+ });});- // Optimistically set the links, otherwise checkbox will not move until we fetch an updated list.- setLinks(updatedLinks);- updateToken(updatedLink);}, 100);+ const handleChange = (link: LinkOptions) => {+ setIsChangingLink(true);+ handleChangeDebounced(link);+ };+const handleDelete = (link: LinkOptions) => {deletingLinks.current.add(link.token);@@ -78,11 +90,12 @@ const useShareProjectContainer = (projectId: string) => {loadState !== "idle" ||createState !== "idle" ||removeState !== "idle" ||- updateState !== "idle";+ updateState !== "idle" ||+ isChangingLink;return {links,- handleChangeDebounced,+ handleChange,handleDelete,handleCreate,isPending,@@ -100,20 +113,15 @@ type ShareButtonProps = {export const ShareProjectContainer = ({ projectId }: ShareButtonProps) => {const { allowAdditionalPermissions } = useStore($permissions);const purchases = useStore($purchases);- const {- links,- handleChangeDebounced,- handleDelete,- handleCreate,- isPending,- } = useShareProjectContainer(projectId);+ const { links, handleChange, handleDelete, handleCreate, isPending } =+ useShareProjectContainer(projectId);return (<ShareProjectallowAdditionalPermissions={allowAdditionalPermissions}isFreePlan={purchases.length === 0}links={links}- onChange={handleChangeDebounced}+ onChange={handleChange}onDelete={handleDelete}onCreate={handleCreate}isPending={isPending}diff --git a/apps/builder/app/shared/share-project/share-project.test.tsx b/apps/builder/app/shared/share-project/share-project.test.tsxnew file mode 100644index 0000000000..330d122e92--- /dev/null+++ b/apps/builder/app/shared/share-project/share-project.test.tsx@@ -0,0 +1,110 @@+import { createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { afterEach, describe, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import { ShareProject, type LinkOptions } from "./share-project";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++const link: LinkOptions = {+ token: "token-1",+ name: "Share project",+ relation: "viewers",+ canCopy: false,+ canClone: false,+ canPublish: false,+};++const getElement = <ElementType extends Element>(selector: string) => {+ const element = document.querySelector<ElementType>(selector);+ if (element === null) {+ throw new Error(`Expected element matching "${selector}"`);+ }+ return element;+};++const getControlByLabel = <ElementType extends HTMLElement>(text: string) => {+ const labels = Array.from(document.querySelectorAll("label"));+ const label = labels.find((label) => label.textContent === text);+ const id = label?.getAttribute("for");+ if (id === undefined || id === null) {+ throw new Error(`Expected label "${text}" to reference a control`);+ }+ const control = document.getElementById(id);+ if (control === null) {+ throw new Error(`Expected control for label "${text}"`);+ }+ return control as ElementType;+};++const click = (element: Element) => {+ act(() => {+ element.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+};++const renderShareProject = ({+ onChange,+}: {+ onChange: (value: LinkOptions) => void;+}) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);++ act(() => {+ root?.render(+ createElement(TooltipProvider, {+ children: createElement(ShareProject, {+ links: [link],+ onChange,+ onDelete: vi.fn(),+ onCreate: vi.fn(),+ builderUrl: ({ authToken }) =>+ `https://example.com?token=${authToken}`,+ isPending: false,+ allowAdditionalPermissions: true,+ isFreePlan: false,+ }),+ })+ );+ });+};++afterEach(() => {+ act(() => {+ root?.unmount();+ });+ root = undefined;+ document.body.innerHTML = "";+});++describe("ShareProject", () => {+ test("keeps share link permission changes in local state before parent rerender", () => {+ const onChange = vi.fn();+ renderShareProject({ onChange });++ click(getElement('[aria-label="Menu Button for options"]'));+ click(getControlByLabel("Editor"));++ const publishCheckbox = getControlByLabel<HTMLButtonElement>("Can publish");+ expect(publishCheckbox.disabled).toBe(false);++ click(publishCheckbox);++ expect(onChange).toHaveBeenNthCalledWith(1, {+ ...link,+ relation: "editors",+ });+ expect(onChange).toHaveBeenNthCalledWith(2, {+ ...link,+ relation: "editors",+ canPublish: true,+ });+ });+});diff --git a/apps/builder/app/shared/share-project/share-project.tsx b/apps/builder/app/shared/share-project/share-project.tsxindex 0b54a88a90..990c77e296 100644--- a/apps/builder/app/shared/share-project/share-project.tsx+++ b/apps/builder/app/shared/share-project/share-project.tsx@@ -1,6 +1,8 @@import {+ useEffect,Fragment,useId,+ useRef,useState,type ComponentProps,type ReactNode,@@ -128,7 +130,7 @@ type MenuProps = {name: string;value: LinkOptions;allowAdditionalPermissions: boolean;- onChange: (value: LinkOptions) => void;+ onChange: (value: LinkOptionsUpdate) => void;onDelete: () => void;};@@ -145,7 +147,7 @@ const Menu = ({const handleCheckedChange = (role: Role) => (checked: boolean) => {if (checked) {- onChange({ ...value, relation: role });+ onChange({ relation: role });}};@@ -154,7 +156,7 @@ const Menu = ({return;}- onChange({ ...value, name: customLinkName.trim() });+ onChange({ name: customLinkName.trim() });};return (@@ -167,6 +169,7 @@ const Menu = ({></Button></PopoverTrigger><PopoverContent+ aria-label={`Share link options ${name}`}css={{//padding: 0,width: theme.spacing[24],@@ -235,7 +238,7 @@ const Menu = ({}checked={value.canClone}onCheckedChange={(canClone) => {- onChange({ ...value, canClone: Boolean(canClone) });+ onChange({ canClone: Boolean(canClone) });}}id={ids.canClone}/>@@ -262,7 +265,7 @@ const Menu = ({}checked={value.canCopy}onCheckedChange={(canCopy) => {- onChange({ ...value, canCopy: Boolean(canCopy) });+ onChange({ canCopy: Boolean(canCopy) });}}id={ids.canCopy}/>@@ -317,7 +320,7 @@ const Menu = ({}checked={value.canPublish}onCheckedChange={(canPublish) => {- onChange({ ...value, canPublish: Boolean(canPublish) });+ onChange({ canPublish: Boolean(canPublish) });}}id={ids.canPublish}/>@@ -394,6 +397,8 @@ export type LinkOptions = {canPublish: boolean;};+type LinkOptionsUpdate = Partial<Omit<LinkOptions, "token">>;+type SharedLinkItemType = {value: LinkOptions;onChange: (value: LinkOptions) => void;@@ -416,15 +421,32 @@ const SharedLinkItem = ({builderUrl,allowAdditionalPermissions,}: SharedLinkItemType) => {- const [currentName, setCurrentName] = useState(value.name);+ const [currentLink, setCurrentLink] = useState(value);+ const currentLinkRef = useRef(value);++ useEffect(() => {+ currentLinkRef.current = value;+ setCurrentLink(value);+ }, [value]);++ const updateCurrentLink = (update: LinkOptionsUpdate) => {+ const nextLink = { ...currentLinkRef.current, ...update };+ currentLinkRef.current = nextLink;+ setCurrentLink(nextLink);+ onChange(nextLink);+ };return (- <Box className={itemStyle()}>- <Label css={{ flexGrow: 1 }}>{currentName}</Label>+ <Box+ className={itemStyle()}+ role="group"+ aria-label={`Share link ${currentLink.name}`}+ >+ <Label css={{ flexGrow: 1 }}>{currentLink.name}</Label><CopyToClipboardtext={builderUrl({- authToken: value.token,- mode: relationToMode[value.relation],+ authToken: currentLink.token,+ mode: relationToMode[currentLink.relation],})}copyText="Copy link">@@ -433,12 +455,9 @@ const SharedLinkItem = ({</IconButton></CopyToClipboard><Menu- name={currentName}- value={value}- onChange={(value) => {- setCurrentName(value.name);- onChange(value);- }}+ name={currentLink.name}+ value={currentLink}+ onChange={updateCurrentLink}onDelete={onDelete}allowAdditionalPermissions={allowAdditionalPermissions}/>@@ -519,7 +538,13 @@ export const ShareProject = ({);return (- <Flex direction="column" css={{ width: theme.spacing[33] }}>+ <Flex+ direction="column"+ role="region"+ aria-label="Share links"+ aria-busy={isPending}+ css={{ width: theme.spacing[33] }}+ >{isFreePlan && (<><ShareLinkSecurityNotice />diff --git a/apps/builder/app/shared/style-source-utils.test.tsx b/apps/builder/app/shared/style-source-utils.test.tsxindex 18b78a77f0..47848fa9cb 100644--- a/apps/builder/app/shared/style-source-utils.test.tsx+++ b/apps/builder/app/shared/style-source-utils.test.tsx@@ -13,6 +13,7 @@ import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";import {getStyleSourceStylesSignature,insertStyleSources,+ insertTokenStyleSources,insertPortalLocalStyleSources,insertLocalStyleSourcesWithNewIds,deleteStyleSourceMutable,@@ -1289,6 +1290,265 @@ describe("insertLocalStyleSourcesWithNewIds", () => {});});+describe("insertLocalStyleSourcesWithNewIds in content mode", () => {+ test("copies local styles for existing breakpoints and reuses token ids", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "fragment-local" },+ { type: "token", id: "existing-token", name: "Existing" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "fragment-instance", values: ["fragment-local"] },+ {+ instanceId: "fragment-instance-with-token",+ values: ["fragment-local", "existing-token"],+ },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("fragment-local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("fragment-local", "missing", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ];+ const fragmentInstanceIds = new Set([+ "fragment-instance",+ "fragment-instance-with-token",+ ]);+ const newInstanceIds = new Map([+ ["fragment-instance", "new-instance"],+ ["fragment-instance-with-token", "new-instance-with-token"],+ ]);+ const styleSources: StyleSources = new Map([+ [+ "existing-token",+ { type: "token", id: "existing-token", name: "Existing" },+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "Base" }]);++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ breakpoints,+ contentMode: true,+ });++ const copiedLocalIds = Array.from(styleSources.keys()).filter(+ (styleSourceId) => styleSourceId !== "existing-token"+ );+ expect(copiedLocalIds).toHaveLength(1);+ const [copiedLocalId] = copiedLocalIds;+ expect(styleSources.get(copiedLocalId)).toMatchObject({ type: "local" });+ expect(styleSourceSelections.get("new-instance")).toEqual({+ instanceId: "new-instance",+ values: [copiedLocalId],+ });+ expect(styleSourceSelections.get("new-instance-with-token")).toEqual({+ instanceId: "new-instance-with-token",+ values: [copiedLocalId, "existing-token"],+ });+ expect(Array.from(styles.values())).toEqual([+ {+ ...fragmentStyles[0],+ styleSourceId: copiedLocalId,+ },+ ]);+ });++ test("skips selections with no copyable content-mode style sources", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "fragment-local" },+ { type: "token", id: "missing-token", name: "Missing" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "fragment-instance", values: ["fragment-local"] },+ { instanceId: "fragment-instance-with-token", values: ["missing-token"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("fragment-local", "missing", "color", {+ type: "keyword",+ value: "red",+ }),+ ];+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds: new Set([+ "fragment-instance",+ "fragment-instance-with-token",+ ]),+ newInstanceIds: new Map([+ ["fragment-instance", "new-instance"],+ ["fragment-instance-with-token", "new-instance-with-token"],+ ]),+ styleSources,+ styleSourceSelections,+ styles,+ breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),+ contentMode: true,+ });++ expect(styleSources).toEqual(new Map());+ expect(styleSourceSelections).toEqual(new Map());+ expect(styles).toEqual(new Map());+ });++ test("does not reuse target local style source ids", () => {+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "fragment-instance", values: ["existing-local"] },+ {+ instanceId: "fragment-instance-with-token",+ values: ["existing-token"],+ },+ ];+ const styleSources: StyleSources = new Map([+ ["existing-local", { type: "local", id: "existing-local" }],+ [+ "existing-token",+ { type: "token", id: "existing-token", name: "Existing" },+ ],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources: [],+ fragmentStyleSourceSelections,+ fragmentStyles: [],+ fragmentInstanceIds: new Set([+ "fragment-instance",+ "fragment-instance-with-token",+ ]),+ newInstanceIds: new Map([+ ["fragment-instance", "new-instance"],+ ["fragment-instance-with-token", "new-instance-with-token"],+ ]),+ styleSources,+ styleSourceSelections,+ styles,+ breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),+ contentMode: true,+ });++ expect(styleSourceSelections.get("new-instance")).toBeUndefined();+ expect(styleSourceSelections.get("new-instance-with-token")).toEqual({+ instanceId: "new-instance-with-token",+ values: ["existing-token"],+ });+ });++ test("copies fragment local style sources even when ids already exist in target", () => {+ const fragmentStyleSources: StyleSource[] = [+ { type: "local", id: "local" },+ ];+ const fragmentStyleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "fragment-instance", values: ["local"] },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ];+ const styleSources: StyleSources = new Map([+ ["local", { type: "local", id: "local" }],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources,+ fragmentStyleSourceSelections,+ fragmentStyles,+ fragmentInstanceIds: new Set(["fragment-instance"]),+ newInstanceIds: new Map([["fragment-instance", "new-instance"]]),+ styleSources,+ styleSourceSelections,+ styles,+ breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),+ contentMode: true,+ });++ const copiedLocalId = styleSourceSelections.get("new-instance")?.values[0];++ expect(copiedLocalId).toBeDefined();+ expect(copiedLocalId).not.toBe("local");+ expect(styleSources.get("local")).toEqual({ type: "local", id: "local" });+ expect(styleSources.get(copiedLocalId ?? "")).toMatchObject({+ type: "local",+ });+ expect(Array.from(styles.values())).toEqual([+ {+ ...fragmentStyles[0],+ styleSourceId: copiedLocalId,+ },+ ]);+ });+});++describe("insertTokenStyleSources", () => {+ test("inserts token sources and remaps their styles", () => {+ const breakpoints = toMap<Breakpoint>([+ { id: "base", label: "base" },+ { id: "desktop", label: "Desktop", minWidth: 1280 },+ ]);+ const styleSources: StyleSources = new Map([+ ["existing-token", { id: "existing-token", type: "token", name: "Old" }],+ ]);+ const styles: Styles = new Map();+ const fragmentStyleSources: StyleSource[] = [+ { id: "token", type: "token", name: "Primary" },+ ];+ const fragmentStyles: StyleDecl[] = [+ createStyleDecl("token", "old-desktop", "color", {+ type: "keyword",+ value: "red",+ }),+ ];++ const styleSourceIdMap = insertTokenStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ styleSources,+ styles,+ breakpoints,+ mergedBreakpointIds: new Map([["old-desktop", "desktop"]]),+ });++ const newTokenId = styleSourceIdMap.get("token");+ expect(newTokenId).toBeDefined();+ expect(newTokenId).not.toBe("token");+ expect(styleSources.get(newTokenId ?? "")).toMatchObject({+ type: "token",+ name: "Primary",+ });+ expect(Array.from(styles.values())).toEqual([+ {+ ...fragmentStyles[0],+ breakpointId: "desktop",+ styleSourceId: newTokenId,+ },+ ]);+ });+});+describe("deleteStyleSourceMutable", () => {test("deletes style source from styleSources map", () => {const styleSources: StyleSources = new Map([diff --git a/apps/builder/app/shared/style-source-utils.ts b/apps/builder/app/shared/style-source-utils.tsindex 324a908fb5..abb77c1707 100644--- a/apps/builder/app/shared/style-source-utils.ts+++ b/apps/builder/app/shared/style-source-utils.ts@@ -339,6 +339,57 @@ export const insertStyleSources = ({};};+export const insertTokenStyleSources = ({+ fragmentStyleSources,+ fragmentStyles,+ styleSources,+ styles,+ breakpoints,+ mergedBreakpointIds,+ conflictResolution = "theirs",+}: {+ fragmentStyleSources: StyleSource[];+ fragmentStyles: StyleDecl[];+ styleSources: StyleSources;+ styles: Styles;+ breakpoints: Map<Breakpoint["id"], Breakpoint>;+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;+ conflictResolution?: ConflictResolution;+}) => {+ const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =+ insertStyleSources({+ fragmentStyleSources,+ fragmentStyles,+ existingStyleSources: styleSources,+ existingStyles: styles,+ breakpoints,+ mergedBreakpointIds,+ conflictResolution,+ });++ for (const [id, styleSource] of updatedStyleSources) {+ styleSources.set(id, styleSource);+ }++ for (const styleDecl of fragmentStyles) {+ if (styleSourceIds.has(styleDecl.styleSourceId) === false) {+ continue;+ }+ const newStyleDecl: StyleDecl = {+ ...styleDecl,+ breakpointId:+ mergedBreakpointIds.get(styleDecl.breakpointId) ??+ styleDecl.breakpointId,+ styleSourceId:+ styleSourceIdMap.get(styleDecl.styleSourceId) ??+ styleDecl.styleSourceId,+ };+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);+ }++ return styleSourceIdMap;+};+/*** Insert local style sources for portal content without changing IDs.* Portal content IDs are preserved to avoid data bloat.@@ -395,9 +446,35 @@ export const insertPortalLocalStyleSources = ({}};+type InsertLocalStyleSourcesWithNewIdsOptions = {+ fragmentStyleSources: StyleSource[];+ fragmentStyleSourceSelections: StyleSourceSelection[];+ fragmentStyles: StyleDecl[];+ fragmentInstanceIds: Set<Instance["id"]>;+ newInstanceIds: Map<Instance["id"], Instance["id"]>;+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+} & (+ | {+ contentMode: true;+ breakpoints: Map<Breakpoint["id"], Breakpoint>;+ styleSourceIdMap?: Map<StyleSource["id"], StyleSource["id"]>;+ mergedBreakpointIds?: Map<Breakpoint["id"], Breakpoint["id"]>;+ }+ | {+ contentMode?: false;+ breakpoints?: Map<Breakpoint["id"], Breakpoint>;+ styleSourceIdMap: Map<StyleSource["id"], StyleSource["id"]>;+ mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;+ }+);+/**- * Insert local style sources with new IDs for regular (non-portal) content.- * Handles merging :root styles and token remapping.+ * Insert local style sources for copied fragment instances.+ * Regular mode duplicates local style sources, remaps token ids, and merges+ * :root local styles. Content mode keeps only local styles that can render with+ * existing breakpoints and reuses existing token ids.*/export const insertLocalStyleSourcesWithNewIds = ({fragmentStyleSources,@@ -405,24 +482,15 @@ export const insertLocalStyleSourcesWithNewIds = ({fragmentStyles,fragmentInstanceIds,newInstanceIds,- styleSourceIdMap,styleSources,styleSourceSelections,styles,- mergedBreakpointIds,-}: {- fragmentStyleSources: StyleSource[];- fragmentStyleSourceSelections: StyleSourceSelection[];- fragmentStyles: StyleDecl[];- fragmentInstanceIds: Set<Instance["id"]>;- newInstanceIds: Map<Instance["id"], Instance["id"]>;- styleSourceIdMap: Map<StyleSource["id"], StyleSource["id"]>;- styleSources: StyleSources;- styleSourceSelections: StyleSourceSelections;- styles: Styles;- mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;-}): void => {- const newLocalStyleSources = new Map();+ contentMode = false,+ breakpoints,+ styleSourceIdMap = new Map(),+ mergedBreakpointIds = new Map(),+}: InsertLocalStyleSourcesWithNewIdsOptions): void => {+ const newLocalStyleSources = new Map<StyleSource["id"], StyleSource>();for (const styleSource of fragmentStyleSources) {if (styleSource.type === "local") {newLocalStyleSources.set(styleSource.id, styleSource);@@ -433,13 +501,29 @@ export const insertLocalStyleSourcesWithNewIds = ({StyleSource["id"],StyleSource["id"]>();+ const copyableContentModeLocalStyleSourceIds = new Set<StyleSource["id"]>();+ if (contentMode) {+ for (const styleDecl of fragmentStyles) {+ if (+ newLocalStyleSources.has(styleDecl.styleSourceId) &&+ breakpoints?.has(styleDecl.breakpointId)+ ) {+ copyableContentModeLocalStyleSourceIds.add(styleDecl.styleSourceId);+ }+ }+ }for (const { instanceId, values } of fragmentStyleSourceSelections) {if (fragmentInstanceIds.has(instanceId) === false) {continue;}+ const newInstanceId = newInstanceIds.get(instanceId);+ if (contentMode && newInstanceId === undefined) {+ continue;+ }+ const targetInstanceId = newInstanceId ?? instanceId;const existingStyleSourceIds =- styleSourceSelections.get(instanceId)?.values ?? [];+ styleSourceSelections.get(targetInstanceId)?.values ?? [];let existingLocalStyleSource;for (const styleSourceId of existingStyleSourceIds) {const styleSource = styleSources.get(styleSourceId);@@ -451,8 +535,27 @@ export const insertLocalStyleSourcesWithNewIds = ({for (let styleSourceId of values) {const newLocalStyleSource = newLocalStyleSources.get(styleSourceId);if (newLocalStyleSource) {+ if (+ contentMode &&+ copyableContentModeLocalStyleSourceIds.has(styleSourceId) === false+ ) {+ continue;+ }+ if (contentMode) {+ const existingNewLocalStyleSourceId = newLocalStyleSourceIds.get(+ newLocalStyleSource.id+ );+ if (existingNewLocalStyleSourceId) {+ newStyleSourceIds.push(existingNewLocalStyleSourceId);+ continue;+ }+ }// merge only :root styles and duplicate others- if (instanceId === ROOT_INSTANCE_ID && existingLocalStyleSource) {+ if (+ contentMode === false &&+ instanceId === ROOT_INSTANCE_ID &&+ existingLocalStyleSource+ ) {// write local styles into existing local style sourcestyleSourceId = existingLocalStyleSource.id;} else {@@ -468,12 +571,20 @@ export const insertLocalStyleSourcesWithNewIds = ({if (mappedTokenId) {styleSourceId = mappedTokenId;}+ if (contentMode) {+ const styleSource = styleSources.get(styleSourceId);+ if (styleSource?.type !== "token") {+ continue;+ }+ }}newStyleSourceIds.push(styleSourceId);}- const newInstanceId = newInstanceIds.get(instanceId) ?? instanceId;- styleSourceSelections.set(newInstanceId, {- instanceId: newInstanceId,+ if (contentMode && newStyleSourceIds.length === 0) {+ continue;+ }+ styleSourceSelections.set(targetInstanceId, {+ instanceId: targetInstanceId,values: newStyleSourceIds,});}@@ -485,8 +596,16 @@ export const insertLocalStyleSourcesWithNewIds = ({...styleDecl,styleSourceId:newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId,- breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,+ breakpointId: contentMode+ ? breakpointId+ : (mergedBreakpointIds.get(breakpointId) ?? breakpointId),};+ if (+ contentMode &&+ breakpoints?.has(newStyleDecl.breakpointId) === false+ ) {+ continue;+ }styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);}}diff --git a/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts b/apps/builder/app/shared/sync/patch/patch-auth.server.test.tsindex 70fdfa44c4..ffcd6efcca 100644--- a/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts+++ b/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts@@ -2,6 +2,50 @@ import { beforeEach, describe, expect, test, vi } from "vitest";const hasProjectPermit = vi.hoisted(() => vi.fn());const readAccessToken = vi.hoisted(() => vi.fn());+const getContentModeCapabilities = vi.hoisted(() =>+ vi.fn(+ (input: {+ instances: Map<string, unknown>;+ metas: Map<string, unknown>;+ props: Map<string, unknown>;+ styleSources: Map<string, unknown>;+ styleSourceSelections: Map<string, unknown>;+ styles: Map<string, unknown>;+ breakpoints: Map<string, unknown>;+ }) => ({+ editablePropIds: new Set(),+ editableInstanceIds: new Set(),+ instances: input.instances,+ metas: input.metas,+ props: input.props,+ htmlTagsByInstanceId: new Map(),+ styleSources: input.styleSources,+ styleSourceSelections: input.styleSourceSelections,+ styles: input.styles,+ breakpoints: input.breakpoints,+ contentRootIds: new Set(),+ })+ )+);+const applyContentModeTransaction = vi.hoisted(() =>+ vi.fn(+ ({+ capabilities,+ transaction,+ }: {+ capabilities: Record<string, unknown>;+ transaction: { id: string; payload: Array<{ namespace: string }> };+ }) => {+ if (transaction.payload.some((change) => change.namespace === "styles")) {+ return { success: false, error: "build-only" };+ }+ return {+ success: true,+ capabilities: { ...capabilities, appliedTransactionId: transaction.id },+ };+ }+ )+);vi.mock("@webstudio-is/trpc-interface/index.server", () => {class AuthorizationError extends Error {}@@ -11,13 +55,9 @@ vi.mock("@webstudio-is/trpc-interface/index.server", () => {};});-vi.mock("@webstudio-is/project/index.server", () => ({- getRequiredPermitForBuildPatchTransaction: (transaction: {- payload: Array<{ namespace: string }>;- }) =>- transaction.payload.some((change) => change.namespace === "styles")- ? "build"- : "edit",+vi.mock("@webstudio-is/project/content-mode-permissions", () => ({+ applyContentModeTransaction,+ getContentModeCapabilities,}));vi.mock("~/env/env.server", () => ({@@ -32,30 +72,23 @@ vi.mock("~/services/token.server", () => ({import {authorizePatchEntries,+ createContentModeCapabilities,createWriterContext,} from "./patch-auth.server";import type { NormalizedPatchRequest } from "./patch-normalize.server";+const buildRow = {+ instances: JSON.stringify([+ { id: "body-1", type: "instance", component: "Body", children: [] },+ ]),+ props: JSON.stringify([]),+ styleSources: JSON.stringify([]),+ styleSourceSelections: JSON.stringify([]),+ styles: JSON.stringify([]),+ breakpoints: JSON.stringify([]),+};+const createContext = () => {- const buildRow = {- pages: JSON.stringify({- meta: {},- homePage: {- id: "page-1",- name: "Home",- path: "",- title: "Home",- meta: {},- rootInstanceId: "body-1",- },- pages: [],- folders: [{ id: "root", name: "Root", slug: "", children: [] }],- }),- instances: JSON.stringify([- { id: "body-1", type: "instance", component: "Body", children: [] },- ]),- props: JSON.stringify([]),- };const context = {authorization: { type: "anonymous" },createTokenContext: vi.fn(async (authToken: string) => ({@@ -145,6 +178,8 @@ describe("authorizePatchEntries", () => {beforeEach(() => {hasProjectPermit.mockReset();readAccessToken.mockReset();+ getContentModeCapabilities.mockClear();+ applyContentModeTransaction.mockClear();});test("checks every transaction with its own writer and required permit", async () => {@@ -169,13 +204,56 @@ describe("authorizePatchEntries", () => {],};- const result = await authorizePatchEntries(context as never, patch);+ const contentModeCapabilities = createContentModeCapabilities(buildRow);++ const result = await authorizePatchEntries(+ context as never,+ patch,+ contentModeCapabilities+ );expect(result.rejected).toEqual([]);expect(result.authorized[0].context.authorization).toMatchObject({type: "user",userId: "user-1",});+ expect(getContentModeCapabilities).toHaveBeenCalledWith(+ expect.objectContaining({+ instances: expect.any(Map),+ metas: expect.any(Map),+ props: expect.any(Map),+ styleSources: expect.any(Map),+ styleSourceSelections: expect.any(Map),+ styles: expect.any(Map),+ breakpoints: expect.any(Map),+ })+ );+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ transaction: patch.entries[0].transaction,+ capabilities: expect.objectContaining({+ editablePropIds: expect.any(Set),+ instances: expect.any(Map),+ metas: expect.any(Map),+ props: expect.any(Map),+ styleSources: expect.any(Map),+ styleSourceSelections: expect.any(Map),+ styles: expect.any(Map),+ breakpoints: expect.any(Map),+ contentRootIds: expect.any(Set),+ }),+ })+ );+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ transaction: patch.entries[1].transaction,+ capabilities: expect.objectContaining({+ appliedTransactionId: patch.entries[0].transaction.id,+ }),+ })+ );expect(hasProjectPermit).toHaveBeenCalledTimes(2);expect(hasProjectPermit).toHaveBeenNthCalledWith(1,@@ -193,24 +271,141 @@ describe("authorizePatchEntries", () => {);});- test("returns rejected entries when a writer does not have the required permit", async () => {- readAccessToken.mockResolvedValue({- userId: "user-1",+ test("does not require build permit after an authorized build-only transaction", async () => {+ readAccessToken+ .mockResolvedValueOnce({ userId: "user-1", projectId: "project-1" })+ .mockResolvedValueOnce({ userId: "user-2", projectId: "project-1" });+ hasProjectPermit.mockResolvedValue(true);++ const patch: NormalizedPatchRequest = {+ buildId: "build-1",projectId: "project-1",- });- hasProjectPermit.mockResolvedValue(false);+ clientVersion: 1,+ entries: [+ {+ transaction: transaction("styles", "tx-build") as never,+ writer: { type: "token", authToken: "token-1" },+ },+ {+ transaction: transaction("props", "tx-edit") as never,+ writer: { type: "token", authToken: "token-2" },+ },+ ],+ };- const result = await authorizePatchEntries(createContext() as never, {+ const result = await authorizePatchEntries(+ createContext() as never,+ patch,+ createContentModeCapabilities(buildRow)+ );++ expect(result.rejected).toEqual([]);+ expect(result.authorized).toHaveLength(2);+ expect(applyContentModeTransaction).toHaveBeenCalledTimes(2);+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ transaction: patch.entries[0].transaction,+ })+ );+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ transaction: patch.entries[1].transaction,+ })+ );+ expect(hasProjectPermit).toHaveBeenNthCalledWith(+ 1,+ { projectId: "project-1", permit: "build" },+ expect.anything()+ );+ expect(hasProjectPermit).toHaveBeenNthCalledWith(+ 2,+ { projectId: "project-1", permit: "edit" },+ expect.anything()+ );+ });++ test("does not require build permit after a rejected build-only transaction", async () => {+ readAccessToken+ .mockResolvedValueOnce({ userId: "user-1", projectId: "project-1" })+ .mockResolvedValueOnce({ userId: "user-2", projectId: "project-1" });+ hasProjectPermit.mockResolvedValueOnce(false).mockResolvedValueOnce(true);++ const patch: NormalizedPatchRequest = {buildId: "build-1",projectId: "project-1",clientVersion: 1,entries: [{- transaction: transaction("styles") as never,+ transaction: transaction("styles", "tx-build") as never,writer: { type: "token", authToken: "token-1" },},+ {+ transaction: transaction("props", "tx-edit") as never,+ writer: { type: "token", authToken: "token-2" },+ },],+ };++ const result = await authorizePatchEntries(+ createContext() as never,+ patch,+ createContentModeCapabilities(buildRow)+ );++ expect(result.rejected).toEqual([+ expect.objectContaining({+ entry: patch.entries[0],+ errors: "You don't have permission to build this project.",+ }),+ ]);+ expect(result.authorized).toEqual([+ expect.objectContaining({+ entry: patch.entries[1],+ }),+ ]);+ expect(applyContentModeTransaction).toHaveBeenCalledTimes(2);+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ transaction: patch.entries[1].transaction,+ })+ );+ expect(hasProjectPermit).toHaveBeenNthCalledWith(+ 1,+ { projectId: "project-1", permit: "build" },+ expect.anything()+ );+ expect(hasProjectPermit).toHaveBeenNthCalledWith(+ 2,+ { projectId: "project-1", permit: "edit" },+ expect.anything()+ );+ });++ test("returns rejected entries when a writer does not have the required permit", async () => {+ readAccessToken.mockResolvedValue({+ userId: "user-1",+ projectId: "project-1",});+ hasProjectPermit.mockResolvedValue(false);++ const result = await authorizePatchEntries(+ createContext() as never,+ {+ buildId: "build-1",+ projectId: "project-1",+ clientVersion: 1,+ entries: [+ {+ transaction: transaction("styles") as never,+ writer: { type: "token", authToken: "token-1" },+ },+ ],+ },+ createContentModeCapabilities(buildRow)+ );expect(result.authorized).toEqual([]);expect(result.rejected).toEqual([diff --git a/apps/builder/app/shared/sync/patch/patch-auth.server.ts b/apps/builder/app/shared/sync/patch/patch-auth.server.tsindex 966c7d95f1..f743197117 100644--- a/apps/builder/app/shared/sync/patch/patch-auth.server.ts+++ b/apps/builder/app/shared/sync/patch/patch-auth.server.ts@@ -4,7 +4,26 @@ import {type AppContext,type AuthPermit,} from "@webstudio-is/trpc-interface/index.server";-import { getRequiredPermitForBuildPatchTransaction } from "@webstudio-is/project/index.server";+import {+ applyContentModeTransaction,+ getContentModeCapabilities,+} from "@webstudio-is/project/content-mode-permissions";+import {+ coreMetas,+ type Breakpoint,+ type Prop,+ type StyleSource,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ parseData,+ parseInstanceData,+} from "@webstudio-is/project-build/build-parser.server";+import { parseStyleSourceSelections } from "@webstudio-is/project-build/style-source-selections.server";+import { parseStyles } from "@webstudio-is/project-build/styles.server";+import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";+import * as animationComponentMetas from "@webstudio-is/sdk-components-animation/metas";+import * as radixComponentMetas from "@webstudio-is/sdk-components-react-radix/metas";import env from "~/env/env.server";import { readAccessToken } from "~/services/token.server";import type {@@ -12,6 +31,15 @@ import type {PatchEntry,} from "./patch-normalize.server";+const componentMetas = new Map<string, WsComponentMeta>(+ Object.entries({+ ...coreMetas,+ ...baseComponentMetas,+ ...animationComponentMetas,+ ...radixComponentMetas,+ })+);+export type AuthorizedPatchEntry = {entry: PatchEntry;context: AppContext;@@ -82,21 +110,51 @@ export const assertProjectPermit = async ({}};+export const createContentModeCapabilities = (build: {+ instances: string;+ props: string;+ styleSources: string;+ styleSourceSelections: string;+ styles: string;+ breakpoints: string;+}) => {+ return getContentModeCapabilities({+ instances: parseInstanceData(build.instances),+ metas: componentMetas,+ props: parseData<Prop>(build.props),+ styleSources: parseData<StyleSource>(build.styleSources),+ styleSourceSelections: parseStyleSourceSelections(+ build.styleSourceSelections+ ),+ styles: parseStyles(build.styles),+ breakpoints: parseData<Breakpoint>(build.breakpoints),+ });+};+export const authorizePatchEntries = async (context: AppContext,- patch: NormalizedPatchRequest+ patch: NormalizedPatchRequest,+ contentModeCapabilities: ReturnType<typeof createContentModeCapabilities>) => {+ let capabilities = contentModeCapabilities;const authorized: AuthorizedPatchEntry[] = [];const rejected: RejectedPatchEntry[] = [];for (const entry of patch.entries) {try {const writerContext = await resolveEntryWriterContext(context, entry);+ const contentModeResult = applyContentModeTransaction({+ capabilities,+ transaction: entry.transaction,+ });await assertProjectPermit({context: writerContext,- permit: getRequiredPermitForBuildPatchTransaction(entry.transaction),+ permit: contentModeResult?.success ? "edit" : "build",projectId: patch.projectId,});+ if (contentModeResult?.success) {+ capabilities = contentModeResult.capabilities;+ }authorized.push({ entry, context: writerContext });} catch (error) {if (error instanceof AuthorizationError) {diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts b/apps/builder/app/shared/sync/patch/patch-service.server.test.tsindex 474477f1b8..4a1c9f98ec 100644--- a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts+++ b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts@@ -1,33 +1,59 @@import { beforeEach, describe, expect, test, vi } from "vitest";-const patchBuild = vi.hoisted(() => vi.fn());+const patchLoadedBuild = vi.hoisted(() => vi.fn());const authorizePatchEntries = vi.hoisted(() => vi.fn());+const createContentModeCapabilities = vi.hoisted(() =>+ vi.fn(() => ({ capabilities: true }))+);vi.mock("@webstudio-is/project/index.server", () => ({- patchBuild,+ patchLoadedBuild,}));vi.mock("./patch-auth.server", () => ({assertProjectPermit: vi.fn(),authorizePatchEntries,+ createContentModeCapabilities,createWriterContext: vi.fn(),}));-import { applyPatchRequest } from "./patch-service.server";+import {+ applyPatchRequest,+ loadAuthorizedPatchState,+} from "./patch-service.server";import type { NormalizedPatchRequest } from "./patch-normalize.server";+const buildRow = {+ projectId: "project-1",+ version: 3,+ instances: JSON.stringify([]),+ props: JSON.stringify([]),+ styleSources: JSON.stringify([]),+ styleSourceSelections: JSON.stringify([]),+ styles: JSON.stringify([]),+ breakpoints: JSON.stringify([]),+};+const createContext = () =>({postgrest: {client: {from: () => ({- select: () => ({- eq: () => ({- single: async () => ({- data: { projectId: "project-1", version: 3 },- error: undefined,- }),- }),+ select: (columns: string) => ({+ eq: () => {+ if (columns === "*") {+ return Promise.resolve({+ data: [buildRow],+ error: undefined,+ });+ }+ return {+ single: async () => ({+ data: buildRow,+ error: undefined,+ }),+ };+ },}),}),},@@ -59,8 +85,9 @@ const patch: NormalizedPatchRequest = {describe("applyPatchRequest", () => {beforeEach(() => {- patchBuild.mockReset();+ patchLoadedBuild.mockReset();authorizePatchEntries.mockReset();+ createContentModeCapabilities.mockClear();});test("returns per-entry partial results while applying authorized entries", async () => {@@ -73,12 +100,30 @@ describe("applyPatchRequest", () => {},],});- patchBuild.mockResolvedValue({ status: "ok", version: 4 });+ patchLoadedBuild.mockImplementation(async ({ build }) => ({+ status: "ok",+ version: 4,+ build: { ...build, version: 4 },+ }));const result = await applyPatchRequest(createContext(), patch);- expect(patchBuild).toHaveBeenCalledWith(+ expect(createContentModeCapabilities).toHaveBeenCalledWith({+ breakpoints: JSON.stringify([]),+ instances: JSON.stringify([]),+ props: JSON.stringify([]),+ styleSourceSelections: JSON.stringify([]),+ styleSources: JSON.stringify([]),+ styles: JSON.stringify([]),+ });+ expect(authorizePatchEntries).toHaveBeenCalledWith(+ expect.anything(),+ patch,+ { capabilities: true }+ );+ expect(patchLoadedBuild).toHaveBeenCalledWith(expect.objectContaining({+ build: expect.objectContaining({ version: 3 }),transactions: [patch.entries[1].transaction],}),{ writer: 2 }@@ -107,9 +152,13 @@ describe("applyPatchRequest", () => {],rejected: [],});- patchBuild+ patchLoadedBuild.mockResolvedValueOnce({ status: "error", errors: "batch failed" })- .mockResolvedValueOnce({ status: "ok", version: 4 })+ .mockImplementationOnce(async ({ build }) => ({+ status: "ok",+ version: 4,+ build: { ...build, version: 4 },+ })).mockResolvedValueOnce({ status: "error", errors: "entry failed" });const result = await applyPatchRequest(createContext(), patch);@@ -137,24 +186,34 @@ describe("applyPatchRequest", () => {],rejected: [],});- patchBuild- .mockResolvedValueOnce({ status: "ok", version: 4 })- .mockResolvedValueOnce({ status: "ok", version: 5 });+ patchLoadedBuild+ .mockImplementationOnce(async ({ build }) => ({+ status: "ok",+ version: 4,+ build: { ...build, version: 4 },+ }))+ .mockImplementationOnce(async ({ build }) => ({+ status: "ok",+ version: 5,+ build: { ...build, version: 5 },+ }));const result = await applyPatchRequest(createContext(), patch);- expect(patchBuild).toHaveBeenCalledTimes(2);- expect(patchBuild).toHaveBeenNthCalledWith(+ expect(patchLoadedBuild).toHaveBeenCalledTimes(2);+ expect(patchLoadedBuild).toHaveBeenNthCalledWith(1,expect.objectContaining({+ build: expect.objectContaining({ version: 3 }),clientVersion: 3,transactions: [patch.entries[0].transaction],}),{ writer: 1 });- expect(patchBuild).toHaveBeenNthCalledWith(+ expect(patchLoadedBuild).toHaveBeenNthCalledWith(2,expect.objectContaining({+ build: expect.objectContaining({ version: 4 }),clientVersion: 4,transactions: [patch.entries[1].transaction],}),@@ -197,7 +256,11 @@ describe("applyPatchRequest", () => {},],});- patchBuild.mockResolvedValue({ status: "ok", version: 4 });+ patchLoadedBuild.mockImplementation(async ({ build }) => ({+ status: "ok",+ version: 4,+ build: { ...build, version: 4 },+ }));const result = await applyPatchRequest(createContext(), duplicatePatch);@@ -225,9 +288,13 @@ describe("applyPatchRequest", () => {],rejected: [],});- patchBuild+ patchLoadedBuild.mockResolvedValueOnce({ status: "error", errors: "batch failed" })- .mockResolvedValueOnce({ status: "ok", version: 4 })+ .mockImplementationOnce(async ({ build }) => ({+ status: "ok",+ version: 4,+ build: { ...build, version: 4 },+ })).mockRejectedValueOnce(new Error("PostgREST unavailable"));await expect(applyPatchRequest(createContext(), patch)).rejects.toThrow(@@ -235,3 +302,24 @@ describe("applyPatchRequest", () => {);});});++describe("loadAuthorizedPatchState", () => {+ beforeEach(() => {+ createContentModeCapabilities.mockClear();+ });++ test("does not load content-mode capabilities for initial patch state", async () => {+ await expect(+ loadAuthorizedPatchState({+ authToken: "token",+ buildId: "build-1",+ context: createContext(),+ })+ ).resolves.toEqual({+ projectId: "project-1",+ version: 3,+ });++ expect(createContentModeCapabilities).not.toHaveBeenCalled();+ });+});diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.ts b/apps/builder/app/shared/sync/patch/patch-service.server.tsindex b87697b60c..bfc9daa0b0 100644--- a/apps/builder/app/shared/sync/patch/patch-service.server.ts+++ b/apps/builder/app/shared/sync/patch/patch-service.server.ts@@ -2,10 +2,12 @@ import {AuthorizationError,type AppContext,} from "@webstudio-is/trpc-interface/index.server";-import { patchBuild } from "@webstudio-is/project/index.server";+import { patchLoadedBuild } from "@webstudio-is/project/index.server";+import { loadRawBuildById } from "@webstudio-is/project-build/index.server";import {assertProjectPermit,authorizePatchEntries,+ createContentModeCapabilities,createWriterContext,type AuthorizedPatchEntry,} from "./patch-auth.server";@@ -76,15 +78,31 @@ const loadBuildState = async (context: AppContext, buildId: string) => {};};-const assertBuildProject = async (- context: AppContext,+const loadBuildPatchState = async (context: AppContext, buildId: string) => {+ const build = await loadRawBuildById(context, buildId);++ return {+ build,+ projectId: String(build.projectId),+ version: Number(build.version),+ contentModeCapabilities: createContentModeCapabilities({+ instances: build.instances,+ props: build.props,+ styleSources: build.styleSources,+ styleSourceSelections: build.styleSourceSelections,+ styles: build.styles,+ breakpoints: build.breakpoints,+ }),+ };+};++const assertBuildProject = (+ state: { projectId: string },patch: Pick<NormalizedPatchRequest, "buildId" | "projectId">) => {- const state = await loadBuildState(context, patch.buildId);if (state.projectId !== patch.projectId) {throw new Error("Build does not belong to project");}- return state;};const acceptedResult = (entry: PatchEntry): PatchEntryResult => ({@@ -115,13 +133,16 @@ const rejectedResult = ({const applyAuthorizedEntries = async ({authorized,+ build,patch,version,}: {authorized: AuthorizedPatchEntry[];+ build: Awaited<ReturnType<typeof loadBuildPatchState>>["build"];patch: NormalizedPatchRequest;version: number;}) => {+ let currentBuild = build;if (authorized.length === 0) {return {version,@@ -136,8 +157,9 @@ const applyAuthorizedEntries = async ({);if (hasSharedContext) {- const batchResult = await patchBuild(+ const batchResult = await patchLoadedBuild({+ build: currentBuild,buildId: patch.buildId,projectId: patch.projectId,clientVersion: version,@@ -147,6 +169,7 @@ const applyAuthorizedEntries = async ({);if (batchResult.status === "ok") {+ currentBuild = batchResult.build;return {status: "ok" as const,version: batchResult.version,@@ -163,8 +186,9 @@ const applyAuthorizedEntries = async ({let currentVersion = version;for (const { entry, context: entryContext } of authorized) {- const entryResult = await patchBuild(+ const entryResult = await patchLoadedBuild({+ build: currentBuild,buildId: patch.buildId,projectId: patch.projectId,clientVersion: currentVersion,@@ -175,6 +199,7 @@ const applyAuthorizedEntries = async ({if (entryResult.status === "ok") {currentVersion = entryResult.version;+ currentBuild = entryResult.build;entries.push(acceptedResult(entry));continue;}@@ -195,10 +220,16 @@ export const applyPatchRequest = async (context: AppContext,patch: NormalizedPatchRequest): Promise<PatchResult> => {- await assertBuildProject(context, patch);- const { authorized, rejected } = await authorizePatchEntries(context, patch);+ const state = await loadBuildPatchState(context, patch.buildId);+ assertBuildProject(state, patch);+ const { authorized, rejected } = await authorizePatchEntries(+ context,+ patch,+ state.contentModeCapabilities+ );const applied = await applyAuthorizedEntries({authorized,+ build: state.build,patch,version: patch.clientVersion,});diff --git a/apps/builder/app/shared/sync/project-queue.test.ts b/apps/builder/app/shared/sync/project-queue.test.tsindex 2339b58711..232a1d9296 100644--- a/apps/builder/app/shared/sync/project-queue.test.ts+++ b/apps/builder/app/shared/sync/project-queue.test.ts@@ -650,6 +650,49 @@ describe("project-queue", () => {vi.unstubAllGlobals();});+ test("partial response sets fatal status", async () => {+ vi.stubGlobal(+ "confirm",+ vi.fn(() => false)+ );++ mockBuildPatch.mockResolvedValue({+ status: "partial",+ version: 1,+ entries: [+ {+ seq: 0,+ transactionId: "tx-1",+ status: "failed",+ errors: "Patch failed",+ },+ ],+ });++ enqueueProjectDetails({+ projectId: "p1",+ buildId: "b1",+ version: 1,+ authPermit: "edit",+ authToken: "tok",+ });+ commandQueue.enqueue({+ type: "transactions",+ projectId: "p1",+ transactions: [makeTx("tx-1")],+ });++ await vi.advanceTimersByTimeAsync(NEW_ENTRIES_INTERVAL * 3);+ await flush();++ expect($syncStatus.get()).toEqual({+ status: "fatal",+ error: "Patch failed",+ });++ vi.unstubAllGlobals();+ });+test("fatal after MAX_ALLOWED_API_ERRORS unknown API errors", async () => {mockBuildPatch.mockResolvedValue({status: "unknown_error",diff --git a/apps/builder/app/shared/sync/project-queue.ts b/apps/builder/app/shared/sync/project-queue.tsindex c0fe337b22..ce45afe074 100644--- a/apps/builder/app/shared/sync/project-queue.ts+++ b/apps/builder/app/shared/sync/project-queue.ts@@ -345,6 +345,7 @@ export class ServerSyncStorage implements SyncStorage {sendTransaction(transaction: Transaction<Change[]>) {if (transaction.object === "server") {$lastTransactionId.set(transaction.id);+ $syncStatus.set({ status: "syncing" });commandQueue.enqueue({type: "transactions",transactions: [transaction],diff --git a/apps/builder/docker-compose.e2e.yaml b/apps/builder/docker-compose.e2e.yamlnew file mode 100644index 0000000000..18bb243e30--- /dev/null+++ b/apps/builder/docker-compose.e2e.yaml@@ -0,0 +1,29 @@+services:+ db:+ image: postgres:16+ environment:+ POSTGRES_DB: webstudio+ POSTGRES_USER: user+ POSTGRES_PASSWORD: pass+ ports:+ - "${E2E_PGPORT:-55432}:5432"+ tmpfs:+ - /var/lib/postgresql/data+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U user -d webstudio"]+ interval: 2s+ timeout: 2s+ retries: 30++ postgrest:+ image: postgrest/postgrest:v12.2.12+ depends_on:+ db:+ condition: service_healthy+ environment:+ PGRST_DB_URI: postgres://user:pass@db:5432/webstudio+ PGRST_DB_SCHEMAS: public+ PGRST_DB_ANON_ROLE: user+ PGRST_SERVER_PORT: 3000+ ports:+ - "${E2E_POSTGREST_PORT:-55433}:3000"diff --git a/apps/builder/e2e/db.ts b/apps/builder/e2e/db.tsnew file mode 100644index 0000000000..095393b508--- /dev/null+++ b/apps/builder/e2e/db.ts@@ -0,0 +1,122 @@+import { execFile } from "node:child_process";+import { promisify } from "node:util";+import { fileURLToPath } from "node:url";+import {+ createClient,+ type Database,+} from "@webstudio-is/postgrest/index.server";++const execFileAsync = promisify(execFile);++const postgrestUrl = process.env.POSTGREST_URL ?? "http://127.0.0.1:55433";+const postgrestApiKey = process.env.POSTGREST_API_KEY ?? "";+const composeFile = fileURLToPath(+ new URL("../docker-compose.e2e.yaml", import.meta.url)+);++const postgrest = createClient(postgrestUrl, postgrestApiKey);++const throwIfError = <Data>({+ error,+ data,+}: {+ error: { message: string } | null;+ data: Data;+}): NonNullable<Data> => {+ if (error) {+ throw new Error(error.message);+ }+ if (data === null || data === undefined) {+ throw new Error("Expected PostgREST response data");+ }+ return data;+};++export const resetDatabase = async () => {+ const sql = `+ DO $$+ DECLARE+ table_names text;+ BEGIN+ SELECT string_agg(format('%I.%I', schemaname, tablename), ', ')+ INTO table_names+ FROM pg_tables+ WHERE schemaname = 'public'+ AND tablename <> '_prisma_migrations';++ IF table_names IS NOT NULL THEN+ EXECUTE 'TRUNCATE TABLE ' || table_names || ' RESTART IDENTITY CASCADE';+ END IF;+ END $$;+ `;++ await execFileAsync(+ "docker",+ [+ "compose",+ "-f",+ composeFile,+ "exec",+ "-T",+ "db",+ "psql",+ "-U",+ "user",+ "-d",+ "webstudio",+ "-v",+ "ON_ERROR_STOP=1",+ "-c",+ sql,+ ],+ { maxBuffer: 1024 * 1024 }+ );+};++type Tables = Database["public"]["Tables"];++export const updateBuild = async (+ id: string,+ row: Tables["Build"]["Update"]+) => {+ return throwIfError(+ await postgrest.from("Build").update(row).eq("id", id).select().single()+ );+};++export const insertAuthorizationToken = async (+ row: Tables["AuthorizationToken"]["Insert"]+) => {+ return throwIfError(+ await postgrest.from("AuthorizationToken").insert(row).select().single()+ );+};++export const insertFile = async (row: Tables["File"]["Insert"]) => {+ return throwIfError(+ await postgrest.from("File").insert(row).select().single()+ );+};++export const insertAsset = async (row: Tables["Asset"]["Insert"]) => {+ return throwIfError(+ await postgrest.from("Asset").insert(row).select().single()+ );+};++export const loadDevBuild = async ({+ projectId,+}: {+ projectId: string;+}): Promise<Database["public"]["Tables"]["Build"]["Row"]> => {+ return throwIfError(+ await postgrest+ .from("Build")+ .select("*")+ .eq("projectId", projectId)+ .is("deployment", null)+ .order("createdAt", { ascending: false })+ .limit(1)+ .single()+ );+};diff --git a/apps/builder/e2e/fixtures/assets/replacement-image.svg b/apps/builder/e2e/fixtures/assets/replacement-image.svgnew file mode 100644index 0000000000..0f8942e434--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/replacement-image.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80">+ <rect width="120" height="80" fill="#ffe4d9" />+ <path d="M24 56 52 24l44 48H24Z" fill="#dc2626" />+</svg>diff --git a/apps/builder/e2e/fixtures/assets/upload-image.svg b/apps/builder/e2e/fixtures/assets/upload-image.svgnew file mode 100644index 0000000000..d195c83de5--- /dev/null+++ b/apps/builder/e2e/fixtures/assets/upload-image.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80">+ <rect width="120" height="80" fill="#d9e4ff" />+ <circle cx="60" cy="40" r="24" fill="#2563eb" />+</svg>diff --git a/apps/builder/e2e/fixtures/content-mode-project.ts b/apps/builder/e2e/fixtures/content-mode-project.tsnew file mode 100644index 0000000000..717b7d798a--- /dev/null+++ b/apps/builder/e2e/fixtures/content-mode-project.ts@@ -0,0 +1,819 @@+import {+ insertAsset,+ insertAuthorizationToken,+ insertFile,+ loadDevBuild,+ updateBuild,+} from "../db";++export type SeededContentModeProject = {+ projectId: string;+ buildId: string;+ editorToken: string;+ builderToken: string;+ initialVersion: number;+ listItemInstanceId: string;+ linkInstanceId: string;+ imageInstanceId: string;+ videoInstanceId: string;+ assetTemplateImageName: string;+ assetTemplateName: string;+ assetTemplateImageAlt: string;+ assetTemplateVideoName: string;+ imageReplacementTemplateName: string;+ imageReplacementTemplateImageAlt: string;+ contentPropsTemplateName: string;+ contentPropsTemplateLinkText: string;+ contentPropsTemplateImageAlt: string;+ contentPropsTemplateVideoName: string;+ editableTextTemplateName: string;+ editableTextTemplateText: string;+ shareLinkEditableText: string;+ collaborationTemplateName: string;+ collaborationTemplateText: string;+ styledHeadingTemplateName: string;+ styledHeadingTemplateText: string;+ styledHeadingTemplateFontSize: string;+ isolatedLocalTemplateName: string;+ isolatedLocalTemplateText: string;+ isolatedLocalTemplateFontSize: string;+ tokenTemplateName: string;+ tokenTemplateText: string;+ tokenTemplateFontSize: string;+ deletableTemplateName: string;+ deletableTemplateText: string;+ nestedTemplateName: string;+ nestedTemplateText: string;+ pageTemplateName: string;+ pageTemplateText: string;+ pageTemplateFontSize: string;+};++const assetTemplateName = "Asset Template";+const assetTemplateImageAlt = "Template asset image";+const assetTemplateImageName = "template-image.svg";+const assetTemplateVideoName = "template-video.mp4";+const assetTemplateImageAssetId = "asset-template-image-asset";+const assetTemplateVideoAssetId = "asset-template-video-asset";+const imageReplacementTemplateName = "Image Replacement Template";+const imageReplacementTemplateImageAlt = "Image replacement template image";+const contentPropsTemplateName = "Content Props Template";+const contentPropsTemplateLinkText = "Content props template link";+const contentPropsTemplateImageAlt = "Content props template image";+const contentPropsTemplateVideoName = "content-props-template-video.mp4";+const editableTextTemplateName = "Editable Text Template";+const editableTextTemplateText = "Editable template content";+const shareLinkEditableText = "Share link editable content";+const collaborationTemplateName = "Collaboration Template";+const collaborationTemplateText = "Collaboration template content";+const styledHeadingTemplateName = "Styled Heading Template";+const styledHeadingTemplateText = "Styled template heading";+const styledHeadingTemplateFontSize = "32px";+const isolatedLocalTemplateName = "Isolated Local Style Template";+const isolatedLocalTemplateText = "Isolated local heading";+const isolatedLocalTemplateFontSize = "34px";+const tokenTemplateName = "Token Template";+const tokenTemplateText = "Token styled heading";+const tokenTemplateFontSize = "36px";+const deletableTemplateName = "Deletable Template";+const deletableTemplateText = "Content block child to delete";+const nestedTemplateName = "Nested Template";+const nestedTemplateText = "Nested content descendant";+const pageTemplateName = "Content Page Template";+const pageTemplateText = "Content page template heading";+const pageTemplateFontSize = "38px";++const getBaseBreakpointId = (breakpoints: string) => {+ const parsedBreakpoints = JSON.parse(breakpoints) as Array<{+ id: string;+ minWidth?: number;+ maxWidth?: number;+ }>;+ return (+ parsedBreakpoints.find(+ (breakpoint) =>+ breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined+ )?.id ??+ parsedBreakpoints.at(0)?.id ??+ "base"+ );+};++const createContentModeBuildData = ({+ listItemInstanceId,+ linkInstanceId,+ imageInstanceId,+ videoInstanceId,+ seededAssetTemplateImageAssetId,+ seededAssetTemplateVideoAssetId,+ pages,+ breakpoints = JSON.stringify([]),+}: {+ listItemInstanceId: string;+ linkInstanceId: string;+ imageInstanceId: string;+ videoInstanceId: string;+ seededAssetTemplateImageAssetId: string;+ seededAssetTemplateVideoAssetId: string;+ pages: string;+ breakpoints?: string;+}) => {+ const rootInstanceId = "body";+ const contentBlockId = "content-block";+ const contentBlockTemplateId = "content-block-template";+ const assetTemplateId = "asset-template";+ const assetTemplateImageInstanceId = "asset-template-image";+ const assetTemplateVideoInstanceId = "asset-template-video";+ const imageReplacementTemplateId = "image-replacement-template";+ const imageReplacementTemplateImageInstanceId =+ "image-replacement-template-image";+ const contentPropsTemplateId = "content-props-template";+ const contentPropsTemplateLinkInstanceId = "content-props-template-link";+ const contentPropsTemplateImageInstanceId = "content-props-template-image";+ const contentPropsTemplateVideoInstanceId = "content-props-template-video";+ const editableTextTemplateId = "editable-text-template";+ const shareLinkEditableInstanceId = "share-link-editable-content";+ const collaborationTemplateId = "collaboration-template";+ const styledHeadingTemplateId = "styled-heading-template";+ const styledHeadingTemplateLocalStyleSourceId =+ "styled-heading-template-local-style-source";+ const isolatedLocalTemplateId = "isolated-local-template";+ const isolatedLocalTemplateStyleSourceId =+ "isolated-local-template-style-source";+ const tokenTemplateId = "token-template";+ const tokenTemplateStyleSourceId = "content-mode-token-style-source";+ const deletableTemplateId = "deletable-template";+ const nestedTemplateId = "nested-template";+ const nestedTemplateTextId = "nested-template-text";+ const pageTemplateId = "content-page-template";+ const pageTemplateRootId = "content-page-template-root";+ const pageTemplateHeadingId = "content-page-template-heading";+ const pageTemplateLocalStyleSourceId =+ "content-page-template-local-style-source";+ const baseBreakpointId = getBaseBreakpointId(breakpoints);+ const instances = [+ {+ type: "instance",+ id: rootInstanceId,+ component: "ws:element",+ tag: "body",+ children: [{ type: "id", value: contentBlockId }],+ },+ {+ type: "instance",+ id: contentBlockId,+ component: "ws:block",+ children: [+ { type: "id", value: listItemInstanceId },+ { type: "id", value: linkInstanceId },+ { type: "id", value: imageInstanceId },+ { type: "id", value: videoInstanceId },+ { type: "id", value: shareLinkEditableInstanceId },+ { type: "id", value: contentBlockTemplateId },+ ],+ },+ {+ type: "instance",+ id: contentBlockTemplateId,+ component: "ws:block-template",+ children: [+ { type: "id", value: assetTemplateId },+ { type: "id", value: styledHeadingTemplateId },+ { type: "id", value: isolatedLocalTemplateId },+ { type: "id", value: tokenTemplateId },+ { type: "id", value: imageReplacementTemplateId },+ { type: "id", value: contentPropsTemplateId },+ { type: "id", value: editableTextTemplateId },+ { type: "id", value: collaborationTemplateId },+ { type: "id", value: deletableTemplateId },+ { type: "id", value: nestedTemplateId },+ ],+ },+ {+ type: "instance",+ id: assetTemplateId,+ component: "ws:element",+ tag: "section",+ label: assetTemplateName,+ children: [+ { type: "id", value: assetTemplateImageInstanceId },+ { type: "id", value: assetTemplateVideoInstanceId },+ ],+ },+ {+ type: "instance",+ id: imageReplacementTemplateId,+ component: "ws:element",+ tag: "section",+ label: imageReplacementTemplateName,+ children: [+ { type: "id", value: imageReplacementTemplateImageInstanceId },+ ],+ },+ {+ type: "instance",+ id: contentPropsTemplateId,+ component: "ws:element",+ tag: "section",+ label: contentPropsTemplateName,+ children: [+ { type: "id", value: contentPropsTemplateLinkInstanceId },+ { type: "id", value: contentPropsTemplateImageInstanceId },+ { type: "id", value: contentPropsTemplateVideoInstanceId },+ ],+ },+ {+ type: "instance",+ id: editableTextTemplateId,+ component: "ws:element",+ tag: "p",+ label: editableTextTemplateName,+ children: [{ type: "text", value: editableTextTemplateText }],+ },+ {+ type: "instance",+ id: shareLinkEditableInstanceId,+ component: "ws:element",+ tag: "p",+ label: "Share Link Editable Content",+ children: [{ type: "text", value: shareLinkEditableText }],+ },+ {+ type: "instance",+ id: collaborationTemplateId,+ component: "ws:element",+ tag: "p",+ label: collaborationTemplateName,+ children: [{ type: "text", value: collaborationTemplateText }],+ },+ {+ type: "instance",+ id: listItemInstanceId,+ component: "ws:element",+ tag: "h1",+ label: "Heading",+ children: [{ type: "text", value: "Initial content" }],+ },+ {+ type: "instance",+ id: linkInstanceId,+ component: "Link",+ label: "Link",+ children: [{ type: "text", value: "Initial link" }],+ },+ {+ type: "instance",+ id: imageInstanceId,+ component: "Image",+ label: "Image",+ children: [],+ },+ {+ type: "instance",+ id: videoInstanceId,+ component: "Video",+ label: "Video",+ children: [],+ },+ {+ type: "instance",+ id: assetTemplateImageInstanceId,+ component: "Image",+ label: "Template Image",+ children: [],+ },+ {+ type: "instance",+ id: assetTemplateVideoInstanceId,+ component: "Video",+ label: "Template Video",+ children: [],+ },+ {+ type: "instance",+ id: imageReplacementTemplateImageInstanceId,+ component: "Image",+ label: "Image Replacement Template Image",+ children: [],+ },+ {+ type: "instance",+ id: contentPropsTemplateLinkInstanceId,+ component: "Link",+ label: "Content Props Template Link",+ children: [{ type: "text", value: contentPropsTemplateLinkText }],+ },+ {+ type: "instance",+ id: contentPropsTemplateImageInstanceId,+ component: "Image",+ label: "Content Props Template Image",+ children: [],+ },+ {+ type: "instance",+ id: contentPropsTemplateVideoInstanceId,+ component: "Video",+ label: "Content Props Template Video",+ children: [],+ },+ {+ type: "instance",+ id: styledHeadingTemplateId,+ component: "ws:element",+ tag: "h2",+ label: styledHeadingTemplateName,+ children: [{ type: "text", value: styledHeadingTemplateText }],+ },+ {+ type: "instance",+ id: isolatedLocalTemplateId,+ component: "ws:element",+ tag: "h2",+ label: isolatedLocalTemplateName,+ children: [{ type: "text", value: isolatedLocalTemplateText }],+ },+ {+ type: "instance",+ id: tokenTemplateId,+ component: "ws:element",+ tag: "h2",+ label: tokenTemplateName,+ children: [{ type: "text", value: tokenTemplateText }],+ },+ {+ type: "instance",+ id: deletableTemplateId,+ component: "ws:element",+ tag: "p",+ label: deletableTemplateName,+ children: [{ type: "text", value: deletableTemplateText }],+ },+ {+ type: "instance",+ id: nestedTemplateId,+ component: "ws:element",+ tag: "section",+ label: nestedTemplateName,+ children: [{ type: "id", value: nestedTemplateTextId }],+ },+ {+ type: "instance",+ id: nestedTemplateTextId,+ component: "ws:element",+ tag: "p",+ label: "Nested Text",+ children: [{ type: "text", value: nestedTemplateText }],+ },+ {+ type: "instance",+ id: pageTemplateRootId,+ component: "ws:element",+ tag: "body",+ children: [{ type: "id", value: pageTemplateHeadingId }],+ },+ {+ type: "instance",+ id: pageTemplateHeadingId,+ component: "ws:element",+ tag: "h1",+ label: "Page Template Heading",+ children: [{ type: "text", value: pageTemplateText }],+ },+ ];++ const props = [+ {+ id: "link-href-prop",+ instanceId: linkInstanceId,+ name: "href",+ type: "string",+ value: "/initial-link",+ },+ {+ id: "image-src-prop",+ instanceId: imageInstanceId,+ name: "src",+ type: "string",+ value:+ "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Crect width='120' height='80' fill='%23d9e4ff'/%3E%3C/svg%3E",+ },+ {+ id: "image-width-prop",+ instanceId: imageInstanceId,+ name: "width",+ type: "number",+ value: 120,+ },+ {+ id: "image-height-prop",+ instanceId: imageInstanceId,+ name: "height",+ type: "number",+ value: 80,+ },+ {+ id: "image-alt-prop",+ instanceId: imageInstanceId,+ name: "alt",+ type: "string",+ value: "Initial image alt",+ },+ {+ id: "video-src-prop",+ instanceId: videoInstanceId,+ name: "src",+ type: "string",+ value: "https://example.com/initial-video.mp4",+ },+ {+ id: "video-width-prop",+ instanceId: videoInstanceId,+ name: "width",+ type: "number",+ value: 120,+ },+ {+ id: "video-height-prop",+ instanceId: videoInstanceId,+ name: "height",+ type: "number",+ value: 80,+ },+ {+ id: "asset-template-image-src-prop",+ instanceId: assetTemplateImageInstanceId,+ name: "src",+ type: "asset",+ value: seededAssetTemplateImageAssetId,+ },+ {+ id: "asset-template-image-width-prop",+ instanceId: assetTemplateImageInstanceId,+ name: "width",+ type: "asset",+ value: seededAssetTemplateImageAssetId,+ },+ {+ id: "asset-template-image-height-prop",+ instanceId: assetTemplateImageInstanceId,+ name: "height",+ type: "asset",+ value: seededAssetTemplateImageAssetId,+ },+ {+ id: "asset-template-image-alt-prop",+ instanceId: assetTemplateImageInstanceId,+ name: "alt",+ type: "asset",+ value: seededAssetTemplateImageAssetId,+ },+ {+ id: "asset-template-video-src-prop",+ instanceId: assetTemplateVideoInstanceId,+ name: "src",+ type: "asset",+ value: seededAssetTemplateVideoAssetId,+ },+ {+ id: "image-replacement-template-image-src-prop",+ instanceId: imageReplacementTemplateImageInstanceId,+ name: "src",+ type: "string",+ value:+ "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Crect width='120' height='80' fill='%23ffe5d0'/%3E%3C/svg%3E",+ },+ {+ id: "image-replacement-template-image-width-prop",+ instanceId: imageReplacementTemplateImageInstanceId,+ name: "width",+ type: "number",+ value: 120,+ },+ {+ id: "image-replacement-template-image-height-prop",+ instanceId: imageReplacementTemplateImageInstanceId,+ name: "height",+ type: "number",+ value: 80,+ },+ {+ id: "image-replacement-template-image-alt-prop",+ instanceId: imageReplacementTemplateImageInstanceId,+ name: "alt",+ type: "string",+ value: imageReplacementTemplateImageAlt,+ },+ {+ id: "content-props-template-link-href-prop",+ instanceId: contentPropsTemplateLinkInstanceId,+ name: "href",+ type: "string",+ value: "/content-props-template-link",+ },+ {+ id: "content-props-template-image-src-prop",+ instanceId: contentPropsTemplateImageInstanceId,+ name: "src",+ type: "string",+ value:+ "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Crect width='120' height='80' fill='%23f3e8ff'/%3E%3C/svg%3E",+ },+ {+ id: "content-props-template-image-width-prop",+ instanceId: contentPropsTemplateImageInstanceId,+ name: "width",+ type: "number",+ value: 120,+ },+ {+ id: "content-props-template-image-height-prop",+ instanceId: contentPropsTemplateImageInstanceId,+ name: "height",+ type: "number",+ value: 80,+ },+ {+ id: "content-props-template-image-alt-prop",+ instanceId: contentPropsTemplateImageInstanceId,+ name: "alt",+ type: "string",+ value: contentPropsTemplateImageAlt,+ },+ {+ id: "content-props-template-video-src-prop",+ instanceId: contentPropsTemplateVideoInstanceId,+ name: "src",+ type: "string",+ value: `https://example.com/${contentPropsTemplateVideoName}`,+ },+ {+ id: "content-props-template-video-width-prop",+ instanceId: contentPropsTemplateVideoInstanceId,+ name: "width",+ type: "number",+ value: 120,+ },+ {+ id: "content-props-template-video-height-prop",+ instanceId: contentPropsTemplateVideoInstanceId,+ name: "height",+ type: "number",+ value: 80,+ },+ ];++ const nextPages = JSON.parse(pages) as {+ homePageId: string;+ pages: Array<{ id: string; rootInstanceId: string }>;+ pageTemplates?: Array<{+ id: string;+ name: string;+ title: string;+ rootInstanceId: string;+ meta: Record<string, unknown>;+ }>;+ };+ const homePage = nextPages.pages.find(+ (page) => page.id === nextPages.homePageId+ );+ if (homePage === undefined) {+ throw new Error("Expected existing build to have a home page");+ }+ homePage.rootInstanceId = rootInstanceId;+ nextPages.pageTemplates = [+ ...(nextPages.pageTemplates ?? []),+ {+ id: pageTemplateId,+ name: pageTemplateName,+ title: JSON.stringify(pageTemplateName),+ rootInstanceId: pageTemplateRootId,+ meta: {+ description: JSON.stringify("Page template description"),+ excludePageFromSearch: "false",+ language: JSON.stringify("en"),+ custom: [{ property: "template", content: JSON.stringify("content") }],+ },+ },+ ];++ return {+ pages: JSON.stringify(nextPages),+ instances: JSON.stringify(instances),+ props: JSON.stringify(props),+ styleSources: JSON.stringify([+ {+ type: "local",+ id: styledHeadingTemplateLocalStyleSourceId,+ },+ {+ type: "local",+ id: isolatedLocalTemplateStyleSourceId,+ },+ {+ type: "token",+ id: tokenTemplateStyleSourceId,+ name: "Content Mode Token",+ },+ {+ type: "local",+ id: pageTemplateLocalStyleSourceId,+ },+ ]),+ styleSourceSelections: JSON.stringify([+ {+ instanceId: styledHeadingTemplateId,+ values: [styledHeadingTemplateLocalStyleSourceId],+ },+ {+ instanceId: isolatedLocalTemplateId,+ values: [isolatedLocalTemplateStyleSourceId],+ },+ {+ instanceId: tokenTemplateId,+ values: [tokenTemplateStyleSourceId],+ },+ {+ instanceId: pageTemplateHeadingId,+ values: [pageTemplateLocalStyleSourceId],+ },+ ]),+ styles: JSON.stringify([+ {+ styleSourceId: styledHeadingTemplateLocalStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "fontSize",+ value: {+ type: "unit",+ unit: "px",+ value: Number.parseFloat(styledHeadingTemplateFontSize),+ },+ },+ {+ styleSourceId: isolatedLocalTemplateStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "fontSize",+ value: {+ type: "unit",+ unit: "px",+ value: Number.parseFloat(isolatedLocalTemplateFontSize),+ },+ },+ {+ styleSourceId: tokenTemplateStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "fontSize",+ value: {+ type: "unit",+ unit: "px",+ value: Number.parseFloat(tokenTemplateFontSize),+ },+ },+ {+ styleSourceId: pageTemplateLocalStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "fontSize",+ value: {+ type: "unit",+ unit: "px",+ value: Number.parseFloat(pageTemplateFontSize),+ },+ },+ ]),+ breakpoints,+ dataSources: JSON.stringify([]),+ resources: JSON.stringify([]),+ marketplaceProduct: JSON.stringify({}),+ };+};++export const prepareExistingContentModeProject = async ({+ projectId,+ editorToken = "e2e-editor-token",+ builderToken = "e2e-builder-token",+ listItemInstanceId = "list-item",+ linkInstanceId = "content-link",+ imageInstanceId = "content-image",+ videoInstanceId = "content-video",+ assetNamePrefix = "",+}: {+ projectId: string;+ editorToken?: string;+ builderToken?: string;+ listItemInstanceId?: string;+ linkInstanceId?: string;+ imageInstanceId?: string;+ videoInstanceId?: string;+ assetNamePrefix?: string;+}): Promise<SeededContentModeProject> => {+ const build = await loadDevBuild({ projectId });+ const seededAssetTemplateImageName = `${assetNamePrefix}${assetTemplateImageName}`;+ const seededAssetTemplateVideoName = `${assetNamePrefix}${assetTemplateVideoName}`;+ const seededAssetTemplateImageAssetId = `${assetNamePrefix}${assetTemplateImageAssetId}`;+ const seededAssetTemplateVideoAssetId = `${assetNamePrefix}${assetTemplateVideoAssetId}`;++ await Promise.all([+ insertFile({+ name: seededAssetTemplateImageName,+ format: "svg",+ size: 120,+ status: "UPLOADED",+ meta: JSON.stringify({ width: 120, height: 80 }),+ }),+ insertFile({+ name: seededAssetTemplateVideoName,+ format: "mp4",+ size: 120,+ status: "UPLOADED",+ meta: JSON.stringify({}),+ }),+ ]);+ await Promise.all([+ insertAsset({+ id: seededAssetTemplateImageAssetId,+ projectId,+ name: seededAssetTemplateImageName,+ filename: seededAssetTemplateImageName,+ description: assetTemplateImageAlt,+ }),+ insertAsset({+ id: seededAssetTemplateVideoAssetId,+ projectId,+ name: seededAssetTemplateVideoName,+ filename: seededAssetTemplateVideoName,+ description: "Template asset video",+ }),+ ]);++ await updateBuild(build.id, {+ version: 0,+ ...createContentModeBuildData({+ listItemInstanceId,+ linkInstanceId,+ imageInstanceId,+ videoInstanceId,+ seededAssetTemplateImageAssetId,+ seededAssetTemplateVideoAssetId,+ pages: build.pages,+ breakpoints: build.breakpoints,+ }),+ });++ await Promise.all([+ insertAuthorizationToken({+ token: editorToken,+ projectId,+ name: "E2E editor token",+ relation: "editors",+ }),+ insertAuthorizationToken({+ token: builderToken,+ projectId,+ name: "E2E builder token",+ relation: "builders",+ }),+ ]);++ return {+ projectId,+ buildId: build.id,+ editorToken,+ builderToken,+ initialVersion: 0,+ listItemInstanceId,+ linkInstanceId,+ imageInstanceId,+ videoInstanceId,+ assetTemplateImageName: seededAssetTemplateImageName,+ assetTemplateName,+ assetTemplateImageAlt,+ assetTemplateVideoName: seededAssetTemplateVideoName,+ imageReplacementTemplateName,+ imageReplacementTemplateImageAlt,+ contentPropsTemplateName,+ contentPropsTemplateLinkText,+ contentPropsTemplateImageAlt,+ contentPropsTemplateVideoName,+ editableTextTemplateName,+ editableTextTemplateText,+ shareLinkEditableText,+ collaborationTemplateName,+ collaborationTemplateText,+ styledHeadingTemplateName,+ styledHeadingTemplateText,+ styledHeadingTemplateFontSize,+ isolatedLocalTemplateName,+ isolatedLocalTemplateText,+ isolatedLocalTemplateFontSize,+ tokenTemplateName,+ tokenTemplateText,+ tokenTemplateFontSize,+ deletableTemplateName,+ deletableTemplateText,+ nestedTemplateName,+ nestedTemplateText,+ pageTemplateName,+ pageTemplateText,+ pageTemplateFontSize,+ };+};diff --git a/apps/builder/e2e/fixtures/content-mode-suite.ts b/apps/builder/e2e/fixtures/content-mode-suite.tsnew file mode 100644index 0000000000..38def19760--- /dev/null+++ b/apps/builder/e2e/fixtures/content-mode-suite.ts@@ -0,0 +1,68 @@+import { loginAndCreateBlankProject } from "../flows/dashboard";+import { newPage } from "../harness";+import { measure } from "../perf";+import {+ prepareExistingContentModeProject,+ type SeededContentModeProject,+} from "./content-mode-project";++type ContentModeProjectOptions = {+ email?: string;+ title?: string;+ devPlan?: string;+ assetNamePrefix?: string;+ editorToken?: string;+ builderToken?: string;+};++let sharedProject: SeededContentModeProject | undefined;++export const createContentModeProject = async ({+ email = "[email protected]",+ title = "Content Mode E2E",+ devPlan,+ assetNamePrefix,+ editorToken,+ builderToken,+}: ContentModeProjectOptions = {}) => {+ const ownerPage = await newPage();++ try {+ const projectId = await measure(+ "content mode fixture login/create project",+ async () =>+ await loginAndCreateBlankProject({+ page: ownerPage,+ email,+ title,+ devPlan,+ })+ );++ return await measure("content mode fixture prepare project", async () => {+ return await prepareExistingContentModeProject({+ projectId,+ assetNamePrefix,+ editorToken,+ builderToken,+ });+ });+ } finally {+ await ownerPage.close();+ }+};++export const setupSharedContentModeProject = async (+ options?: ContentModeProjectOptions+) => {+ sharedProject = await createContentModeProject(options);+ return sharedProject;+};++export const getSharedContentModeProject = () => {+ if (sharedProject === undefined) {+ throw new Error("Expected shared content-mode project to be initialized");+ }++ return sharedProject;+};diff --git a/apps/builder/e2e/flows/assertions.ts b/apps/builder/e2e/flows/assertions.tsnew file mode 100644index 0000000000..5c34493f06--- /dev/null+++ b/apps/builder/e2e/flows/assertions.ts@@ -0,0 +1,26 @@+import type { Locator, Page } from "playwright";++export const expectLocatorHidden = async ({+ locator,+ message,+}: {+ locator: Locator;+ message: string;+}) => {+ if (await locator.isVisible({ timeout: 1_000 }).catch(() => false)) {+ throw new Error(message);+ }+};++export const expectTextHidden = async ({+ page,+ text,+}: {+ page: Page;+ text: string;+}) => {+ await expectLocatorHidden({+ locator: page.getByText(text, { exact: true }).first(),+ message: `Expected text "${text}" to be hidden`,+ });+};diff --git a/apps/builder/e2e/flows/assets-panel.ts b/apps/builder/e2e/flows/assets-panel.tsnew file mode 100644index 0000000000..08b9cf364c--- /dev/null+++ b/apps/builder/e2e/flows/assets-panel.ts@@ -0,0 +1,107 @@+import path from "node:path";+import type { Page } from "playwright";+import { waitForChangeToBeSaved } from "./sync-status";++const assetFixturePath = (filename: string) =>+ path.join(process.cwd(), "e2e", "fixtures", "assets", filename);++const getAssetTitleLocator = ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const { name } = path.parse(filename);+ return page.locator(`[title^="${name}"]`).first();+};++export const openAssetsPanel = async ({ page }: { page: Page }) => {+ await page.getByRole("tab", { name: "Assets" }).click();+ await page.getByRole("button", { name: "Upload asset" }).waitFor();+};++export const uploadAsset = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const fileChooserPromise = page.waitForEvent("filechooser");+ await page.getByRole("button", { name: "Upload asset" }).click();+ const fileChooser = await fileChooserPromise;+ await fileChooser.setFiles(assetFixturePath(filename));+ const title = await waitForAsset({ page, filename });+ await waitForChangeToBeSaved({ page });+ return title;+};++export const openAssetDetails = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const asset = page.getByTitle(filename);+ await asset.hover();+ await asset.getByRole("button", { name: "Options" }).click();+ await page.getByText("Asset details").waitFor();+};++export const replaceSelectedAsset = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const fileChooserPromise = page.waitForEvent("filechooser");+ await page.getByRole("button", { name: "Replace asset" }).click();+ const fileChooser = await fileChooserPromise;+ await fileChooser.setFiles(assetFixturePath(filename));+ const title = await waitForAsset({ page, filename });+ await waitForChangeToBeSaved({ page });+ return title;+};++export const deleteSelectedAsset = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ await page.getByRole("button", { name: "Delete" }).click();+ await page.getByTitle(filename).waitFor({ state: "hidden" });+ await waitForChangeToBeSaved({ page });+};++export const waitForAsset = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const asset = getAssetTitleLocator({ page, filename });+ await asset.waitFor({ state: "visible", timeout: 30_000 });+ const title = await asset.getAttribute("title");+ if (title === null) {+ throw new Error(`Expected uploaded asset ${filename} to have a title`);+ }+ return title;+};++export const chooseAssetByFilename = async ({+ page,+ filename,+}: {+ page: Page;+ filename: string;+}) => {+ const title = await waitForAsset({ page, filename });+ await page.getByAltText(title, { exact: true }).last().click();+ return title;+};diff --git a/apps/builder/e2e/flows/block-outline.ts b/apps/builder/e2e/flows/block-outline.tsnew file mode 100644index 0000000000..deffe669e0--- /dev/null+++ b/apps/builder/e2e/flows/block-outline.ts@@ -0,0 +1,28 @@+import type { Page } from "playwright";+import { waitForCanvasFrame } from "./builder";+import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";++export const deleteContentBlockChildAfterCanvasText = async ({+ page,+ text,+}: {+ page: Page;+ text: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ await waitForSyncStatus({ page, status: "idle" });++ await page.keyboard.down("Alt");+ try {+ await canvas.getByText(text, { exact: true }).hover();+ const deleteButton = page+ .getByRole("button", { name: "Delete block" })+ .last();+ await deleteButton.waitFor({ state: "visible" });+ const save = waitForChangeToBeSaved({ page });+ await deleteButton.click();+ await save;+ } finally {+ await page.keyboard.up("Alt");+ }+};diff --git a/apps/builder/e2e/flows/builder.ts b/apps/builder/e2e/flows/builder.tsnew file mode 100644index 0000000000..f17e0fac80--- /dev/null+++ b/apps/builder/e2e/flows/builder.ts@@ -0,0 +1,148 @@+import type { Frame, Page } from "playwright";+import { getProjectBuilderUrl } from "../harness";++const delay = (ms: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, ms));++const builderNetworkIdleTimeout =+ Number.parseInt(process.env.E2E_BUILDER_NETWORK_IDLE_TIMEOUT_MS ?? "", 10) ||+ 5_000;++export const getCanvasFrame = async (page: Page) => {+ const iframe = await page.locator("iframe").first().elementHandle();+ return (await iframe?.contentFrame()) ?? undefined;+};++export const waitForCanvasFrame = async ({ page }: { page: Page }) => {+ try {+ await page.locator("iframe").first().waitFor({+ state: "attached",+ timeout: 30_000,+ });+ } catch (error) {+ const bodyText = await page+ .locator("body")+ .innerText()+ .catch(() => "");+ throw new Error(`Expected canvas iframe. Body: ${bodyText}`, {+ cause: error,+ });+ }++ const startedAt = Date.now();+ while (Date.now() - startedAt < 30_000) {+ const canvas = await getCanvasFrame(page);+ if (canvas !== undefined) {+ return canvas;+ }+ await delay(250);+ }++ throw new Error("Expected canvas frame");+};++export const waitForCanvasText = async ({+ page,+ text,+}: {+ page: Page;+ text: string;+}) => {+ const startedAt = Date.now();+ let lastError: unknown;++ while (Date.now() - startedAt < 30_000) {+ const canvas = await getCanvasFrame(page);+ if (canvas === undefined) {+ await delay(250);+ continue;+ }++ try {+ await canvas.getByText(text).waitFor({+ state: "visible",+ timeout: 1_000,+ });+ return;+ } catch (error) {+ lastError = error;+ await delay(250);+ }+ }++ const canvas = await getCanvasFrame(page);+ const frameText = await canvas+ ?.locator("body")+ .innerText()+ .catch(() => "");+ const frameHtml = await canvas+ ?.locator("body")+ .innerHTML()+ .catch(() => "");+ throw new Error(+ `Expected canvas text "${text}". Frame text: ${frameText}. Frame HTML: ${frameHtml}`,+ { cause: lastError }+ );+};++export const waitForCanvasTextHidden = async ({+ page,+ text,+}: {+ page: Page;+ text: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.getByText(text, { exact: true }).first().waitFor({+ state: "hidden",+ timeout: 30_000,+ });+};++export const dismissBlockingAlerts = async ({ page }: { page: Page }) => {+ const startedAt = Date.now();+ while (Date.now() - startedAt < 3_000) {+ const dismissButton = page.getByRole("button", { name: "Dismiss" });+ if (await dismissButton.isVisible({ timeout: 500 }).catch(() => false)) {+ await dismissButton.click();+ return;+ }+ await delay(100);+ }+};++export const openProjectBuilder = async ({+ page,+ projectId,+ authToken,+ mode,+}: {+ page: Page;+ projectId: string;+ authToken?: string;+ mode?: "content" | "preview";+}): Promise<Frame> => {+ await page.goto(getProjectBuilderUrl({ projectId, authToken, mode }));+ await page+ .waitForLoadState("networkidle", { timeout: builderNetworkIdleTimeout })+ .catch(() => undefined);+ const canvas = await waitForCanvasFrame({ page });+ await dismissBlockingAlerts({ page });+ return canvas;+};++export const openBuilderUrl = async ({+ page,+ url,+}: {+ page: Page;+ url: string;+}): Promise<Frame> => {+ await page.goto(url);+ await page+ .waitForLoadState("networkidle", { timeout: builderNetworkIdleTimeout })+ .catch(() => undefined);+ const canvas = await waitForCanvasFrame({ page });+ await dismissBlockingAlerts({ page });+ return canvas;+};diff --git a/apps/builder/e2e/flows/canvas-media.ts b/apps/builder/e2e/flows/canvas-media.tsnew file mode 100644index 0000000000..4af9ff8bc0--- /dev/null+++ b/apps/builder/e2e/flows/canvas-media.ts@@ -0,0 +1,66 @@+import type { Page } from "playwright";+import { waitForCanvasFrame } from "./builder";++export const waitForCanvasImage = async ({+ page,+ alt,+}: {+ page: Page;+ alt: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.getByRole("img", { name: alt }).waitFor({+ state: "visible",+ timeout: 10_000,+ });+};++export const waitForCanvasImageSourceName = async ({+ page,+ sourceName,+}: {+ page: Page;+ sourceName: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.locator(`img[src*="${sourceName}"]`).waitFor({+ state: "visible",+ timeout: 10_000,+ });+};++export const selectCanvasImage = async ({+ page,+ alt,+}: {+ page: Page;+ alt: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.getByRole("img", { name: alt }).click();+};++export const waitForCanvasVideoSource = async ({+ page,+ sourceName,+}: {+ page: Page;+ sourceName: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.locator(`video[src*="${sourceName}"]`).waitFor({+ state: "visible",+ timeout: 10_000,+ });+};++export const selectCanvasVideoSource = async ({+ page,+ sourceName,+}: {+ page: Page;+ sourceName: string;+}) => {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.locator(`video[src*="${sourceName}"]`).click();+};diff --git a/apps/builder/e2e/flows/canvas-selection.ts b/apps/builder/e2e/flows/canvas-selection.tsnew file mode 100644index 0000000000..4e34ae3060--- /dev/null+++ b/apps/builder/e2e/flows/canvas-selection.ts@@ -0,0 +1,81 @@+import type { Page } from "playwright";+import { waitForCanvasFrame } from "./builder";++const delay = (ms: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, ms));++export const selectCanvasTextInstanceForProps = async ({+ page,+ text,+ propertyLabel,+}: {+ page: Page;+ text: string;+ propertyLabel: string;+}) => {+ const startedAt = Date.now();+ let lastBodyText = "";++ while (Date.now() - startedAt < 10_000) {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.getByText(text).click();+ await delay(300);+ await page.keyboard.press("Escape");++ if (+ await page+ .getByText(propertyLabel, { exact: true })+ .first()+ .isVisible({ timeout: 500 })+ .catch(() => false)+ ) {+ return;+ }++ lastBodyText = await page+ .locator("body")+ .innerText()+ .catch(() => "");+ await delay(250);+ }++ throw new Error(+ `Expected selected canvas text "${text}" to show property "${propertyLabel}". Page text: ${lastBodyText}`+ );+};++export const selectCanvasTextInstance = async ({+ page,+ text,+}: {+ page: Page;+ text: string;+}) => {+ const startedAt = Date.now();+ let lastBodyText = "";++ while (Date.now() - startedAt < 10_000) {+ const canvas = await waitForCanvasFrame({ page });+ await canvas.getByText(text).click();+ await delay(300);++ if (+ (await page+ .getByText("No instance selected", { exact: true })+ .isVisible({ timeout: 500 })+ .catch(() => false)) === false+ ) {+ return;+ }++ lastBodyText = await page+ .locator("body")+ .innerText()+ .catch(() => "");+ await delay(250);+ }++ throw new Error(+ `Expected to select canvas text "${text}". Page text: ${lastBodyText}`+ );+};diff --git a/apps/builder/e2e/flows/canvas-style.ts b/apps/builder/e2e/flows/canvas-style.tsnew file mode 100644index 0000000000..19f68128df--- /dev/null+++ b/apps/builder/e2e/flows/canvas-style.ts@@ -0,0 +1,119 @@+import type { Page } from "playwright";+import { getCanvasFrame } from "./builder";++const delay = (ms: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, ms));++const getVisibleCanvasTextStyleValues = async ({+ page,+ text,+ property,+}: {+ page: Page;+ text: string;+ property: string;+}) => {+ const canvas = await getCanvasFrame(page);+ if (canvas === undefined) {+ return;+ }++ const locator = canvas.getByText(text);+ const total = await locator.count();+ const values = [];+ for (let index = 0; index < total; index += 1) {+ const item = locator.nth(index);+ if (+ (await item.isVisible({ timeout: 1_000 }).catch(() => false)) === false+ ) {+ continue;+ }+ values.push(+ await item.evaluate(+ (element, cssProperty) =>+ element.ownerDocument.defaultView+ ?.getComputedStyle(element)+ .getPropertyValue(cssProperty) ?? "",+ property+ )+ );+ }+ return values;+};++export const waitForCanvasTextStyle = async ({+ page,+ text,+ property,+ value,+}: {+ page: Page;+ text: string;+ property: string;+ value: string;+}) => {+ const startedAt = Date.now();+ let lastValue = "";++ while (Date.now() - startedAt < 30_000) {+ const values = await getVisibleCanvasTextStyleValues({+ page,+ text,+ property,+ });+ if (values === undefined) {+ await delay(250);+ continue;+ }++ lastValue = values[0] ?? "";+ if (lastValue === value) {+ return;+ }+ await delay(250);+ }++ throw new Error(+ `Expected canvas text "${text}" to have ${property}: ${value}. Last value: ${lastValue}`+ );+};++export const waitForCanvasTextStyleCount = async ({+ page,+ text,+ property,+ value,+ count,+}: {+ page: Page;+ text: string;+ property: string;+ value: string;+ count: number;+}) => {+ const startedAt = Date.now();+ let lastValues: string[] = [];++ while (Date.now() - startedAt < 30_000) {+ const values = await getVisibleCanvasTextStyleValues({+ page,+ text,+ property,+ });+ if (values === undefined) {+ await delay(250);+ continue;+ }++ lastValues = values;++ if (lastValues.filter((item) => item === value).length === count) {+ return;+ }+ await delay(250);+ }++ throw new Error(+ `Expected ${count} visible canvas texts "${text}" to have ${property}: ${value}. Last values: ${lastValues.join(", ")}`+ );+};diff --git a/apps/builder/e2e/flows/content-editing.ts b/apps/builder/e2e/flows/content-editing.tsnew file mode 100644index 0000000000..92d3ca1ac7--- /dev/null+++ b/apps/builder/e2e/flows/content-editing.ts@@ -0,0 +1,117 @@+import type { Locator, Page } from "playwright";+import {+ getCanvasFrame,+ waitForCanvasFrame,+ waitForCanvasText,+} from "./builder";+import { waitForChangeToBeSaved } from "./sync-status";++const delay = (ms: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, ms));++const startCanvasTextEditing = async ({+ target,+ editable,+}: {+ target: Locator;+ editable: Locator;+}) => {+ await target.click();+ if (await editable.isVisible({ timeout: 2_000 }).catch(() => false)) {+ return;+ }++ await target.click();+ await target.press("Enter");+ if (await editable.isVisible({ timeout: 2_000 }).catch(() => false)) {+ return;+ }++ await target.dblclick();+ await editable.waitFor({ state: "visible", timeout: 2_000 });+};++export const waitForContentEditMode = async ({ page }: { page: Page }) => {+ const canvas = await waitForCanvasFrame({ page });+ await canvas+ .locator("body[data-ws-content-edit-mode='ready']")+ .waitFor({ state: "visible", timeout: 10_000 });+};++export const replaceCanvasText = async ({+ page,+ currentText,+ text,+}: {+ page: Page;+ currentText: string;+ text: string;+}) => {+ await waitForContentEditMode({ page });++ const startedAt = Date.now();+ let lastError: unknown;+ let frameHtml = "";+ let activated = false;++ while (Date.now() - startedAt < 10_000) {+ const canvas = await getCanvasFrame(page);+ if (canvas === undefined) {+ await delay(250);+ continue;+ }++ try {+ const target = canvas.getByText(currentText);+ await target.waitFor({ state: "visible", timeout: 1_000 });++ const editable = canvas.locator("[contenteditable]");++ await startCanvasTextEditing({ target, editable });+ await editable.click();+ await page.keyboard.press("ControlOrMeta+A");+ frameHtml = await canvas+ .locator("body")+ .innerHTML()+ .catch(() => "");+ activated = true;+ break;+ } catch (error) {+ lastError = error;+ await delay(250);+ }+ }++ if (frameHtml === "") {+ const canvas = await getCanvasFrame(page);+ frameHtml =+ (await canvas+ ?.locator("body")+ .innerHTML()+ .catch(() => "")) ?? "";+ }++ if (activated === false) {+ throw new Error(+ `Expected to edit canvas text "${currentText}". Frame HTML: ${frameHtml}`,+ { cause: lastError }+ );+ }++ const canvas = await getCanvasFrame(page);+ if (canvas === undefined) {+ throw new Error("Expected canvas frame after text editing started");+ }+ const editable = canvas.locator("[contenteditable]");+ const save = waitForChangeToBeSaved({ page });+ try {+ await page.keyboard.type(text);+ await canvas.locator("body").click({ position: { x: 1, y: 1 } });+ await editable.waitFor({ state: "hidden", timeout: 1_000 });+ await waitForCanvasText({ page, text });+ await save;+ } catch (error) {+ await save.catch(() => undefined);+ throw error;+ }+};diff --git a/apps/builder/e2e/flows/dashboard.ts b/apps/builder/e2e/flows/dashboard.tsnew file mode 100644index 0000000000..28566f6b9d--- /dev/null+++ b/apps/builder/e2e/flows/dashboard.ts@@ -0,0 +1,113 @@+import { dashboardUrl, getProjectIdFromBuilderUrl } from "../harness";+import type { Page } from "playwright";++const loginReadyTimeout = 30_000;++export const loginWithSecret = async ({+ page,+ email,+ devPlan,+}: {+ page: Page;+ email: string;+ devPlan?: string;+}) => {+ if (devPlan !== undefined) {+ await page.context().clearCookies();+ }++ console.info("e2e: opening login");+ await page.goto(`${dashboardUrl}/login`);+ const loginWithSecretButton = page.getByRole("button", {+ name: "Login with Secret",+ });+ let loginState: "login" | "dashboard";+ try {+ loginState = await Promise.any([+ loginWithSecretButton+ .waitFor({ state: "visible", timeout: loginReadyTimeout })+ .then(() => "login" as const),+ page+ .waitForURL(`${dashboardUrl}/dashboard`, {+ timeout: loginReadyTimeout,+ })+ .then(() => "dashboard" as const),+ ]);+ } catch (error) {+ const bodyText = await page+ .locator("body")+ .innerText()+ .catch(() => "");+ throw new Error(+ `Expected login page or dashboard at ${page.url()}. Body: ${bodyText}`,+ { cause: error }+ );+ }+ if (loginState === "dashboard") {+ console.info("e2e: dashboard loaded");+ return;+ }+ await loginWithSecretButton.click();+ await page.getByPlaceholder("Auth secret").fill("test");+ await page.getByPlaceholder("Email (optional)").fill(email);+ if (devPlan !== undefined) {+ await page.locator('select[name="devPlan"]').selectOption(devPlan);+ }+ console.info("e2e: submitting dev login");+ await page.getByRole("button", { name: "Login" }).click();+ await page.waitForURL(`${dashboardUrl}/dashboard`);+ console.info("e2e: dashboard loaded");+};++export const createBlankProject = async ({+ page,+ title,+}: {+ page: Page;+ title: string;+}) => {+ const createProjectButton = page.getByRole("button", {+ name: /Create a blank project|New project/,+ });+ try {+ await createProjectButton.waitFor({ state: "visible", timeout: 10_000 });+ } catch (error) {+ const bodyText = await page+ .locator("body")+ .innerText()+ .catch(() => "");+ throw new Error(+ `Expected dashboard create-project button at ${page.url()}. Body: ${bodyText}`,+ { cause: error }+ );+ }++ console.info("e2e: opening create project dialog");+ await createProjectButton.click();+ await page.getByPlaceholder("My Project").fill(title);+ console.info("e2e: submitting create project");+ await page.getByRole("button", { name: "Create Project" }).click();+ await page.waitForURL(/https:\/\/p-[^.]+\.wstd\.dev:\d+\//);+ console.info(`e2e: created project at ${page.url()}`);++ const projectId = getProjectIdFromBuilderUrl(page.url());+ if (projectId === undefined) {+ throw new Error(`Expected builder URL, received ${page.url()}`);+ }+ return projectId;+};++export const loginAndCreateBlankProject = async ({+ page,+ email,+ title,+ devPlan,+}: {+ page: Page;+ email: string;+ title: string;+ devPlan?: string;+}) => {+ await loginWithSecret({ page, email, devPlan });+ return await createBlankProject({ page, title });+};diff --git a/apps/builder/e2e/flows/pages-panel.ts b/apps/builder/e2e/flows/pages-panel.tsnew file mode 100644index 0000000000..6abb4cd181--- /dev/null+++ b/apps/builder/e2e/flows/pages-panel.ts@@ -0,0 +1,254 @@+import type { Locator, Page } from "playwright";+import { expectLocatorHidden, expectTextHidden } from "./assertions";+import { waitForCanvasText } from "./builder";+import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";++const getPageSettingsControl = ({+ page,+ label,+}: {+ page: Page;+ label: string | RegExp;+}): Locator => {+ if (typeof label === "string") {+ return page.getByLabel(label, { exact: true });+ }+ return page.getByLabel(label);+};++export const getPageSettingsPathInput = ({ page }: { page: Page }) =>+ page.getByRole("textbox", { name: "Path", exact: true });++export const fillAllowedPageSettings = async ({+ page,+ name,+ path,+ title,+ description,+ language,+ socialImage,+ metadata,+}: {+ page: Page;+ name: string;+ path: string;+ title: string;+ description: string;+ language: string;+ socialImage: string;+ metadata: {+ property: string;+ content: string;+ };+}) => {+ await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(+ () => undefined+ );++ const metadataGroup = getCustomMetadataGroup(page);+ const save = waitForChangeToBeSaved({ page });+ for (const field of [+ { label: "Page name", value: name },+ { label: "Path", value: path },+ { label: "Title", value: title },+ { label: "Description", value: description },+ { label: "Language", value: language },+ ]) {+ const control = getPageSettingsControl({+ page,+ label: field.label,+ });+ await control.fill(field.value);+ await control.blur();+ }+ await page.getByLabel("Exclude this page from search results").click();+ const socialImageInput = page.getByPlaceholder("https://www.url.com").first();+ await socialImageInput.fill(socialImage);+ await socialImageInput.blur();+ await metadataGroup+ .getByLabel("Property", { exact: true })+ .first()+ .fill(metadata.property);+ await metadataGroup.getByLabel("Property", { exact: true }).first().blur();+ await metadataGroup+ .getByLabel("Content", { exact: true })+ .first()+ .fill(metadata.content);+ await metadataGroup.getByLabel("Content", { exact: true }).first().blur();+ await save;+ await waitForSyncStatus({ page, status: "idle" });+};++export const openPagesPanel = async ({ page }: { page: Page }) => {+ const tab = page.getByRole("tab", { name: "Pages" });+ if ((await tab.getAttribute("aria-selected")) !== "true") {+ await tab.click();+ }+ await page.getByText("Pages", { exact: true }).first().waitFor({+ state: "visible",+ timeout: 10_000,+ });+};++export const openPageSettings = async ({+ page,+ pageName,+}: {+ page: Page;+ pageName: string;+}) => {+ await openPagesPanel({ page });+ const pageRow = page.getByRole("group", { name: `Page ${pageName}` });+ await pageRow.hover();+ await pageRow.getByRole("button", { name: "Open page settings" }).click();+ await page.getByText("Page settings", { exact: true }).waitFor();+};++export const openPage = async ({+ page,+ pageName,+ canvasText,+}: {+ page: Page;+ pageName: string;+ canvasText: string;+}) => {+ await openPagesPanel({ page });+ await page.getByText(pageName, { exact: true }).first().click();+ await waitForCanvasText({ page, text: canvasText });+ await waitForSyncStatus({ page, status: "idle" });+};++export const createPageFromTemplate = async ({+ page,+ templateName,+ pageName,+ canvasText,+}: {+ page: Page;+ templateName: string;+ pageName: string;+ canvasText: string;+}) => {+ await openPagesPanel({ page });+ const template = page.getByText(templateName, { exact: true }).first();+ await template.scrollIntoViewIfNeeded();+ await template.hover();+ await page.getByRole("button", { name: "Create page from template" }).click();+ await page.getByText("Create page from template", { exact: true }).waitFor();++ await page.getByLabel("Page name").fill(pageName);+ const save = waitForChangeToBeSaved({ page });+ await page.getByRole("button", { name: "Create page", exact: true }).click();+ await save;++ await waitForCanvasText({ page, text: canvasText });+ await waitForSyncStatus({ page, status: "idle" });+};++export const choosePageSettingsSocialImageAsset = async ({+ page,+ filename,+ label = filename,+}: {+ page: Page;+ filename: string;+ label?: string;+}) => {+ await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(+ () => undefined+ );+ await page.getByRole("button", { name: "Choose image from assets" }).click();+ const save = waitForChangeToBeSaved({ page });+ await page.getByAltText(label, { exact: true }).click();+ await save;+ await page.getByText(filename, { exact: true }).waitFor();+};++const getCustomMetadataGroup = (page: Page) =>+ page.getByRole("group", { name: "Custom metadata" });++export const expectCustomMetadataValue = async ({+ page,+ property,+ content,+}: {+ page: Page;+ property: string;+ content: string;+}) => {+ const metadata = getCustomMetadataGroup(page);+ if (+ (await metadata+ .getByLabel("Property", { exact: true })+ .first()+ .inputValue()) !== property+ ) {+ throw new Error("Expected edited custom metadata property to persist");+ }+ if (+ (await metadata+ .getByLabel("Content", { exact: true })+ .first()+ .inputValue()) !== content+ ) {+ throw new Error("Expected edited custom metadata content to persist");+ }+};++export const expectContentModePageSettingsRestrictions = async ({+ page,+}: {+ page: Page;+}) => {+ await expectTextHidden({ page, text: "Authentication" });+ await expectTextHidden({ page, text: "Redirect " });+ await expectTextHidden({ page, text: "Document type" });+ await expectTextHidden({ page, text: "Status code " });+ await expectTextHidden({+ page,+ text: "The plain text content served for this page.",+ });+ await expectTextHidden({ page, text: "Marketplace" });+ await expectLocatorHidden({+ locator: page.getByLabel(/Make .* the home page/),+ message: "Expected home page control to be unavailable in content mode",+ });+ await expectLocatorHidden({+ locator: page.getByRole("button", { name: "Delete page" }),+ message: "Expected page deletion to be unavailable in content mode",+ });+ await expectLocatorHidden({+ locator: page.getByRole("button", { name: "Duplicate page" }),+ message: "Expected page duplication to be unavailable in content mode",+ });+};++export const expectContentModePagePathError = async ({+ page,+}: {+ page: Page;+}) => {+ await getPageSettingsPathInput({ page }).hover();+ await page+ .getByRole("tooltip")+ .getByText("Editors can only set static page paths")+ .waitFor({ state: "visible" });+};++export const expectContentModeTemplateActionsUnavailable = async ({+ page,+ templateName,+}: {+ page: Page;+ templateName: string;+}) => {+ await openPagesPanel({ page });+ const template = page.getByText(templateName, { exact: true }).first();+ await template.scrollIntoViewIfNeeded();+ await template.hover();+ await expectLocatorHidden({+ locator: page.getByRole("button", { name: "Open template settings" }),+ message: "Expected template settings to be unavailable in content mode",+ });+};diff --git a/apps/builder/e2e/flows/props-panel.ts b/apps/builder/e2e/flows/props-panel.tsnew file mode 100644index 0000000000..89e161fff7--- /dev/null+++ b/apps/builder/e2e/flows/props-panel.ts@@ -0,0 +1,110 @@+import type { Page } from "playwright";+import { chooseAssetByFilename } from "./assets-panel";+import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";++const getPropertyLabel = ({ page, label }: { page: Page; label: string }) =>+ page.getByText(label, { exact: true }).first();++export const fillSelectedStringProperty = async ({+ page,+ label,+ control,+ value,+}: {+ page: Page;+ label: string;+ control: "url" | "text";+ value: string;+}) => {+ await getPropertyLabel({ page, label }).waitFor({+ state: "visible",+ timeout: 10_000,+ });++ const input = getPropertyInput({ page, control });+ await input.waitFor({ state: "visible", timeout: 10_000 });++ await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(+ () => undefined+ );+ const save = waitForChangeToBeSaved({ page });+ await input.fill(value);+ await input.blur();+ await save;+};++export const chooseSelectedAssetProperty = async ({+ page,+ label,+ assetLabel,+ assetFilename,+ triggerName = "Choose source",+}: {+ page: Page;+ label: string;+ assetLabel?: string;+ assetFilename?: string;+ triggerName?: string | RegExp;+}) => {+ await getPropertyLabel({ page, label }).waitFor({+ state: "visible",+ timeout: 10_000,+ });++ await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(+ () => undefined+ );+ await page.getByRole("button", { name: triggerName }).click();+ const save = waitForChangeToBeSaved({ page });+ if (assetFilename !== undefined) {+ await chooseAssetByFilename({ page, filename: assetFilename });+ } else if (assetLabel !== undefined) {+ await page.getByAltText(assetLabel, { exact: true }).click();+ } else {+ throw new Error("Expected assetLabel or assetFilename");+ }+ await save;+};++const getPropertyInput = ({+ page,+ control,+}: {+ page: Page;+ control: "url" | "text";+}) =>+ control === "url"+ ? page.getByPlaceholder("https://www.url.com").first()+ : page.locator("textarea").first();++export const waitForSelectedStringPropertyValue = async ({+ page,+ label,+ control,+ value,+}: {+ page: Page;+ label: string;+ control: "url" | "text";+ value: string;+}) => {+ await getPropertyLabel({ page, label }).waitFor({+ state: "visible",+ timeout: 10_000,+ });++ const input = getPropertyInput({ page, control });+ await input.waitFor({ state: "visible", timeout: 10_000 });++ const startedAt = Date.now();+ while (Date.now() - startedAt < 10_000) {+ if ((await input.inputValue()) === value) {+ return;+ }+ await new Promise<void>((resolve) => setTimeout(resolve, 100));+ }++ throw new Error(+ `Expected selected property "${label}" to have value "${value}", received "${await input.inputValue()}"`+ );+};diff --git a/apps/builder/e2e/flows/share-dialog.ts b/apps/builder/e2e/flows/share-dialog.tsnew file mode 100644index 0000000000..6bc5ce230d--- /dev/null+++ b/apps/builder/e2e/flows/share-dialog.ts@@ -0,0 +1,168 @@+import type { Locator, Page } from "playwright";++type ShareRole = "Viewer" | "Editor" | "Builder" | "Admin";++const getShareLinkGroup = ({ page, name }: { page: Page; name: string }) =>+ page.getByRole("group", { name: `Share link ${name}` });++const getShareLinkOptions = ({ page, name }: { page: Page; name: string }) =>+ page.getByRole("dialog", { name: `Share link options ${name}` }).last();++const getCreateShareLinkButton = (page: Page) =>+ page.getByRole("button", {+ name: /Share a custom link|Add another link/,+ });++const getShareLinksRegion = (page: Page) =>+ page.getByRole("region", { name: "Share links" });++const waitForShareLinksIdle = async ({ page }: { page: Page }) => {+ await getShareLinksRegion(page).waitFor({+ state: "visible",+ timeout: 10_000,+ });+ await page.waitForFunction(+ () =>+ document+ .querySelector('[role="region"][aria-label="Share links"]')+ ?.getAttribute("aria-busy") === "false",+ undefined,+ { timeout: 10_000 }+ );+};++const waitForShareLinkMutation = async ({ page }: { page: Page }) => {+ await page.waitForFunction(+ () =>+ document+ .querySelector('[role="region"][aria-label="Share links"]')+ ?.getAttribute("aria-busy") === "true",+ undefined,+ { timeout: 2_000 }+ );+ await waitForShareLinksIdle({ page });+};++const waitForShareLinksReady = async ({ page }: { page: Page }) => {+ await waitForShareLinksIdle({ page });+ await getCreateShareLinkButton(page).click({+ trial: true,+ timeout: 10_000,+ });+};++const selectRole = async ({+ options,+ role,+}: {+ options: Locator;+ role: ShareRole;+}) => {+ const checkedRoleSwitch = options.getByRole("switch", {+ name: role,+ checked: true,+ });+ if (await checkedRoleSwitch.isVisible({ timeout: 500 }).catch(() => false)) {+ return false;+ }++ const roleSwitch = options.getByRole("switch", { name: role });+ if (await roleSwitch.isDisabled()) {+ throw new Error(`Expected share-link role "${role}" to be enabled`);+ }+ await roleSwitch.click();+ return true;+};++export const openShareDialog = async ({ page }: { page: Page }) => {+ await page.getByRole("button", { name: "Share" }).click();+ await page.getByRole("dialog").getByText("Share", { exact: true }).waitFor({+ state: "visible",+ timeout: 10_000,+ });+};++export const expectShareUnavailable = async ({ page }: { page: Page }) => {+ const shareButton = page.getByRole("button", { name: "Share" });+ if (await shareButton.isVisible({ timeout: 1_000 }).catch(() => false)) {+ if ((await shareButton.isDisabled()) === false) {+ throw new Error("Expected Share button to be unavailable");+ }+ }+};++export const createShareLink = async ({+ page,+ name,+ role,+}: {+ page: Page;+ name: string;+ role: ShareRole;+}) => {+ await waitForShareLinksReady({ page });+ const createButton = getCreateShareLinkButton(page);+ await createButton.click();+ await waitForShareLinksIdle({ page });++ const customLink = getShareLinkGroup({ page, name: "Custom link" });+ await customLink.waitFor({ state: "visible", timeout: 10_000 });+ await customLink+ .getByRole("button", { name: "Menu Button for options" })+ .click();+ const customLinkOptions = getShareLinkOptions({+ page,+ name: "Custom link",+ });+ await customLinkOptions.getByLabel("Name").fill(name);+ await page.keyboard.press("Enter");+ await waitForShareLinkMutation({ page });++ const renamedLink = getShareLinkGroup({ page, name });+ await renamedLink.waitFor({ state: "visible", timeout: 10_000 });+ await renamedLink+ .getByRole("button", { name: "Menu Button for options" })+ .click();+ const renamedLinkOptions = getShareLinkOptions({ page, name });+ if (await selectRole({ options: renamedLinkOptions, role })) {+ await waitForShareLinkMutation({ page });+ }+ await renamedLink+ .getByRole("button", { name: "Menu Button for options" })+ .click();+ await waitForShareLinksReady({ page });+};++export const copyShareLink = async ({+ page,+ name,+}: {+ page: Page;+ name: string;+}) => {+ const group = getShareLinkGroup({ page, name });+ await group.getByRole("button", { name: "Copy link" }).click();++ return await page.evaluate(async () => {+ return await navigator.clipboard.readText();+ });+};++export const updateShareLinkRole = async ({+ page,+ name,+ role,+}: {+ page: Page;+ name: string;+ role: ShareRole;+}) => {+ const group = getShareLinkGroup({ page, name });+ await group.getByRole("button", { name: "Menu Button for options" }).click();+ const options = getShareLinkOptions({ page, name });+ if (await selectRole({ options, role })) {+ await waitForShareLinkMutation({ page });+ }+ await group.getByRole("button", { name: "Menu Button for options" }).click();+ await waitForShareLinksReady({ page });+};diff --git a/apps/builder/e2e/flows/sync-status.ts b/apps/builder/e2e/flows/sync-status.tsnew file mode 100644index 0000000000..095f9aef40--- /dev/null+++ b/apps/builder/e2e/flows/sync-status.ts@@ -0,0 +1,58 @@+import type { Page } from "playwright";++type SyncStatusDotStatus = "idle" | "pending" | "saved" | "error";++const getSyncStatusDot = (page: Page) =>+ page.getByRole("status", { name: /^Sync status:/ });++const getSyncStatusDotByStatus = ({+ page,+ status,+}: {+ page: Page;+ status: SyncStatusDotStatus;+}) =>+ page.locator(+ `[role="status"][aria-label^="Sync status:"][data-sync-status="${status}"]`+ );++export const waitForSyncStatus = async ({+ page,+ status,+ timeout = 10_000,+}: {+ page: Page;+ status: SyncStatusDotStatus;+ timeout?: number;+}) => {+ await getSyncStatusDot(page).waitFor({+ state: "attached",+ timeout,+ });+ await getSyncStatusDotByStatus({ page, status }).waitFor({ timeout });+};++export const waitForChangeToBeSaved = async ({+ page,+ timeout = 10_000,+}: {+ page: Page;+ timeout?: number;+}) => {+ await getSyncStatusDot(page).waitFor({+ state: "attached",+ timeout,+ });++ await Promise.race([+ getSyncStatusDotByStatus({ page, status: "saved" }).waitFor({ timeout }),+ getSyncStatusDotByStatus({ page, status: "error" })+ .waitFor({ timeout })+ .then(async () => {+ const label =+ (await getSyncStatusDot(page).getAttribute("aria-label")) ??+ "Sync status: error";+ throw new Error(`Expected change to save, received ${label}`);+ }),+ ]);+};diff --git a/apps/builder/e2e/flows/template-insertion.ts b/apps/builder/e2e/flows/template-insertion.tsnew file mode 100644index 0000000000..47cf907a37--- /dev/null+++ b/apps/builder/e2e/flows/template-insertion.ts@@ -0,0 +1,50 @@+import type { Page } from "playwright";+import { waitForCanvasFrame } from "./builder";+import { waitForChangeToBeSaved } from "./sync-status";++const getVisibleInsertBlockButton = async ({+ page,+ anchorText,+}: {+ page: Page;+ anchorText: string;+}) => {+ await page.keyboard.press("Escape");+ const canvas = await waitForCanvasFrame({ page });+ const target = canvas.getByText(anchorText, { exact: true }).first();+ const button = page.getByRole("button", { name: "Insert block" }).last();+ const startedAt = Date.now();+ let lastError: unknown;++ while (Date.now() - startedAt < 10_000) {+ try {+ await target.scrollIntoViewIfNeeded();+ await target.hover();+ await button.waitFor({ state: "visible", timeout: 1_000 });+ return button;+ } catch (error) {+ lastError = error;+ }+ }++ throw new Error(`Expected insert block button for "${anchorText}"`, {+ cause: lastError,+ });+};++export const insertTemplateAfterCanvasText = async ({+ page,+ anchorText,+ templateName,+}: {+ page: Page;+ anchorText: string;+ templateName: string;+}) => {+ const insertButton = await getVisibleInsertBlockButton({ page, anchorText });+ await insertButton.click();++ const save = waitForChangeToBeSaved({ page });+ await page.getByRole("menuitemradio", { name: templateName }).click();+ await save;+};diff --git a/apps/builder/e2e/harness.ts b/apps/builder/e2e/harness.tsnew file mode 100644index 0000000000..9733a239dd--- /dev/null+++ b/apps/builder/e2e/harness.ts@@ -0,0 +1,176 @@+import { parseBuilderUrl } from "@webstudio-is/http-client";+import { basename } from "node:path";+import {+ chromium,+ type Browser,+ type BrowserContext,+ type BrowserContextOptions,+} from "playwright";++const builderPort =+ process.env.E2E_BUILDER_PORT ??+ String(20_000 + ((process.pid + Date.now()) % 40_000));++export const builderUrl =+ process.env.E2E_BUILDER_URL ?? `https://127.0.0.1:${builderPort}`;++const builderUrlObject = new URL(builderUrl);++export const dashboardUrl = `${builderUrlObject.protocol}//wstd.dev:${builderUrlObject.port}`;++export const postgrestUrl =+ process.env.POSTGREST_URL ?? "http://127.0.0.1:55433";++export const serviceToken =+ process.env.TRPC_SERVER_API_TOKEN ?? "e2e-service-token";++export type Test = {+ name: string;+ run: () => Promise<void>;+};++export type Suite = {+ name: string;+ beforeAll?: () => Promise<void>;+ beforeEach?: () => Promise<void>;+ afterAll?: () => Promise<void>;+ tests: Test[];+};++type TestApi = ((name: string, run: () => Promise<void>) => void) & {+ beforeAll: (run: () => Promise<void>) => void;+ beforeEach: (run: () => Promise<void>) => void;+ afterAll: (run: () => Promise<void>) => void;+};++const suites: Suite[] = [];+const suitesByFile = new Map<string, Suite>();++const formatSuiteName = (filePath: string) => {+ return basename(filePath, ".e2e.ts").replaceAll("-", " ");+};++const getCallerFile = () => {+ const stack = new Error().stack ?? "";+ const callerLine = stack+ .split("\n")+ .find(+ (line) =>+ line.includes("/e2e/tests/") &&+ line.includes(".e2e.ts") &&+ line.includes("/harness.ts") === false+ );+ const filePath = callerLine?.match(/(\/[^():]+\.e2e\.ts)/)?.[1];+ if (filePath === undefined) {+ throw new Error("Expected e2e test to be registered from an .e2e.ts file");+ }+ return filePath;+};++const getFileSuite = () => {+ const filePath = getCallerFile();+ let suite = suitesByFile.get(filePath);+ if (suite !== undefined) {+ return suite;+ }++ suite = { name: formatSuiteName(filePath), tests: [] };+ suitesByFile.set(filePath, suite);+ suites.push(suite);+ return suite;+};++export const test: TestApi = Object.assign(+ (name: string, run: () => Promise<void>) => {+ getFileSuite().tests.push({ name, run });+ },+ {+ beforeAll: (run: () => Promise<void>) => {+ getFileSuite().beforeAll = run;+ },+ beforeEach: (run: () => Promise<void>) => {+ getFileSuite().beforeEach = run;+ },+ afterAll: (run: () => Promise<void>) => {+ getFileSuite().afterAll = run;+ },+ }+);++export const getSuites = () => suites;++let browser: Browser | undefined;+let context: BrowserContext | undefined;++const browserContextOptions: BrowserContextOptions = {+ ignoreHTTPSErrors: true,+ permissions: ["clipboard-read", "clipboard-write"],+};++export const startBrowser = async () => {+ browser = await chromium.launch();+ context = await browser.newContext(browserContextOptions);+};++export const stopBrowser = async () => {+ await context?.close();+ await browser?.close();+ context = undefined;+ browser = undefined;+};++export const newPage = async () => {+ if (context === undefined) {+ throw new Error("Browser context is not initialized");+ }++ return await context.newPage();+};++export const newIsolatedPage = async () => {+ if (browser === undefined) {+ throw new Error("Browser is not initialized");+ }++ const isolatedContext = await browser.newContext(browserContextOptions);++ return {+ page: await isolatedContext.newPage(),+ close: async () => {+ await isolatedContext.close();+ },+ };+};++export const getProjectBuilderUrl = ({+ projectId,+ authToken,+ mode,+}: {+ projectId: string;+ authToken?: string;+ mode?: "content" | "preview";+}) => {+ const url = new URL(dashboardUrl);+ url.hostname = `p-${projectId}.wstd.dev`;+ if (authToken !== undefined) {+ url.searchParams.set("authToken", authToken);+ }+ if (mode !== undefined) {+ url.searchParams.set("mode", mode);+ }+ return url.href;+};++export const getProjectIdFromBuilderUrl = (url: string) => {+ return parseBuilderUrl(url).projectId;+};++export const assert = (+ condition: unknown,+ message: string+): asserts condition => {+ if (condition === false || condition === undefined || condition === null) {+ throw new Error(message);+ }+};diff --git a/apps/builder/e2e/perf.ts b/apps/builder/e2e/perf.tsnew file mode 100644index 0000000000..4f7a222c2d--- /dev/null+++ b/apps/builder/e2e/perf.ts@@ -0,0 +1,32 @@+const metrics: Array<{ phase: string; duration: number }> = [];++export const logPerf = (phase: string, startedAt: number) => {+ const duration = Date.now() - startedAt;+ metrics.push({ phase, duration });+ console.info(`[e2e:perf] phase="${phase}" duration=${duration}ms`);+};++export const printPerfSummary = () => {+ if (metrics.length === 0) {+ return;+ }++ console.info("[e2e:perf:summary] begin");+ for (const { phase, duration } of metrics) {+ console.info(`[e2e:perf:summary] phase="${phase}" duration=${duration}ms`);+ }+ console.info("[e2e:perf:summary] end");+};++export const measure = async <Result>(+ phase: string,+ task: () => Promise<Result>+) => {+ const startedAt = Date.now();++ try {+ return await task();+ } finally {+ logPerf(phase, startedAt);+ }+};diff --git a/apps/builder/e2e/plans.ts b/apps/builder/e2e/plans.tsnew file mode 100644index 0000000000..7374ae514b--- /dev/null+++ b/apps/builder/e2e/plans.ts@@ -0,0 +1,17 @@+export const e2ePaidPlanName = "E2E Paid Plan";++export const e2ePlans = [+ {+ name: e2ePaidPlanName,+ features: {+ allowAdditionalPermissions: true,+ allowContentMode: true,+ allowStagingPublish: true,+ maxWorkspaces: 5,+ maxDailyPublishesPerUser: 100,+ maxProjectsAllowedPerUser: 100,+ maxAssetsPerProject: 100,+ },+ prices: {},+ },+];diff --git a/apps/builder/e2e/run-local.sh b/apps/builder/e2e/run-local.shnew file mode 100644index 0000000000..03d2d2a259--- /dev/null+++ b/apps/builder/e2e/run-local.sh@@ -0,0 +1,265 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"+COMPOSE_FILE="$ROOT_DIR/apps/builder/docker-compose.e2e.yaml"+SCHEMA_SNAPSHOT="$ROOT_DIR/apps/builder/e2e/schema/current.sql"++export AUTH_SECRET="${AUTH_SECRET:-test}"+export DATABASE_URL="${DATABASE_URL:-postgresql://user:pass@localhost:55432/webstudio}"+export DIRECT_URL="${DIRECT_URL:-$DATABASE_URL}"+export E2E_DB_BOOTSTRAP="${E2E_DB_BOOTSTRAP:-auto}"+export E2E_GENERATE_PRISMA="${E2E_GENERATE_PRISMA:-auto}"+export E2E_PGPORT="${E2E_PGPORT:-55432}"+export E2E_POSTGREST_PORT="${E2E_POSTGREST_PORT:-55433}"+export POSTGREST_API_KEY="${POSTGREST_API_KEY:-}"+export POSTGREST_URL="${POSTGREST_URL:-http://127.0.0.1:55433}"+export TRPC_SERVER_API_TOKEN="${TRPC_SERVER_API_TOKEN:-e2e-service-token}"+export E2E_DOCKER_TIMEOUT_SECONDS="${E2E_DOCKER_TIMEOUT_SECONDS:-60}"+export E2E_MIGRATIONS_TIMEOUT_SECONDS="${E2E_MIGRATIONS_TIMEOUT_SECONDS:-300}"+export E2E_INSTALL_PLAYWRIGHT="${E2E_INSTALL_PLAYWRIGHT:-auto}"+export E2E_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS="${E2E_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS:-300}"+export E2E_RUN_TESTS="${E2E_RUN_TESTS:-true}"+export E2E_PACKAGE_BUILD_TIMEOUT_SECONDS="${E2E_PACKAGE_BUILD_TIMEOUT_SECONDS:-120}"+export E2E_BUILDER_BUILD_TIMEOUT_SECONDS="${E2E_BUILDER_BUILD_TIMEOUT_SECONDS:-600}"+export E2E_TEST_COMMAND_TIMEOUT_SECONDS="${E2E_TEST_COMMAND_TIMEOUT_SECONDS:-900}"+export E2E_WRITE_SCHEMA_SNAPSHOT="${E2E_WRITE_SCHEMA_SNAPSHOT:-false}"++RUN_STARTED_AT="$(date +%s%3N)"++now_ms() {+ date +%s%3N+}++cleanup() {+ if [ "${E2E_SKIP_CLEANUP:-}" = "true" ]; then+ return+ fi++ local started_at+ started_at="$(now_ms)"+ docker compose -f "$COMPOSE_FILE" down --volumes --remove-orphans+ local duration_ms+ duration_ms="$(($(now_ms) - started_at))"+ echo "[e2e:perf] phase=cleanup duration=${duration_ms}ms"+}++trap cleanup EXIT++run_step() {+ local name="$1"+ local timeout_seconds="$2"+ shift 2++ local started_at+ started_at="$(now_ms)"+ echo "▶ $name"+ "$@" &+ local pid="$!"+ local timeout_at+ timeout_at="$(($(now_ms) + timeout_seconds * 1000))"+ while kill -0 "$pid" 2>/dev/null; do+ if [ "$(now_ms)" -ge "$timeout_at" ]; then+ echo "Timed out after ${timeout_seconds}s: $name" >&2+ kill "$pid" 2>/dev/null || true+ sleep 10+ kill -9 "$pid" 2>/dev/null || true+ wait "$pid" || true+ return 124+ fi+ sleep 0.1+ done+ local status=0+ wait "$pid" || status="$?"+ if [ "$status" -ne 0 ]; then+ return "$status"+ fi+ local duration_ms+ duration_ms="$(($(now_ms) - started_at))"+ echo "✓ $name"+ echo "[e2e:perf] phase=\"$name\" duration=${duration_ms}ms"+}++wait_for_step() {+ local name="$1"+ local pid="$2"+ local status=0++ wait "$pid" || status="$?"+ if [ "$status" -ne 0 ]; then+ echo "Step failed: $name" >&2+ return "$status"+ fi+}++bootstrap_with_schema_snapshot() {+ if [ ! -f "$SCHEMA_SNAPSHOT" ]; then+ return 1+ fi++ docker compose -f "$COMPOSE_FILE" exec -T db \+ psql -q -U user -d webstudio -v ON_ERROR_STOP=1 <"$SCHEMA_SNAPSHOT" \+ >/dev/null+}++bootstrap_with_migrations() {+ pnpm --dir "$ROOT_DIR" --filter=./packages/prisma-client migrations migrate --dev --cwd ../../apps/builder+}++write_schema_snapshot() {+ mkdir -p "$(dirname "$SCHEMA_SNAPSHOT")"+ docker compose -f "$COMPOSE_FILE" exec -T db \+ pg_dump -U user -d webstudio --schema-only --no-owner --no-privileges \+ >"$SCHEMA_SNAPSHOT"+ echo "Wrote $SCHEMA_SNAPSHOT"+}++bootstrap_database() {+ case "$E2E_DB_BOOTSTRAP" in+ schema)+ bootstrap_with_schema_snapshot+ ;;+ migrations)+ bootstrap_with_migrations+ ;;+ auto)+ if [ -f "$SCHEMA_SNAPSHOT" ]; then+ bootstrap_with_schema_snapshot+ echo "Bootstrapped database from $SCHEMA_SNAPSHOT"+ else+ echo "No schema snapshot found at $SCHEMA_SNAPSHOT; falling back to migrations"+ bootstrap_with_migrations+ fi+ ;;+ *)+ echo "Unknown E2E_DB_BOOTSTRAP value: $E2E_DB_BOOTSTRAP" >&2+ exit 1+ ;;+ esac++ if [ "$E2E_WRITE_SCHEMA_SNAPSHOT" = "true" ]; then+ write_schema_snapshot+ fi+}++has_prisma_client() {+ [ -f "$ROOT_DIR/packages/prisma-client/src/__generated__/index.js" ]+}++generate_prisma_client() {+ case "$E2E_GENERATE_PRISMA" in+ true)+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/prisma-client generate+ ;;+ false)+ echo "Skipping Prisma client generation"+ ;;+ auto)+ if has_prisma_client; then+ echo "Skipping Prisma client generation; generated client already exists"+ else+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/prisma-client generate+ fi+ ;;+ *)+ echo "Unknown E2E_GENERATE_PRISMA value: $E2E_GENERATE_PRISMA" >&2+ exit 1+ ;;+ esac+}++has_playwright_chromium() {+ (+ cd "$ROOT_DIR/apps/builder"+ node -e "const { chromium } = require('playwright'); const fs = require('fs'); process.exit(fs.existsSync(chromium.executablePath()) ? 0 : 1)"+ )+}++install_playwright_chromium() {+ case "$E2E_INSTALL_PLAYWRIGHT" in+ true)+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/builder exec playwright install --with-deps chromium+ ;;+ false)+ echo "Skipping Playwright Chromium install"+ ;;+ auto)+ if has_playwright_chromium; then+ echo "Skipping Playwright Chromium install; browser already exists"+ else+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/builder exec playwright install --with-deps chromium+ fi+ ;;+ *)+ echo "Unknown E2E_INSTALL_PLAYWRIGHT value: $E2E_INSTALL_PLAYWRIGHT" >&2+ exit 1+ ;;+ esac+}++build_builder_package_entries() {+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/http-client build+}++build_builder_app() {+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/builder build+}++wait_for_database() {+ local timeout_at+ timeout_at="$(($(now_ms) + E2E_DOCKER_TIMEOUT_SECONDS * 1000))"++ until docker compose -f "$COMPOSE_FILE" exec -T db \+ psql -q -U user -d webstudio -v ON_ERROR_STOP=1 -c "SELECT 1" \+ >/dev/null 2>&1; do+ if [ "$(now_ms)" -ge "$timeout_at" ]; then+ echo "Timed out waiting for e2e database" >&2+ return 1+ fi+ sleep 0.1+ done+}++run_step "start e2e database" "$E2E_DOCKER_TIMEOUT_SECONDS" \+ docker compose -f "$COMPOSE_FILE" up -d db++run_step "generate prisma client" "$E2E_MIGRATIONS_TIMEOUT_SECONDS" \+ generate_prisma_client &+generate_prisma_client_pid="$!"++if [ "$E2E_RUN_TESTS" = "true" ]; then+ run_step "install playwright chromium" "$E2E_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS" \+ install_playwright_chromium &+ install_playwright_chromium_pid="$!"++ run_step "build builder package entries" "$E2E_PACKAGE_BUILD_TIMEOUT_SECONDS" \+ build_builder_package_entries &+ build_builder_package_entries_pid="$!"+fi++run_step "wait for e2e database" "$E2E_DOCKER_TIMEOUT_SECONDS" \+ wait_for_database++run_step "bootstrap database schema" "$E2E_MIGRATIONS_TIMEOUT_SECONDS" \+ bootstrap_database++wait_for_step "generate prisma client" "$generate_prisma_client_pid"++if [ "$E2E_RUN_TESTS" = "true" ]; then+ wait_for_step "install playwright chromium" "$install_playwright_chromium_pid"+ wait_for_step "build builder package entries" "$build_builder_package_entries_pid"++ run_step "start e2e postgrest" "$E2E_DOCKER_TIMEOUT_SECONDS" \+ docker compose -f "$COMPOSE_FILE" up -d postgrest++ if [ "${E2E_BUILDER_URL:-}" = "" ]; then+ run_step "build builder app" "$E2E_BUILDER_BUILD_TIMEOUT_SECONDS" \+ build_builder_app+ fi++ run_step "run builder e2e tests" "$E2E_TEST_COMMAND_TIMEOUT_SECONDS" \+ pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/builder e2e:ci+fi++TOTAL_DURATION_MS="$(($(now_ms) - RUN_STARTED_AT))"+echo "[e2e:perf] phase=total duration=${TOTAL_DURATION_MS}ms"diff --git a/apps/builder/e2e/run.ts b/apps/builder/e2e/run.tsnew file mode 100644index 0000000000..0b858ae518--- /dev/null+++ b/apps/builder/e2e/run.ts@@ -0,0 +1,280 @@+import { spawn, type ChildProcess } from "node:child_process";+import { setTimeout as delay } from "node:timers/promises";+import {+ builderUrl,+ dashboardUrl,+ getSuites,+ newPage,+ postgrestUrl,+ serviceToken,+ startBrowser,+ stopBrowser,+} from "./harness";+import { resetDatabase } from "./db";+import { logPerf, measure, printPerfSummary } from "./perf";+import { e2ePlans } from "./plans";+import "./tests/content-mode-editing.e2e";+import "./tests/share-link-permissions.e2e";++const testTimeoutMs =+ Number.parseInt(process.env.E2E_TEST_TIMEOUT_MS ?? "", 10) || 60_000;+const testFilter = process.env.E2E_TEST_FILTER;++process.env.NODE_TLS_REJECT_UNAUTHORIZED ??= "0";++const waitForHttp = async (url: string, timeoutMs: number) => {+ const startedAt = Date.now();+ let lastError: unknown;++ while (Date.now() - startedAt < timeoutMs) {+ try {+ const response = await fetch(url);+ await response.arrayBuffer();+ if (response.status < 500) {+ return;+ }+ } catch (error) {+ lastError = error;+ }+ await delay(250);+ }++ throw new Error(`Timed out waiting for ${url}: ${String(lastError)}`);+};++const waitForPostgrest = async () => {+ const url = new URL("/User?select=*", postgrestUrl);+ const startedAt = Date.now();+ let successfulResponses = 0;++ while (Date.now() - startedAt < 30_000) {+ try {+ const response = await fetch(url.href);+ await response.arrayBuffer();+ if (response.status < 500) {+ successfulResponses += 1;+ if (successfulResponses === 3) {+ return;+ }+ }+ } catch {+ successfulResponses = 0;+ }+ await delay(250);+ }++ throw new Error(`Timed out waiting for ${url.href}`);+};++const waitForBuilder = async (child: ChildProcess) => {+ await Promise.race([+ waitForHttp(dashboardUrl, 60_000),+ new Promise<never>((_, reject) => {+ child.once("exit", (code, signal) => {+ reject(+ new Error(+ `Builder server exited before becoming ready: code=${code}, signal=${signal}`+ )+ );+ });+ }),+ ]);+};++const warmLoginRoute = async () => {+ const page = await newPage();+ try {+ await page.goto(`${dashboardUrl}/login`);+ await page+ .getByRole("button", { name: "Login with Secret" })+ .waitFor({ state: "visible", timeout: 60_000 });+ } finally {+ await page.close();+ }+};++const withTimeout = async <Result>(+ name: string,+ timeoutMs: number,+ task: () => Promise<Result>+) => {+ let timeout: NodeJS.Timeout | undefined;++ try {+ return await Promise.race([+ task(),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(() => {+ reject(new Error(`Timed out after ${timeoutMs}ms: ${name}`));+ }, timeoutMs);+ }),+ ]);+ } finally {+ clearTimeout(timeout);+ }+};++const pipeBuilderOutput = (child: ChildProcess) => {+ child.stdout?.on("data", (chunk) => {+ process.stdout.write(`[builder] ${chunk}`);+ });+ child.stderr?.on("data", (chunk) => {+ process.stderr.write(`[builder] ${chunk}`);+ });+};++const runSuiteTests = async ({+ suite,+ tests,+}: {+ suite: ReturnType<typeof getSuites>[number];+ tests: ReturnType<typeof getSuites>[number]["tests"];+}) => {+ try {+ for (const test of tests) {+ const startedAt = Date.now();+ await withTimeout(+ `${suite.name} › ${test.name}`,+ testTimeoutMs,+ async () => {+ await suite.beforeEach?.();+ await test.run();+ }+ );+ const duration = Date.now() - startedAt;+ console.info(`✓ ${suite.name} › ${test.name} (${duration}ms)`);+ }+ } finally {+ const afterAllStartedAt = Date.now();+ await withTimeout(`${suite.name} afterAll`, testTimeoutMs, async () => {+ await suite.afterAll?.();+ });+ logPerf(`${suite.name} afterAll`, afterAllStartedAt);+ }+};++const getBuilderEnv = () => ({+ ...process.env,+ AUTH_SECRET: process.env.AUTH_SECRET ?? "test",+ DATABASE_URL:+ process.env.DATABASE_URL ??+ "postgresql://user:pass@localhost:55432/webstudio",+ DEV_LOGIN: "true",+ GITHUB_SHA: process.env.GITHUB_SHA ?? "local",+ POSTGREST_API_KEY: process.env.POSTGREST_API_KEY ?? "",+ POSTGREST_URL: postgrestUrl,+ PORT: new URL(builderUrl).port,+ PLANS: process.env.PLANS ?? JSON.stringify(e2ePlans),+ TRPC_SERVER_API_TOKEN: serviceToken,+});++const startBuiltBuilder = async () => {+ const child = spawn(+ "pnpm",+ ["exec", "tsx", "--conditions=webstudio", "./e2e/serve-built-remix.ts"],+ {+ cwd: new URL("..", import.meta.url),+ env: {+ ...getBuilderEnv(),+ HOST: "127.0.0.1",+ NODE_ENV: "production",+ },+ stdio: ["ignore", "pipe", "pipe"],+ }+ );++ pipeBuilderOutput(child);+ return child;+};++const startBuilder = async (): Promise<ChildProcess | undefined> => {+ if (process.env.E2E_BUILDER_URL !== undefined) {+ return undefined;+ }++ const server = await startBuiltBuilder();+ try {+ await waitForBuilder(server);+ } catch (error) {+ await stopBuilder(server);+ throw error;+ }+ return server;+};++const stopBuilder = async (child: ChildProcess | undefined) => {+ if (child === undefined || child.killed) {+ return;+ }++ child.kill("SIGTERM");+ await Promise.race([+ new Promise<void>((resolve) => child.once("exit", () => resolve())),+ delay(5_000).then(() => {+ child.kill("SIGKILL");+ }),+ ]);+};++const run = async () => {+ const totalStartedAt = Date.now();+ const bootStartedAt = Date.now();+ let builder: ChildProcess | undefined;++ try {+ const postgrestReady = measure("wait for postgrest", async () => {+ await waitForPostgrest();+ });+ const builderReady = measure("start builder", startBuilder);+ const browserReady = measure("start browser", startBrowser);+ builder = await builderReady;+ await postgrestReady;+ await browserReady;+ await measure("warm login route", warmLoginRoute);+ logPerf("boot builder/browser", bootStartedAt);+ const testsStartedAt = Date.now();+ const runnableSuites = getSuites()+ .map((suite) => ({+ suite,+ tests: suite.tests.filter(+ (test) => testFilter === undefined || test.name.includes(testFilter)+ ),+ }))+ .filter(({ tests }) => tests.length > 0);++ await measure("reset database", resetDatabase);++ for (const { suite } of runnableSuites) {+ const beforeAllStartedAt = Date.now();+ await withTimeout(`${suite.name} beforeAll`, testTimeoutMs, async () => {+ await suite.beforeAll?.();+ });+ logPerf(`${suite.name} beforeAll`, beforeAllStartedAt);+ }++ const results = await Promise.allSettled(+ runnableSuites.map(async ({ suite, tests }) => {+ const suiteStartedAt = Date.now();+ await runSuiteTests({ suite, tests });+ const suiteDuration = Date.now() - suiteStartedAt;+ console.info(`✓ ${suite.name} completed (${suiteDuration}ms)`);+ })+ );++ const failedSuite = results.find((result) => result.status === "rejected");+ if (failedSuite?.status === "rejected") {+ throw failedSuite.reason;+ }+ logPerf("tests", testsStartedAt);+ } finally {+ await stopBrowser();+ await stopBuilder(builder);+ logPerf("runner total", totalStartedAt);+ printPerfSummary();+ }+};++run().catch(async (error) => {+ console.error(error);+ process.exit(1);+});diff --git a/apps/builder/e2e/schema/README.md b/apps/builder/e2e/schema/README.mdnew file mode 100644index 0000000000..d187b76aac--- /dev/null+++ b/apps/builder/e2e/schema/README.md@@ -0,0 +1,10 @@+This directory stores the optional e2e database schema snapshot.++The snapshot should contain database structure only. Test data belongs in the+typed fixtures under `apps/builder/e2e/fixtures`.++Refresh the snapshot with:++```sh+pnpm e2e:builder:update-schema+```diff --git a/apps/builder/e2e/schema/current.sql b/apps/builder/e2e/schema/current.sqlnew file mode 100644index 0000000000..acecc21214--- /dev/null+++ b/apps/builder/e2e/schema/current.sql@@ -0,0 +1,1461 @@+--+-- PostgreSQL database dump+--++\restrict J29mZQHzSYuDPm8eRJiWoDBJq2TAh0b0ii1URRuunEM0BP9wmmC5I93noDiexdr++-- Dumped from database version 16.14 (Debian 16.14-1.pgdg13+1)+-- Dumped by pg_dump version 16.14 (Debian 16.14-1.pgdg13+1)++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;++--+-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -+--++CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;+++--+-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: -+--++COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';+++--+-- 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 (+ extensions.uuid_generate_v4(),+ user_id,+ title,+ domain+ )+ RETURNING * INTO new_project;++ INSERT INTO "Asset" (id, name, "projectId")+ SELECT asset.id, asset.name, new_project.id AS "projectId"+ FROM "Asset" AS asset, "File" AS file+ WHERE+ asset.name = file.name AND+ file.status = 'UPLOADED' AND+ asset."projectId" = old_project.id;++ -- set preview image asset after copying assets to the project+ 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+ )+ SELECT+ extensions.uuid_generate_v4() AS id,+ new_project.id AS "projectId",+ pages,+ "styleSources",+ "styleSourceSelections",+ styles,+ breakpoints,+ props,+ instances,+ "dataSources",+ resources+ 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",+ "publishStatus",+ "projectId",+ id,+ deployment+ )+ SELECT+ version,+ "lastTransactionId",+ pages,+ breakpoints,+ styles,+ "styleSources",+ "styleSourceSelections",+ props,+ "dataSources",+ resources,+ instances,+ "marketplaceProduct",+ "publishStatus",+ "projectId",+ extensions.uuid_generate_v4() as id,+ create_production_build.deployment as deployment+ FROM "Build"+ WHERE "projectId" = project_id AND "Build"."deployment" IS NULL+ 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" = '[]'::text,+ styles = '[]'::text,+ breakpoints = '[]'::text,+ "styleSourceSelections" = '[]'::text,+ props = '[]'::text,+ instances = '[]'::text,+ "dataSources" = '[]'::text,+ resources = '[]'::text,+ "marketplaceProduct" = '{}'::text,+ "isCleaned" = TRUE+ WHERE deployment IS NOT NULL+ AND id NOT IN (SELECT "buildId" FROM latest_builds)+ AND "isCleaned" = FALSE+ AND "createdAt" BETWEEN from_date AND to_date; -- Filter by date range (for testing purposes)+END;+$$;+++--+-- 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+);+++--+-- Name: DashboardProject; Type: VIEW; Schema: public; Owner: -+--++CREATE VIEW public."DashboardProject" AS+ SELECT id,+ title,+ tags,+ domain,+ "userId",+ "workspaceId",+ "isDeleted",+ "createdAt",+ "previewImageAssetId",+ "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: 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"+ 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: 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+);+++--+-- Name: ApprovedMarketplaceProduct; Type: VIEW; Schema: public; Owner: -+--++CREATE VIEW public."ApprovedMarketplaceProduct" AS+ SELECT DISTINCT ON ("projectId") "projectId",+ "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 ((deployment IS NOT NULL) AND ("projectId" IN ( SELECT "Project".id+ FROM public."Project"+ WHERE (("Project"."isDeleted" = false) AND ("Project"."marketplaceApprovalStatus" = ('APPROVED'::text)::public."MarketplaceApprovalStatus")))))+ ORDER BY "projectId", "createdAt" DESC, 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+);+++--+-- Name: ClientReferences; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public."ClientReferences" (+ reference text DEFAULT public.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+);+++--+-- Name: LatestStaticBuildPerProject; Type: VIEW; Schema: public; Owner: -+--++CREATE VIEW public."LatestStaticBuildPerProject" AS+ SELECT DISTINCT ON ("projectId") id AS "buildId",+ "projectId",+ "updatedAt",+ "publishStatus"+ FROM public."Build" bld+ WHERE ((deployment IS NOT NULL) AND (((deployment)::jsonb ->> 'destination'::text) = 'static'::text))+ ORDER BY "projectId", "createdAt" DESC, 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 id AS "buildId",+ "projectId",+ "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 ((deployment IS NOT NULL) AND ("isCleaned" = false))+ ORDER BY "projectId", "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: 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: 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: 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: 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 J29mZQHzSYuDPm8eRJiWoDBJq2TAh0b0ii1URRuunEM0BP9wmmC5I93noDiexdr+diff --git a/apps/builder/e2e/serve-built-remix.ts b/apps/builder/e2e/serve-built-remix.tsnew file mode 100644index 0000000000..b239d6818c--- /dev/null+++ b/apps/builder/e2e/serve-built-remix.ts@@ -0,0 +1,75 @@+import { installGlobals } from "@remix-run/node";+import { createRequestHandler as createExpressRequestHandler } from "@remix-run/express";+import type { ServerBuild } from "@remix-run/server-runtime";+import express from "express";+import { readdirSync, readFileSync } from "node:fs";+import https from "node:https";+import path from "node:path";+import { pathToFileURL } from "node:url";++installGlobals({ nativeFetch: true });++const resolveServerBuildPath = () => {+ const serverDirectory = path.resolve("build/server");+ const serverBuild = readdirSync(serverDirectory, {+ withFileTypes: true,+ }).find((entry) => entry.isDirectory());++ if (serverBuild === undefined) {+ throw new Error(`Could not find server build in ${serverDirectory}`);+ }++ return path.join(serverDirectory, serverBuild.name, "index.js");+};++const start = async () => {+ const build = (await import(+ pathToFileURL(resolveServerBuildPath()).href+ )) as ServerBuild;+ const port = Number(process.env.PORT ?? 3000);+ const host = process.env.HOST;+ const app = express();++ app.disable("x-powered-by");+ app.use(+ build.publicPath,+ express.static(build.assetsBuildDirectory, {+ immutable: true,+ maxAge: "1y",+ })+ );+ app.use(express.static("public", { maxAge: "1h" }));+ app.use(+ createExpressRequestHandler({+ build,+ mode: "production",+ })+ );++ const server = https.createServer(+ {+ cert: readFileSync(path.resolve("../../https/fullchain.pem")),+ key: readFileSync(path.resolve("../../https/privkey.pem")),+ },+ app+ );++ server.listen(port, host, () => {+ console.info(`[builder-e2e] https://${host ?? "localhost"}:${port}`);+ });++ for (const signal of ["SIGTERM", "SIGINT"] as const) {+ process.once(signal, () => {+ server.close((error) => {+ if (error !== undefined) {+ console.error(error);+ }+ });+ });+ }+};++start().catch((error) => {+ console.error(error);+ process.exit(1);+});diff --git a/apps/builder/e2e/tests/content-mode-editing.e2e.ts b/apps/builder/e2e/tests/content-mode-editing.e2e.tsnew file mode 100644index 0000000000..0614e847d2--- /dev/null+++ b/apps/builder/e2e/tests/content-mode-editing.e2e.ts@@ -0,0 +1,917 @@+import {+ deleteSelectedAsset,+ openAssetDetails,+ openAssetsPanel,+ replaceSelectedAsset,+ uploadAsset,+} from "../flows/assets-panel";+import { deleteContentBlockChildAfterCanvasText } from "../flows/block-outline";+import {+ openProjectBuilder,+ waitForCanvasFrame,+ waitForCanvasText,+ waitForCanvasTextHidden,+} from "../flows/builder";+import {+ selectCanvasTextInstance,+ selectCanvasTextInstanceForProps,+} from "../flows/canvas-selection";+import { expectLocatorHidden, expectTextHidden } from "../flows/assertions";+import {+ selectCanvasImage,+ selectCanvasVideoSource,+ waitForCanvasImage,+ waitForCanvasImageSourceName,+ waitForCanvasVideoSource,+} from "../flows/canvas-media";+import {+ waitForCanvasTextStyle,+ waitForCanvasTextStyleCount,+} from "../flows/canvas-style";+import { replaceCanvasText } from "../flows/content-editing";+import {+ chooseSelectedAssetProperty,+ fillSelectedStringProperty,+ waitForSelectedStringPropertyValue,+} from "../flows/props-panel";+import {+ choosePageSettingsSocialImageAsset,+ createPageFromTemplate,+ expectContentModePagePathError,+ expectContentModePageSettingsRestrictions,+ expectContentModeTemplateActionsUnavailable,+ expectCustomMetadataValue,+ fillAllowedPageSettings,+ getPageSettingsPathInput,+ openPage,+ openPageSettings,+ openPagesPanel,+} from "../flows/pages-panel";+import { waitForSyncStatus } from "../flows/sync-status";+import { insertTemplateAfterCanvasText } from "../flows/template-insertion";+import {+ getSharedContentModeProject,+ setupSharedContentModeProject,+} from "../fixtures/content-mode-suite";+import { newIsolatedPage, test } from "../harness";+import { measure } from "../perf";++test.beforeAll(async () => {+ await setupSharedContentModeProject();+});+test("Editor can insert content templates with assets and styles", async () => {+ const fixture = getSharedContentModeProject();+ const { page, close } = await newIsolatedPage();++ try {+ await measure("content mode open editor for asset template", async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ });+ await waitForCanvasText({ page, text: "Initial content" });+ await waitForSyncStatus({ page, status: "idle" });++ await measure("content mode insert asset template", async () => {+ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.assetTemplateName,+ });+ });+ await waitForCanvasImage({+ page,+ alt: fixture.assetTemplateImageAlt,+ });+ await waitForCanvasVideoSource({+ page,+ sourceName: fixture.assetTemplateVideoName,+ });++ await measure("content mode insert heading template", async () => {+ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.styledHeadingTemplateName,+ });+ });+ await waitForCanvasText({+ page,+ text: fixture.styledHeadingTemplateText,+ });+ await waitForCanvasTextStyle({+ page,+ text: fixture.styledHeadingTemplateText,+ property: "font-size",+ value: fixture.styledHeadingTemplateFontSize,+ });++ await measure("content mode insert token template", async () => {+ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.tokenTemplateName,+ });+ });+ await waitForCanvasText({+ page,+ text: fixture.tokenTemplateText,+ });+ await waitForCanvasTextStyle({+ page,+ text: fixture.tokenTemplateText,+ property: "font-size",+ value: fixture.tokenTemplateFontSize,+ });++ await measure("content mode insert local style templates", async () => {+ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.isolatedLocalTemplateName,+ });+ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.isolatedLocalTemplateName,+ });+ });+ await waitForCanvasTextStyleCount({+ page,+ text: fixture.isolatedLocalTemplateText,+ property: "font-size",+ value: fixture.isolatedLocalTemplateFontSize,+ count: 2,+ });++ await measure("content mode reload editor for asset template", async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ });+ await waitForCanvasImage({+ page,+ alt: fixture.assetTemplateImageAlt,+ });+ await waitForCanvasVideoSource({+ page,+ sourceName: fixture.assetTemplateVideoName,+ });+ await waitForCanvasTextStyle({+ page,+ text: fixture.styledHeadingTemplateText,+ property: "font-size",+ value: fixture.styledHeadingTemplateFontSize,+ });+ await waitForCanvasTextStyle({+ page,+ text: fixture.tokenTemplateText,+ property: "font-size",+ value: fixture.tokenTemplateFontSize,+ });+ await waitForCanvasTextStyleCount({+ page,+ text: fixture.isolatedLocalTemplateText,+ property: "font-size",+ value: fixture.isolatedLocalTemplateFontSize,+ count: 2,+ });+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});+test("Editor can upload, replace, and delete asset in content mode", async () => {+ const fixture = getSharedContentModeProject();+ const { page, close } = await newIsolatedPage();+ const uploadFilename = "upload-image.svg";+ const replacementFilename = "replacement-image.svg";++ try {+ await measure("content mode open editor for asset workflows", async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ });+ await waitForCanvasText({ page, text: "Initial content" });+ await waitForSyncStatus({ page, status: "idle" });++ let uploadedAssetTitle = "";+ await measure("content mode upload asset", async () => {+ await openAssetsPanel({ page });+ uploadedAssetTitle = await uploadAsset({+ page,+ filename: uploadFilename,+ });+ });++ let replacementAssetTitle = "";+ await measure("content mode replace asset", async () => {+ await openAssetDetails({ page, filename: uploadedAssetTitle });+ replacementAssetTitle = await replaceSelectedAsset({+ page,+ filename: replacementFilename,+ });+ });++ await measure("content mode delete asset", async () => {+ await openAssetDetails({ page, filename: replacementAssetTitle });+ await deleteSelectedAsset({+ page,+ filename: replacementAssetTitle,+ });+ });++ await measure(+ "content mode reload editor for asset workflows",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await openAssetsPanel({ page });+ await page.getByTitle(uploadedAssetTitle).waitFor({ state: "hidden" });+ await page.getByTitle(replacementAssetTitle).waitFor({ state: "hidden" });+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});+test("Editor can replace image source with asset in content mode", async () => {+ const fixture = getSharedContentModeProject();+ const { page, close } = await newIsolatedPage();+ const uploadFilename = "upload-image.svg";+ const replacementFilename = "replacement-image.svg";++ try {+ await measure(+ "content mode open editor for image source asset replacement",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await waitForCanvasText({ page, text: "Initial content" });+ await waitForSyncStatus({ page, status: "idle" });++ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.imageReplacementTemplateName,+ });+ await waitForCanvasImage({+ page,+ alt: fixture.imageReplacementTemplateImageAlt,+ });++ let uploadedAssetTitle = "";+ await measure("content mode upload image source asset", async () => {+ await openAssetsPanel({ page });+ uploadedAssetTitle = await uploadAsset({+ page,+ filename: uploadFilename,+ });+ });++ await selectCanvasImage({+ page,+ alt: fixture.imageReplacementTemplateImageAlt,+ });+ await measure("content mode choose image source asset", async () => {+ await chooseSelectedAssetProperty({+ page,+ label: "Source",+ assetFilename: uploadFilename,+ });+ });+ await waitForCanvasImageSourceName({ page, sourceName: "upload-image_" });++ let replacementAssetTitle = "";+ await measure("content mode replace used image source asset", async () => {+ await openAssetsPanel({ page });+ await openAssetDetails({+ page,+ filename: uploadedAssetTitle,+ });+ replacementAssetTitle = await replaceSelectedAsset({+ page,+ filename: replacementFilename,+ });+ });+ await waitForCanvasImageSourceName({+ page,+ sourceName: "replacement-image_",+ });++ await measure(+ "content mode reload editor for image source asset replacement",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await waitForCanvasImageSourceName({+ page,+ sourceName: "replacement-image_",+ });+ await openAssetsPanel({ page });+ await page.getByTitle(replacementAssetTitle).waitFor();+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});+test("Editor can delete direct children but not protected containers", async () => {+ const fixture = getSharedContentModeProject();+ const { page, close } = await newIsolatedPage();++ try {+ await measure(+ "content mode open editor for direct child delete",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await waitForCanvasText({ page, text: "Initial content" });+ await waitForSyncStatus({ page, status: "idle" });++ await measure("content mode insert deletable template", async () => {+ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.deletableTemplateName,+ });+ });+ await waitForCanvasText({+ page,+ text: fixture.deletableTemplateText,+ });++ await measure("content mode delete direct child", async () => {+ await deleteContentBlockChildAfterCanvasText({+ page,+ text: fixture.deletableTemplateText,+ });+ });+ await waitForCanvasTextHidden({+ page,+ text: fixture.deletableTemplateText,+ });++ await measure(+ "content mode reload editor for direct child delete",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await waitForCanvasTextHidden({+ page,+ text: fixture.deletableTemplateText,+ });+ await waitForSyncStatus({ page, status: "idle" });++ await measure("content mode insert nested template", async () => {+ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.nestedTemplateName,+ });+ });+ await waitForCanvasText({+ page,+ text: fixture.nestedTemplateText,+ });+ await waitForSyncStatus({ page, status: "idle" });++ await measure("content mode try nested delete", async () => {+ const canvas = await waitForCanvasFrame({ page });+ await page.keyboard.down("Alt");+ try {+ await canvas.getByText(fixture.nestedTemplateText).hover();+ await page+ .getByRole("button", { name: "Delete block" })+ .waitFor({ state: "hidden", timeout: 1_000 });+ } finally {+ await page.keyboard.up("Alt");+ }+ });+ await waitForCanvasText({+ page,+ text: fixture.nestedTemplateText,+ });+ await waitForSyncStatus({ page, status: "idle" });++ await openPagesPanel({ page });+ await expectContentModeTemplateActionsUnavailable({+ page,+ templateName: fixture.pageTemplateName,+ });++ await page.getByRole("tab", { name: "Navigator" }).click();+ await expectTextHidden({ page, text: "Global Root" });+ await expectTextHidden({ page, text: fixture.pageTemplateName });+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});+test("Editor can edit text and content props but not design props", async () => {+ const fixture = getSharedContentModeProject();+ const editedHref = "/edited-link";+ const editedImageSrc =+ "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='80'%3E%3Crect width='120' height='80' fill='%23dff7e8'/%3E%3C/svg%3E";+ const editedImageAlt = "Edited image alt";+ const editedVideoSrc = "https://example.com/edited-video.mp4";+ const editedContent = "Edited isolated content";+ const { page, close } = await newIsolatedPage();++ try {+ await measure("content mode open editor for props", async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ });+ await waitForCanvasText({ page, text: "Initial link" });+ await waitForSyncStatus({ page, status: "idle" });++ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.editableTextTemplateName,+ });+ await waitForCanvasText({+ page,+ text: fixture.editableTextTemplateText,+ });++ await insertTemplateAfterCanvasText({+ page,+ anchorText: "Initial content",+ templateName: fixture.contentPropsTemplateName,+ });+ await waitForCanvasText({+ page,+ text: fixture.contentPropsTemplateLinkText,+ });+ await waitForCanvasImage({+ page,+ alt: fixture.contentPropsTemplateImageAlt,+ });+ await waitForCanvasVideoSource({+ page,+ sourceName: fixture.contentPropsTemplateVideoName,+ });++ await measure("content mode edit text and save", async () => {+ await replaceCanvasText({+ page,+ currentText: fixture.editableTextTemplateText,+ text: editedContent,+ });+ });++ await selectCanvasTextInstanceForProps({+ page,+ text: "Initial link",+ propertyLabel: "Href",+ });+ await expectLocatorHidden({+ locator: page.getByRole("tab", { name: "Style" }),+ message: "Expected Style tab to be unavailable in content mode",+ });+ await expectTextHidden({ page, text: "Style sources" });+ await expectTextHidden({ page, text: "Target" });++ await selectCanvasTextInstanceForProps({+ page,+ text: fixture.contentPropsTemplateLinkText,+ propertyLabel: "Href",+ });+ await fillSelectedStringProperty({+ page,+ label: "Href",+ control: "url",+ value: editedHref,+ });++ await selectCanvasImage({+ page,+ alt: fixture.contentPropsTemplateImageAlt,+ });+ await fillSelectedStringProperty({+ page,+ label: "Source",+ control: "url",+ value: editedImageSrc,+ });+ await fillSelectedStringProperty({+ page,+ label: "Alt",+ control: "text",+ value: editedImageAlt,+ });++ await selectCanvasVideoSource({+ page,+ sourceName: fixture.contentPropsTemplateVideoName,+ });+ await fillSelectedStringProperty({+ page,+ label: "Source",+ control: "url",+ value: editedVideoSrc,+ });++ await measure("content mode reload editor for props", async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ });+ await waitForCanvasText({+ page,+ text: fixture.contentPropsTemplateLinkText,+ });+ await waitForCanvasText({ page, text: editedContent });+ await waitForSyncStatus({ page, status: "idle" });++ await selectCanvasTextInstanceForProps({+ page,+ text: fixture.contentPropsTemplateLinkText,+ propertyLabel: "Href",+ });+ await waitForSelectedStringPropertyValue({+ page,+ label: "Href",+ control: "url",+ value: editedHref,+ });++ await selectCanvasImage({+ page,+ alt: editedImageAlt,+ });+ await waitForSelectedStringPropertyValue({+ page,+ label: "Source",+ control: "url",+ value: editedImageSrc,+ });+ await waitForSelectedStringPropertyValue({+ page,+ label: "Alt",+ control: "text",+ value: editedImageAlt,+ });++ await selectCanvasVideoSource({+ page,+ sourceName: "edited-video.mp4",+ });+ await waitForSelectedStringPropertyValue({+ page,+ label: "Source",+ control: "url",+ value: editedVideoSrc,+ });+ await waitForCanvasText({ page, text: editedContent });+ } finally {+ await close();+ }+});+test("Editor can create styled page from template in content mode", async () => {+ const fixture = getSharedContentModeProject();+ const { page, close } = await newIsolatedPage();+ const pageName = "Created content page";++ try {+ await measure(+ "content mode open editor for page template creation",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await waitForCanvasText({ page, text: "Initial link" });+ await waitForSyncStatus({ page, status: "idle" });++ await measure("content mode create page from template", async () => {+ await createPageFromTemplate({+ page,+ templateName: fixture.pageTemplateName,+ pageName,+ canvasText: fixture.pageTemplateText,+ });+ });+ await waitForCanvasTextStyle({+ page,+ text: fixture.pageTemplateText,+ property: "font-size",+ value: fixture.pageTemplateFontSize,+ });++ await measure(+ "content mode reload created page from template",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ await openPage({+ page,+ pageName,+ canvasText: fixture.pageTemplateText,+ });+ }+ );+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});+test("Editor can edit allowed page settings", async () => {+ const fixture = getSharedContentModeProject();+ const { page, close } = await newIsolatedPage();+ const pageName = "Settings content page";+ const editedName = "Edited settings content page";+ const editedPath = "/edited-settings-content-page";+ const editedTitle = "Edited settings title";+ const editedDescription = "Edited settings description";+ const editedLanguage = "en-US";+ const editedSocialImage = "https://example.com/content-mode-social.png";++ try {+ await measure(+ "content mode open editor for allowed page settings",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await waitForCanvasText({ page, text: "Initial link" });+ await waitForSyncStatus({ page, status: "idle" });++ await createPageFromTemplate({+ page,+ templateName: fixture.pageTemplateName,+ pageName,+ canvasText: fixture.pageTemplateText,+ });+ await openPageSettings({ page, pageName });++ await fillAllowedPageSettings({+ page,+ name: editedName,+ path: editedPath,+ title: editedTitle,+ description: editedDescription,+ language: editedLanguage,+ socialImage: editedSocialImage,+ metadata: {+ property: "content-mode",+ content: "edited metadata",+ },+ });+ await choosePageSettingsSocialImageAsset({+ page,+ filename: fixture.assetTemplateImageName,+ label: fixture.assetTemplateImageAlt,+ });++ await measure(+ "content mode reload editor for allowed page settings",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await openPageSettings({ page, pageName: editedName });+ await page.getByLabel("Page name").waitFor();+ if ((await page.getByLabel("Page name").inputValue()) !== editedName) {+ throw new Error("Expected edited page name to persist");+ }+ if (+ (await getPageSettingsPathInput({ page }).inputValue()) !== editedPath+ ) {+ throw new Error("Expected edited page path to persist");+ }+ if ((await page.getByLabel("Title").inputValue()) !== editedTitle) {+ throw new Error("Expected edited page title to persist");+ }+ if (+ (await page.getByLabel("Description").inputValue()) !== editedDescription+ ) {+ throw new Error("Expected edited page description to persist");+ }+ if (+ (await page+ .getByLabel("Exclude this page from search results")+ .isChecked()) === false+ ) {+ throw new Error("Expected edited search visibility to persist");+ }+ if ((await page.getByLabel("Language").inputValue()) !== editedLanguage) {+ throw new Error("Expected edited page language to persist");+ }+ const socialPreviewImage = page.getByRole("img", {+ name: "Social sharing preview image",+ });+ await socialPreviewImage.waitFor();+ const socialPreviewImageSrc = await socialPreviewImage.getAttribute("src");+ if (+ socialPreviewImageSrc?.includes(fixture.assetTemplateImageName) !== true+ ) {+ throw new Error(+ `Expected social image preview to render ${fixture.assetTemplateImageName}, received ${socialPreviewImageSrc}`+ );+ }+ await expectCustomMetadataValue({+ page,+ property: "content-mode",+ content: "edited metadata",+ });+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});+test("Editor is blocked from invalid paths and restricted page settings", async () => {+ const fixture = getSharedContentModeProject();+ const { page, close } = await newIsolatedPage();+ const pageName = "Blocked settings content page";+ const invalidPaths = ["/posts/:slug", "/docs/*", "https://x.com"];++ try {+ await measure(+ "content mode open editor for blocked page paths",+ async () => {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ });+ }+ );+ await waitForCanvasText({ page, text: "Initial link" });+ await waitForSyncStatus({ page, status: "idle" });++ await createPageFromTemplate({+ page,+ templateName: fixture.pageTemplateName,+ pageName,+ canvasText: fixture.pageTemplateText,+ });+ await openPageSettings({ page, pageName });++ for (const path of invalidPaths) {+ const pathInput = getPageSettingsPathInput({ page });+ await pathInput.fill(path);+ await pathInput.blur();+ await expectContentModePagePathError({ page });+ await waitForSyncStatus({ page, status: "idle" });+ }+ await expectContentModePageSettingsRestrictions({ page });+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});+test("Edit-only and build-capable users can collaborate in content mode", async () => {+ const fixture = getSharedContentModeProject();+ const editor = await newIsolatedPage();+ const builder = await newIsolatedPage();++ try {+ await measure("open editor and builder sessions", async () => {+ await Promise.all([+ openProjectBuilder({+ page: editor.page,+ projectId: fixture.projectId,+ authToken: fixture.editorToken,+ mode: "content",+ }),+ openProjectBuilder({+ page: builder.page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ }),+ ]);+ });+ await waitForCanvasText({ page: editor.page, text: "Initial content" });+ await waitForCanvasText({ page: builder.page, text: "Initial content" });+ await waitForSyncStatus({ page: editor.page, status: "idle" });+ await waitForSyncStatus({ page: builder.page, status: "idle" });++ await insertTemplateAfterCanvasText({+ page: editor.page,+ anchorText: "Initial content",+ templateName: fixture.collaborationTemplateName,+ });+ await waitForCanvasText({+ page: editor.page,+ text: fixture.collaborationTemplateText,+ });+ await waitForSyncStatus({ page: editor.page, status: "idle" });++ await openProjectBuilder({+ page: builder.page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForCanvasText({+ page: builder.page,+ text: fixture.collaborationTemplateText,+ });++ await replaceCanvasText({+ page: editor.page,+ currentText: fixture.collaborationTemplateText,+ text: "Collaborative editor text",+ });+ await waitForSyncStatus({ page: editor.page, status: "idle" });++ await selectCanvasTextInstance({+ page: editor.page,+ text: "Collaborative editor text",+ });+ await expectLocatorHidden({+ locator: editor.page.getByRole("tab", { name: "Style" }),+ message:+ "Expected edit-only collaborator to be blocked from design controls",+ });++ await openProjectBuilder({+ page: builder.page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForCanvasText({+ page: builder.page,+ text: "Collaborative editor text",+ });++ await selectCanvasTextInstance({+ page: builder.page,+ text: "Collaborative editor text",+ });+ await builder.page+ .getByRole("tab", { name: "Style" })+ .waitFor({ state: "visible" });+ await waitForSyncStatus({ page: editor.page, status: "idle" });+ await waitForSyncStatus({ page: builder.page, status: "idle" });+ } finally {+ await editor.close();+ await builder.close();+ }+});diff --git a/apps/builder/e2e/tests/share-link-permissions.e2e.ts b/apps/builder/e2e/tests/share-link-permissions.e2e.tsnew file mode 100644index 0000000000..99195e4696--- /dev/null+++ b/apps/builder/e2e/tests/share-link-permissions.e2e.ts@@ -0,0 +1,302 @@+import { expectLocatorHidden, expectTextHidden } from "../flows/assertions";+import {+ openBuilderUrl,+ openProjectBuilder,+ waitForCanvasText,+} from "../flows/builder";+import {+ selectCanvasTextInstance,+ selectCanvasTextInstanceForProps,+} from "../flows/canvas-selection";+import { replaceCanvasText } from "../flows/content-editing";+import { loginWithSecret } from "../flows/dashboard";+import {+ copyShareLink,+ createShareLink,+ expectShareUnavailable,+ openShareDialog,+ updateShareLinkRole,+} from "../flows/share-dialog";+import { waitForSyncStatus } from "../flows/sync-status";+import { createContentModeProject } from "../fixtures/content-mode-suite";+import { newIsolatedPage, newPage, test } from "../harness";+import { measure } from "../perf";+import { e2ePaidPlanName } from "../plans";++const ownerEmail = "[email protected]";+const baselineText = "Initial content";++type ShareLinkFixtures = {+ projectId: string;+ viewerUrl: string;+ editorUrl: string;+ builderUrl: string;+ adminUrl: string;+ shareLinkEditableText: string;+};++let links: ShareLinkFixtures | undefined;++const getShareLinkFixtures = () => {+ if (links === undefined) {+ throw new Error("Expected share-link fixtures to be initialized");+ }+ return links;+};++const expectLinkMode = ({+ link,+ mode,+}: {+ link: string;+ mode: "preview" | "content" | "design";+}) => {+ const actualMode = new URL(link).searchParams.get("mode");+ if (actualMode !== mode) {+ throw new Error(`Expected share link mode ${mode}, received ${actualMode}`);+ }+};++const expectCurrentMode = ({+ pageUrl,+ mode,+}: {+ pageUrl: string;+ mode: "preview" | "content" | "design";+}) => {+ const actualMode = new URL(pageUrl).searchParams.get("mode");+ if (mode === "design") {+ if (actualMode !== null) {+ throw new Error(`Expected current mode design, received ${actualMode}`);+ }+ return;+ }+ if (actualMode !== mode) {+ throw new Error(`Expected current mode ${mode}, received ${actualMode}`);+ }+};++test.beforeAll(async () => {+ const fixture = await createContentModeProject({+ email: ownerEmail,+ title: "Share Link E2E",+ devPlan: e2ePaidPlanName,+ assetNamePrefix: "share-link-",+ editorToken: "share-link-e2e-editor-token",+ builderToken: "share-link-e2e-builder-token",+ });+ const ownerPage = await newPage();++ try {+ await measure("share link open owner project", async () => {+ await openProjectBuilder({+ page: ownerPage,+ projectId: fixture.projectId,+ });+ });+ await waitForCanvasText({ page: ownerPage, text: baselineText });++ await measure("share link create links", async () => {+ await openShareDialog({ page: ownerPage });+ await createShareLink({+ page: ownerPage,+ name: "E2E Viewer link",+ role: "Viewer",+ });+ const viewerUrl = await copyShareLink({+ page: ownerPage,+ name: "E2E Viewer link",+ });++ await createShareLink({+ page: ownerPage,+ name: "E2E Editor link",+ role: "Editor",+ });+ const editorUrl = await copyShareLink({+ page: ownerPage,+ name: "E2E Editor link",+ });++ await createShareLink({+ page: ownerPage,+ name: "E2E Builder link",+ role: "Builder",+ });+ const builderUrl = await copyShareLink({+ page: ownerPage,+ name: "E2E Builder link",+ });++ await createShareLink({+ page: ownerPage,+ name: "E2E Admin link",+ role: "Admin",+ });+ const adminUrl = await copyShareLink({+ page: ownerPage,+ name: "E2E Admin link",+ });++ links = {+ projectId: fixture.projectId,+ viewerUrl,+ editorUrl,+ builderUrl,+ adminUrl,+ shareLinkEditableText: fixture.shareLinkEditableText,+ };+ });+ } finally {+ await ownerPage.close();+ }+});+test("Share links enforce viewer, editor, builder, admin, and owner permissions", async () => {+ const {+ projectId,+ viewerUrl,+ editorUrl,+ builderUrl,+ adminUrl,+ shareLinkEditableText,+ } = getShareLinkFixtures();+ const viewer = await newIsolatedPage();+ const editor = await newIsolatedPage();+ const builderPage = await newIsolatedPage();+ const admin = await newIsolatedPage();+ const ownerPage = await newPage();+ const visitor = await newIsolatedPage();+ const editedText = "Share-link editor text";++ try {+ expectLinkMode({ link: viewerUrl, mode: "preview" });+ expectLinkMode({ link: editorUrl, mode: "content" });+ expectLinkMode({ link: builderUrl, mode: "design" });+ expectLinkMode({ link: adminUrl, mode: "design" });++ await Promise.all([+ (async () => {+ await openBuilderUrl({ page: viewer.page, url: viewerUrl });+ await waitForCanvasText({ page: viewer.page, text: baselineText });+ await expectShareUnavailable({ page: viewer.page });+ await expectTextHidden({+ page: viewer.page,+ text: "No instance selected",+ });+ await expectLocatorHidden({+ locator: viewer.page.getByRole("tab", { name: "Style" }),+ message: "Expected Style tab to be unavailable for viewer link",+ });+ })(),+ (async () => {+ await openBuilderUrl({ page: builderPage.page, url: builderUrl });+ await waitForCanvasText({+ page: builderPage.page,+ text: baselineText,+ });+ await waitForSyncStatus({ page: builderPage.page, status: "idle" });+ await expectShareUnavailable({ page: builderPage.page });++ await selectCanvasTextInstance({+ page: builderPage.page,+ text: baselineText,+ });+ await builderPage.page+ .getByRole("tab", { name: "Style" })+ .waitFor({ state: "visible", timeout: 10_000 });+ })(),+ (async () => {+ await openBuilderUrl({ page: admin.page, url: adminUrl });+ await waitForCanvasText({ page: admin.page, text: baselineText });+ await waitForSyncStatus({ page: admin.page, status: "idle" });+ await expectShareUnavailable({ page: admin.page });++ const publishButton = admin.page.getByRole("button", {+ name: "Publish",+ });+ await publishButton.waitFor({ state: "visible", timeout: 10_000 });+ if (await publishButton.isDisabled()) {+ throw new Error("Expected admin share link to allow publishing");+ }+ })(),+ ]);++ await openBuilderUrl({ page: editor.page, url: editorUrl });+ await waitForCanvasText({ page: editor.page, text: baselineText });+ await waitForSyncStatus({ page: editor.page, status: "idle" });+ expectCurrentMode({ pageUrl: editor.page.url(), mode: "content" });++ await waitForCanvasText({ page: editor.page, text: shareLinkEditableText });+ await replaceCanvasText({+ page: editor.page,+ currentText: shareLinkEditableText,+ text: editedText,+ });++ await openBuilderUrl({ page: editor.page, url: editorUrl });+ await waitForCanvasText({ page: editor.page, text: editedText });+ await waitForSyncStatus({ page: editor.page, status: "idle" });+ await expectShareUnavailable({ page: editor.page });++ await selectCanvasTextInstanceForProps({+ page: editor.page,+ text: "Initial link",+ propertyLabel: "Href",+ });+ await expectLocatorHidden({+ locator: editor.page.getByRole("tab", { name: "Style" }),+ message: "Expected Style tab to be unavailable for editor link",+ });++ await loginWithSecret({ page: ownerPage, email: ownerEmail });+ await openProjectBuilder({ page: ownerPage, projectId });+ await waitForCanvasText({ page: ownerPage, text: baselineText });++ await openShareDialog({ page: ownerPage });+ await createShareLink({+ page: ownerPage,+ name: "E2E Updated link",+ role: "Viewer",+ });+ const updatedViewerUrl = await copyShareLink({+ page: ownerPage,+ name: "E2E Updated link",+ });+ expectLinkMode({ link: updatedViewerUrl, mode: "preview" });++ await openBuilderUrl({ page: visitor.page, url: updatedViewerUrl });+ await waitForCanvasText({ page: visitor.page, text: baselineText });+ await expectLocatorHidden({+ locator: visitor.page.getByRole("tab", { name: "Style" }),+ message: "Expected updated link to start as viewer",+ });++ await updateShareLinkRole({+ page: ownerPage,+ name: "E2E Updated link",+ role: "Builder",+ });+ const updatedBuilderUrl = await copyShareLink({+ page: ownerPage,+ name: "E2E Updated link",+ });+ expectLinkMode({ link: updatedBuilderUrl, mode: "design" });++ await openBuilderUrl({ page: visitor.page, url: updatedBuilderUrl });+ await waitForCanvasText({ page: visitor.page, text: baselineText });+ await selectCanvasTextInstance({+ page: visitor.page,+ text: baselineText,+ });+ await visitor.page+ .getByRole("tab", { name: "Style" })+ .waitFor({ state: "visible", timeout: 10_000 });+ } finally {+ await viewer.close();+ await editor.close();+ await builderPage.close();+ await admin.close();+ await ownerPage.close();+ await visitor.close();+ }+});diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex b970e05323..3c6ed9ad04 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -13,6 +13,8 @@"start": "remix-serve build/server/index.js","dev": "remix vite:dev","dev:auth": "DEBUG=ws:* remix vite:dev",+ "e2e:ci": "tsx --conditions=webstudio ./e2e/run.ts",+ "e2e:local": "bash ./e2e/run-local.sh","typecheck": "tsgo --noEmit --emitDeclarationOnly false","test": "vitest run"},@@ -48,6 +50,7 @@"@radix-ui/react-tooltip": "^1.2.4","@react-aria/interactions": "^3.23.0","@react-aria/utils": "^3.27.0",+ "@remix-run/express": "^2.16.5","@remix-run/node": "^2.16.5","@remix-run/react": "^2.16.5","@remix-run/serve": "^2.16.5",@@ -92,6 +95,7 @@"debug": "^4.3.7","downshift": "^6.1.7","entrijs": "^0.0.11",+ "express": "^4.21.1","fast-deep-equal": "^3.1.3","immer": "^10.1.1","immerhin": "^0.10.0",@@ -132,6 +136,7 @@"@remix-run/dev": "^2.16.5","@types/debug": "^4.1.12","@types/dom-navigation": "^1.0.5",+ "@types/express": "^4.17.21","@types/papaparse": "^5.5.2","@types/react": "^18.2.70","@types/react-dom": "^18.2.25",@@ -142,6 +147,7 @@"fast-glob": "^3.3.2","html-tags": "^4.0.0","msw": "^2.13.2",+ "playwright": "^1.50.1","react-router-dom": "^6.30.0","react-test-renderer": "18.3.0-canary-14898b6a9-20240318","type-fest": "^4.37.0",diff --git a/package.json b/package.jsonindex 10967c5305..d1d3df70e2 100644--- a/package.json+++ b/package.json@@ -11,6 +11,8 @@"lint": "oxlint --deny-warnings","fixtures": "pnpm -r fixtures:link && pnpm -r fixtures:sync && pnpm -r fixtures:build","checks": "pnpm -r test && pnpm -r typecheck && pnpm lint && pnpm fixtures",+ "e2e:builder": "bash ./apps/builder/e2e/run-local.sh",+ "e2e:builder:update-schema": "E2E_DB_BOOTSTRAP=migrations E2E_WRITE_SCHEMA_SNAPSHOT=true E2E_RUN_TESTS=false bash ./apps/builder/e2e/run-local.sh","playwright": "pnpm -r playwright-init","format": "prettier --write \"**/*.{ts,tsx,md}\"","storybook:dev": "storybook dev -p 6006",diff --git a/packages/project-build/package.json b/packages/project-build/package.jsonindex 84ee4fd4f3..252824a100 100644--- a/packages/project-build/package.json+++ b/packages/project-build/package.json@@ -14,6 +14,15 @@},"./index.server": {"webstudio": "./src/index.server.ts"+ },+ "./build-parser.server": {+ "webstudio": "./src/db/build-parser.ts"+ },+ "./style-source-selections.server": {+ "webstudio": "./src/db/style-source-selections.ts"+ },+ "./styles.server": {+ "webstudio": "./src/db/styles.ts"}},"sideEffects": false,diff --git a/packages/project/package.json b/packages/project/package.jsonindex 117d4e5208..97b2c7f6a9 100644--- a/packages/project/package.json+++ b/packages/project/package.json@@ -41,6 +41,10 @@"./build-patch-core.server": {"webstudio": "./src/db/build-patch-core.ts","import": "./src/db/build-patch-core.ts"+ },+ "./content-mode-permissions": {+ "webstudio": "./src/content-mode-permissions.ts",+ "import": "./src/content-mode-permissions.ts"}},"license": "AGPL-3.0-or-later",diff --git a/packages/project/src/content-mode-permissions.test.ts b/packages/project/src/content-mode-permissions.test.tsnew file mode 100644index 0000000000..3bb58c7d4b--- /dev/null+++ b/packages/project/src/content-mode-permissions.test.ts@@ -0,0 +1,3377 @@+import { describe, expect, test } from "vitest";+import {+ blockComponent,+ blockTemplateComponent,+ getStyleDeclKey,+} from "@webstudio-is/sdk";+import type {+ Instance,+ Prop,+ StyleDecl,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ __testing__,+ applyContentModeTransaction,+ getContentModeCapabilities,+ getContentModeEditableInstanceIds,+ getContentModePropNamesByTag,+ isContentModeCopyableProp,+ isContentModePagePath,+ validateContentModeTransaction,+} from "./content-mode-permissions";+import type { BuildPatchTransaction } from "./db/build-patch-core";++const metas = new Map<string, WsComponentMeta>([+ [+ "Link",+ {+ props: {+ href: {+ type: "string",+ control: "url",+ required: false,+ contentMode: true,+ },+ target: {+ type: "string",+ control: "text",+ required: false,+ },+ },+ },+ ],+]);++const instances = new Map<string, Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "link" }],+ },+ ],+ [+ "link",+ {+ type: "instance",+ id: "link",+ component: "Link",+ children: [],+ },+ ],+]);++const props = new Map<string, Prop>([+ [+ "href-prop",+ {+ id: "href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/",+ },+ ],+ [+ "target-prop",+ {+ id: "target-prop",+ instanceId: "link",+ name: "target",+ type: "string",+ value: "_self",+ },+ ],+]);+const styleSources = new Map([+ ["token", { type: "token" as const, id: "token", name: "Token" }],+ ["local", { type: "local" as const, id: "local" }],+]);++const transaction = (+ namespace: string,+ patches: BuildPatchTransaction["payload"][number]["patches"]+): BuildPatchTransaction => ({+ id: "tx-1",+ payload: [{ namespace, patches }],+});++describe("content mode permissions", () => {+ test("allows only static page paths in content mode", () => {+ expect(isContentModePagePath("/about")).toBe(true);+ expect(isContentModePagePath("")).toBe(true);+ expect(isContentModePagePath("/")).toBe(false);+ expect(isContentModePagePath("about")).toBe(false);+ expect(isContentModePagePath("/about/")).toBe(false);+ expect(isContentModePagePath("/about//team")).toBe(false);+ expect(isContentModePagePath("/s")).toBe(false);+ expect(isContentModePagePath("/build/main.js")).toBe(false);+ expect(isContentModePagePath("/posts/:slug")).toBe(false);+ expect(isContentModePagePath("/docs/*")).toBe(false);+ expect(isContentModePagePath("https://example.com")).toBe(false);+ expect(isContentModePagePath(1)).toBe(false);+ });++ test("derives content-mode prop names by tag", () => {+ expect(+ getContentModePropNamesByTag(+ new Map([+ [+ "Link",+ {+ ...metas.get("Link"),+ presetStyle: { a: [] },+ },+ ],+ ])+ )+ ).toEqual(new Map([["a", new Set(["href"])]]));+ expect(getContentModePropNamesByTag(metas)).toEqual(new Map());+ expect(+ getContentModePropNamesByTag(+ new Map([+ [+ "Link",+ {+ ...metas.get("Link"),+ presetStyle: { a: [] },+ },+ ],+ ])+ )+ .get("a")+ ?.has("target")+ ).toBe(false);+ });++ test("merges content prop names for the same tag", () => {+ expect(+ getContentModePropNamesByTag(+ new Map([+ [+ "Link",+ {+ ...metas.get("Link"),+ presetStyle: { a: [] },+ },+ ],+ [+ "Image",+ {+ presetStyle: { a: [] },+ props: {+ alt: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],+ ])+ )+ ).toEqual(new Map([["a", new Set(["href", "alt"])]]));+ });++ test("derives editable instance ids from default content roots", () => {+ expect(getContentModeEditableInstanceIds({ instances })).toEqual(+ new Set(["block", "link"])+ );+ });++ test("derives editable instance ids from explicit content roots", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["link"]),+ instances,+ })+ ).toEqual(new Set(["link"]));+ });++ test("skips block templates when deriving editable instance ids", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["template"]),+ instances: new Map([+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "link" }],+ },+ ],+ [+ "link",+ {+ type: "instance",+ id: "link",+ component: "Link",+ children: [],+ },+ ],+ ]),+ })+ ).toEqual(new Set());+ });++ test("does not infer block templates as default content roots", () => {+ expect(+ getContentModeEditableInstanceIds({+ instances: new Map([+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "link" }],+ },+ ],+ [+ "link",+ {+ type: "instance",+ id: "link",+ component: "Link",+ children: [],+ },+ ],+ ]),+ })+ ).toEqual(new Set());+ });++ test("does not include instances outside content roots", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["root"]),+ instances: new Map([+ [+ "root",+ {+ type: "instance",+ id: "root",+ component: "Box",+ children: [],+ },+ ],+ [+ "outside",+ {+ type: "instance",+ id: "outside",+ component: "Link",+ children: [],+ },+ ],+ ]),+ })+ ).toEqual(new Set(["root"]));+ });++ test("stops traversal at nested block templates", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["block"]),+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "template" }],+ },+ ],+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "link" }],+ },+ ],+ [+ "link",+ {+ type: "instance",+ id: "link",+ component: "Link",+ children: [],+ },+ ],+ ]),+ })+ ).toEqual(new Set(["block"]));+ });++ test("ignores missing child references while deriving editable instances", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["root"]),+ instances: new Map([+ [+ "root",+ {+ type: "instance",+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "missing" }],+ },+ ],+ ]),+ })+ ).toEqual(new Set(["root"]));+ });++ test("does not loop on recursive instance references", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["root"]),+ instances: new Map([+ [+ "root",+ {+ type: "instance",+ id: "root",+ component: "Box",+ children: [{ type: "id", value: "root" }],+ },+ ],+ ]),+ })+ ).toEqual(new Set(["root"]));+ });++ test("ignores non-id children while deriving editable instances", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["root"]),+ instances: new Map([+ [+ "root",+ {+ type: "instance",+ id: "root",+ component: "Box",+ children: [{ type: "text", value: "Text" }],+ },+ ],+ ]),+ })+ ).toEqual(new Set(["root"]));+ });++ test("ignores missing explicit content roots", () => {+ expect(+ getContentModeEditableInstanceIds({+ contentRootIds: new Set(["missing"]),+ instances,+ })+ ).toEqual(new Set());+ });++ test("validates content-mode page meta values", () => {+ expect(__testing__.isContentModePageMetaValue("title", "Title")).toBe(true);+ expect(__testing__.isContentModePageMetaValue("title", 1)).toBe(false);+ expect(+ __testing__.isContentModePageMetaValue("custom", [+ { property: "og:type", content: "website" },+ ])+ ).toBe(true);+ expect(+ __testing__.isContentModePageMetaValue("custom", [+ { property: "og:type", content: 1 },+ ])+ ).toBe(false);+ expect(__testing__.isContentModePageMetaValue("auth", "value")).toBe(false);+ });++ test("validates content-mode page meta objects", () => {+ expect(+ __testing__.hasOnlyContentModePageMeta({+ title: "Title",+ custom: [{ property: "og:type", content: "website" }],+ })+ ).toBe(true);+ expect(__testing__.hasOnlyContentModePageMeta({ auth: "value" })).toBe(+ false+ );+ });++ test("validates content-mode prop patch values", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ __testing__.isContentModePropPatchValue({+ capabilities,+ editableInstanceIds: new Set(["link"]),+ expectedPropId: "new-href-prop",+ value: {+ id: "new-href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/about",+ },+ })+ ).toBe(true);+ expect(+ __testing__.isContentModePropPatchValue({+ capabilities,+ editableInstanceIds: new Set(["link"]),+ expectedPropId: "new-href-prop",+ value: {+ id: "different-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/about",+ },+ })+ ).toBe(false);+ });++ test("validates that page-created roots contain only added instances", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "existing",+ {+ type: "instance",+ id: "existing",+ component: "Box",+ children: [],+ },+ ],+ [+ "new-root",+ {+ type: "instance",+ id: "new-root",+ component: "Body",+ children: [{ type: "id", value: "new-child" }],+ },+ ],+ [+ "new-child",+ {+ type: "instance",+ id: "new-child",+ component: "Box",+ children: [],+ },+ ],+ ]),+ metas,+ props: new Map(),+ styleSources,+ contentRootIds: new Set(["new-root"]),+ });+ const context = {+ capabilities,+ initialContentRootIds: new Set<string>(),+ initialEditableInstanceIds: new Set<string>(),+ initialEditableInstanceRootIds: new Map<string, string>(),+ initialBlockTemplateChildIdsByInstanceId: new Map(),+ addedInstanceIds: new Set(["new-root", "new-child"]),+ removedEditableInstanceIds: new Set<string>(),+ addedPageIds: new Set<string>(),+ addedLocalStyleSourceIds: new Set<string>(),+ removedLocalStyleSourceIds: new Set<string>(),+ selectedLocalStyleSourceIds: new Set<string>(),+ styledLocalStyleSourceIds: new Set<string>(),+ editableInstanceIds: new Set<string>(),+ };++ expect(+ __testing__.hasOnlyAddedInstancesInSubtree(context, "new-root")+ ).toBe(true);+ capabilities.instances.set("new-root", {+ type: "instance",+ id: "new-root",+ component: "Body",+ children: [{ type: "id", value: "existing" }],+ });+ expect(+ __testing__.hasOnlyAddedInstancesInSubtree(context, "new-root")+ ).toBe(false);+ });++ test("validates duplicate content instance references", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "item" },+ { type: "id", value: "item" },+ ],+ },+ ],+ [+ "item",+ {+ type: "instance",+ id: "item",+ component: "Box",+ children: [],+ },+ ],+ ]),+ metas,+ props: new Map(),+ styleSources,+ });++ expect(+ __testing__.validateEditableInstanceReferences({+ capabilities,+ initialContentRootIds: new Set(["block"]),+ initialEditableInstanceIds: new Set(["block", "item"]),+ initialEditableInstanceRootIds: new Map([["item", "block"]]),+ initialBlockTemplateChildIdsByInstanceId: new Map(),+ addedInstanceIds: new Set(),+ removedEditableInstanceIds: new Set(),+ addedPageIds: new Set<string>(),+ addedLocalStyleSourceIds: new Set(),+ removedLocalStyleSourceIds: new Set(),+ selectedLocalStyleSourceIds: new Set(),+ styledLocalStyleSourceIds: new Set(),+ editableInstanceIds: new Set(["block", "item"]),+ })+ ).toEqual({+ success: false,+ error: "Content instances must not be referenced multiple times.",+ });+ });++ test("uses the same capabilities for UI prop checks and transaction validation", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ breakpoints: new Map([["base", { id: "base", label: "Base" }]]),+ });++ expect(capabilities.editablePropIds.has("href-prop")).toBe(true);+ expect(capabilities.editableInstanceIds).toEqual(+ new Set(["block", "link"])+ );+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ { op: "replace", path: ["href-prop", "value"], value: "/about" },+ ]),+ })+ ).toEqual({ success: true });++ expect(capabilities.editablePropIds.has("target-prop")).toBe(false);+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ { op: "replace", path: ["target-prop", "value"], value: "_blank" },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "target-prop" is not editable in content mode.',+ });+ });++ test("scopes content mode props to content roots", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "outside-link",+ {+ type: "instance",+ id: "outside-link",+ component: "Link",+ children: [],+ },+ ],+ ]),+ metas,+ props: new Map([+ [+ "outside-href-prop",+ {+ id: "outside-href-prop",+ instanceId: "outside-link",+ name: "href",+ type: "string",+ value: "/",+ },+ ],+ ]),+ styleSources,+ });++ expect(capabilities.editablePropIds.has("outside-href-prop")).toBe(false);+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "replace",+ path: ["outside-href-prop", "value"],+ value: "/about",+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "outside-href-prop" is not editable in content mode.',+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "add",+ path: ["new-outside-href-prop"],+ value: {+ id: "new-outside-href-prop",+ instanceId: "outside-link",+ name: "href",+ type: "string",+ value: "/about",+ },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "new-outside-href-prop" is not editable in content mode.',+ });++ const templateCapabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "template" }],+ },+ ],+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "template-link" }],+ },+ ],+ [+ "template-link",+ {+ type: "instance",+ id: "template-link",+ component: "Link",+ children: [],+ },+ ],+ ]),+ metas,+ props: new Map([+ [+ "template-href-prop",+ {+ id: "template-href-prop",+ instanceId: "template-link",+ name: "href",+ type: "string",+ value: "/",+ },+ ],+ ]),+ styleSources,+ });++ expect(templateCapabilities.editablePropIds.has("template-href-prop")).toBe(+ false+ );+ });++ test("supports explicit content roots for template fragment checks", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ contentRootIds: new Set(["link"]),+ });++ expect(capabilities.editablePropIds.has("href-prop")).toBe(true);+ });++ test("validates new content mode props from patch values", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props: new Map(),+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "add",+ path: ["href-prop"],+ value: {+ id: "href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/about",+ },+ },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "add",+ path: ["new-href-prop"],+ value: {+ id: "new-href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/about",+ },+ },+ {+ op: "replace",+ path: ["new-href-prop", "value"],+ value: "/contact",+ },+ ]),+ })+ ).toEqual({ success: true });++ expect(+ validateContentModeTransaction({+ capabilities: getContentModeCapabilities({+ instances,+ metas,+ props: new Map(),+ styleSources,+ }),+ transaction: transaction("props", [+ {+ op: "add",+ path: ["new-href-prop"],+ value: {+ id: "new-href-prop",+ instanceId: "link",+ name: "href",+ type: "number",+ value: 1,+ },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "new-href-prop" is not editable in content mode.',+ });+ });++ test("returns advanced capabilities after applying a content mode transaction", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props: new Map(),+ styleSources,+ });++ const result = applyContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "add",+ path: ["href-prop"],+ value: {+ id: "href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/about",+ },+ },+ ]),+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.capabilities.editablePropIds.has("href-prop")).toBe(true);+ expect(result.capabilities.props.has("href-prop")).toBe(true);+ }+ expect(capabilities.editablePropIds.has("href-prop")).toBe(false);+ expect(capabilities.props.has("href-prop")).toBe(false);+ });++ test("returns updated prop values after applying a content mode transaction", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ const result = applyContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "replace",+ path: ["href-prop", "value"],+ value: "/updated",+ },+ ]),+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.capabilities.props.get("href-prop")).toEqual({+ id: "href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/updated",+ });+ }+ expect(capabilities.props.get("href-prop")).toEqual({+ id: "href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/",+ });+ });++ test("does not mutate shared capabilities while validating transactions", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "props",+ patches: [+ { op: "remove", path: ["href-prop"] },+ {+ op: "add",+ path: ["new-href-prop"],+ value: {+ id: "new-href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/about",+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });++ expect(capabilities.editablePropIds.has("href-prop")).toBe(true);+ expect(capabilities.editablePropIds.has("new-href-prop")).toBe(false);+ expect(capabilities.props.has("href-prop")).toBe(true);+ expect(capabilities.props.has("new-href-prop")).toBe(false);+ });++ test("treats asset props as content props inside content roots", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props: new Map([+ [+ "asset-prop",+ {+ id: "asset-prop",+ instanceId: "link",+ name: "image",+ type: "asset",+ value: "asset-1",+ },+ ],+ ]),+ styleSources,+ });++ expect(capabilities.editablePropIds.has("asset-prop")).toBe(true);+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "replace",+ path: ["asset-prop", "value"],+ value: "asset-2",+ },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "add",+ path: ["new-asset-prop"],+ value: {+ id: "new-asset-prop",+ instanceId: "link",+ name: "image",+ type: "asset",+ value: "asset-1",+ },+ },+ ]),+ })+ ).toEqual({ success: true });+ });++ test("identifies editable and copyable content mode props", () => {+ const contentProps = new Map<string, Prop>([+ [+ "asset-prop",+ {+ id: "asset-prop",+ instanceId: "link",+ name: "image",+ type: "asset",+ value: "asset-1",+ },+ ],+ [+ "expression-prop",+ {+ id: "expression-prop",+ instanceId: "link",+ name: "href",+ type: "expression",+ value: "data",+ },+ ],+ ]);+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props: contentProps,+ styleSources,+ });++ expect(capabilities.editablePropIds.has("asset-prop")).toBe(true);+ expect(+ isContentModeCopyableProp({+ capabilities,+ prop: contentProps.get("asset-prop")!,+ })+ ).toBe(true);+ expect(capabilities.editablePropIds.has("expression-prop")).toBe(false);+ expect(+ isContentModeCopyableProp({+ capabilities,+ prop: contentProps.get("expression-prop")!,+ })+ ).toBe(false);+ });++ test("supports content mode props derived from ws:element tag", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "image-element",+ {+ type: "instance",+ id: "image-element",+ component: "ws:element",+ children: [],+ },+ ],+ ]),+ metas: new Map([+ ["ws:element", {}],+ [+ "Image",+ {+ presetStyle: { img: [] },+ props: {+ alt: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],+ ]),+ props: new Map([+ [+ "tag-prop",+ {+ id: "tag-prop",+ instanceId: "image-element",+ name: "tag",+ type: "string",+ value: "img",+ },+ ],+ [+ "alt-prop",+ {+ id: "alt-prop",+ instanceId: "image-element",+ name: "alt",+ type: "string",+ value: "Previous",+ },+ ],+ ]),+ styleSources,+ contentRootIds: new Set(["image-element"]),+ });++ expect(capabilities.editablePropIds.has("alt-prop")).toBe(true);+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ { op: "replace", path: ["alt-prop", "value"], value: "Updated" },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ {+ op: "add",+ path: ["new-alt-prop"],+ value: {+ id: "new-alt-prop",+ instanceId: "image-element",+ name: "alt",+ type: "string",+ value: "New",+ },+ },+ ]),+ })+ ).toEqual({ success: true });+ });++ test("validates new props against instances added in the same transaction", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ ...instances,+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ } satisfies Instance,+ ],+ ]),+ metas,+ props: new Map(),+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: ["new-href-prop"],+ value: {+ id: "new-href-prop",+ instanceId: "new-link",+ name: "href",+ type: "string",+ value: "/about",+ },+ },+ ],+ },+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-link"],+ value: {+ type: "instance",+ id: "new-link",+ component: "Link",+ children: [],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-link" },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-2",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root-2"],+ value: {+ type: "instance",+ id: "new-root-2",+ component: "Body",+ children: [],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["folders", "root", "children", 0],+ value: "new-page-2",+ },+ {+ op: "add",+ path: ["pages", "new-page-2"],+ value: {+ id: "new-page-2",+ name: "New page 2",+ path: "/new-page-2",+ title: "New page 2",+ rootInstanceId: "new-root-2",+ meta: {},+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });+ });++ test("allows legacy content mode structural namespaces through capabilities", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "template-container" },+ { type: "id", value: "instance-1" },+ ],+ },+ ],+ [+ "template-container",+ {+ type: "instance",+ id: "template-container",+ component: blockTemplateComponent,+ children: [{ type: "id", value: "template-child" }],+ },+ ],+ [+ "template-child",+ {+ type: "instance",+ id: "template-child",+ component: "Box",+ children: [],+ },+ ],+ [+ "instance-1",+ {+ type: "instance",+ id: "instance-1",+ component: "Box",+ children: [],+ },+ ],+ [+ "outside",+ {+ type: "instance",+ id: "outside",+ component: "Box",+ children: [],+ },+ ],+ ]),+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "replace", path: ["instance-1", "children"], value: [] },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-instance"],+ value: {+ type: "instance",+ id: "new-instance",+ component: "Box",+ children: [],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-instance" },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-parent"],+ value: {+ type: "instance",+ id: "new-parent",+ component: "Box",+ children: [{ type: "id", value: "new-child" }],+ },+ },+ {+ op: "add",+ path: ["new-child"],+ value: {+ type: "instance",+ id: "new-child",+ component: "Box",+ children: [],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-parent" },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "add",+ path: ["instance-1", "children", 0],+ value: { type: "text", value: "content" },+ },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "replace",+ path: ["instance-1", "children", 0],+ value: { type: "text", value: "updated" },+ },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["instance-1", "children", 0] },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "add",+ path: ["instance-1", "children", "bad-index"],+ value: { type: "text", value: "content" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-with-outside-child"],+ value: {+ type: "instance",+ id: "new-with-outside-child",+ component: "Box",+ children: [{ type: "id", value: "outside" }],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-with-outside-child" },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Instance patch is outside content roots.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "outside" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "replace",+ path: ["block", "children"],+ value: [{ type: "id", value: "outside" }],+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "add",+ path: ["instance-1", "children", 0],+ value: { type: "unsupported", value: "content" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("styleSourceSelections", [+ {+ op: "add",+ path: ["instance-1"],+ value: { instanceId: "instance-1", values: ["token"] },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error:+ "Style source selections are editable only for new content instances.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("styleSourceSelections", [+ {+ op: "add",+ path: ["instance-1"],+ value: { instanceId: "instance-1", values: ["local"] },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error:+ "Style source selections are editable only for new content instances.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("styleSourceSelections", [+ {+ op: "add",+ path: ["instance-1"],+ value: { instanceId: "instance-1", values: ["missing"] },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error:+ "Style source selections are editable only for new content instances.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block", "children", 1] },+ { op: "remove", path: ["instance-1"] },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["instance-1"] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Removed content instances must not be referenced.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block"] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "replace", path: ["outside", "children"], value: [] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is outside content roots.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["outside"] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is outside content roots.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "replace", path: ["template-child", "children"], value: [] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is outside content roots.",+ });+ });++ test("allows content insertion patches that preserve block template children", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [+ { type: "id", value: "instance-1" },+ { type: "id", value: "template-container" },+ ],+ },+ ],+ [+ "instance-1",+ {+ type: "instance",+ id: "instance-1",+ component: "Box",+ children: [],+ },+ ],+ [+ "template-container",+ {+ type: "instance",+ id: "template-container",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "other-template-container",+ {+ type: "instance",+ id: "other-template-container",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]),+ metas,+ props: new Map(),+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["block", "children", 1],+ value: { type: "id", value: "new-instance" },+ },+ {+ op: "add",+ path: ["block", "children", 2],+ value: { type: "id", value: "template-container" },+ },+ {+ op: "add",+ path: ["new-instance"],+ value: {+ type: "instance",+ id: "new-instance",+ component: "Box",+ children: [],+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "add",+ path: ["block", "children", 1],+ value: { type: "id", value: "other-template-container" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ });++ test("allows cleaning up any props from removed editable instances", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(capabilities.editablePropIds.has("target-prop")).toBe(false);+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ { op: "remove", path: ["block", "children", 0] },+ { op: "remove", path: ["link"] },+ ],+ },+ {+ namespace: "props",+ patches: [+ { op: "remove", path: ["href-prop"] },+ { op: "remove", path: ["target-prop"] },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });+ });++ test("allows cleaning up local styles from removed editable instances", () => {+ const styleDecl: StyleDecl = {+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ };+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ styleSourceSelections: new Map([+ ["link", { instanceId: "link", values: ["local"] }],+ ]),+ styles: new Map([[getStyleDeclKey(styleDecl), styleDecl]]),+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ { op: "remove", path: ["block", "children", 0] },+ { op: "remove", path: ["link"] },+ ],+ },+ {+ namespace: "props",+ patches: [+ { op: "remove", path: ["href-prop"] },+ { op: "remove", path: ["target-prop"] },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [{ op: "remove", path: ["link"] }],+ },+ {+ namespace: "styleSources",+ patches: [{ op: "remove", path: ["local"] }],+ },+ {+ namespace: "styles",+ patches: [{ op: "remove", path: [getStyleDeclKey(styleDecl)] }],+ },+ ],+ },+ })+ ).toEqual({ success: true });+ });++ test("rejects removed editable instances that keep style cleanup data", () => {+ const styleDecl: StyleDecl = {+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ };+ const createCapabilities = () =>+ getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ styleSourceSelections: new Map([+ ["link", { instanceId: "link", values: ["local"] }],+ ]),+ styles: new Map([[getStyleDeclKey(styleDecl), styleDecl]]),+ });+ const removeInstanceAndProps = [+ {+ namespace: "instances",+ patches: [+ { op: "remove" as const, path: ["block", "children", 0] },+ { op: "remove" as const, path: ["link"] },+ ],+ },+ {+ namespace: "props",+ patches: [+ { op: "remove" as const, path: ["href-prop"] },+ { op: "remove" as const, path: ["target-prop"] },+ ],+ },+ ];++ expect(+ validateContentModeTransaction({+ capabilities: createCapabilities(),+ transaction: {+ id: "tx-1",+ payload: removeInstanceAndProps,+ },+ })+ ).toEqual({+ success: false,+ error: "Removed content instances must not keep style selections.",+ });+ expect(+ validateContentModeTransaction({+ capabilities: createCapabilities(),+ transaction: {+ id: "tx-1",+ payload: [+ ...removeInstanceAndProps,+ {+ namespace: "styleSourceSelections",+ patches: [{ op: "remove", path: ["link"] }],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Removed content instances must not keep local style sources.",+ });+ expect(+ validateContentModeTransaction({+ capabilities: createCapabilities(),+ transaction: {+ id: "tx-1",+ payload: [+ ...removeInstanceAndProps,+ {+ namespace: "styleSourceSelections",+ patches: [{ op: "remove", path: ["link"] }],+ },+ {+ namespace: "styleSources",+ patches: [{ op: "remove", path: ["local"] }],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Removed content instances must not keep local styles.",+ });+ });++ test("rejects removed editable instances that keep props", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block", "children", 0] },+ { op: "remove", path: ["link"] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Removed content instances must not keep props.",+ });+ });++ test("rejects orphaning content instances", () => {+ const nestedInstances = new Map<string, Instance>([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "parent" }],+ },+ ],+ [+ "parent",+ {+ type: "instance",+ id: "parent",+ component: "Box",+ children: [{ type: "id", value: "child" }],+ },+ ],+ [+ "child",+ {+ type: "instance",+ id: "child",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const capabilities = getContentModeCapabilities({+ instances: nestedInstances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block", "children", 0] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Content instances must remain reachable from content roots.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block", "children", 0] },+ { op: "remove", path: ["parent"] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Content instances must remain reachable from content roots.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block", "children", 0] },+ { op: "remove", path: ["parent"] },+ { op: "remove", path: ["child"] },+ ]),+ })+ ).toEqual({ success: true });+ });++ test("rejects moving existing content instances between content roots", () => {+ const multiRootInstances = new Map<string, Instance>([+ [+ "block-1",+ {+ type: "instance",+ id: "block-1",+ component: blockComponent,+ children: [{ type: "id", value: "item" }],+ },+ ],+ [+ "block-2",+ {+ type: "instance",+ id: "block-2",+ component: blockComponent,+ children: [],+ },+ ],+ [+ "item",+ {+ type: "instance",+ id: "item",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const capabilities = getContentModeCapabilities({+ instances: multiRootInstances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block-1", "children", 0] },+ {+ op: "add",+ path: ["block-2", "children", 0],+ value: { type: "id", value: "item" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Content instances must stay within their content root.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "remove", path: ["block-1", "children", 0] },+ {+ op: "add",+ path: ["block-1", "children", 0],+ value: { type: "id", value: "item" },+ },+ ]),+ })+ ).toEqual({ success: true });+ });++ test("rejects referencing one content instance from multiple parents", () => {+ const multiRootInstances = new Map<string, Instance>([+ [+ "block-1",+ {+ type: "instance",+ id: "block-1",+ component: blockComponent,+ children: [{ type: "id", value: "item" }],+ },+ ],+ [+ "block-2",+ {+ type: "instance",+ id: "block-2",+ component: blockComponent,+ children: [],+ },+ ],+ [+ "item",+ {+ type: "instance",+ id: "item",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const capabilities = getContentModeCapabilities({+ instances: multiRootInstances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "add",+ path: ["block-2", "children", 0],+ value: { type: "id", value: "item" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Content instances must not be referenced multiple times.",+ });+ });++ test("rejects referencing one new content instance multiple times", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [],+ },+ ],+ ]),+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-instance"],+ value: {+ type: "instance",+ id: "new-instance",+ component: "Box",+ children: [],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-instance" },+ },+ {+ op: "add",+ path: ["block", "children", 1],+ value: { type: "id", value: "new-instance" },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Content instances must not be referenced multiple times.",+ });+ });++ test("allows asset changes", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("assets", [+ {+ op: "add",+ path: ["asset-1"],+ value: { id: "asset-1" },+ },+ ]),+ })+ ).toEqual({ success: true });+ });++ test("allows removing content page meta fields", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "remove",+ path: ["pages", "page-1", "meta", "socialImageUrl"],+ },+ {+ op: "remove",+ path: ["pages", "page-1", "meta", "socialImageAssetId"],+ },+ ]),+ })+ ).toEqual({ success: true });+ });++ test("allows choosing social image asset while clearing social image url", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "socialImageAssetId"],+ value: "asset-1",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "socialImageUrl"],+ value: undefined,+ },+ ]),+ })+ ).toEqual({ success: true });+ });++ test("rejects content prop metadata changes", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ { op: "replace", path: ["href-prop", "name"], value: "target" },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "href-prop" is not editable in content mode.',+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ { op: "remove", path: ["href-prop", "value"] },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "href-prop" is not editable in content mode.',+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("props", [+ { op: "replace", path: ["href-prop", "value"], value: 1 },+ ]),+ })+ ).toEqual({+ success: false,+ error: 'Prop "href-prop" is not editable in content mode.',+ });+ });++ test("rejects instance metadata changes", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ { op: "replace", path: ["link", "component"], value: "Box" },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ });++ test("allows whole-instance replacement when only children change", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "list-item" }],+ },+ ],+ [+ "list-item",+ {+ type: "instance",+ id: "list-item",+ component: "ws:element",+ tag: "li",+ label: "List Item",+ children: [{ type: "text", value: "Old text" }],+ },+ ],+ ]),+ metas,+ props,+ styleSources,+ });++ const result = applyContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "replace",+ path: ["list-item"],+ value: {+ type: "instance",+ id: "list-item",+ component: "ws:element",+ tag: "li",+ label: "List Item",+ children: [{ type: "text", value: "New text" }],+ },+ },+ ]),+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.capabilities.instances.get("list-item")?.children).toEqual([+ { type: "text", value: "New text" },+ ]);+ }+ });++ test("rejects whole-instance replacement when metadata changes", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "list-item" }],+ },+ ],+ [+ "list-item",+ {+ type: "instance",+ id: "list-item",+ component: "ws:element",+ tag: "li",+ label: "List Item",+ children: [{ type: "text", value: "Old text" }],+ },+ ],+ ]),+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "replace",+ path: ["list-item"],+ value: {+ type: "instance",+ id: "list-item",+ component: "ws:element",+ tag: "div",+ label: "List Item",+ children: [{ type: "text", value: "New text" }],+ },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ });++ test("rejects whole-instance replacement with outside child reference", () => {+ const capabilities = getContentModeCapabilities({+ instances: new Map([+ [+ "block",+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "list-item" }],+ },+ ],+ [+ "list-item",+ {+ type: "instance",+ id: "list-item",+ component: "ws:element",+ tag: "li",+ label: "List Item",+ children: [{ type: "text", value: "Old text" }],+ },+ ],+ [+ "outside",+ {+ type: "instance",+ id: "outside",+ component: "Box",+ children: [],+ },+ ],+ ]),+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("instances", [+ {+ op: "replace",+ path: ["list-item"],+ value: {+ type: "instance",+ id: "list-item",+ component: "ws:element",+ tag: "li",+ label: "List Item",+ children: [{ type: "id", value: "outside" }],+ },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Instance patch is not editable in content mode.",+ });+ });++ test("allows limited page field patches", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ { op: "replace", path: ["pages", "page-1", "name"], value: "About" },+ {+ op: "replace",+ path: ["pages", "page-1", "path"],+ value: "/about",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "title"],+ value: "About",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "description"],+ value: "About us",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "excludePageFromSearch"],+ value: "false",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "language"],+ value: "en-US",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "socialImageAssetId"],+ value: "asset-1",+ },+ {+ op: "add",+ path: ["pages", "page-1", "meta", "socialImageAssetId"],+ value: undefined,+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "socialImageUrl"],+ value: "https://example.com/image.png",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "custom"],+ value: [{ property: "og:type", content: "website" }],+ },+ {+ op: "add",+ path: ["pages", "page-1", "meta", "custom", 0],+ value: { property: "", content: '""' },+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "custom", 0, "property"],+ value: "og:title",+ },+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "custom", 0, "content"],+ value: '"About"',+ },+ {+ op: "remove",+ path: ["pages", "page-1", "meta", "custom", 0],+ },+ ]),+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ { op: "remove", path: ["pages", "page-1", "name"] },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "custom", 0, "content"],+ value: 1,+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "custom", 0, "name"],+ value: "og:type",+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1"],+ value: {+ id: "page-1",+ name: "About",+ path: "/about",+ title: "About",+ rootInstanceId: "root-1",+ meta: {},+ },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "meta"],+ value: { description: "About us" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ for (const metaField of [+ "auth",+ "redirect",+ "status",+ "documentType",+ "content",+ ]) {+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "meta", metaField],+ value: "value",+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ }+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ { op: "replace", path: ["pages", "page-1", "title"], value: 1 },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ for (const path of ["/posts/:slug", "/docs/*", "https://example.com"]) {+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "path"],+ value: path,+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ }+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "custom"],+ value: [{ property: "og:type", content: 1 }],+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("pages", [+ {+ op: "replace",+ path: ["pages", "page-1", "meta", "auth", "path"],+ value: "/private",+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-3",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root"],+ value: {+ type: "instance",+ id: "new-root",+ component: "Body",+ children: [],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["pages", "new-page"],+ value: {+ id: "new-page",+ name: "New page",+ path: "/new-page",+ title: "New page",+ rootInstanceId: "new-root",+ marketplace: { include: true },+ meta: {},+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-3",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root-3"],+ value: {+ type: "instance",+ id: "new-root-3",+ component: "Body",+ children: [],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["pages", "new-page-3"],+ value: {+ id: "new-page-3",+ name: "New page 3",+ path: "/new-page-3",+ title: "New page 3",+ rootInstanceId: "new-root-3",+ meta: { custom: [{ property: "og:type", content: 1 }] },+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ });++ test("allows creating a page when its root instance is added in the same transaction", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root"],+ value: {+ type: "instance",+ id: "new-root",+ component: "Body",+ children: [],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["pages", "new-page"],+ value: {+ id: "new-page",+ name: "New page",+ path: "/new-page",+ title: "New page",+ rootInstanceId: "new-root",+ meta: {+ description: "Description",+ custom: [{ property: "og:type", content: "website" }],+ },+ },+ },+ {+ op: "add",+ path: ["folders", "root", "children", 0],+ value: "new-page",+ },+ ],+ },+ ],+ },+ })+ ).toEqual({ success: true });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-3",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root-3"],+ value: {+ type: "instance",+ id: "new-root-3",+ component: "Body",+ children: [{ type: "id", value: "link" }],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["pages", "new-page-3"],+ value: {+ id: "new-page-3",+ name: "New page 3",+ path: "/new-page-3",+ title: "New page 3",+ rootInstanceId: "new-root-3",+ meta: {},+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-dynamic-path",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root-dynamic"],+ value: {+ type: "instance",+ id: "new-root-dynamic",+ component: "Body",+ children: [],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["pages", "new-page-dynamic"],+ value: {+ id: "new-page-dynamic",+ name: "New page dynamic",+ path: "/new-page/:slug",+ title: "New page dynamic",+ rootInstanceId: "new-root-dynamic",+ meta: {},+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ });++ test("rejects page creation with build-owned fields", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root"],+ value: {+ type: "instance",+ id: "new-root",+ component: "Body",+ children: [],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["pages", "new-page"],+ value: {+ id: "new-page",+ name: "New page",+ path: "/new-page",+ title: "New page",+ rootInstanceId: "new-root",+ systemDataSourceId: "system",+ meta: {},+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-2",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-root"],+ value: {+ type: "instance",+ id: "new-root",+ component: "Body",+ children: [],+ },+ },+ ],+ },+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["pages", "new-page"],+ value: {+ id: "new-page",+ name: "New page",+ path: "/new-page",+ title: "New page",+ rootInstanceId: "new-root",+ meta: {+ auth: { method: "basic", login: "u", password: "p" },+ },+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "Page patch is not editable in content mode.",+ });+ });++ test("allows styles only for local style sources created in the same transaction", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });+ const styleDecl: StyleDecl = {+ styleSourceId: "new-local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ };++ const result = validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-1",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-link"],+ value: {+ type: "instance",+ id: "new-link",+ component: "Link",+ children: [],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-link" },+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["new-link"],+ value: { instanceId: "new-link", values: ["new-local"] },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: [getStyleDeclKey(styleDecl)],+ value: styleDecl,+ },+ ],+ },+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["new-local"],+ value: { type: "local", id: "new-local" },+ },+ ],+ },+ ],+ },+ });++ expect(result).toEqual({ success: true });+ expect(capabilities.styleSources.has("new-local")).toBe(false);++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("styleSources", [+ {+ op: "add",+ path: ["new-token"],+ value: { type: "token", id: "new-token", name: "Token" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error: "Only new local style sources are editable in content mode.",+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("styles", [+ {+ op: "replace",+ path: [+ getStyleDeclKey({+ ...styleDecl,+ styleSourceId: "local",+ }),+ ],+ value: { ...styleDecl, styleSourceId: "local" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error:+ "Only styles for new local style sources are editable in content mode.",+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-2",+ payload: [+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: [getStyleDeclKey(styleDecl)],+ value: styleDecl,+ },+ ],+ },+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["new-local"],+ value: { type: "local", id: "new-local" },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error:+ "New local style sources must be selected by new content instances.",+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("styleSources", [+ {+ op: "add",+ path: ["unused-local"],+ value: { type: "local", id: "unused-local" },+ },+ ]),+ })+ ).toEqual({+ success: false,+ error:+ "New local style sources must be selected by new content instances.",+ });+ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-3",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-empty-style-link"],+ value: {+ type: "instance",+ id: "new-empty-style-link",+ component: "Link",+ children: [],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-empty-style-link" },+ },+ ],+ },+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["empty-local"],+ value: { type: "local", id: "empty-local" },+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["new-empty-style-link"],+ value: {+ instanceId: "new-empty-style-link",+ values: ["empty-local"],+ },+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error: "New local style sources must have styles in content mode.",+ });+ });++ test("rejects styles for missing breakpoints", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ breakpoints: new Map([["base", { id: "base", label: "Base" }]]),+ });+ const styleDecl: StyleDecl = {+ styleSourceId: "missing-breakpoint-local",+ breakpointId: "missing",+ property: "color",+ value: { type: "keyword", value: "red" },+ };++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: {+ id: "tx-missing-breakpoint",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["new-missing-breakpoint-link"],+ value: {+ type: "instance",+ id: "new-missing-breakpoint-link",+ component: "Link",+ children: [],+ },+ },+ {+ op: "add",+ path: ["block", "children", 0],+ value: { type: "id", value: "new-missing-breakpoint-link" },+ },+ ],+ },+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["missing-breakpoint-local"],+ value: { type: "local", id: "missing-breakpoint-local" },+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["new-missing-breakpoint-link"],+ value: {+ instanceId: "new-missing-breakpoint-link",+ values: ["missing-breakpoint-local"],+ },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: [+ getStyleDeclKey({+ ...styleDecl,+ }),+ ],+ value: styleDecl,+ },+ ],+ },+ ],+ },+ })+ ).toEqual({+ success: false,+ error:+ "Only styles for existing breakpoints are editable in content mode.",+ });+ });++ test("rejects design namespaces", () => {+ const capabilities = getContentModeCapabilities({+ instances,+ metas,+ props,+ styleSources,+ });++ expect(+ validateContentModeTransaction({+ capabilities,+ transaction: transaction("styles", [+ { op: "add", path: ["style-1"], value: {} },+ ]),+ })+ ).toEqual({+ success: false,+ error:+ "Only styles for new local style sources are editable in content mode.",+ });+ });+});diff --git a/packages/project/src/content-mode-permissions.ts b/packages/project/src/content-mode-permissions.tsnew file mode 100644index 0000000000..3c7445c91c--- /dev/null+++ b/packages/project/src/content-mode-permissions.ts@@ -0,0 +1,1623 @@+import type { Patch } from "immer";+import {+ Instance as InstanceSchema,+ InstanceChild as InstanceChildSchema,+ Prop as PropSchema,+ StyleDecl as StyleDeclSchema,+ StyleSource as StyleSourceSchema,+ StyleSourceSelection as StyleSourceSelectionSchema,+ PagePath,+ blockComponent,+ blockTemplateComponent,+ getHtmlTagsFromProps,+ getHtmlTagFromInstance,+ isPathnamePattern,+ getStyleDeclKey,+ type Breakpoints,+ type Instance,+ type Prop,+ type Props,+ type StyleDecl,+ type StyleSource,+ type StyleSourceSelections,+ type StyleSources,+ type Styles,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import type { BuildPatchTransaction } from "./db/build-patch-core";++export type ContentModeCapabilities = {+ editablePropIds: Set<Prop["id"]>;+ editableInstanceIds: Set<Instance["id"]>;+ instances: Map<Instance["id"], Instance>;+ metas: Map<Instance["component"], WsComponentMeta>;+ props: Props;+ htmlTagsByInstanceId: Map<Instance["id"], string>;+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+ breakpoints?: Breakpoints;+ contentRootIds: Set<Instance["id"]>;+};++type ContentModeTransactionContext = {+ capabilities: ContentModeCapabilities;+ initialContentRootIds: Set<Instance["id"]>;+ initialEditableInstanceIds: Set<Instance["id"]>;+ initialEditableInstanceRootIds: Map<Instance["id"], Instance["id"]>;+ initialBlockTemplateChildIdsByInstanceId: Map<+ Instance["id"],+ Set<Instance["id"]>+ >;+ addedInstanceIds: Set<Instance["id"]>;+ removedEditableInstanceIds: Set<Instance["id"]>;+ addedPageIds: Set<string>;+ addedLocalStyleSourceIds: Set<StyleSource["id"]>;+ removedLocalStyleSourceIds: Set<StyleSource["id"]>;+ selectedLocalStyleSourceIds: Set<StyleSource["id"]>;+ styledLocalStyleSourceIds: Set<StyleSource["id"]>;+ editableInstanceIds: Set<Instance["id"]>;+};++export type ContentModeValidationResult =+ | { success: true }+ | { success: false; error: string };++export type AppliedContentModeTransactionResult =+ | { success: true; capabilities: ContentModeCapabilities }+ | { success: false; error: string };++const contentModePageFields = new Set(["name", "path", "title"]);++export const isContentModePagePath = (value: unknown) =>+ typeof value === "string" &&+ (value === "" || PagePath.safeParse(value).success) &&+ isPathnamePattern(value) === false &&+ value.includes(":") === false &&+ value.includes("*") === false;++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null;++const isString = (value: unknown) => typeof value === "string";+const isOptionalString = (value: unknown) =>+ value === undefined || typeof value === "string";++const isContentModeCustomMeta = (value: unknown) =>+ Array.isArray(value) &&+ value.every(+ (item) =>+ isRecord(item) &&+ typeof item.property === "string" &&+ typeof item.content === "string"+ );++const contentModePageMetaValidators: Record<+ string,+ (value: unknown) => boolean+> = {+ description: isString,+ title: isString,+ excludePageFromSearch: isString,+ language: isString,+ socialImageAssetId: isOptionalString,+ socialImageUrl: isOptionalString,+ custom: isContentModeCustomMeta,+};++export const contentModePageMetaFields = new Set(+ Object.keys(contentModePageMetaValidators)+);++const isContentModePageMetaValue = (field: string, value: unknown) => {+ return contentModePageMetaValidators[field]?.(value) ?? false;+};++const isContentModeCustomMetaPatch = (patch: Patch) => {+ const [, , , , index, field] = patch.path;+ if (typeof index !== "number") {+ return false;+ }++ if (patch.path.length === 5) {+ if (patch.op === "remove") {+ return true;+ }+ return (+ (patch.op === "add" || patch.op === "replace") &&+ isRecord(patch.value) &&+ typeof patch.value.property === "string" &&+ typeof patch.value.content === "string"+ );+ }++ if (patch.path.length !== 6) {+ return false;+ }+ if (field !== "property" && field !== "content") {+ return false;+ }+ return patch.op === "replace" && typeof patch.value === "string";+};++export const getContentModePropNamesByTag = (+ metas: Map<Instance["component"], WsComponentMeta>+) => {+ const propNamesByTag = new Map<string, Set<Prop["name"]>>();++ for (const meta of metas.values()) {+ const tags = Object.keys(meta.presetStyle ?? {});+ if (tags.length === 0) {+ continue;+ }+ for (const [propName, propMeta] of Object.entries(meta.props ?? {})) {+ if (propMeta.contentMode !== true) {+ continue;+ }+ for (const tag of tags) {+ let propNames = propNamesByTag.get(tag);+ if (propNames === undefined) {+ propNames = new Set();+ propNamesByTag.set(tag, propNames);+ }+ propNames.add(propName);+ }+ }+ }++ return propNamesByTag;+};++const getDefaultContentRootIds = (instances: Map<Instance["id"], Instance>) => {+ const contentRootIds = new Set<Instance["id"]>();+ for (const instance of instances.values()) {+ if (instance.component === blockComponent) {+ contentRootIds.add(instance.id);+ }+ }+ return contentRootIds;+};++export const getContentModeEditableInstanceIds = ({+ contentRootIds,+ instances,+}: {+ contentRootIds?: Set<Instance["id"]>;+ instances: Map<Instance["id"], Instance>;+}) => {+ contentRootIds ??= getDefaultContentRootIds(instances);+ return new Set(+ getContentModeEditableInstanceRootIds({+ contentRootIds,+ instances,+ }).keys()+ );+};++const getContentModeEditableInstanceRootIds = ({+ contentRootIds,+ instances,+}: {+ contentRootIds: Set<Instance["id"]>;+ instances: Map<Instance["id"], Instance>;+}) => {+ const editableInstanceIds = new Set<Instance["id"]>();+ const rootIdsByInstanceId = new Map<Instance["id"], Instance["id"]>();+ const visit = (instanceId: Instance["id"], rootId: Instance["id"]) => {+ if (editableInstanceIds.has(instanceId)) {+ return;+ }+ const instance = instances.get(instanceId);+ if (+ instance === undefined ||+ instance.component === blockTemplateComponent+ ) {+ return;+ }+ editableInstanceIds.add(instanceId);+ rootIdsByInstanceId.set(instanceId, rootId);+ for (const child of instance.children) {+ if (child.type === "id") {+ visit(child.value, rootId);+ }+ }+ };+ for (const rootId of contentRootIds) {+ visit(rootId, rootId);+ }+ return rootIdsByInstanceId;+};++const getBlockTemplateChildIdsByInstanceId = (+ instances: Map<Instance["id"], Instance>+) => {+ const childIdsByInstanceId = new Map<Instance["id"], Set<Instance["id"]>>();+ for (const instance of instances.values()) {+ const blockTemplateChildIds = new Set<Instance["id"]>();+ for (const child of instance.children) {+ if (child.type !== "id") {+ continue;+ }+ if (instances.get(child.value)?.component === blockTemplateComponent) {+ blockTemplateChildIds.add(child.value);+ }+ }+ if (blockTemplateChildIds.size > 0) {+ childIdsByInstanceId.set(instance.id, blockTemplateChildIds);+ }+ }+ return childIdsByInstanceId;+};++const getContentModePropMeta = ({+ capabilities,+ instance,+ propName,+}: {+ capabilities: ContentModeCapabilities;+ instance: Instance;+ propName: Prop["name"];+}) => {+ const meta = capabilities.metas.get(instance.component);+ const propMeta = meta?.props?.[propName];+ if (propMeta?.contentMode === true) {+ return propMeta;+ }++ const tag = getHtmlTagFromInstance({+ instance,+ metas: capabilities.metas,+ props: capabilities.props,+ htmlTagsByInstanceId: capabilities.htmlTagsByInstanceId,+ });+ if (tag === undefined) {+ return;+ }+ for (const componentMeta of capabilities.metas.values()) {+ if (Object.keys(componentMeta.presetStyle ?? {}).includes(tag) === false) {+ continue;+ }+ const propMeta = componentMeta.props?.[propName];+ if (propMeta?.contentMode === true) {+ return propMeta;+ }+ }+};++const isContentModePropForInstance = ({+ capabilities,+ instance,+ prop,+}: {+ capabilities: ContentModeCapabilities;+ instance: Instance;+ prop: Prop;+}) =>+ prop.type === "asset" ||+ getContentModePropMeta({+ capabilities,+ instance,+ propName: prop.name,+ })?.type === prop.type;++const contentModeNonCopyablePropTypes = new Set<Prop["type"]>([+ "resource",+ "parameter",+ "expression",+ "action",+ "animationAction",+]);++export const isContentModeCopyableProp = ({+ capabilities,+ prop,+}: {+ capabilities: ContentModeCapabilities;+ prop: Prop;+}) =>+ capabilities.editablePropIds.has(prop.id) &&+ contentModeNonCopyablePropTypes.has(prop.type) === false;++export const getContentModeCapabilities = ({+ instances,+ metas,+ props,+ styleSources,+ styleSourceSelections = new Map(),+ styles = new Map(),+ breakpoints,+ contentRootIds: providedContentRootIds,+}: {+ instances: Map<Instance["id"], Instance>;+ metas: Map<Instance["component"], WsComponentMeta>;+ props: Props;+ styleSources: StyleSources;+ styleSourceSelections?: StyleSourceSelections;+ styles?: Styles;+ breakpoints?: Breakpoints;+ contentRootIds?: Set<Instance["id"]>;+}): ContentModeCapabilities => {+ const editablePropIds = new Set<Prop["id"]>();+ const contentRootIds = new Set<Instance["id"]>();+ for (const instanceId of providedContentRootIds ??+ getDefaultContentRootIds(instances)) {+ if (instances.has(instanceId)) {+ contentRootIds.add(instanceId);+ }+ }+ const editableInstanceIds = getContentModeEditableInstanceIds({+ contentRootIds,+ instances,+ });+ const capabilities = {+ editablePropIds,+ editableInstanceIds,+ instances,+ metas,+ props,+ htmlTagsByInstanceId: getHtmlTagsFromProps(props),+ styleSources,+ styleSourceSelections,+ styles,+ breakpoints,+ contentRootIds,+ };+ for (const prop of props.values()) {+ const instance = instances.get(prop.instanceId);+ if (instance === undefined) {+ continue;+ }+ if (editableInstanceIds.has(instance.id) === false) {+ continue;+ }+ if (isContentModePropForInstance({ capabilities, instance, prop })) {+ editablePropIds.add(prop.id);+ }+ }++ return capabilities;+};++const isContentModePropPatchValue = ({+ capabilities,+ editableInstanceIds,+ expectedPropId,+ value,+}: {+ capabilities: ContentModeCapabilities;+ editableInstanceIds: Set<Instance["id"]>;+ expectedPropId: Prop["id"];+ value: unknown;+}) => {+ const prop = PropSchema.safeParse(value);+ if (prop.success === false) {+ return false;+ }++ if (prop.data.id !== expectedPropId) {+ return false;+ }++ const instance = capabilities.instances.get(prop.data.instanceId);+ if (instance === undefined) {+ return false;+ }+ if (editableInstanceIds.has(instance.id) === false) {+ return false;+ }++ return isContentModePropForInstance({+ capabilities,+ instance,+ prop: prop.data,+ });+};++const validatePropPatch = (+ context: ContentModeTransactionContext,+ patch: Patch+): ContentModeValidationResult => {+ const { capabilities } = context;+ const [propId] = patch.path;+ if (typeof propId !== "string") {+ return {+ success: false,+ error: "Prop patch is not editable in content mode.",+ };+ }++ if (patch.op === "remove" && patch.path.length === 1) {+ const prop = capabilities.props.get(propId);+ if (prop && context.removedEditableInstanceIds.has(prop.instanceId)) {+ capabilities.editablePropIds.delete(propId);+ capabilities.props.delete(propId);+ return { success: true };+ }+ }++ if (capabilities.editablePropIds.has(propId)) {+ if (patch.op === "remove" && patch.path.length === 1) {+ capabilities.editablePropIds.delete(propId);+ capabilities.props.delete(propId);+ return { success: true };+ }+ const prop = capabilities.props.get(propId);+ if (+ prop &&+ patch.path.length === 2 &&+ patch.path[1] === "value" &&+ (patch.op === "add" || patch.op === "replace") &&+ PropSchema.safeParse({ ...prop, value: patch.value }).success+ ) {+ capabilities.props.set(propId, { ...prop, value: patch.value } as Prop);+ return { success: true };+ }+ }++ if (+ patch.path.length === 1 &&+ (patch.op === "add" || patch.op === "replace") &&+ isContentModePropPatchValue({+ capabilities,+ editableInstanceIds: context.editableInstanceIds,+ expectedPropId: propId,+ value: patch.value,+ })+ ) {+ capabilities.editablePropIds.add(propId);+ capabilities.props.set(propId, patch.value as Prop);+ return { success: true };+ }++ return {+ success: false,+ error: `Prop "${propId}" is not editable in content mode.`,+ };+};++const isContentModePagePatch = (patch: Patch) => {+ const [collection, pageId, field, metaField] = patch.path;+ if (+ collection !== "pages" ||+ typeof pageId !== "string" ||+ typeof field !== "string"+ ) {+ return false;+ }++ // Page patches are scoped as ["pages", pageId, field].+ // Editors can change only a small set of top-level editorial fields.+ // Whole-page add/replace/remove patches like ["pages", pageId] stay build-only+ // because they can change rootInstanceId, system data sources, folders, etc.+ if (patch.path.length === 3 && contentModePageFields.has(field)) {+ if (field === "path") {+ return isContentModePagePath(patch.value);+ }+ return typeof patch.value === "string";+ }++ // Meta field patches are scoped as ["pages", pageId, "meta", metaField].+ // Keep this list explicit: page meta also contains auth, redirects, status,+ // document type, and raw content settings that are not content editing.+ if (field !== "meta" || typeof metaField !== "string") {+ return false;+ }++ if (metaField === "custom" && patch.path.length > 4) {+ return isContentModeCustomMetaPatch(patch);+ }++ if (+ patch.path.length !== 4 ||+ contentModePageMetaFields.has(metaField) === false+ ) {+ return false;+ }++ if (patch.op === "remove") {+ return true;+ }++ return isContentModePageMetaValue(metaField, patch.value);+};++const hasOnlyContentModePageMeta = (meta: Record<string, unknown>) => {+ for (const [field, value] of Object.entries(meta)) {+ if (contentModePageMetaFields.has(field) === false) {+ return false;+ }+ if (isContentModePageMetaValue(field, value) === false) {+ return false;+ }+ }+ return true;+};++const isInstanceChild = (value: unknown) =>+ InstanceChildSchema.safeParse(value).success;++const isInstanceChildren = (value: unknown) =>+ Array.isArray(value) && value.every(isInstanceChild);++const isEditableChildrenPatch = (patch: Patch) => {+ if (patch.path.length === 2 && patch.op === "replace") {+ return isInstanceChildren(patch.value);+ }+ if (patch.path.length !== 3 || typeof patch.path[2] !== "number") {+ return false;+ }+ if (patch.op === "remove") {+ return true;+ }+ if (patch.op === "add" || patch.op === "replace") {+ return isInstanceChild(patch.value);+ }+ return false;+};++const isAllowedContentModeChildReference = (+ context: ContentModeTransactionContext,+ instanceId: Instance["id"],+ child: Instance["children"][number]+) =>+ child.type !== "id" ||+ context.initialEditableInstanceIds.has(child.value) ||+ context.addedInstanceIds.has(child.value) ||+ context.initialBlockTemplateChildIdsByInstanceId+ .get(instanceId)+ ?.has(child.value) === true;++const isAllowedContentModeChildrenPatch = (+ context: ContentModeTransactionContext,+ patch: Patch+) => {+ const [instanceId] = patch.path;+ if (typeof instanceId !== "string") {+ return false;+ }+ if (patch.op === "remove") {+ return true;+ }+ if (patch.path.length === 2) {+ if (isInstanceChildren(patch.value) === false) {+ return false;+ }+ const children = patch.value as Instance["children"];+ return children.every((child) =>+ isAllowedContentModeChildReference(context, instanceId, child)+ );+ }+ return (+ isInstanceChild(patch.value) &&+ isAllowedContentModeChildReference(context, instanceId, patch.value)+ );+};++const hasOnlyAllowedContentModeChildReferences = (+ context: ContentModeTransactionContext,+ instance: Instance+) =>+ instance.children.every((child) =>+ isAllowedContentModeChildReference(context, instance.id, child)+ );++const hasSameInstanceMetadata = (left: Instance, right: Instance) =>+ left.type === right.type &&+ left.id === right.id &&+ left.component === right.component &&+ left.tag === right.tag &&+ left.label === right.label;++const hasOnlyKeys = (value: Record<string, unknown>, keys: Set<string>) => {+ for (const key of Object.keys(value)) {+ if (keys.has(key) === false) {+ return false;+ }+ }+ return true;+};++const contentModePageCreateFields = new Set([+ "id",+ "name",+ "path",+ "title",+ "rootInstanceId",+ "meta",+]);++const hasOnlyAddedInstancesInSubtree = (+ context: ContentModeTransactionContext,+ rootInstanceId: Instance["id"]+) => {+ const visited = new Set<Instance["id"]>();+ const visit = (instanceId: Instance["id"]): boolean => {+ if (visited.has(instanceId)) {+ return true;+ }+ if (context.addedInstanceIds.has(instanceId) === false) {+ return false;+ }+ visited.add(instanceId);+ const instance = context.capabilities.instances.get(instanceId);+ if (instance === undefined) {+ return false;+ }+ for (const child of instance.children) {+ if (child.type === "id" && visit(child.value) === false) {+ return false;+ }+ }+ return true;+ };+ return visit(rootInstanceId);+};++const validatePagePatch = (+ context: ContentModeTransactionContext,+ patch: Patch+): ContentModeValidationResult => {+ if (isContentModePagePatch(patch)) {+ return { success: true };+ }++ const [collection, pageId] = patch.path;+ if (+ collection === "pages" &&+ typeof pageId === "string" &&+ patch.path.length === 2 &&+ patch.op === "add"+ ) {+ const page = patch.value;+ if (+ isRecord(page) &&+ page.id === pageId &&+ typeof page.name === "string" &&+ isContentModePagePath(page.path) &&+ typeof page.title === "string" &&+ typeof page.rootInstanceId === "string" &&+ isRecord(page.meta) &&+ hasOnlyKeys(page, contentModePageCreateFields) &&+ context.addedInstanceIds.has(page.rootInstanceId) &&+ hasOnlyAddedInstancesInSubtree(context, page.rootInstanceId) &&+ hasOnlyContentModePageMeta(page.meta)+ ) {+ context.addedPageIds.add(pageId);+ context.capabilities.contentRootIds.add(page.rootInstanceId);+ return { success: true };+ }+ }++ if (+ collection === "folders" &&+ typeof pageId === "string" &&+ patch.path[2] === "children" &&+ patch.path.length === 4 &&+ patch.op === "add" &&+ typeof patch.value === "string" &&+ context.addedPageIds.has(patch.value)+ ) {+ return { success: true };+ }++ return {+ success: false,+ error: "Page patch is not editable in content mode.",+ };+};++const isPageFolderChildPatch = (patch: Patch) => {+ const [collection, folderId, field] = patch.path;+ return (+ collection === "folders" &&+ typeof folderId === "string" &&+ field === "children"+ );+};++const validatePagePatches = (+ context: ContentModeTransactionContext,+ patches: Patch[]+): ContentModeValidationResult => {+ for (const patch of patches) {+ if (isPageFolderChildPatch(patch)) {+ continue;+ }+ const result = validatePagePatch(context, patch);+ if (result.success === false) {+ return result;+ }+ }++ for (const patch of patches) {+ if (isPageFolderChildPatch(patch) === false) {+ continue;+ }+ const result = validatePagePatch(context, patch);+ if (result.success === false) {+ return result;+ }+ }++ return { success: true };+};++const validateInstancePatch = (+ context: ContentModeTransactionContext,+ patch: Patch+): ContentModeValidationResult => {+ const [instanceId, field] = patch.path;+ if (typeof instanceId !== "string") {+ return {+ success: false,+ error: "Instance patch is not editable in content mode.",+ };+ }++ if (patch.op === "remove" && patch.path.length === 1) {+ if (context.initialContentRootIds.has(instanceId)) {+ return {+ success: false,+ error: "Instance patch is not editable in content mode.",+ };+ }+ return context.removedEditableInstanceIds.has(instanceId) ||+ context.editableInstanceIds.has(instanceId)+ ? { success: true }+ : {+ success: false,+ error: "Instance patch is outside content roots.",+ };+ }++ if (+ field === "children" &&+ isEditableChildrenPatch(patch) &&+ isAllowedContentModeChildrenPatch(context, patch)+ ) {+ return context.editableInstanceIds.has(instanceId)+ ? { success: true }+ : {+ success: false,+ error: "Instance patch is outside content roots.",+ };+ }++ if (patch.path.length === 1 && patch.op === "replace") {+ const instance = InstanceSchema.safeParse(patch.value);+ if (+ instance.success &&+ instance.data.id === instanceId &&+ hasOnlyAllowedContentModeChildReferences(context, instance.data)+ ) {+ return context.editableInstanceIds.has(instanceId)+ ? { success: true }+ : {+ success: false,+ error: "Instance patch is outside content roots.",+ };+ }+ }++ if (+ patch.path.length === 1 &&+ patch.op === "add" &&+ context.addedInstanceIds.has(instanceId)+ ) {+ const instance = InstanceSchema.safeParse(patch.value);+ if (+ instance.success &&+ instance.data.id === instanceId &&+ context.editableInstanceIds.has(instanceId) &&+ hasOnlyAllowedContentModeChildReferences(context, instance.data)+ ) {+ return { success: true };+ }+ if (instance.success && instance.data.id === instanceId) {+ return {+ success: false,+ error: "Instance patch is outside content roots.",+ };+ }+ }++ return {+ success: false,+ error: "Instance patch is not editable in content mode.",+ };+};++const validateInstancePatchShape = (+ capabilities: ContentModeCapabilities,+ patch: Patch+): ContentModeValidationResult => {+ const [instanceId, field] = patch.path;+ if (typeof instanceId !== "string") {+ return {+ success: false,+ error: "Instance patch is not editable in content mode.",+ };+ }++ if (patch.op === "remove" && patch.path.length === 1) {+ return { success: true };+ }++ if (field === "children" && isEditableChildrenPatch(patch)) {+ return { success: true };+ }++ if (patch.path.length === 1 && patch.op === "replace") {+ const instance = InstanceSchema.safeParse(patch.value);+ const currentInstance = capabilities.instances.get(instanceId);+ if (+ instance.success &&+ instance.data.id === instanceId &&+ currentInstance !== undefined &&+ hasSameInstanceMetadata(currentInstance, instance.data)+ ) {+ return { success: true };+ }+ }++ if (+ patch.path.length === 1 &&+ patch.op === "add" &&+ capabilities.instances.has(instanceId) === false+ ) {+ const instance = InstanceSchema.safeParse(patch.value);+ if (instance.success && instance.data.id === instanceId) {+ return { success: true };+ }+ }++ return {+ success: false,+ error: "Instance patch is not editable in content mode.",+ };+};++const validateStyleSourceSelectionPatch = (+ context: ContentModeTransactionContext,+ patch: Patch+): ContentModeValidationResult => {+ const { capabilities } = context;+ const [instanceId] = patch.path;+ if (typeof instanceId !== "string") {+ return {+ success: false,+ error: "Style source selection patch is not editable in content mode.",+ };+ }++ if (+ patch.op === "remove" &&+ patch.path.length === 1 &&+ context.removedEditableInstanceIds.has(instanceId)+ ) {+ capabilities.styleSourceSelections.delete(instanceId);+ return { success: true };+ }++ if (context.editableInstanceIds.has(instanceId) === false) {+ return {+ success: false,+ error: "Style source selection patch is outside content roots.",+ };+ }+ if (context.addedInstanceIds.has(instanceId) === false) {+ return {+ success: false,+ error:+ "Style source selections are editable only for new content instances.",+ };+ }++ if (+ patch.path.length !== 1 ||+ (patch.op !== "add" && patch.op !== "replace")+ ) {+ return {+ success: false,+ error: "Style source selection patch is not editable in content mode.",+ };+ }++ const selection = StyleSourceSelectionSchema.safeParse(patch.value);+ if (selection.success === false) {+ return {+ success: false,+ error: "Style source selection patch is not editable in content mode.",+ };+ }+ if (selection.data.instanceId !== instanceId) {+ return {+ success: false,+ error: "Style source selection patch is not editable in content mode.",+ };+ }++ for (const styleSourceId of selection.data.values) {+ const styleSource = capabilities.styleSources.get(styleSourceId);+ const isAllowedExistingStyleSource = styleSource?.type === "token";+ const isAllowedTransactionStyleSource =+ context.addedLocalStyleSourceIds.has(styleSourceId);+ if (+ isAllowedExistingStyleSource === false &&+ isAllowedTransactionStyleSource === false+ ) {+ return {+ success: false,+ error:+ "Only token or transaction-local style sources are editable in content mode.",+ };+ }+ if (isAllowedTransactionStyleSource) {+ context.selectedLocalStyleSourceIds.add(styleSourceId);+ }+ }++ capabilities.styleSourceSelections.set(instanceId, selection.data);+ return { success: true };+};++const addRemovedInstanceLocalStyleSources = (+ context: ContentModeTransactionContext,+ instanceId: Instance["id"]+) => {+ const selection = context.capabilities.styleSourceSelections.get(instanceId);+ if (selection === undefined) {+ return;+ }+ for (const styleSourceId of selection.values) {+ const styleSource = context.capabilities.styleSources.get(styleSourceId);+ if (styleSource?.type === "local") {+ context.removedLocalStyleSourceIds.add(styleSourceId);+ }+ }+};++const validateRemovedInstanceReferences = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ for (const instance of context.capabilities.instances.values()) {+ for (const child of instance.children) {+ if (+ child.type === "id" &&+ context.removedEditableInstanceIds.has(child.value)+ ) {+ return {+ success: false,+ error: "Removed content instances must not be referenced.",+ };+ }+ }+ }+ return { success: true };+};++const validateEditableInstanceReachability = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ const rootIdsByInstanceId = getContentModeEditableInstanceRootIds({+ contentRootIds: context.capabilities.contentRootIds,+ instances: context.capabilities.instances,+ });+ for (const instanceId of context.initialEditableInstanceIds) {+ if (context.initialContentRootIds.has(instanceId)) {+ continue;+ }+ if (context.removedEditableInstanceIds.has(instanceId)) {+ continue;+ }+ if (context.capabilities.instances.has(instanceId) === false) {+ continue;+ }+ const rootId = rootIdsByInstanceId.get(instanceId);+ if (rootId === undefined) {+ return {+ success: false,+ error: "Content instances must remain reachable from content roots.",+ };+ }+ if (rootId !== context.initialEditableInstanceRootIds.get(instanceId)) {+ return {+ success: false,+ error: "Content instances must stay within their content root.",+ };+ }+ }+ return { success: true };+};++const validateEditableInstanceReferences = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ const referenceCounts = new Map<Instance["id"], number>();+ const visited = new Set<Instance["id"]>();+ const visit = (instanceId: Instance["id"]) => {+ if (visited.has(instanceId)) {+ return;+ }+ const instance = context.capabilities.instances.get(instanceId);+ if (+ instance === undefined ||+ instance.component === blockTemplateComponent+ ) {+ return;+ }+ visited.add(instanceId);+ for (const child of instance.children) {+ if (child.type !== "id") {+ continue;+ }+ referenceCounts.set(+ child.value,+ (referenceCounts.get(child.value) ?? 0) + 1+ );+ visit(child.value);+ }+ };++ for (const rootId of context.capabilities.contentRootIds) {+ visit(rootId);+ }++ for (const [instanceId, referenceCount] of referenceCounts) {+ if (+ referenceCount > 1 &&+ (context.initialEditableInstanceIds.has(instanceId) ||+ context.addedInstanceIds.has(instanceId))+ ) {+ return {+ success: false,+ error: "Content instances must not be referenced multiple times.",+ };+ }+ }++ return { success: true };+};++export const __testing__ = {+ isContentModePageMetaValue,+ hasOnlyContentModePageMeta,+ hasOnlyAddedInstancesInSubtree,+ isContentModePropPatchValue,+ validateEditableInstanceReferences,+};++const validateStyleSourcePatch = (+ context: ContentModeTransactionContext,+ patch: Patch+): ContentModeValidationResult => {+ const [styleSourceId] = patch.path;+ if (+ typeof styleSourceId === "string" &&+ patch.path.length === 1 &&+ patch.op === "remove"+ ) {+ const styleSource = context.capabilities.styleSources.get(styleSourceId);+ if (+ styleSource?.type === "local" &&+ context.removedLocalStyleSourceIds.has(styleSourceId)+ ) {+ context.capabilities.styleSources.delete(styleSourceId);+ return { success: true };+ }+ }++ if (+ typeof styleSourceId !== "string" ||+ patch.path.length !== 1 ||+ patch.op !== "add"+ ) {+ return {+ success: false,+ error: "Style source patch is not editable in content mode.",+ };+ }++ if (context.capabilities.styleSources.has(styleSourceId)) {+ return {+ success: false,+ error: "Style source patch is not editable in content mode.",+ };+ }++ const styleSource = StyleSourceSchema.safeParse(patch.value);+ if (+ styleSource.success === false ||+ styleSource.data.type !== "local" ||+ styleSource.data.id !== styleSourceId+ ) {+ return {+ success: false,+ error: "Only new local style sources are editable in content mode.",+ };+ }++ context.addedLocalStyleSourceIds.add(styleSourceId);+ context.capabilities.styleSources.set(styleSourceId, styleSource.data);+ return { success: true };+};++const validateSelectedLocalStyleSources = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ for (const styleSourceId of context.addedLocalStyleSourceIds) {+ if (context.selectedLocalStyleSourceIds.has(styleSourceId) === false) {+ return {+ success: false,+ error:+ "New local style sources must be selected by new content instances.",+ };+ }+ }+ return { success: true };+};++const validateStyledLocalStyleSources = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ for (const styleSourceId of context.addedLocalStyleSourceIds) {+ if (context.styledLocalStyleSourceIds.has(styleSourceId) === false) {+ return {+ success: false,+ error: "New local style sources must have styles in content mode.",+ };+ }+ }+ return { success: true };+};++const validateRemovedInstanceProps = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ for (const prop of context.capabilities.props.values()) {+ if (context.removedEditableInstanceIds.has(prop.instanceId)) {+ return {+ success: false,+ error: "Removed content instances must not keep props.",+ };+ }+ }+ return { success: true };+};++const validateRemovedInstanceStyleSourceSelections = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ for (const instanceId of context.removedEditableInstanceIds) {+ if (context.capabilities.styleSourceSelections.has(instanceId)) {+ return {+ success: false,+ error: "Removed content instances must not keep style selections.",+ };+ }+ }+ return { success: true };+};++const validateRemovedLocalStyleSources = (+ context: ContentModeTransactionContext+): ContentModeValidationResult => {+ for (const styleSourceId of context.removedLocalStyleSourceIds) {+ if (context.capabilities.styleSources.has(styleSourceId)) {+ return {+ success: false,+ error: "Removed content instances must not keep local style sources.",+ };+ }+ }+ for (const styleDecl of context.capabilities.styles.values()) {+ if (context.removedLocalStyleSourceIds.has(styleDecl.styleSourceId)) {+ return {+ success: false,+ error: "Removed content instances must not keep local styles.",+ };+ }+ }+ return { success: true };+};++const validateStylePatch = (+ context: ContentModeTransactionContext,+ patch: Patch+): ContentModeValidationResult => {+ const [styleDeclKey] = patch.path;+ if (+ typeof styleDeclKey === "string" &&+ patch.path.length === 1 &&+ patch.op === "remove"+ ) {+ const styleDecl = context.capabilities.styles.get(styleDeclKey);+ if (+ styleDecl &&+ context.removedLocalStyleSourceIds.has(styleDecl.styleSourceId)+ ) {+ context.capabilities.styles.delete(styleDeclKey);+ return { success: true };+ }+ }++ if (+ typeof styleDeclKey !== "string" ||+ patch.path.length !== 1 ||+ (patch.op !== "add" && patch.op !== "replace")+ ) {+ return {+ success: false,+ error: "Style patch is not editable in content mode.",+ };+ }++ const styleDecl = StyleDeclSchema.safeParse(patch.value);+ if (+ styleDecl.success === false ||+ getStyleDeclKey(styleDecl.data as StyleDecl) !== styleDeclKey ||+ context.selectedLocalStyleSourceIds.has(styleDecl.data.styleSourceId) ===+ false+ ) {+ return {+ success: false,+ error:+ "Only styles for new local style sources are editable in content mode.",+ };+ }+ if (+ context.capabilities.breakpoints !== undefined &&+ context.capabilities.breakpoints.has(styleDecl.data.breakpointId) === false+ ) {+ return {+ success: false,+ error:+ "Only styles for existing breakpoints are editable in content mode.",+ };+ }++ context.styledLocalStyleSourceIds.add(styleDecl.data.styleSourceId);+ context.capabilities.styles.set(styleDeclKey, styleDecl.data);+ return { success: true };+};++const validatePatchChange = (+ context: ContentModeTransactionContext,+ change: BuildPatchTransaction["payload"][number]+): ContentModeValidationResult => {+ if (change.namespace === "instances") {+ for (const patch of change.patches) {+ const result = validateInstancePatch(context, patch);+ if (result.success === false) {+ return result;+ }+ }+ return { success: true };+ }++ if (change.namespace === "props") {+ for (const patch of change.patches) {+ const result = validatePropPatch(context, patch);+ if (result.success === false) {+ return result;+ }+ }+ return { success: true };+ }++ if (change.namespace === "styleSourceSelections") {+ for (const patch of change.patches) {+ const result = validateStyleSourceSelectionPatch(context, patch);+ if (result.success === false) {+ return result;+ }+ }+ return { success: true };+ }++ if (change.namespace === "styleSources") {+ for (const patch of change.patches) {+ const result = validateStyleSourcePatch(context, patch);+ if (result.success === false) {+ return result;+ }+ }+ return { success: true };+ }++ if (change.namespace === "styles") {+ for (const patch of change.patches) {+ const result = validateStylePatch(context, patch);+ if (result.success === false) {+ return result;+ }+ }+ return { success: true };+ }++ if (change.namespace === "assets") {+ return { success: true };+ }++ if (change.namespace === "pages") {+ return validatePagePatches(context, change.patches);+ }++ return {+ success: false,+ error: `Namespace "${change.namespace}" is not editable in content mode.`,+ };+};++const applyValidatedInstancePatch = (+ capabilities: ContentModeCapabilities,+ patch: Patch+) => {+ const [instanceId, field, index] = patch.path;+ if (patch.op === "remove") {+ if (patch.path.length === 1) {+ capabilities.instances.delete(instanceId as Instance["id"]);+ capabilities.contentRootIds.delete(instanceId as Instance["id"]);+ return;+ }+ if (+ field === "children" &&+ typeof index === "number" &&+ patch.path.length === 3+ ) {+ const instance = capabilities.instances.get(instanceId as Instance["id"]);+ if (instance) {+ instance.children.splice(index, 1);+ }+ }+ return;+ }+ if (patch.op === "add") {+ if (patch.path.length === 1) {+ capabilities.instances.set(+ instanceId as Instance["id"],+ patch.value as Instance+ );+ return;+ }+ if (+ field === "children" &&+ typeof index === "number" &&+ patch.path.length === 3+ ) {+ const instance = capabilities.instances.get(instanceId as Instance["id"]);+ if (instance) {+ instance.children.splice(index, 0, patch.value);+ }+ }+ return;+ }+ if (+ patch.op === "replace" &&+ patch.path.length === 1 &&+ typeof instanceId === "string"+ ) {+ capabilities.instances.set(instanceId, patch.value as Instance);+ return;+ }+ if (+ patch.op === "replace" &&+ field === "children" &&+ typeof index === "number" &&+ patch.path.length === 3+ ) {+ const instance = capabilities.instances.get(instanceId as Instance["id"]);+ if (instance) {+ instance.children[index] = patch.value;+ }+ return;+ }+ if (+ patch.op === "replace" &&+ field === "children" &&+ patch.path.length === 2+ ) {+ const instance = capabilities.instances.get(instanceId as Instance["id"]);+ if (instance) {+ instance.children = patch.value;+ }+ }+};++export const applyContentModeTransaction = ({+ capabilities,+ transaction,+}: {+ capabilities: ContentModeCapabilities;+ transaction: BuildPatchTransaction;+}): AppliedContentModeTransactionResult => {+ const transactionCapabilities: ContentModeCapabilities = {+ ...capabilities,+ editablePropIds: new Set(capabilities.editablePropIds),+ editableInstanceIds: new Set(capabilities.editableInstanceIds),+ instances: new Map(+ Array.from(capabilities.instances, ([id, instance]) => [+ id,+ structuredClone(instance),+ ])+ ),+ props: new Map(capabilities.props),+ htmlTagsByInstanceId: new Map(capabilities.htmlTagsByInstanceId),+ styleSources: new Map(capabilities.styleSources),+ styleSourceSelections: new Map(capabilities.styleSourceSelections),+ styles: new Map(capabilities.styles),+ breakpoints:+ capabilities.breakpoints === undefined+ ? undefined+ : new Map(capabilities.breakpoints),+ contentRootIds: new Set(capabilities.contentRootIds),+ };+ const initialEditableInstanceRootIds = getContentModeEditableInstanceRootIds({+ contentRootIds: transactionCapabilities.contentRootIds,+ instances: transactionCapabilities.instances,+ });+ const initialEditableInstanceIds = new Set(+ initialEditableInstanceRootIds.keys()+ );+ const context: ContentModeTransactionContext = {+ capabilities: transactionCapabilities,+ initialContentRootIds: new Set(transactionCapabilities.contentRootIds),+ initialEditableInstanceIds,+ initialEditableInstanceRootIds,+ initialBlockTemplateChildIdsByInstanceId:+ getBlockTemplateChildIdsByInstanceId(transactionCapabilities.instances),+ addedInstanceIds: new Set(),+ removedEditableInstanceIds: new Set(),+ addedPageIds: new Set(),+ addedLocalStyleSourceIds: new Set(),+ removedLocalStyleSourceIds: new Set(),+ selectedLocalStyleSourceIds: new Set(),+ styledLocalStyleSourceIds: new Set(),+ editableInstanceIds: new Set(),+ };++ for (const change of transaction.payload) {+ if (change.namespace !== "instances") {+ continue;+ }+ for (const patch of change.patches) {+ const result = validateInstancePatchShape(transactionCapabilities, patch);+ if (result.success === false) {+ return result;+ }+ if (+ patch.op === "add" &&+ patch.path.length === 1 &&+ typeof patch.path[0] === "string"+ ) {+ context.addedInstanceIds.add(patch.path[0]);+ }+ if (+ patch.op === "remove" &&+ patch.path.length === 1 &&+ typeof patch.path[0] === "string" &&+ initialEditableInstanceIds.has(patch.path[0])+ ) {+ context.removedEditableInstanceIds.add(patch.path[0]);+ addRemovedInstanceLocalStyleSources(context, patch.path[0]);+ }+ applyValidatedInstancePatch(transactionCapabilities, patch);+ }+ }++ for (const change of transaction.payload) {+ if (change.namespace !== "pages") {+ continue;+ }+ const result = validatePatchChange(context, change);+ if (result.success === false) {+ return result;+ }+ }++ context.editableInstanceIds = getContentModeEditableInstanceIds({+ contentRootIds: transactionCapabilities.contentRootIds,+ instances: transactionCapabilities.instances,+ });+ transactionCapabilities.editableInstanceIds = context.editableInstanceIds;++ for (const change of transaction.payload) {+ if (change.namespace !== "styleSources") {+ continue;+ }+ const result = validatePatchChange(context, change);+ if (result.success === false) {+ return result;+ }+ }++ for (const change of transaction.payload) {+ if (change.namespace !== "instances") {+ continue;+ }+ const result = validatePatchChange(context, change);+ if (result.success === false) {+ return result;+ }+ }++ const removedInstanceReferencesResult =+ validateRemovedInstanceReferences(context);+ if (removedInstanceReferencesResult.success === false) {+ return removedInstanceReferencesResult;+ }+ const editableInstanceReachabilityResult =+ validateEditableInstanceReachability(context);+ if (editableInstanceReachabilityResult.success === false) {+ return editableInstanceReachabilityResult;+ }+ const editableInstanceReferencesResult =+ validateEditableInstanceReferences(context);+ if (editableInstanceReferencesResult.success === false) {+ return editableInstanceReferencesResult;+ }++ for (const change of transaction.payload) {+ if (change.namespace !== "styleSourceSelections") {+ continue;+ }+ const result = validatePatchChange(context, change);+ if (result.success === false) {+ return result;+ }+ }++ const selectedLocalStyleSourceResult =+ validateSelectedLocalStyleSources(context);+ if (selectedLocalStyleSourceResult.success === false) {+ return selectedLocalStyleSourceResult;+ }++ for (const change of transaction.payload) {+ if (+ change.namespace === "instances" ||+ change.namespace === "pages" ||+ change.namespace === "styleSources" ||+ change.namespace === "styleSourceSelections"+ ) {+ continue;+ }+ const result = validatePatchChange(context, change);+ if (result.success === false) {+ return result;+ }+ }++ const removedInstancePropsResult = validateRemovedInstanceProps(context);+ if (removedInstancePropsResult.success === false) {+ return removedInstancePropsResult;+ }+ const removedInstanceStyleSourceSelectionsResult =+ validateRemovedInstanceStyleSourceSelections(context);+ if (removedInstanceStyleSourceSelectionsResult.success === false) {+ return removedInstanceStyleSourceSelectionsResult;+ }+ const removedLocalStyleSourcesResult =+ validateRemovedLocalStyleSources(context);+ if (removedLocalStyleSourcesResult.success === false) {+ return removedLocalStyleSourcesResult;+ }++ const styledLocalStyleSourceResult = validateStyledLocalStyleSources(context);+ if (styledLocalStyleSourceResult.success === false) {+ return styledLocalStyleSourceResult;+ }++ return { success: true, capabilities: transactionCapabilities };+};++export const validateContentModeTransaction = ({+ capabilities,+ transaction,+}: {+ capabilities: ContentModeCapabilities;+ transaction: BuildPatchTransaction;+}): ContentModeValidationResult => {+ const result = applyContentModeTransaction({ capabilities, transaction });+ return result.success ? { success: true } : result;+};diff --git a/packages/project/src/db/build-patch-permissions.test.ts b/packages/project/src/db/build-patch-permissions.test.tsindex dd5f5fcc74..74195c2e4f 100644--- a/packages/project/src/db/build-patch-permissions.test.ts+++ b/packages/project/src/db/build-patch-permissions.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from "vitest";import { getRequiredPermitForBuildPatchTransaction } from "./build-patch-permissions";import type { BuildPatchTransaction } from "./build-patch-core";+import type { ContentModeCapabilities } from "../content-mode-permissions";const transaction = (namespace: string,@@ -12,122 +13,42 @@ const transaction = (payload: [{ namespace, patches }],});-describe("getRequiredPermitForBuildPatchTransaction", () => {- test("allows content prop edits with edit permit", () => {- expect(- getRequiredPermitForBuildPatchTransaction(transaction("props"))- ).toBe("edit");- });-- test("allows content block instance edits with edit permit", () => {- expect(- getRequiredPermitForBuildPatchTransaction(- transaction("instances", [- {- op: "replace",- path: ["instance-1", "children"],- value: [{ type: "text", value: "Title" }],- },- ])- )- ).toBe("edit");- });-- test("requires build permit for style edits", () => {- expect(- getRequiredPermitForBuildPatchTransaction(transaction("styles"))- ).toBe("build");- });-- test("allows editor page settings changes with edit permit", () => {- expect(- getRequiredPermitForBuildPatchTransaction(- transaction("pages", [- { op: "replace", path: ["pages", "page-1", "name"], value: "About" },- {- op: "replace",- path: ["pages", "page-1", "meta", "description"],- value: "About us",- },- ])- )- ).toBe("edit");- });+const capabilities: ContentModeCapabilities = {+ editablePropIds: new Set(["prop-1"]),+ editableInstanceIds: new Set(["instance-1"]),+ instances: new Map(),+ metas: new Map(),+ props: new Map([+ [+ "prop-1",+ {+ id: "prop-1",+ instanceId: "instance-1",+ name: "title",+ type: "string",+ value: "Old title",+ },+ ],+ ]),+ htmlTagsByInstanceId: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ styles: new Map(),+ contentRootIds: new Set(),+};++const permit = (buildPatchTransaction: BuildPatchTransaction) =>+ getRequiredPermitForBuildPatchTransaction(+ buildPatchTransaction,+ capabilities+ );- test("requires build permit for whole meta replacements", () => {- expect(- getRequiredPermitForBuildPatchTransaction(- transaction("pages", [- {- op: "replace",- path: ["pages", "page-1", "meta"],- value: {- description: "About us",- },- },- ])- )- ).toBe("build");- });-- test("requires build permit for creating pages", () => {- expect(- getRequiredPermitForBuildPatchTransaction(- transaction("pages", [- {- op: "add",- path: ["pages", "page-1"],- value: {- id: "page-1",- name: "Landing",- path: "/landing",- title: "Landing",- meta: {},- rootInstanceId: "root-1",- },- },- ])- )- ).toBe("build");- });-- test("requires build permit for design edits not tied to page creation", () => {- expect(- getRequiredPermitForBuildPatchTransaction(- transaction("styles", [- {- op: "add",- path: ["style-1"],- value: {- styleSourceId: "style-source-1",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- },- ])- )- ).toBe("build");- });-- test("requires build permit when any change in the transaction is design scoped", () => {- expect(- getRequiredPermitForBuildPatchTransaction({- id: "tx-1",- payload: [- { namespace: "props", patches: [] },- {- namespace: "breakpoints",- patches: [{ op: "add", path: ["bp-1"], value: {} }],- },- ],- })- ).toBe("build");+describe("getRequiredPermitForBuildPatchTransaction", () => {+ test("returns edit permit for content mode transactions", () => {+ expect(permit(transaction("props"))).toBe("edit");});- test("requires build permit for unknown namespaces", () => {- expect(- getRequiredPermitForBuildPatchTransaction(transaction("unknown"))- ).toBe("build");+ test("returns build permit for transactions outside content mode", () => {+ expect(permit(transaction("styles"))).toBe("build");});});diff --git a/packages/project/src/db/build-patch-permissions.ts b/packages/project/src/db/build-patch-permissions.tsindex 75716381c5..dd5a72a8d3 100644--- a/packages/project/src/db/build-patch-permissions.ts+++ b/packages/project/src/db/build-patch-permissions.ts@@ -1,30 +1,15 @@import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";import type { BuildPatchTransaction } from "./build-patch-core";--type BuildPatchChange = BuildPatchTransaction["payload"][number];--const isEditorSafeChange = (change: BuildPatchChange) => {- if (change.namespace === "instances" || change.namespace === "props") {- return true;- }-- return (- change.namespace === "pages" &&- change.patches.every((patch) => {- const [collection, pageId, field] = patch.path;- return (- collection === "pages" &&- typeof pageId === "string" &&- ((patch.path.length === 3 &&- (field === "name" || field === "path" || field === "title")) ||- (patch.path.length === 4 && field === "meta"))- );- })- );-};+import {+ validateContentModeTransaction,+ type ContentModeCapabilities,+} from "../content-mode-permissions";export const getRequiredPermitForBuildPatchTransaction = (- transaction: BuildPatchTransaction+ transaction: BuildPatchTransaction,+ capabilities: ContentModeCapabilities): AuthPermit => {- return transaction.payload.every(isEditorSafeChange) ? "edit" : "build";+ return validateContentModeTransaction({ capabilities, transaction }).success+ ? "edit"+ : "build";};diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.tsindex f6e26f2f8f..bc2906e051 100644--- a/packages/project/src/db/build-patch.test.ts+++ b/packages/project/src/db/build-patch.test.ts@@ -8,7 +8,11 @@ import {} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import type { Patch } from "immer";-import { patchBuild, type BuildPatchTransaction } from "./build-patch";+import {+ patchBuild,+ patchLoadedBuild,+ type BuildPatchTransaction,+} from "./build-patch";import {createBuildPatchUpdate,singlePlayerVersionMismatchResult,@@ -91,6 +95,44 @@ const transaction = (});describe("patchBuild", () => {+ test("patches an already loaded build and returns the updated build row", async () => {+ let didLoadBuild = false;+ server.use(+ db.get("Build", () => {+ didLoadBuild = true;+ return json([buildRow]);+ }),+ db.patch("Build", () => empty({ headers: { "Content-Range": "*/1" } }))+ );++ const result = await patchLoadedBuild(+ {+ build: buildRow,+ buildId: "build-1",+ projectId: "project-1",+ clientVersion: 3,+ transactions: [transaction()],+ },+ createContext()+ );++ expect(result.status).toBe("ok");+ if (result.status === "ok") {+ expect(result.version).toBe(4);+ expect(result.build.version).toBe(4);+ expect(JSON.parse(result.build.props)).toEqual([+ {+ id: "prop-1",+ instanceId: "body-1",+ name: "title",+ type: "string",+ value: "New title",+ },+ ]);+ }+ expect(didLoadBuild).toBe(false);+ });+test("applies transactions, validates data, and updates build with optimistic version guard", async () => {let updatedBuild: unknown;server.use(diff --git a/packages/project/src/db/build-patch.ts b/packages/project/src/db/build-patch.tsindex c2d1e4e331..f95fad4027 100644--- a/packages/project/src/db/build-patch.ts+++ b/packages/project/src/db/build-patch.ts@@ -1,6 +1,7 @@import { patchAssets } from "@webstudio-is/asset-uploader/index.server";import type { Build } from "@webstudio-is/project-build";import { loadRawBuildById } from "@webstudio-is/project-build/index.server";+import type { Database } from "@webstudio-is/postgrest/index.server";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import type { Project } from "./project";import { updatePreviewImage } from "./project";@@ -18,21 +19,31 @@ export type PatchBuildResult =| { status: "version_mismatched"; errors: string }| { status: "error"; errors: string };-export const patchBuild = async (+type PatchLoadedBuildResult =+ | {+ status: "ok";+ version: number;+ build: Database["public"]["Tables"]["Build"]["Row"];+ }+ | { status: "version_mismatched"; errors: string }+ | { status: "error"; errors: string };++export const patchLoadedBuild = async ({+ build,buildId,projectId,transactions,clientVersion,}: {+ build: Database["public"]["Tables"]["Build"]["Row"];buildId: Build["id"];projectId: Project["id"];transactions: BuildPatchTransaction[];clientVersion: number;},context: AppContext-): Promise<PatchBuildResult> => {- const build = await loadRawBuildById(context, buildId);+): Promise<PatchLoadedBuildResult> => {const result = await createBuildPatchUpdate({build,clientVersion,@@ -44,7 +55,7 @@ export const patchBuild = async (}if (result.update === undefined) {- return { status: "ok", version: result.nextVersion };+ return { status: "ok", version: result.nextVersion, build };}// build.patch does not have the worker's atomic Build+asset commit path.@@ -84,5 +95,36 @@ export const patchBuild = async ();}- return { status: "ok", version: result.nextVersion };+ return {+ status: "ok",+ version: result.nextVersion,+ build: { ...build, ...result.update, version: result.nextVersion },+ };+};++export const patchBuild = async (+ {+ buildId,+ projectId,+ transactions,+ clientVersion,+ }: {+ buildId: Build["id"];+ projectId: Project["id"];+ transactions: BuildPatchTransaction[];+ clientVersion: number;+ },+ context: AppContext+): Promise<PatchBuildResult> => {+ const build = await loadRawBuildById(context, buildId);+ const result = await patchLoadedBuild(+ { build, buildId, projectId, transactions, clientVersion },+ context+ );++ if (result.status !== "ok") {+ return result;+ }++ return { status: "ok", version: result.version };};diff --git a/packages/sdk/src/css.ts b/packages/sdk/src/css.tsindex d15ddd3ad6..2b29e447df 100644--- a/packages/sdk/src/css.ts+++ b/packages/sdk/src/css.ts@@ -15,7 +15,12 @@ import type { Styles } from "./schema/styles";import type { StyleSourceSelections } from "./schema/style-source-selections";import type { WsComponentMeta } from "./schema/component-meta";import { createScope } from "./scope";-import { parseComponentName, ROOT_INSTANCE_ID } from "./instances-utils";+import {+ getHtmlTagsFromProps,+ getHtmlTagFromInstance,+ parseComponentName,+ ROOT_INSTANCE_ID,+} from "./instances-utils";import { descendantComponent, rootComponent } from "./core-metas";export const addFontRules = ({@@ -101,22 +106,19 @@ export const generateCss = ({const tagsByComponent = new Map<Instance["component"], Set<string>>();tagsByComponent.set(rootComponent, new Set(["html"]));- const tagByInstanceId = new Map<Instance["id"], string>();- for (const prop of props.values()) {- if (prop.type === "string" && prop.name === "tag") {- tagByInstanceId.set(prop.instanceId, prop.value);- }- }+ const htmlTagsByInstanceId = getHtmlTagsFromProps(props);for (const instance of instances.values()) {- const propTag = tagByInstanceId.get(instance.id);- const meta = componentMetas.get(instance.component);- const metaTag = Object.keys(meta?.presetStyle ?? {}).at(0);let componentTags = tagsByComponent.get(instance.component);if (componentTags === undefined) {componentTags = new Set();tagsByComponent.set(instance.component, componentTags);}- const tag = instance.tag ?? propTag ?? metaTag;+ const tag = getHtmlTagFromInstance({+ instance,+ metas: componentMetas,+ props,+ htmlTagsByInstanceId,+ });if (tag) {componentTags.add(tag);}diff --git a/packages/sdk/src/instances-utils.test.tsx b/packages/sdk/src/instances-utils.test.tsxindex 30e5ffaaff..49dfd48fb0 100644--- a/packages/sdk/src/instances-utils.test.tsx+++ b/packages/sdk/src/instances-utils.test.tsx@@ -3,6 +3,8 @@ import { $, renderData, ws } from "@webstudio-is/template";import {findTreeInstanceIds,findTreeInstanceIdsExcludingSlotDescendants,+ getHtmlTagsFromProps,+ getHtmlTagFromInstance,getIndexesWithinAncestors,parseComponentName,} from "./instances-utils";@@ -53,6 +55,107 @@ test("extract short name and namespace from component name", () => {expect(parseComponentName("radix:Box")).toEqual(["radix", "Box"]);});+test("get html tag from instance", () => {+ const metas = new Map<Instance["component"], WsComponentMeta>([+ ["Box", { presetStyle: { section: [] } }],+ ["XmlNode", { presetStyle: { div: [] } }],+ ]);+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="meta"></$.Box>+ <$.Box ws:id="prop" ws:tag="article"></$.Box>+ <$.Box ws:id="instance" ws:tag="nav"></$.Box>+ <$.XmlNode ws:id="xml" tag="svg"></$.XmlNode>+ </$.Body>+ );++ expect(+ getHtmlTagFromInstance({+ instance: instances.get("meta") as Instance,+ metas,+ props,+ })+ ).toEqual("section");+ expect(+ getHtmlTagFromInstance({+ instance: instances.get("prop") as Instance,+ metas,+ props,+ htmlTagsByInstanceId: getHtmlTagsFromProps(props),+ })+ ).toEqual("article");+ expect(+ getHtmlTagFromInstance({+ instance: {+ ...(instances.get("instance") as Instance),+ tag: "nav",+ },+ metas,+ props,+ })+ ).toEqual("nav");+ expect(+ getHtmlTagFromInstance({+ instance: instances.get("xml") as Instance,+ metas,+ props,+ })+ ).toBeUndefined();+});++test("gets html tags from props", () => {+ const { props } = renderData(+ <$.Body ws:id="body">+ <$.XmlNode ws:id="xml" tag="svg"></$.XmlNode>+ </$.Body>+ );+ props.set("tag-prop", {+ id: "tag-prop",+ instanceId: "box",+ name: "tag",+ type: "string",+ value: "article",+ });++ expect(getHtmlTagsFromProps(props)).toEqual(+ new Map([+ ["box", "article"],+ ["xml", "svg"],+ ])+ );+});++test("get html tag from instance reads mutable props maps", () => {+ const metas = new Map<Instance["component"], WsComponentMeta>([+ ["Box", { presetStyle: { section: [] } }],+ ]);+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ const instance = instances.get("box") as Instance;+ props.set("tag-prop", {+ id: "tag-prop",+ instanceId: "box",+ name: "tag",+ type: "string",+ value: "article",+ });++ expect(getHtmlTagFromInstance({ instance, metas, props })).toEqual("article");++ props.set("tag-prop", {+ id: "tag-prop",+ instanceId: "box",+ name: "tag",+ type: "string",+ value: "aside",+ });++ expect(getHtmlTagFromInstance({ instance, metas, props })).toEqual("aside");+});+test("get indexes within ancestors", () => {const { instances } = renderData(<$.Body ws:id="body0">diff --git a/packages/sdk/src/instances-utils.ts b/packages/sdk/src/instances-utils.tsindex 4c9969d96c..f4a73b5150 100644--- a/packages/sdk/src/instances-utils.ts+++ b/packages/sdk/src/instances-utils.ts@@ -1,5 +1,6 @@import type { WsComponentMeta } from "./schema/component-meta";import type { Instance, Instances } from "./schema/instances";+import type { Props } from "./schema/props";import { blockTemplateComponent } from "./core-metas";export const ROOT_INSTANCE_ID = ":root";@@ -61,6 +62,39 @@ export const parseComponentName = (componentName: string) => {return [namespace, name] as const;};+export const getHtmlTagsFromProps = (props: Props) => {+ const tags = new Map<Instance["id"], string>();+ for (const prop of props.values()) {+ if (prop.type === "string" && prop.name === "tag") {+ tags.set(prop.instanceId, prop.value);+ }+ }+ return tags;+};++export const getHtmlTagFromInstance = ({+ instance,+ metas,+ props,+ htmlTagsByInstanceId,+}: {+ instance: Instance;+ metas: Map<Instance["component"], WsComponentMeta>;+ props: Props;+ htmlTagsByInstanceId?: Map<Instance["id"], string>;+}) => {+ // XmlNode's "tag" prop is an XML element name, not an HTML rendering tag.+ if (instance.component === "XmlNode") {+ return;+ }+ const meta = metas.get(instance.component);+ const metaTag = Object.keys(meta?.presetStyle ?? {}).at(0);+ const propTag =+ htmlTagsByInstanceId?.get(instance.id) ??+ getHtmlTagsFromProps(props).get(instance.id);+ return instance.tag ?? propTag ?? metaTag;+};+export type IndexesWithinAncestors = Map<Instance["id"], number>;export const getIndexesWithinAncestors = (diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9851b8a396..cd12a4cf60 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -190,6 +190,9 @@ importers:'@react-aria/utils':specifier: ^3.27.0+ '@remix-run/express':+ specifier: ^2.16.5+ version: 2.16.5([email protected])([email protected])'@remix-run/node':specifier: ^2.16.5version: 2.16.5([email protected])@@ -325,6 +328,9 @@ importers:entrijs:specifier: ^0.0.11version: 0.0.11+ express:+ specifier: ^4.21.1+ version: 4.21.1fast-deep-equal:specifier: ^3.1.3version: 3.1.3@@ -437,6 +443,9 @@ importers:'@types/dom-navigation':specifier: ^1.0.5version: 1.0.5+ '@types/express':+ specifier: ^4.17.21+ version: 4.17.21'@types/papaparse':specifier: ^5.5.2version: 5.5.2@@ -467,6 +476,9 @@ importers:msw:specifier: ^2.13.2version: 2.13.2(@types/[email protected])([email protected])+ playwright:+ specifier: ^1.50.1+ version: 1.50.1react-router-dom:specifier: ^6.30.0@@ -5657,6 +5669,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-fnQmj8lELIj7BSrZQAdBMHEHX8OZLYIHXqAKT1O7tDfLxaINzf00PMjw22r3N/xXh0w/sGHlO6SVaCQ2mj78lg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==}++ '@types/[email protected]':+ resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}+'@types/[email protected]':resolution: {integrity: sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==}@@ -5678,12 +5696,21 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-02S5fmqeoKzVZCHPZid4b8JH2eM5HzQLZWN2FohQEy/0eXTq8VXZfSN6Pcr3F6N9R/vNrj7cpgbhjie6m/1tCA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==}+'@types/[email protected]':resolution: {integrity: sha512-wN+8bYxIpJf+5oZdrdtaX04qUuWHcKxcDEgRS9Qm9ZClSHjzEn13SxUC+5eRM+4yXIeTYk8mTzLAWGF64847ew==}'@types/[email protected]':resolution: {integrity: sha512-wLEm0QvaoawEDoTRwzTXp4b4jpwiJDvR5KMnFnVodm3scufTlBOWRD6N1OBf9TZMhjlNsSfcO5V+7AF4+Vy+9g==}+ '@types/[email protected]':+ resolution: {integrity: sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==}+'@types/[email protected]':resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}@@ -5693,6 +5720,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-+OWZQfAYyio6YkJb3HLxDrvnx6SWWDbC0zVPfBRzUk0/nqoDyf6dNxQi3eArPe8rJ473nobTMQ/8Zk+LxJ+Yuw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==}+'@types/[email protected]':resolution: {integrity: sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==}@@ -5705,6 +5735,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==}+ '@types/[email protected]':+ resolution: {integrity: sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}+'@types/[email protected]':resolution: {integrity: sha512-o/V48vf4MQh7juIKZU2QGDfli6p1+OOi5oXx36Hffpc9adsHeXjVp8rHuPkjd8VT8sOJ2Zp05HR7CdpGTIUFUA==}@@ -5717,6 +5753,15 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow==}+ '@types/[email protected]':+ resolution: {integrity: sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==}++ '@types/[email protected]':+ resolution: {integrity: sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==}+'@types/[email protected]':resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==}@@ -9825,7 +9870,7 @@ snapshots:'@babel/traverse': 7.25.9'@babel/types': 7.27.0convert-source-map: 2.0.0- debug: 4.4.0+ debug: 4.4.3gensync: 1.0.0-beta.2json5: 2.2.3semver: 6.3.1@@ -10073,7 +10118,7 @@ snapshots:'@babel/parser': 7.27.0'@babel/template': 7.25.9'@babel/types': 7.27.0- debug: 4.4.0+ debug: 4.4.3globals: 11.12.0transitivePeerDependencies:- supports-color@@ -13008,6 +13053,15 @@ snapshots:dependencies:'@types/node': 22.13.10+ '@types/[email protected]':+ dependencies:+ '@types/connect': 3.4.38+ '@types/node': 22.13.10++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.13.10+'@types/[email protected]': {}'@types/[email protected]':@@ -13026,6 +13080,20 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/node': 22.13.10+ '@types/qs': 6.15.1+ '@types/range-parser': 1.2.7+ '@types/send': 1.2.1++ '@types/[email protected]':+ dependencies:+ '@types/body-parser': 1.19.6+ '@types/express-serve-static-core': 4.19.8+ '@types/qs': 6.15.1+ '@types/serve-static': 1.15.10+'@types/[email protected]':dependencies:'@types/node': 22.13.10@@ -13034,6 +13102,8 @@ snapshots:dependencies:'@types/unist': 3.0.0+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@ -13042,6 +13112,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@ -13054,6 +13126,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}++ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/react': 18.2.79@@ -13067,6 +13143,21 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/mime': 1.3.5+ '@types/node': 22.13.10++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.13.10++ '@types/[email protected]':+ dependencies:+ '@types/http-errors': 2.0.5+ '@types/node': 22.13.10+ '@types/send': 0.17.6+'@types/[email protected]': {}'@types/[email protected]': {}@@ -13591,7 +13682,6 @@ snapshots:dependencies:es-errors: 1.3.0function-bind: 1.1.2- optional: truedependencies:@@ -13981,7 +14071,6 @@ snapshots:call-bind-apply-helpers: 1.0.2es-errors: 1.3.0gopd: 1.2.0- optional: truedependencies:@@ -14024,10 +14113,9 @@ snapshots:dependencies:- get-intrinsic: 1.2.4+ get-intrinsic: 1.3.0- optional: true+ [email protected]: {}@@ -14036,7 +14124,6 @@ snapshots:dependencies:es-errors: 1.3.0- optional: truedependencies:@@ -14055,7 +14142,7 @@ snapshots:dependencies:- debug: 4.4.0+ debug: 4.4.3esbuild: 0.25.3transitivePeerDependencies:- supports-color@@ -14533,7 +14620,6 @@ snapshots:has-symbols: 1.1.0hasown: 2.0.3math-intrinsics: 1.1.0- optional: true@@ -14547,7 +14633,6 @@ snapshots:dependencies:dunder-proto: 1.0.1es-object-atoms: 1.1.1- optional: truedependencies:@@ -14612,8 +14697,7 @@ snapshots:dependencies:get-intrinsic: 1.2.1- optional: true+ [email protected]: {}@@ -14650,8 +14734,7 @@ snapshots:- optional: true+ [email protected]: {}dependencies:@@ -14672,7 +14755,6 @@ snapshots:dependencies:function-bind: 1.1.2- optional: truedependencies:@@ -15147,8 +15229,7 @@ snapshots:'@babel/runtime': 7.25.0remove-accents: 0.5.0- optional: true+ [email protected]: {}dependencies:@@ -16696,7 +16777,7 @@ snapshots:define-data-property: 1.1.4es-errors: 1.3.0function-bind: 1.1.2- get-intrinsic: 1.2.4+ get-intrinsic: 1.3.0gopd: 1.0.1has-property-descriptors: 1.0.2@@ -16740,7 +16821,7 @@ snapshots:dependencies:call-bind: 1.0.7es-errors: 1.3.0- get-intrinsic: 1.2.4+ get-intrinsic: 1.3.0object-inspect: 1.13.3@@ -17338,7 +17419,7 @@ snapshots:[email protected](@types/[email protected]):dependencies:cac: 6.7.14- debug: 4.4.0+ debug: 4.4.3pathe: 1.1.2picocolors: 1.1.1vite: 5.4.11(@types/[email protected])